|
| 1 | +package framework |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "strings" |
| 9 | + "time" |
| 10 | + |
| 11 | + core "k8s.io/api/core/v1" |
| 12 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 13 | + "k8s.io/client-go/kubernetes" |
| 14 | + "k8s.io/client-go/kubernetes/scheme" |
| 15 | + "k8s.io/client-go/rest" |
| 16 | + "k8s.io/client-go/tools/remotecommand" |
| 17 | +) |
| 18 | + |
| 19 | +// ExpectedNginxField contains an nginx directive key and value, |
| 20 | +// and the expected file, server, and location block that it should exist in. |
| 21 | +type ExpectedNginxField struct { |
| 22 | + // Directive is the directive name. |
| 23 | + Directive string |
| 24 | + // Value is the value for the directive. Can be the full value or a substring. If it's a substring, |
| 25 | + // then ValueSubstringAllowed should be true. |
| 26 | + Value string |
| 27 | + // File is the file name that should contain the directive. Can be a full filename or a substring. |
| 28 | + File string |
| 29 | + // Location is the location name that the directive should exist in. |
| 30 | + Location string |
| 31 | + // Servers are the server names that the directive should exist in. |
| 32 | + Servers []string |
| 33 | + // ValueSubstringAllowed allows the expected value to be a substring of the real value. |
| 34 | + // This makes it easier for cases when real values are complex file names or contain things we |
| 35 | + // don't care about, and we just want to check if a substring exists. |
| 36 | + ValueSubstringAllowed bool |
| 37 | +} |
| 38 | + |
| 39 | +// ValidateNginxFieldExists accepts the nginx config and the configuration for the expected field, |
| 40 | +// and returns whether or not that field exists where it should. |
| 41 | +func ValidateNginxFieldExists(conf *Payload, expFieldCfg ExpectedNginxField) error { |
| 42 | + for _, config := range conf.Config { |
| 43 | + if !strings.Contains(config.File, expFieldCfg.File) { |
| 44 | + continue |
| 45 | + } |
| 46 | + |
| 47 | + for _, directive := range config.Parsed { |
| 48 | + if len(expFieldCfg.Servers) == 0 { |
| 49 | + if expFieldCfg.fieldFound(directive) { |
| 50 | + return nil |
| 51 | + } |
| 52 | + continue |
| 53 | + } |
| 54 | + |
| 55 | + for _, serverName := range expFieldCfg.Servers { |
| 56 | + if directive.Directive == "server" && getServerName(directive.Block) == serverName { |
| 57 | + for _, serverDirective := range directive.Block { |
| 58 | + if expFieldCfg.Location == "" && expFieldCfg.fieldFound(serverDirective) { |
| 59 | + return nil |
| 60 | + } else if serverDirective.Directive == "location" && |
| 61 | + fieldExistsInLocation(serverDirective, expFieldCfg) { |
| 62 | + return nil |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + b, err := json.Marshal(conf) |
| 71 | + if err != nil { |
| 72 | + return fmt.Errorf("error marshaling nginx config: %w", err) |
| 73 | + } |
| 74 | + |
| 75 | + return fmt.Errorf("field not found; expected: %+v\nNGINX conf: %s", expFieldCfg, string(b)) |
| 76 | +} |
| 77 | + |
| 78 | +func getServerName(serverBlock Directives) string { |
| 79 | + for _, directive := range serverBlock { |
| 80 | + if directive.Directive == "server_name" { |
| 81 | + return directive.Args[0] |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + return "" |
| 86 | +} |
| 87 | + |
| 88 | +func (e ExpectedNginxField) fieldFound(directive *Directive) bool { |
| 89 | + arg := strings.Join(directive.Args, " ") |
| 90 | + |
| 91 | + valueMatch := arg == e.Value |
| 92 | + if e.ValueSubstringAllowed { |
| 93 | + valueMatch = strings.Contains(arg, e.Value) |
| 94 | + } |
| 95 | + |
| 96 | + return directive.Directive == e.Directive && valueMatch |
| 97 | +} |
| 98 | + |
| 99 | +func fieldExistsInLocation(locationDirective *Directive, expFieldCfg ExpectedNginxField) bool { |
| 100 | + // location could start with '=', so get the last element which is the path |
| 101 | + loc := locationDirective.Args[len(locationDirective.Args)-1] |
| 102 | + if loc == expFieldCfg.Location { |
| 103 | + for _, directive := range locationDirective.Block { |
| 104 | + if expFieldCfg.fieldFound(directive) { |
| 105 | + return true |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + return false |
| 111 | +} |
| 112 | + |
| 113 | +// injectCrossplaneContainer adds an ephemeral container that contains crossplane for parsing |
| 114 | +// nginx config. It attaches to the nginx container and shares volumes with it. |
| 115 | +func injectCrossplaneContainer( |
| 116 | + k8sClient kubernetes.Interface, |
| 117 | + timeout time.Duration, |
| 118 | + ngfPodName, |
| 119 | + namespace string, |
| 120 | +) error { |
| 121 | + ctx, cancel := context.WithTimeout(context.Background(), timeout) |
| 122 | + defer cancel() |
| 123 | + |
| 124 | + pod := &core.Pod{ |
| 125 | + ObjectMeta: metav1.ObjectMeta{ |
| 126 | + Name: ngfPodName, |
| 127 | + Namespace: namespace, |
| 128 | + }, |
| 129 | + Spec: core.PodSpec{ |
| 130 | + EphemeralContainers: []core.EphemeralContainer{ |
| 131 | + { |
| 132 | + TargetContainerName: "nginx", |
| 133 | + EphemeralContainerCommon: core.EphemeralContainerCommon{ |
| 134 | + Name: "crossplane", |
| 135 | + Image: "nginx-crossplane:latest", |
| 136 | + ImagePullPolicy: "Never", |
| 137 | + Stdin: true, |
| 138 | + VolumeMounts: []core.VolumeMount{ |
| 139 | + { |
| 140 | + MountPath: "/etc/nginx/conf.d", |
| 141 | + Name: "nginx-conf", |
| 142 | + }, |
| 143 | + { |
| 144 | + MountPath: "/etc/nginx/stream-conf.d", |
| 145 | + Name: "nginx-stream-conf", |
| 146 | + }, |
| 147 | + { |
| 148 | + MountPath: "/etc/nginx/module-includes", |
| 149 | + Name: "module-includes", |
| 150 | + }, |
| 151 | + { |
| 152 | + MountPath: "/etc/nginx/secrets", |
| 153 | + Name: "nginx-secrets", |
| 154 | + }, |
| 155 | + { |
| 156 | + MountPath: "/etc/nginx/includes", |
| 157 | + Name: "nginx-includes", |
| 158 | + }, |
| 159 | + }, |
| 160 | + }, |
| 161 | + }, |
| 162 | + }, |
| 163 | + }, |
| 164 | + } |
| 165 | + |
| 166 | + podClient := k8sClient.CoreV1().Pods(namespace) |
| 167 | + if _, err := podClient.UpdateEphemeralContainers(ctx, ngfPodName, pod, metav1.UpdateOptions{}); err != nil { |
| 168 | + return fmt.Errorf("error adding ephemeral container: %w", err) |
| 169 | + } |
| 170 | + |
| 171 | + return nil |
| 172 | +} |
| 173 | + |
| 174 | +// createCrossplaneExecutor creates the executor for the crossplane command. |
| 175 | +func createCrossplaneExecutor( |
| 176 | + k8sClient kubernetes.Interface, |
| 177 | + k8sConfig *rest.Config, |
| 178 | + ngfPodName, |
| 179 | + namespace string, |
| 180 | +) (remotecommand.Executor, error) { |
| 181 | + cmd := []string{"./crossplane", "/etc/nginx/nginx.conf"} |
| 182 | + opts := &core.PodExecOptions{ |
| 183 | + Command: cmd, |
| 184 | + Container: "crossplane", |
| 185 | + Stdout: true, |
| 186 | + Stderr: true, |
| 187 | + } |
| 188 | + |
| 189 | + req := k8sClient.CoreV1().RESTClient().Post(). |
| 190 | + Resource("pods"). |
| 191 | + SubResource("exec"). |
| 192 | + Name(ngfPodName). |
| 193 | + Namespace(namespace). |
| 194 | + VersionedParams(opts, scheme.ParameterCodec) |
| 195 | + |
| 196 | + exec, err := remotecommand.NewSPDYExecutor(k8sConfig, http.MethodPost, req.URL()) |
| 197 | + if err != nil { |
| 198 | + return nil, fmt.Errorf("error creating executor: %w", err) |
| 199 | + } |
| 200 | + |
| 201 | + return exec, nil |
| 202 | +} |
| 203 | + |
| 204 | +// The following types are copied from https://github.com/nginxinc/nginx-go-crossplane, |
| 205 | +// with unnecessary fields stripped out. |
| 206 | +type Payload struct { |
| 207 | + Config []Config `json:"config"` |
| 208 | +} |
| 209 | + |
| 210 | +type Config struct { |
| 211 | + File string `json:"file"` |
| 212 | + Parsed Directives `json:"parsed"` |
| 213 | +} |
| 214 | + |
| 215 | +type Directive struct { |
| 216 | + Comment *string `json:"comment,omitempty"` |
| 217 | + Directive string `json:"directive"` |
| 218 | + File string `json:"file,omitempty"` |
| 219 | + Args []string `json:"args"` |
| 220 | + Includes []int `json:"includes,omitempty"` |
| 221 | + Block Directives `json:"block,omitempty"` |
| 222 | + Line int `json:"line"` |
| 223 | +} |
| 224 | + |
| 225 | +type Directives []*Directive |
0 commit comments