diff --git a/.github/workflows/multus.yaml b/.github/workflows/multus.yaml index f71b1482e..a24a6289b 100644 --- a/.github/workflows/multus.yaml +++ b/.github/workflows/multus.yaml @@ -55,6 +55,9 @@ jobs: - name: Setup multus run: ./tests/scripts/multus/setup-multus.sh + - name: Set up multus prerequisite host routing + run: kubectl create -f tests/scripts/multus/host-cfg-ds.yaml + - name: Install public and cluster NADs in default namespace run: kubectl create -f tests/scripts/multus/default-public-cluster-nads.yaml diff --git a/Documentation/CRDs/Cluster/network-providers.md b/Documentation/CRDs/Cluster/network-providers.md index 053e443a9..142d8cda4 100644 --- a/Documentation/CRDs/Cluster/network-providers.md +++ b/Documentation/CRDs/Cluster/network-providers.md @@ -207,26 +207,43 @@ ranges could be manually specified for the networks if needed. ### Validating Multus configuration -We **highly** recommend validating your Multus configuration before you install Rook. A tool exists -to facilitate validating the Multus configuration. After installing the Rook operator and before -installing any Custom Resources, run the tool from the operator pod. +We **highly** recommend validating your Multus configuration before you install a CephCluster. +A tool exists to facilitate validating the Multus configuration. After installing the Rook operator +and before installing any Custom Resources, run the tool from the operator pod. The tool's CLI is designed to be as helpful as possible. Get help text for the multus validation tool like so: -```console -kubectl --namespace rook-ceph exec -it deploy/rook-ceph-operator -- rook multus validation run --help -``` +1. Exec into the Rook operator pod -Then, update the args in the -[multus-validation](https://github.com/rook/rook/blob/master/deploy/examples/multus-validation.yaml) -job template. Minimally, add the NAD names(s) for public and/or cluster as needed and then, -create the job to validate the Multus configuration. + ```console + kubectl --namespace rook-ceph exec -it deploy/rook-ceph-operator -- bash + ``` -If the tool fails, it will suggest what things may be preventing Multus networks from working -properly, and it will request the logs and outputs that will help debug issues. +2. Output and read the tool's help text -Check the logs of the pod created by the job to know the status of the validation test. + ```console + rook multus validation run --help + ``` + +3. Use the validation tool config file for advanced configuration. + + ```console + rook multus validation config --help + ``` + + Generate a sample config, that includes commented help text, using one of the available templates. + +4. Run the tool after configuring. If the tool fails, it will suggest what things may be preventing + Multus networks from working properly, and it will request the logs and outputs that will help + debug issues. + +!!! note + The tool requires host network access. Many Kubernetes distros have security limitations. Use + the tool's `serviceAccountName` config option or `--service-account-name` CLI flag to instruct + the tool to run using a particular ServiceAccount in order to allow necessary permissions. + An example compatible with openshift is provided in the Rook repository at + [deploy/examples/multus-validation-test-openshift.yaml](https://github.com/rook/rook/blob/master/deploy/examples/multus-validation-test-openshift.yaml) ### Known limitations with Multus @@ -445,6 +462,10 @@ may be something like PXE, ignition config, cloud-init, Ansible, or any other su reboot is likely necessary to apply configuration updates, but wait until the next step to reboot nodes. +If desired, check that the NetworkAttachmentDefinition modification and host configurations are +compatible using the [Multus validation tool](#validating-multus-configuration). For the upgrade +case, use the `hostCheckOnly: true` config option or `--host-check-only` CLI flag. + **Step 4** After the NetworkAttachmentDefinition is modified, OSD pods must be restarted. It is easiest to diff --git a/Makefile b/Makefile index b4ce0cce7..ffdbe5efc 100644 --- a/Makefile +++ b/Makefile @@ -179,7 +179,6 @@ prune: ## Prune cached artifacts. @$(MAKE) -C images prune docs: helm-docs - @build/deploy/generate-deploy-examples.sh crds: $(CONTROLLER_GEN) $(YQ) @echo Updating CRD manifests diff --git a/build/deploy/generate-deploy-examples.sh b/build/deploy/generate-deploy-examples.sh deleted file mode 100755 index ca276a49a..000000000 --- a/build/deploy/generate-deploy-examples.sh +++ /dev/null @@ -1,24 +0,0 @@ -#! /usr/bin/env bash -set -e - -SCRIPT_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) -MANIFEST_FILE=../../deploy/examples/multus-validation.yaml -SED=${SCRIPT_ROOT}/../../build/sed-in-place -if [[ ${SKIP_GEN} = true ]]; then - echo "SKIP_GEN is set, skipping manifest generation" - exit -fi -OUT_FILE="${SCRIPT_ROOT}/${MANIFEST_FILE}" -TMP_FILE="$(mktemp)" - -START_MARKER='# THE BELOW HELP TEXT IS AUTO-GENERATED BY `make docs`$' -END_MARKER='# THE ABOVE HELP TEXT IS AUTO-GENERATED BY `make docs`$' - -go run ${SCRIPT_ROOT}/../../cmd/rook/*.go multus validation run --help | awk '{print "# "$0}' | sed -e 's/[ \t]*$//' > ${TMP_FILE} - -${SED} -e "/$START_MARKER/,/$END_MARKER/{ /$START_MARKER/{ p ; r $TMP_FILE - - }; /$END_MARKER/p; d; }" ${OUT_FILE} - -rm -f ${TMP_FILE} - diff --git a/cmd/rook/userfacing/multus/validation/validation.go b/cmd/rook/userfacing/multus/validation/validation.go index 57ef73159..e5f1c4321 100644 --- a/cmd/rook/userfacing/multus/validation/validation.go +++ b/cmd/rook/userfacing/multus/validation/validation.go @@ -38,6 +38,9 @@ var ( // keep special var for `--daemons-per-node` that needs put into node config for validation run flagDaemonsPerNode = -1 + + // keep special var for --host-check-only flag that can override what is from config file + flagHostCheckOnly = false ) // commands @@ -131,6 +134,9 @@ func init() { "The default value is set to the worst-case value for a Rook Ceph cluster with 3 portable OSDs, 3 portable monitors, "+ "and where all optional child resources have been created with 1 daemon such that they all might run on a single node in a failure scenario. "+ "If you aren't sure what to choose for this value, add 1 for each additional OSD beyond 3.") + runCmd.Flags().BoolVar(&flagHostCheckOnly, "host-check-only", defaultConfig.HostCheckOnly, + "Only check that hosts can connect to the server via the public network. Do not start clients. "+ + "This mode is recommended when a Rook cluster is already running and consuming the public network specified.") runCmd.Flags().StringVar(&validationConfig.NginxImage, "nginx-image", defaultConfig.NginxImage, "The Nginx image used for the validation server and clients.") @@ -147,7 +153,8 @@ func init() { "clients to start, and it therefore may take longer for all clients to become 'Ready'; in that case, this value can be set slightly higher.") runCmd.Flags().StringVarP(&validationConfigFile, "config", "c", "", - "The validation test config file to use. This cannot be used with other flags.") + "The validation test config file to use. This cannot be used with other flags except --host-check-only.") + // allow using --host-check-only in combo with --config so the same config can be used with that flag if desired runCmd.MarkFlagsMutuallyExclusive("config", "timeout-minutes") runCmd.MarkFlagsMutuallyExclusive("config", "namespace") runCmd.MarkFlagsMutuallyExclusive("config", "public-network") @@ -184,6 +191,11 @@ func runValidation(ctx context.Context) { } } + // allow --host-check-only(=true) flag to override default/configfile settings + if flagHostCheckOnly { + validationConfig.HostCheckOnly = true + } + if err := validationConfig.ValidationTestConfig.Validate(); err != nil { fmt.Print(err.Error() + "\n") os.Exit(22 /* EINVAL */) diff --git a/deploy/examples/multus-validation-test-openshift.yaml b/deploy/examples/multus-validation-test-openshift.yaml new file mode 100644 index 000000000..5781ee162 --- /dev/null +++ b/deploy/examples/multus-validation-test-openshift.yaml @@ -0,0 +1,38 @@ +# ServiceAccount and RBAC to support running multus validation test on OpenShift +# Deploy these resources, then use `serviceAccountName: multus-validation-test` in the validation +# test config file. +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: multus-validation-test + namespace: openshift-storage +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: multus-validation-test + namespace: openshift-storage +rules: + - apiGroups: + - security.openshift.io + resourceNames: + - hostnetwork-v2 + resources: + - securitycontextconstraints + verbs: + - use +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: multus-validation-test + namespace: openshift-storage +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: multus-validation-test +subjects: + - kind: ServiceAccount + name: multus-validation-test + namespace: openshift-storage diff --git a/deploy/examples/multus-validation.yaml b/deploy/examples/multus-validation.yaml deleted file mode 100644 index b33689ab2..000000000 --- a/deploy/examples/multus-validation.yaml +++ /dev/null @@ -1,173 +0,0 @@ -#################################################################################################### -# This manifest contains a Kubernetes Job and supporting definitions for running Rook's Multus -# validation tool. The Multus validation tool's help text is copied below. Modify the Job -# definition in this manifest based on the needs of your cluster. -#################################################################################################### -# THE BELOW HELP TEXT IS AUTO-GENERATED BY `make docs` -# -# Run a validation test that determines whether the current Multus and system -# configurations will support Rook with Multus. -# -# This should be run BEFORE Rook is installed. -# -# This is a fairly long-running test. It starts up a web server and many -# clients to verify that Multus network communication works properly. -# -# It does *not* perform any load testing. Networks that cannot support high -# volumes of Ceph traffic may still encounter runtime issues. This may be -# particularly noticeable with high I/O load or during OSD rebalancing -# (see: https://docs.ceph.com/en/latest/architecture/#rebalancing). -# For example, during Rook or Ceph cluster upgrade. -# -# Override the kube config file location by setting the KUBECONFIG environment variable. -# -# Usage: -# rook multus validation run [--public-network=] [--cluster-network=] [flags] -# -# Flags: -# --cluster-network string The name of the Network Attachment Definition (NAD) that will be used for Ceph's cluster network. This should be a namespaced name in the form / if the NAD is defined in a different namespace from the cluster namespace. -# -c, --config string The validation test config file to use. This cannot be used with other flags. -# --daemons-per-node int The number of validation test daemons to run per node. It is recommended to set this to the maximum number of Ceph daemons that can run on any node in the worst case of node failure(s). The default value is set to the worst-case value for a Rook Ceph cluster with 3 portable OSDs, 3 portable monitors, and where all optional child resources have been created with 1 daemon such that they all might run on a single node in a failure scenario. If you aren't sure what to choose for this value, add 1 for each additional OSD beyond 3. (default 19) -# --flaky-threshold-seconds timeoutSeconds This is the time window in which validation clients are all expected to become 'Ready' together. Validation clients are all started at approximately the same time, and they should all stabilize at approximately the same time. Once the first validation client becomes 'Ready', the tool checks that all of the remaining clients become 'Ready' before this threshold duration elapses. In networks that have connectivity issues, limited bandwidth, or high latency, clients will contend for network traffic with each other, causing some clients to randomly fail and become 'Ready' later than others. These randomly-failing clients are considered 'flaky.' Adjust this value to reflect expectations for the underlying network. For fast and reliable networks, this can be set to a smaller value. For networks that are intended to be slow, this can be set to a larger value. Additionally, for very large Kubernetes clusters, it may take longer for all clients to start, and it therefore may take longer for all clients to become 'Ready'; in that case, this value can be set slightly higher. (default 30s) -# -h, --help help for run -# -n, --namespace string The namespace for validation test resources. It is recommended to set this to the namespace in which Rook's Ceph cluster will be installed. (default "rook-ceph") -# --nginx-image string The Nginx image used for the validation server and clients. (default "quay.io/nginx/nginx-unprivileged:stable-alpine") -# --public-network string The name of the Network Attachment Definition (NAD) that will be used for Ceph's public network. This should be a namespaced name in the form / if the NAD is defined in a different namespace from the cluster namespace. -# --timeout-minutes timeoutMinutes The time to wait for resources to change to the expected state. For example, for the test web server to start, for test clients to become ready, or for test resources to be deleted. At longest, this may need to reflect the time it takes for client pods to to pull images, get address assignments, and then for each client to determine that its network connection is stable. Minimum: 1 minute. Recommended: 2 minutes or more. (default 3m0s) -# -# Global Flags: -# --log-level string logging level for logging/tracing output (valid values: ERROR,WARNING,INFO,DEBUG) (default "INFO") -# THE ABOVE HELP TEXT IS AUTO-GENERATED BY `make docs` -#################################################################################################### ---- -# Service account for job that validates multus configuration -apiVersion: v1 -kind: ServiceAccount -metadata: - name: rook-ceph-multus-validation - namespace: rook-ceph # namespace:cluster -# imagePullSecrets: -# - name: my-registry-secret ---- -# Aspects of multus validation job that require access to the operator/cluster namespace -kind: Role -apiVersion: rbac.authorization.k8s.io/v1 -metadata: - name: rook-ceph-multus-validation - namespace: rook-ceph # namespace:cluster -rules: - - apiGroups: [""] - resources: ["configmaps", "configmaps/finalizers", "pods"] - verbs: ["get", "list", "create", "update", "delete"] - - apiGroups: ["apps"] - resources: ["daemonsets"] - verbs: ["list", "create", "delete", "deletecollection"] - - apiGroups: ["k8s.cni.cncf.io"] - resources: ["network-attachment-definitions"] - verbs: ["get"] - - apiGroups: ["batch"] - resources: ["jobs"] - verbs: ["get", "list", "delete"] ---- -# Allow the multus validation job to run in this namespace -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: rook-ceph-multus-validation - namespace: rook-ceph # namespace:cluster -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: Role - name: rook-ceph-multus-validation -subjects: - - kind: ServiceAccount - name: rook-ceph-multus-validation - namespace: rook-ceph # namespace:cluster ---- -# A job that runs the multus validation tool -apiVersion: batch/v1 -kind: Job -metadata: - name: rook-ceph-multus-validation - namespace: rook-ceph # namespace:cluster - labels: - app: rook-ceph-multus-validation -spec: - template: - metadata: - labels: - app: rook-ceph-multus-validation - spec: - serviceAccountName: rook-ceph-multus-validation - containers: - - name: multus-validation - image: rook/ceph:master - command: ["rook"] - args: - - "multus" - - "validation" - - "run" - # - "--public-network=" # uncomment and replace NAD name if using public network - # - "--cluster-network=" # uncomment and replace NAD name if using cluster network - # - "--nginx-image=" # uncomment and replace IMAGE with the nginx image you want use for the validation server and clients - # - "--daemons-per-node=" # uncomment and replace COUNT with the maximum number of daemons that should be running on each node during validation - env: - - name: POD_NAMESPACE - valueFrom: - fieldRef: - fieldPath: metadata.namespace - - name: ROOK_LOG_LEVEL - value: DEBUG - restartPolicy: Never ---- -# This Pod Security Policy (PSP) allows the job to run in Kubernetes environments using PSPs -# apiVersion: rbac.authorization.k8s.io/v1 -# kind: RoleBinding -# metadata: -# name: rook-ceph-multus-validation-psp -# namespace: rook-ceph # namespace:cluster -# roleRef: -# apiGroup: rbac.authorization.k8s.io -# kind: ClusterRole -# name: psp:rook -# subjects: -# - kind: ServiceAccount -# name: rook-ceph-multus-validation -# namespace: rook-ceph # namespace:cluster -# --- -# SecurityContextConstraints(SCC) for the Rook and Ceph daemons -# kind: SecurityContextConstraints -# apiVersion: security.openshift.io/v1 -# metadata: -# name: rook-ceph-multus-validation -# allowPrivilegedContainer: true -# allowHostDirVolumePlugin: true -# allowHostPID: false -# # set to true if running rook with host networking enabled -# allowHostNetwork: true -# # set to true if running rook with the provider as host -# allowHostPorts: true -# priority: -# allowedCapabilities: ["MKNOD"] -# allowHostIPC: true -# readOnlyRootFilesystem: false -# # drop all default privileges -# requiredDropCapabilities: ["All"] -# defaultAddCapabilities: [] -# runAsUser: -# type: RunAsAny -# seLinuxContext: -# type: RunAsAny -# fsGroup: -# type: RunAsAny -# supplementalGroups: -# type: RunAsAny -# seccompProfiles: -# - "*" -# volumes: -# - configMap -# - emptyDir -# - projected -# users: -# - system:serviceaccount:rook-ceph:rook-ceph-multus-validation # serviceaccount:namespace:cluster ---- diff --git a/pkg/daemon/multus/config.go b/pkg/daemon/multus/config.go index 401aa4435..a651a183b 100644 --- a/pkg/daemon/multus/config.go +++ b/pkg/daemon/multus/config.go @@ -38,6 +38,8 @@ var ( var ( DefaultValidationNamespace = "rook-ceph" + DefaultServiceAccountName = "rook-ceph-system" + DefaultValidationOSDsPerNode = 3 DefaultValidationOtherDaemonsPerNode = 16 @@ -70,13 +72,15 @@ func init() { // for this struct from getting out of date, see the output of ValidationTestConfig.ToYAML() for // usage text for each field. type ValidationTestConfig struct { - Namespace string `yaml:"namespace"` - PublicNetwork string `yaml:"publicNetwork"` - ClusterNetwork string `yaml:"clusterNetwork"` - ResourceTimeout time.Duration `yaml:"resourceTimeout"` - FlakyThreshold time.Duration `yaml:"flakyThreshold"` - NginxImage string `yaml:"nginxImage"` - NodeTypes map[string]NodeConfig `yaml:"nodeTypes"` + Namespace string `yaml:"namespace"` + ServiceAccountName string `yaml:"serviceAccountName"` + PublicNetwork string `yaml:"publicNetwork"` + ClusterNetwork string `yaml:"clusterNetwork"` + ResourceTimeout time.Duration `yaml:"resourceTimeout"` + FlakyThreshold time.Duration `yaml:"flakyThreshold"` + HostCheckOnly bool `yaml:"hostCheckOnly"` + NginxImage string `yaml:"nginxImage"` + NodeTypes map[string]NodeConfig `yaml:"nodeTypes"` } type NodeConfig struct { @@ -114,10 +118,11 @@ func (t *TolerationType) ToJSON() (string, error) { // The default test is a converged-node test with no placement. func NewDefaultValidationTestConfig() *ValidationTestConfig { return &ValidationTestConfig{ - Namespace: DefaultValidationNamespace, - ResourceTimeout: DefaultValidationResourceTimeout, - FlakyThreshold: DefaultValidationFlakyThreshold, - NginxImage: DefaultValidationNginxImage, + Namespace: DefaultValidationNamespace, + ServiceAccountName: DefaultServiceAccountName, + ResourceTimeout: DefaultValidationResourceTimeout, + FlakyThreshold: DefaultValidationFlakyThreshold, + NginxImage: DefaultValidationNginxImage, NodeTypes: map[string]NodeConfig{ DefaultValidationNodeType: { OSDsPerNode: DefaultValidationOSDsPerNode, @@ -266,10 +271,11 @@ var dedicatedWorkerNodeConfig = NodeConfig{ func NewDedicatedStorageNodesValidationTestConfig() *ValidationTestConfig { return &ValidationTestConfig{ - Namespace: DefaultValidationNamespace, - ResourceTimeout: DefaultValidationResourceTimeout, - FlakyThreshold: DefaultValidationFlakyThreshold, - NginxImage: DefaultValidationNginxImage, + Namespace: DefaultValidationNamespace, + ServiceAccountName: DefaultServiceAccountName, + ResourceTimeout: DefaultValidationResourceTimeout, + FlakyThreshold: DefaultValidationFlakyThreshold, + NginxImage: DefaultValidationNginxImage, NodeTypes: map[string]NodeConfig{ DedicatedStorageNodeType: dedicatedStorageNodeConfig, DedicatedWorkerNodeType: dedicatedWorkerNodeConfig, @@ -283,10 +289,11 @@ const ( func NewArbiterValidationTestConfig() *ValidationTestConfig { return &ValidationTestConfig{ - Namespace: DefaultValidationNamespace, - ResourceTimeout: DefaultValidationResourceTimeout, - FlakyThreshold: DefaultValidationFlakyThreshold, - NginxImage: DefaultValidationNginxImage, + Namespace: DefaultValidationNamespace, + ServiceAccountName: DefaultServiceAccountName, + ResourceTimeout: DefaultValidationResourceTimeout, + FlakyThreshold: DefaultValidationFlakyThreshold, + NginxImage: DefaultValidationNginxImage, NodeTypes: map[string]NodeConfig{ DedicatedStorageNodeType: dedicatedStorageNodeConfig, DedicatedWorkerNodeType: dedicatedWorkerNodeConfig, diff --git a/pkg/daemon/multus/config.yaml b/pkg/daemon/multus/config.yaml index e38fea5c8..fb4cd5032 100644 --- a/pkg/daemon/multus/config.yaml +++ b/pkg/daemon/multus/config.yaml @@ -2,6 +2,12 @@ # Rook-Ceph cluster will be installed. namespace: "{{ .Namespace }}" +# The service account to run validation test pods as. Empty means pods won't use a service account. +# This is useful in Kubernetes environments where security rules are in place. +# Notably, host checker pods require host network access. +# The default is to use the same service account for the Rook operator (rook-ceph-system). +serviceAccountName: "{{ .ServiceAccountName }}" + # These fields should be set to the name of the Network Attachment Definition (NAD) which will be # used for the Ceph cluster's public or cluster network, respectively. This should be a namespaced # name in the form / if the NAD is defined in a different namespace from the @@ -29,6 +35,13 @@ resourceTimeout: "{{ .ResourceTimeout }}" # longer for all clients to become "Ready"; in that case, this value can be set slightly higher. flakyThreshold: "{{ .FlakyThreshold }}" +# Enable host-check-only mode. This will instruct the validation test routine to only check host +# connectivity to the server via the public network. It won't start clients and cannot check for +# network flakiness. This mode is recommended when a Rook cluster is already running and consuming +# the public network specified. This mode avoids disrupting to the running Rook cluster that could +# be impacted by a large number of running clients that might run without this mode enabled. +hostCheckOnly: {{ .HostCheckOnly }} + # The Nginx image which will be used for the web server and clients. nginxImage: "{{ .NginxImage }}" diff --git a/pkg/daemon/multus/config_test.go b/pkg/daemon/multus/config_test.go index 0e4387017..821533f5c 100644 --- a/pkg/daemon/multus/config_test.go +++ b/pkg/daemon/multus/config_test.go @@ -36,12 +36,14 @@ func TestValidationTestConfig_YAML(t *testing.T) { {"empty config", emptyValidationTestConfig}, {"default config", NewDefaultValidationTestConfig()}, {"full config", &ValidationTestConfig{ - Namespace: "my-rook", - PublicNetwork: "my-pub", - ClusterNetwork: "my-priv", - ResourceTimeout: 2 * time.Minute, - FlakyThreshold: 30 * time.Second, - NginxImage: "myorg/nginx:latest", + Namespace: "my-rook", + ServiceAccountName: "my-svc-acct", + PublicNetwork: "my-pub", + ClusterNetwork: "my-priv", + ResourceTimeout: 2 * time.Minute, + FlakyThreshold: 30 * time.Second, + HostCheckOnly: true, + NginxImage: "myorg/nginx:latest", NodeTypes: map[string]NodeConfig{ "osdOnlyNodes": { OSDsPerNode: 9, diff --git a/pkg/daemon/multus/host-daemonset.yaml b/pkg/daemon/multus/host-daemonset.yaml new file mode 100644 index 000000000..475595d49 --- /dev/null +++ b/pkg/daemon/multus/host-daemonset.yaml @@ -0,0 +1,68 @@ +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: multus-validation-test-host-checker-{{ .NodeType }} + labels: + app: multus-validation-test-host-checker + nodeType: "{{ .NodeType }}" + app.kubernetes.io/name: "host-checker" + app.kubernetes.io/instance: "host-checker-{{ .NodeType }}" + app.kubernetes.io/component: "host-checker" + app.kubernetes.io/part-of: "multus-validation-test" + app.kubernetes.io/managed-by: "rook-cli" +spec: + selector: + matchLabels: + app: multus-validation-test-host-checker + nodeType: "{{ .NodeType }}" + template: + metadata: + labels: + app: multus-validation-test-host-checker + nodeType: "{{ .NodeType }}" + spec: + nodeSelector: + {{- range $k, $v := .Placement.NodeSelector }} + {{ $k }}: {{ $v }} + {{- end }} + tolerations: + {{- range $idx, $toleration := .Placement.Tolerations }} + - {{ $toleration.ToJSON }} + {{- end }} + securityContext: + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + hostNetwork: true + containers: + - name: readiness-check-web-server-public-addr + # use nginx image because it's already used for the web server pod and has a non-root user + image: "{{ .NginxImage }}" + command: + - sleep + - infinity + resources: {} + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - "ALL" + # A readiness probe makes validation testing easier than investigate container logs. + # Additionally, readiness probe failures don't result in CrashLoopBackoff -- ideal here, + # where ever-longer back-offs would cause tests to run for much longer than necessary. + readinessProbe: + # Low failure threshold and high success threshold. Intended to be very sensitive to + # failures. If probe fails with any regularity, Ceph OSDs likely won't be stable. + failureThreshold: 1 + successThreshold: 12 + periodSeconds: 5 + # Assumption: a network with a latency more than 4 seconds for this validation test's + # simple client-server response likely won't support acceptable performance for any + # production Ceph cluster. + timeoutSeconds: 4 + # TODO: exec:curl works but httpGet fails. Why? need custom header? + exec: + command: + - "curl" + - "--insecure" + - "{{ .PublicNetworkAddress }}:8080" diff --git a/pkg/daemon/multus/resources.go b/pkg/daemon/multus/resources.go index a058e4862..81f457287 100644 --- a/pkg/daemon/multus/resources.go +++ b/pkg/daemon/multus/resources.go @@ -157,13 +157,13 @@ func (vt *ValidationTest) startImagePullers(ctx context.Context, owners []meta.O return nil } -func (vt *ValidationTest) deleteImagePullers(ctx context.Context) error { +func (vt *ValidationTest) deleteDaemonsetsWithLabel(ctx context.Context, label string) error { noGracePeriod := int64(0) delOpts := meta.DeleteOptions{ GracePeriodSeconds: &noGracePeriod, } listOpts := meta.ListOptions{ - LabelSelector: imagePullAppLabel(), + LabelSelector: label, } err := vt.Clientset.AppsV1().DaemonSets(vt.Namespace).DeleteCollection(ctx, delOpts, listOpts) if err != nil { @@ -176,6 +176,27 @@ func (vt *ValidationTest) deleteImagePullers(ctx context.Context) error { return nil } +func (vt *ValidationTest) startHostCheckers( + ctx context.Context, + owners []meta.OwnerReference, + serverPublicAddr string, +) error { + for typeName, nodeType := range vt.NodeTypes { + ds, err := vt.generateHostCheckerDaemonSet(serverPublicAddr, typeName, nodeType.Placement) + if err != nil { + return fmt.Errorf("failed to generate host checker daemonset: %w", err) + } + ds.SetOwnerReferences(owners) // set owner so cleanup is easier + + _, err = vt.Clientset.AppsV1().DaemonSets(vt.Namespace).Create(ctx, ds, meta.CreateOptions{}) + if err != nil { + return fmt.Errorf("failed to create host checker daemonset: %w", err) + } + } + + return nil +} + func (vt *ValidationTest) startClients( ctx context.Context, owners []meta.OwnerReference, @@ -335,10 +356,10 @@ func (vt *ValidationTest) getNumRunningPods( return numRunning, nil } -func (vt *ValidationTest) numClientsReady(ctx context.Context, expectedNumPods int) (int, error) { - pods, err := vt.getClientPods(ctx, expectedNumPods) +func (vt *ValidationTest) numPodsReadyWithLabel(ctx context.Context, label string) (int, error) { + pods, err := vt.getPodsWithLabel(ctx, label) if err != nil { - return 0, fmt.Errorf("unexpected error getting client pods: %w", err) + return 0, fmt.Errorf("unexpected error getting pods with label %q: %w", label, err) } numReady := 0 for _, p := range pods.Items { @@ -349,16 +370,13 @@ func (vt *ValidationTest) numClientsReady(ctx context.Context, expectedNumPods i return numReady, nil } -func (vt *ValidationTest) getClientPods(ctx context.Context, expectedNumPods int) (*core.PodList, error) { +func (vt *ValidationTest) getPodsWithLabel(ctx context.Context, label string) (*core.PodList, error) { listOpts := meta.ListOptions{ - LabelSelector: clientAppLabel(), + LabelSelector: label, } pods, err := vt.Clientset.CoreV1().Pods(vt.Namespace).List(ctx, listOpts) if err != nil { - return nil, fmt.Errorf("failed to list client pods: %w", err) - } - if len(pods.Items) != expectedNumPods { - return nil, fmt.Errorf("the number of pods listed [%d] does not match the number expected [%d]", len(pods.Items), expectedNumPods) + return nil, fmt.Errorf("failed to list pods with label %q: %w", label, err) } return pods, err } diff --git a/pkg/daemon/multus/templates.go b/pkg/daemon/multus/templates.go index 275e0f2a8..4f8afe23d 100644 --- a/pkg/daemon/multus/templates.go +++ b/pkg/daemon/multus/templates.go @@ -39,6 +39,9 @@ var ( //go:embed image-pull-daemonset.yaml imagePullDaemonSet string + //go:embed host-daemonset.yaml + hostCheckerDaemonSet string + //go:embed client-daemonset.yaml clientDaemonSet string ) @@ -55,6 +58,13 @@ type imagePullTemplateConfig struct { Placement PlacementConfig } +type hostCheckerTemplateConfig struct { + NodeType string + NginxImage string + PublicNetworkAddress string + Placement PlacementConfig +} + type clientTemplateConfig struct { NodeType string ClientType string @@ -73,6 +83,10 @@ func imagePullAppLabel() string { return "app=multus-validation-test-image-pull" } +func hostCheckerAppLabel() string { + return "app=multus-validation-test-host-checker" +} + func getNodeType(m *metav1.ObjectMeta) string { return m.GetLabels()["nodeType"] } @@ -89,6 +103,7 @@ const ( type daemonsetAppType string const imagePullDaemonSetAppType = "image pull" +const hostCheckerDaemonsetAppType = "host checker" const clientDaemonSetAppType = "client" func (vt *ValidationTest) generateWebServerTemplateConfig(placement PlacementConfig) webServerTemplateConfig { @@ -99,6 +114,19 @@ func (vt *ValidationTest) generateWebServerTemplateConfig(placement PlacementCon } } +func (vt *ValidationTest) generateHostCheckerTemplateConfig( + serverPublicAddr string, + nodeType string, + placement PlacementConfig, +) hostCheckerTemplateConfig { + return hostCheckerTemplateConfig{ + NodeType: nodeType, + PublicNetworkAddress: serverPublicAddr, + NginxImage: vt.NginxImage, + Placement: placement, + } +} + func (vt *ValidationTest) generateClientTemplateConfig( attachPublic, attachCluster bool, serverPublicAddr, serverClusterAddr string, @@ -150,6 +178,8 @@ func (vt *ValidationTest) generateWebServerPod(placement PlacementConfig) (*core return nil, fmt.Errorf("failed to unmarshal web server pod template: %w", err) } + vt.applyServiceAccountToPodSpec(&p.Spec) + return &p, nil } @@ -182,6 +212,29 @@ func (vt *ValidationTest) generateImagePullDaemonSet(nodeType string, placement return nil, fmt.Errorf("failed to unmarshal image pull daemonset template: %w", err) } + vt.applyServiceAccountToPodSpec(&d.Spec.Template.Spec) + + return &d, nil +} + +func (vt *ValidationTest) generateHostCheckerDaemonSet( + serverPublicAddr string, + nodeType string, + placement PlacementConfig, +) (*apps.DaemonSet, error) { + t, err := loadTemplate("hostCheckerDaemonSet", hostCheckerDaemonSet, vt.generateHostCheckerTemplateConfig(serverPublicAddr, nodeType, placement)) + if err != nil { + return nil, fmt.Errorf("failed to load host checker daemonset template: %w", err) + } + + var d apps.DaemonSet + err = yaml.Unmarshal(t, &d) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal host checker daemonset template: %w", err) + } + + vt.applyServiceAccountToPodSpec(&d.Spec.Template.Spec) + return &d, nil } @@ -203,6 +256,8 @@ func (vt *ValidationTest) generateClientDaemonSet( return nil, fmt.Errorf("failed to unmarshal client daemonset template: %w", err) } + vt.applyServiceAccountToPodSpec(&d.Spec.Template.Spec) + return &d, nil } @@ -217,6 +272,12 @@ func (vt *ValidationTest) generateNetworksAnnotationValue(public, cluster bool) return strings.Join(nets, ",") } +func (vt *ValidationTest) applyServiceAccountToPodSpec(ps *core.PodSpec) { + if vt.ServiceAccountName != "" { + ps.ServiceAccountName = vt.ServiceAccountName + } +} + func loadTemplate(name, templateFileText string, config interface{}) ([]byte, error) { var writer bytes.Buffer t := template.New(name) diff --git a/pkg/daemon/multus/validation.go b/pkg/daemon/multus/validation.go index d2676e2cc..b800da0f5 100644 --- a/pkg/daemon/multus/validation.go +++ b/pkg/daemon/multus/validation.go @@ -85,7 +85,7 @@ type getExpectedNumberOfImagePullPodsState struct { // the length of time to wait for daemonset scheduler to stabilize to a specific number of pods // started. must be lower than the state timeout duration -var podSchedulerDebounceTime = 30 * time.Second +var podSchedulerDebounceTime = 5 * time.Second // TODO: reset after testing func (s *getExpectedNumberOfImagePullPodsState) Run( ctx context.Context, vsm *validationStateMachine, @@ -137,6 +137,8 @@ func (s *ensureNodeTypesDoNotOverlapState) Run(ctx context.Context, vsm *validat * Reusable state to verify that expected number of pods are "Running" but not necessarily "Ready" * > Verify all image pull pods are running * -- next state --> Delete image pull daemonset + * > Verify all host checker pods are running + * -- next state --> Verify all host checker pods are "Ready" * > Verify all client pods are running * -- next state --> Verify all client pods are "Ready" */ @@ -144,6 +146,7 @@ type verifyAllPodsRunningState struct { AppType daemonsetAppType ImagePullPodsPerNodeType perNodeTypeCount ExpectedNumPods int + WebServerInfo *podNetworkInfo } func (s *verifyAllPodsRunningState) Run(ctx context.Context, vsm *validationStateMachine) (suggestions []string, err error) { @@ -155,6 +158,13 @@ func (s *verifyAllPodsRunningState) Run(ctx context.Context, vsm *validationStat podSelectorLabel = imagePullAppLabel() // image pull pods don't have multus labels, so this can't be a multus issue suggestions = append(suggestions, "inability to run image pull pods is likely an issue with Nginx image or Kubernetes itself") + case hostCheckerDaemonsetAppType: + if s.WebServerInfo == nil { + return []string{}, fmt.Errorf("internal error; web server info is nil when checking for host checker readiness") + } + podSelectorLabel = hostCheckerAppLabel() + // host checker pods don't have multus labels, so this can't be a multus issue + suggestions = append(suggestions, "inability to run host checker pods likely means that cluster security permissions disallow pods with host network enabled") case clientDaemonSetAppType: podSelectorLabel = clientAppLabel() suggestions = append(suggestions, "clients not being able to run can mean multus is unable to provide them with addresses") @@ -178,6 +188,11 @@ func (s *verifyAllPodsRunningState) Run(ctx context.Context, vsm *validationStat vsm.SetNextState(&deleteImagePullersState{ ImagePullPodsPerNodeType: s.ImagePullPodsPerNodeType, }) + case hostCheckerDaemonsetAppType: + vsm.SetNextState(&verifyAllHostCheckersReadyState{ + WebServerInfo: *s.WebServerInfo, + ImagePullPodsPerNodeType: s.ImagePullPodsPerNodeType, + }) case clientDaemonSetAppType: vsm.vt.Logger.Infof("verifying all %d 'Running' client pods reach 'Ready' state", s.ExpectedNumPods) vsm.SetNextState(&verifyAllClientsReadyState{ @@ -198,7 +213,7 @@ type deleteImagePullersState struct { } func (s *deleteImagePullersState) Run(ctx context.Context, vsm *validationStateMachine) (suggestions []string, err error) { - err = vsm.vt.deleteImagePullers(ctx) + err = vsm.vt.deleteDaemonsetsWithLabel(ctx, imagePullAppLabel()) if err != nil { // erroring here is not strictly necessary but does indicate a k8s issue that probably affects future test steps return []string{"inability to delete resources is likely an issue with Kubernetes itself"}, err @@ -212,7 +227,7 @@ func (s *deleteImagePullersState) Run(ctx context.Context, vsm *validationStateM /* * > Get web server info - * -- next state --> Start clients + * -- next state --> Start host checkers */ type getWebServerInfoState struct { ImagePullPodsPerNodeType perNodeTypeCount @@ -240,8 +255,8 @@ func (s *getWebServerInfoState) Run(ctx context.Context, vsm *validationStateMac if err != nil { return suggestions, err } - vsm.vt.Logger.Infof("starting clients on each node") - vsm.SetNextState(&startClientsState{ + vsm.vt.Logger.Infof("starting host checkers on each node") + vsm.SetNextState(&startHostCheckersState{ WebServerInfo: info, ImagePullPodsPerNodeType: s.ImagePullPodsPerNodeType, }) @@ -249,8 +264,112 @@ func (s *getWebServerInfoState) Run(ctx context.Context, vsm *validationStateMac } /* - * Start clients - * -- next state --> Verify all client pods are running + * > Start host checkers + * -- next state --> Verify all host checker pods are running + */ +type startHostCheckersState struct { + WebServerInfo podNetworkInfo + ImagePullPodsPerNodeType perNodeTypeCount +} + +func (s *startHostCheckersState) Run(ctx context.Context, vsm *validationStateMachine) (suggestions []string, err error) { + if vsm.vt.PublicNetwork == "" { + vsm.vt.Logger.Infof("not starting host checkers because public network is not specified") + vsm.SetNextState(&startClientsState{ + WebServerInfo: s.WebServerInfo, + ImagePullPodsPerNodeType: s.ImagePullPodsPerNodeType, + }) + return []string{}, nil + } + + err = vsm.vt.startHostCheckers(ctx, vsm.resourceOwnerRefs, s.WebServerInfo.publicAddr) + if err != nil { + err = fmt.Errorf("failed to start host checkers: %w", err) + vsm.Exit() // this is a whole validation test failure if we can't start host checkers + return []string{}, err + } + + // we expect only one host checker pod per host, which is the same as the image pullers, so we + // can use that as our expectation + vsm.vt.Logger.Infof("verifying host checker pods begin 'Running': count per node type: %v", s.ImagePullPodsPerNodeType) + vsm.SetNextState(&verifyAllPodsRunningState{ + AppType: hostCheckerDaemonsetAppType, + ImagePullPodsPerNodeType: s.ImagePullPodsPerNodeType, + ExpectedNumPods: s.ImagePullPodsPerNodeType.Total(), + WebServerInfo: &s.WebServerInfo, + }) + return []string{}, nil +} + +/* + * > Verify all host checker pods are "Ready" + * -- next state --> Delete host checkers + */ +type verifyAllHostCheckersReadyState struct { + WebServerInfo podNetworkInfo + ImagePullPodsPerNodeType perNodeTypeCount +} + +func (s *verifyAllHostCheckersReadyState) Run(ctx context.Context, vsm *validationStateMachine) (suggestions []string, err error) { + totalExpected := s.ImagePullPodsPerNodeType.Total() + + numReady, err := vsm.vt.numPodsReadyWithLabel(ctx, hostCheckerAppLabel()) + hostSuggestions := []string{ + "the host may not have a route that directs traffic to the public network", + "the public Network Attachment Definition may not have a route that directs traffic to hosts", + "there may be a network firewall or security policy blocking inter-node traffic on multus networks", + } + if err != nil { + return hostSuggestions, err + } + + if numReady != totalExpected { + return hostSuggestions, fmt.Errorf("number of 'Ready' host checkers [%d] is not the number expected [%d]", numReady, totalExpected) + } + + vsm.vt.Logger.Infof("all %d host checkers are 'Ready'", totalExpected) + vsm.SetNextState(&deleteHostCheckersState{ + WebServerInfo: s.WebServerInfo, + ImagePullPodsPerNodeType: s.ImagePullPodsPerNodeType, + }) + return []string{}, nil +} + +/* + * > Delete host checkers + * < host check only == true > + * -- next state --> Exit / Done + * < host check only == false > + * -- next state --> Start clients + */ +type deleteHostCheckersState struct { + WebServerInfo podNetworkInfo + ImagePullPodsPerNodeType perNodeTypeCount +} + +func (s *deleteHostCheckersState) Run(ctx context.Context, vsm *validationStateMachine) (suggestions []string, err error) { + err = vsm.vt.deleteDaemonsetsWithLabel(ctx, hostCheckerAppLabel()) + if err != nil { + // erroring here is not strictly necessary but does indicate a k8s issue that probably affects future test steps + return []string{"inability to delete resources is likely an issue with Kubernetes itself"}, err + } + + if vsm.vt.HostCheckOnly { + vsm.vt.Logger.Infof("done checking hosts in hostCheckOnly mode; exiting") + vsm.Exit() + return []string{}, nil + } + + vsm.SetNextState(&startClientsState{ + WebServerInfo: s.WebServerInfo, + ImagePullPodsPerNodeType: s.ImagePullPodsPerNodeType, + }) + return []string{}, nil +} + +/* + * > Start clients + * -- next state --> Verify all client pods are running */ type startClientsState struct { WebServerInfo podNetworkInfo @@ -258,6 +377,8 @@ type startClientsState struct { } func (s *startClientsState) Run(ctx context.Context, vsm *validationStateMachine) (suggestions []string, err error) { + vsm.vt.Logger.Infof("starting clients on each node") + podsPerNodeType := perNodeTypeCount{} for nodeType := range vsm.vt.NodeTypes { numClientDaemonsetsStarted, err := vsm.vt.startClients(ctx, vsm.resourceOwnerRefs, s.WebServerInfo.publicAddr, s.WebServerInfo.clusterAddr, nodeType) @@ -277,6 +398,7 @@ func (s *startClientsState) Run(ctx context.Context, vsm *validationStateMachine AppType: clientDaemonSetAppType, ImagePullPodsPerNodeType: s.ImagePullPodsPerNodeType, ExpectedNumPods: podsPerNodeType.Total(), + WebServerInfo: &s.WebServerInfo, }) return []string{}, nil } @@ -295,7 +417,7 @@ type verifyAllClientsReadyState struct { } func (s *verifyAllClientsReadyState) Run(ctx context.Context, vsm *validationStateMachine) (suggestions []string, err error) { - numReady, err := vsm.vt.numClientsReady(ctx, s.ExpectedNumClients) + numReady, err := vsm.vt.numPodsReadyWithLabel(ctx, clientAppLabel()) collocationSuggestion := "if clients on the same node as the web server become ready but not others, " + "there may be a network firewall or security policy blocking inter-node traffic on multus networks" defaultSuggestions := append([]string{collocationSuggestion, flakyNetworkSuggestion}, unableToProvideAddressSuggestions...) @@ -360,6 +482,11 @@ func (vt *ValidationTest) Run(ctx context.Context) (*ValidationTestResults, erro suggestedDebugging: []string{}, } + if vt.PublicNetwork == "" && vt.HostCheckOnly { + vt.Logger.Infof("hostCheckOnly is set, and there is no public network; no host prerequisites are needed, so host check is successful") + return testResults, nil + } + // configmap's purpose is to serve as the owner resource object for all other test resources. // this allows users to clean up a botched test easily just by deleting this configmap owningConfigMap, err := vt.createOwningConfigMap(ctx) diff --git a/tests/scripts/multus/default-public-cluster-nads.yaml b/tests/scripts/multus/default-public-cluster-nads.yaml index bd8e96b51..28ccd184a 100644 --- a/tests/scripts/multus/default-public-cluster-nads.yaml +++ b/tests/scripts/multus/default-public-cluster-nads.yaml @@ -7,7 +7,20 @@ metadata: labels: annotations: spec: - config: '{ "cniVersion": "0.3.1", "type": "macvlan", "master": "eth0", "mode": "bridge", "ipam": { "type": "whereabouts", "range": "192.168.20.0/24" } }' + config: | + { + "cniVersion": "0.3.1", + "type": "macvlan", + "master": "eth0", + "mode": "bridge", + "ipam": { + "type": "whereabouts", + "range": "192.168.20.0/24", + "routes": [ + {"dst": "192.168.29.0/24"} + ] + } + } --- apiVersion: k8s.cni.cncf.io/v1 kind: NetworkAttachmentDefinition @@ -17,4 +30,14 @@ metadata: labels: annotations: spec: - config: '{ "cniVersion": "0.3.1", "type": "macvlan", "master": "eth0", "mode": "bridge", "ipam": { "type": "whereabouts", "range": "fc00::/96" } }' + config: | + { + "cniVersion": "0.3.1", + "type": "macvlan", + "master": "eth0", + "mode": "bridge", + "ipam": { + "type": "whereabouts", + "range": "fc00::/96" + } + } diff --git a/tests/scripts/multus/host-cfg-ds.yaml b/tests/scripts/multus/host-cfg-ds.yaml new file mode 100644 index 000000000..ca95d4f66 --- /dev/null +++ b/tests/scripts/multus/host-cfg-ds.yaml @@ -0,0 +1,68 @@ +#################################################################################################### +# this daemonset configures each minikube or KinD node to route to the multus public net +# it is not suitable for production +#################################################################################################### +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: host-net-config + labels: + app: host-net-config +spec: + selector: + matchLabels: + app: host-net-config + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 100 # allow updating all at once + template: + metadata: + labels: + app: host-net-config + spec: + hostNetwork: true + tolerations: + # also run on control plane nodes for KinD testing + - key: "node-role.kubernetes.io/control-plane" + operator: "Exists" + terminationGracePeriodSeconds: 0 # allow updating/deleting immediately + containers: + - name: test + image: quay.io/ceph/ceph:v18 + env: + - name: IFACE_NAME + value: eth0 # IFACE_NAME + command: + - bash + - -x + - -c + args: + - | + IFACE='$(IFACE_NAME)' + + NODE_PUBLIC_NET_IP_FIRST3='192.168.29' + NET_ATT_DEF_PUBLIC_NET_CIDR='192.168.20.0/24' + + # get the last part of the interface's IP addr + ip -4 addr show $IFACE + ip_cidr="$(ip -4 addr show $IFACE | grep inet | awk '{print $2}')" # e.g., 192.168.100.3/24 + ip="${ip_cidr%/*}" # e.g., 192.168.100.3 + last="${ip##*.}" # e.g., 3 + + # add a shim to connect IFACE to the macvlan public network, with a static IP + # avoid IP conflicts by re-using the last part of the existing IFACE IP + ip link add public-shim link ${IFACE} type macvlan mode bridge + ip addr add ${NODE_PUBLIC_NET_IP_FIRST3}.${last}/24 dev public-shim + ip link set public-shim up + ip route add ${NET_ATT_DEF_PUBLIC_NET_CIDR} dev public-shim + + ip addr show $IFACE + ip addr show public-shim + ip route show + + sleep infinity + resources: {} + securityContext: + capabilities: + add: ["NET_ADMIN"]