Skip to content

Commit add4b98

Browse files
author
Kate Osborn
committed
Write deployment context in init container
1 parent 1744837 commit add4b98

File tree

33 files changed

+886
-275
lines changed

33 files changed

+886
-275
lines changed

charts/nginx-gateway-fabric/templates/configmap.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,6 @@ data:
2929
ssl_certificate_key /etc/nginx/certs-bootstrap/tls.key;
3030
{{- end }}
3131
enforce_initial_report off;
32+
deployment_context /etc/nginx/main-includes/deployment_ctx.json;
3233
}
3334
{{- end }}

charts/nginx-gateway-fabric/templates/deployment.yaml

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,20 +34,30 @@ spec:
3434
{{- toYaml .Values.topologySpreadConstraints | nindent 8 }}
3535
{{- end }}
3636
initContainers:
37-
- name: copy-nginx-config
37+
- name: init
3838
image: {{ .Values.nginxGateway.image.repository }}:{{ default .Chart.AppVersion .Values.nginxGateway.image.tag }}
3939
imagePullPolicy: {{ .Values.nginxGateway.image.pullPolicy }}
4040
command:
4141
- /usr/bin/gateway
42-
- copy
42+
- initialize
4343
- --source
4444
- /includes/main.conf
4545
{{- if .Values.nginx.plus }}
4646
- --source
4747
- /includes/mgmt.conf
48+
- --nginx-plus
4849
{{- end }}
4950
- --destination
5051
- /etc/nginx/main-includes
52+
env:
53+
- name: POD_NAMESPACE
54+
valueFrom:
55+
fieldRef:
56+
fieldPath: metadata.namespace
57+
- name: POD_NAME
58+
valueFrom:
59+
fieldRef:
60+
fieldPath: metadata.name
5161
securityContext:
5262
seccompProfile:
5363
type: RuntimeDefault

cmd/gateway/commands.go

Lines changed: 60 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@ package main
33
import (
44
"errors"
55
"fmt"
6-
"io"
76
"os"
8-
"path/filepath"
97
"runtime/debug"
108
"strconv"
119
"time"
@@ -22,8 +20,10 @@ import (
2220
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/provisioner"
2321
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/static"
2422
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/config"
23+
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/nginx/file"
2524
)
2625

26+
// These flags are shared by mutliple commands.
2727
const (
2828
domain = "gateway.nginx.org"
2929
gatewayClassFlag = "gatewayclass"
@@ -32,6 +32,7 @@ const (
3232
gatewayCtlrNameFlag = "gateway-ctlr-name"
3333
gatewayCtlrNameUsageFmt = `The name of the Gateway controller. ` +
3434
`The controller name must be of the form: DOMAIN/PATH. The controller's domain is '%s'`
35+
plusFlag = "nginx-plus"
3536
)
3637

3738
func createRootCommand() *cobra.Command {
@@ -47,7 +48,6 @@ func createRootCommand() *cobra.Command {
4748
return rootCmd
4849
}
4950

50-
//nolint:gocyclo
5151
func createStaticModeCommand() *cobra.Command {
5252
// flag names
5353
const (
@@ -63,7 +63,6 @@ func createStaticModeCommand() *cobra.Command {
6363
leaderElectionDisableFlag = "leader-election-disable"
6464
leaderElectionLockNameFlag = "leader-election-lock-name"
6565
productTelemetryDisableFlag = "product-telemetry-disable"
66-
plusFlag = "nginx-plus"
6766
gwAPIExperimentalFlag = "gateway-api-experimental-features"
6867
usageReportSecretFlag = "usage-report-secret"
6968
usageReportEndpointFlag = "usage-report-endpoint"
@@ -164,14 +163,9 @@ func createStaticModeCommand() *cobra.Command {
164163
return fmt.Errorf("error validating POD_IP environment variable: %w", err)
165164
}
166165

167-
namespace := os.Getenv("POD_NAMESPACE")
168-
if namespace == "" {
169-
return errors.New("POD_NAMESPACE environment variable must be set")
170-
}
171-
172-
podName := os.Getenv("POD_NAME")
173-
if podName == "" {
174-
return errors.New("POD_NAME environment variable must be set")
166+
podNsName, err := getPodNsName()
167+
if err != nil {
168+
return fmt.Errorf("could not get pod nsname: %w", err)
175169
}
176170

177171
imageSource := os.Getenv("BUILD_AGENT")
@@ -229,8 +223,8 @@ func createStaticModeCommand() *cobra.Command {
229223
GatewayPodConfig: config.GatewayPodConfig{
230224
PodIP: podIP,
231225
ServiceName: serviceName.value,
232-
Namespace: namespace,
233-
Name: podName,
226+
Namespace: podNsName.Namespace,
227+
Name: podNsName.Name,
234228
},
235229
HealthConfig: config.HealthConfig{
236230
Enabled: !disableHealth,
@@ -244,7 +238,7 @@ func createStaticModeCommand() *cobra.Command {
244238
LeaderElection: config.LeaderElectionConfig{
245239
Enabled: !disableLeaderElection,
246240
LockName: leaderElectionLockName.String(),
247-
Identity: podName,
241+
Identity: podNsName.Name,
248242
},
249243
UsageReportConfig: usageReportConfig,
250244
ProductTelemetryConfig: config.ProductTelemetryConfig{
@@ -524,29 +518,50 @@ func createSleepCommand() *cobra.Command {
524518
return cmd
525519
}
526520

527-
func createCopyCommand() *cobra.Command {
521+
func createInitializeCommand() *cobra.Command {
528522
// flag names
529523
const srcFlag = "source"
530524
const destFlag = "destination"
525+
531526
// flag values
532527
var srcFiles []string
533528
var dest string
529+
var plus bool
534530

535531
cmd := &cobra.Command{
536-
Use: "copy",
537-
Short: "Copy files to another directory",
532+
Use: "initialize",
533+
Short: "Write initial configuration files",
538534
RunE: func(_ *cobra.Command, _ []string) error {
539-
if err := validateSleepArgs(srcFiles, dest); err != nil {
535+
if err := validateCopyArgs(srcFiles, dest); err != nil {
540536
return err
541537
}
542538

543-
for _, src := range srcFiles {
544-
if err := copyFile(src, dest); err != nil {
545-
return err
546-
}
539+
podNsName, err := getPodNsName()
540+
if err != nil {
541+
return fmt.Errorf("could not get pod nsname: %w", err)
547542
}
548543

549-
return nil
544+
logger := ctlrZap.New()
545+
klog.SetLogger(logger)
546+
logger.Info(
547+
"Starting init container",
548+
"source filenames to copy", srcFiles,
549+
"destination directory", dest,
550+
"nginx-plus",
551+
plus,
552+
)
553+
log.SetLogger(logger)
554+
555+
return initialize(initializeConfig{
556+
controllerPodNSName: podNsName,
557+
fileManager: file.NewStdLibOSFileManager(),
558+
logger: logger,
559+
plus: plus,
560+
copy: copyFiles{
561+
srcFileNames: srcFiles,
562+
destDirName: dest,
563+
},
564+
})
550565
},
551566
}
552567

@@ -564,31 +579,18 @@ func createCopyCommand() *cobra.Command {
564579
"The destination directory for the source files to be copied to",
565580
)
566581

582+
cmd.Flags().BoolVar(
583+
&plus,
584+
plusFlag,
585+
false,
586+
"Use NGINX Plus",
587+
)
588+
567589
cmd.MarkFlagsRequiredTogether(srcFlag, destFlag)
568590

569591
return cmd
570592
}
571593

572-
func copyFile(src, dest string) error {
573-
srcFile, err := os.Open(src)
574-
if err != nil {
575-
return fmt.Errorf("error opening source file: %w", err)
576-
}
577-
defer srcFile.Close()
578-
579-
destFile, err := os.Create(filepath.Join(dest, filepath.Base(src)))
580-
if err != nil {
581-
return fmt.Errorf("error creating destination file: %w", err)
582-
}
583-
defer destFile.Close()
584-
585-
if _, err := io.Copy(destFile, srcFile); err != nil {
586-
return fmt.Errorf("error copying file contents: %w", err)
587-
}
588-
589-
return nil
590-
}
591-
592594
func parseFlags(flags *pflag.FlagSet) ([]string, []string) {
593595
var flagKeys, flagValues []string
594596

@@ -634,3 +636,17 @@ func getBuildInfo() (commitHash string, commitTime string, dirtyBuild string) {
634636

635637
return
636638
}
639+
640+
func getPodNsName() (types.NamespacedName, error) {
641+
namespace := os.Getenv("POD_NAMESPACE")
642+
if namespace == "" {
643+
return types.NamespacedName{}, errors.New("POD_NAMESPACE environment variable must be set")
644+
}
645+
646+
podName := os.Getenv("POD_NAME")
647+
if podName == "" {
648+
return types.NamespacedName{}, errors.New("POD_NAME environment variable must be set")
649+
}
650+
651+
return types.NamespacedName{Namespace: namespace, Name: podName}, nil
652+
}

cmd/gateway/commands_test.go

Lines changed: 3 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@ package main
22

33
import (
44
"io"
5-
"os"
6-
"path/filepath"
75
"testing"
86

97
. "github.com/onsi/gomega"
@@ -474,14 +472,15 @@ func TestSleepCmdFlagValidation(t *testing.T) {
474472
}
475473
}
476474

477-
func TestCopyCmdFlagValidation(t *testing.T) {
475+
func TestInitializeCmdFlagValidation(t *testing.T) {
478476
t.Parallel()
479477
tests := []flagTestCase{
480478
{
481479
name: "valid flags",
482480
args: []string{
483481
"--source=/my/file",
484482
"--destination=dest/file",
483+
"--nginx-plus",
485484
},
486485
wantErr: false,
487486
},
@@ -513,29 +512,12 @@ func TestCopyCmdFlagValidation(t *testing.T) {
513512
for _, test := range tests {
514513
t.Run(test.name, func(t *testing.T) {
515514
t.Parallel()
516-
cmd := createCopyCommand()
515+
cmd := createInitializeCommand()
517516
testFlag(t, cmd, test)
518517
})
519518
}
520519
}
521520

522-
func TestCopyFile(t *testing.T) {
523-
t.Parallel()
524-
g := NewWithT(t)
525-
526-
src, err := os.CreateTemp(os.TempDir(), "testfile")
527-
g.Expect(err).ToNot(HaveOccurred())
528-
defer os.Remove(src.Name())
529-
530-
dest, err := os.MkdirTemp(os.TempDir(), "testdir")
531-
g.Expect(err).ToNot(HaveOccurred())
532-
defer os.RemoveAll(dest)
533-
534-
g.Expect(copyFile(src.Name(), dest)).To(Succeed())
535-
_, err = os.Stat(filepath.Join(dest, filepath.Base(src.Name())))
536-
g.Expect(err).ToNot(HaveOccurred())
537-
}
538-
539521
func TestParseFlags(t *testing.T) {
540522
t.Parallel()
541523
g := NewWithT(t)

0 commit comments

Comments
 (0)