554 Commits
v3.3 ... v4.1.2

Author SHA1 Message Date
Doug Smith
adfb270991 Merge pull request #1341 from dougbtv/net-attach-def-client-v174
Updates net-attach-def client library to v1.7.4
2024-10-01 09:36:43 -04:00
dougbtv
b171bb702b Updates net-attach-def client library to v1.7.4
Which improves backwards compatibility for network-status in latest updates to the client library, especially related to Calico.

See also: https://github.com/k8snetworkplumbingwg/network-attachment-definition-client/pull/72
2024-09-30 15:57:48 -04:00
Doug Smith
f1e887e239 Merge pull request #1336 from dougbtv/net-attach-def-client-v173
Bumps net-attach-def client to v1.7.3
2024-09-13 12:03:57 -04:00
dougbtv
100766d1a4 Bumps net-attach-def client to v1.7.3
Previous version didn't account for accounts for the sandox interfaces when reporting the interfaces in the network-status annotation when calculating the default:true interface
2024-09-13 09:56:52 -04:00
Doug Smith
e074c2a56b Merge pull request #1335 from dougbtv/net-attach-def-client-v172
Bumps net-attach-def client library to v1.7.2
2024-09-12 13:35:46 -04:00
dougbtv
38d03eb816 Bumps net-attach-def client library to v1.7.2
This fixes the default:true for multiple interface returns from CNI for cluster default network, where all interfaces in that return were marked as default:true in the network-status
2024-09-12 11:25:26 -04:00
Doug Smith
b554c96160 Merge pull request #1334 from dougbtv/disable-dra-e2e-temporarily
Disabled DRA test temporarily
2024-09-12 10:55:16 -04:00
dougbtv
92ff1b1ee8 Disabled DRA test temporarily 2024-09-12 10:06:17 -04:00
Doug Smith
31e77aafab Merge pull request #1321 from ah8ad3/update-install-readme
Doc: change install from file to url in readme, how-to-use
2024-08-29 09:41:23 -04:00
Ahmad Zolfaghari
dec0607a94 doc: change install from file to url in readme, how-to-use
Signed-off-by: Ahmad Zolfaghari <ah8ad3@gmail.com>
2024-08-09 16:32:07 +03:30
Doug Smith
3c33f6f028 Merge pull request #1314 from dougbtv/client-lib-multiple-if-cni-result
Updates to use CreateNetworkStauses from net-attach-def client, bump to v1.7.1
2024-08-05 07:59:36 -04:00
dougbtv
a28d1e4693 [bump] Bumps net-attach-def client lib to v1.7.1 2024-08-01 13:35:34 -04:00
Doug Smith
b9019016d7 Merge pull request #1317 from adrianchiris/pr-1302-update
create multus kubeconfig for in case of non auto flag.
2024-08-01 13:29:00 -04:00
abasitt
ca21ef66d1 create multus kubeconfig for incase of non auto flag. 2024-08-01 18:25:28 +03:00
Doug Smith
b11ea828e9 Merge pull request #1299 from adrianchiris/cleanup-multus-conf
Cleanup multus conf on exit
2024-08-01 09:37:25 -04:00
Doug Smith
fd9736b527 Merge pull request #1297 from sfackler/thick-arm
Build multiarch thick images
2024-08-01 09:35:58 -04:00
adrianc
6ade0ce262 update how-to-use doc
Signed-off-by: adrianc <adrianc@nvidia.com>
2024-08-01 16:18:55 +03:00
Doug Smith
f54693f501 Merge pull request #1313 from vasrem/chore/update-dra-e2e
Update DRA integration info and fix e2e test
2024-07-25 16:28:32 -04:00
dougbtv
bc6c8d5c76 Updates to use CreateNetworkStauses from net-attach-def client for multiple interfaces in CNI results 2024-07-25 16:15:50 -04:00
Vasilis Remmas
04fb8190fe Update DRA integration info and e2e test
Signed-off-by: Vasilis Remmas <vremmas@nvidia.com>
2024-07-24 09:34:53 +02:00
adrianc
004f1e6a12 delete multus conf file generated by thin_entrypoint
- if cleanup-config-on-exit is set delete generated multus
  config file on exit.

- add an option to skip watch for master cni config and kubeconfig
  as cleanup-config-on-exit with multus-conf-file=auto also triggered
  the watch for cases when deletion of multus config is desired but watch isnt

- setup signal handling to allow config file cleanup on exit

Signed-off-by: adrianc <adrianc@nvidia.com>
2024-07-18 18:09:23 +03:00
adrianc
334fdce751 Add signals package
this provides a simple way to handle incoming
os signas using context

Signed-off-by: adrianc <adrianc@nvidia.com>
2024-07-18 18:09:22 +03:00
Doug Smith
8587734174 Merge pull request #1305 from alrokayan/patch-1
Update how-to-use.md
2024-07-18 10:15:49 -04:00
Mohammed Alrokayan
9b4a0ce9a6 Update how-to-use.md
typo KUBERNETES_SERVICE_PROTOCOL
2024-06-30 15:20:10 +03:00
Steven Fackler
cd81346c1a Add a note about multi-arch support 2024-06-25 11:39:21 -04:00
Doug Smith
41013e7580 Merge pull request #1300 from adrianchiris/fix-mount-prop-var-lib-kubelet
Add mountPropagation to host-var-lib-kubelet
2024-06-20 09:50:47 -04:00
adrianc
849a3cd453 Add mountPropagation to host-var-lib-kubelet
This is needed to avoid issues with volume unmounts
when (other) pods exit as by default kubernetes mounts
as private.

Signed-off-by: adrianc <adrianc@nvidia.com>
2024-06-18 16:25:18 +03:00
Steven Fackler
572e4e05e3 Build multiarch thick images 2024-06-12 12:46:29 -04:00
Doug Smith
aff99fccc5 Merge pull request #1284 from ader1990/patch-1
arm64: build image for arm v8
2024-06-06 09:57:43 -04:00
Doug Smith
4757be12ac Merge pull request #1286 from s1061123/fix-type-scope-comment
Not exposed APIReadyCheckFunc to outside of package
2024-06-06 09:55:42 -04:00
Tomofumi Hayashi
d23856b784 Not exposed APIReadyCheckFunc to outside of package
APIReadyCheckFunc is used only in api, hence it can be decapitalize
to make its scope only in this package. This fix changes its scope.
In addition, api.APIReadyCheckFunc seems to be redundant so the name
is changed. Change the comment to fit to golang style, too.
2024-05-25 01:40:12 +09:00
Doug Smith
9f5c0239a8 Merge pull request #1078 from moshe010/dra
add support for Dynamic Resource Allocation
2024-05-23 11:06:17 -04:00
Doug Smith
d9f1c7c6e7 Merge pull request #1243 from adrianchiris/allow_undersocre_in_ifname
Change Validation of interface name
2024-05-23 09:43:12 -04:00
Adrian Vladu
bb47b55999 arm64: build image for arm v8
Fixes: https://github.com/k8snetworkplumbingwg/multus-cni/issues/1281

Signed-off-by: Adrian Vladu <avladu@cloudbasesolutions.com>
2024-05-17 16:59:50 +03:00
Tomofumi Hayashi
75c0245020 Merge pull request #1279 from dougbtv/skip-api-ready-on-cni-del
Thick plugin should not wait for API readiness on CNI DEL
2024-05-15 22:50:50 +09:00
dougbtv
181f56f026 Thick plugin should not wait for API readiness on CNI DEL
This modifies the behavior on CNI DEL for the thick plugin to just check once for API readiness, as opposed to waiting.
2024-05-14 11:23:47 -04:00
Vasilis Remmas
c9d411c2c2 Add warning in docs that DRA is alpha and in preview
Signed-off-by: Vasilis Remmas <vremmas@nvidia.com>
2024-05-13 13:49:59 +02:00
Tomofumi Hayashi
5a2597b329 Merge pull request #1270 from ordovicia/thin-master-cni-file-flag
thin plugin: Handle `--multus-master-cni-file-name` flag
2024-05-10 01:12:15 +09:00
Doug Smith
c6a371b6bc Merge pull request #1274 from s1061123/fix/gateway-nil
Fix CNI cache update function to prevent nil access
2024-05-09 23:22:23 +09:00
Tomofumi Hayashi
5fe124932a Fix CNI cache update function to prevent nil access
deleteDefaultGWResult() may create 'routes:null' in CNI cache file
and it causes nil pointer access at addDefaultGWCacheBytes().
This code change prevents deleteDefaultGWResult() to generate
'routes:null' in cache file.
2024-05-09 04:03:00 +09:00
Tomofumi Hayashi
4457289d1d Merge pull request #1272 from s1061123/fix-readiness
Fix defaultnetworkfile in unit test
2024-05-02 02:39:17 +09:00
Tomofumi Hayashi
541a8032c3 Fix defaultnetworkfile in unit test
rename conf param, 'defaultnetworkfile' to 'readinessindicatorfile'
2024-05-02 02:30:26 +09:00
Tomofumi Hayashi
89188023ef Merge pull request #1266 from k8snetworkplumbingwg/dependabot/go_modules/golang.org/x/net-0.23.0
Bump golang.org/x/net from 0.17.0 to 0.23.0
2024-05-01 15:29:20 +09:00
Hidehito Yabuuchi
633985d82f thin plugin: Handle --multus-master-cni-file-name flag
Multus v3.9.3 has `--multus-master-cni-file-name` flag to specify the
name of a primary CNI config file.
https://github.com/k8snetworkplumbingwg/multus-cni/blob/v3.9.3/images/entrypoint.sh#L22

In Multus v4.0.2, the thin plugin has the flag defined, but it is not
read and so does not have effect.

This pull request fixes the problem by making the thin plugin correctly
handles `--multus-master-cni-file-name` flag.

Fixes #1226

Signed-off-by: Hidehito Yabuuchi <hyab@preferred.jp>
2024-04-25 18:31:54 +09:00
dependabot[bot]
5a407e1a21 Bump golang.org/x/net from 0.17.0 to 0.23.0
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.17.0 to 0.23.0.
- [Commits](https://github.com/golang/net/compare/v0.17.0...v0.23.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-19 12:20:28 +00:00
Doug Smith
9c2771b842 Merge pull request #1250 from SchSeba/support_mtu
Bump cni and network-attachment-definition-client to support MTU
2024-04-17 10:17:13 -04:00
Tomofumi Hayashi
897cb1a759 Merge pull request #1261 from dougbtv/deads_upstreampick_fallback
Enforce termination message policy on all platform pods
2024-04-17 03:37:44 +09:00
David Eads
e214154f5f OCPBUGS-28230: enforce termination message policy on all platform pods 2024-04-16 14:08:55 -04:00
Vasilis Remmas
2c796b5956 Add DRA Integration E2E test
Signed-off-by: Vasilis Remmas <vremmas@nvidia.com>
2024-04-11 19:53:00 +02:00
Moshe Levi
202533cf1d support for Dynamic Resource Allocation doc update
Signed-off-by: Moshe Levi <moshele@nvidia.com>
2024-04-11 19:16:46 +02:00
Moshe Levi
40378cabd3 add support for Dynamic Resource Allocation
Signed-off-by: Moshe Levi <moshele@nvidia.com>
2024-04-11 19:16:46 +02:00
Sebastian Sch
30d6aa06e5 Bump cni and network-attachment-definition-client
This is to support the new MTU field in cni network results

Signed-off-by: Sebastian Sch <sebassch@gmail.com>
2024-04-11 17:28:29 +03:00
Tomofumi Hayashi
b6206a0dbf Merge pull request #1242 from k8snetworkplumbingwg/dependabot/go_modules/google.golang.org/protobuf-1.33.0
Bump google.golang.org/protobuf from 1.31.0 to 1.33.0
2024-04-02 15:01:08 +09:00
adrianc
d625d48231 Change Validation of interface name
interface name should not be limited to DNS-1123 label format.
instead validate interface name if provided in pod network annotation
in a similar manner as iproute2[1].

this will allow to request interface names such as: "uplink_p0"

[1]11740815bf/lib/utils.c (L832)

Signed-off-by: adrianc <adrianc@nvidia.com>
2024-03-14 18:05:57 +02:00
Tomofumi Hayashi
0fd3fa7919 Fix typo 2024-03-14 23:16:06 +09:00
Doug Smith
ad81dbf50f Merge pull request #1236 from igsilya/failure-logs
server: More concise error messages.
2024-03-14 10:03:51 -04:00
dependabot[bot]
7ad0dd287a Bump google.golang.org/protobuf from 1.31.0 to 1.33.0
Bumps google.golang.org/protobuf from 1.31.0 to 1.33.0.

---
updated-dependencies:
- dependency-name: google.golang.org/protobuf
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-13 23:19:51 +00:00
Tomofumi Hayashi
b09350cf1a Merge pull request #1086 from mengzhuo/master
Delete .travis.yaml
2024-03-01 00:12:11 +09:00
Ilya Maximets
ddc78f1244 server: More concise error messages.
On the CNI request failure, multus-cni prints out cmdArgs.  In all
cases, except for debug printing, this is done with %s and a special
printing function.  However, the handleCNIRequest is an exception for
some reason.  That leads to unintelligible error messages in case
of CNI request failures (severely abridged):

 CmdAdd (shim): CNI request failed with status 400:
 '&{ContainerID:<id> Netns:/var/run/netns/<uuid> IfName:eth0
    Args:<args> Path: StdinData:[125 121 111 117 114 32 97 100 118
    101 114 116 105 115 101 109 101 110 116 32 99 111 117 108 100
    32 98 101 32 104 101 114 101 125 ... another 650 numbers ]}
 ContainerID:"<id>" Netns:"/var/run/netns/<uuid>" IfName:"eth0"
 Args:"<args>" Path:"" ERRORED: error configuring pod ...

printCmdArgs() should be used for this case as well to avoid huge
hardly readable logs.

At the same time, the content of cniCmdArgs is always appended to
the error twice as seen in the example above.  The first time by the
HandleCNIRequest and another time by the handleCNIRequest.  Same for
the HandleDelegateRequest path.

Just removing the prefixing from the lower level handlers while
keeping higher level ones.  The 'ERRORED' part migrated to the higher
level handler functions to preserve the overall look of the error.

Signed-off-by: Ilya Maximets <i.maximets@ovn.org>
2024-02-29 00:38:07 +01:00
Tomofumi Hayashi
5f0b4cdc6b Merge pull request #1235 from dougbtv/remove-readiness-check-on-del
Skips checking for readiness on CNI DEL
2024-02-22 23:55:21 +09:00
dougbtv
a1915e1a8e Skips checking for readiness on CNI DEL (and instead warns)
Because deletes should favor a successful path, the readiness check should be skipped for pod removals.

This can cause an issue where there's pods pending deletes and that might impact scheduling of a pod that may be necessary in order to set the readiness indicator.

Adds a new method  to check for readiness indicator alone in order to immediately log a warning.
2024-02-22 09:15:11 -05:00
Patryk Matuszak
53a68c35ff Recreate configs only if base files changed (#1234) 2024-02-21 02:24:15 +09:00
Doug Smith
ca5a4c9aa9 Merge pull request #1230 from s1061123/update-kind
Update kind e2e
2024-02-15 13:25:27 -05:00
Tomofumi Hayashi
03fcb34abe Update kind e2e 2024-02-16 02:30:17 +09:00
Doug Smith
ba18cf5ab3 Merge pull request #1214 from s1061123/add-netdef-informer
Add net-attach-def informer for thick plugin
2024-02-15 09:40:57 -05:00
Doug Smith
b271fbf84d Merge pull request #1229 from s1061123/fix/filepath
Add filepath sanity check
2024-02-14 10:48:12 -05:00
Tomofumi Hayashi
748930239d Add filepath sanity check 2024-02-15 00:29:07 +09:00
Doug Smith
c550826675 Merge pull request #1228 from s1061123/fix/reload-kubeconfig-if-failed
Reload bootstrap kubeconfig if cert mgr failed to load valid certs
2024-02-13 10:49:49 -05:00
Tomofumi Hayashi
a337317533 Reload bootstrap kubeconfig if cert mgr failed to load valid certs
When user recreate whole cluster certs, multus thick plugin's
previous cert is no longer valid. In such case, we need to prevent
to use cert manager's old certs and restart it from bootstrap
kubeconfig. This fix reloads client config from bootstrap
kubeconfig if cert mgr's cert is failed to load pod.
2024-02-14 00:46:12 +09:00
Tomofumi Hayashi
8e5060b9a7 Opt out to mount service account token (#1219) 2024-02-01 17:33:59 +09:00
Dennis Periquet
6c982f3fee supplement log with stringified version of StdinData to enhance debug (#1215) 2024-01-26 01:30:58 +09:00
Doug Smith
1071115e90 Merge pull request #1217 from s1061123/add-sleep-thin
Add additional sleep in thick entrypoint
2024-01-25 11:10:57 -05:00
Tomofumi Hayashi
493d421cf7 Update github actions (#1216) 2024-01-26 00:46:09 +09:00
Tomofumi Hayashi
24b2d55c84 Add additional sleep in thick entrypoint 2024-01-26 00:45:47 +09:00
Tomofumi Hayashi
6812ce0ed6 Update e2e related tools (#1212) 2024-01-24 22:39:54 +09:00
Tomofumi Hayashi
6ac6fe675f Add net-attach-def informer for thick plugin
This change introduces net-attach-def informer in multus-daemon,
thick pluign case. It could reduced API calls to get
net-attach-def.
2024-01-20 02:04:21 +09:00
Fish-pro
3477c9c827 fix(quick start)-You do not need to clone the repository and directly deliver the installation file (#1210)
Signed-off-by: Zechun Chen <zechun.chen@daocloud.io>
2024-01-18 23:45:57 +09:00
Lionel Jouin
36ba3039ae Add watch permission to thick e2e template (#1208)
As described in #1171, the watch function is required in the clusterrole
for the thick Multus version, otherwise "Failed to watch *v1.Pod" would
be returned.
2024-01-18 23:45:40 +09:00
Tomofumi Hayashi
40687759fb Reduce informer memory usage by informer transform (#1203)
This fix reduces multus-daemon memory usage with k8s 0.29 informer
transform to trim unnecessary Pod object information to multus.
2024-01-18 23:32:21 +09:00
Tomofumi Hayashi
a70da3556a Fix a wait to account for the possiblity of a not ready unix socket (#1207) 2024-01-11 13:34:37 +09:00
Doug Smith
003fbd5785 Merge pull request #1202 from s1061123/add-timeout
Add timeout
2024-01-05 08:04:02 -05:00
Tomofumi Hayashi
6e4f62f2f2 disable revive's dot-imports in unit test files 2024-01-05 14:32:09 +09:00
Tomofumi Hayashi
197877d113 Adds a wait to account for the possiblity of a not ready unix socket 2024-01-05 14:27:31 +09:00
Doug Smith
ab7d64e96f Refactors the configuration options document reference (#1180) 2024-01-04 23:54:56 +09:00
dependabot[bot]
acfbd42719 Bump google.golang.org/grpc from 1.53.0 to 1.56.3 (#1182)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.53.0 to 1.56.3.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.53.0...v1.56.3)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-11 14:48:54 +09:00
Doug Smith
c76db9c7a0 Merge pull request #1194 from s1061123/fix-logging
Fix to use lumberjack only for logging files
2023-12-07 09:14:30 -05:00
Tomofumi Hayashi
540a887651 Fix to use lumberjack only for logging files 2023-12-07 21:08:17 +09:00
Tomofumi Hayashi
d97514f841 Ignore dot-imports error message only for go test files 2023-12-07 20:56:36 +09:00
Moshe Levi
e4404b2645 fix e2e test ModuleNotFoundError: No module named 'pkg_resources' (#1189)
Signed-off-by: Moshe Levi <moshele@nvidia.com>
Signed-off-by: Tomofumi Hayashi <tohayash@redhat.com>
2023-12-07 20:51:02 +09:00
Jonatan
a373a2286d Deployments: Add watch permission to thick example (#1171)
The ClusterRole was missing the watch permission on pods, which resulted in Multus throwing this error message every few seconds:

Failed to watch *v1.Pod: unknown (get pods)
2023-12-04 20:28:18 +09:00
dependabot[bot]
e2e8cfb677 Bump golang.org/x/net from 0.8.0 to 0.17.0 (#1176)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.8.0 to 0.17.0.
- [Commits](https://github.com/golang/net/compare/v0.8.0...v0.17.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-17 14:21:43 +09:00
Doug Smith
b710020f7b Merge pull request #1173 from s1061123/remove-status-set-del
Suppress status unset in cmdDel
2023-10-04 11:50:16 -04:00
Tomofumi Hayashi
46fe38e2c5 Suppress status unset in cmdDel
This change stops to update status in CNI's DEL command.
There are two reasons:

1. cmd DEL is invoked at only pod deletion, hence k8s does not
guarantee the pod and it may be already deleted. Hence this
API may failed.

2. In stateful set's pod recreation case, it may have race
condition to update the status at cmd DEL case.
In stateful set case, same pod name, i.e. stateful-0, is deleted
and then created again. In this case, if old Pod's CNI DEL command
is not finished before new Pod's creation, then SetStatus function
is failed due to pod UID mismatch.
2023-10-04 23:28:26 +09:00
Doug Smith
d7e391e006 Merge pull request #1167 from s1061123/fix-params
Per node certificates: Add duration parameter
2023-09-26 14:14:03 -04:00
Tomofumi Hayashi
6a0c905347 Fix per node cert feature
This change introduces certDuration as parameter to customize
cert duration. In addition, environment variable for node name
is matched to other usages.
2023-09-27 00:54:32 +09:00
Peng Liu
4d69fed8ad Fix incorrect mount volume name in the thick plugin manifest (#1166)
Signed-off-by: Peng Liu <pliu@redhat.com>
2023-09-25 22:31:02 +09:00
Peng Liu
1dd4edded2 Move chroot from multus main process to its child processes (#1161)
We used to run chroot in multus main process when calling other CNI
plugin binary. We also use a mutex to lock the access to pod files.
But this causes performance issues when facing heavy
CNI_ADD/CNI_DEL requests.

With this patch, we do chroot in the child processes instead. So
file operations in the main process will not be affected by chroot.

This change requires the multus thick plugin pod to mount CNI bin
directory to the same path in the container host.

Signed-off-by: Peng Liu <pliu@redhat.com>
2023-09-22 17:08:57 +09:00
Doug Smith
857d070679 Merge pull request #1159 from s1061123/per-node-cert
Add per-node-certification support
2023-09-18 12:16:03 -04:00
Tomofumi Hayashi
e5d19fff6b Add per-node-certification support
This change introduces per-node certification for multus pods.
Once multus pod is launched, then specified bootstrap kubeconfig
is used for initial access, then multus sends CSR request to
kube API to get original certs for kube API access. Once it is
accepted then the multus pod uses generated certs for kube access.
2023-09-19 00:38:29 +09:00
Doug Smith
acfdc64991 Merge pull request #1158 from s1061123/bump-ver
Bump golang and k8s API version
2023-09-17 13:18:16 -04:00
Tomofumi Hayashi
f8afd78120 Bump golang and k8s API version 2023-09-18 01:40:44 +09:00
Doug Smith
ddb977f4b9 Merge pull request #1154 from dcbw/shared-informer
Performance and efficiency improvements in daemon/server mode
2023-09-15 09:56:52 -04:00
Dan Williams
d9c06e99d1 server: don't set CNI config readinessindicatorfile when using ConfigManager
For whatever reason calling os.Stat() on the readiness indicator file
from CmdAdd()/CmdDel() when multus is running in server mode and is
containerized often returns "file not found", which triggers the
polling behavior of GetReadinessIndicatorFile(). This greatly delays
CNI operations that should be pretty quick. Even if an exponential
backoff is used, os.Stat() can still return "file not found"
multiple times, even though the file clearly exists.

But it turns out we don't need to check the readiness file in server
mode when running with MultusConfigFile == "auto". In this mode the
server starts the ConfigManager which (a) waits until the file exists
and (b) fsnotify watches the readiness and (c) exits the daemon
immediately if the file is deleted or moved.

This means we can assume that while the daemon is running and the
server is handling CNI requests that the readiness file exists;
otherwise the daemon would have exited. Thus CmdAdd/CmdDel don't
need to run a lot of possibly failing os.Stat() calls in the CNI
hot paths.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-14 08:58:19 -05:00
Dan Williams
b0df7dd5e3 server/config: use filepath.Join()
Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-14 08:58:19 -05:00
Dan Williams
fb4f4aa4c1 server/config: un-export some functions no longer used outside the module
Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-14 08:58:19 -05:00
Dan Williams
c2add82b93 server/config: fix MonitorPluginConfiguration test
The test was comparing the same configuration to itself, since
nothing in the changed CNI configuration is used in the written
multus configuration.

Instead make sure the updated CNI config contains something
that will be reflected in the written multus configuration,
and while we're there use a more robust way to wait for the
config to be written via gomega.Eventually().

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-14 08:58:19 -05:00
Dan Williams
8539a476fd server/config: consolidate ConfigManager start and fsnotify watching
Simplify setup by moving the post-creation operations like
GenerateConfig() and PersistMultusConfig() into a new Start() function
that also begins watching the configuration directory. This better
encapsulates the manager functionality in the object.

We can also get rid of the done channel passed to the config
manager and just use the existing WaitGroup to determine when to
exit the daemon main().

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-14 08:58:19 -05:00
Dan Williams
4ade85669b server/config: simplify ConfigManager creation
A couple of the setup variables for NewManager*() are already in the
multus config that it gets passed, so use those instead of passing
explicitly.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-14 08:58:19 -05:00
Dan Williams
50c0357467 server: use a shared informer pod cache rather than direct apiserver access
When running in server mode we can use a shared informer to listen for
Pod events from the apiserver, and grab pod info from that cache rather
than doing direct apiserver requests each time.

This reduces apiserver load and retry latency, since multus can poll
the local cache more frequently than it should do direct apiserver
requests.

Oddly static pods don't show up in the informer by the timeout and
require a direct apiserver request. Since static pods are not common
and are typically long-running, it should not be a big issue to
fall back to direct apiserver access for them.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-14 08:57:12 -05:00
Dan Williams
cec1a53cd8 server: simplify server start
Move server start code to a common function that both regular
and test code can use. Also shut down the server from the
testcases.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-13 07:54:41 -05:00
Dan Williams
1605ffcad5 daemon: remove unused done channel
Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-13 07:54:41 -05:00
Dan Williams
7c68481e43 vendor: add client-go and more apimachinery modules
We'll need these for the next commit.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-13 07:54:41 -05:00
Dan Williams
6b8d24c1ef server: make CmdAdd/Del/Check struct member functions
Then we can just use the Server struct kube client and exec rather
than passing them through the function parameters.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-13 07:54:41 -05:00
Dan Williams
752f28c2bc k8sclient: bump QPS to 50
Multus is a pretty critical piece of infrastructure, so it shouldn't
be subject to the same lower QPS limits as most components are.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-13 07:54:41 -05:00
Dan Williams
fff8519517 k8sclient: make InClusterK8sClient() call GetK8sClient()
We want the in-cluster client that the multus server uses to use
the same client config (QPS, protobuf, grpc, etc) as the regular
client.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-13 07:54:41 -05:00
Dan Williams
02ce071abb github: export and upload e2e test kind logs (#1157)
When things go wrong the logs can help figure out why.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2023-09-13 21:51:58 +09:00
Doug Smith
7ea924b8f1 Merge pull request #1148 from s1061123/fix/1126
Add 'cniConfigDir' to specify config dir
2023-08-31 14:16:37 -04:00
Tomofumi Hayashi
f6afc79b47 Add 'cniConfigDir' to specify config dir
Fix #1126
2023-09-01 03:02:29 +09:00
Doug Smith
3a95111901 Merge pull request #1145 from s1061123/refine-build
Refine build script
2023-08-25 11:06:37 -04:00
Tomofumi Hayashi
4456e91b5c Refine build script 2023-08-24 01:52:15 +09:00
Doug Smith
c5a0002be4 Merge pull request #1142 from s1061123/fix/1130
fix multus config file generation to avoid self-delegation
2023-08-16 10:58:56 -04:00
Tomofumi Hayashi
159f2610c0 fix multus config file generation to avoid self-delegation
Check masterConfigPath file and skip if it is multus generated
files. Fix #1130
2023-08-16 21:00:26 +09:00
Doug Smith
8d8aa80cd5 Merge pull request #1101 from AlinaSecret/fix-race-condition
Fix race conditions in logging package functions and enable race detection in tests
2023-08-11 10:29:11 -04:00
Alina Sudakov
272b3ca8fa Fix race conditions in logging package functions
The logging package contains two functions, SetLogOptions and SetLogFile, that could experience race conditions when multiple goroutines access and modify the logger struct concurrently. 
To address these issues, a copy of the logger struct is now created in each function to eliminate data races.

In addition, the test-go.sh script is updated to include the '-race' flag, enabling race detection during testing. This change helps prevent future race conditions by activating the Go race detector.

Signed-off-by: Alina Sudakov <asudakov@redhat.com>
2023-08-10 13:17:19 +03:00
Tomofumi Hayashi
d5883bdbfa Fix multus-daemon quit process (#1133) 2023-08-04 01:16:37 +09:00
Doug Smith
46d446f0e5 Merge pull request #1131 from s1061123/thick-readiness
Support readinessIndicator file in thick multus-daemon
2023-08-01 10:11:18 -04:00
Tomofumi Hayashi
41d5d08686 Support readinessIndicator file in thick multus-daemon
This change supports readinessIndicatorfile in multus-daemon and
refines goroutine termination in case of signal with context.
2023-08-01 23:01:17 +09:00
Doug Smith
bf79dc3269 Merge pull request #1127 from s1061123/add-ready-check
This change introduces wait to generate config until API is ready
2023-07-24 09:54:21 -04:00
Tomofumi Hayashi
82324a7795 This change introduces wait to generate config until API is ready 2023-07-24 22:38:08 +09:00
dependabot[bot]
91a82a1264 Bump google.golang.org/grpc from 1.40.0 to 1.53.0 (#1120)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.40.0 to 1.53.0.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.40.0...v1.53.0)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-20 23:37:26 +09:00
Doug Smith
0bc8103654 Merge pull request #1125 from s1061123/refine-options
Refine and fix parameters
2023-07-20 09:39:05 -04:00
Tomofumi Hayashi
fa60329105 Refine and fix parameters
This changes refines parameters in multus thick/thin.
- delete unused parameter, confDir
- add multus-cni-conf-dir
- fix multusConfigPath in non-default params case
2023-07-20 21:22:54 +09:00
Doug Smith
99c4481e08 Merge pull request #1085 from s1061123/fix/fix-sliceindex
Fix potential issue, slice bounds out of range error
2023-06-29 10:07:42 -04:00
Doug Smith
f03765681f Merge pull request #1095 from s1061123/fix/plugin-without-interface
Fix multus to support CNI plugin which does not create interface
2023-05-18 13:51:56 -04:00
Tomofumi Hayashi
22304806c8 Fix multus to support CNI plugin which does not create interface
This change fixes multus to support CNI plugin which does not
create any interface and return empty result. Some CNI plugin
may do network configuration change only and does not create
any interface and return empty CNI result. Current multus assumes
that CNI config always creates some interfaces hence above CNI
plugin is out of assumption and multus may not work with such
plugins.
2023-05-18 02:40:27 +09:00
Meng Zhuo
649a4c5dd3 Delete .travis.yaml
#559 had already drop this file
2023-05-06 09:32:14 +08:00
Doug Smith
0c37bb043c Merge pull request #1084 from s1061123/fix/del-noerr
Suppress error message in cmdDel, in thick plugin
2023-05-02 14:54:41 -04:00
Tomofumi Hayashi
da704f8f63 Fix potential issue, slice bounds out of range error 2023-05-03 03:42:33 +09:00
Tomofumi Hayashi
5d64ec3367 Suppress error message in cmdDel, in thick plugin
This fix suppress error message in thick plugin's shim, for
DEL command, to align with CNI spec.

Fix #1080
2023-05-03 03:33:01 +09:00
Tomofumi Hayashi
b05ff2db4e Fix origin github action workflows 2023-05-03 03:32:32 +09:00
Doug Smith
b9acfeb6b7 Adds permanent slack invite (#1083) 2023-04-27 23:07:48 +09:00
Tomofumi Hayashi
77aac95dfc Fix github action 2023-04-15 02:07:39 +09:00
Tomofumi Hayashi
72945e3679 Add missing mutex lock for race condition fix (#1074) 2023-04-15 02:02:44 +09:00
Tomofumi Hayashi
1b01e3e486 Change gopkg.in to v4 for v4 release 2023-04-13 23:36:40 +09:00
Tomofumi Hayashi
fe14c17fe7 Refine dockerfile to use buildx multi-arch image for thin plugin (#1070) 2023-04-13 23:15:00 +09:00
Tomofumi Hayashi
66b0c5c371 Update goreleaser (#1069)
This change update goleleaser action and goreleaser config file
to release multus binaries, including multus-daemon and multus-shim
2023-04-13 22:43:30 +09:00
Tomofumi Hayashi
f3a371358a Update golang to 1.19 (#1067) 2023-04-13 22:42:32 +09:00
Tomofumi Hayashi
b4bea43f7e Cleanup code comment (#1068)
This change removes unnecessary comment.
2023-04-13 22:41:14 +09:00
Tomofumi Hayashi
7c22973f9f Add mutex lock for load confs in GetDefaultNetworks (#1073)
Thick server's chroot mutex is missing in GetDefaultNetworks,
that touch the pod filesystem. This change adds mutex lock there
and prevent race condition.

Fix #1072
2023-04-13 22:40:16 +09:00
Doug Smith
487c6fcec4 Merge pull request #1066 from s1061123/fix/thick-log-options
Refactoring thick daemon config processing
2023-04-10 09:40:00 -04:00
Tomofumi Hayashi
c279938e21 Refactoring thick daemon config processing
to damonset config file, hence command line option parsing is no
longer used. This change removes these parts.

Fix #1058.
2023-04-08 01:34:05 +09:00
Tomofumi Hayashi
855e8bee45 Add workaround patch for okd-builder.Dockerfile build failure (#1063)
Fix #1062
2023-04-07 00:30:11 +09:00
Tomofumi Hayashi
5bce250398 Fix linter warning message (#1057) 2023-04-07 00:20:04 +09:00
Miguel Duarte Barroso
1add898a3c Cni daemon config does not need shim socket path (#1059)
* config, daemon: shim socket path is not needed

The shim socket dir attribute is only required for the shim (cni
configuration). Thus, it can be removed from the daemon configuration.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* config, daemon: rename socket dir attribute

Now the socketDir parameter no longer stutters.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

---------

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2023-04-07 00:12:15 +09:00
Miguel Duarte Barroso
7ced7dd10c docs, thick plugin: align docs with new configuration reference (#1055)
* config, daemon: shim socket path is not needed

The shim socket dir attribute is only required for the shim (cni
configuration). Thus, it can be removed from the daemon configuration.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* config, daemon: rename socket dir attribute

Now the socketDir parameter no longer stutters.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* docs, thick plugin: align docs with new configuration reference

PR #1053 - [0] - changed the thick plugin configuration to happen
exclusively via the user provided config map. This PR aligns the multus
documentation with the existing code.

[0] - https://github.com/k8snetworkplumbingwg/multus-cni/pull/1053

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

---------

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2023-04-07 00:11:17 +09:00
Tomofumi Hayashi
21f84c0162 Remove 'cni-version' option in default deployment (#1061)
This change removes 'cni-version' option in entrypoint
from default deployment manifest. This change uses cniVersion of
delegate CNI, cluster network.
2023-04-05 21:24:03 +09:00
Doug Smith
7cf1c2f0c2 Merge pull request #1054 from s1061123/dev/distroless-thin
Change thin container base image to distroless
2023-04-03 14:41:22 -04:00
Tomofumi Hayashi
dcf92c8e94 Change thin container base image to distroless
This commit changes thin container base image to distroless
to simplify container image. It replace old shell script entrypoint
to golang implementation and implement multus installer (i.e. copy).
2023-04-03 15:44:52 +09:00
Miguel Duarte Barroso
6c2e09529b Improve v4 config (#1053)
* Draft for refine options

* config: remove command line args; use configMap/JSON config

The `socketDir` configuration was split in two, since the multus daemon,
and multus shim have the socket in different paths. This allows the user
to customize these paths.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* deployment, ci: update daemonset spec

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

---------

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
Co-authored-by: Tomofumi Hayashi <tohayash@redhat.com>
Co-authored-by: dougbtv <dosmith@redhat.com>
2023-03-30 22:58:03 +09:00
Doug Smith
c129e72779 Merge pull request #1044 from s1061123/dev/remove-old-conf
Remove old/obsolated config from repo
2023-03-02 09:41:44 -05:00
Tomofumi Hayashi
adf5e98b1b Remove old/obsolated config from repo
As of #1012 discussion, several conf file seems to be obsolated
and not updated to track the changes. This change removes these
obsolated files.
2023-03-02 22:33:51 +09:00
杨刚 (成都)
346a54ccd9 Cleanup : github.com/pkg/errors has been archived. (#1035)
Signed-off-by: yanggang <gang.yang@daocloud.io>
2023-02-21 00:39:06 +09:00
dependabot[bot]
6d97cf9071 Bump golang.org/x/net from 0.1.0 to 0.7.0 (#1039)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.1.0 to 0.7.0.
- [Release notes](https://github.com/golang/net/releases)
- [Commits](https://github.com/golang/net/compare/v0.1.0...v0.7.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-02-21 00:38:39 +09:00
杨刚 (成都)
3680725cb0 align case line . (#1033)
Signed-off-by: yanggang <gang.yang@daocloud.io>
2023-02-21 00:38:22 +09:00
Doug Smith
e6299693aa Merge pull request #1028 from s1061123/dev/remove-restart-crio
Remove deprecated 'restart-crio' option
2023-02-20 09:32:30 -05:00
杨刚 (成都)
43e2008107 code clean for if condtion (#1037)
Signed-off-by: yanggang <gang.yang@daocloud.io>
2023-02-14 01:41:51 +09:00
杨刚 (成都)
f5b64339bf clean wrong notes. (#1036)
Signed-off-by: yanggang <gang.yang@daocloud.io>
2023-02-14 01:41:19 +09:00
Tomofumi Hayashi
d1d0da1457 Remove deprecated 'restart-crio' option
'restart-crio' option was used for workaround crio issues.
This issue no longer exists, hence make it obsolate and removed.
2023-02-06 14:37:01 +09:00
Doug Smith
e692127d19 Readme updates, includes thick-plugin-by-default installation text (#1004) 2022-12-23 00:00:08 +09:00
Yury K
0ae7db9bbc Update network-attachment-definition-client to v1.4.0 (#984)
Update network-attachment-definition-client package
to support DeviceInfo spec 1.1.0

Signed-off-by: Yury Kulazhenkov <ykulazhenkov@nvidia.com>

Signed-off-by: Yury Kulazhenkov <ykulazhenkov@nvidia.com>
2022-12-22 23:55:40 +09:00
Doug Smith
95b45eff5d Updates config options and tests for socketfile and cniconfdir between thin/thick (#1002) 2022-12-20 02:37:34 +09:00
Doug Smith
b660d69e18 Merge pull request #998 from s1061123/dev/action-update
Update github action version
2022-12-15 11:17:45 -05:00
Doug Smith
873857273f Merge pull request #999 from s1061123/fix/warning
Fix warning message about package comment
2022-12-15 11:17:16 -05:00
Tomofumi Hayashi
442da10303 Update github action version 2022-12-16 01:10:41 +09:00
Tomofumi Hayashi
3ffa206abc Fix warning message about package comment 2022-12-16 00:43:01 +09:00
Doug Smith
971a110db7 Create an openshift origin (OKD) golang builder image in build pipeline (#992) 2022-12-14 22:50:20 +09:00
Doug Smith
d7a8f962da Merge pull request #969 from liornoy/ginkgov2
Bump ginkgo to v2
2022-12-13 13:26:03 -05:00
Doug Smith
36952b8401 Merge pull request #990 from s1061123/fix/remove-origin
Remove origin from CI build
2022-12-13 13:25:09 -05:00
Tomofumi Hayashi
0a0e9b4db9 Remove origin from CI build
This change remove origin build from CI pipeline because
origin's golang version is too old.
2022-12-14 03:02:55 +09:00
liornoy
7a549fd9ac Update tests source code to ginkgo v2
This commit updates the tests to import ginkgo v2.
2022-12-13 19:37:13 +02:00
liornoy
048438e0ef Bump ginkgo to v2
This commit bumps ginkgo to version v2.5.1.
2022-12-13 19:37:13 +02:00
Tomofumi Hayashi
344fb0ae09 Do 'go mod tidy' to cleanup go.mod/go.sum (#988) 2022-12-14 02:20:42 +09:00
Doug Smith
26902b29b6 Merge pull request #987 from s1061123/dev/go118
Bump go version to 1.18/1.19
2022-12-13 09:48:52 -05:00
Doug Smith
d84add88b9 Merge pull request #986 from s1061123/fix/so-long-gorilla
This removes gorilla/mux from multus
2022-12-13 09:44:04 -05:00
Tomofumi Hayashi
546e715c9e Bump go version to 1.18/1.19
Bump go version to 1.18/1.19, supported in golang community.
2022-12-13 23:30:30 +09:00
Tomofumi Hayashi
1454d912f4 This removes gorilla/mux from multus
This change removes gorilla/mux dependency from the multus-thick
because goriila team no longer support gorilla packages, including
gorilla/mux.
2022-12-13 17:35:34 +09:00
yulng
6eda6d9deb add check test result for interface net1 (#960)
Signed-off-by: yulng <wei.yang@daocloud.io>

Signed-off-by: yulng <wei.yang@daocloud.io>
2022-12-13 17:01:14 +09:00
Ayush Patel
33ce772b98 Add NOTICE (#967)
Signed-off-by: Ayush Patel <patel.ayush08@gmail.com>

Signed-off-by: Ayush Patel <patel.ayush08@gmail.com>
2022-12-08 23:50:37 +09:00
lgtm-com[bot]
b8304cf7dc Add CodeQL workflow for GitHub code scanning (#981)
Co-authored-by: LGTM Migrator <lgtm-migrator@users.noreply.github.com>
2022-12-08 23:47:00 +09:00
Doug Smith
7ce5e9fbdc Merge pull request #976 from s1061123/dev/simple-kubeletpkg
Simplify kubeletclient code to reduce parse url
2022-11-29 11:29:16 -05:00
Miguel Duarte Barroso
a9ace511d8 server: add healthz endpoint (#963)
From the node (or any privileged pod having mounted the multus socket)
you can now query the multus-cni server liveliness - for instance:

```
root@kind-worker:/# curl -v --unix-socket /run/multus/multus.sock localhost/healthz
*   Trying /run/multus/multus.sock:0...
* Connected to localhost (/host/run/multus/multus.sock) port 80 (#0)
> GET /healthz HTTP/1.1
> Host: localhost
> User-Agent: curl/7.74.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Mon, 14 Nov 2022 17:21:07 GMT
< Content-Length: 0
< Connection: close
<
* Closing connection 0
```

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2022-11-29 23:34:13 +09:00
Tomofumi Hayashi
6c52c476bf Simplify kubeletclient code to reduce parse url
This removes unused variables and simplify kubeletclient code.
2022-11-28 18:05:24 +09:00
Doug Smith
c75d773248 Merge pull request #957 from s1061123/fix/948
Change conditional flow to use cache file in CmdDel
2022-11-10 11:12:15 -05:00
Tomofumi Hayashi
82c09a98b7 Change conditional flow to use cache file in CmdDel
This fix changes conditional flow to use net-attach-def if
cache file is collapsed in CmdDel.

Fix #948
2022-11-11 00:22:15 +09:00
yanggang
103e70778b clean code (#952)
Signed-off-by: yanggang <gang.yang@daocloud.io>

Signed-off-by: yanggang <gang.yang@daocloud.io>
2022-11-10 01:00:27 +09:00
yanggang
40d600b336 Upgrade fsnotify (#954)
* This makes checking events a lot easier

* upgrade fsnotify package

Signed-off-by: yanggang <gang.yang@daocloud.io>

Signed-off-by: yanggang <gang.yang@daocloud.io>
2022-11-10 00:35:44 +09:00
yanggang
b6c50f2d07 we should keep the first character Big for aligned info note (#953)
Signed-off-by: yanggang <gang.yang@daocloud.io>

Signed-off-by: yanggang <gang.yang@daocloud.io>
2022-11-10 00:34:28 +09:00
yanggang
4f91106f29 remove io/ioutil for advanced golang (#951)
Signed-off-by: yanggang <gang.yang@daocloud.io>

Signed-off-by: yanggang <gang.yang@daocloud.io>
2022-11-10 00:18:54 +09:00
Tomofumi Hayashi
77e0150afe Fix license boilerplate/copyright in go files (#947)
This change fix license boilerplate and its copyright.
The updated year in copyright is based on the file creation date.
If older than 2021, added copyright is transfered to multus
authors from Intel corporation as the multus code was officially
transfered to Kubernetes Networking Plumbing Working Group on
March 11, 2021.
2022-11-02 21:49:57 +09:00
Moshe Levi
6f8fa8c286 fix resource api grpc failed to connect to unix socket (#946)
After commit c6fa047212
resource api got broken in 2 places. first place handled by f530d3eb84
The second break was in replacing podresources.GetV1Client with getKubeletResourceClient.
The GetV1Client remove the protocol (e.g unix:) by calling GetAddressAndDialer, but the getKubeletResourceClient
is using the full endpoint (with the portocol) causing failed to connect to unix socket.
This patch remove the unix: prefix before the grpc connect.

Fixes: #944
Signed-off-by: Moshe Levi <moshele@nvidia.com>

Signed-off-by: Moshe Levi <moshele@nvidia.com>
2022-11-02 21:47:55 +09:00
yulng
8550fa62a5 Modify the judgment of test results (#936) 2022-10-31 22:34:10 +09:00
Gao PeiLiang
a3f9694d09 delegate plugin delete success, delete cache file (#926) 2022-10-31 22:32:51 +09:00
Moshe Levi
fd893ab625 grpc: move to use grpc.WithTransportCredentials() (#942)
see 2c8bfad910

Signed-off-by: Moshe Levi <moshele@nvidia.com>

Signed-off-by: Moshe Levi <moshele@nvidia.com>
2022-10-29 00:47:05 +09:00
Moshe Levi
f530d3eb84 fix kubeletSocket scope (#941)
The kubeletSocket in the function is scoping the const kubeletSocket
which causing resource api to fail with

"stat /var/lib/kubelet/pod-resources/.sock: no such file or directory"

Signed-off-by: Moshe Levi <moshele@nvidia.com>

Signed-off-by: Moshe Levi <moshele@nvidia.com>
2022-10-26 22:25:38 +09:00
Doug Smith
e43ed9274e Merge pull request #939 from s1061123/fix/server
Fix multus-daemon in case of user given config
2022-10-24 16:03:48 -04:00
yulng
f52aa691d6 Add "EOF" to the Cat command, otherwise the operation will fail (#932) (#934)
Add EOF to the Cat command, otherwise the operation will fail
2022-10-25 00:57:09 +09:00
Tomofumi Hayashi
46daed0654 Fix multus-daemon in case of user given config
This fix the issue #931 to refining server startup code including
file copy and channel processing, with simplification.
2022-10-25 00:46:40 +09:00
yulng
e9bb5e5f48 Add "EOF" to the Cat command, otherwise the operation will fail (#932)
Add EOF to the Cat command, otherwise the operation will fail
2022-10-23 14:58:08 +09:00
Doug Smith
fa8a6e6880 Merge pull request #925 from s1061123/dev/rc-api
Support IPs, MAC and cni-args in delegate API
2022-10-14 11:34:12 -04:00
Tomofumi Hayashi
6f90a0f075 Support IPs, MAC and cni-args in delegate API 2022-10-15 00:12:17 +09:00
Doug Smith
efa8c62ec4 Merge pull request #930 from s1061123/fix/mod-ver
Fix kubelet version in go.mod
2022-10-14 11:07:58 -04:00
Tomofumi Hayashi
7c619d64a6 Fix kubelet version in go.mod
fix #928
2022-10-14 23:32:26 +09:00
Eoghan Russell
1aac2431b8 Fix broken link in README (#919) 2022-09-26 23:26:25 +09:00
Doug Smith
f372831536 Merge pull request #915 from s1061123/fix/delegate-api
Fix deleate API to load conflist
2022-09-20 13:19:58 -04:00
Tomofumi Hayashi
3e97437e31 Fix deleate API to load conflist 2022-09-21 01:56:53 +09:00
Miguel Duarte Barroso
b1aba95892 Idiomatic config unit tests (#908)
* gomega, unit tests: use `HaveLen` matcher

The `HaveLen` matcher provides a better error msg when the test fails,
resulting in easier debugging.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* gomega, unit tests: use `BeEmpty` matcher

The `BeEmpty` matcher is more idiomatic, and results in better error
msgs when the test fails.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* gomega, unit tests: use `BeTrue` and `BeFalse` matchers

These matchers are more idiomatic.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2022-09-19 10:22:08 -04:00
Doug Smith
371123659b Merge pull request #906 from TimFroidcoeur/fix_multiple_default_gw
fix multiple default gw
2022-09-01 16:18:38 -04:00
Tim Froidcoeur
8da20f38ea fix multiple default gw
when the configuration specifies both an IPv4 and IPv6 default route,
the IsFilterV4Gateway and IsFilterV6Gateway flags should both be false,
to allow the gateway configuration.
The logic in CheckGatewayConfig would do the inverse, setting both to
true in case of both IPv4 and IPv6 gateway.

Fixes: d52f2b6a ("Update libcni cache when default-route net selection
is used")
Signed-off-by: Tim Froidcoeur <tim.froidcoeur@tessares.net>
2022-09-01 16:50:19 +02:00
Doug Smith
d93a3bb736 Merge pull request #899 from jklare/jk_readme_thick_plugin
rephrase readme section describing thin vs thick plugin
2022-08-26 15:11:52 -04:00
Doug Smith
e882d51b3c Merge pull request #903 from s1061123/dev/fedora-image
[WIP]Change container image to python:slim from centos
2022-08-26 14:35:23 -04:00
Tomofumi Hayashi
db7cc6bc80 Change container image to fedora from centos
This change introduce fedora container for multus image.
2022-08-27 02:57:58 +09:00
Doug Smith
33c0d1bd86 Merge pull request #900 from s1061123/fix/image-tag
Fix container tags for thick plugin
2022-08-25 11:29:17 -04:00
Tomofumi Hayashi
12c6c91586 Fix container tags for thick plugin 2022-08-25 23:07:32 +09:00
Jan Klare
2f12b5ce99 rephrase readme section describing thin vs thick plugin
Signed-off-by: Jan Klare <jan.klare@bisdn.de>
2022-08-24 14:45:26 +02:00
Doug Smith
0c515497d7 recommends thick plugin in quickstart (#894) 2022-08-24 20:23:33 +09:00
Doug Smith
68a9593f84 Merge pull request #897 from s1061123/fix/add-disclaimers
Update deployment yaml
2022-08-22 13:35:21 -04:00
Tomofumi Hayashi
95c4d0c1c5 Update deployment yaml
This change adds note section in deployment yaml to explicitly
mention the scope of this yaml.
2022-08-23 01:19:24 +09:00
Doug Smith
5498080119 Merge pull request #893 from k8snetworkplumbingwg/feature/multus-4.0
Feature/multus 4.0
2022-08-18 16:48:02 -04:00
Tomofumi Hayashi
3d9cec4ec9 Merge remote-tracking branch 'origin/master' into feature/multus-4.0 2022-08-19 00:07:30 +09:00
Tomofumi Hayashi
505ab4567c Add delegate API in multus-daemon (#890)
This changes introduce delegate API function in multus-daemon.
This API will be consumed from other programs for hot-plug
interface into running pod. This change also cleanups server
code to split into client code and server code to easy to import
from other golang code.
2022-08-10 00:45:23 +09:00
Doug Smith
8dee74d7b9 Merge pull request #870 from s1061123/dev/doc-modified
Add 4.0 document
2022-08-01 11:19:02 -04:00
Doug Smith
fba6d66720 Merge pull request #886 from s1061123/update-libcni
Bump libcni to fetch the bugfix
2022-07-29 11:06:14 -04:00
Tomofumi Hayashi
7f7bb354c5 Bump libcni to fetch the bugfix
This change introduces https://github.com/containernetworking/cni/pull/904
to fix the issue.
2022-07-29 20:31:57 +09:00
Doug Smith
f4c0adf54c Merge pull request #881 from chrisplo/detect-python3
Detect python3
2022-07-22 09:48:40 -04:00
Chris Plock
ac6757b9cc Detect python3
fixes https://github.com/k8snetworkplumbingwg/multus-cni/issues/880
2022-07-15 15:13:27 -07:00
Doug Smith
70c970cd6e Merge pull request #878 from tomkukral/print-kubeconfig
write output file for generated kubeconfig
2022-07-12 08:39:17 -04:00
Doug Smith
3deb079546 Merge pull request #876 from s1061123/dev/update-golang
Update golang version to 1.18.x
2022-07-11 16:11:44 -04:00
Doug Smith
9cb6fb57bf Merge pull request #877 from s1061123/dev/refine-build
Refine build-go.sh and update 'version' output
2022-07-11 16:10:31 -04:00
Tomáš Kukrál
95adff55b0 write output file for generated kubeconfig
This change will make debugging easier in cases when non-default
location is used and user forgot to mount new directory.
2022-07-08 14:02:51 +02:00
Tomofumi Hayashi
99dd6678d5 Refine build-go.sh and update 'version' output 2022-07-07 01:44:13 +09:00
Tomofumi Hayashi
6f5fdf64c7 Update golang version to 1.18.x 2022-07-07 00:31:25 +09:00
Tomofumi Hayashi
9d67fbd520 Add 4.0 document 2022-06-27 22:12:23 +09:00
Doug Smith
ca8c9c5791 Merge pull request #864 from s1061123/default-route-pointer
Use *[]net.IP for 'default-route' network selection element.
2022-06-21 15:47:09 -04:00
Doug Smith
18a660ebc7 Merge pull request #867 from mmirecki/downwardapi
Fix missing device-info in networks-status annotation for chained plugins
2022-06-21 14:38:29 -04:00
mmirecki
358f09bfe2 Merge remote-tracking branch 'upstream/master' into downwardapi 2022-06-21 20:14:34 +02:00
Tomofumi Hayashi
107624ccff Use *[]net.IP for 'default-route' network selection element. 2022-06-22 02:12:08 +09:00
Doug Smith
13eb83a01c Merge pull request #868 from s1061123/fix/revive-err
Fix revive error
2022-06-21 11:26:44 -04:00
Tomofumi Hayashi
dc57189cf9 Fix revive error 2022-06-21 23:39:18 +09:00
Doug Smith
3cda380ad1 Merge pull request #865 from s1061123/fix/m40-revive-err
Fix revive's error
2022-06-21 10:24:15 -04:00
mmirecki
2bf8dae9a8 Fix missing device-info in networks-status annotation for chained plugins 2022-06-21 14:47:04 +02:00
Tomofumi Hayashi
2993671acd Fix revive's error 2022-06-21 00:58:24 +09:00
Tomofumi Hayashi
a735987501 Merge remote-tracking branch 'origin/master' into feature/multus-4.0 2022-06-14 18:04:33 +09:00
Doug Smith
8bbb594dad Merge pull request #862 from s1061123/fix/cmddel-nostatus-update
Skip status update in CmdDel if getPod is failed
2022-06-13 13:22:17 -04:00
Tomofumi Hayashi
fcc8e44f14 Skip status update in CmdDel if getPod is failed
This change skips to update pod's network-status annotation
when getPod is failed at the beginning of CmdDel. If getPod is
failed, K8s api gets stucked in many cases, hence pod update
might be failed in most cases.
2022-06-14 02:14:43 +09:00
Doug Smith
3572647e5b Merge pull request #860 from s1061123/dev/add-ut
Add unit-test to increase test coverage
2022-06-10 10:39:20 -04:00
Doug Smith
2eb5d2f653 Merge pull request #857 from s1061123/dev/metrics
Add metrics support
2022-06-10 10:38:34 -04:00
疯狂的小企鹅
be56f8dc30 Fixed that in.Delegates may remain in the CmdDel (#859)
Co-authored-by: jinda.ljd <jinda.ljd@alibaba-inc.com>
2022-06-08 21:03:14 +09:00
Tomofumi Hayashi
580b72a5b2 Add unit-test to increase test coverage 2022-06-08 13:49:17 +09:00
Tomofumi Hayashi
a77d3cbedb Merge remote-tracking branch 'origin/master' into feature/multus-4.0 2022-06-06 23:37:59 +09:00
Miguel Duarte Barroso
d2a4b832f2 config, logging: correct the logging parameters (#856)
The logging parameters were listing using uppercase, which is wrong. 

According to multus configuration, they should be in camelCase - [0] and [1].

[0] - 779170a48e/pkg/types/types.go (L45)
[1] - 779170a48e/pkg/types/types.go (L46)
2022-06-06 22:33:05 +09:00
Tomofumi Hayashi
9f3e6b0da0 Add metrics support
This change introduces prometheus metric exporter support for
multus-daemon, thick plugin.
2022-06-04 00:45:37 +09:00
Tomofumi Hayashi
df903a757e Merge remote-tracking branch 'origin/master' into feature/multus-4.0 2022-06-02 18:04:49 +09:00
Nikhil Simha
779170a48e Added hyperlink for logging (#851)
* Added hyperlink for logging

This may make it easier for users to find info on logging parameters since there isn't a dedicated docs page for it.

* Fixed hyperlink

Linked to proper section
2022-05-26 09:33:22 -04:00
Doug Smith
5ee0274b5b Bumps net-attach-def client library to v1.1.1 (#846)
This accounts for CNI v1.0 formatted IP address information (no longer requires version field)
2022-05-12 22:58:23 +09:00
Doug Smith
42a2642852 Merge pull request #844 from danielmellado/fix-images-docs
Fix wrong location for daemonset in readme
2022-05-10 11:42:14 -04:00
Daniel Mellado
b5323e4144 Fix wrong location for daemonset in readme
This PR fixes an outdated reference in the docs where
multus-daemonset.yml was expected to be found under the images folder.
2022-05-10 17:06:47 +02:00
Tomofumi Hayashi
485642c18f Merge remote-tracking branch 'origin/master' into feature/multus-4.0 2022-05-07 00:36:30 +09:00
Doug Smith
dcbc215b93 The cachefile name should be the delegate configuration name (#841)
It was previously using the net-attach-def name, which doesn't align with the cache file. Causing default-route selection to not succeed.
2022-05-07 00:06:37 +09:00
Doug Smith
5ede36fb43 Merge pull request #839 from s1061123/dev/refine-k8s-lib
Refine Kubernetes APIs
2022-05-04 13:27:00 -04:00
Tomofumi Hayashi
16bd359bc0 Update k8s api to v1.22.8 2022-04-28 22:55:55 +09:00
Tomofumi Hayashi
c6fa047212 Remove k8s.io/kubernetes dependency from multus
Fix #675
2022-04-26 18:22:36 +09:00
Tomofumi Hayashi
59415ad0d6 Merge remote-tracking branch 'origin/master' into feature/multus-4.0 2022-04-26 16:46:16 +09:00
Dan Williams
ecc1482d50 types: fix usage of strings.Split() for parsing CNI_ARGS (#836)
* types: fix usage of strings.Split() for parsing CNI_ARGS

strings.Split() returns a slice, in this case with two elements of
the key and value. As such we shouldn't range over the slice when
the code is expecting a 2-element slice of key/value.

Otherwise we get errors for valid CNI_ARGS like:

2022-04-22T11:53:54Z [error] CreateCNIRuntimeConf: CNI_ARGS K8S_POD_NAMESPACE=openshift-etcd K8S_POD_NAMESPACE 17 is not recognized as CNI arg, skipped
2022-04-22T11:53:54Z [error] CreateCNIRuntimeConf: CNI_ARGS K8S_POD_NAMESPACE=openshift-etcd openshift-etcd 14 is not recognized as CNI arg, skipped

Fixes: d7d2a99ab5 ("Replace setenv with runtimeConfig set")

Signed-off-by: Dan Williams <dcbw@redhat.com>

* types/conf: fix handling of CNI_ARGS additions to rt.Args

We want to set the CNI_ARGS value in rt.Args if the existing value
is empty, not if the key doesn't exist yet. Since the rt.Args array
is pre-created with the K8S args keys, empty values of those keys
couldn't be overwritten with the previous scheme that just checked
if the key existed.

If the CNI_ARGS key wasn't found in rt.Args then add it; previously
a typo ("isExists != false") prevented that with inverted logic.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2022-04-26 00:13:09 +09:00
Doug Smith
b34486308c Merge pull request #834 from s1061123/fix/sriov
Fix sr-iov support
2022-04-25 09:51:23 -04:00
Nikhil Simha
dd15abc9b1 Added a static pod e2e test. (#835)
* Added bash e2e test for static pods. Checks for net1 interface on pod.

Signed-off-by: nicklesimba <simha.nikhil@gmail.com>

* Enable static pod test in CI

Signed-off-by: nicklesimba <simha.nikhil@gmail.com>

* Addressed review comments

Signed-off-by: nicklesimba <simha.nikhil@gmail.com>
2022-04-22 00:35:39 +09:00
Tomofumi Hayashi
10fcc49f4d Merge remote-tracking branch 'origin/master' into feature/multus-4.0 2022-04-19 00:18:38 +09:00
jinglina
706de7c2c6 delete type conversion (#833) 2022-04-18 22:34:40 +09:00
Doug Smith
ea0df58e7c Merge pull request #831 from s1061123/update-golang
Update golang version to 1.17
2022-04-18 09:33:43 -04:00
Tomofumi Hayashi
4670f1f240 Fix sr-iov support
Fix thick plugin daemonset to add volume mapping required for
sr-iov and fix code to update network status.
In addition, fix checkpoint structures to support K8s without
kubelet pod resources API.

fix #665 and #778
2022-04-18 21:28:13 +09:00
Tomofumi Hayashi
4ada0c3ae8 Update golang version to 1.17 2022-04-14 23:30:30 +09:00
Doug Smith
13e4b3a1c4 Merge pull request #828 from s1061123/dev/chroot
Add chroot option in multus-daemon
2022-04-13 15:38:56 -04:00
Tomofumi Hayashi
282b40a503 Add chroot option in multus-daemon
This change introduces 'chroot' option in multus-daemon to execute
delegate CNI with host filesystem context.
2022-04-13 19:36:53 +09:00
Tomofumi Hayashi
bf4d6c716c Merge remote-tracking branch 'origin/master' into feature/multus-4.0 2022-04-12 21:42:19 +09:00
Tomofumi Hayashi
77ed17b392 Fix letter 2022-04-12 15:06:44 +09:00
Cyclinder
6bcb6bf403 add some flags for customize the log settings (#817) 2022-04-12 00:22:48 +09:00
Doug Smith
588ee8f192 Fixes log message on CNI Check (#825) 2022-04-11 20:35:47 +09:00
Cyclinder
ce533f01cc update e2e tools version for kind and cni-plugins (#830) 2022-04-11 14:08:22 +09:00
Tomofumi Hayashi
579d83f359 Merge remote-tracking branch 'origin' into feature/multus-4.0 2022-04-06 00:42:23 +09:00
Tomofumi Hayashi
51c39205a8 Remove error handling for getPod to force to proceed cmdDel.
In cmdDel, CNI Spec mentioned that plugin should proceed cmdDel
without any error, hence the change removes error returning
at cmdDel.

fix #822
2022-04-06 00:34:53 +09:00
Tomofumi Hayashi
4180f88442 Refine multus-daemon config 2022-04-06 00:34:53 +09:00
Tomofumi Hayashi
d1046fa1c9 Fix install binary for thick plugin 2022-04-06 00:34:53 +09:00
Tomofumi Hayashi
0a144e597a Fix thick plugin to run kind-e2e test 2022-04-06 00:34:53 +09:00
Tomofumi Hayashi
2f5af62a92 Refine unit test in pkg/multus
Some of tests are duplicated hence deduped. In addition, sort
these unit tests based on cniVersion.
2022-04-06 00:34:53 +09:00
Cyclinder
80693bde62 fix the usage of flag "overrideNetworkName" (#805) 2022-04-06 00:34:53 +09:00
Doug Smith
3abb21a80c crio: mount /run rslave (#802)
to prevent "unknown FS magic on "/var/run/netns/*": 1021994" errors

Signed-off-by: Peter Hunt <pehunt@redhat.com>

Co-authored-by: Peter Hunt <pehunt@redhat.com>
2022-04-06 00:34:53 +09:00
Doug Smith
e7aaf8f5d5 only warn when netns can't be opened (#803) 2022-04-06 00:34:53 +09:00
Tomofumi Hayashi
93ec0c121e Support CNI 1.0.0
Fix #792
2022-04-06 00:34:53 +09:00
Tomofumi Hayashi
ecc98be9c6 Split multus unit tests into several files
To simplify multus unit tests, split it into several files,
based on testing CNI version.
2022-04-06 00:34:53 +09:00
Tomofumi Hayashi
b8d4d46462 check version incompatibility (#762) (#798)
* multus: entrypoint: disallow incompatible cni versions

When top level CNI version is 0.4.0 or more, nested CNI version
can't be less than 0.4.0 since these are incompatible. This
closes issue #737.

Signed-off-by: Balazs Nemeth <bnemeth@redhat.com>

* multus: thick: disallow incompatible cni versions

Similarly to disallowing incompatible versions in entrypoint.sh,
add the same logic in go for the thick plugin.

Signed-off-by: Balazs Nemeth <bnemeth@redhat.com>

* multus: add unit test for incompatible cni versions

Signed-off-by: Balazs Nemeth <bnemeth@redhat.com>

Co-authored-by: Balazs Nemeth <bnemeth@redhat.com>
2022-04-06 00:34:53 +09:00
Tomofumi Hayashi
869b94ffaa Simplify e2e scripts (#795) 2022-04-06 00:34:53 +09:00
Tomofumi Hayashi
d4a30c383d Make binary file and directory name consistent
This change make binary file and directory name consistent.
In addition, change the package name cni to server because cni
is a bit umbiguous for cni plugin's repository.
2022-04-06 00:34:53 +09:00
Tomofumi Hayashi
d4a3ea4fd0 Replace setenv with runtimeConfig set (#785)
setenv refers environment variables, which is unique in process,
not unique to go routine. Hence it may causes some issue in multi
threaded case, hence it is replaced with libcni's runtimeConfig
value set to set these variables at libcni side, after process
fork.
2022-04-06 00:34:53 +09:00
Miguel Duarte Barroso
fb31217e2c thick-plugin: refactor multus
Multus is refactored as a thick plugin, featuring 2 main components:
  - a server listening to a unix domain socket, running in a pod
  - a shim, a binary on the host that will send JSON requests built from
    its environment / stdin values to the aforementioned server.

The pod where the multus daemon is running must share the host's PID
namespace.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

react to maintainers review

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

thick, deployment: update the daemonset spec

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

thick, config: validate the cni config passed by the runtime

Without this patch, we're blindly trusting anything sent by the server.
This way, we assure the requests arriving at the multus controller are
valid before hand.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

thick: model client / server config

Also add a new command line parameter on the multus controller, pointing
it to the server configuration.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

SQUASH candidate, thick, config: cleanup the configuration

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

multus: use args.args instead of an env variable

CNI is already filling the args structure; we should consume that
rather than rely on the environment variables.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

unit tests: remove weird tests that check an impossible scenario

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

docs, thick: document the thick plugin variant

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

thick, server, multus: re-use common types

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2022-04-06 00:34:52 +09:00
Doug Smith
0453b52097 Merge pull request #823 from s1061123/fix/cmddel
Remove error handling for getPod to force to proceed cmdDel.
2022-04-04 15:41:36 -04:00
Tomofumi Hayashi
2d53334211 Remove error handling for getPod to force to proceed cmdDel.
In cmdDel, CNI Spec mentioned that plugin should proceed cmdDel
without any error, hence the change removes error returning
at cmdDel.

fix #822
2022-04-05 02:29:41 +09:00
Cyclinder
45428a53ce fix the usage of flag "overrideNetworkName" (#805) 2022-03-04 16:01:21 +09:00
Doug Smith
6c12dc8c4f crio: mount /run rslave (#802)
to prevent "unknown FS magic on "/var/run/netns/*": 1021994" errors

Signed-off-by: Peter Hunt <pehunt@redhat.com>

Co-authored-by: Peter Hunt <pehunt@redhat.com>
2022-03-04 02:02:37 +09:00
Doug Smith
7559625a38 only warn when netns can't be opened (#803) 2022-03-04 02:02:24 +09:00
Balazs Nemeth
450e1d3414 check version incompatibility (#762)
* multus: entrypoint: disallow incompatible cni versions

When top level CNI version is 0.4.0 or more, nested CNI version
can't be less than 0.4.0 since these are incompatible. This
closes issue #737.

Signed-off-by: Balazs Nemeth <bnemeth@redhat.com>

* multus: thick: disallow incompatible cni versions

Similarly to disallowing incompatible versions in entrypoint.sh,
add the same logic in go for the thick plugin.

Signed-off-by: Balazs Nemeth <bnemeth@redhat.com>

* multus: add unit test for incompatible cni versions

Signed-off-by: Balazs Nemeth <bnemeth@redhat.com>
2022-02-28 21:50:39 +09:00
Tomofumi Hayashi
6dd45f38f9 Replace setenv with runtimeConfig set (#785)
setenv refers environment variables, which is unique in process,
not unique to go routine. Hence it may causes some issue in multi
threaded case, hence it is replaced with libcni's runtimeConfig
value set to set these variables at libcni side, after process
fork.
2022-02-21 23:55:33 +09:00
Doug Smith
843147aca0 Merge pull request #775 from s1061123/fix/773
Suppress uid mismatch error/warning in case of static pod
2022-02-07 12:44:04 -05:00
Miguel Duarte Barroso
191b8cb0ec e2e tests: always pull new multus images (#783)
Currently, the local workflow is far from optimal, since for every
change on the multus images the developers are required to redeploy
the kind cluster.

A more efficient workflow would be to build a local image, upload it to
the kind cluster, and finally re-deploy (delete & re-provision) the
daemonset, which would be running the new version.

For this flow to be possible, the multus container `imagePullPolicy`
must be set to `Always` - [0] - otherwise, the image is not updated.

[0] - https://kubernetes.io/docs/concepts/containers/images/#updating-images

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2022-01-26 21:37:03 +09:00
Miguel Duarte Barroso
9e79b79a89 multus, e2e tests: allow event sending to k8s API (#776)
Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2022-01-20 23:50:16 +09:00
Tomofumi Hayashi
2e474f4c95 Suppress uid mismatch error/warning in case of static pod
In static pod case, kube api returns mirror pod UID hence
uid must be mismatched. This fix suppress error/warning message
in such case.

Fix #773
2022-01-15 23:17:53 +09:00
Doug Smith
27a86dafbc Merge pull request #779 from nicklesimba/patch-3
Update development.md
2022-01-14 11:10:03 -05:00
Nikhil Simha
daf96bffb3 Update development.md
Fixed doc for how to test
2022-01-14 10:59:29 -05:00
Doug Smith
7a53c910f2 Merge pull request #774 from nicklesimba/patch-2
Update quickstart.md
2022-01-11 13:59:45 -05:00
Nikhil Simha
38b1cd1cec Update quickstart.md
Specified location of 00-multus.conf for clarity
2022-01-11 13:57:48 -05:00
Sho Shimizu
6adb4dc4c4 Add toleration against NoExecute (#768) 2022-01-07 00:06:19 +09:00
Miguel Duarte Barroso
12df5bda72 run gofmt on the code (#772)
Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2022-01-05 01:33:58 +09:00
Doug Smith
ed18a1f175 Merge pull request #764 from s1061123/fix/default-route
Update libcni cache when default-route net selection is used
2021-12-15 12:28:40 -05:00
Tomofumi Hayashi
d52f2b6a45 Update libcni cache when default-route net selection is used
To keep consistency between actual network and CNI result in cache,
update libcni cache when multus add/del default routes by
`default-route` network selection.
2021-12-15 01:57:51 +09:00
Doug Smith
4d9731bd3a Merge pull request #757 from maiqueb/fix-flaky-config-regen-test
flaky: fix delegate CNI conf updates unit test
2021-12-14 10:06:01 -05:00
Miguel Duarte Barroso
0da5449854 thick, config regen, test: fix test
The test was just checking that a READ/WRITE fsnotify.Event for
the multus configuration was being seen; this patch changes this
behavior, and assures that the delegateCNI configuration update results
in turn on the update of the multus configuration file.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2021-12-14 10:10:15 +01:00
Miguel Duarte Barroso
653c4b481d thick, config regen, tests: use a unique path for multus config
Using a unique path for the config generation will lessen the
amount of events caught by the test that checks if the multus
configuration must be re-generated as a result a default cluster
configuration update.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2021-12-09 14:46:36 +01:00
Doug Smith
b9d0d93d6e Pod UID mismatches should only warn on CNI DEL (#763) 2021-11-23 17:52:45 +09:00
Balazs Nemeth
84fde9d711 Update images/README.md (#761) 2021-11-19 21:22:34 +09:00
Doug Smith
4e0e65044b Merge pull request #758 from maiqueb/fix-legacy-entrypoint-e2e-tests
CI, e2e tests: fix legacy
2021-11-15 08:18:59 -05:00
Miguel Duarte Barroso
70660236a8 CI, e2e tests: fix legacy
Our CI is currently mistakenly executing the thick img on the e2e
legacy lanes. Furthermore, the e2e daemonset spec provided features
(and uses) the kubeconfig / multus conf generation binaries
provided only on the thick image.

This commit addresses these by enabling the e2e `setup_cluster.sh`
script user to specify the path to the desired deployment
configuration.

Github workflows are updated accordingly.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2021-11-15 12:38:26 +01:00
Moritz Kröger
130db696ca Update quickstart.md (#754)
* Update quickstart.md

removed unnecassary dollarsign since it kills the quick copy functionality of Code in Github

* Update README.md

* Update quickstart.md

* Update how-to-use.md

Co-authored-by: Doug Smith <douglaskippsmith@gmail.com>
2021-11-12 00:24:06 +09:00
Doug Smith
ada145ca5f Merge pull request #753 from s1061123/fix/cni-bin-dir
Added --cni-bin-dir and --multus-bin-file for regression
2021-11-11 00:00:46 +09:00
Tomofumi Hayashi
25c46c84b8 Added --cni-bin-dir and --multus-bin-file for regression 2021-11-08 17:40:54 +09:00
Etienne Champetier
32c952e501 Fixup thick deployment, make images thiner (#747)
* deployment, thick: only use thick image

Signed-off-by: Etienne Champetier <e.champetier@ateme.com>

* images: only keep binaries and LICENSE

Signed-off-by: Etienne Champetier <e.champetier@ateme.com>
2021-11-02 14:20:37 +09:00
Tomofumi Hayashi
7091831a00 Remove dependency of go-dproxy (#746)
This change removes to dependency of go-dproxy from multus to
reducing library dependencies.
2021-10-28 12:15:11 -04:00
Tomofumi Hayashi
1e43784d4c Change the sort of image push. 2021-10-28 23:04:07 +09:00
Miguel Duarte Barroso
42fde2292d deployment, thick: remove extra multus-cni-config mountpoint (#745)
This volume was removed since multus now requires the default cluster
network CNI configuration to be available. As such, the volume as
removed, but we unfortunately forgot to remove to remove the volume
mount.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2021-10-28 09:37:35 -04:00
Miguel Duarte Barroso
8ba2accb9f Replace entrypoint script with initcontainers (#718)
* build: install the multus binary in an init container

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* build: generate kubeconfig via go

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* build: generate multus cni configuration via golang

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* build: provide a docker img for daemon based deployments

We will have 2 different images (only on amd64 archs):
- legacy entrypoint script based
- daemonized process

The `image-build` docker action is updated, to build these 2 images.

There will be 2 different deployment specs, along with e2e test
lanes, one for each of the aforementioned alternatives.

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* build: delegate CNI config watch loop via golang

For the thick-plugin alternative, provide the watch loop for
configuration regeneration via a golang binary.

Over time, this binary is expected to run the control loop to watch
out for pod updates.

To enable current multus users to chose when they upgrade to this new
deployment setup, these changes are provided in separate multus images,
having a different yaml spec files. Both of these alternatives are
tested e2e, since a new lane is introduced.

The following libraries are introduced, along with the motivation for
adding them:
- dproxy: allows traversing the default network configuration arbitrarily,
  similar to what an X path / JSON path tool provides.
  Repo is available at [0].
- fsnotify: watch for changes in the default CNI configuration file.
  Repo is available at [1].

The config map providing the default network CNI configuration is not
copied over, since originally, the user was not required to install a
default network CNI plugin first, but, nowadays, this is a required
step of multus.

As such, it is no longer required to provide a default CNI
configuration.

[0] - https://github.com/koron/go-dproxy
[1] - https://github.com/fsnotify/fsnotify

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* run gofmt

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* refactor: make the builder pattern more idiomatic to golang

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>

* build: update github actions to release new imgs

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2021-10-27 08:42:37 -04:00
Dan Williams
b56dd5f67f multus: test Pod UID scenarios when both passed and not passed by runtime
Because the tests fake out the OS exec functionality, the environment that
would usually be passed to a plugin instead gets passed as a string array
to the ExecPlugin() function in the tests. But when verifying the expected
environment this function was looking at the actual OS environment rather
than the passed string array. Fix that.

Use that to test various cases of the pod UID being passed to plugins.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2021-10-26 01:20:43 +09:00
Dan Williams
e8e99f1771 multus: log error marshaling delegate netconf
Fixes an unused variable warning too.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2021-10-26 01:20:43 +09:00
Dan Williams
cb19a22cb9 multus: fail if given pod UID does not match Kube API pod UID
If the runtime passes a pod UID via K8S_POD_UID (which both CRIO and
containerd do as of mid-2021) then fail if the pod we get from the
Kube API has a different UID. This would indicate that the pod was
deleted and recreated while Multus was attempting to set up
networking for the old pod instance's sandbox, and it's pointless
to continue setting up a sandbox for a dead pod instance.

Also pass the pod UID through to plugins so they can perform
additional checking and validation on the pods they get from the
Kube API.

Signed-off-by: Dan Williams <dcbw@redhat.com>
2021-10-26 01:20:43 +09:00
Miguel Duarte Barroso
392726842f e2e tests: allow podman OCI
Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2021-10-20 20:58:32 +09:00
Tomofumi Hayashi
76c31b0861 Fix version string in '-v' option
Due to change the file layout, previous version command does not
work. This change fix it.
2021-10-15 00:07:20 +09:00
Doug Smith
51a74efe57 Merge pull request #729 from s1061123/dev/update-layout
Change file layout and mention the supported Kubernetes version
2021-09-29 10:19:02 -04:00
Tomofumi Hayashi
bf0b37e010 Change file layout and mention the supported Kubernetes version 2021-09-28 22:40:51 +09:00
Doug Smith
efdc0a5c7d Merge pull request #724 from s1061123/downgrade-k8s-vendor
Downgrade Kubernetes vendor version
2021-09-17 14:46:50 -04:00
Tomofumi Hayashi
ae4a28b689 Downgrade Kubernetes vendor version
Multus community decide that multus support the Kubernetes that
Kubernetes community supports, so changed vendor code to the
oldest version of currently supported.
2021-09-17 22:48:12 +09:00
Doug Smith
e1b0698eb2 Merge pull request #723 from s1061123/update-go-version
Update golang version (at least >= 1.16)
2021-09-15 08:13:42 -04:00
Tomofumi Hayashi
35fdb29385 Update golang version (at least >= 1.16)
Currently golang community supports 1.16 and later, hence, need
to update golang version in our build pipeline. This change
updates golang version to 1.17/1.16.
2021-09-14 16:53:35 +09:00
张祖建
a28f5cb56c Fix typos
Signed-off-by: 张祖建 <zhangzujian.7@gmail.com>
2021-09-14 00:25:01 +09:00
Doug Smith
ad257698ef Merge pull request #712 from nicklesimba/patch-1
Update quickstart.md
2021-08-25 16:48:33 -04:00
Nikhil Simha
8b3bbf38c8 Update quickstart.md
There is a typo in the expected resulting annotations
2021-08-25 13:27:18 -04:00
Doug Smith
a506d7606c Merge pull request #696 from cgchinmay/fix_entrypoint
Use MULTUS_MASTER_CNI_FILE_NAME as MASTER_PLUGIN as is, if specified
2021-07-16 15:25:51 -04:00
Chinmay Gadgil
7e44bb6d21 Use MULTUS_MASTER_CNI_FILE_NAME as MASTER_PLUGIN as is, if specified 2021-07-12 10:30:20 -07:00
Tomofumi Hayashi
9b45d4b211 Merge branch 'master' of https://github.com/k8snetworkplumbingwg/multus-cni 2021-07-08 22:52:30 +09:00
Doug Smith
f77c591d69 Merge pull request #695 from cgchinmay/update_golang_version
Update golang version for installing packages
2021-07-08 09:52:03 -04:00
Tomofumi Hayashi
8c9f409032 Fix github action 2021-07-08 22:52:02 +09:00
Chinmay Gadgil
0724c2b9b0 Update golang version for installing packages 2021-07-06 22:56:21 -07:00
Miguel Duarte Barroso
085870c4b5 Export poll[Interval|Timeout] as constants
Thus not repeating ourselves, nor shadowing the global variables
that had the same name (pollInterval / pollTimeout).

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2021-06-26 00:06:30 +09:00
Miguel Duarte Barroso
26ef3c3eb4 Cut the retry interval and timeout by half on pod retrieval
Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2021-06-26 00:06:30 +09:00
Miguel Duarte Barroso
1eeab9b589 Retry pod retrieval on multiple error types
Also retry on the following error types (cmd ADD/DEL):
- IsInternalError
- IsConnectionReset
- IsConnectionRefused

Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2021-06-26 00:06:30 +09:00
Doug Smith
7f5620db76 Merge pull request #689 from maiqueb/fix-missing-cni-version-example
examples: missing cni version on version without delegates
2021-06-23 12:57:56 -04:00
Miguel Duarte Barroso
1e29a6b50c examples: missing cni version on version without delegates
Signed-off-by: Miguel Duarte Barroso <mdbarroso@redhat.com>
2021-06-23 18:23:30 +02:00
Peng Liu
d09cc8e581 Use the default socket path in GetResourceClient when unspecified
Signed-off-by: Peng Liu <pliu@redhat.com>
2021-06-08 23:05:54 +09:00
xieyanker
cd23938191 Update calico daemonset's url 2021-06-02 21:32:08 +09:00
xieyanker
3b8aa66765 Fix typo 2021-06-02 21:31:37 +09:00
Doug Smith
37adefba51 Merge pull request #679 from xieyanker/master_cni_file
Support the specific cni file name
2021-06-02 08:08:05 -04:00
xieyanker
ec30b99534 Update how-to-use --multus-master-cni-file-name 2021-06-02 14:24:41 +08:00
xieyanker
a53233028b Update ORG_PATH for test-go.sh 2021-06-01 21:58:05 +09:00
xieyanker
492ffec8c8 Support the specific cni file name 2021-05-29 15:29:37 +08:00
Doug Smith
c25a39c5a3 Merge pull request #672 from s1061123/dev/update-lib
Update vendor package
2021-05-26 14:04:02 -04:00
Tomofumi Hayashi
3f1031e7b4 Update vendor package 2021-05-27 02:25:34 +09:00
Tomofumi Hayashi
2339c11a15 Remove global variables from kubletclient
Fixes #673
2021-05-27 01:45:15 +09:00
Sho SHIMIZU
2ba3d3cda2 Describe additional condition when using clusterNetwork
When configuring `clsuterNetwork` in Multus CNI config, the value
for `clusterNetwork` needs to match the value for `name` key in
the file `clusterNetwork` setting refers to. This condition is
undocumented in doc/configuration.md. This PR adds description
on the condition for users to understand `clusterNetwork` config
more clearly.

Signed-off-by: Sho SHIMIZU <sho.shimizu@gmail.com>
2021-05-24 22:11:30 +09:00
dougbtv
6abe8ee06b The kubeconfig creation should be an atomic operation 2021-05-13 22:40:06 +09:00
Doug Smith
a03b3e8c41 Merge pull request #666 from s1061123/fix/update-nad-lib
Update net-attach-def client library
2021-05-12 12:11:14 -04:00
Tomofumi Hayashi
753d18740a Update net-attach-def client library 2021-05-11 01:29:26 +09:00
Doug Smith
1a0fa953f9 Merge pull request #661 from xieyanker/patch-1
update 30-multus.conf to 00-multus.conf
2021-04-29 09:39:45 -04:00
xieyanker
bd57d31780 update 30-multus.conf to 00-multus.conf 2021-04-28 15:50:41 +08:00
Doug Smith
91a7d22e2b Merge pull request #657 from s1061123/dev/add-cluster-net-name
Add cluster network name in pod network annotation
2021-04-20 15:01:55 -04:00
Doug Smith
8d555dba24 Merge pull request #658 from e0ne/fix-typo
Fix typo: s/Lauch/Launch
2021-04-20 15:01:00 -04:00
Ivan Kolodyazhny
e566760a45 Fix typo: s/Lauch/Launch 2021-04-20 21:18:04 +03:00
Tomofumi Hayashi
cd7492f79b Add cluster network name in pod network annotation
This addresses #656
2021-04-19 23:20:36 +09:00
Bjorn Svensson
9e3ad2ea1e Correcting Dockerfile path for manual e2e tests
Signed-off-by: Björn Svensson <bjorn.a.svensson@est.tech>
2021-04-19 17:34:30 +09:00
Doug Smith
a52680b3bf Merge pull request #651 from s1061123/dev/add-arm32
Add arm32v7 container image support
2021-04-07 11:37:00 -04:00
Tomofumi Hayashi
78cf9fced8 Add arm32v7 container image support
Currently multus-cni releases arm32 binary as release tar ball.
This changes also introduce container image for easy deployment.
Fix #639
2021-04-04 04:23:39 +09:00
dougbtv
905b5d0e42 Github action for closing stale issues 2021-04-03 18:12:58 +09:00
dougbtv
0ef8c27a67 [docs] Adds release policy 2021-04-01 22:53:15 +09:00
Doug Smith
e603d8dbb0 Merge pull request #644 from s1061123/dev/cleanup-dev-info
Skip to call device-info related function if not required
2021-04-01 09:52:17 -04:00
Tomofumi Hayashi
9e96c38ebe Skip to call device-info related function if not required
The case withot DeviceInfo/ResourceName, we could skip functions
related to device info. This change skips to call these functions
if delegates does not have DeviceInfo/ResourceName.
2021-04-01 03:55:57 +09:00
Doug Smith
ad6f57f14d Merge pull request #643 from s1061123/fix/no-network-error
[WIP] Change nil instead of error in case of no network annotation
2021-03-31 12:14:56 -04:00
Tomofumi Hayashi
479e2bd78e Change nil instead of error in case of no network annotation
fix #642
2021-03-31 23:06:55 +09:00
Doug Smith
ae56437297 Merge pull request #638 from s1061123/dev/use-non-default-libcni-cache
Change libcni's cache directory from default for multus delegates
2021-03-29 17:05:05 -04:00
Doug Smith
dc4d6e6764 Merge pull request #636 from s1061123/fix/error-on-syntax-error
Return error on annotation parsing error
2021-03-29 09:23:27 -04:00
Tomofumi Hayashi
75acc10312 Change libcni's cache directory from default for multus delegates
This changes CNI cache directory to non default places to avoid
conflicts among CNI runtimes.
2021-03-27 04:12:10 +09:00
Tomofumi Hayashi
8d7308e6bb Return error on annotation parsing error
Fix #635
2021-03-26 01:31:01 +09:00
Doug Smith
c4b9534529 Merge pull request #634 from s1061123/fix/delete_old_main
Delete main from pkg/multus because now it was moved to cmd/main.go
2021-03-24 17:02:45 -04:00
Tomofumi Hayashi
c8e63996c8 Delete main from pkg/multus because now it was moved to cmd/main.go 2021-03-25 03:02:50 +09:00
dougbtv
5d98a0e0eb Updates Readinessindicator error message to be actionable by users 2021-03-24 04:19:44 +09:00
Doug Smith
343a4e3687 Merge pull request #629 from s1061123/fix/change-org-name
Fix/change org name
2021-03-17 15:36:17 -04:00
Doug Smith
feb52328d2 Merge pull request #627 from s1061123/fix/change-image-url
Change image url to ghcr.io
2021-03-16 14:50:00 -04:00
Tomofumi Hayashi
118cc629cf Update organization name due to ownership change 2021-03-16 16:24:49 +09:00
Tomofumi Hayashi
784fecfa02 Change image url to ghcr.io 2021-03-13 05:05:17 +09:00
Doug Smith
f6298a3a29 Merge pull request #626 from s1061123/dev/use-ghcr
Change github action to use ghcr.io
2021-03-12 14:51:45 -05:00
Tomofumi Hayashi
20049dedfe Change github action to use ghcr.io 2021-03-13 04:38:21 +09:00
Doug Smith
20a5d5f34a Merge pull request #625 from e0ne/example-pod
Fix link to an example pod with SRIOV network
2021-03-12 14:33:59 -05:00
Ivan Kolodyazhny
b97c443a56 Fix link to an example pod with SRIOV network 2021-03-11 16:48:04 +02:00
Doug Smith
40a0faed5e Merge pull request #624 from s1061123/dev/bump-libcni
Bump libcni version
2021-03-10 15:53:14 -05:00
Tomofumi Hayashi
5feb1343cd Bump libcni version 2021-03-11 04:50:21 +09:00
Yun Zhou
dc9315f125 Provide the option to not to log via STDERR
Today, Multus will always log via STDERR, and these logs will then
logged by the Kubelet. If we also choose to have Multus log to a file by
setting the LogFile option in the CNI configuration, the same logs will
be logged twice.

This commit provide the option to disable logging to STDERR.

Signed-off-by: Yun Zhou <yunz@nvidia.com>
2021-03-10 17:13:12 +09:00
Kennelly, Martin
5141eab28a Fix invite to NPWG slack
Readding NPWG slack invite mechanism.

Signed-off-by: Kennelly, Martin <martin.kennelly@intel.com>
2021-03-02 04:39:51 +09:00
Doug Smith
c1166d2d3d Merge pull request #617 from s1061123/fix/check-tty
Conditional check for tty/non-tty in case of wait (i.e. read)
2021-02-25 10:22:17 -05:00
Tomofumi Hayashi
de463cca0d Conditional check for tty/non-tty in case of wait (i.e. read)
Fix #615.
2021-02-26 00:18:06 +09:00
Tomofumi Hayashi
02ad030899 Fix CI info 2021-02-24 15:32:46 +09:00
Doug Smith
e80696dc8e Merge pull request #613 from s1061123/dev/update-gh-actions
Update github actions CI pipeline including lint error fix
2021-02-23 10:05:55 -05:00
Tomofumi Hayashi
9bfb9b9b67 Update github actions CI pipeline including lint error fix 2021-02-23 20:01:34 +09:00
Doug Smith
a0d292a0e8 Merge pull request #606 from dougbtv/bump-protobuf
Bump protobuf to v1.3.2
2021-02-18 14:56:41 -05:00
dougbtv
fe42962eb5 [deps][vendor] Updates gogo/protobuf 2021-02-18 11:29:20 -05:00
Kennelly, Martin
094dcbe2c2 Update Slack URL in README following renaming
Signed-off-by: Kennelly, Martin <martin.kennelly@intel.com>
2021-02-18 23:42:26 +09:00
dougbtv
8bbd3fdcf2 Change to sleep infinity & read and omit & wait on sleep n (e.g. not infinity) 2021-02-18 23:42:00 +09:00
Doug Smith
e728da78bc Merge pull request #611 from yoheiueda/s390x
Add s390x support
2021-02-18 09:39:40 -05:00
Yohei Ueda
9824963f79 Add s390x support
This PR updates the GitHub Actions workflows to build multus
container images for the IBM Z architecture (s390x), and also
adds daemonsets for s390x nodes.

entrypoint.sh uses python3 when it is available, since centos images
are not available for s390x, and python2 is not installed by default
on debian-based images.

Signed-off-by: Yohei Ueda <yohei@jp.ibm.com>
2021-02-18 01:40:33 -05:00
Doug Smith
cd9efbf703 Merge pull request #607 from amorenoz/bug/runtime
conf: do not modify global runtimeconfig when merging
2021-02-16 14:23:34 -05:00
Adrian Moreno
91e4efcd68 conf: make a copy of global RuntimeConfig on merge
When we call mergeRuntimeConfig, the global RuntimeConfig gets
overwritten with the result of the merging, thus affecting the
subsequent delegates.

Do not modify the global RuntimeConfig and instead make a copy
when merging it.

Also, if a value has been provided for CNIDeviceInfoFile in the
delegate's runtimeconfig, overwrite it to avoid possible name
colissions.

Signed-off-by: Adrian Moreno <amorenoz@redhat.com>
2021-02-11 20:39:41 +01:00
dougbtv
63734fc026 Adds a trap for SIGTERM in entrypoint script 2021-02-10 04:57:07 +09:00
Doug Smith
bd90c262f6 Merge pull request #603 from s1061123/fix/graceperiod
Add grace period to missing deployment template
2021-01-29 08:40:48 -05:00
Tomofumi Hayashi
d093709f94 Add grace period to missing deployment template 2021-01-28 15:25:45 +09:00
dougbtv
f6df613c32 Pods in daemonset should have grace period reduced.
Otherwise, it can take a long time for the daemonset to stop, and there's no real reason it needs to hang out for a long time.
2021-01-28 15:22:27 +09:00
dougbtv
d4e8699825 The readme links need to be updated after directory change.
This updates the links to point to "doc/" instead of "docs/"
2020-12-17 05:23:14 +09:00
Nikhil Simha
62abb002dd Restructured multus to use Go standard project layout. 2020-12-16 22:38:10 +09:00
Doug Smith
bd9f2e9700 Merge pull request #595 from Mmduh-483/capabilities-entry-fail
Fix entrypoint fail to read capabilities in non chain plugin config
2020-12-14 08:28:41 -05:00
Mamduh Alassi
09190bce3e Fix entrypoint fail to read capabilities in non chain plugin config
entrypoint script fails with error when try reading capabilities in
non chain plugin config file when using "--multus-conf-file=auto"

Signed-off-by: Mamduh Alassi <mamduhala@mellanox.com>
2020-12-14 12:58:35 +02:00
Doug Smith
24386abae3 Merge pull request #553 from venuiyer/vi-multus
Allow the default-route to be empty
2020-12-10 09:45:53 -05:00
dougbtv
476c738c13 Allows specifying "global namespaces" when using namespace isolation 2020-12-10 23:40:18 +09:00
Doug Smith
e924318e18 Merge pull request #577 from Billy99/billy99-device-info
Add DeviceInfo Data to NetworkStatus Annotation
2020-12-01 13:50:26 -05:00
dougbtv
cfa0d64925 Multus should exit zero on DEL when cache file is missing and pod cannot be found.
Otherwise, this can cause a pod to not be fully deleted, its sandbox may remain as the DEL continues to be retried due to exiting non-zero every time.

See: https://bugzilla.redhat.com/show_bug.cgi?id=1900835
2020-11-25 22:11:17 +09:00
Billy McFall
ae797801b1 Remove Multus version of NetworkStatus
NetworkStatus was moved to network-attachment-definition-client in previous
merges and the Multus version of the structure was left behind, and not
being used.

Signed-off-by: Billy McFall <22157057+Billy99@users.noreply.github.com>
2020-11-19 16:38:42 -05:00
Billy McFall
f826461b06 Add DeviceInfo Data to Network Status Annotation
Signed-off-by: Billy McFall <22157057+Billy99@users.noreply.github.com>
2020-11-19 16:38:42 -05:00
Billy McFall
fb557ab20f Add CNIDeviceFile in RuntimeConfig
DPDeviceFile is used by Device Plugins to pass device data to CNIs, as defined
in the device-info-spec. The name of the DPDeviceFile is defined by the
device-info-spec as:
 <ResourceName>-<DeviceID>-device.json

If the DPDeviceFile exists, the NPWG implementation makes a copy of the file
and passes the name of the file to the delegate CNI via capabilityArgs as
CNIDeviceFile. If the DPDeviceFile does not exist, the filename is still
passed to the CNI. The CNI can create the file and popluate it if a device
is created within the CNI.

The name of the CNIDeviceFile is not defined by device-info-spec, but to
ensure the name does not clash it is formed by the following unique triplet:
[networkName, PodUUID, ifName]

k8snetworkplumbingwg/network-attachment-definition-client repo has utility
functions to abstract some of this functionality so it can be reused across
Device Plugins, NPWG implementations and CNIs.

Signed-off-by: Billy McFall <22157057+Billy99@users.noreply.github.com>
2020-11-19 16:38:30 -05:00
Billy McFall
fd3f485e63 Add deviceID support in runtimeConfig
Signed-off-by: Billy McFall <22157057+Billy99@users.noreply.github.com>
2020-11-19 16:34:29 -05:00
Billy McFall
665c43a2cd Merge RuntimeConf on delPlugins
RuntimeConfig depends on the delegate configuration. The Netconf runtime
information should be merged with the delegate config and the result
added to each command that is sent to the delegates. That was being done
for all commands except for delPlugins.

Do not export MergeCNIRuntimeConfig and call it from
CreateCNIRuntimeConf that now accepts a delegate ptr.

Call it from delPlugins for each delegate

Signed-off-by: Billy McFall <22157057+Billy99@users.noreply.github.com>
2020-11-19 16:34:15 -05:00
Billy McFall
2cd91b6bad Update vendor for network-attachment-definition-client update
Signed-off-by: Billy McFall <22157057+Billy99@users.noreply.github.com>
2020-11-19 16:06:54 -05:00
Billy McFall
e064679967 Point to latest network-attachment-definition-client
Move Multus to use latest network-attachment-definition-client repo which
contains the device-info-spec changes.

Signed-off-by: Billy McFall <22157057+Billy99@users.noreply.github.com>
2020-11-19 16:06:54 -05:00
Doug Smith
6a23d65fea Merge pull request #583 from aojea/cmdadddel
clarify cmdAdd error
2020-11-19 10:45:04 -05:00
Antonio Ojea
1b58bed5a6 clarify cmdAdd error
it can happen that a CNI Add operation is canceled because the
runtime sends a CNI Del too fast, so the pod was already deleted
when multus try to set the network status annotations.

Since multus is an executable and can not persist state, it can't
track the CNI requests that are done in parallel, but it can
assume that, if it was able to get the pod from the API, and in a
subsequent request the pod no longer exists, it is because it was
deleted.

Signed-off-by: Antonio Ojea <aojea@redhat.com>
2020-11-19 10:30:12 +01:00
Doug Smith
957e26674a Merge pull request #573 from rhdojun/patch-1
Update quickstart.md
2020-11-12 09:35:38 -05:00
Doug Smith
36d3874c4c Merge pull request #571 from Billy99/billy99-k8s-rebase
Bump kubernetes dependencies to v0.18.3
2020-10-27 15:36:55 -04:00
rhdojun
4bfc2b14f2 Update quickstart.md
Felt like the line wasn't finished yet.
2020-10-27 13:12:34 +01:00
Billy McFall
f62529d4ff Update source for k8s bump to v0.18.3
Signed-off-by: Billy McFall <22157057+Billy99@users.noreply.github.com>
2020-10-23 15:49:49 -04:00
Billy McFall
36b5edff29 Update vendor, go.mod and go.sum for k8s bump to v0.18.3
Signed-off-by: Billy McFall <22157057+Billy99@users.noreply.github.com>
2020-10-23 10:55:54 -04:00
Billy McFall
c8739f64b9 Run 'go fmt' on code base.
Signed-off-by: Billy McFall <22157057+Billy99@users.noreply.github.com>
2020-10-23 10:43:23 -04:00
Doug Smith
bc95a19c5d Merge pull request #559 from s1061123/fix/remove-travis
Remove travis.yml because CI is now switched to github/actions
2020-09-15 20:06:16 -04:00
Tomofumi Hayashi
0e4b8be1e7 Remove travis.yml because CI is now switched to github/actions 2020-09-15 16:47:14 +09:00
Doug Smith
d13e06a5df Merge pull request #556 from s1061123/add-default-route-e2e
Add e2e tests for default-route annotation
2020-09-14 13:31:45 -04:00
Tomofumi Hayashi
ff3ee290c9 Add e2e tests for default-route annotation 2020-09-14 12:56:12 +09:00
Shane Utt
8cc60f7dd8 Add ARM64 to images
This PR takes the existing ARM64v8 build
and creates Daemonsets in the install images
to deploy it for ARM based K8s clusters.

Fixes #554

Signed-off-by: Shane Utt <shaneutt@linux.com>
2020-09-14 12:47:34 +09:00
venu iyer
292d9a9af3 Allow the default-route to be empty
In
https://docs.google.com/document/d/1Ny03h6IDVy_e_vmElOqR7UdTPAG_RNydhVE1Kx54kFQ,
section 4.1.2.1.9,

"
4.1.2.1.9 “default-route” Default route selection for a particular attachment

This optional key with value of type string-array is used to explicitly select
which attachment will receive the default route. The value of items in the
“default-route” array are intended to be gateways, e.g. an IP address to which
packets that do not match any other routes are sent. This key must only be set
on one item in the Network Attachment Selection Annotation. This list may be empty.
"

However en empty list will fail currently; this change accommodates an
empty "default-route" by retaining the default route added by the
delegate.

Signed-off-by: venugopal iyer <venugopali@nvidia.com>
2020-09-08 14:53:25 -07:00
Doug Smith
2a01aec396 Merge pull request #552 from intel/fix/e2e
Update e2e
2020-09-03 13:50:14 -04:00
Tomofumi Hayashi
17b24d5fd5 Update e2e
This change contains following:
 - update kind version to 0.8.1
 - update setup script due to update
 - add teardown script
 - update README
2020-09-04 02:20:35 +09:00
Doug Smith
2dab3225de Merge pull request #550 from s1061123/fix/image-url
Specify image repo URL explicitly
2020-08-31 08:36:41 -04:00
Tomofumi Hayashi
95cc1902c0 Specify image repo URL explicitly
This fix supplies domain for container image repo because
in some runtime configuration, 'docker.io' is not specified as
default container repository url.
2020-08-31 14:58:10 +09:00
Mamduh Alassi
36f2fd64e0 Use latest image version 3.6 in daemonset files 2020-08-20 22:35:19 +09:00
Doug Smith
be492e1778 Merge pull request #545 from clementnuss/master
Pull underlying capabilities up to 00-multus.conf
2020-08-06 09:37:02 -04:00
Clément Nussbaumer
4c271a57d5 Pull underlying capabilities up to 00-multus.conf
Using Python, we analyze the content of the master plugin configuration,
and we integrate any capabilities from the underlying chained plugins
declaration. We only pull enabled capabilties from the underlying
(chained) plugin definitions.

Fixes intel#544

Signed-off-by: <Clement.Nussbaumer@Swisscom.com>
2020-08-05 10:29:05 +02:00
Doug Smith
e15f97860f Merge pull request #541 from s1061123/fix/crd
Fix CRD yaml file for right explan information
2020-07-28 10:39:13 -04:00
Tomofumi Hayashi
78669323d2 Fix CRD yaml file for right explan information 2020-07-28 11:56:08 +09:00
Doug Smith
c85b79f5ff Merge pull request #536 from s1061123/fix/update-vendor
Update vendors
2020-07-21 20:17:50 -04:00
Tomofumi Hayashi
801e1e8940 Update vendors 2020-07-22 09:15:24 +09:00
Doug Smith
41fefbb001 Merge pull request #522 from s1061123/fix/del-error-fix
Fix/del error fix
2020-07-21 17:13:33 -04:00
Tomofumi Hayashi
4eb6ae1553 Fix error handling on cmdDel
Fix #519
2020-07-21 14:52:07 +09:00
Doug Smith
b5211cb0d2 Merge pull request #534 from bmwiedemann/date
Allow to override build date with SOURCE_DATE_EPOCH
2020-07-09 09:52:28 -04:00
Bernhard M. Wiedemann
29df24fa6c Allow to override build date with SOURCE_DATE_EPOCH
in order to make builds reproducible.
See https://reproducible-builds.org/ for why this is good
and https://reproducible-builds.org/specs/source-date-epoch/
for the definition of this variable.

This date call only works with GNU date.

Also use UTC to be independent of timezone.
2020-07-08 05:08:11 +02:00
Doug Smith
e4a8c9f639 Merge pull request #530 from rktidwell/master
build: Enable -mod build flag to be toggled via environment variable
2020-07-06 08:49:58 -04:00
Adrian Chiris
2796202d8c Add infinibandGUID runtime config to delegate netconf
This commit extend the various network conf methods
to translate `infiniband-guid` network attachment configuration
to `infinibandGUID` CNI runtime config.

- Update relevant methods in types package
- Update unit tests
2020-06-26 14:55:21 +09:00
Adrian Chiris
46be700cb5 Struct updates
- Add `infinibandGUID` CNI runtime config
- Add `infiniband-guid` Network attachment attribute
- Reflect infiniband guid request in Delegate network config
2020-06-26 14:55:21 +09:00
Ryan Tidwell
a167d54608 build: Enable -mod build flag to be toggled via environment variable
This change will enable builds to be performed with the option of
passing the -mod flag to 'go build'. This can be done by optionally
setting the MODMODE environment variable prior to building.

For example, toggling the -mod setting for the build can be
accomplished as follows:

```
$ MODMODE=vendor ./build
```

Signed-off-by: Ryan Tidwell <rtidwell@suse.com>
2020-06-24 16:11:19 -05:00
Shahar Klein
ecb79330c0 Add support for log rotation
When using debug level the log files tends to fill up quickly.
Add support for log rotation using lumberjack, simple and easy to use
log rotation module.

Signed-off-by: Shahar Klein <sklein@nvidia.com>
2020-06-17 15:31:19 +09:00
Doug Smith
3882e405ef Merge pull request #515 from s1061123/fix/namespace-in-status
Fix network status name/namespace to compliant with multi-net-spec
2020-06-09 15:08:23 -04:00
Doug Smith
5e15ff18f8 Merge pull request #518 from dougbtv/readme-typo
README typo for roll-YOUR-own
2020-06-09 15:07:49 -04:00
dougbtv
28bb98f78b README typo for roll-YOUR-own 2020-06-09 15:07:19 -04:00
Tomofumi Hayashi
e7c8977423 Fix network status name/namespace to compliant with multi-net-spec
This fix changes network status name to net-attach-def name with
namespace, to compliant with k8s npwg's multi-net-spec.
2020-06-09 12:43:49 +09:00
Doug Smith
fff8e490b9 Merge pull request #511 from s1061123/fix/error-on-fail
Change the error handling for kubernetes client
2020-06-08 09:14:02 -04:00
dougbtv
809a16fbed Adds code of conduct 2020-06-05 09:18:10 +09:00
Tomofumi Hayashi
f5dcb9d8be Change the error handling for kubernetes client
This change adds retry to wait a bit if kubernetes client
returns service unavailable.

This fixes #492
2020-06-01 23:17:42 +09:00
Doug Smith
fdd7d30095 Merge pull request #507 from s1061123/dev/update-example
Simplify examples directory
2020-05-28 09:59:10 -04:00
Tomofumi Hayashi
c976f6bceb Add deviceid in clusterNetwork 2020-05-28 10:00:29 +09:00
Tomofumi Hayashi
8131923b14 Simplify examples directory 2020-05-19 21:29:19 +09:00
Tomofumi Hayashi
4eac660359 Introduce gopkg.in for go module
This change introduces gopkg.in to allow everyone to use multus
code as library. Currently multus-cni uses version 'v3', hence
it hits go modules limitation, as #504 describes.

This change fix #504 with gopkg.in.
2020-05-15 21:33:26 +09:00
dougbtv
ec5fd6c923 Move pre-1.16 Kubernetes assets to a deprecated folder (to later remove) 2020-05-08 09:50:33 +09:00
Doug Smith
b8540e190d Merge pull request #455 from cucosion/feature/gkeexample
Daemonset for Google Kubernetes Engine for kubernetes cluster version…
2020-04-30 09:44:45 -04:00
Doug Smith
a4c2b67784 Merge pull request #497 from s1061123/fix/improve-cni-logs
[WIP] Fix/improve cni logs
2020-04-30 08:43:09 -04:00
Tomofumi Hayashi
b2439f8279 Simplify error message in case of delegating CNI error
This fix removes redundant error messages and try to simplify
if the error comes from delegating CNI plugins.
2020-04-30 18:02:05 +09:00
dougbtv
c8fc357f05 Adds development docs note regarding issue policy 2020-04-30 10:59:26 +09:00
dougbtv
92beb4bcdc Sets the Kubernetes API calls timeout to 60 seconds 2020-04-23 10:47:11 +09:00
dougbtv
931c12531d Allows namespaceIsolation to allow pods in any namespace refer to the default namespace 2020-04-22 09:08:11 +09:00
Doug Smith
8dba1f4a37 Merge pull request #487 from redhat-nfvpe/dev/test
Skip docker push action if REPOSITORY_PASS is not set
2020-04-21 08:56:08 -04:00
Tomofumi Hayashi
aeaf78a310 Skip docker push action if REPOSITORY_PASS is not set 2020-04-21 21:54:44 +09:00
Tomofumi Hayashi
ab073f88cd Add error message in case of unexpected situation
To troubleshooting #481, adds error message for further analysis.
2020-04-21 21:42:57 +09:00
Ted Yu
1df1e4f530 Check Pod parameter against nil before calling Eventf
Signed-off-by: Ted Yu <yuzhihong@gmail.com>
2020-04-21 00:12:36 +09:00
dougbtv
81297f5b74 Updates Dockerfile to golang 1.13 (specifying version) 2020-04-20 21:44:17 +09:00
dougbtv
3ddc6250de Fix pre 1.16 api version for CRDs 2020-04-17 17:10:20 +09:00
dougbtv
8fff5aac60 Add description fields to NetworkAttachmentDefinition CRD 2020-04-16 02:01:40 +09:00
Doug Smith
6ccf03e8b3 Merge pull request #473 from ashish-billore/master
Error log for network-attachment-definition
2020-04-02 09:46:00 -04:00
dougbtv
c0891354ff Adds readinessindicatorfile check on CNI DEL 2020-04-02 22:40:09 +09:00
ashish-billore
ea95133ef4 Error log for network-attachment-definition
Corrected the error for missing network-attachment-definition
updated test for this error.
2020-04-02 17:40:32 +09:00
Doug Smith
5931d24639 Merge pull request #469 from ashish-billore/patch-2
Update quickstart.md
2020-03-30 08:40:33 -04:00
Ashish Billore
055f74fc61 Update quickstart.md 2020-03-30 14:02:35 +09:00
Mamduh Alassi
14fb6be109 Use latest image version 3.4.1 in daemonset file 2020-03-27 00:21:21 +09:00
ICucos
b6bfb75af0 Daemonset for Google Kubernetes Engine for kubernetes cluster version pre 1.16. To be able to start cluster with version 1.15 i used "gcloud container clusters create cl-name --zone europe-west1-b --num-nodes=2 --machine-type=n1-standard-8 --image-type ubuntu --enable-network-policy --cluster-version=1.15.9-gke.24". !!!!important to start the cluster with --enable-network-policy that will enable CNI in kublet 2020-03-25 13:03:44 +02:00
Tomofumi Hayashi
7f50f5f175 Fix CI workflow 2020-03-23 23:49:05 +09:00
Doug Smith
ea72e56fab Merge pull request #462 from s1061123/dev/add-arm64v8-ci
Add arm64 build in CI workflow
2020-03-23 09:52:25 -04:00
Tomofumi Hayashi
055a7568ad Logging improvement (UID, net-attach-def)
This change adds pod UID and net-attach-def name in verbose log
and sends kubernetes event when net-attach-def is not found.
2020-03-23 21:32:33 +09:00
Tomofumi Hayashi
c7cd0ef822 Add arm64 build in CI workflow 2020-03-23 13:00:50 +09:00
Trevor Tao
f885b38332 Add Dockerfile for building image on arm64
Add Dockerfile.arm64 for building Multus image on arm64.

Actually it's multi-arch capable and works for
amd64 platform too if used.

Signed-off-by: Trevor Tao <trevor.tao@arm.com>
2020-03-19 22:41:27 +09:00
Trevor Tao
cd1a76f919 Add Dockerfile for building image on arm64
Add Dockerfile.arm64 for building Multus image on arm64.

Actually it's multi-arch capable and works for
amd64 platform too if used.

Signed-off-by: Trevor Tao <trevor.tao@arm.com>
2020-03-19 22:41:27 +09:00
Tomofumi Hayashi
079c853eba Add Kubernetes event log when the pod is launched 2020-03-16 22:08:03 +09:00
Tomofumi Hayashi
bfaf22964b Fix goreleaser file for build-release error 2020-03-16 21:58:41 +09:00
ICucos
1bc8064a5b Daemonset for Google Kubernetes Engine for kubernetes cluster version 1.16 +. To be able to start cluster with version 1.16 i used rapid channel "gcloud beta container clusters create cluster --zone europe-west1-b --num-nodes=1 --machine-type=n1-standard-8 --image-type ubuntu --enable-network-policy --release-channel=rapid --enable-autorepair" 2020-03-16 13:19:36 +02:00
Tomofumi Hayashi
eaf6ff6e20 Update vendor file to fix #426 2020-03-13 12:16:49 +09:00
Adrian Chiris
5577822b36 Pass DeviceID to each plugin in configuration list
Until today, it was hardcoded that DeviceID will only be
injected for the first CNI in the chain.

This commit modifies multus to pass DeviceID to each network
configuration element in a network configuration list.
This will  allow multiple CNI's to act on DeviceID when CNI
plugins are being chained for a specific network.

The change is required to allow CNI's to ensure network
isolation (introduced in kernel >= 5.2.0 see [1]) for RDMA devices
when exist.

e.g for SR-IOV network:
sriov-cni moves network device associated with the provided DeviceID
to to the container's network namespace.
An "RDMA cni" would do the same for the corresponding RDMA device when
RDMA traffic is desired on the network.

[1] https://patchwork.kernel.org/cover/10810451/
2020-03-12 23:48:03 +09:00
Periyasamy Palanisamy
32fe803221 Log message after logger initialization
In cmdCheck and cmdDelete debug messages are logged even before logger
is initialized with its log level and file (done in types.LoadNetConf).
Because of this those debug messages are not logged into the file.

Signed-off-by: Periyasamy Palanisamy <periyasamy.palanisamy@est.tech>
2020-03-05 23:48:15 +09:00
Doug Smith
1412caafbd Merge pull request #446 from s1061123/no-config-invalidation
Removes configuration invalidation
2020-03-02 10:08:45 -05:00
Tomofumi Hayashi
bdece11192 Removes configuration invalidation 2020-02-28 12:43:49 +09:00
Doug Smith
32952b929c Merge pull request #442 from s1061123/dev/kind-e2e
[WIP]Add e2e test with kind in CI pipeline
2020-02-20 09:35:25 -05:00
dougbtv
1042a5e25f Changes wait.ExponentialBackoff to wait.PollImmediate and exposes readinessindicatorfile via entrypoint parameter 2020-02-19 10:03:43 +09:00
dougbtv
9774ddade1 [docs] Updates quickstart to use alpine image 2020-02-13 17:09:37 +09:00
Tomofumi Hayashi
76c458228e Add e2e test with kind in CI pipeline 2020-02-13 17:02:22 +09:00
dougbtv
4fdaf3f427 [bugfix] Fixes unnecessary wait when readinessindicatorfile is not present 2020-02-13 01:04:28 +09:00
Tomofumi Hayashi
8334b73296 Add Github Actions for CI pipeline, to be replace with travis 2020-02-12 22:57:04 +09:00
groclawski
3e601c6ffe double word fix 2020-02-11 00:04:04 +09:00
Tomofumi Hayashi
9c35b5ccf2 Fix travis CI 2020-02-10 16:01:18 +09:00
Tomofumi Hayashi
da9da81be9 Fix travis ci error 2020-01-25 01:18:32 +09:00
Doug Smith
36f630fd39 Merge pull request #431 from s1061123/dev/container-march-images
Support container multi architecture image with manifest
2020-01-23 09:40:07 -05:00
Tomofumi Hayashi
dfd19e5b10 Support container multi architecture image with manifest 2020-01-21 02:48:10 +09:00
Doug Smith
c534b7d364 Uses atomic operation for writing config file (#430) 2020-01-17 16:10:46 -05:00
Michael C. Cambria
c35c4b7e97 Add CNI Check support (#427)
Add tests for CNI version 0.4.0
2020-01-13 09:57:21 -05:00
Tomofumi Hayashi
b2bf154328 Fix travis ci (#421)
This change update travis pipeline as following:
 - cleanup unused parameters/stages
 - add condition based on parameter (now user can use travis CI
   in cloned repo)
 - suppress ppc64 deployment because amd64 also build ppc images
   and other arch (fixes #418)
2019-12-11 15:41:36 -05:00
Tomofumi Hayashi
9874c14e23 Replace multus code with NPWG client library code 2019-12-10 14:38:09 +09:00
Tomofumi Hayashi
f4f2f65d1d Use NPWG client library to manipulate net-attach-defs
This change introduce NPWG client library functions to manipulate
net-attach-defs. This also requires to change k8sclient and unit
test code as well.
2019-12-10 14:38:09 +09:00
Shravan Vallala
cb3f59e7e7 Server URL in multus kubeconfig at /etc/cni/net.d/multus.d/multus.kubeconfig
is not properly setup for IPv6 installs

Fix:

If the API server host is IPv6 address then the server url should
include square braces to separate the IP address and port correctly
2019-12-10 09:09:37 +09:00
Shravan Vallala
a3712815fd Server URL in multus kubeconfig at
/etc/cni/net.d/multus.d/multus.kubeconfig is not properly setup for IPv6
installs

Fix:

If the API server host is IPv6 address then the server url should
include square braces to separate the IP address and port correctly
2019-12-10 09:09:37 +09:00
Doug Smith
230f314877 Bump daemonset tag to v3.4 (#417) 2019-12-03 12:38:10 -08:00
Tomofumi Hayashi
a314f90dda Fix unit test to track on updated error message 2019-11-15 08:31:49 -05:00
dougbtv
ecc474a264 Skips binary copy in entrypoint with new parameter 2019-11-07 23:24:04 +08:00
Dan Williams
c7f957194b multus: print pod namespace/name in cmdAdd/cmdDel error messages
Signed-off-by: Dan Williams <dcbw@redhat.com>
2019-11-06 10:04:47 -05:00
dougbtv
8c76fd62e0 Adds cursory unit test for default-route and cleans lint (and one errant test) 2019-10-29 13:34:24 -04:00
dougbtv
3a9dd7ed76 Properly uses default-route in annotation to set the gateway. Fixes network status results. 2019-10-29 13:34:24 -04:00
Tomofumi Hayashi
165e23b72c Support gateway in NetworkSelectionElement
Changes config JSON from gateway to default-route, adds Readme, fixes lint

Co-authored-by: dougbtv <dosmith@redhat.com>
2019-10-29 13:34:24 -04:00
Michal Rostecki
84c348ce18 build: Allow to define VERSION and COMMIT without git
Previously the build script required git to be used and installed which
did not allow to build Multus from a tarball which doesn't contain .git
directory. That made packaging of Multus hard.

Example usage after the change if you do not want to use git:

```
$ VERSION=v3.3 COMMIT=ba33df ./build
```

Signed-off-by: Michal Rostecki <mrostecki@opensuse.org>
2019-10-29 09:06:44 -04:00
Tomofumi Hayashi
8bdb7104d7 Update k8s npwg repo name due to its change 2019-10-29 09:06:27 -04:00
Tim Rozet
3fbfe40e12 Fixes K8sNetworkPlumbingWG package capitalization
Migrates package to use capitalized name, also cleans up dependencies.

Signed-off-by: Tim Rozet <trozet@redhat.com>
2019-10-21 10:42:49 -04:00
Tim Rozet
e8baccff16 Removes duplicate NetworkAttachment CRD ref
The CRD is now defined in the NetworkPlumbingWG org, along with
generated libs for client, listers, informers, and deep copy functions.
Therefore remove the duplicate definition here, and use the standard
definition.

Signed-off-by: Tim Rozet <trozet@redhat.com>
2019-10-21 10:42:49 -04:00
Tomofumi Hayashi
2745e46ed8 Support 'cni-args' in NetworkSelectionElement 2019-10-21 21:33:07 +09:00
Tomofumi Hayashi
adec211ae1 Support CNI RuntimeConfig for portmap/bandwidth/ip/mac
This changes introduce CNI RuntimeConfig for portmap, bandwidth,
ip and mac for latest specification. IP and Mac is previously
applied through CNI_ARGS, but it is changed to RuntimeConfig
for now.
2019-10-16 09:20:11 -04:00
Tomofumi Hayashi
0a2f7b18d3 Improve error/debug message
This diff changes error message with fixed format for easy-to-read
for users.
2019-10-10 10:32:45 -04:00
4703 changed files with 901418 additions and 265352 deletions

24
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,24 @@
on: [push, pull_request]
name: Build
jobs:
build:
strategy:
matrix:
go-version: [1.20.x, 1.21.x]
goarch: [386, amd64, arm, arm64, ppc64le, s390x]
os: [ubuntu-latest] #, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v4
- name: Build
env:
GOARCH: ${{ matrix.goarch }}
GOOS: ${{ matrix.goos }}
run: ./hack/build-go.sh

41
.github/workflows/codeql.yml vendored Normal file
View File

@@ -0,0 +1,41 @@
name: "CodeQL"
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
schedule:
- cron: "46 8 * * 0"
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ go ]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
queries: +security-and-quality
- name: Autobuild
uses: github/codeql-action/autobuild@v2
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{ matrix.language }}"

82
.github/workflows/image-build.yml vendored Normal file
View File

@@ -0,0 +1,82 @@
name: Image build
on: [pull_request]
jobs:
build-thin:
name: Image build thin plugin
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
# note: disable sbom/provenance for now (gchr.io does not managed well yet)
- name: Build container image
uses: docker/build-push-action@v5
with:
context: .
push: false
tags: ghcr.io/${{ github.repository }}:latest
file: images/Dockerfile
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/ppc64le,linux/s390x
sbom: false
provenance: false
# note: disable sbom/provenance for now (gchr.io does not managed well yet)
- name: Build container debug image
uses: docker/build-push-action@v5
with:
context: .
push: false
tags: ghcr.io/${{ github.repository }}:latest
file: images/Dockerfile.debug
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8,linux/ppc64le,linux/s390x
sbom: false
provenance: false
build-thick:
name: Image thick plugin
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build container image
uses: docker/build-push-action@v5
with:
context: .
push: false
tags: ghcr.io/${{ github.repository }}:latest-thick
file: images/Dockerfile.thick
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8,linux/ppc64le,linux/s390x
sbom: false
provenance: false
build-origin:
name: Image build/origin
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Download OKD Builder Dockerfile
run: curl https://raw.githubusercontent.com/okd-project/images/main/builder/Dockerfile -o images/okd-builder.Dockerfile
- name: Patch OKD Builder Dockerfile to workaround error
run: sed -i -e "s/yum install -y yum-utils/rpm --import \/etc\/pki\/rpm-gpg\/*;yum install -y yum-utils/" images/okd-builder.Dockerfile
- name: Create root for builder
run: mkdir root
- name: Organically build golang builder image
run: docker build -t local/okdbuilder:latest -f images/okd-builder.Dockerfile .
- name: Organically build Multus origin image
run: docker build -t local/multus-cni:latest-origin -f images/Dockerfile.openshift .

116
.github/workflows/image-push-master.yml vendored Normal file
View File

@@ -0,0 +1,116 @@
name: Image push for master
on:
push:
branches:
- master
env:
image-push-owner: 'k8snetworkplumbingwg'
jobs:
push-thick:
name: Image push thick image
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
if: ${{ github.repository_owner == env.image-push-owner }}
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Push container image for thick plugin
if: ${{ github.repository_owner == env.image-push-owner }}
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
ghcr.io/${{ github.repository }}:latest-thick
ghcr.io/${{ github.repository }}:snapshot-thick
file: images/Dockerfile.thick
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8,linux/ppc64le,linux/s390x
sbom: false
provenance: false
push-thin:
name: Image push thin image
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
if: ${{ github.repository_owner == env.image-push-owner }}
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Push thin container image
if: ${{ github.repository_owner == env.image-push-owner }}
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
ghcr.io/${{ github.repository }}:latest
ghcr.io/${{ github.repository }}:snapshot
file: images/Dockerfile
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8,linux/ppc64le,linux/s390x
sbom: false
provenance: false
- name: Push thin container debug image
if: ${{ github.repository_owner == env.image-push-owner }}
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
ghcr.io/${{ github.repository }}:latest-debug
ghcr.io/${{ github.repository }}:snapshot-debug
file: images/Dockerfile.debug
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8,linux/ppc64le,linux/s390x
sbom: false
provenance: false
# TODO: need to fix this action
# push-origin:
# name: Image push/origin
# runs-on: ubuntu-latest
# steps:
# - name: Check out code into the Go module directory
# uses: actions/checkout@v4
#
# - name: Set up Docker Buildx
# uses: docker/setup-buildx-action@v3
#
# - name: Login to GitHub Container Registry
# if: github.repository_owner == 'k8snetworkplumbingwg'
# uses: docker/login-action@v3
# with:
# registry: ghcr.io
# username: ${{ github.repository_owner }}
# password: ${{ secrets.GITHUB_TOKEN }}
#
# - name: Push container image
# if: github.repository_owner == 'k8snetworkplumbingwg'
# uses: docker/build-push-action@v5
# with:
# context: .
# push: true
# tags: |
# ghcr.io/${{ github.repository }}:latest-origin
# ghcr.io/${{ github.repository }}:snapshot-origin
# file: images/Dockerfile.openshift

138
.github/workflows/image-push-release.yml vendored Normal file
View File

@@ -0,0 +1,138 @@
name: Image push release
on:
push:
tags:
- v*
env:
image-push-owner: 'k8snetworkplumbingwg'
jobs:
push-thick:
name: Image push thick image
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
if: ${{ github.repository_owner == env.image-push-owner }}
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker meta
id: docker_meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
flavor: |
latest=false
- name: Push container image for thick plugin
if: ${{ github.repository_owner == env.image-push-owner }}
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
ghcr.io/${{ github.repository }}:stable-thick
${{ steps.docker_meta.outputs.tags }}-thick
file: images/Dockerfile.thick
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8,linux/ppc64le,linux/s390x
sbom: false
provenance: false
push-thin:
name: Image push thin image/amd64
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
if: ${{ github.repository_owner == env.image-push-owner }}
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker meta
id: docker_meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
flavor: |
latest=false
- name: Push thin container image
if: ${{ github.repository_owner == env.image-push-owner }}
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
ghcr.io/${{ github.repository }}:stable
${{ steps.docker_meta.outputs.tags }}
file: images/Dockerfile
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8,linux/ppc64le,linux/s390x
sbom: false
provenance: false
- name: Push thin container debug image
if: ${{ github.repository_owner == env.image-push-owner }}
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
ghcr.io/${{ github.repository }}:stable-debug
${{ steps.docker_meta.outputs.tags }}-debug
file: images/Dockerfile.debug
platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8,linux/ppc64le,linux/s390x
sbom: false
provenance: false
# TODO: need to fix this action
# push-origin:
# name: Image push/origin
# runs-on: ubuntu-latest
# steps:
# - name: Check out code into the Go module directory
# uses: actions/checkout@v4
#
# - name: Set up Docker Buildx
# uses: docker/setup-buildx-action@v3
#
# - name: Login to GitHub Container Registry
# if: github.repository_owner == 'k8snetworkplumbingwg'
# uses: docker/login-action@v3
# with:
# registry: ghcr.io
# username: ${{ github.repository_owner }}
# password: ${{ secrets.GITHUB_TOKEN }}
#
# - name: Docker meta
# id: docker_meta
# uses: crazy-max/ghaction-docker-meta@v1
# with:
# images: ghcr.io/${{ github.repository }}
# tag-latest: false
#
# - name: Push container image
# if: github.repository_owner == 'k8snetworkplumbingwg'
# uses: docker/build-push-action@v5
# with:
# context: .
# push: true
# tags: |
# ghcr.io/${{ github.repository }}:stable-origin
# ${{ steps.docker_meta.outputs.tags }}-origin
# file: images/Dockerfile.openshift

107
.github/workflows/kind-e2e.yml vendored Normal file
View File

@@ -0,0 +1,107 @@
name: e2e-kind
on: [push, pull_request]
jobs:
e2e-kind:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- docker-file: images/Dockerfile.thick
cni-version: "0.3.1"
multus-manifest: multus-daemonset-thick.yml
- docker-file: images/Dockerfile
cni-version: "0.3.1"
multus-manifest: multus-daemonset.yml
- docker-file: images/Dockerfile.thick
cni-version: "0.4.0"
multus-manifest: multus-daemonset-thick.yml
- docker-file: images/Dockerfile
cni-version: "0.4.0"
multus-manifest: multus-daemonset.yml
# need to wait kind to support CNI 1.0.0 (now kind 0.11 supports up to 0.4.0)
# - docker-file: images/Dockerfile.thick
# cni-version: "1.0.0"
# multus-manifest: multus-thick-daemonset.yml
# - docker-file: images/Dockerfile
# cni-version: "1.0.0"
# multus-manifest: multus-daemonset.yml
env:
JOB_NAME: "${{ matrix.cni-version }}-${{ matrix.multus-manifest }}"
if: >
(( github.event.pull_request.head.repo.owner.login != github.event.pull_request.base.repo.owner.login ) &&
github.event_name == 'pull_request' ) || (github.event_name == 'push' && github.event.commits != '[]' )
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Setup python
uses: actions/setup-python@v5
with:
python-version: 3.x
- name: Setup j2cli
run: |
sudo apt-get install -y j2cli
echo $(j2 --version)
- name: Build latest-amd64
uses: docker/build-push-action@v5
with:
context: .
load: true
tags: localhost:5000/multus:e2e
file: ${{ matrix.docker-file }}
platforms: linux/amd64
- name: Get kind/kubectl/koko
working-directory: ./e2e
run: ./get_tools.sh
- name: generate yaml files
working-directory: ./e2e
run: env CNI_VERSION=${{ matrix.cni-version }} ./generate_yamls.sh
- name: Setup cluster
working-directory: ./e2e
run: MULTUS_MANIFEST=${{ matrix.multus-manifest }} MULTUS_DOCKERFILE=none ./setup_cluster.sh
- name: Test simple pod
working-directory: ./e2e
run: ./test-simple-pod.sh
- name: Test macvlan1
working-directory: ./e2e
run: ./test-simple-macvlan1.sh
- name: Test static pod
working-directory: ./e2e
run: ./test-static-pod.sh
- name: Test default route1
working-directory: ./e2e
run: ./test-default-route1.sh
# - name: Test DRA integration
# working-directory: ./e2e
# run: ./test-dra-integration.sh
- name: Export kind logs
if: always()
run: |
mkdir -p /tmp/kind/logs
kind export logs --loglevel=debug /tmp/kind/logs
- name: Upload kind logs
if: always()
uses: actions/upload-artifact@v4
with:
name: kind-logs-${{ env.JOB_NAME }}-${{ github.run_id }}
path: /tmp/kind/logs
- name: cleanup cluster and registry
run: |
kind delete cluster

26
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,26 @@
name: Release binaries
on:
push:
tags:
- 'v*'
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: 1.19.x
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v5
with:
version: latest
args: release --rm-dist
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

15
.github/workflows/stale-issues-prs.yml vendored Normal file
View File

@@ -0,0 +1,15 @@
name: 'Close stale issues and PRs'
on:
schedule:
- cron: '30 1 * * *'
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
stale-issue-message: 'This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 7 days.'
stale-pr-message: 'This pull request is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 7 days.'
days-before-stale: 90
days-before-close: 7

48
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,48 @@
on: [push, pull_request]
name: Test
jobs:
test:
strategy:
matrix:
go-version: [1.20.x, 1.21.x]
os: [ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v4
- name: Run Revive Action by pulling pre-built image
uses: docker://morphy/revive-action:v2
with:
exclude: "./vendor/..."
- name: Run go fmt
run: go fmt ./...
#run: diff -u <(echo -n) <(gofmt -d -s .)
- name: Run go vet
run: go vet ./...
- name: Test
run: sudo ./hack/test-go.sh
- name: Send coverage
uses: shogo82148/actions-goveralls@v1
with:
path-to-profile: coverage.out
flag-name: Go-${{ matrix.go }}
parallel: true
# notifies that all test jobs are finished.
finish:
needs: test
runs-on: ubuntu-latest
steps:
- uses: shogo82148/actions-goveralls@v1
with:
parallel-finished: true

8
.gitignore vendored
View File

@@ -1,9 +1,17 @@
# Binary output dir
bin/
e2e/bin/
e2e/yamls/
e2e/repos/
# GOPATH created by the build script
gopath/
# Editor paths
.swp*
.swo*
.idea*
# Test outputs
*.out
*.test

View File

@@ -6,19 +6,53 @@ before:
hooks:
- go mod download
builds:
-
env:
- CGO_ENABLED=0
main: ./multus/
goos:
- linux
goarch:
- 386
- amd64
- arm
- arm64
archive:
wrap_in_directory: true
- env:
- CGO_ENABLED=0
id: multus
binary: multus
main: ./cmd/multus
goos:
- linux
goarch:
- 386
- amd64
- arm
- arm64
- s390x
ldflags:
- -X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.version={{ .Tag }} -X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.commit={{ .Commit }} -X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.date={{ .Date }}
- env:
- CGO_ENABLED=0
id: multus-daemon
binary: multus-daemon
main: ./cmd/multus-daemon
goos:
- linux
goarch:
- 386
- amd64
- arm
- arm64
- s390x
ldflags:
- -X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.version={{ .Tag }} -X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.commit={{ .Commit }} -X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.date={{ .Date }}
- env:
- CGO_ENABLED=0
id: multus-shim
binary: multus-shim
main: ./cmd/multus-shim
goos:
- linux
goarch:
- 386
- amd64
- arm
- arm64
- s390x
ldflags:
- -X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.version={{ .Tag }} -X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.commit={{ .Commit }} -X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.date={{ .Date }}
archives:
- wrap_in_directory: true
checksum:
name_template: 'checksums.txt'
snapshot:

View File

@@ -1,105 +0,0 @@
language: go
# see https://docs.travis-ci.com/user/reference/overview/#Virtualization-environments
# for the detail
# sudo: requried
dist: trusty
go:
- 1.12.x
env:
global:
- GO111MODULE=on
- REGISTRY_USER=${REGISTRY_USER}
- REGISTRY_PASS=${REGISTRY_PASS}
- secure: "${REGISTRY_SECURE}"
matrix:
- TARGET=amd64
- TARGET=ppc64le
before_install:
- sudo apt-get update -qq
- go get github.com/mattn/goveralls
install:
- go get -u golang.org/x/lint/golint
before_script:
# Make gopath... to run golint/go fmt/go vet
# Suppress golint for fixing lint later.
- golint ./... | grep -v vendor | grep -v ALL_CAPS | xargs -r false
- go fmt ./...
- go vet ./...
# - gocyclo -over 15 ./multus
script:
- GOARCH="${TARGET}" ./build
- |
if [ "${TARGET}" == "amd64" ]; then
sudo env PATH=${PATH} ./test.sh
goveralls -coverprofile=coverage.out -service=travis-ci
mkdir -p ${TRAVIS_BUILD_DIR}/dist
tar cvfz ${TRAVIS_BUILD_DIR}/dist/multus-cni_amd64.tar.gz --warning=no-file-changed --exclude="dist" .
docker build -t nfvpe/multus:latest-amd64 .
docker build -t nfvpe/multus:latest-ppc64le -f Dockerfile.ppc64le .
docker build -t nfvpe/multus-origin:latest -f Dockerfile.openshift .
fi
deploy:
# Release on versioned tag (e.g. v1.0)
- provider: script
#skip_cleanup: true
script: curl -sL https://git.io/goreleaser | bash
on:
tags: true
all_branches: true
condition: "$TRAVIS_TAG =~ ^v[0-9].*$"
# Push images to Dockerhub on tag
- provider: script
skip_cleanup: true
script: >
bash -c '
docker tag nfvpe/multus:latest-amd64 nfvpe/multus:latest;
docker tag nfvpe/multus:latest-amd64 nfvpe/multus:stable;
docker tag nfvpe/multus:latest-amd64 nfvpe/multus:stable-amd64;
docker tag nfvpe/multus:latest-amd64 nfvpe/multus:$TRAVIS_TAG;
docker tag nfvpe/multus:latest-ppc64le nfvpe/multus:stable-ppc64le;
docker login -u "$REGISTRY_USER" -p "$REGISTRY_PASS";
docker push nfvpe/multus:latest;
docker push nfvpe/multus:latest-amd64;
docker push nfvpe/multus:latest-ppc64le;
docker push nfvpe/multus:stable;
docker push nfvpe/multus:stable-amd64;
docker push nfvpe/multus:stable-ppc64le;
docker push nfvpe/multus:$TRAVIS_TAG;
echo done'
on:
tags: true
all_branches: true
condition: "$TRAVIS_TAG =~ ^v[0-9].*$"
# Push images to Dockerhub on merge to master
- provider: script
on:
branch: master
script: >
bash -c '
docker tag nfvpe/multus:latest-amd64 nfvpe/multus:snapshot;
docker tag nfvpe/multus:latest-amd64 nfvpe/multus:snapshot-amd64;
docker tag nfvpe/multus:latest-ppc64le nfvpe/multus:snapshot-ppc64le;
docker login -u "$REGISTRY_USER" -p "$REGISTRY_PASS";
docker push nfvpe/multus:snapshot;
docker push nfvpe/multus:snapshot-amd64;
docker push nfvpe/multus:snapshot-ppc64le;
docker push nfvpe/multus:latest;
docker push nfvpe/multus:latest-amd64;
docker push nfvpe/multus:latest-ppc64le;
echo done'
after_success:
# put build tgz to bintray
- curl -T ${TRAVIS_BUILD_DIR}/dist/multus-cni_amd64.tar.gz -u${BINTRAY_USER}:${BINTRAY_APIKEY} https://api.bintray.com/content/redhat-nfvpe/multus-cni-crd-snapshots/snapshot/snapshot-${TRAVIS_COMMIT}/multus-cni_amd64-${TRAVIS_COMMIT}.tar.gz
# publish uploaded file
- curl -X POST -u${BINTRAY_USER}:${BINTRAY_APIKEY} https://api.bintray.com/content/redhat-nfvpe/multus-cni-crd-snapshots/snapshot/snapshot-${TRAVIS_COMMIT}/publish
# put it in bintray download list
- sleep 20
- "curl -X PUT -H 'Accept: application/json' -H 'Content-type: application/json' -u${BINTRAY_USER}:${BINTRAY_APIKEY} https://api.bintray.com/file_metadata/redhat-nfvpe/multus-cni-crd-snapshots/multus-cni_amd64-${TRAVIS_COMMIT}.tar.gz -d '{\"list_in_downloads\":true}'"

130
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,130 @@
# Multus CNI Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
[The Multus Slack Page](https://intel-corp.herokuapp.com/).
All complaints will be reviewed and investigated promptly and fairly. Or you
may specifically contact Doug Smith (dosmith@redhat.com) via email.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

View File

@@ -1,20 +0,0 @@
# This Dockerfile is used to build the image available on DockerHub
FROM centos:centos7 as build
# Add everything
ADD . /usr/src/multus-cni
ENV INSTALL_PKGS "git golang"
RUN rpm --import https://mirror.go-repo.io/centos/RPM-GPG-KEY-GO-REPO && \
curl -s https://mirror.go-repo.io/centos/go-repo.repo | tee /etc/yum.repos.d/go-repo.repo && \
yum install -y $INSTALL_PKGS && \
rpm -V $INSTALL_PKGS && \
cd /usr/src/multus-cni && \
./build
FROM centos:centos7
COPY --from=build /usr/src/multus-cni /usr/src/multus-cni
WORKDIR /
ADD ./images/entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]

View File

@@ -1,20 +0,0 @@
# This dockerfile is specific to building Multus for OpenShift
FROM openshift/origin-release:golang-1.10 as builder
ADD . /usr/src/multus-cni
WORKDIR /usr/src/multus-cni
ENV GO111MODULE=off
RUN ./build
FROM openshift/origin-base
RUN mkdir -p /usr/src/multus-cni/images && mkdir -p /usr/src/multus-cni/bin
COPY --from=builder /usr/src/multus-cni/bin/multus /usr/src/multus-cni/bin
ADD ./images/entrypoint.sh /
LABEL io.k8s.display-name="Multus CNI" \
io.k8s.description="This is a component of OpenShift Container Platform and provides a meta CNI plugin." \
io.openshift.tags="openshift" \
maintainer="Doug Smith <dosmith@redhat.com>"
ENTRYPOINT ["/entrypoint.sh"]

View File

@@ -1,25 +0,0 @@
# This Dockerfile is used to build the image available on DockerHub
FROM centos:centos7 as build
# Add everything
ADD . /usr/src/multus-cni
ENV GOARCH "ppc64le"
ENV GOOS "linux"
ENV INSTALL_PKGS "git golang"
RUN rpm --import https://mirror.go-repo.io/centos/RPM-GPG-KEY-GO-REPO && \
curl -s https://mirror.go-repo.io/centos/go-repo.repo | tee /etc/yum.repos.d/go-repo.repo && \
yum install -y $INSTALL_PKGS && \
rpm -V $INSTALL_PKGS && \
cd /usr/src/multus-cni && \
./build
# build ppc container
FROM ppc64le/centos:latest
COPY --from=build /usr/src/multus-cni /usr/src/multus-cni
WORKDIR /
ADD ./images/entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]

2
NOTICE Normal file
View File

@@ -0,0 +1,2 @@
Copyright 2016 Intel Corporation
Copyright 2021 Multus Authors

View File

@@ -1,8 +1,8 @@
# Multus-CNI
![multus-cni Logo](https://github.com/intel/multus-cni/blob/master/doc/images/Multus.png)
![multus-cni Logo](https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/docs/images/Multus.png)
[![Travis CI](https://travis-ci.org/intel/multus-cni.svg?branch=master)](https://travis-ci.org/intel/multus-cni/builds)[![Go Report Card](https://goreportcard.com/badge/github.com/intel/multus-cni)](https://goreportcard.com/report/github.com/intel/multus-cni)[![Coverage Status](https://coveralls.io/repos/github/intel/multus-cni/badge.svg)](https://coveralls.io/github/intel/multus-cni)
[![Build](https://github.com/k8snetworkplumbingwg/multus-cni/actions/workflows/build.yml/badge.svg)](https://github.com/k8snetworkplumbingwg/multus-cni/actions/workflows/build.yml)[![Test](https://github.com/k8snetworkplumbingwg/multus-cni/actions/workflows/test.yml/badge.svg)](https://github.com/k8snetworkplumbingwg/multus-cni/actions/workflows/test.yml)[![Go Report Card](https://goreportcard.com/badge/github.com/k8snetworkplumbingwg/multus-cni)](https://goreportcard.com/report/github.com/k8snetworkplumbingwg/multus-cni)[![Coverage Status](https://coveralls.io/repos/github/k8snetworkplumbingwg/multus-cni/badge.svg)](https://coveralls.io/github/k8snetworkplumbingwg/multus-cni)
Multus CNI enables attaching multiple network interfaces to pods in Kubernetes.
@@ -18,34 +18,49 @@ Multus is one of the projects in the [Baremetal Container Experience kit](https:
Here's an illustration of the network interfaces attached to a pod, as provisioned by Multus CNI. The diagram shows the pod with three interfaces: `eth0`, `net0` and `net1`. `eth0` connects kubernetes cluster network to connect with kubernetes server/services (e.g. kubernetes api-server, kubelet and so on). `net0` and `net1` are additional network attachments and connect to other networks by using [other CNI plugins](https://kubernetes.io/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/) (e.g. vlan/vxlan/ptp).
![multus-pod-image](doc/images/multus-pod-image.svg)
![multus-pod-image](docs/images/multus-pod-image.svg)
## Quickstart Installation Guide
The quickstart installation method for Multus requires that you have first installed a Kubernetes CNI plugin to serve as your pod-to-pod network, which we refer to as your "default network" (a network interface that every pod will be creatd with). Each network attachment created by Multus will be in addition to this default network interface. For more detail on installing a default network CNI plugins, refer to our [quick-start guide](doc/quickstart.md).
The quickstart installation method for Multus requires that you have first installed a Kubernetes CNI plugin to serve as your pod-to-pod network, which we refer to as your "default network" (a network interface that every pod will be created with). Each network attachment created by Multus will be in addition to this default network interface. For more detail on installing a default network CNI plugin, refer to our [quick-start guide](docs/quickstart.md).
Clone this GitHub repository, we'll apply a daemonset which installs Multus using to `kubectl` from this repo. From the root directory of the clone, apply the daemonset YAML file:
To use latest features try command below which applies a daemonset and installs thick Multus using `kubectl`:
```
$ cat ./images/multus-daemonset.yml | kubectl apply -f -
kubectl apply -f https://raw.githubusercontent.com/k8snetworkplumbingwg/multus-cni/master/deployments/multus-daemonset-thick.yml
```
This will configure your systems to be ready to use Multus CNI, but, to get started with adding additional interfaces to your pods, refer to our complete [quick-start guide](doc/quickstart.md)
This will configure your systems to be ready to use Multus CNI, but, to get started with adding additional interfaces to your pods, refer to our complete [quick-start guide](docs/quickstart.md)
## Additional installation Options
## Thin Plugin v.s Thick Plugin
- Install via daemonset using the quick-start guide, above.
- Download binaries from [release page](https://github.com/intel/multus-cni/releases)
- By Docker image from [Docker Hub](https://hub.docker.com/r/nfvpe/multus/tags/)
- Or, roll-you-own and build from source
- See [Development](doc/development.md)
With the multus 4.0 release, we introduce a new client/server-style plugin deployment. This new deployment is called ['thick plugin'](docs/thick-plugin.md), in contrast to deployments in previous versions, which is now called a 'thin plugin'. The new thick plugin consists of two binaries, multus-daemon and multus-shim CNI plugin. The 'multus-daemon' will be deployed to all nodes as a local agent and supports additional features, such as metrics, which were not available with the 'thin plugin' deployment before. Due to these additional features, the 'thick plugin' comes with the trade-off of consuming more resources than the 'thin plugin'.
We recommend using the thick plugin in most environments, but if you wish to run the thin plugin, or are in a resource-constrained environment, you may do so with:
```
kubectl apply -f https://raw.githubusercontent.com/k8snetworkplumbingwg/multus-cni/master/deployments/multus-daemonset.yml
```
## Additional Installation Options
In addition to the [quick-start guide](docs/quickstart.md), you may:
- Download binaries from [release page](https://github.com/k8snetworkplumbingwg/multus-cni/releases)
- By Docker image from [GitHub Container Registry](https://github.com/orgs/k8snetworkplumbingwg/packages/container/package/multus-cni)
- Or, roll-your-own and build from source
- See [Development](docs/development.md)
## Comprehensive Documentation
- [How to use](doc/how-to-use.md)
- [Configuration](doc/configuration.md)
- [Development](doc/development.md)
- [How to use](docs/how-to-use.md)
- [Quick Start Guide](docs/quickstart.md)
- [Configuration](docs/configuration.md)
- [Development and Support Information](docs/development.md)
- [Thick Plugin](docs/thick-plugin.md)
## Contact Us
For any questions about Multus CNI, feel free to ask a question in #general in the [Intel-Corp Slack](https://intel-corp.herokuapp.com/), or open up a GitHub issue.
For any questions about Multus CNI, open up a GitHub issue or feel free to ask a question in #general in the [NPWG Slack](https://npwg-team.slack.com/).
To be invited, use [this slack invite link](https://join.slack.com/t/npwg-team/shared_invite/zt-1u2vmsn2b-tKdOokdPY73zn9B32JoAOg).

48
build
View File

@@ -1,48 +0,0 @@
#!/usr/bin/env bash
set -e
DEST_DIR="bin"
if [ ! -d ${DEST_DIR} ]; then
mkdir ${DEST_DIR}
fi
# Add version/commit/date into binary
# In case of TravisCI, need to check error code of 'git describe'.
set +e
git describe --tags --abbrev=0 > /dev/null 2>&1
if [ "$?" != "0" ]; then
VERSION="master"
else
VERSION=$(git describe --tags --abbrev=0)
fi
set -e
DATE=$(date --iso-8601=seconds)
COMMIT=$(git rev-parse --verify HEAD)
LDFLAGS="-X main.version=${VERSION:-master} -X main.commit=${COMMIT} -X main.date=${DATE}"
export CGO_ENABLED=0
# this if... will be removed when gomodules goes default
if [ "$GO111MODULE" == "off" ]; then
echo "Building plugin without go module"
echo "Warning: this will be deprecated in near future so please use go modules!"
ORG_PATH="github.com/intel"
REPO_PATH="${ORG_PATH}/multus-cni"
if [ ! -h gopath/src/${REPO_PATH} ]; then
mkdir -p gopath/src/${ORG_PATH}
ln -s ../../../.. gopath/src/${REPO_PATH} || exit 255
fi
export GO15VENDOREXPERIMENT=1
export GOBIN=${PWD}/bin
export GOPATH=${PWD}/gopath
go install -tags no_openssl -ldflags "${LDFLAGS}" "$@" ${REPO_PATH}/multus
else
# build with go modules
export GO111MODULE=on
echo "Building plugins"
go build -o ${DEST_DIR}/multus -tags no_openssl -ldflags "${LDFLAGS}" "$@" ./multus
fi

View File

@@ -1,110 +0,0 @@
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package checkpoint
import (
"encoding/json"
"io/ioutil"
"github.com/intel/multus-cni/logging"
"github.com/intel/multus-cni/types"
v1 "k8s.io/api/core/v1"
)
const (
checkPointfile = "/var/lib/kubelet/device-plugins/kubelet_internal_checkpoint"
)
// PodDevicesEntry maps PodUID, resource name and allocated device id
type PodDevicesEntry struct {
PodUID string
ContainerName string
ResourceName string
DeviceIDs []string
AllocResp []byte
}
type checkpointData struct {
PodDeviceEntries []PodDevicesEntry
RegisteredDevices map[string][]string
}
type checkpointFileData struct {
Data checkpointData
Checksum uint64
}
type checkpoint struct {
fileName string
podEntires []PodDevicesEntry
}
// GetCheckpoint returns an instance of Checkpoint
func GetCheckpoint() (types.ResourceClient, error) {
logging.Debugf("GetCheckpoint(): invoked")
return getCheckpoint(checkPointfile)
}
func getCheckpoint(filePath string) (types.ResourceClient, error) {
cp := &checkpoint{fileName: filePath}
err := cp.getPodEntries()
if err != nil {
return nil, err
}
logging.Debugf("getCheckpoint(): created checkpoint instance with file: %s", filePath)
return cp, nil
}
// getPodEntries gets all Pod device allocation entries from checkpoint file
func (cp *checkpoint) getPodEntries() error {
cpd := &checkpointFileData{}
rawBytes, err := ioutil.ReadFile(cp.fileName)
if err != nil {
return logging.Errorf("getPodEntries(): error reading file %s\n%v\n", checkPointfile, err)
}
if err = json.Unmarshal(rawBytes, cpd); err != nil {
return logging.Errorf("getPodEntries(): error unmarshalling raw bytes %v", err)
}
cp.podEntires = cpd.Data.PodDeviceEntries
logging.Debugf("getPodEntries(): podEntires %+v", cp.podEntires)
return nil
}
// GetComputeDeviceMap returns an instance of a map of ResourceInfo
func (cp *checkpoint) GetPodResourceMap(pod *v1.Pod) (map[string]*types.ResourceInfo, error) {
podID := string(pod.UID)
resourceMap := make(map[string]*types.ResourceInfo)
if podID == "" {
return nil, logging.Errorf("GetPodResourceMap(): invalid Pod cannot be empty")
}
for _, pod := range cp.podEntires {
if pod.PodUID == podID {
entry, ok := resourceMap[pod.ResourceName]
if ok {
// already exists; append to it
entry.DeviceIDs = append(entry.DeviceIDs, pod.DeviceIDs...)
} else {
// new entry
resourceMap[pod.ResourceName] = &types.ResourceInfo{DeviceIDs: pod.DeviceIDs}
}
}
}
return resourceMap, nil
}

371
cmd/cert-approver/main.go Normal file
View File

@@ -0,0 +1,371 @@
// Copyright (c) 2023 Network Plumbing Working Group
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This is Kubernetes controller which approves CSR submitted by multus.
// This command is required only if multus runs with per-node certificate.
package main
// Note: cert-approver should be simple, just approve multus' CSR, hence
// this go code should not have any dependencies from pkg/, if possible,
// to keep its code simplicity.
import (
"context"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"os/signal"
"reflect"
"strings"
"syscall"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/apimachinery/pkg/util/wait"
certificatesv1 "k8s.io/api/certificates/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/klog/v2"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/certificate/csr"
"k8s.io/client-go/util/workqueue"
)
// CertController object
type CertController struct {
clientset kubernetes.Interface
queue workqueue.RateLimitingInterface
informer cache.SharedIndexInformer
broadcaster record.EventBroadcaster
recorder record.EventRecorder
commonNamePrefixes string
}
const (
maxDuration = time.Hour * 24 * 365
resyncPeriod time.Duration = time.Second * 3600 // resync every one hour, default is 10 hour
maxRetries = 5
)
var (
// ControllerName provides controller name
ControllerName = "csr-approver"
// NamePrefix specifies which name in certification request should be target to approve
NamePrefix = "system:multus"
// Organization specifies which org in certification request should be target to approve
Organization = []string{"system:multus"}
// Groups specifies which group in certification request should be target to approve
Groups = sets.New[string]("system:nodes", "system:multus", "system:authenticated")
// UserPrefixes specifies which name prefix in certification request should be target to approve
UserPrefixes = sets.New[string]("system:node", NamePrefix)
// Usages specifies which usage in certification request should be target to approve
Usages = sets.New[certificatesv1.KeyUsage](
certificatesv1.UsageDigitalSignature,
certificatesv1.UsageClientAuth)
)
// NewCertController creates certcontroller
func NewCertController() (*CertController, error) {
var clientset kubernetes.Interface
// setup Kubernetes API client
config, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
clientset, err = kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
informer := cache.NewSharedIndexInformer(
cache.NewListWatchFromClient(
clientset.CertificatesV1().RESTClient(),
"certificatesigningrequests", corev1.NamespaceAll, fields.Everything()),
&certificatesv1.CertificateSigningRequest{},
resyncPeriod,
nil)
broadcaster := record.NewBroadcaster()
broadcaster.StartLogging(klog.Infof)
broadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: clientset.CoreV1().Events("")})
recorder := broadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: "cert-approver"})
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
c := &CertController{
clientset: clientset,
informer: informer,
queue: queue,
commonNamePrefixes: NamePrefix,
broadcaster: broadcaster,
recorder: recorder,
}
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
if csr, ok := obj.(*certificatesv1.CertificateSigningRequest); ok {
if c.filterCSR(csr) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
}
}
},
})
return c, nil
}
// Run starts controller
func (c *CertController) Run(stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer c.queue.ShutDown()
klog.Info("Starting cert approver")
go c.informer.Run(stopCh)
if !cache.WaitForCacheSync(stopCh, c.HasSynced) {
utilruntime.HandleError(fmt.Errorf("Timed out waiting for caches to sync"))
return
}
klog.Info("cert approver synced and ready")
wait.Until(c.runWorker, time.Second, stopCh)
}
// HasSynced is required for the cache.Controller interface.
func (c *CertController) HasSynced() bool {
return c.informer.HasSynced()
}
// LastSyncResourceVersion is required for the cache.Controller interface.
func (c *CertController) LastSyncResourceVersion() string {
return c.informer.LastSyncResourceVersion()
}
func (c *CertController) runWorker() {
for c.processNextItem() {
// continue looping
}
}
func (c *CertController) processNextItem() bool {
// Wait until there is a new item in the working queue
key, quit := c.queue.Get()
if quit {
return false
}
// Tell the queue that we are done with processing this key. This unblocks the key for other workers
// This allows safe parallel processing because two pods with the same key are never processed in
// parallel.
defer c.queue.Done(key)
// Invoke the method containing the business logic
err := c.processItem(key.(string))
// Handle the error if something went wrong during the execution of the business logic
c.handleErr(err, key)
return true
}
// handleErr checks if an error happened and makes sure we will retry later.
func (c *CertController) handleErr(err error, key interface{}) {
if err == nil {
// Forget about the #AddRateLimited history of the key on every successful synchronization.
// This ensures that future processing of updates for this key is not delayed because of
// an outdated error history.
c.queue.Forget(key)
return
}
// This controller retries 5 times if something goes wrong. After that, it stops trying.
if c.queue.NumRequeues(key) < maxRetries {
klog.Infof("Error syncing csr %s: %v", key, err)
// Re-enqueue the key rate limited. Based on the rate limiter on the
// queue and the re-enqueue history, the key will be processed later again.
c.queue.AddRateLimited(key)
return
}
c.queue.Forget(key)
// Report to an external entity that, even after several retries, we could not successfully process this key
utilruntime.HandleError(err)
klog.Infof("Dropping csr %q out of the queue: %v", key, err)
}
func (c *CertController) processItem(key string) error {
startTime := time.Now()
obj, _, err := c.informer.GetIndexer().GetByKey(key)
if err != nil {
return fmt.Errorf("Error fetching object with key %s from store: %v", key, err)
}
req, _ := obj.(*certificatesv1.CertificateSigningRequest)
nodeName := "unknown"
defer func() {
klog.Infof("Finished syncing CSR %s for %s node in %v", req.Name, nodeName, time.Since(startTime))
}()
if len(req.Status.Certificate) > 0 {
klog.V(5).Infof("CSR %s is already signed", req.Name)
return nil
}
if isApprovedOrDenied(&req.Status) {
klog.V(5).Infof("CSR %s is already approved/denied", req.Name)
return nil
}
csrPEM, _ := pem.Decode(req.Spec.Request)
if csrPEM == nil {
return fmt.Errorf("failed to PEM-parse the CSR block in .spec.request: no CSRs were found")
}
x509CSR, err := x509.ParseCertificateRequest(csrPEM.Bytes)
if err != nil {
return fmt.Errorf("failed to parse the CSR bytes: %v", err)
}
i := strings.LastIndex(req.Spec.Username, ":")
if i == -1 || i == len(req.Spec.Username)-1 {
return fmt.Errorf("failed to parse the username: %s", req.Spec.Username)
}
ctx := context.Background()
prefix := req.Spec.Username[:i]
nodeName = req.Spec.Username[i+1:]
if !UserPrefixes.Has(prefix) {
return c.denyCSR(ctx, req, fmt.Sprintf("CSR %q was created by an unexpected user: %q", req.Name, req.Spec.Username))
}
if errs := validation.IsDNS1123Subdomain(nodeName); len(errs) != 0 {
return c.denyCSR(ctx, req, fmt.Sprintf("extracted node name %q is not a valid DNS subdomain %v", nodeName, errs))
}
if usages := sets.New[certificatesv1.KeyUsage](req.Spec.Usages...); !usages.Equal(Usages) {
return c.denyCSR(ctx, req, fmt.Sprintf("CSR %q was created with unexpected usages: %v", req.Name, usages.UnsortedList()))
}
if !Groups.HasAll(req.Spec.Groups...) {
return c.denyCSR(ctx, req, fmt.Sprintf("CSR %q was created by a user with unexpected groups: %v", req.Name, req.Spec.Groups))
}
expectedSubject := fmt.Sprintf("%s:%s", c.commonNamePrefixes, nodeName)
if x509CSR.Subject.CommonName != expectedSubject {
return c.denyCSR(ctx, req, fmt.Sprintf("expected the CSR's commonName to be %q, but it is %q", expectedSubject, x509CSR.Subject.CommonName))
}
if !reflect.DeepEqual(x509CSR.Subject.Organization, Organization) {
return c.denyCSR(ctx, req, fmt.Sprintf("expected the CSR's organization to be %v, but it is %v", Organization, x509CSR.Subject.Organization))
}
if req.Spec.ExpirationSeconds == nil {
return c.denyCSR(ctx, req, fmt.Sprintf("CSR %q was created without specyfying the expirationSeconds", req.Name))
}
if csr.ExpirationSecondsToDuration(*req.Spec.ExpirationSeconds) > maxDuration {
return c.denyCSR(ctx, req, fmt.Sprintf("CSR %q was created with invalid expirationSeconds value: %d", req.Name, *req.Spec.ExpirationSeconds))
}
return c.approveCSR(ctx, req)
}
// CSR specific functions
func (c *CertController) filterCSR(csr *certificatesv1.CertificateSigningRequest) bool {
nsName := types.NamespacedName{Namespace: csr.Namespace, Name: csr.Name}
csrPEM, _ := pem.Decode(csr.Spec.Request)
if csrPEM == nil {
klog.Errorf("Failed to PEM-parse the CSR block in .spec.request: no CSRs were found in %s", nsName)
return false
}
x509CSR, err := x509.ParseCertificateRequest(csrPEM.Bytes)
if err != nil {
klog.Errorf("Failed to parse the CSR .spec.request of %q: %v", nsName, err)
return false
}
return strings.HasPrefix(x509CSR.Subject.CommonName, c.commonNamePrefixes) &&
csr.Spec.SignerName == certificatesv1.KubeAPIServerClientSignerName
}
func (c *CertController) approveCSR(ctx context.Context, csr *certificatesv1.CertificateSigningRequest) error {
csr.Status.Conditions = append(csr.Status.Conditions,
certificatesv1.CertificateSigningRequestCondition{
Type: certificatesv1.CertificateApproved,
Status: corev1.ConditionTrue,
Reason: "AutoApproved",
Message: fmt.Sprintf("Auto-approved CSR %q", csr.Name),
})
c.recorder.Eventf(csr, corev1.EventTypeNormal, "CSRApproved", "CSR %q has been approved by %s", csr.Name, ControllerName)
_, err := c.clientset.CertificatesV1().CertificateSigningRequests().UpdateApproval(ctx, csr.Name, csr, metav1.UpdateOptions{})
return err
}
func (c *CertController) denyCSR(ctx context.Context, csr *certificatesv1.CertificateSigningRequest, message string) error {
csr.Status.Conditions = append(csr.Status.Conditions,
certificatesv1.CertificateSigningRequestCondition{
Type: certificatesv1.CertificateDenied,
Status: corev1.ConditionTrue,
Reason: "CSRDenied",
Message: message,
},
)
c.recorder.Eventf(csr, corev1.EventTypeWarning, "CSRDenied", "The CSR %q has been denied by: %s", csr.Name, ControllerName, message)
_, err := c.clientset.CertificatesV1().CertificateSigningRequests().Update(ctx, csr, metav1.UpdateOptions{})
return err
}
func isApprovedOrDenied(status *certificatesv1.CertificateSigningRequestStatus) bool {
for _, c := range status.Conditions {
if c.Type == certificatesv1.CertificateApproved || c.Type == certificatesv1.CertificateDenied {
return true
}
}
return false
}
func main() {
klog.Infof("starting cert-approver")
// Start watching for pod creations
certController, err := NewCertController()
if err != nil {
klog.Fatal(err)
}
stopCh := make(chan struct{})
defer close(stopCh)
go certController.Run(stopCh)
sigterm := make(chan os.Signal, 1)
signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
<-sigterm
}

View File

@@ -0,0 +1,56 @@
// Copyright (c) 2023 Multus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This is a install tool for multus plugins
package main
import (
"fmt"
"os"
"github.com/spf13/pflag"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/cmdutils"
)
func main() {
typeFlag := pflag.StringP("type", "t", "", "specify installer type (thick/thin)")
destDir := pflag.StringP("dest-dir", "d", "/host/opt/cni/bin", "destination directory")
helpFlag := pflag.BoolP("help", "h", false, "show help message and quit")
pflag.Parse()
if *helpFlag {
pflag.PrintDefaults()
os.Exit(1)
}
multusFileName := ""
switch *typeFlag {
case "thick":
multusFileName = "multus-shim"
case "thin":
multusFileName = "multus"
default:
fmt.Fprintf(os.Stderr, "--type is missing or --type has invalid value\n")
os.Exit(1)
}
err := cmdutils.CopyFileAtomic(fmt.Sprintf("/usr/src/multus-cni/bin/%s", multusFileName), *destDir, fmt.Sprintf("%s.temp", multusFileName), multusFileName)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to copy file %s: %v\n", multusFileName, err)
os.Exit(1)
}
fmt.Printf("multus %s copy succeeded!\n", multusFileName)
}

View File

@@ -0,0 +1,145 @@
// Copyright (c) 2023 Multus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This binary submit CSR for kube controll access for multus thin plugin
// and generate Kubeconfig
package main
import (
"encoding/base64"
"fmt"
"os"
"os/signal"
"path/filepath"
"syscall"
"text/template"
"time"
"github.com/spf13/pflag"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/k8sclient"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog/v2"
)
var kubeConfigTemplate = `apiVersion: v1
clusters:
- cluster:
certificate-authority-data: {{.CADATA}}
server: {{.K8S_APISERVER}}
name: default-cluster
contexts:
- context:
cluster: default-cluster
namespace: default
user: default-auth
name: default-context
current-context: default-context
kind: Config
preferences: {}
users:
- name: default-auth
user:
client-certificate: {{.CERTDIR}}/multus-client-current.pem
client-key: {{.CERTDIR}}/multus-client-current.pem
`
func main() {
certDir := pflag.StringP("certdir", "", "/tmp", "specify cert directory")
bootstrapConfig := pflag.StringP("bootstrap-config", "", "/tmp/kubeconfig", "specify bootstrap kubernetes config")
kubeconfigPathRaw := pflag.StringP("kubeconfig", "", "/run/multus/kubeconfig", "specify output kubeconfig path")
certDurationString := pflag.StringP("cert-duration", "", "10m", "specify certificate duration")
helpFlag := pflag.BoolP("help", "h", false, "show help message and quit")
kubeconfigPath, err := filepath.Abs(*kubeconfigPathRaw)
if err != nil {
klog.Fatalf("illegal path %s in kubeconfigPath %s: %v", kubeconfigPath, *kubeconfigPathRaw, err)
}
pflag.Parse()
if *helpFlag {
pflag.PrintDefaults()
os.Exit(1)
}
// check variables
if _, err := os.Stat(*bootstrapConfig); err != nil {
klog.Fatalf("failed to read bootstrap config %q", *bootstrapConfig)
}
st, err := os.Stat(*certDir)
if err != nil {
klog.Fatalf("failed to find cert directory %q", *certDir)
}
if !st.IsDir() {
klog.Fatalf("cert directory %q is not directory", *certDir)
}
certDuration, err := time.ParseDuration(*certDurationString)
if err != nil {
klog.Fatalf("failed to parse duration %q: %v", *certDurationString, err)
}
nodeName := os.Getenv("MULTUS_NODE_NAME")
if nodeName == "" {
klog.Fatalf("cannot identify node name from MULTUS_NODE_NAME env variables")
}
// retrieve API server from bootstrapConfig()
config, err := clientcmd.BuildConfigFromFlags("", *bootstrapConfig)
if err != nil {
klog.Fatalf("cannot get in-cluster config: %v", err)
}
apiServer := fmt.Sprintf("%s%s", config.Host, config.APIPath)
caData := base64.StdEncoding.EncodeToString(config.CAData)
// run certManager to create certification
if _, err = k8sclient.PerNodeK8sClient(nodeName, *bootstrapConfig, certDuration, *certDir); err != nil {
klog.Fatalf("failed to start cert manager: %v", err)
}
fp, err := os.OpenFile(kubeconfigPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
klog.Fatalf("cannot create kubeconfig file %q: %v", kubeconfigPath, err)
}
// render kubeconfig
templateKubeconfig, err := template.New("kubeconfig").Parse(kubeConfigTemplate)
if err != nil {
klog.Fatalf("template parse error: %v", err)
}
templateData := map[string]string{
"CADATA": caData,
"CERTDIR": *certDir,
"K8S_APISERVER": apiServer,
}
// genearate kubeconfig from template
if err = templateKubeconfig.Execute(fp, templateData); err != nil {
klog.Fatalf("cannot create kubeconfig: %v", err)
}
if err = fp.Close(); err != nil {
klog.Fatalf("cannot save kubeconfig: %v", err)
}
klog.Infof("kubeconfig %q is saved", kubeconfigPath)
// wait for signal
sigterm := make(chan os.Signal, 1)
signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
<-sigterm
klog.Infof("signal received. remove kubeconfig %q and quit.", kubeconfigPath)
err = os.Remove(kubeconfigPath)
if err != nil {
klog.Errorf("failed to remove kubeconfig %q: %v", kubeconfigPath, err)
}
}

219
cmd/multus-daemon/main.go Normal file
View File

@@ -0,0 +1,219 @@
// Copyright (c) 2021 Multus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This binary works as a server that receives requests from multus-shim
// CNI plugin and creates network interface for kubernets pods.
package main
import (
"context"
"flag"
"fmt"
"io"
"net/http"
"os"
"os/signal"
"os/user"
"path/filepath"
"sync"
"syscall"
utilwait "k8s.io/apimachinery/pkg/util/wait"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/logging"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus"
srv "gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/server"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/server/api"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/server/config"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/types"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
// keep in command line option
version := flag.Bool("version", false, "Show version")
configFilePath := flag.String("config", srv.DefaultMultusDaemonConfigFile, "Specify the path to the multus-daemon configuration")
flag.Parse()
if *version {
fmt.Printf("multus-daemon: %s\n", multus.PrintVersionString())
os.Exit(4)
}
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
daemonConf, err := cniServerConfig(*configFilePath)
if err != nil {
os.Exit(1)
}
multusConf, err := config.ParseMultusConfig(*configFilePath)
if err != nil {
logging.Panicf("startMultusDaemon failed to load the multus configuration: %v", err)
os.Exit(1)
}
logging.Verbosef("multus-daemon started")
if multusConf.ReadinessIndicatorFile != "" {
// Check readinessindicator file before daemon launch
logging.Verbosef("Readiness Indicator file check")
if err := types.GetReadinessIndicatorFile(multusConf.ReadinessIndicatorFile); err != nil {
_ = logging.Errorf("have you checked that your default network is ready? still waiting for readinessindicatorfile @ %v. pollimmediate error: %v", multusConf.ReadinessIndicatorFile, err)
os.Exit(1)
}
logging.Verbosef("Readiness Indicator file check done!")
}
var configManager *config.Manager
var ignoreReadinessIndicator bool
if multusConf.MultusConfigFile == "auto" {
if multusConf.CNIVersion == "" {
_ = logging.Errorf("the CNI version is a mandatory parameter when the '-multus-config-file=auto' option is used")
}
// Generate multus CNI config from current CNI config
configManager, err = config.NewManager(*multusConf)
if err != nil {
_ = logging.Errorf("failed to create the configuration manager for the primary CNI plugin: %v", err)
os.Exit(2)
}
// ConfigManager watches the readiness indicator file (if configured)
// and exits the daemon when that is removed. The CNIServer does
// not need to re-do that check every CNI operation
ignoreReadinessIndicator = true
} else {
if err := copyUserProvidedConfig(multusConf.MultusConfigFile, multusConf.CniConfigDir); err != nil {
logging.Errorf("failed to copy the user provided configuration %s: %v", multusConf.MultusConfigFile, err)
}
}
if err := startMultusDaemon(ctx, daemonConf, ignoreReadinessIndicator); err != nil {
logging.Panicf("failed start the multus thick-plugin listener: %v", err)
os.Exit(3)
}
// Wait until daemon ready
logging.Verbosef("API readiness check")
if api.WaitUntilAPIReady(daemonConf.SocketDir) != nil {
logging.Panicf("failed to ready multus-daemon socket: %v", err)
os.Exit(1)
}
logging.Verbosef("API readiness check done!")
signalCh := make(chan os.Signal, 16)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
go func() {
for sig := range signalCh {
logging.Verbosef("caught %v, stopping...", sig)
cancel()
}
}()
var wg sync.WaitGroup
if configManager != nil {
if err := configManager.Start(ctx, &wg); err != nil {
_ = logging.Errorf("failed to start config manager: %v", err)
os.Exit(3)
}
}
wg.Wait()
logging.Verbosef("multus daemon is exited")
}
func startMultusDaemon(ctx context.Context, daemonConfig *srv.ControllerNetConf, ignoreReadinessIndicator bool) error {
if user, err := user.Current(); err != nil || user.Uid != "0" {
return fmt.Errorf("failed to run multus-daemon with root: %v, now running in uid: %s", err, user.Uid)
}
if err := srv.FilesystemPreRequirements(daemonConfig.SocketDir); err != nil {
return fmt.Errorf("failed to prepare the cni-socket for communicating with the shim: %w", err)
}
server, err := srv.NewCNIServer(daemonConfig, daemonConfig.ConfigFileContents, ignoreReadinessIndicator)
if err != nil {
return fmt.Errorf("failed to create the server: %v", err)
}
if daemonConfig.MetricsPort != nil {
go utilwait.UntilWithContext(ctx, func(_ context.Context) {
http.Handle("/metrics", promhttp.Handler())
logging.Debugf("metrics port: %d", *daemonConfig.MetricsPort)
logging.Debugf("metrics: %s", http.ListenAndServe(fmt.Sprintf(":%d", *daemonConfig.MetricsPort), nil))
}, 0)
}
l, err := srv.GetListener(api.SocketPath(daemonConfig.SocketDir))
if err != nil {
return fmt.Errorf("failed to start the CNI server using socket %s. Reason: %+v", api.SocketPath(daemonConfig.SocketDir), err)
}
server.Start(ctx, l)
go func() {
<-ctx.Done()
server.Shutdown(context.Background())
}()
return nil
}
func cniServerConfig(configFilePath string) (*srv.ControllerNetConf, error) {
path, err := filepath.Abs(configFilePath)
if err != nil {
return nil, fmt.Errorf("illegal path %s in server config path %s: %w", path, configFilePath, err)
}
configFileContents, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return srv.LoadDaemonNetConf(configFileContents)
}
func copyUserProvidedConfig(multusConfigPath string, cniConfigDir string) error {
path, err := filepath.Abs(multusConfigPath)
if err != nil {
return fmt.Errorf("illegal path %s in multusConfigPath %s: %w", path, multusConfigPath, err)
}
srcFile, err := os.Open(path)
if err != nil {
return fmt.Errorf("failed to open (READ only) file %s: %w", path, err)
}
dstFileName := cniConfigDir + "/" + filepath.Base(multusConfigPath)
dstFile, err := os.Create(dstFileName)
if err != nil {
return fmt.Errorf("creating copying file %s: %w", dstFileName, err)
}
nBytes, err := io.Copy(dstFile, srcFile)
if err != nil {
return fmt.Errorf("error copying file: %w", err)
}
srcFileInfo, err := srcFile.Stat()
if err != nil {
return fmt.Errorf("failed to stat the file: %w", err)
} else if nBytes != srcFileInfo.Size() {
return fmt.Errorf("error copying file - copied only %d bytes out of %d", nBytes, srcFileInfo.Size())
}
return nil
}

58
cmd/multus-shim/main.go Normal file
View File

@@ -0,0 +1,58 @@
// Copyright (c) 2022 Multus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This is a "Multi-plugin".The delegate concept referred from CNI project
// It reads other plugin netconf, and then invoke them, e.g.
// flannel or sriov plugin.
package main
import (
"flag"
"fmt"
"os"
"github.com/containernetworking/cni/pkg/skel"
cniversion "github.com/containernetworking/cni/pkg/version"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/server/api"
)
func main() {
// Init command line flags to clear vendored packages' one, especially in init()
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
// add version flag
versionOpt := false
flag.BoolVar(&versionOpt, "version", false, "Show application version")
flag.BoolVar(&versionOpt, "v", false, "Show application version")
flag.Parse()
if versionOpt {
fmt.Printf("multus-shim: %s\n", multus.PrintVersionString())
return
}
skel.PluginMain(
func(args *skel.CmdArgs) error {
return api.CmdAdd(args)
},
func(args *skel.CmdArgs) error {
return api.CmdCheck(args)
},
func(args *skel.CmdArgs) error {
return api.CmdDel(args)
},
cniversion.All, "meta-plugin that delegates to other CNI plugins")
}

59
cmd/multus/main.go Normal file
View File

@@ -0,0 +1,59 @@
// Copyright (c) 2016 Intel Corporation
// Copyright (c) 2021 Multus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This is a "Multi-plugin".The delegate concept referred from CNI project
// It reads other plugin netconf, and then invoke them, e.g.
// flannel or sriov plugin.
package main
import (
"flag"
"fmt"
"os"
"github.com/containernetworking/cni/pkg/skel"
cniversion "github.com/containernetworking/cni/pkg/version"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus"
)
func main() {
// Init command line flags to clear vendored packages' one, especially in init()
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
// add version flag
versionOpt := false
flag.BoolVar(&versionOpt, "version", false, "Show application version")
flag.BoolVar(&versionOpt, "v", false, "Show application version")
flag.Parse()
if versionOpt {
fmt.Printf("multus: %s\n", multus.PrintVersionString())
return
}
skel.PluginMain(
func(args *skel.CmdArgs) error {
result, err := multus.CmdAdd(args, nil, nil)
if err != nil {
return err
}
return result.Print()
},
func(args *skel.CmdArgs) error {
return multus.CmdCheck(args, nil, nil)
},
func(args *skel.CmdArgs) error { return multus.CmdDel(args, nil, nil) },
cniversion.All, "meta-plugin that delegates to other CNI plugins")
}

683
cmd/thin_entrypoint/main.go Normal file
View File

@@ -0,0 +1,683 @@
// Copyright (c) 2023 Multus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This is a entrypoint for thin (stand-alone) images.
package main
import (
"bytes"
"crypto/sha256"
b64 "encoding/base64"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/containernetworking/cni/libcni"
"github.com/spf13/pflag"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/cmdutils"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/signals"
)
// Options stores command line options
type Options struct {
CNIBinDir string
CNIConfDir string
CNIVersion string
MultusConfFile string
MultusBinFile string // may be hidden or remove?
MultusCNIConfDir string
SkipMultusBinaryCopy bool
MultusKubeConfigFileHost string
MultusMasterCNIFileName string
NamespaceIsolation bool
GlobalNamespaces string
MultusAutoconfigDir string
MultusLogToStderr bool
MultusLogLevel string
MultusLogFile string
OverrideNetworkName bool
CleanupConfigOnExit bool
RenameConfFile bool
ReadinessIndicatorFile string
AdditionalBinDir string
ForceCNIVersion bool
SkipTLSVerify bool
SkipMultusConfWatch bool
}
const (
serviceAccountTokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token"
serviceAccountCAFile = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
)
func (o *Options) addFlags() {
pflag.ErrHelp = nil // suppress error message for help
fs := pflag.CommandLine
fs.StringVar(&o.CNIBinDir, "cni-bin-dir", "/host/opt/cni/bin", "CNI binary directory")
fs.StringVar(&o.CNIConfDir, "cni-conf-dir", "/host/etc/cni/net.d", "CNI config directory")
fs.StringVar(&o.CNIVersion, "cni-version", "", "CNI version for multus CNI config (e.g. '0.3.1')")
fs.StringVar(&o.MultusConfFile, "multus-conf-file", "auto", "multus CNI config file")
fs.StringVar(&o.MultusBinFile, "multus-bin-file", "/usr/src/multus-cni/bin/multus", "multus binary file path")
fs.StringVar(&o.MultusCNIConfDir, "multus-cni-conf-dir", "/host/etc/cni/multus/net.d", "multus specific CNI config directory")
fs.BoolVar(&o.SkipMultusBinaryCopy, "skip-multus-binary-copy", false, "skip multus binary file copy")
fs.StringVar(&o.MultusKubeConfigFileHost, "multus-kubeconfig-file-host", "/etc/cni/net.d/multus.d/multus.kubeconfig", "kubeconfig for multus (used only with --multus-conf-file=auto)")
fs.StringVar(&o.MultusMasterCNIFileName, "multus-master-cni-file-name", "", "master CNI file in multus-autoconfig-dir")
fs.BoolVar(&o.NamespaceIsolation, "namespace-isolation", false, "namespace isolation")
fs.StringVar(&o.GlobalNamespaces, "global-namespaces", "", "global namespaces, comma separated (used only with --namespace-isolation=true)")
fs.StringVar(&o.MultusAutoconfigDir, "multus-autoconfig-dir", "/host/etc/cni/net.d", "multus autoconfig dir (used only with --multus-conf-file=auto)")
fs.BoolVar(&o.MultusLogToStderr, "multus-log-to-stderr", true, "log to stderr")
fs.StringVar(&o.MultusLogLevel, "multus-log-level", "", "multus log level")
fs.StringVar(&o.MultusLogFile, "multus-log-file", "", "multus log file")
fs.BoolVar(&o.OverrideNetworkName, "override-network-name", false, "override network name from master cni file (used only with --multus-conf-file=auto)")
fs.BoolVar(&o.CleanupConfigOnExit, "cleanup-config-on-exit", false, "cleanup config file on exit")
fs.BoolVar(&o.SkipMultusConfWatch, "skip-config-watch", false, "dont watch for config (master cni and kubeconfig) changes (used only with --multus-conf-file=auto)")
fs.BoolVar(&o.RenameConfFile, "rename-conf-file", false, "rename master config file to invalidate (used only with --multus-conf-file=auto)")
fs.StringVar(&o.ReadinessIndicatorFile, "readiness-indicator-file", "", "readiness indicator file (used only with --multus-conf-file=auto)")
fs.StringVar(&o.AdditionalBinDir, "additional-bin-dir", "", "adds binDir option to configuration (used only with --multus-conf-file=auto)")
fs.BoolVar(&o.SkipTLSVerify, "skip-tls-verify", false, "skip TLS verify")
fs.BoolVar(&o.ForceCNIVersion, "force-cni-version", false, "force cni version to '--cni-version' (only for e2e-kind testing)")
fs.MarkHidden("force-cni-version")
fs.MarkHidden("skip-tls-verify")
}
func (o *Options) verifyFileExists() error {
// CNIConfDir
if _, err := os.Stat(o.CNIConfDir); err != nil {
return fmt.Errorf("cni-conf-dir is not found: %v", err)
}
// CNIBinDir
if _, err := os.Stat(o.CNIBinDir); err != nil {
return fmt.Errorf("cni-bin-dir is not found: %v", err)
}
// MultusBinFile
if _, err := os.Stat(o.MultusBinFile); err != nil {
return fmt.Errorf("multus-bin-file is not found: %v", err)
}
if o.MultusConfFile != "auto" {
// MultusConfFile
if _, err := os.Stat(o.MultusConfFile); err != nil {
return fmt.Errorf("multus-conf-file is not found: %v", err)
}
}
return nil
}
const kubeConfigTemplate = `# Kubeconfig file for Multus CNI plugin.
apiVersion: v1
kind: Config
clusters:
- name: local
cluster:
server: {{ .KubeConfigHost }}
{{ .KubeServerTLS }}
users:
- name: multus
user:
token: "{{ .KubeServiceAccountToken }}"
contexts:
- name: multus-context
context:
cluster: local
user: multus
current-context: multus-context
`
func getFileAndHash(filepath string) ([]byte, []byte, error) {
if _, err := os.Stat(filepath); err != nil {
return nil, nil, fmt.Errorf("file %s not found: %v", filepath, err)
}
content, err := os.ReadFile(filepath)
if err != nil {
return nil, nil, fmt.Errorf("cannot read %s file: %v", filepath, err)
}
hash := sha256.New()
hash.Write(content)
return content, hash.Sum(nil), nil
}
func (o *Options) createKubeConfig(prevCAHash, prevSATokenHash []byte) ([]byte, []byte, error) {
caFileByte, caHash, err := getFileAndHash(serviceAccountCAFile)
if err != nil {
return nil, nil, err
}
saTokenByte, saTokenHash, err := getFileAndHash(serviceAccountTokenFile)
if err != nil {
return nil, nil, err
}
caUnchanged := prevCAHash != nil && bytes.Equal(prevCAHash, caHash)
saUnchanged := prevSATokenHash != nil && bytes.Equal(prevSATokenHash, saTokenHash)
if o.SkipTLSVerify {
if saUnchanged {
return caHash, saTokenHash, nil
}
} else {
if caUnchanged && saUnchanged {
return caHash, saTokenHash, nil
}
}
if prevSATokenHash != nil {
// don't log "recreating" on first function execution
fmt.Printf("CA (%v) or SA token (%v) changed - recreating kubeconfig\n", !caUnchanged, !saUnchanged)
}
// create multus.d directory
if err := os.MkdirAll(fmt.Sprintf("%s/multus.d", o.CNIConfDir), 0755); err != nil {
return nil, nil, fmt.Errorf("cannot create multus.d directory: %v", err)
}
// create multus cni conf directory
if err := os.MkdirAll(o.MultusCNIConfDir, 0755); err != nil {
return nil, nil, fmt.Errorf("cannot create multus-cni-conf-dir(%s) directory: %v", o.MultusCNIConfDir, err)
}
// get Kubernetes service protocol/host/port
kubeProtocol := os.Getenv("KUBERNETES_SERVICE_PROTOCOL")
if kubeProtocol == "" {
kubeProtocol = "https"
}
kubeHost := os.Getenv("KUBERNETES_SERVICE_HOST")
kubePort := os.Getenv("KUBERNETES_SERVICE_PORT")
// check tlsConfig
tlsConfig := ""
if o.SkipTLSVerify {
tlsConfig = "insecure-skip-tls-verify: true"
} else {
// create tlsConfig by service account CA file
caFileB64 := bytes.ReplaceAll([]byte(b64.StdEncoding.EncodeToString(caFileByte)), []byte("\n"), []byte(""))
tlsConfig = fmt.Sprintf("certificate-authority-data: %s", string(caFileB64))
}
// create kubeconfig by template and replace it by atomic
tempKubeConfigFile := fmt.Sprintf("%s/multus.d/multus.kubeconfig.new", o.CNIConfDir)
multusKubeConfig := fmt.Sprintf("%s/multus.d/multus.kubeconfig", o.CNIConfDir)
fp, err := os.OpenFile(tempKubeConfigFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return nil, nil, fmt.Errorf("cannot create kubeconfig temp file: %v", err)
}
templateKubeconfig, err := template.New("kubeconfig").Parse(kubeConfigTemplate)
if err != nil {
return nil, nil, fmt.Errorf("template parse error: %v", err)
}
templateData := map[string]string{
"KubeConfigHost": fmt.Sprintf("%s://[%s]:%s", kubeProtocol, kubeHost, kubePort),
"KubeServerTLS": tlsConfig,
"KubeServiceAccountToken": string(saTokenByte),
}
// generate kubeconfig from template
if err = templateKubeconfig.Execute(fp, templateData); err != nil {
return nil, nil, fmt.Errorf("cannot create kubeconfig: %v", err)
}
if err := fp.Sync(); err != nil {
os.Remove(fp.Name())
return nil, nil, fmt.Errorf("cannot flush kubeconfig temp file: %v", err)
}
if err := fp.Close(); err != nil {
os.Remove(fp.Name())
return nil, nil, fmt.Errorf("cannot close kubeconfig temp file: %v", err)
}
// replace file with tempfile
if err := os.Rename(tempKubeConfigFile, multusKubeConfig); err != nil {
return nil, nil, fmt.Errorf("cannot replace %q with temp file %q: %v", multusKubeConfig, tempKubeConfigFile, err)
}
fmt.Printf("kubeconfig is created in %s\n", multusKubeConfig)
return caHash, saTokenHash, nil
}
const multusConflistTemplate = `{
"cniVersion": "{{ .CNIVersion }}",
"name": "{{ .MasterPluginNetworkName }}",
"plugins": [ {
"type": "multus",{{
.NestedCapabilities
}}{{
.NamespaceIsolationConfig
}}{{
.GlobalNamespacesConfig
}}{{
.LogToStderrConfig
}}{{
.LogLevelConfig
}}{{
.LogFileConfig
}}{{
.AdditionalBinDirConfig
}}{{
.MultusCNIConfDirConfig
}}{{
.ReadinessIndicatorFileConfig
}}
"kubeconfig": "{{ .MultusKubeConfigFileHost }}",
"delegates": [
{{ .MasterPluginJSON }}
]
}]
}
`
const multusConfTemplate = `{
"cniVersion": "{{ .CNIVersion }}",
"name": "{{ .MasterPluginNetworkName }}",
"type": "multus",{{
.NestedCapabilities
}}{{
.NamespaceIsolationConfig
}}{{
.GlobalNamespacesConfig
}}{{
.LogToStderrConfig
}}{{
.LogLevelConfig
}}{{
.LogFileConfig
}}{{
.AdditionalBinDirConfig
}}{{
.MultusCNIConfDirConfig
}}{{
.ReadinessIndicatorFileConfig
}}
"kubeconfig": "{{ .MultusKubeConfigFileHost }}",
"delegates": [
{{ .MasterPluginJSON }}
]
}
`
func (o *Options) getMasterConfigPath() (string, error) {
// Master config file is specified
if o.MultusMasterCNIFileName != "" {
return filepath.Join(o.MultusAutoconfigDir, o.MultusMasterCNIFileName), nil
}
// Pick the alphabetically first config file from MultusAutoconfigDir
files, err := libcni.ConfFiles(o.MultusAutoconfigDir, []string{".conf", ".conflist"})
if err != nil {
return "", fmt.Errorf("cannot find master CNI config in %q: %v", o.MultusAutoconfigDir, err)
}
for _, filename := range files {
if !strings.HasPrefix(filepath.Base(filename), "00-multus.conf") {
return filename, nil
}
}
// No config file found
return "", fmt.Errorf("cannot find valid master CNI config in %q", o.MultusAutoconfigDir)
}
func (o *Options) createMultusConfig(prevMasterConfigFileHash []byte) (string, []byte, error) {
masterConfigPath, err := o.getMasterConfigPath()
if err != nil {
return "", nil, err
}
masterConfigBytes, masterConfigFileHash, err := getFileAndHash(masterConfigPath)
if err != nil {
return "", nil, err
}
if prevMasterConfigFileHash != nil && bytes.Equal(prevMasterConfigFileHash, masterConfigFileHash) {
return masterConfigPath, masterConfigFileHash, nil
}
if prevMasterConfigFileHash != nil {
// don't log "recreating" on first function execution
fmt.Printf("master config changed - recreating multus config\n")
}
masterConfig := map[string]interface{}{}
if err = json.Unmarshal(masterConfigBytes, &masterConfig); err != nil {
return "", nil, fmt.Errorf("cannot read master CNI config json: %v", err)
}
// check CNIVersion
masterCNIVersionElem, ok := masterConfig["cniVersion"]
if !ok {
return "", nil, fmt.Errorf("cannot get cniVersion in master CNI config file %q: %v", masterConfigPath, err)
}
if o.ForceCNIVersion {
masterConfig["cniVersion"] = o.CNIVersion
fmt.Printf("force CNI version to %q\n", o.CNIVersion)
} else {
masterCNIVersion := masterCNIVersionElem.(string)
if o.CNIVersion != "" && masterCNIVersion != o.CNIVersion {
return "", nil, fmt.Errorf("Multus cni version is %q while master plugin cni version is %q", o.CNIVersion, masterCNIVersion)
}
o.CNIVersion = masterCNIVersion
}
cniVersionConfig := o.CNIVersion
// check OverrideNetworkName (if true, get master plugin name, otherwise 'multus-cni-network'
masterPluginNetworkName := "multus-cni-network"
if o.OverrideNetworkName {
masterPluginNetworkElem, ok := masterConfig["name"]
if !ok {
return "", nil, fmt.Errorf("cannot get name in master CNI config file %q: %v", masterConfigPath, err)
}
masterPluginNetworkName = masterPluginNetworkElem.(string)
fmt.Printf("master plugin name is overrided to %q\n", masterPluginNetworkName)
}
// check capabilities (from master conf, top and 'plugins')
masterCapabilities := map[string]bool{}
_, isMasterConfList := masterConfig["plugins"]
if isMasterConfList {
masterPluginsElem, ok := masterConfig["plugins"]
if !ok {
return "", nil, fmt.Errorf("cannot get 'plugins' field in master CNI config file %q: %v", masterConfigPath, err)
}
masterPlugins := masterPluginsElem.([]interface{})
for _, v := range masterPlugins {
pluginFields := v.(map[string]interface{})
capabilitiesElem, ok := pluginFields["capabilities"]
if ok {
capabilities := capabilitiesElem.(map[string]interface{})
for k, v := range capabilities {
masterCapabilities[k] = v.(bool)
}
}
}
fmt.Printf("master capabilities is get from conflist\n")
} else {
masterCapabilitiesElem, ok := masterConfig["capabilities"]
if ok {
for k, v := range masterCapabilitiesElem.(map[string]interface{}) {
masterCapabilities[k] = v.(bool)
}
}
fmt.Printf("master capabilities is get from conffile\n")
}
nestedCapabilitiesConf := ""
if len(masterCapabilities) != 0 {
capabilitiesByte, err := json.Marshal(masterCapabilities)
if err != nil {
return "", nil, fmt.Errorf("cannot get capabilities map: %v", err)
}
nestedCapabilitiesConf = fmt.Sprintf("\n \"capabilities\": %s,", string(capabilitiesByte))
}
// check NamespaceIsolation
namespaceIsolationConfig := ""
if o.NamespaceIsolation {
namespaceIsolationConfig = "\n \"namespaceIsolation\": true,"
}
// check GlobalNamespaces
globalNamespaceConfig := ""
if o.GlobalNamespaces != "" {
globalNamespaceConfig = fmt.Sprintf("\n \"globalNamespaces\": %q,", o.GlobalNamespaces)
}
// check MultusLogToStderr
logToStderrConfig := ""
if !o.MultusLogToStderr {
logToStderrConfig = "\n \"logToStderr\": false,"
}
// check MultusLogLevel (debug/error/panic/verbose) and reject others
logLevelConfig := ""
logLevelStr := strings.ToLower(o.MultusLogLevel)
switch logLevelStr {
case "debug", "error", "panic", "verbose":
logLevelConfig = fmt.Sprintf("\n \"logLevel\": %q,", logLevelStr)
case "":
// no logLevel config, skipped
default:
return "", nil, fmt.Errorf("Log levels should be one of: debug/verbose/error/panic, did not understand: %q", o.MultusLogLevel)
}
// check MultusLogFile
logFileConfig := ""
if o.MultusLogFile != "" {
logFileConfig = fmt.Sprintf("\n \"logFile\": %q,", o.MultusLogFile)
}
// check AdditionalBinDir
additionalBinDirConfig := ""
if o.AdditionalBinDir != "" {
additionalBinDirConfig = fmt.Sprintf("\n \"binDir\": %q,", o.AdditionalBinDir)
}
// check MultusCNIConfDir
multusCNIConfDirConfig := ""
if o.MultusCNIConfDir != "" {
multusCNIConfDirConfig = fmt.Sprintf("\n \"cniConf\": %q,", o.MultusCNIConfDir)
}
// check ReadinessIndicatorFile
readinessIndicatorFileConfig := ""
if o.ReadinessIndicatorFile != "" {
readinessIndicatorFileConfig = fmt.Sprintf("\n \"readinessindicatorfile\": %q,", o.ReadinessIndicatorFile)
}
// fill .MasterPluginJSON
masterPluginByte, err := json.Marshal(masterConfig)
if err != nil {
return "", nil, fmt.Errorf("cannot encode master CNI config: %v", err)
}
// generate multus config
tempFileName := fmt.Sprintf("%s/00-multus.conf.new", o.CNIConfDir)
fp, err := os.OpenFile(tempFileName, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return "", nil, fmt.Errorf("cannot create multus cni temp file: %v", err)
}
// use conflist template if cniVersionConfig == "1.0.0"
multusConfFilePath := fmt.Sprintf("%s/00-multus.conf", o.CNIConfDir)
templateMultusConfig, err := template.New("multusCNIConfig").Parse(multusConfTemplate)
if err != nil {
return "", nil, fmt.Errorf("template parse error: %v", err)
}
if o.CNIVersion == "1.0.0" { //Check 1.0.0 or above!
multusConfFilePath = fmt.Sprintf("%s/00-multus.conflist", o.CNIConfDir)
templateMultusConfig, err = template.New("multusCNIConfig").Parse(multusConflistTemplate)
if err != nil {
return "", nil, fmt.Errorf("template parse error: %v", err)
}
}
templateData := map[string]string{
"CNIVersion": cniVersionConfig,
"MasterPluginNetworkName": masterPluginNetworkName,
"NestedCapabilities": nestedCapabilitiesConf,
"NamespaceIsolationConfig": namespaceIsolationConfig,
"GlobalNamespacesConfig": globalNamespaceConfig,
"LogToStderrConfig": logToStderrConfig,
"LogLevelConfig": logLevelConfig,
"LogFileConfig": logFileConfig,
"AdditionalBinDirConfig": additionalBinDirConfig,
"MultusCNIConfDirConfig": multusCNIConfDirConfig,
"ReadinessIndicatorFileConfig": readinessIndicatorFileConfig,
"MultusKubeConfigFileHost": o.MultusKubeConfigFileHost, // be fixed?
"MasterPluginJSON": string(masterPluginByte),
}
if err = templateMultusConfig.Execute(fp, templateData); err != nil {
return "", nil, fmt.Errorf("cannot create multus cni config: %v", err)
}
if err := fp.Sync(); err != nil {
os.Remove(tempFileName)
return "", nil, fmt.Errorf("cannot flush multus cni config: %v", err)
}
if err := fp.Close(); err != nil {
os.Remove(tempFileName)
return "", nil, fmt.Errorf("cannot close multus cni config: %v", err)
}
if err := os.Rename(tempFileName, multusConfFilePath); err != nil {
return "", nil, fmt.Errorf("cannot replace %q with temp file %q: %v", multusConfFilePath, tempFileName, err)
}
if o.RenameConfFile {
//masterConfigPath
renamedMasterConfigPath := fmt.Sprintf("%s.old", masterConfigPath)
if err := os.Rename(masterConfigPath, renamedMasterConfigPath); err != nil {
return "", nil, fmt.Errorf("cannot move original master file to %q", renamedMasterConfigPath)
}
fmt.Printf("Original master file moved to %q\n", renamedMasterConfigPath)
}
return masterConfigPath, masterConfigFileHash, nil
}
func main() {
opt := Options{}
opt.addFlags()
helpFlag := pflag.BoolP("help", "h", false, "show help message and quit")
pflag.Parse()
if *helpFlag {
pflag.PrintDefaults()
os.Exit(1)
}
err := opt.verifyFileExists()
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
return
}
// copy multus binary
if !opt.SkipMultusBinaryCopy {
// Copy
if err = cmdutils.CopyFileAtomic(opt.MultusBinFile, opt.CNIBinDir, "_multus", "multus"); err != nil {
fmt.Fprintf(os.Stderr, "failed at multus copy: %v\n", err)
return
}
}
var masterConfigHash, caHash, saTokenHash []byte
var masterConfigFilePath string
// copy user specified multus conf to CNI conf directory
if opt.MultusConfFile != "auto" {
caHash, saTokenHash, err = opt.createKubeConfig(nil, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create multus kubeconfig: %v\n", err)
return
}
confFileName := filepath.Base(opt.MultusConfFile)
tempConfFileName := fmt.Sprintf("%s.temp", confFileName)
if err = cmdutils.CopyFileAtomic(opt.MultusConfFile, opt.CNIConfDir, tempConfFileName, confFileName); err != nil {
fmt.Fprintf(os.Stderr, "failed at copy multus conf file: %v\n", err)
return
}
fmt.Printf("multus config file %s is copied.\n", opt.MultusConfFile)
} else { // auto generate multus config
caHash, saTokenHash, err = opt.createKubeConfig(nil, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create multus kubeconfig: %v\n", err)
return
}
fmt.Printf("kubeconfig file is created.\n")
masterConfigFilePath, masterConfigHash, err = opt.createMultusConfig(nil)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create multus config: %v\n", err)
return
}
fmt.Printf("multus config file is created.\n")
}
ctx := signals.SetupSignalHandler()
if opt.CleanupConfigOnExit {
defer cleanupMultusConf(&opt)
}
watchChanges := opt.CleanupConfigOnExit && opt.MultusConfFile == "auto" && !opt.SkipMultusConfWatch
if watchChanges {
fmt.Printf("Entering watch loop...\n")
masterConfigExists := true
outer:
for range time.Tick(1 * time.Second) {
select {
case <-ctx.Done():
// signal received break from loop
break outer
default:
// Check kubeconfig and update if different (i.e. service account updated)
caHash, saTokenHash, err = opt.createKubeConfig(caHash, saTokenHash)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to update multus kubeconfig: %v\n", err)
return
}
// TODO: should we watch master CNI config (by fsnotify? https://github.com/fsnotify/fsnotify)
_, err = os.Stat(masterConfigFilePath)
// if masterConfigFilePath is no longer exists
if os.IsNotExist(err) {
if masterConfigExists {
fmt.Printf("Master plugin @ %q has been deleted. waiting for its restoration...\n", masterConfigFilePath)
}
masterConfigExists = false
continue
}
if !masterConfigExists {
fmt.Printf("Master plugin @ %q was restored. Regenerating given configuration.\n", masterConfigFilePath)
masterConfigExists = true
}
masterConfigFilePath, masterConfigHash, err = opt.createMultusConfig(masterConfigHash)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create multus config: %v\n", err)
return
}
}
}
} else {
// wait until signal received
<-ctx.Done()
}
}
func cleanupMultusConf(opt *Options) {
// try remove multus conf
if opt.MultusConfFile == "auto" {
multusConfFilePath := fmt.Sprintf("%s/00-multus.conf", opt.CNIConfDir)
_ = os.Remove(multusConfFilePath)
multusConfFilePath = fmt.Sprintf("%s/00-multus.conflist", opt.CNIConfDir)
_ = os.Remove(multusConfFilePath)
} else {
confFileName := filepath.Base(opt.MultusConfFile)
_ = os.Remove(filepath.Join(opt.CNIConfDir, confFileName))
}
}

View File

@@ -0,0 +1,544 @@
package main
// disable dot-imports only for testing
//revive:disable:dot-imports
import (
"fmt"
"os"
"path/filepath"
"syscall"
"testing"
. "github.com/onsi/ginkgo/v2" //nolint:golint
. "github.com/onsi/gomega" //nolint:golint
)
// chrootTestHelper performs chroot syscall, returns func to get back to original root or error if occurred
func chrootTestHelper(path string) (func() error, error) {
root, err := os.Open("/")
if err != nil {
return nil, err
}
if err := syscall.Chroot(path); err != nil {
root.Close()
return nil, err
}
return func() error {
defer root.Close()
if err := root.Chdir(); err != nil {
return err
}
return syscall.Chroot(".")
}, nil
}
func TestThinEntrypoint(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "thin_entrypoint")
}
var _ = Describe("thin entrypoint testing", func() {
It("always pass just example", func() {
a := 10
Expect(a).To(Equal(10))
})
It("Run verifyFileExists() with expected environment, autoconfig", func() {
// create directory and files
tmpDir, err := os.MkdirTemp("", "multus_thin_entrypoint_tmp")
Expect(err).NotTo(HaveOccurred())
cniConfDir := fmt.Sprintf("%s/cni_conf_dir", tmpDir)
cniBinDir := fmt.Sprintf("%s/cni_bin_dir", tmpDir)
multusBinFile := fmt.Sprintf("%s/multus_bin", tmpDir)
multusConfFile := fmt.Sprintf("%s/multus_conf", tmpDir)
// CNIConfDir
Expect(os.Mkdir(cniConfDir, 0755)).To(Succeed())
// CNIBinDir
Expect(os.Mkdir(cniBinDir, 0755)).To(Succeed())
// MultusBinFile
Expect(os.WriteFile(multusBinFile, nil, 0744)).To(Succeed())
// MultusConfFile
Expect(os.WriteFile(multusConfFile, nil, 0744)).To(Succeed())
err = (&Options{
CNIConfDir: cniConfDir,
CNIBinDir: cniBinDir,
MultusBinFile: multusBinFile,
MultusConfFile: multusConfFile,
}).verifyFileExists()
Expect(err).NotTo(HaveOccurred())
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
It("Run verifyFileExists() with invalid environmentMultusConfFile", func() {
// create directory and files
tmpDir, err := os.MkdirTemp("", "multus_thin_entrypoint_tmp")
Expect(err).NotTo(HaveOccurred())
cniConfDir := fmt.Sprintf("%s/cni_conf_dir", tmpDir)
cniBinDir := fmt.Sprintf("%s/cni_bin_dir", tmpDir)
multusBinFile := fmt.Sprintf("%s/multus_bin", tmpDir)
multusConfFile := fmt.Sprintf("%s/multus_conf", tmpDir)
// CNIConfDir
Expect(os.Mkdir(cniConfDir, 0755)).To(Succeed())
// CNIBinDir
Expect(os.Mkdir(cniBinDir, 0755)).To(Succeed())
// MultusConfFile
Expect(os.WriteFile(multusConfFile, nil, 0744)).To(Succeed())
err = (&Options{
CNIConfDir: cniConfDir,
CNIBinDir: cniBinDir,
MultusBinFile: multusBinFile,
MultusConfFile: multusConfFile,
}).verifyFileExists()
Expect(err).To(HaveOccurred())
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
It("Run createMultusConfig(), default, conf", func() {
// create directory and files
tmpDir, err := os.MkdirTemp("", "multus_thin_entrypoint_tmp")
Expect(err).NotTo(HaveOccurred())
multusAutoConfigDir := fmt.Sprintf("%s/auto_conf", tmpDir)
cniConfDir := fmt.Sprintf("%s/cni_conf", tmpDir)
Expect(os.Mkdir(multusAutoConfigDir, 0755)).To(Succeed())
Expect(os.Mkdir(cniConfDir, 0755)).To(Succeed())
// create master CNI config
masterCNIConfig := `
{
"cniVersion": "0.3.1",
"name": "test1",
"type": "cnitesttype"
}`
Expect(os.WriteFile(fmt.Sprintf("%s/10-testcni.conf", multusAutoConfigDir), []byte(masterCNIConfig), 0755)).To(Succeed())
masterConfigPath, masterConfigHash, err := (&Options{
MultusAutoconfigDir: multusAutoConfigDir,
CNIConfDir: cniConfDir,
MultusKubeConfigFileHost: "/etc/foobar_kubeconfig",
}).createMultusConfig(nil)
Expect(err).NotTo(HaveOccurred())
Expect(masterConfigPath).NotTo(Equal(""))
Expect(masterConfigHash).NotTo(Equal(""))
expectedResult := `{
"cniVersion": "0.3.1",
"name": "multus-cni-network",
"type": "multus",
"logToStderr": false,
"kubeconfig": "/etc/foobar_kubeconfig",
"delegates": [
{"cniVersion":"0.3.1","name":"test1","type":"cnitesttype"}
]
}
`
conf, err := os.ReadFile(fmt.Sprintf("%s/00-multus.conf", cniConfDir))
Expect(string(conf)).To(Equal(expectedResult))
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
It("Run createMultusConfig(), capabilities, conf", func() {
// create directory and files
tmpDir, err := os.MkdirTemp("", "multus_thin_entrypoint_tmp")
Expect(err).NotTo(HaveOccurred())
multusAutoConfigDir := fmt.Sprintf("%s/auto_conf", tmpDir)
cniConfDir := fmt.Sprintf("%s/cni_conf", tmpDir)
Expect(os.Mkdir(multusAutoConfigDir, 0755)).To(Succeed())
Expect(os.Mkdir(cniConfDir, 0755)).To(Succeed())
// create master CNI config
masterCNIConfig := `
{
"cniVersion": "0.3.1",
"name": "test1",
"capabilities": { "bandwidth": true },
"type": "cnitesttype"
}`
Expect(os.WriteFile(fmt.Sprintf("%s/10-testcni.conf", multusAutoConfigDir), []byte(masterCNIConfig), 0755)).To(Succeed())
masterConfigPath, masterConfigHash, err := (&Options{
MultusAutoconfigDir: multusAutoConfigDir,
CNIConfDir: cniConfDir,
MultusKubeConfigFileHost: "/etc/foobar_kubeconfig",
}).createMultusConfig(nil)
Expect(err).NotTo(HaveOccurred())
Expect(masterConfigPath).NotTo(Equal(""))
Expect(masterConfigHash).NotTo(Equal(""))
expectedResult := `{
"cniVersion": "0.3.1",
"name": "multus-cni-network",
"type": "multus",
"capabilities": {"bandwidth":true},
"logToStderr": false,
"kubeconfig": "/etc/foobar_kubeconfig",
"delegates": [
{"capabilities":{"bandwidth":true},"cniVersion":"0.3.1","name":"test1","type":"cnitesttype"}
]
}
`
conf, err := os.ReadFile(fmt.Sprintf("%s/00-multus.conf", cniConfDir))
Expect(string(conf)).To(Equal(expectedResult))
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
It("Run createMultusConfig(), with options, conf", func() {
// create directory and files
tmpDir, err := os.MkdirTemp("", "multus_thin_entrypoint_tmp")
Expect(err).NotTo(HaveOccurred())
multusAutoConfigDir := fmt.Sprintf("%s/auto_conf", tmpDir)
cniConfDir := fmt.Sprintf("%s/cni_conf", tmpDir)
Expect(os.Mkdir(multusAutoConfigDir, 0755)).To(Succeed())
Expect(os.Mkdir(cniConfDir, 0755)).To(Succeed())
// create master CNI config
masterCNIConfig := `
{
"cniVersion": "0.3.1",
"name": "test1",
"type": "cnitesttype"
}`
err = os.WriteFile(fmt.Sprintf("%s/10-testcni.conf", multusAutoConfigDir), []byte(masterCNIConfig), 0755)
Expect(err).NotTo(HaveOccurred())
masterConfigPath, masterConfigHash, err := (&Options{
MultusAutoconfigDir: multusAutoConfigDir,
CNIConfDir: cniConfDir,
MultusKubeConfigFileHost: "/etc/foobar_kubeconfig",
NamespaceIsolation: true,
GlobalNamespaces: "foobar,barfoo",
MultusLogToStderr: true,
MultusLogLevel: "DEBUG",
MultusLogFile: "/tmp/foobar.log",
AdditionalBinDir: "/tmp/add_bin_dir",
MultusCNIConfDir: "/tmp/multus/net.d",
ReadinessIndicatorFile: "/var/lib/foobar_indicator",
}).createMultusConfig(nil)
Expect(err).NotTo(HaveOccurred())
Expect(masterConfigPath).NotTo(Equal(""))
Expect(masterConfigHash).NotTo(Equal(""))
expectedResult := `{
"cniVersion": "0.3.1",
"name": "multus-cni-network",
"type": "multus",
"namespaceIsolation": true,
"globalNamespaces": "foobar,barfoo",
"logLevel": "debug",
"logFile": "/tmp/foobar.log",
"binDir": "/tmp/add_bin_dir",
"cniConf": "/tmp/multus/net.d",
"readinessindicatorfile": "/var/lib/foobar_indicator",
"kubeconfig": "/etc/foobar_kubeconfig",
"delegates": [
{"cniVersion":"0.3.1","name":"test1","type":"cnitesttype"}
]
}
`
conf, err := os.ReadFile(fmt.Sprintf("%s/00-multus.conf", cniConfDir))
Expect(string(conf)).To(Equal(expectedResult))
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
It("Run createMultusConfig(), default, conflist", func() {
// create directory and files
tmpDir, err := os.MkdirTemp("", "multus_thin_entrypoint_tmp")
Expect(err).NotTo(HaveOccurred())
multusAutoConfigDir := fmt.Sprintf("%s/auto_conf", tmpDir)
cniConfDir := fmt.Sprintf("%s/cni_conf", tmpDir)
Expect(os.Mkdir(multusAutoConfigDir, 0755)).To(Succeed())
Expect(os.Mkdir(cniConfDir, 0755)).To(Succeed())
// create master CNI config
masterCNIConfig := `
{
"cniVersion": "1.0.0",
"name": "test1",
"type": "cnitesttype"
}`
Expect(os.WriteFile(fmt.Sprintf("%s/10-testcni.conf", multusAutoConfigDir), []byte(masterCNIConfig), 0755)).To(Succeed())
masterConfigPath, masterConfigHash, err := (&Options{
MultusAutoconfigDir: multusAutoConfigDir,
CNIConfDir: cniConfDir,
MultusKubeConfigFileHost: "/etc/foobar_kubeconfig",
}).createMultusConfig(nil)
Expect(err).NotTo(HaveOccurred())
Expect(masterConfigPath).NotTo(Equal(""))
Expect(masterConfigHash).NotTo(Equal(""))
expectedResult :=
`{
"cniVersion": "1.0.0",
"name": "multus-cni-network",
"plugins": [ {
"type": "multus",
"logToStderr": false,
"kubeconfig": "/etc/foobar_kubeconfig",
"delegates": [
{"cniVersion":"1.0.0","name":"test1","type":"cnitesttype"}
]
}]
}
`
conf, err := os.ReadFile(fmt.Sprintf("%s/00-multus.conflist", cniConfDir))
Expect(string(conf)).To(Equal(expectedResult))
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
It("Run createMultusConfig(), capabilities, conflist", func() {
// create directory and files
tmpDir, err := os.MkdirTemp("", "multus_thin_entrypoint_tmp")
Expect(err).NotTo(HaveOccurred())
multusAutoConfigDir := fmt.Sprintf("%s/auto_conf", tmpDir)
cniConfDir := fmt.Sprintf("%s/cni_conf", tmpDir)
Expect(os.Mkdir(multusAutoConfigDir, 0755)).To(Succeed())
Expect(os.Mkdir(cniConfDir, 0755)).To(Succeed())
// create master CNI config
masterCNIConfig := `
{
"cniVersion": "1.0.0",
"name": "test1",
"capabilities": { "bandwidth": true },
"type": "cnitesttype"
}`
Expect(os.WriteFile(fmt.Sprintf("%s/10-testcni.conflist", multusAutoConfigDir), []byte(masterCNIConfig), 0755)).To(Succeed())
masterConfigPath, masterConfigHash, err := (&Options{
MultusAutoconfigDir: multusAutoConfigDir,
CNIConfDir: cniConfDir,
MultusKubeConfigFileHost: "/etc/foobar_kubeconfig",
}).createMultusConfig(nil)
Expect(err).NotTo(HaveOccurred())
Expect(masterConfigPath).NotTo(Equal(""))
Expect(masterConfigHash).NotTo(Equal(""))
expectedResult :=
`{
"cniVersion": "1.0.0",
"name": "multus-cni-network",
"plugins": [ {
"type": "multus",
"capabilities": {"bandwidth":true},
"logToStderr": false,
"kubeconfig": "/etc/foobar_kubeconfig",
"delegates": [
{"capabilities":{"bandwidth":true},"cniVersion":"1.0.0","name":"test1","type":"cnitesttype"}
]
}]
}
`
conf, err := os.ReadFile(fmt.Sprintf("%s/00-multus.conflist", cniConfDir))
Expect(string(conf)).To(Equal(expectedResult))
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
It("Run createMultusConfig(), with options, conflist", func() {
// create directory and files
tmpDir, err := os.MkdirTemp("", "multus_thin_entrypoint_tmp")
Expect(err).NotTo(HaveOccurred())
multusAutoConfigDir := fmt.Sprintf("%s/auto_conf", tmpDir)
cniConfDir := fmt.Sprintf("%s/cni_conf", tmpDir)
Expect(os.Mkdir(multusAutoConfigDir, 0755)).To(Succeed())
Expect(os.Mkdir(cniConfDir, 0755)).To(Succeed())
// create master CNI config
masterCNIConfig := `
{
"cniVersion": "1.0.0",
"name": "test1",
"type": "cnitesttype"
}`
Expect(os.WriteFile(fmt.Sprintf("%s/10-testcni.conflist", multusAutoConfigDir), []byte(masterCNIConfig), 0755)).To(Succeed())
masterConfigPath, masterConfigHash, err := (&Options{
MultusAutoconfigDir: multusAutoConfigDir,
CNIConfDir: cniConfDir,
MultusKubeConfigFileHost: "/etc/foobar_kubeconfig",
NamespaceIsolation: true,
GlobalNamespaces: "foobar,barfoo",
MultusLogToStderr: true,
MultusLogLevel: "DEBUG",
MultusLogFile: "/tmp/foobar.log",
AdditionalBinDir: "/tmp/add_bin_dir",
MultusCNIConfDir: "/tmp/multus/net.d",
ReadinessIndicatorFile: "/var/lib/foobar_indicator",
}).createMultusConfig(nil)
Expect(err).NotTo(HaveOccurred())
Expect(masterConfigPath).NotTo(Equal(""))
Expect(masterConfigHash).NotTo(Equal(""))
expectedResult :=
`{
"cniVersion": "1.0.0",
"name": "multus-cni-network",
"plugins": [ {
"type": "multus",
"namespaceIsolation": true,
"globalNamespaces": "foobar,barfoo",
"logLevel": "debug",
"logFile": "/tmp/foobar.log",
"binDir": "/tmp/add_bin_dir",
"cniConf": "/tmp/multus/net.d",
"readinessindicatorfile": "/var/lib/foobar_indicator",
"kubeconfig": "/etc/foobar_kubeconfig",
"delegates": [
{"cniVersion":"1.0.0","name":"test1","type":"cnitesttype"}
]
}]
}
`
conf, err := os.ReadFile(fmt.Sprintf("%s/00-multus.conflist", cniConfDir))
Expect(string(conf)).To(Equal(expectedResult))
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
It("Run createMultusConfig(), with options, conflist", func() {
// create directory and files
tmpDir, err := os.MkdirTemp("", "multus_thin_entrypoint_tmp")
Expect(err).NotTo(HaveOccurred())
multusAutoConfigDir := fmt.Sprintf("%s/auto_conf", tmpDir)
cniConfDir := fmt.Sprintf("%s/cni_conf", tmpDir)
Expect(os.Mkdir(multusAutoConfigDir, 0755)).To(Succeed())
Expect(os.Mkdir(cniConfDir, 0755)).To(Succeed())
// create master CNI config
masterCNIConfigFileName := "10-testcni.conf"
masterCNIConfig := `
{
"cniVersion": "1.0.0",
"name": "test1",
"type": "cnitesttype"
}`
Expect(os.WriteFile(fmt.Sprintf("%s/%s", multusAutoConfigDir, masterCNIConfigFileName), []byte(masterCNIConfig), 0755)).To(Succeed())
// create another CNI config
anotherCNIConfigFileName := "09-test2cni.conf" // Alphabetically before masterCNIConfigFileName
anotherCNIConfig := `
{
"cniVersion": "1.0.0",
"name": "test2",
"type": "cnitest2type"
}`
Expect(os.WriteFile(fmt.Sprintf("%s/%s", multusAutoConfigDir, anotherCNIConfigFileName), []byte(anotherCNIConfig), 0755)).To(Succeed())
masterConfigPath, masterConfigHash, err := (&Options{
MultusAutoconfigDir: multusAutoConfigDir,
MultusMasterCNIFileName: masterCNIConfigFileName,
CNIConfDir: cniConfDir,
MultusKubeConfigFileHost: "/etc/foobar_kubeconfig",
}).createMultusConfig(nil)
Expect(err).NotTo(HaveOccurred())
Expect(masterConfigPath).NotTo(Equal(""))
Expect(masterConfigHash).NotTo(Equal(""))
expectedResult :=
`{
"cniVersion": "1.0.0",
"name": "multus-cni-network",
"plugins": [ {
"type": "multus",
"logToStderr": false,
"kubeconfig": "/etc/foobar_kubeconfig",
"delegates": [
{"cniVersion":"1.0.0","name":"test1","type":"cnitesttype"}
]
}]
}
`
conf, err := os.ReadFile(fmt.Sprintf("%s/00-multus.conflist", cniConfDir))
Expect(string(conf)).To(Equal(expectedResult))
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
It("Run createKubeConfig()", func() {
// create temp dir and files
tmpDir := GinkgoT().TempDir()
cniConfDir := "/cni_conf"
Expect(os.Mkdir(filepath.Join(tmpDir, cniConfDir), 0755)).To(Succeed())
multusConfDir := "/multus_conf"
Expect(os.Mkdir(filepath.Join(tmpDir, multusConfDir), 0755)).To(Succeed())
// Create service account CA file and token file with dummy data
svcAccountPath := filepath.Join(tmpDir, "var/run/secrets/kubernetes.io/serviceaccount")
Expect(os.MkdirAll(svcAccountPath, 0755)).ToNot(HaveOccurred())
svcAccountCAFile := filepath.Join(tmpDir, serviceAccountCAFile)
svcAccountTokenFile := filepath.Join(tmpDir, serviceAccountTokenFile)
Expect(os.WriteFile(svcAccountCAFile, []byte("dummy-ca-content"), 0644)).To(Succeed())
Expect(os.WriteFile(svcAccountTokenFile, []byte("dummy-token-content"), 0644)).To(Succeed())
// Set up the Options struct
options := &Options{
CNIConfDir: cniConfDir,
MultusCNIConfDir: multusConfDir,
}
// Run the createKubeConfig function in a chroot env
back, err := chrootTestHelper(tmpDir)
Expect(err).ToNot(HaveOccurred())
caHash, saTokenHash, err := options.createKubeConfig(nil, nil)
Expect(back()).ToNot(HaveOccurred())
// back to original root
Expect(err).NotTo(HaveOccurred())
Expect(caHash).NotTo(BeNil())
Expect(saTokenHash).NotTo(BeNil())
// Verify the kubeconfig file was created successfully
kubeConfigPath := filepath.Join(tmpDir, cniConfDir, "multus.d", "multus.kubeconfig")
content, err := os.ReadFile(kubeConfigPath)
Expect(err).NotTo(HaveOccurred())
Expect(content).NotTo(BeEmpty())
// Cleanup
Expect(os.RemoveAll(tmpDir)).To(Succeed())
})
})

View File

@@ -0,0 +1,227 @@
# Note:
# This deployment file is designed for 'quickstart' of multus, easy installation to test it,
# hence this deployment yaml does not care about following things intentionally.
# - various configuration options
# - minor deployment scenario
# - upgrade/update/uninstall scenario
# Multus team understand users deployment scenarios are diverse, hence we do not cover
# comprehensive deployment scenario. We expect that it is covered by each platform deployment.
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: network-attachment-definitions.k8s.cni.cncf.io
spec:
group: k8s.cni.cncf.io
scope: Namespaced
names:
plural: network-attachment-definitions
singular: network-attachment-definition
kind: NetworkAttachmentDefinition
shortNames:
- net-attach-def
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
description: 'NetworkAttachmentDefinition is a CRD schema specified by the Network Plumbing
Working Group to express the intent for attaching pods to one or more logical or physical
networks. More information available at: https://github.com/k8snetworkplumbingwg/multi-net-spec'
type: object
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this represen
tation of an object. Servers should convert recognized schemas to the
latest internal value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources'
type: string
kind:
description: 'Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint the client
submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
type: string
metadata:
type: object
spec:
description: 'NetworkAttachmentDefinition spec defines the desired state of a network attachment'
type: object
properties:
config:
description: 'NetworkAttachmentDefinition config is a JSON-formatted CNI configuration'
type: string
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: multus
rules:
- apiGroups: ["k8s.cni.cncf.io"]
resources:
- '*'
verbs:
- '*'
- apiGroups:
- ""
resources:
- pods
- pods/status
verbs:
- get
- update
- apiGroups:
- ""
- events.k8s.io
resources:
- events
verbs:
- create
- patch
- update
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: multus
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: multus
subjects:
- kind: ServiceAccount
name: multus
namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: multus
namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
name: multus-cni-config
namespace: kube-system
labels:
tier: node
app: multus
data:
# NOTE: If you'd prefer to manually apply a configuration file, you may create one here.
# In the case you'd like to customize the Multus installation, you should change the arguments to the Multus pod
# change the "args" line below from
# - "--multus-conf-file=auto"
# to:
# "--multus-conf-file=/tmp/multus-conf/70-multus.conf"
# Additionally -- you should ensure that the name "70-multus.conf" is the alphabetically first name in the
# /etc/cni/net.d/ directory on each node, otherwise, it will not be used by the Kubelet.
cni-conf.json: |
{
"name": "multus-cni-network",
"type": "multus",
"capabilities": {
"portMappings": true
},
"delegates": [
{
"cniVersion": "0.3.1",
"name": "default-cni-network",
"plugins": [
{
"type": "flannel",
"name": "flannel.1",
"delegate": {
"isDefaultGateway": true,
"hairpinMode": true
}
},
{
"type": "portmap",
"capabilities": {
"portMappings": true
}
}
]
}
],
"kubeconfig": "/etc/cni/net.d/multus.d/multus.kubeconfig"
}
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: kube-multus-ds
namespace: kube-system
labels:
tier: node
app: multus
name: multus
spec:
selector:
matchLabels:
name: multus
updateStrategy:
type: RollingUpdate
template:
metadata:
labels:
tier: node
app: multus
name: multus
spec:
hostNetwork: true
tolerations:
- operator: Exists
effect: NoSchedule
- operator: Exists
effect: NoExecute
serviceAccountName: multus
containers:
- name: kube-multus
# crio support requires multus:latest for now. support 3.3 or later.
image: ghcr.io/k8snetworkplumbingwg/multus-cni:stable
command: ["/entrypoint.sh"]
args:
- "--cni-version=0.3.1"
- "--cni-bin-dir=/host/usr/libexec/cni"
- "--multus-conf-file=auto"
resources:
requests:
cpu: "100m"
memory: "50Mi"
limits:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: true
capabilities:
add: ["SYS_ADMIN"]
terminationMessagePolicy: FallbackToLogsOnError
volumeMounts:
- name: run
mountPath: /run
mountPropagation: HostToContainer
- name: cni
mountPath: /host/etc/cni/net.d
- name: cnibin
mountPath: /host/usr/libexec/cni
- name: multus-cfg
mountPath: /tmp/multus-conf
terminationGracePeriodSeconds: 10
volumes:
- name: run
hostPath:
path: /run
- name: cni
hostPath:
path: /etc/cni/net.d
- name: cnibin
hostPath:
path: /usr/libexec/cni
- name: multus-cfg
configMap:
name: multus-cni-config
items:
- key: cni-conf.json
path: 70-multus.conf

View File

@@ -0,0 +1,249 @@
# Note:
# This deployment file is designed for 'quickstart' of multus, easy installation to test it,
# hence this deployment yaml does not care about following things intentionally.
# - various configuration options
# - minor deployment scenario
# - upgrade/update/uninstall scenario
# Multus team understand users deployment scenarios are diverse, hence we do not cover
# comprehensive deployment scenario. We expect that it is covered by each platform deployment.
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: network-attachment-definitions.k8s.cni.cncf.io
spec:
group: k8s.cni.cncf.io
scope: Namespaced
names:
plural: network-attachment-definitions
singular: network-attachment-definition
kind: NetworkAttachmentDefinition
shortNames:
- net-attach-def
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
description: 'NetworkAttachmentDefinition is a CRD schema specified by the Network Plumbing
Working Group to express the intent for attaching pods to one or more logical or physical
networks. More information available at: https://github.com/k8snetworkplumbingwg/multi-net-spec'
type: object
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this represen
tation of an object. Servers should convert recognized schemas to the
latest internal value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources'
type: string
kind:
description: 'Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint the client
submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
type: string
metadata:
type: object
spec:
description: 'NetworkAttachmentDefinition spec defines the desired state of a network attachment'
type: object
properties:
config:
description: 'NetworkAttachmentDefinition config is a JSON-formatted CNI configuration'
type: string
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: multus
rules:
- apiGroups: ["k8s.cni.cncf.io"]
resources:
- '*'
verbs:
- '*'
- apiGroups:
- ""
resources:
- pods
- pods/status
verbs:
- get
- list
- update
- watch
- apiGroups:
- ""
- events.k8s.io
resources:
- events
verbs:
- create
- patch
- update
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: multus
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: multus
subjects:
- kind: ServiceAccount
name: multus
namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: multus
namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
name: multus-daemon-config
namespace: kube-system
labels:
tier: node
app: multus
data:
daemon-config.json: |
{
"chrootDir": "/hostroot",
"cniVersion": "0.3.1",
"logLevel": "verbose",
"logToStderr": true,
"cniConfigDir": "/host/etc/cni/net.d",
"multusAutoconfigDir": "/host/etc/cni/net.d",
"multusConfigFile": "auto",
"socketDir": "/host/run/multus/"
}
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: kube-multus-ds
namespace: kube-system
labels:
tier: node
app: multus
name: multus
spec:
selector:
matchLabels:
name: multus
updateStrategy:
type: RollingUpdate
template:
metadata:
labels:
tier: node
app: multus
name: multus
spec:
hostNetwork: true
hostPID: true
tolerations:
- operator: Exists
effect: NoSchedule
- operator: Exists
effect: NoExecute
serviceAccountName: multus
containers:
- name: kube-multus
image: ghcr.io/k8snetworkplumbingwg/multus-cni:snapshot-thick
command: [ "/usr/src/multus-cni/bin/multus-daemon" ]
resources:
requests:
cpu: "100m"
memory: "50Mi"
limits:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: true
terminationMessagePolicy: FallbackToLogsOnError
volumeMounts:
- name: cni
mountPath: /host/etc/cni/net.d
# multus-daemon expects that cnibin path must be identical between pod and container host.
# e.g. if the cni bin is in '/opt/cni/bin' on the container host side, then it should be mount to '/opt/cni/bin' in multus-daemon,
# not to any other directory, like '/opt/bin' or '/usr/bin'.
- name: cnibin
mountPath: /opt/cni/bin
- name: host-run
mountPath: /host/run
- name: host-var-lib-cni-multus
mountPath: /var/lib/cni/multus
- name: host-var-lib-kubelet
mountPath: /var/lib/kubelet
mountPropagation: HostToContainer
- name: host-run-k8s-cni-cncf-io
mountPath: /run/k8s.cni.cncf.io
- name: host-run-netns
mountPath: /run/netns
mountPropagation: HostToContainer
- name: multus-daemon-config
mountPath: /etc/cni/net.d/multus.d
readOnly: true
- name: hostroot
mountPath: /hostroot
mountPropagation: HostToContainer
env:
- name: MULTUS_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
initContainers:
- name: install-multus-binary
image: ghcr.io/k8snetworkplumbingwg/multus-cni:snapshot-thick
command:
- "cp"
- "/usr/src/multus-cni/bin/multus-shim"
- "/host/opt/cni/bin/multus-shim"
resources:
requests:
cpu: "10m"
memory: "15Mi"
securityContext:
privileged: true
terminationMessagePolicy: FallbackToLogsOnError
volumeMounts:
- name: cnibin
mountPath: /host/opt/cni/bin
mountPropagation: Bidirectional
terminationGracePeriodSeconds: 10
volumes:
- name: cni
hostPath:
path: /etc/cni/net.d
- name: cnibin
hostPath:
path: /opt/cni/bin
- name: hostroot
hostPath:
path: /
- name: multus-daemon-config
configMap:
name: multus-daemon-config
items:
- key: daemon-config.json
path: daemon-config.json
- name: host-run
hostPath:
path: /run
- name: host-var-lib-cni-multus
hostPath:
path: /var/lib/cni/multus
- name: host-var-lib-kubelet
hostPath:
path: /var/lib/kubelet
- name: host-run-k8s-cni-cncf-io
hostPath:
path: /run/k8s.cni.cncf.io
- name: host-run-netns
hostPath:
path: /run/netns/

View File

@@ -0,0 +1,236 @@
# Note:
# This deployment file is designed for 'quickstart' of multus, easy installation to test it,
# hence this deployment yaml does not care about following things intentionally.
# - various configuration options
# - minor deployment scenario
# - upgrade/update/uninstall scenario
# Multus team understand users deployment scenarios are diverse, hence we do not cover
# comprehensive deployment scenario. We expect that it is covered by each platform deployment.
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: network-attachment-definitions.k8s.cni.cncf.io
spec:
group: k8s.cni.cncf.io
scope: Namespaced
names:
plural: network-attachment-definitions
singular: network-attachment-definition
kind: NetworkAttachmentDefinition
shortNames:
- net-attach-def
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
description: 'NetworkAttachmentDefinition is a CRD schema specified by the Network Plumbing
Working Group to express the intent for attaching pods to one or more logical or physical
networks. More information available at: https://github.com/k8snetworkplumbingwg/multi-net-spec'
type: object
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this represen
tation of an object. Servers should convert recognized schemas to the
latest internal value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources'
type: string
kind:
description: 'Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint the client
submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
type: string
metadata:
type: object
spec:
description: 'NetworkAttachmentDefinition spec defines the desired state of a network attachment'
type: object
properties:
config:
description: 'NetworkAttachmentDefinition config is a JSON-formatted CNI configuration'
type: string
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: multus
rules:
- apiGroups: ["k8s.cni.cncf.io"]
resources:
- '*'
verbs:
- '*'
- apiGroups:
- ""
resources:
- pods
- pods/status
verbs:
- get
- update
- apiGroups:
- ""
- events.k8s.io
resources:
- events
verbs:
- create
- patch
- update
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: multus
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: multus
subjects:
- kind: ServiceAccount
name: multus
namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: multus
namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
name: multus-cni-config
namespace: kube-system
labels:
tier: node
app: multus
data:
# NOTE: If you'd prefer to manually apply a configuration file, you may create one here.
# In the case you'd like to customize the Multus installation, you should change the arguments to the Multus pod
# change the "args" line below from
# - "--multus-conf-file=auto"
# to:
# "--multus-conf-file=/tmp/multus-conf/70-multus.conf"
# Additionally -- you should ensure that the name "70-multus.conf" is the alphabetically first name in the
# /etc/cni/net.d/ directory on each node, otherwise, it will not be used by the Kubelet.
cni-conf.json: |
{
"name": "multus-cni-network",
"type": "multus",
"capabilities": {
"portMappings": true
},
"delegates": [
{
"cniVersion": "0.3.1",
"name": "default-cni-network",
"plugins": [
{
"type": "flannel",
"name": "flannel.1",
"delegate": {
"isDefaultGateway": true,
"hairpinMode": true
}
},
{
"type": "portmap",
"capabilities": {
"portMappings": true
}
}
]
}
],
"kubeconfig": "/etc/cni/net.d/multus.d/multus.kubeconfig"
}
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: kube-multus-ds
namespace: kube-system
labels:
tier: node
app: multus
name: multus
spec:
selector:
matchLabels:
name: multus
updateStrategy:
type: RollingUpdate
template:
metadata:
labels:
tier: node
app: multus
name: multus
spec:
hostNetwork: true
tolerations:
- operator: Exists
effect: NoSchedule
- operator: Exists
effect: NoExecute
serviceAccountName: multus
containers:
- name: kube-multus
image: ghcr.io/k8snetworkplumbingwg/multus-cni:snapshot
command: ["/thin_entrypoint"]
args:
- "--multus-conf-file=auto"
- "--multus-autoconfig-dir=/host/etc/cni/net.d"
- "--cni-conf-dir=/host/etc/cni/net.d"
resources:
requests:
cpu: "100m"
memory: "50Mi"
limits:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: true
terminationMessagePolicy: FallbackToLogsOnError
volumeMounts:
- name: cni
mountPath: /host/etc/cni/net.d
- name: cnibin
mountPath: /host/opt/cni/bin
- name: multus-cfg
mountPath: /tmp/multus-conf
initContainers:
- name: install-multus-binary
image: ghcr.io/k8snetworkplumbingwg/multus-cni:snapshot
command: ["/install_multus"]
args:
- "--type"
- "thin"
resources:
requests:
cpu: "10m"
memory: "15Mi"
securityContext:
privileged: true
terminationMessagePolicy: FallbackToLogsOnError
volumeMounts:
- name: cnibin
mountPath: /host/opt/cni/bin
mountPropagation: Bidirectional
terminationGracePeriodSeconds: 10
volumes:
- name: cni
hostPath:
path: /etc/cni/net.d
- name: cnibin
hostPath:
path: /opt/cni/bin
- name: multus-cfg
configMap:
name: multus-cni-config
items:
- key: cni-conf.json
path: 70-multus.conf

View File

@@ -1,277 +0,0 @@
## Multus-cni Configuration Reference
Following is the example of multus config file, in `/etc/cni/net.d/`.
(`"Note1"` and `"Note2"` are just comments, so you can remove them at your configuration)
```
{
"name": "node-cni-network",
"type": "multus",
"kubeconfig": "/etc/kubernetes/node-kubeconfig.yaml",
"confDir": "/etc/cni/multus/net.d",
"cniDir": "/var/lib/cni/multus",
"binDir": "/opt/cni/bin",
"logFile": "/var/log/multus.log",
"logLevel": "debug",
"capabilities": {
"portMappings": true
},
"readinessindicatorfile": "",
"namespaceIsolation": false,
"Note1":"NOTE: you can set clusterNetwork+defaultNetworks OR delegates!!",
"clusterNetwork": "defaultCRD",
"defaultNetworks": ["sidecarCRD", "flannel"],
"systemNamespaces": ["kube-system", "admin"],
"multusNamespace": "kube-system",
"Note2":"NOTE: If you use clusterNetwork/defaultNetworks, delegates is ignored",
"delegates": [{
"type": "weave-net",
"hairpinMode": true
}, {
"type": "macvlan",
... (snip)
}]
}
```
* `name` (string, required): the name of the network
* `type` (string, required): &quot;multus&quot;
* `confDir` (string, optional): directory for CNI config file that multus reads. default `/etc/cni/multus/net.d`
* `cniDir` (string, optional): Multus CNI data directory, default `/var/lib/cni/multus`
* `binDir` (string, optional): additional directory for CNI plugins which multus calls, in addition to the default (the default is typically set to `/opt/cni/bin`)
* `kubeconfig` (string, optional): kubeconfig file for the out of cluster communication with kube-apiserver. See the example [kubeconfig](https://github.com/intel/multus-cni/blob/master/doc/node-kubeconfig.yaml). If you would like to use CRD (i.e. network attachment definition), this is required
* `logFile` (string, optional): file path for log file. multus puts log in given file
* `logLevel` (string, optional): logging level ("debug", "error", "verbose", or "panic")
* `namespaceIsolation` (boolean, optional): Enables a security feature where pods are only allowed to access `NetworkAttachmentDefinitions` in the namespace where the pod resides. Defaults to false.
* `capabilities` ({}list, optional): [capabilities](https://github.com/containernetworking/cni/blob/master/CONVENTIONS.md#dynamic-plugin-specific-fields-capabilities--runtime-configuration) supported by at least one of the delegates. (NOTE: Multus only supports portMappings capability for now). See the [example](https://github.com/intel/multus-cni/blob/master/examples/multus-ptp-portmap.conf).
* `readinessindicatorfile`: The path to a file whose existance denotes that the default network is ready
User should chose following parameters combination (`clusterNetwork`+`defaultNetworks` or `delegates`):
* `clusterNetwork` (string, required): default CNI network for pods, used in kubernetes cluster (Pod IP and so on): name of network-attachment-definition, CNI json file name (without extention, .conf/.conflist) or directory for CNI config file
* `defaultNetworks` ([]string, required): default CNI network attachment: name of network-attachment-definition, CNI json file name (without extention, .conf/.conflist) or directory for CNI config file
* `systemNamespaces` ([]string, optional): list of namespaces for Kubernetes system (namespaces listed here will not have `defaultNetworks` added)
* `multusNamespace` (string, optional): namespace for `clusterNetwork`/`defaultNetworks`
* `delegates` ([]map,required): number of delegate details in the Multus
### Network selection flow of clusterNetwork/defaultNetworks
Multus will find network for clusterNetwork/defaultNetworks as following sequences:
1. CRD object for given network name, in 'kube-system' namespace
1. CNI json config file in `confDir`. Given name should be without extention, like .conf/.conflist. (e.g. "test" for "test.conf")
1. Directory for CNI json config file. Multus will find alphabetically first file for the network
1. Multus failed to find network. Multus raise error message
## Miscellaneous config
### Default Network Readiness Indicator
You may wish for your "default network" (that is, the CNI plugin & its configuration you specify as your default delegate) to become ready before you attach networks with Multus. This is disabled by default and not used unless you add the readiness check option(s) to your CNI configuration file.
For example, if you use Flannel as a default network, the recommended method for Flannel to be installed is via a daemonset that also drops a configuration file in `/etc/cni/net.d/`. This may apply to other plugins that place that configuration file upon their readiness, hence, Multus uses their configuration filename as a semaphore and optionally waits to attach networks to pods until that file exists.
In this manner, you may prevent pods from crash looping, and instead wait for that default network to be ready.
Only one option is necessary to configure this functionality:
* `readinessindicatorfile`: The path to a file whose existance denotes that the default network is ready.
*NOTE*: If `readinessindicatorfile` is unset, or is an empty string, this functionality will be disabled, and is disabled by default.
### Logging
You may wish to enable some enhanced logging for Multus, especially during the process where you're configuring Multus and need to understand what is or isn't working with your particular configuration.
Multus will always log via `STDERR`, which is the standard method by which CNI plugins communicate errors, and these errors are logged by the Kubelet. This method is always enabled.
#### Writing to a Log File
Optionally, you may have Multus log to a file on the filesystem. This file will be written locally on each node where Multus is executed. You may configure this via the `LogFile` option in the CNI configuration. By default this additional logging to a flat file is disabled.
For example in your CNI configuration, you may set:
```
"LogFile": "/var/log/multus.log",
```
#### Logging Level
The default logging level is set as `panic` -- this will log only the most critical errors, and is the least verbose logging level.
The available logging level values, in decreasing order of verbosity are:
* `debug`
* `verbose`
* `error`
* `panic`
You may configure the logging level by using the `LogLevel` option in your CNI configuration. For example:
```
"LogLevel": "debug",
```
### Namespace Isolation
The functionality provided by the `namespaceIsolation` configuration option enables a mode where Multus only allows pods to access custom resources (the `NetworkAttachmentDefinitions`) within the namespace where that pod resides. In other words, the `NetworkAttachmentDefinitions` are isolated to usage within the namespace in which they're created.
For example, if a pod is created in the namespace called `development`, Multus will not allow networks to be attached when defined by custom resources created in a different namespace, say in the `default` network.
Consider the situation where you have a system that has users of different privilege levels -- as an example, a platform which has two administrators: a Senior Administrator and a Junior Administrator. The Senior Administrator may have access to all namespaces, and some network configurations as used by Multus are considered to be privileged in that they allow access to some protected resources available on the network. However, the Junior Administrator has access to only a subset of namespaces, and therefore it should be assumed that the Junior Administrator cannot create pods in their limited subset of namespaces. The `namespaceIsolation` feature provides for this isolation, allowing pods created in given namespaces to only access custom resources in the same namespace as the pod.
Namespace Isolation is disabled by default.
#### Configuration example
```
"namespaceIsolation": true,
```
#### Usage example
Let's setup an example where we:
* Create a custom resource in a namespace called `privileged`
* Create a pod in a namespace called `development`, and have annotations that reference a custom resource in the `privileged` namespace. The creation of this pod should be disallowed by Multus (as we'll have the use of the custom resources limited only to those custom resources created within the same namespace as the pod).
Given the above scenario with a Junior & Senior Administrator. You may assume that the Senior Administrator has access to all namespaces, whereas the Junior Administrator has access only to the `development` namespace.
Firstly, we show that we have a number of namespaces available:
```
# List the available namespaces
[user@kube-master ~]$ kubectl get namespaces
NAME STATUS AGE
default Active 7h27m
development Active 3h
kube-public Active 7h27m
kube-system Active 7h27m
privileged Active 4s
```
We'll create a `NetworkAttachmentDefinition` in the `privileged` namespace.
```
# Show the network attachment definition we're creating.
[user@kube-master ~]$ cat cr.yml
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth0",
"mode": "bridge",
"ipam": {
"type": "host-local",
"subnet": "192.168.1.0/24",
"rangeStart": "192.168.1.200",
"rangeEnd": "192.168.1.216",
"routes": [
{ "dst": "0.0.0.0/0" }
],
"gateway": "192.168.1.1"
}
}'
# Create that network attachment definition in the privileged namespace
[user@kube-master ~]$ kubectl create -f cr.yml -n privileged
networkattachmentdefinition.k8s.cni.cncf.io/macvlan-conf created
# List the available network attachment definitions in the privileged namespace.
[user@kube-master ~]$ kubectl get networkattachmentdefinition.k8s.cni.cncf.io -n privileged
NAME AGE
macvlan-conf 11s
```
Next, we'll create a pod with an annotation that references the privileged namespace. Pay particular attention to the annotation that reads `k8s.v1.cni.cncf.io/networks: privileged/macvlan-conf` -- where it contains a reference to a `namespace/configuration-name` formatted network attachment name. In this case referring to the `macvlan-conf` in the namespace called `privileged`.
```
# Show the yaml for a pod.
[user@kube-master ~]$ cat example.pod.yml
apiVersion: v1
kind: Pod
metadata:
name: samplepod
annotations:
k8s.v1.cni.cncf.io/networks: privileged/macvlan-conf
spec:
containers:
- name: samplepod
command: ["/bin/bash", "-c", "sleep 2000000000000"]
image: dougbtv/centos-network
# Create that pod.
[user@kube-master ~]$ kubectl create -f example.pod.yml -n development
pod/samplepod created
```
You'll note that pod fails to spawn successfully. If you check the Multus logs, you'll see an entry such as:
```
2018-12-18T21:41:32Z [error] GetPodNetwork: namespace isolation violation: podnamespace: development / target namespace: privileged
```
This error expresses that the pod resides in the namespace named `development` but refers to a `NetworkAttachmentDefinition` outside of that namespace, in this case, the namespace named `privileged`.
In a positive example, you'd instead create the `NetworkAttachmentDefinition` in the `development` namespace, and you'd have an annotation that either A. does not reference a namespace, or B. refers to the same annotation.
A positive example may be:
```
# Create the same NetworkAttachmentDefinition as above, however in the development namespace
[user@kube-master ~]$ kubectl create -f cr.yml -n development
networkattachmentdefinition.k8s.cni.cncf.io/macvlan-conf created
# Show the yaml for a sample pod which references macvlan-conf without a namspace/ format
[user@kube-master ~]$ cat positive.example.pod
apiVersion: v1
kind: Pod
metadata:
name: samplepod
annotations:
k8s.v1.cni.cncf.io/networks: macvlan-conf
spec:
containers:
- name: samplepod
command: ["/bin/bash", "-c", "sleep 2000000000000"]
image: dougbtv/centos-network
# Create that pod.
[user@kube-master ~]$ kubectl create -f positive.example.pod -n development
pod/samplepod created
# We can see that this pod has been launched successfully.
[user@kube-master ~]$ kubectl get pods -n development
NAME READY STATUS RESTARTS AGE
samplepod 1/1 Running 0 31s
```
### Specify default cluster network in Pod annotations
Users may also specify the default network for any given pod (via annotation), for cases where there are multiple cluster networks available within a Kubernetes cluster.
Example use cases may include:
1. During a migration from one default network to another (e.g. from Flannel to Calico), it may be practical if both network solutions are able to operate in parallel. Users can then control which network a pod should attach to during the transition period.
2. Some users may deploy multiple cluster networks for the sake of their security considerations, and may desire to specify the default network for individual pods.
Follow these steps to specify the default network on a pod-by-pod basis:
1. First, you need to define all your cluster networks as network-attachment-definition objects.
2. Next, you can specify the network you want in pods with the `v1.multus-cni.io/default-network` annotation. Pods which do not specify this annotation will keep using the CNI as defined in the Multus config file.
```yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-example
annotations:
v1.multus-cni.io/default-network: calico-conf
...
```

View File

@@ -1,30 +0,0 @@
## Development Information
## How to build the multus-cni?
```
git clone https://github.com/intel/multus-cni.git
cd multus-cni
./build
```
## How to run CI tests?
Multus has go unit tests (based on ginkgo framework).The following commands drive CI tests manually in your environment:
```
sudo ./test.sh
```
## Logging Best Practices
Following are multus logging best practices:
* Add `logging.Debugf()` at the begining of functions
* In case of error handling, use `logging.Errorf()` with given error info
* `logging.Panicf()` only be used for critical errors (it should NOT normally be used)
## CI Introduction
TBD

View File

@@ -1,551 +0,0 @@
## Multus CNI usage guide
### Prerequisites
* Kubelet configured to use CNI
* Kubernetes version with CRD support (generally )
Your Kubelet(s) must be configured to run with the CNI network plugin. Please see [Kubernetes document for CNI](https://kubernetes.io/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/#cni) for more details.
### Install Multus
Generally we recommend two options: Manually place a Multus binary in your `/opt/cni/bin`, or use our [quick-start method](quickstart.md) -- which creates a daemonset that has an opinionated way of how to install & configure Multus CNI (recommended).
*Copy Multus Binary into place*
You may acquire the Multus binary via compilation (see the [developer guide](development.md)) or download the a binary from the [GitHub releases](https://github.com/intel/multus-cni/releases) page. Copy multus binary into CNI binary directory, usually `/opt/cni/bin`. Perform this on all nodes in your cluster (master and nodes).
$ cp multus /opt/cni/bin
*Via Daemonset method*
As a [quickstart](quickstart.md), you may apply these YAML files (included in the clone of this repository). Run this command (typically you would run this on the master, or wherever you have access to the `kubectl` command to manage your cluster).
$ cat ./images/{multus-daemonset.yml,flannel-daemonset.yml} | kubectl apply -f -
If you need more comprehensive detail, continue along with this guide, otherwise, you may wish to either [follow the quickstart guide]() or skip to the ['Create network attachment definition'](#create-network-attachment-definition) section.
### Set up conf file in /etc/cni/net.d/ (Installed automatically by Daemonset)
**If you use daemonset to install multus, skip this section and go to "Create network attachment"**
You put CNI config file in `/etc/cni/net.d`. Kubernetes CNI runtime uses the alphabetically first file in the directory. (`"NOTE1"`, `"NOTE2"` are just comments, you can remove them at your configuration)
Execute following commands at all Kubernetes nodes (i.e. master and minions)
```
$ mkdir -p /etc/cni/net.d
$ cat >/etc/cni/net.d/30-multus.conf <<EOF
{
"name": "multus-cni-network",
"type": "multus",
"readinessindicatorfile": "/var/run/flannel/subnet.env",
"delegates": [
{
"NOTE1": "This is example, wrote your CNI config in delegates",
"NOTE2": "If you use flannel, you also need to run flannel daemonset before!",
"type": "flannel",
"name": "flannel.1",
"delegate": {
"isDefaultGateway": true
}
}
],
"kubeconfig": "/etc/cni/net.d/multus.d/multus.kubeconfig"
}
EOF
```
For the detail, please take a look into [Configuration Reference](configuration.md)
**NOTE: You can use "clusterNetwork"/"defaultNetworks" instead of "delegates", see []() for the detail**
As above config, you need to set `"kubeconfig"` in the config file for NetworkAttachmentDefinition(CRD).
##### Which network will be used for "Pod IP"?
In case of "delegates", the first delegates network will be used for "Pod IP". Otherwise, "clusterNetwork" will be used for "Pod IP".
#### Create ServiceAccount, ClusterRole and its binding
Create resources for multus to access CRD objects as following command:
```
# Execute following commands at Kubernetes master
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: ServiceAccount
metadata:
name: multus
namespace: kube-system
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: multus
rules:
- apiGroups: ["k8s.cni.cncf.io"]
resources:
- '*'
verbs:
- '*'
- apiGroups:
- ""
resources:
- pods
- pods/status
verbs:
- get
- update
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: multus
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: multus
subjects:
- kind: ServiceAccount
name: multus
namespace: kube-system
EOF
```
#### Set up kubeconfig file
Create kubeconfig at master node as following commands:
```
# Execute following command at Kubernetes master
$ mkdir -p /etc/cni/net.d/multus.d
$ SERVICEACCOUNT_CA=$(kubectl get secrets -n=kube-system -o json | jq -r '.items[]|select(.metadata.annotations."kubernetes.io/service-account.name"=="multus")| .data."ca.crt"')
$ SERVICEACCOUNT_TOKEN=$(kubectl get secrets -n=kube-system -o json | jq -r '.items[]|select(.metadata.annotations."kubernetes.io/service-account.name"=="multus")| .data.token' | base64 -d )
$ KUBERNETES_SERVICE_PROTO=$(kubectl get all -o json | jq -r .items[0].spec.ports[0].name)
$ KUBERNETES_SERVICE_HOST=$(kubectl get all -o json | jq -r .items[0].spec.clusterIP)
$ KUBERNETES_SERVICE_PORT=$(kubectl get all -o json | jq -r .items[0].spec.ports[0].port)
$ cat > /etc/cni/net.d/multus.d/multus.kubeconfig <<EOF
# Kubeconfig file for Multus CNI plugin.
apiVersion: v1
kind: Config
clusters:
- name: local
cluster:
server: ${KUBERNETES_SERVICE_PROTOCOL:-https}://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}
certificate-authority-data: ${SERVICEACCOUNT_CA}
users:
- name: multus
user:
token: "${SERVICEACCOUNT_TOKEN}"
contexts:
- name: multus-context
context:
cluster: local
user: multus
current-context: multus-context
EOF
```
Copy `/etc/cni/net.d/multus.d/multus.kubeconfig` into other Kubernetes nodes
**NOTE: Recommend to exec 'chmod 600 /etc/cni/net.d/multus.d/multus.kubeconfig' to keep secure**
```
$ scp /etc/cni/net.d/multus.d/multus.kubeconfig ...
```
### Setup CRDs (daemonset automatically does)
**If you use daemonset to install multus, skip this section and go to "Create network attachment"**
Create CRD definition in Kubernetes as following command at master node:
```
# Execute following command at Kubernetes master
$ cat <<EOF | kubectl create -f -
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: network-attachment-definitions.k8s.cni.cncf.io
spec:
group: k8s.cni.cncf.io
version: v1
scope: Namespaced
names:
plural: network-attachment-definitions
singular: network-attachment-definition
kind: NetworkAttachmentDefinition
shortNames:
- net-attach-def
validation:
openAPIV3Schema:
properties:
spec:
properties:
config:
type: string
EOF
```
### Create network attachment definition
The 'NetworkAttachmentDefinition' is used to setup the network attachment, i.e. secondary interface for the pod, There are two ways to configure the 'NetworkAttachmentDefinition' as following:
- NetworkAttachmentDefinition with json CNI config
- NetworkAttachmentDefinition with CNI config file
#### NetworkAttachmentDefinition with json CNI config:
Following command creates NetworkAttachmentDefinition. CNI config is in `config:` field.
```
# Execute following command at Kubernetes master
$ cat <<EOF | kubectl create -f -
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf-1
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "host-local",
"ranges": [
[ {
"subnet": "10.10.0.0/16",
"rangeStart": "10.10.1.20",
"rangeEnd": "10.10.3.50",
"gateway": "10.10.0.254"
} ]
]
}
}'
EOF
```
#### NetworkAttachmentDefinition with CNI config file:
If NetworkAttachmentDefinition has no spec, multus find a file in defaultConfDir ('/etc/cni/multus/net.d', with same name in the 'name' field of CNI config.
```
# Execute following command at Kubernetes master
$ cat <<EOF | kubectl create -f -
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf-2
EOF
```
```
# Execute following commands at all Kubernetes nodes (i.e. master and minions)
$ cat <<EOF > /etc/cni/multus/net.d/macvlan2.conf
{
"cniVersion": "0.3.0",
"type": "macvlan",
"name": "macvlan-conf-2",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "host-local",
"ranges": [
[ {
"subnet": "11.10.0.0/16",
"rangeStart": "11.10.1.20",
"rangeEnd": "11.10.3.50"
} ]
]
}
}
```
### Run pod with network annotation
#### Lauch pod with text annotation
```
# Execute following command at Kubernetes master
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-01
annotations:
k8s.v1.cni.cncf.io/networks: macvlan-conf-1, macvlan-conf-2
spec:
containers:
- name: pod-case-01
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
#### Lauch pod with text annotation for NetworkAttachmentDefinition in different namespace
You can also specify NetworkAttachmentDefinition with its namespace as adding `<namespace>/`
```
# Execute following command at Kubernetes master
$ cat <<EOF | kubectl create -f -
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf-3
namespace: testns1
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "host-local",
"ranges": [
[ {
"subnet": "12.10.0.0/16",
"rangeStart": "12.10.1.20",
"rangeEnd": "12.10.3.50"
} ]
]
}
}'
EOF
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-02
annotations:
k8s.v1.cni.cncf.io/networks: testns1/macvlan-conf-3
spec:
containers:
- name: pod-case-02
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
#### Lauch pod with text annotation with interface name
You can also specify interface name as adding `@<ifname>`.
```
# Execute following command at Kubernetes master
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-03
annotations:
k8s.v1.cni.cncf.io/networks: macvlan-conf-1@macvlan1
spec:
containers:
- name: pod-case-03
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
#### Lauch pod with json annotation
```
# Execute following command at Kubernetes master
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-04
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name" : "macvlan-conf-1" },
{ "name" : "macvlan-conf-2" }
]'
spec:
containers:
- name: pod-case-04
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
#### Lauch pod with json annotation for NetworkAttachmentDefinition in different namespace
You can also specify NetworkAttachmentDefinition with its namespace as adding `"namespace": "<namespace>"`.
```
# Execute following command at Kubernetes master
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-05
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name" : "macvlan-conf-1",
"namespace": "testns1" }
]'
spec:
containers:
- name: pod-case-05
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
#### Lauch pod with json annotation with interface
You can also specify interface name as adding `"interface": "<ifname>"`.
```
# Execute following command at Kubernetes master
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-06
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name" : "macvlan-conf-1",
"interface": "macvlan1" },
{ "name" : "macvlan-conf-2" }
]'
spec:
containers:
- name: pod-case-06
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
### Verifying pod network
Following the example of `ip -d address` output of above pod, "pod-case-06":
```
# Execute following command at Kubernetes master
$ kubectl exec -it pod-case-06 -- ip -d address
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 promiscuity 0 numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
3: eth0@if11: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UP group default
link/ether 0a:58:0a:f4:02:06 brd ff:ff:ff:ff:ff:ff link-netnsid 0 promiscuity 0
veth numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535
inet 10.244.2.6/24 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::ac66:45ff:fe7c:3a19/64 scope link
valid_lft forever preferred_lft forever
4: macvlan1@if3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default
link/ether 4e:6d:7a:4e:14:87 brd ff:ff:ff:ff:ff:ff link-netnsid 0 promiscuity 0
macvlan mode bridge numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535
inet 10.10.1.22/16 scope global macvlan1
valid_lft forever preferred_lft forever
inet6 fe80::4c6d:7aff:fe4e:1487/64 scope link
valid_lft forever preferred_lft forever
5: net2@if3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default
link/ether 6e:e3:71:7f:86:f7 brd ff:ff:ff:ff:ff:ff link-netnsid 0 promiscuity 0
macvlan mode bridge numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535
inet 11.10.1.22/16 scope global net2
valid_lft forever preferred_lft forever
inet6 fe80::6ce3:71ff:fe7f:86f7/64 scope link
valid_lft forever preferred_lft forever
```
| Interface name | Description |
| --- | --- |
| lo | loopback |
| eth0 | Default network interface (flannel) |
| macvlan1 | macvlan interface (macvlan-conf-1) |
| net2 | macvlan interface (macvlan-conf-2) |
## Entrypoint Parameters
Multus CNI, when installed using the daemonset-style installation uses an entrypoint script which copies the Multus binary into place, places CNI configurations. This entrypoint takes a variety of parameters for customization.
Typically, you'd modified the daemonset YAML itself to specify these parameters.
For example, the `command` and `args` parameters in the `containers` section of the DaemonSet may look something like:
```
command: ["/entrypoint.sh"]
args:
- "--multus-conf-file=auto"
- "--namespace-isolation=true"
- "--multus-log-level=verbose"
```
Note that some of the defaults have directories inside the root directory named `/host/`, this is because it is deployed as a container and we have host file system locations mapped into this directory inside the container. If you use other directories, you may have to change the mounted volumes.
### Entrypoint script parameters
Each parameter is shown with the default as the value.
--cni-conf-dir=/host/etc/cni/net.d
This is the configuration directory where Multus will write its configuration file.
--cni-bin-dir=/host/opt/cni/bin
This the directory in which the Multus binary will be installed.
--namespace-isolation=false
Setting this option to true enables the Namespace isolation feature, which insists that custom resources must be created in the same namespace as the pods, otherwise it will refuse to attach those definitions as additional interfaces.
--multus-bin-file=/usr/src/multus-cni/bin/multus
This option lets you set which binary executable to copy from the container onto the host (into the directory specified by `--cni-bin-dir`), allowing one to copy an alternate version or build of Multus CNI.
--multus-conf-file=/usr/src/multus-cni/images/70-multus.conf
The `--multus-conf-file` is one of two options; it can be set to a source file to be copied into the location specified by `--cni-conf-dir`. Or, to a value of `auto`, that is: `--multus-conf-file=auto`.
The automatic configuration option is used to automatically generate Multus configurations given existing on-disk CNI configurations for your default network.
In the case that `--multus-conf-file=auto` -- The entrypoint script will look at the `--multus-autoconfig-dir` (by default, the same as the `--cni-conf-dir`). Multus will wait (600 seconds) until there's a CNI configuration file there, and it will take the alphabetically first configuration there, and it will wrap that configuration into a Multus configuration.
--multus-autoconfig-dir=/host/etc/cni/net.d
Used only with `--multus-conf-file=auto`. This option allows one to set which directory will be used to generate configuration files.
This can be used if you have your CNI configuration stored in an alternate location, or, you have constraints on race conditions where you'd like to generate your default network configuration first, and then only have Multus write its configuration when it finds that configuration -- allowing only Multus to write the CNI configuration in the `--cni-conf-dir`, therefore notifying the Kubelet that the node is in a ready state.
--multus-kubeconfig-file-host=/etc/cni/net.d/multus.d/multus.kubeconfig
Used only with `--multus-conf-file=auto`. Allows you to specify an alternate path to the Kubeconfig.
--multus-log-level=
--multus-log-file=
Used only with `--multus-conf-file=auto`. See the documentation for logging for which values are permitted.
Used only with `--multus-conf-file=auto`. Allows you to specify CNI spec version. Please set if you need to speicfy CNI spec version.
--cni-version=
In some cases, the original CNI configuration that the Multus configuration was generated from (using `--multus-conf-file=auto`) may be used as a sort of semaphor for network readiness -- as this model is used by the Kubelet itself. If you need to disable Multus' availablity, you may wish to clean out the generated configuration file when the source file for autogeneration of the config file is no longer present. You can use this functionality by setting:
--cleanup-config-on-exit=true
When using CRIO, you may need to restart CRIO to get the Multus configuration file to take -- this is rarely necessary.
--restart-crio=false
Additionally when using CRIO, you may wish to have the CNI config file that's used as the source for `--multus-conf-file=auto` renamed. This boolean option when set to true automatically renames the file with a `.old` suffix to the original filename.
--rename-conf-file=true
When using `--multus-conf-file=auto` you may also care to specify a `binDir` in the configuration, this can be accomplished using the `--additional-bin-dir` option.
--additional-bin-dir=/opt/multus/bin

382
docs/configuration.md Normal file
View File

@@ -0,0 +1,382 @@
# Multus-cni Configuration Reference
## Introduction
Aside from setting options for Multus, one of the goals of configuration is to set the configuration for your *default network*. The default network is also sometimes referred as the "primary CNI plugin", the "primary network", or a "default CNI plugin" and is the CNI plugin that is used to implement [the Kubernetes networking model](https://kubernetes.io/docs/concepts/services-networking/#the-kubernetes-network-model) in your cluster. Common examples include Flannel, Weave, Calico, Cillium, and OVN-Kubernetes, among others.
Here we will refer to this as your default CNI plugin or default network.
## Example configuration
Following is the example of multus config file, in `/etc/cni/net.d/`.
Example configuration using `clusterNetwork` (see also [using delegates](#using-delegates))
```
{
"cniVersion": "0.3.1",
"name": "node-cni-network",
"type": "multus",
"kubeconfig": "/etc/kubernetes/node-kubeconfig.yaml",
"confDir": "/etc/cni/multus/net.d",
"cniDir": "/var/lib/cni/multus",
"binDir": "/opt/cni/bin",
"logFile": "/var/log/multus.log",
"logLevel": "debug",
"logOptions": {
"maxAge": 5,
"maxSize": 100,
"maxBackups": 5,
"compress": true
},
"capabilities": {
"portMappings": true
},
"namespaceIsolation": false,
"clusterNetwork": "/etc/cni/net.d/99-flannel.conf",
"defaultNetworks": ["sidecarCRD", "exampleNetwork"],
"systemNamespaces": ["kube-system", "admin"],
"multusNamespace": "kube-system",
allowTryDeleteOnErr: false
}
```
## Index of configuration options
This is a general index of options, however note that you must set either the `clusterNetwork` or `delegates` options, see the following sections after the index for details.
* `name` (string, required): The name of the network
* `type` (string, required): Must be set to the value of &quot;multus&quot;
* `confDir` (string, optional): directory for CNI config file that multus reads. default `/etc/cni/multus/net.d`
* `cniDir` (string, optional): Multus CNI data directory, default `/var/lib/cni/multus`
* `binDir` (string, optional): additional directory for CNI plugins which multus calls, in addition to the default (the default is typically set to `/opt/cni/bin`)
* `kubeconfig` (string, optional): kubeconfig file for the out of cluster communication with kube-apiserver. See the example [kubeconfig](https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/docs/node-kubeconfig.yaml). If you would like to use CRD (i.e. network attachment definition), this is required
* [`logToStderr`](#Logging-via-STDERR) (bool, optional): Enable or disable logging to `STDERR`. Defaults to true.
* [`logFile`](#Writing-to-a-Log-File) (string, optional): file path for log file. multus puts log in given file
* [`logLevel`](#Logging-Level) (string, optional): logging level (values in decreasing order of verbosity: "debug", "error", "verbose", or "panic")
* [`logOptions`](#Logging-Options) (object, optional): logging option, More detailed log configuration
* [`namespaceIsolation`](#Namespace-Isolation) (boolean, optional): Enables a security feature where pods are only allowed to access `NetworkAttachmentDefinitions` in the namespace where the pod resides. Defaults to false.
* [`globalNamespaces`](#Allow-specific-namespaces-to-be-used-across-namespaces-when-using-namespace-isolation): (string, optional): Used only when `namespaceIsolation` is true, allows specification of comma-delimited list of namespaces which may be referred to outside of namespace isolation.
* `capabilities` ({}list, optional): [capabilities](https://github.com/containernetworking/cni/blob/master/CONVENTIONS.md#dynamic-plugin-specific-fields-capabilities--runtime-configuration) supported by at least one of the delegates. (NOTE: Multus only supports portMappings/Bandwidth capability for cluster networks).
* [`readinessindicatorfile`](#Default-Network-Readiness-Indicator): The path to a file whose existence denotes that the default network is ready
message to next when some missing error. Defaults to false.
* `systemNamespaces` ([]string, optional): list of namespaces for Kubernetes system (namespaces listed here will not have `defaultNetworks` added)
* `multusNamespace` (string, optional): namespace for `clusterNetwork`/`defaultNetworks` (the default value is `kube-system`)
* `retryDeleteOnError` (bool, optional): Enable or disable delegate DEL
### Using `clusterNetwork`
Using the `clusterNetwork` option and the `delegates` are **mutually exclusive**. If `clusterNetwork` is set, the `delegates` field is *ignored*.
You **must** set one or the other.
Therefore:
* Set `clusterNetwork` and if this is set, optionally set the `defaultNetworks`.
* OR you **must** set `delegates`.
Options:
* `clusterNetwork` (string, required if not using `delegates`): the default CNI plugin to be executed.
* `defaultNetworks` ([]string, optional): Additional / secondary network attachment that is always attached to each pod.
The following values are valid for both `clusterNetwork` and `defaultNetworks` and are processed in the following order:
* The name of a `NetworkAttachmentDefinition` custom resource in the namespace specified by the `multusNamespace` configuration option
* The `"name"` value in the contents of a CNI JSON configuration file in the CNI configuration directory,
* The given name for `clusterNetwork` should match the value for `name` key in the contents of the CNI JSON file (e.g. `"name": "test"` in `my.conf` when `"clusterNetwork": "test"`)
* A path to a directory containing CNI json configuration files. The alphabetically first file will be used.
* Absolute file path for CNI config file
* If none of the above are found using the value, Multus will raise an error.
If for example you have `defaultNetworks` set as:
```
"defaultNetworks": ["sidecarNetwork", "exampleNetwork"],
```
In this example, the values in the expression refer to `NetworkAttachmentDefinition` custom resource names. Therefore, there must be `NetworkAttachmentDefinitions` already created with the names `sidecarNetwork` and `exampleNetwork`.
This means that in addition to the cluster network, each pod would be assigned two additional networks by default, and the pod would present three interfaces, e.g. `eth0`, `net1`, and `net2`, with `net1` and `net2` being set by the above described `NetworkAttachmentDefinitions`. Additional attachments as made by setting `k8s.v1.cni.cncf.io/networks` on pods will be made in addition to those set in the `defaultNetworks` configuration option.
### Using `delegates`
If `clusterNetwork` is not set, you **must** use `delegates`.
* `delegates` ([]map, required if not using `clusterNetwork`). List of CNI configurations to be used as your default CNI plugin(s).
Example configuration using `delegates`:
```
{
"cniVersion": "0.3.1",
"name": "node-cni-network",
"type": "multus",
"kubeconfig": "/etc/kubernetes/node-kubeconfig.yaml",
"confDir": "/etc/cni/multus/net.d",
"cniDir": "/var/lib/cni/multus",
"binDir": "/opt/cni/bin",
"delegates": [{
"type": "weave-net",
"hairpinMode": true
}, {
"type": "macvlan",
... (snip)
}]
}
```
## Configuration Option Details
### Default Network Readiness Indicator
You may desire that your default network becomes ready before attaching networks with Multus. This is disabled by default and not used unless you set the `readinessindicatorfile` option to a non-blank value.
For example, if you use Flannel as a default network, the recommended method for Flannel to be installed is via a daemonset that also drops a configuration file in `/etc/cni/net.d/`. This may apply to other plugins that place that configuration file upon their readiness, therefore, Multus uses their configuration filename as a semaphore and optionally waits to attach networks to pods until that file exists.
In this manner, you may prevent pods from crash looping, and instead wait for that default network to be ready.
Only one option is necessary to configure this functionality:
* `readinessindicatorfile`: The path to a file whose existence denotes that the default network is ready.
*NOTE*: If `readinessindicatorfile` is unset, or is an empty string, this functionality will be disabled, and is disabled by default.
### Logging
You may wish to enable some enhanced logging for Multus, especially during the process where you're configuring Multus and need to understand what is or isn't working with your particular configuration.
#### Logging via STDERR
By default, Multus will log via `STDERR`, which is the standard method by which CNI plugins communicate errors, and these errors are logged by the Kubelet.
Optionally, you may disable this method by setting the `logToStderr` option in your CNI configuration:
```
"logToStderr": false,
```
#### Writing to a Log File
Optionally, you may have Multus log to a file on the filesystem. This file will be written locally on each node where Multus is executed. You may configure this via the `LogFile` option in the CNI configuration. By default this additional logging to a flat file is disabled.
For example in your CNI configuration, you may set:
```
"logFile": "/var/log/multus.log",
```
#### Logging Level
The default logging level is set as `panic` -- this will log only the most critical errors, and is the least verbose logging level.
The available logging level values, in decreasing order of verbosity are:
* `debug`
* `verbose`
* `error`
* `panic`
You may configure the logging level by using the `LogLevel` option in your CNI configuration. For example:
```
"logLevel": "debug",
```
#### Logging Options
If you want a more detailed configuration of the logging, This includes the following parameters:
* `maxAge` the maximum number of days to retain old log files in their filename
* `maxSize` the maximum size in megabytes of the log file before it gets rotated
* `maxBackups` the maximum number of days to retain old log files in their filename
* `compress` compress determines if the rotated log files should be compressed using gzip
For example in your CNI configuration, you may set:
```
"logOptions": {
"maxAge": 5,
"maxSize": 100,
"maxBackups": 5,
"compress": true
}
```
### Namespace Isolation
The functionality provided by the `namespaceIsolation` configuration option enables a mode where Multus only allows pods to access custom resources (the `NetworkAttachmentDefinitions`) within the namespace where that pod resides. In other words, the `NetworkAttachmentDefinitions` are isolated to usage within the namespace in which they're created.
**NOTE**: The default namespace is special in this scenario. Even with namespace isolation enabled, any pod, in any namespace is allowed to refer to `NetworkAttachmentDefinitions` in the default namespace. This allows you to create commonly used unprivileged `NetworkAttachmentDefinitions` without having to put them in all namespaces. For example, if you had a `NetworkAttachmentDefinition` named `foo` the default namespace, you may reference it in an annotation with: `default/foo`.
**NOTE**: You can also add additional namespaces which can be referred to globally using the `global-namespaces` option (see next section).
For example, if a pod is created in the namespace called `development`, Multus will not allow networks to be attached when defined by custom resources created in a different namespace, say in the `default` network.
Consider the situation where you have a system that has users of different privilege levels -- as an example, a platform which has two administrators: a Senior Administrator and a Junior Administrator. The Senior Administrator may have access to all namespaces, and some network configurations as used by Multus are considered to be privileged in that they allow access to some protected resources available on the network. However, the Junior Administrator has access to only a subset of namespaces, and therefore it should be assumed that the Junior Administrator cannot create pods in their limited subset of namespaces. The `namespaceIsolation` feature provides for this isolation, allowing pods created in given namespaces to only access custom resources in the same namespace as the pod.
Namespace Isolation is disabled by default.
#### Configuration example
```
"namespaceIsolation": true,
```
#### Usage example
Let's setup an example where we:
* Create a custom resource in a namespace called `privileged`
* Create a pod in a namespace called `development`, and have annotations that reference a custom resource in the `privileged` namespace. The creation of this pod should be disallowed by Multus (as we'll have the use of the custom resources limited only to those custom resources created within the same namespace as the pod).
Given the above scenario with a Junior & Senior Administrator. You may assume that the Senior Administrator has access to all namespaces, whereas the Junior Administrator has access only to the `development` namespace.
Firstly, we show that we have a number of namespaces available:
```
# List the available namespaces
[user@kube-master ~]$ kubectl get namespaces
NAME STATUS AGE
default Active 7h27m
development Active 3h
kube-public Active 7h27m
kube-system Active 7h27m
privileged Active 4s
```
We'll create a `NetworkAttachmentDefinition` in the `privileged` namespace.
```
# Show the network attachment definition we're creating.
[user@kube-master ~]$ cat cr.yml
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth0",
"mode": "bridge",
"ipam": {
"type": "host-local",
"subnet": "192.168.1.0/24",
"rangeStart": "192.168.1.200",
"rangeEnd": "192.168.1.216",
"routes": [
{ "dst": "0.0.0.0/0" }
],
"gateway": "192.168.1.1"
}
}'
# Create that network attachment definition in the privileged namespace
[user@kube-master ~]$ kubectl create -f cr.yml -n privileged
networkattachmentdefinition.k8s.cni.cncf.io/macvlan-conf created
# List the available network attachment definitions in the privileged namespace.
[user@kube-master ~]$ kubectl get networkattachmentdefinition.k8s.cni.cncf.io -n privileged
NAME AGE
macvlan-conf 11s
```
Next, we'll create a pod with an annotation that references the privileged namespace. Pay particular attention to the annotation that reads `k8s.v1.cni.cncf.io/networks: privileged/macvlan-conf` -- where it contains a reference to a `namespace/configuration-name` formatted network attachment name. In this case referring to the `macvlan-conf` in the namespace called `privileged`.
```
# Show the yaml for a pod.
[user@kube-master ~]$ cat example.pod.yml
apiVersion: v1
kind: Pod
metadata:
name: samplepod
annotations:
k8s.v1.cni.cncf.io/networks: privileged/macvlan-conf
spec:
containers:
- name: samplepod
command: ["/bin/bash", "-c", "sleep 2000000000000"]
image: dougbtv/centos-network
# Create that pod.
[user@kube-master ~]$ kubectl create -f example.pod.yml -n development
pod/samplepod created
```
You'll note that pod fails to spawn successfully. If you check the Multus logs, you'll see an entry such as:
```
2018-12-18T21:41:32Z [error] GetNetworkDelegates: namespace isolation enabled, annotation violates permission, pod is in namespace development but refers to target namespace privileged
```
This error expresses that the pod resides in the namespace named `development` but refers to a `NetworkAttachmentDefinition` outside of that namespace, in this case, the namespace named `privileged`.
In a positive example, you'd instead create the `NetworkAttachmentDefinition` in the `development` namespace, and you'd have an annotation that either A. does not reference a namespace, or B. refers to the same annotation.
A positive example may be:
```
# Create the same NetworkAttachmentDefinition as above, however in the development namespace
[user@kube-master ~]$ kubectl create -f cr.yml -n development
networkattachmentdefinition.k8s.cni.cncf.io/macvlan-conf created
# Show the yaml for a sample pod which references macvlan-conf without a namspace/ format
[user@kube-master ~]$ cat positive.example.pod
apiVersion: v1
kind: Pod
metadata:
name: samplepod
annotations:
k8s.v1.cni.cncf.io/networks: macvlan-conf
spec:
containers:
- name: samplepod
command: ["/bin/bash", "-c", "sleep 2000000000000"]
image: dougbtv/centos-network
# Create that pod.
[user@kube-master ~]$ kubectl create -f positive.example.pod -n development
pod/samplepod created
# We can see that this pod has been launched successfully.
[user@kube-master ~]$ kubectl get pods -n development
NAME READY STATUS RESTARTS AGE
samplepod 1/1 Running 0 31s
```
### Allow specific namespaces to be used across namespaces when using namespace isolation
The `globalNamespaces` configuration option is only used when `namespaceIsolation` is set to true. `globalNamespaces` specifies a comma-delimited list of namespaces which can be referred to from outside of any given namespace in which a pod resides.
```
"globalNamespaces": "default,namespace-a,namespace-b",
```
Note that when using `globalNamespaces` the `default` namespace must be specified in the list if you wish to use that namespace, when `globalNamespaces` is not set, the `default` namespace is implied to be used across namespaces.
### Specify default cluster network in Pod annotations
Users may also specify the default network for any given pod (via annotation), for cases where there are multiple cluster networks available within a Kubernetes cluster.
Example use cases may include:
1. During a migration from one default network to another (e.g. from Flannel to Calico), it may be practical if both network solutions are able to operate in parallel. Users can then control which network a pod should attach to during the transition period.
2. Some users may deploy multiple cluster networks for the sake of their security considerations, and may desire to specify the default network for individual pods.
Follow these steps to specify the default network on a pod-by-pod basis:
1. First, you need to define all your cluster networks as network-attachment-definition objects.
2. Next, you can specify the network you want in pods with the `v1.multus-cni.io/default-network` annotation. Pods which do not specify this annotation will keep using the CNI as defined in the Multus config file.
```yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-example
annotations:
v1.multus-cni.io/default-network: calico-conf
...
```

65
docs/development.md Normal file
View File

@@ -0,0 +1,65 @@
## Development/Support Information
## Which Kubernetes version is supported in multus?
Currently multus team supports Kubernetes that Kubernetes community maintains.
See [Version Skew Policy](https://kubernetes.io/releases/version-skew-policy/) for the details.
## How to debug multus-cni thin image?
Latest multus uses [distroless](https://github.com/GoogleContainerTools/distroless) container image for its base,
hence there is no shell command. If you want to execute shell in multus pod, please use `-debug` image (e.g. ghcr.io/k8snetworkplumbingwg/multus-cni:snapshot-debug), which has shell.
## How to utilize multus-cni code as library?
Multus now uses [gopkg.in](http://gopkg.in/) to expose its code as library.
You can use following command to import our code into your go code.
```
go get gopkg.in/k8snetworkplumbingwg/multus-cni.v4
```
## How do I submit an issue?
Use GitHub as normally, you'll be presented with an option to submit a issue or enhancement request.
Issues are considered stale after 90 days. After which, the maintainers reserve the right to close an issue.
Typically, we'll tag the submitter and ask for more information if necessary before closing.
If an issue is closed that you don't feel is sufficiently resolved, please feel free to re-open the issue and provide any necessary information.
## How do I build multus-cni?
You can use the built in `./hack/build-go.sh` script!
```
git clone https://github.com/k8snetworkplumbingwg/multus-cni.git
cd multus-cni
./hack/build-go.sh
```
## How do I run CI tests?
Multus has go unit tests (based on ginkgo framework).The following commands drive CI tests manually in your environment:
```
sudo ./hack/test-go.sh
```
## What are the best practices for logging?
The following are the best practices for multus logging:
* Add `logging.Debugf()` at the beginning of functions
* In case of error handling, use `logging.Errorf()` with given error info
* `logging.Panicf()` only be used for critical errors (it should NOT normally be used)
## Multus release schedule
On the first maintainer's meeting, twice yearly, after January 1st and July 1st, if a new version has not been tagged, a new version will tagged.
## Multi-arch builds
Multus is currently built for a number of architectures, however, our testing and validation is only performed against x86 architectures. Our x86 architecture has end to end testing, however, for other architectures, only supported via best effort community contributions.

767
docs/how-to-use.md Normal file
View File

@@ -0,0 +1,767 @@
## Multus CNI usage guide
### Prerequisites
* Kubelet configured to use CNI
* Kubernetes version with CRD support (generally )
Your Kubelet(s) must be configured to run with the CNI network plugin. Please see [Kubernetes document for CNI](https://kubernetes.io/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/#cni) for more details.
### Install Multus
Generally we recommend two options: Manually place a Multus binary in your `/opt/cni/bin`, or use our [quick-start method](quickstart.md) -- which creates a daemonset that has an opinionated way of how to install & configure Multus CNI (recommended).
*Copy Multus Binary into place*
You may acquire the Multus binary via compilation (see the [developer guide](development.md)) or download the a binary from the [GitHub releases](https://github.com/k8snetworkplumbingwg/multus-cni/releases) page. Copy multus binary into CNI binary directory, usually `/opt/cni/bin`. Perform this on all nodes in your cluster (master and nodes).
cp multus /opt/cni/bin
*Via Daemonset method*
As a [quickstart](quickstart.md), you may apply these YAML files. Run this command (typically you would run this on the master, or wherever you have access to the `kubectl` command to manage your cluster).
kubectl apply -f https://raw.githubusercontent.com/k8snetworkplumbingwg/multus-cni/master/deployments/multus-daemonset.yml # thin deployment
or
kubectl apply -f https://raw.githubusercontent.com/k8snetworkplumbingwg/multus-cni/master/deployments/multus-daemonset-thick.yml # thick (client/server) deployment
If you need more comprehensive detail, continue along with this guide, otherwise, you may wish to either [follow the quickstart guide]() or skip to the ['Create network attachment definition'](#create-network-attachment-definition) section.
### Set up conf file in /etc/cni/net.d/ (Installed automatically by Daemonset)
**If you use daemonset to install multus, skip this section and go to "Create network attachment"**
You put CNI config file in `/etc/cni/net.d`. Kubernetes CNI runtime uses the alphabetically first file in the directory. (`"NOTE1"`, `"NOTE2"` are just comments, you can remove them at your configuration)
Execute following commands at all Kubernetes nodes (i.e. master and minions)
```
mkdir -p /etc/cni/net.d
cat >/etc/cni/net.d/00-multus.conf <<EOF
{
"name": "multus-cni-network",
"type": "multus",
"readinessindicatorfile": "/run/flannel/subnet.env",
"delegates": [
{
"NOTE1": "This is example, wrote your CNI config in delegates",
"NOTE2": "If you use flannel, you also need to run flannel daemonset before!",
"type": "flannel",
"name": "flannel.1",
"delegate": {
"isDefaultGateway": true
}
}
],
"kubeconfig": "/etc/cni/net.d/multus.d/multus.kubeconfig"
}
EOF
```
For the detail, please take a look into [Configuration Reference](configuration.md)
**NOTE: You can use "clusterNetwork"/"defaultNetworks" instead of "delegates", see []() for the detail**
As above config, you need to set `"kubeconfig"` in the config file for NetworkAttachmentDefinition(CRD).
##### Which network will be used for "Pod IP"?
In case of "delegates", the first delegates network will be used for "Pod IP". Otherwise, "clusterNetwork" will be used for "Pod IP".
#### Create ServiceAccount, ClusterRole and its binding
Create resources for multus to access CRD objects as following command:
```
# Execute following commands at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: ServiceAccount
metadata:
name: multus
namespace: kube-system
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: multus
rules:
- apiGroups: ["k8s.cni.cncf.io"]
resources:
- '*'
verbs:
- '*'
- apiGroups:
- ""
resources:
- pods
- pods/status
verbs:
- get
- update
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: multus
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: multus
subjects:
- kind: ServiceAccount
name: multus
namespace: kube-system
EOF
```
#### Set up kubeconfig file
Create kubeconfig at master node as following commands:
```
# Execute following command at Kubernetes master
mkdir -p /etc/cni/net.d/multus.d
SERVICEACCOUNT_CA=$(kubectl get secrets -n=kube-system -o json | jq -r '.items[]|select(.metadata.annotations."kubernetes.io/service-account.name"=="multus")| .data."ca.crt"')
SERVICEACCOUNT_TOKEN=$(kubectl get secrets -n=kube-system -o json | jq -r '.items[]|select(.metadata.annotations."kubernetes.io/service-account.name"=="multus")| .data.token' | base64 -d )
KUBERNETES_SERVICE_PROTOCOL=$(kubectl get all -o json | jq -r .items[0].spec.ports[0].name)
KUBERNETES_SERVICE_HOST=$(kubectl get all -o json | jq -r .items[0].spec.clusterIP)
KUBERNETES_SERVICE_PORT=$(kubectl get all -o json | jq -r .items[0].spec.ports[0].port)
cat > /etc/cni/net.d/multus.d/multus.kubeconfig <<EOF
# Kubeconfig file for Multus CNI plugin.
apiVersion: v1
kind: Config
clusters:
- name: local
cluster:
server: ${KUBERNETES_SERVICE_PROTOCOL:-https}://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}
certificate-authority-data: ${SERVICEACCOUNT_CA}
users:
- name: multus
user:
token: "${SERVICEACCOUNT_TOKEN}"
contexts:
- name: multus-context
context:
cluster: local
user: multus
current-context: multus-context
EOF
```
Copy `/etc/cni/net.d/multus.d/multus.kubeconfig` into other Kubernetes nodes
**NOTE: Recommend to exec 'chmod 600 /etc/cni/net.d/multus.d/multus.kubeconfig' to keep secure**
```
scp /etc/cni/net.d/multus.d/multus.kubeconfig ...
```
### Setup CRDs (daemonset automatically does)
**If you use daemonset to install multus, skip this section and go to "Create network attachment"**
Create CRD definition in Kubernetes as following command at master node:
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: network-attachment-definitions.k8s.cni.cncf.io
spec:
group: k8s.cni.cncf.io
version: v1
scope: Namespaced
names:
plural: network-attachment-definitions
singular: network-attachment-definition
kind: NetworkAttachmentDefinition
shortNames:
- net-attach-def
validation:
openAPIV3Schema:
properties:
spec:
properties:
config:
type: string
EOF
```
### Create network attachment definition
The 'NetworkAttachmentDefinition' is used to setup the network attachment, i.e. secondary interface for the pod, There are two ways to configure the 'NetworkAttachmentDefinition' as following:
- NetworkAttachmentDefinition with json CNI config
- NetworkAttachmentDefinition with CNI config file
#### NetworkAttachmentDefinition with json CNI config:
Following command creates NetworkAttachmentDefinition. CNI config is in `config:` field.
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf-1
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "host-local",
"ranges": [
[ {
"subnet": "10.10.0.0/16",
"rangeStart": "10.10.1.20",
"rangeEnd": "10.10.3.50",
"gateway": "10.10.0.254"
} ]
]
}
}'
EOF
```
#### NetworkAttachmentDefinition with CNI config file:
If NetworkAttachmentDefinition has no spec, multus find a file in defaultConfDir ('/etc/cni/multus/net.d', with same name in the 'name' field of CNI config.
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf-2
EOF
```
```
# Execute following commands at all Kubernetes nodes (i.e. master and minions)
cat <<EOF > /etc/cni/multus/net.d/macvlan2.conf
{
"cniVersion": "0.3.0",
"type": "macvlan",
"name": "macvlan-conf-2",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "host-local",
"ranges": [
[ {
"subnet": "11.10.0.0/16",
"rangeStart": "11.10.1.20",
"rangeEnd": "11.10.3.50"
} ]
]
}
}
EOF
```
### Run pod with network annotation
#### Launch pod with text annotation
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-01
annotations:
k8s.v1.cni.cncf.io/networks: macvlan-conf-1, macvlan-conf-2
spec:
containers:
- name: pod-case-01
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
#### Launch pod with text annotation for NetworkAttachmentDefinition in different namespace
You can also specify NetworkAttachmentDefinition with its namespace as adding `<namespace>/`
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf-3
namespace: testns1
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "host-local",
"ranges": [
[ {
"subnet": "12.10.0.0/16",
"rangeStart": "12.10.1.20",
"rangeEnd": "12.10.3.50"
} ]
]
}
}'
EOF
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-02
annotations:
k8s.v1.cni.cncf.io/networks: testns1/macvlan-conf-3
spec:
containers:
- name: pod-case-02
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
#### Launch pod with text annotation with interface name
You can also specify interface name as adding `@<ifname>`.
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-03
annotations:
k8s.v1.cni.cncf.io/networks: macvlan-conf-1@macvlan1
spec:
containers:
- name: pod-case-03
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
#### Launch pod with json annotation
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-04
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name" : "macvlan-conf-1" },
{ "name" : "macvlan-conf-2" }
]'
spec:
containers:
- name: pod-case-04
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
#### Launch pod with json annotation for NetworkAttachmentDefinition in different namespace
You can also specify NetworkAttachmentDefinition with its namespace as adding `"namespace": "<namespace>"`.
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-05
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name" : "macvlan-conf-1",
"namespace": "testns1" }
]'
spec:
containers:
- name: pod-case-05
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
#### Launch pod with json annotation with interface
You can also specify interface name as adding `"interface": "<ifname>"`.
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-case-06
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name" : "macvlan-conf-1",
"interface": "macvlan1" },
{ "name" : "macvlan-conf-2" }
]'
spec:
containers:
- name: pod-case-06
image: docker.io/centos/tools:latest
command:
- /sbin/init
EOF
```
### Verifying pod network
Following the example of `ip -d address` output of above pod, "pod-case-06":
```
# Execute following command at Kubernetes master
kubectl exec -it pod-case-06 -- ip -d address
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 promiscuity 0 numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
3: eth0@if11: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UP group default
link/ether 0a:58:0a:f4:02:06 brd ff:ff:ff:ff:ff:ff link-netnsid 0 promiscuity 0
veth numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535
inet 10.244.2.6/24 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::ac66:45ff:fe7c:3a19/64 scope link
valid_lft forever preferred_lft forever
4: macvlan1@if3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default
link/ether 4e:6d:7a:4e:14:87 brd ff:ff:ff:ff:ff:ff link-netnsid 0 promiscuity 0
macvlan mode bridge numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535
inet 10.10.1.22/16 scope global macvlan1
valid_lft forever preferred_lft forever
inet6 fe80::4c6d:7aff:fe4e:1487/64 scope link
valid_lft forever preferred_lft forever
5: net2@if3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default
link/ether 6e:e3:71:7f:86:f7 brd ff:ff:ff:ff:ff:ff link-netnsid 0 promiscuity 0
macvlan mode bridge numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535
inet 11.10.1.22/16 scope global net2
valid_lft forever preferred_lft forever
inet6 fe80::6ce3:71ff:fe7f:86f7/64 scope link
valid_lft forever preferred_lft forever
```
| Interface name | Description |
| --- | --- |
| lo | loopback |
| eth0 | Default network interface (flannel) |
| macvlan1 | macvlan interface (macvlan-conf-1) |
| net2 | macvlan interface (macvlan-conf-2) |
## Specifying a default route for a specific attachment
Typically, the default route for a pod will route traffic over the `eth0` and therefore over the cluster-wide default network. You may wish to specify that a different network attachment will have the default route.
You can achieve this by using the JSON formatted annotation and specifying a `default-route` key.
*NOTE*: It's important that you consider that this may impact some functionality of getting traffic to route over the cluster-wide default network.
For example, we have a this configuration for macvlan:
```
cat <<EOF | kubectl create -f -
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth0",
"mode": "bridge",
"ipam": {
"type": "host-local",
"subnet": "192.168.2.0/24",
"rangeStart": "192.168.2.200",
"rangeEnd": "192.168.2.216",
"routes": [
{ "dst": "0.0.0.0/0" }
],
"gateway": "192.168.2.1"
}
}'
EOF
```
We can then create a pod which uses the `default-route` key in the JSON formatted `k8s.v1.cni.cncf.io/networks` annotation.
```
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: samplepod
annotations:
k8s.v1.cni.cncf.io/networks: '[{
"name": "macvlan-conf",
"default-route": ["192.168.2.1"]
}]'
spec:
containers:
- name: samplepod
command: ["/bin/bash", "-c", "trap : TERM INT; sleep infinity & wait"]
image: dougbtv/centos-network
EOF
```
This will set `192.168.2.1` as the default route over the `net1` interface, such as:
```
kubectl exec -it samplepod -- ip route
default via 192.168.2.1 dev net1
10.244.0.0/24 dev eth0 proto kernel scope link src 10.244.0.169
10.244.0.0/16 via 10.244.0.1 dev eth0
```
## Entrypoint Parameters
Multus CNI, when installed using the daemonset-style installation uses an entrypoint script which copies the Multus binary into place, places CNI configurations. This entrypoint takes a variety of parameters for customization.
Typically, you'd modified the daemonset YAML itself to specify these parameters.
For example, the `command` and `args` parameters in the `containers` section of the DaemonSet may look something like:
```
command: ["/thin_entrypoint"]
args:
- "--multus-conf-file=auto"
- "--namespace-isolation=true"
- "--multus-log-level=verbose"
```
Note that some of the defaults have directories inside the root directory named `/host/`, this is because it is deployed as a container and we have host file system locations mapped into this directory inside the container. If you use other directories, you may have to change the mounted volumes.
### Entrypoint script parameters
Each parameter is shown with the default as the value.
--cni-conf-dir=/host/etc/cni/net.d
This is the configuration directory where Multus will write its configuration file.
--cni-bin-dir=/host/opt/cni/bin
This the directory in which the Multus binary will be installed.
--namespace-isolation=false
Setting this option to true enables the Namespace isolation feature, which insists that custom resources must be created in the same namespace as the pods, otherwise it will refuse to attach those definitions as additional interfaces. See (the configuration guide for more information)[configuration.md].
--global-namespaces=default,foo,bar
The `--global-namespaces` works only when `--namespace-isolation=true`. This takes a comma-separated list of namespaces which can be referred to globally when namespace isolation is enabled. See (the configuration guide for more information)[configuration.md].
--multus-bin-file=/usr/src/multus-cni/bin/multus
This option lets you set which binary executable to copy from the container onto the host (into the directory specified by `--cni-bin-dir`), allowing one to copy an alternate version or build of Multus CNI.
--multus-conf-file=/usr/src/multus-cni/images/70-multus.conf
The `--multus-conf-file` is one of two options; it can be set to a source file to be copied into the location specified by `--cni-conf-dir`. Or, to a value of `auto`, that is: `--multus-conf-file=auto`.
The automatic configuration option is used to automatically generate Multus configurations given existing on-disk CNI configurations for your default network.
In the case that `--multus-conf-file=auto` -- The entrypoint script will look at the `--multus-autoconfig-dir` (by default, the same as the `--cni-conf-dir`). Multus will take the alphabetically first configuration there and wrap that into a Multus configuration.
--multus-autoconfig-dir=/host/etc/cni/net.d
Used only with `--multus-conf-file=auto`. This option allows one to set which directory will be used to generate configuration files.
This can be used if you have your CNI configuration stored in an alternate location, or, you have constraints on race conditions where you'd like to generate your default network configuration first, and then only have Multus write its configuration when it finds that configuration -- allowing only Multus to write the CNI configuration in the `--cni-conf-dir`, therefore notifying the Kubelet that the node is in a ready state.
--multus-kubeconfig-file-host=/etc/cni/net.d/multus.d/multus.kubeconfig
Used only with `--multus-conf-file=auto`. Allows you to specify an alternate path to the Kubeconfig.
--multus-master-cni-file-name=
The `--multus-master-cni-file-name` can be used to select the cni file as the master cni, rather than the first file in cni-conf-dir. For example, `--multus-master-cni-file-name=10-calico.conflist`.
--multus-log-level=
--multus-log-file=
Used only with `--multus-conf-file=auto`. See the [documentation for logging](https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/docs/configuration.md#logging) for which values are permitted.
Used only with `--multus-conf-file=auto`. Allows you to specify CNI spec version. Please set if you need to specify CNI spec version.
--cni-version=
In some cases, the original CNI configuration that the Multus configuration was generated from (using `--multus-conf-file=auto`) may be used as a sort of semaphor for network readiness -- as this model is used by the Kubelet itself. If you need to disable Multus' availability, you may wish to clean out the generated configuration file when the source file for autogeneration of the config file is no longer present. You can use this functionality by setting:
--cleanup-config-on-exit=true
When specifying `--cleanup-config-on-exit=true` the entrypoint script will delete any generated/copied Multus configuration files when entrypoint script
exits (upon Pod termination). This allows Multus to be safely removed from the cluster when its no longer needed.
In addition, when both `--cleanup-config-on-exit=true` and `--multus-conf-file=auto` are specified, the entrypoint script will watch for changes of the
master CNI configuration and kubeconfig. when such change detected, the script will re-genereate Multus configuration. Watch can be skipped by setting:
--skip-config-watch
Additionally when using CRIO, you may wish to have the CNI config file that's used as the source for `--multus-conf-file=auto` renamed. This boolean option when set to true automatically renames the file with a `.old` suffix to the original filename.
--rename-conf-file=true
When using `--multus-conf-file=auto` you may also care to specify a `binDir` in the configuration, this can be accomplished using the `--additional-bin-dir` option.
--additional-bin-dir=/opt/multus/bin
Sometimes, you may wish to not have the entrypoint copy the binary file onto the host. Potentially, you have another way to copy in a specific version of Multus, for example. By default, it's always copied, but you may disable the copy with:
--skip-multus-binary-copy=true
If you wish to have auto configuration use the `readinessindicatorfile` in the configuration, you can use the `--readiness-indicator-file` to express which file should be used as the readiness indicator.
--readiness-indicator-file=/path/to/file
### Run pod with network annotation and Dynamic Resource Allocation driver
> :warning: Dynamic Resource Allocation (DRA) is [currently an alpha](https://kubernetes.io/docs/concepts/scheduling-eviction/dynamic-resource-allocation/),
> and is subject to change. Please consider this functionality as a preview. The architecture and usage of DRA in
> Multus CNI may change in the future as this technology matures.
>
> The current DRA integration is based on the DRA API for Kubernetes 1.26 to 1.30. With Kubernetes 1.31, the DRA API
> will change and multus doesn't integrate with the new API yet.
Dynamic Resource Allocation is alternative mechanism to device plugin which allows to requests pod and container
resources.
The following sections describe how to use DRA with multus and NVIDIA DRA driver. Other DRA networking driver vendors
should follow similar concepts to make use of multus DRA support.
#### Prerequisite
1. Kubernetes 1.27
2. Container Runtime with CDI support enabled
3. Kubernetes runtime-config=resource.k8s.io/v1alpha2
4. Kubernetes feature-gates=DynamicResourceAllocation=True,KubeletPodResourcesDynamicResources=true
#### Install DRA driver
The current example uses NVIDIA DRA driver for networking. This DRA driver is not publicly available. An alternative to
this DRA driver is available at [dra-example-driver](https://github.com/kubernetes-sigs/dra-example-driver).
#### Create dynamic resource class with NVIDIA network DRA driver
The `ResourceClass` defines the resource pool of `sf-pool-1`.
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: resource.k8s.io/v1alpha2
kind: ResourceClass
metadata:
name: sf-pool-1
driverName: net.resource.nvidia.com
EOF
```
#### Create network attachment definition with resource name
The `k8s.v1.cni.cncf.io/resourceName` should match the `ResourceClass` name defined in the section above.
In this example it is `sf-pool-1`. Multus query the K8s PodResource API to fetch the `resourceClass` name and also
query the NetworkAttachmentDefinition `k8s.v1.cni.cncf.io/resourceName`. If both has the same name multus send the
CDI device name in the DeviceID argument.
##### NetworkAttachmentDefinition for ovn-kubernetes example:
Following command creates NetworkAttachmentDefinition. CNI config is in `config:` field.
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: default
annotations:
k8s.v1.cni.cncf.io/resourceName: sf-pool-1
spec:
config: '{
"cniVersion": "0.4.0",
"dns": {},
"ipam": {},
"logFile": "/var/log/ovn-kubernetes/ovn-k8s-cni-overlay.log",
"logLevel": "4",
"logfile-maxage": 5,
"logfile-maxbackups": 5,
"logfile-maxsize": 100,
"name": "ovn-kubernetes",
"type": "ovn-k8s-cni-overlay"
}'
EOF
```
#### Create DRA Resource Claim
Following command creates `ResourceClaim` `sf` which request resource from `ResourceClass` `sf-pool-1`.
```
# Execute following command at Kubernetes master
cat <<EOF | kubectl create -f -
apiVersion: resource.k8s.io/v1alpha2
kind: ResourceClaim
metadata:
namespace: default
name: sf
spec:
spec:
resourceClassName: sf-pool-1
EOF
```
#### Launch pod with DRA Resource Claim
Following command Launch a Pod with primiry network `default` and `ResourceClaim` `sf`.
```
apiVersion: v1
kind: Pod
metadata:
namespace: default
name: test-sf-claim
annotations:
v1.multus-cni.io/default-network: default
spec:
restartPolicy: Always
containers:
- name: with-resource
image: docker.io/library/ubuntu:22.04
command: ["/bin/sh", "-ec", "while :; do echo '.'; sleep 5 ; done"]
resources:
claims:
- name: resource
resourceClaims:
- name: resource
source:
resourceClaimName: sf
```

View File

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

View File

Before

Width:  |  Height:  |  Size: 190 KiB

After

Width:  |  Height:  |  Size: 190 KiB

View File

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 49 KiB

View File

Before

Width:  |  Height:  |  Size: 197 KiB

After

Width:  |  Height:  |  Size: 197 KiB

View File

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 34 KiB

View File

@@ -1,6 +1,6 @@
# Quickstart Guide
This guide is intended as a way to get you off the ground, and using Multus CNI to create Kubernetes pods with multiple interfaces. If you're already using Multus and need more detail, see the [comprehensive usage guide](how-to-use.md). This document a quickstart and a getting started guide in one, intended for your first run-through of Multus CNI.
This guide is intended as a way to get you off the ground, using Multus CNI to create Kubernetes pods with multiple interfaces. If you're already using Multus and need more detail, see the [comprehensive usage guide](how-to-use.md). This document is a quickstart and a getting started guide in one, intended for your first run-through of Multus CNI.
We'll first install Multus CNI, and then we'll setup some configurations so that you can see how multiple interfaces are created for pods.
@@ -15,11 +15,13 @@ Two things we'll refer to a number of times through this document are:
Our installation method requires that you first have installed Kubernetes and have configured a default network -- that is, a CNI plugin that's used for your pod-to-pod connectivity.
We support Kubernetes versions that Kubernetes community supports. Please see [Supported versions](https://kubernetes.io/releases/version-skew-policy/#supported-versions) in Kubernetes document.
To install Kubernetes, you may decide to use [kubeadm](https://kubernetes.io/docs/setup/independent/create-cluster-kubeadm/), or potentially [kubespray](https://github.com/kubernetes-sigs/kubespray).
After installing Kubernetes, you must install a default network CNI plugin. If you're using kubeadm, refer to the "[Installing a pod network add-on](https://kubernetes.io/docs/setup/independent/create-cluster-kubeadm/#pod-network)" section in the kubeadm documentation. If it's your first time, we generally recommend using Flannel for the sake of simplicity.
Alternatively, for advanced use cases, for installing Multus and a default network plugin at the same time, you may refer to the [Kubernetes Network Plumbing Group's Reference Deployments](https://github.com/K8sNetworkPlumbingWG/reference-deployment).
Alternatively, for advanced use cases, for installing Multus and a default network plugin at the same time, you may refer to the [Kubernetes Network Plumbing Group's Reference Deployments](https://github.com/k8snetworkplumbingwg/reference-deployment).
To verify that you default network is ready, you may list your Kubernetes nodes with:
@@ -27,35 +29,38 @@ To verify that you default network is ready, you may list your Kubernetes nodes
kubectl get nodes
```
In the case that your default network is ready
In the case that your default network is ready you will see the `STATUS` column also switch to `Ready` for each node.
```
NAME STATUS ROLES AGE VERSION
master-0 Ready master 1h v1.17.1
master-1 Ready master 1h v1.17.1
master-2 Ready master 1h v1.17.1
```
## Installation
Our recommended quickstart method to deploy Multus is to deploy using a Daemonset (a method of running pods on each nodes in your cluster), this spins up pods which install a Multus binary and configure Multus for usage.
Firstly, clone this GitHub repository.
We'll apply a YAML file with `kubectl` from this repo, which installs the Multus components.
Recommended installation:
```
git clone https://github.com/intel/multus-cni.git && cd multus-cni
kubectl apply -f https://raw.githubusercontent.com/k8snetworkplumbingwg/multus-cni/master/deployments/multus-daemonset-thick.yml
```
See the [thick plugin docs](./thick-plugin.md) for more information about this architecture.
If you're using Kubernetes 1.16+, we'll apply a YAML file with `kubectl` from this repo.
Alternatively, you may install the thin-plugin with:
```
$ cat ./images/multus-daemonset.yml | kubectl apply -f -
kubectl apply -f https://raw.githubusercontent.com/k8snetworkplumbingwg/multus-cni/master/deployments/multus-daemonset.yml
```
Or, for Kubernetes versions < 1.16, use the prior version yaml:
```
$ cat ./images/multus-daemonset-pre-1.16.yml | kubectl apply -f -
```
### What the Multus daemonset does
* Starts a Multus daemonset, this runs a pod on each node which places a Multus binary on each node in `/opt/cni/bin`
* Reads the lexigraphically (alphabetically) first configuration file in `/etc/cni/net.d`, and creates a new configuration file for Multus as `/etc/cni/net.d/00-multus.conf`, this configuration is auto-generated and is based on the default network configuration (which is assumed to be the alphabetically first configuration)
* Reads the lexicographically (alphabetically) first configuration file in `/etc/cni/net.d`, and creates a new configuration file for Multus on each node as `/etc/cni/net.d/00-multus.conf`, this configuration is auto-generated and is based on the default network configuration (which is assumed to be the alphabetically first configuration)
* Creates a `/etc/cni/net.d/multus.d` directory on each node with authentication information for Multus to access the Kubernetes API.
@@ -64,10 +69,10 @@ $ cat ./images/multus-daemonset-pre-1.16.yml | kubectl apply -f -
Generally, the first step in validating your installation is to ensure that the Multus pods have run without error, you may see an overview of those by looking at:
```
$ kubectl get pods --all-namespaces | grep -i multus
kubectl get pods --all-namespaces | grep -i multus
```
You may further validate that it has ran by looking at the `/etc/cni/net.d/` directory and ensure that the alphabetically first
You may further validate that it has ran by looking at the `/etc/cni/net.d/` directory and ensure that the auto-generated `/etc/cni/net.d/00-multus.conf` exists corresponding to the alphabetically first configuration file.
## Creating additional interfaces
@@ -91,11 +96,11 @@ CNI configurations are JSON, and we have a structure here that has a few things
2. `type`: This tells CNI which binary to call on disk. Each CNI plugin is a binary that's called. Typically, these binaries are stored in `/opt/cni/bin` on each node, and CNI executes this binary. In this case we've specified the `loopback` binary (which create a loopback-type network interface). If this is your first time installing Multus, you might want to verify that the plugins that are in the "type" field are actually on disk in the `/opt/cni/bin` directory.
3. `additional`: This field is put here as an example, each CNI plugin can specify whatever configuration parameters they'd like in JSON. These are specific to the binary you're calling in the `type` field.
For an even further example -- take a look at the [bridge CNI plugin README](https://github.com/containernetworking/plugins/tree/master/plugins/main/bridge) which shows additional
For an even further example -- take a look at the [bridge CNI plugin README](https://github.com/containernetworking/plugins/tree/master/plugins/main/bridge) which shows additional details.
If you'd like more information about CNI configuration, you can read [the entire CNI specification](https://github.com/containernetworking/cni/blob/master/SPEC.md). It might also be useful to look at the [CNI reference plugins](https://github.com/containernetworking/plugins) and see how they're configured.
You do not need to reload or refresh the Kubelets when CNI configurations change. These are read on each creation & deletion of pods. So if you change a configuration, it'll apply the next time a pod is created. Existing pods may need to be restarted if they need the new configuration.
You do not need to reload or refresh the Kubelets when CNI configurations change. These are read on each creation & deletion of pods. So if you change a configuration, it'll apply the next time a pod is created. Existing pods may need to be restarted if they need the new configuration.
### Storing a configuration as a Custom Resource
@@ -151,7 +156,7 @@ kubectl describe network-attachment-definitions macvlan-conf
### Creating a pod that attaches an additional interface
We're going to create a pod. This will look familiar as any pod you might have created before, but, we'll have a special `annotations` field -- in this case we'll have an annotation called `k8s.v1.cni.cncf.io/networks`. This field takes a comma delimited list of the names of your `NetworkAttachmentDefinition`s as we created above. Note in the comand below that we have the annotation of `k8s.v1.cni.cncf.io/networks: macvlan-conf` where `macvlan-conf` is the name we used above when we created our configuration.
We're going to create a pod. This will look familiar as any pod you might have created before, but, we'll have a special `annotations` field -- in this case we'll have an annotation called `k8s.v1.cni.cncf.io/networks`. This field takes a comma delimited list of the names of your `NetworkAttachmentDefinition`s as we created above. Note in the command below that we have the annotation of `k8s.v1.cni.cncf.io/networks: macvlan-conf` where `macvlan-conf` is the name we used above when we created our configuration.
Let's go ahead and create a pod (that just sleeps for a really long time) with this command:
@@ -166,18 +171,18 @@ metadata:
spec:
containers:
- name: samplepod
command: ["/bin/bash", "-c", "trap : TERM INT; sleep infinity & wait"]
image: dougbtv/centos-network
command: ["/bin/ash", "-c", "trap : TERM INT; sleep infinity & wait"]
image: alpine
EOF
```
You may now inspect the pod and see what interfaces interfaces are attached, like so:
You may now inspect the pod and see what interfaces are attached, like so:
```
$ kubectl exec -it samplepod -- ip a
kubectl exec -it samplepod -- ip a
```
You should note that there's 3 interfaces:
You should note that there are 3 interfaces:
* `lo` a loopback interface
* `eth0` our default network
@@ -189,7 +194,7 @@ For additional confirmation, use `kubectl describe pod samplepod` and there will
```
Annotations: k8s.v1.cni.cncf.io/networks: macvlan-conf
k8s.v1.cni.cncf.io/networks-status:
k8s.v1.cni.cncf.io/network-status:
[{
"name": "cbr0",
"ips": [
@@ -225,8 +230,8 @@ metadata:
spec:
containers:
- name: samplepod
command: ["/bin/bash", "-c", "trap : TERM INT; sleep infinity & wait"]
image: dougbtv/centos-network
command: ["/bin/ash", "-c", "trap : TERM INT; sleep infinity & wait"]
image: alpine
EOF
```

113
docs/thick-plugin.md Normal file
View File

@@ -0,0 +1,113 @@
# Multus Thick plugin
Multus CNI can also be deployed using a thick plugin architecture, which is
characterized by a client/server architecture.
The client - which will be referred to as "shim" - is a binary executable
located on the Kubernetes node's file-system that
[speaks CNI](https://github.com/containernetworking/cni/blob/master/SPEC.md#section-2-execution-protocol):
the runtime - Kubernetes - passes parameters to the plugin via environment
variables and configuration - which is passed via stdin.
The plugin returns a result on stdout on success, or an error on stderr if the
operation fails. Configuration and results are a JSON encoded string.
Once the shim is invoked by the runtime (Kubernetes) it will contact the
multus-daemon (server) via a unix domain socket which is bind mounted to the
host's file-system; the multus-daemon is the one that will do all the
heavy-pulling: fetch the delegate CNI configuration from the corresponding
`net-attach-def`, compute the `RuntimeConfig`, and finally, invoke the delegate.
It will then return the result of the operation back to the client.
Please refer to the diagram below for a visual representation of the flow
described above:
```
┌─────────┐ ┌───────┐ ┌────────┐ ┌──────────┐
│ │ cni ADD/DEL │ │ REST POST │ │ cni ADD/DEL │ │
│ runtime ├────────────►│ shim │===========│ daemon ├────────────►│ delegate │
│ │<------------│ │ │ │<------------│ │
└─────────┘ └───────┘ └────────┘ └──────────┘
```
## How to use it
### Configure Deployment
If your delegate CNI plugin requires some files which is in container host, please update
update `deployments/multus-daemonset-thick.yml` to add directory into multus-daemon pod.
For example, flannel requires `/run/flannel/subnet.env`, so you need to mount this directory
into the multus-daemon pod.
Required directory/files are different for each CNI plugin, so please refer your CNI plugin.
### Deployment
There is a dedicated multus daemonset specification for users wanting to use
this thick plugin variant. This reference deployment spec of multus can be
deployed by following these commands:
```bash
kubectl apply -f deployments/multus-daemonset-thick.yml
```
### Command line parameters
The available command line parameters are:
- `config`: Defaults to `"/etc/cni/net.d/multus.d/daemon-config.json"`
- `version`: Prints the daemon config version and exits
### Server / Daemon configuration
The server configuration is encoded in JSON, and allows the following keys:
- `"chrootDir"`: Specify the directory which points to host root from the pod. See 'Chroot configuration' section for the details.
- `"socketDir"`: Specify the location where the unix domain socket used
for client/server communication will be located. This is the location where the
**Daemon** will read the configuration from. Defaults to `"/run/multus"`.
- `"metricsPort"`: Metrics port (of multus' metric exporter); by default, no port
is provided.
- `"logFile"`: the path to where the daemon logs will be persisted.
- `"logLevel"`: the logging level for the multus daemon logs.
- `"logToStderr"`: enable this to have the daemon multus logs echoed to stderr
as well. By default, it is disabled.
In addition, you can add any configuration which is in [configuration reference](https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/docs/configuration.md#multus-cni-configuration-reference). Server configuration override multus CNI configuration (e.g. `/etc/cni/net.d/00-multus.conf`)
Below you can see an example of the daemon configuration:
```json
{
"chrootDir": "/hostroot",
"confDir": "/host/etc/cni/net.d",
"logToStderr": true,
"logLevel": "verbose",
"logFile": "/tmp/multus.log",
"binDir": "/opt/cni/bin",
"cniDir": "/var/lib/cni/multus",
"socketDir": "/host/run/multus/",
"cniVersion": "0.3.1",
"cniConfigDir": "/host/etc/cni/net.d",
"multusConfigFile": "auto",
"multusAutoconfigDir": "/host/etc/cni/net.d"
}
```
### Client / Shim configuration
The multus shim configuration is encoded in JSON, and essentially is just a
regular CNI configuration, usually available in `/etc/cni/net.d/00-multus.conf`.
It allows the following keys:
- `"cniVersion"`: the CNI version for the Multus CNI plugin.
- `"logFile"`: the path to where the daemon logs will be persisted.
- `"logLevel"`: the logging level for the multus daemon logs.
- `"logToStderr"`: enable this to have the daemon multus logs echoed to stderr
as well. By default, it is disabled.
#### Chroot configuration
In thick plugin case, delegate CNI plugin is executed by multus-daemon from Pod, hence if the delegate CNI requires resources in container host, for example unix socket or even file, then CNI plugin is failed to execute because multus-daemon runs in Pod. Multus-daemon supports "chrootDir" option which executes delegate CNI under chroot (to container host).
This configuration is enabled in deployments/multus-daemonset-thick.yml as default.

26
e2e/README.md Normal file
View File

@@ -0,0 +1,26 @@
## Multus e2e test with kind
### Prerequisite
To run the e2e test, you need the following components:
- curl
- jinjanator
- docker
### How to test e2e
```
$ git clone https://github.com/k8snetworkplumbingwg/multus-cni.git
$ cd multus-cni/e2e
$ ./get_tools.sh
$ ./generate_yamls.sh
$ ./setup_cluster.sh
$ ./test-simple-macvlan1.sh
```
### How to teardown cluster
```
$ ./teardown.sh
```

17
e2e/generate_yamls.sh Executable file
View File

@@ -0,0 +1,17 @@
#!/bin/sh
if [ ! -d yamls ]; then
mkdir yamls
fi
# specify CNI version (default: 0.4.0)
export CNI_VERSION=${CNI_VERSION:-0.4.0}
templates_dir="$(dirname $(readlink -f $0))/templates"
# generate yaml files based on templates/*.j2 to yamls directory
for i in `ls templates/`; do
echo $i
j2 -e CNI_VERSION ${templates_dir}/$i -o yamls/${i%.j2}
done
unset CNI_VERSION

16
e2e/get_tools.sh Executable file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
set -o errexit
if [ ! -d bin ]; then
mkdir bin
fi
curl -Lo ./bin/kind "https://github.com/kubernetes-sigs/kind/releases/download/v0.22.0/kind-$(uname)-amd64"
chmod +x ./bin/kind
curl -Lo ./bin/kubectl https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl
chmod +x ./bin/kubectl
curl -Lo ./bin/koko https://github.com/redhat-nfvpe/koko/releases/download/v0.83/koko_0.83_linux_amd64
chmod +x ./bin/koko
curl -Lo ./bin/jq https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
chmod +x ./bin/jq
wget -qO- https://get.helm.sh/helm-v3.14.3-linux-amd64.tar.gz | tar xvzf - --strip-components=1 -C ./bin linux-amd64/helm

69
e2e/setup_cluster.sh Executable file
View File

@@ -0,0 +1,69 @@
#!/bin/sh
set -o errexit
export PATH=${PATH}:./bin
# define the OCI binary to be used. Acceptable values are `docker`, `podman`.
# Defaults to `docker`.
OCI_BIN="${OCI_BIN:-docker}"
# define the deployment spec to use when deploying multus.
# Acceptable values are `multus-daemonset.yml`. `multus-daemonset-thick.yml`.
# Defaults to `multus-daemonset-thick.yml`.
MULTUS_MANIFEST="${MULTUS_MANIFEST:-multus-daemonset-thick.yml}"
# define the dockerfile to build multus.
# Acceptable values are `Dockerfile`. `Dockerfile.thick`.
# Defaults to `Dockerfile.thick`.
MULTUS_DOCKERFILE="${MULTUS_DOCKERFILE:-Dockerfile.thick}"
kind_network='kind'
if [ "${MULTUS_DOCKERFILE}" != "none" ]; then
$OCI_BIN build -t localhost:5000/multus:e2e -f ../images/${MULTUS_DOCKERFILE} ..
fi
# deploy cluster with kind
cat <<EOF | kind create cluster --config=-
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
kubeadmConfigPatches:
- |
kind: InitConfiguration
nodeRegistration:
kubeletExtraArgs:
pod-manifest-path: "/etc/kubernetes/manifests/"
feature-gates: "DynamicResourceAllocation=true,KubeletPodResourcesDynamicResources=true"
- role: worker
# Required by DRA Integration
##
featureGates:
DynamicResourceAllocation: true
runtimeConfig:
"api/alpha": "true"
containerdConfigPatches:
# Enable CDI as described in
# https://github.com/container-orchestrated-devices/container-device-interface#containerd-configuration
- |-
[plugins."io.containerd.grpc.v1.cri"]
enable_cdi = true
##
EOF
# load multus image from container host to kind node
kind load docker-image localhost:5000/multus:e2e
worker1_pid=$($OCI_BIN inspect --format "{{ .State.Pid }}" kind-worker)
worker2_pid=$($OCI_BIN inspect --format "{{ .State.Pid }}" kind-worker2)
kind export kubeconfig
sudo env PATH=${PATH} koko -p "$worker1_pid,eth1" -p "$worker2_pid,eth1"
sleep 1
kubectl -n kube-system wait --for=condition=available deploy/coredns --timeout=300s
kubectl create -f yamls/$MULTUS_MANIFEST
sleep 1
kubectl -n kube-system wait --for=condition=ready -l name=multus pod --timeout=300s
kubectl create -f yamls/cni-install.yml
sleep 1
kubectl -n kube-system wait --for=condition=ready -l name=cni-plugins pod --timeout=300s

11
e2e/simple-static-pod.yml Normal file
View File

@@ -0,0 +1,11 @@
apiVersion: v1
kind: Pod
metadata:
name: static-web
annotations:
k8s.v1.cni.cncf.io/networks: "bridge-nad"
spec:
containers:
- name: web
image: centos:8
command: ["/bin/bash", "-c", "trap : TERM INT; sleep infinity & wait"]

15
e2e/static-pod-nad.yml Normal file
View File

@@ -0,0 +1,15 @@
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: bridge-nad
spec:
config: '{
"cniVersion": "0.3.1",
"name": "testnet",
"type": "bridge",
"bridge": "testnet0",
"ipam": {
"type": "host-local",
"subnet": "10.10.0.0/16"
}
}'

7
e2e/teardown.sh Executable file
View File

@@ -0,0 +1,7 @@
#!/bin/sh
#set -o errexit
export PATH=${PATH}:./bin
# delete cluster kind
kind delete cluster

View File

@@ -0,0 +1,64 @@
---
kind: ConfigMap
apiVersion: v1
metadata:
name: cni-install-sh
namespace: kube-system
data:
install_cni.sh: |
cd /tmp
wget https://github.com/containernetworking/plugins/releases/download/v1.4.0/cni-plugins-linux-amd64-v1.4.0.tgz
cd /host/opt/cni/bin
tar xvfzp /tmp/cni-plugins-linux-amd64-v1.4.0.tgz
sleep infinite
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: install-cni-plugins
namespace: kube-system
labels:
name: cni-plugins
spec:
selector:
matchLabels:
name: cni-plugins
template:
metadata:
labels:
name: cni-plugins
spec:
hostNetwork: true
nodeSelector:
kubernetes.io/arch: amd64
tolerations:
- operator: Exists
effect: NoSchedule
containers:
- name: install-cni-plugins
image: alpine
command: ["/bin/sh", "/scripts/install_cni.sh"]
resources:
requests:
cpu: "100m"
memory: "50Mi"
limits:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: true
volumeMounts:
- name: cni-bin
mountPath: /host/opt/cni/bin
- name: scripts
mountPath: /scripts
volumes:
- name: cni-bin
hostPath:
path: /opt/cni/bin
- name: scripts
configMap:
name: cni-install-sh
items:
- key: install_cni.sh
path: install_cni.sh

View File

@@ -0,0 +1,57 @@
---
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: default-route-config
spec:
config: '{
"cniVersion": "{{ CNI_VERSION }}",
"plugins": [
{
"type": "macvlan",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "static"
}
} ]
}'
---
apiVersion: v1
kind: Pod
metadata:
name: default-route-worker1
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name": "default-route-config",
"ips": [ "10.1.1.21/24" ] ,
"default-route": [ "10.1.1.254" ] }
]'
labels:
app: default-route1
spec:
containers:
- name: default-route-worker1
image: centos:8
command: ["/bin/sleep", "10000"]
securityContext:
privileged: true
---
apiVersion: v1
kind: Pod
metadata:
name: default-route-worker2
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name": "default-route-config",
"ips": [ "10.1.1.22/24" ] }
]'
labels:
app: default-route1
spec:
containers:
- name: default-route-worker2
image: centos:8
command: ["/bin/sleep", "10000"]
securityContext:
privileged: true

View File

@@ -0,0 +1,49 @@
---
apiVersion: resource.k8s.io/v1alpha2
kind: ResourceClaimTemplate
metadata:
name: gpu.example.com
spec:
spec:
resourceClassName: gpu.example.com
---
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: dra-net
annotations:
k8s.v1.cni.cncf.io/resourceName: gpu.example.com
spec:
config: '{
"cniVersion": "{{ CNI_VERSION }}",
"plugins": [{
"name": "mynet",
"type": "dummy",
"ipam": {
"type": "host-local",
"subnet": "10.1.2.0/24"
}
}]
}'
---
apiVersion: v1
kind: Pod
metadata:
name: dra-integration
labels:
app: dra-integration
annotations:
k8s.v1.cni.cncf.io/networks: default/dra-net
spec:
containers:
- name: ctr0
image: ubuntu:22.04
command: ["bash", "-c"]
args: ["export; sleep 9999"]
resources:
claims:
- name: gpu
resourceClaims:
- name: gpu
source:
resourceClaimTemplateName: gpu.example.com

View File

@@ -0,0 +1,210 @@
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: network-attachment-definitions.k8s.cni.cncf.io
spec:
group: k8s.cni.cncf.io
scope: Namespaced
names:
plural: network-attachment-definitions
singular: network-attachment-definition
kind: NetworkAttachmentDefinition
shortNames:
- net-attach-def
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
config:
type: string
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: multus
rules:
- apiGroups: ["k8s.cni.cncf.io"]
resources:
- '*'
verbs:
- '*'
- apiGroups:
- ""
resources:
- pods
- pods/status
verbs:
- get
- list
- update
- watch
- apiGroups:
- ""
- events.k8s.io
resources:
- events
verbs:
- create
- patch
- update
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: multus
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: multus
subjects:
- kind: ServiceAccount
name: multus
namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: multus
namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
name: multus-daemon-config
namespace: kube-system
labels:
tier: node
app: multus
data:
daemon-config.json: |
{
"confDir": "/host/etc/cni/net.d",
"logToStderr": true,
"logLevel": "debug",
"logFile": "/tmp/multus.log",
"binDir": "/host/opt/cni/bin",
"cniDir": "/var/lib/cni/multus",
"socketDir": "/host/run/multus",
"cniVersion": "{{ CNI_VERSION }}",
"cniConfigDir": "/host/etc/cni/net.d",
"multusConfigFile": "auto",
"forceCNIVersion": true,
"multusAutoconfigDir": "/host/etc/cni/net.d"
}
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: kube-multus-ds-amd64
namespace: kube-system
labels:
tier: node
app: multus
name: multus
spec:
selector:
matchLabels:
name: multus
updateStrategy:
type: RollingUpdate
template:
metadata:
labels:
tier: node
app: multus
name: multus
spec:
hostNetwork: true
hostPID: true
nodeSelector:
kubernetes.io/arch: amd64
tolerations:
- operator: Exists
effect: NoSchedule
serviceAccountName: multus
containers:
- name: kube-multus
image: localhost:5000/multus:e2e
command: [ "/usr/src/multus-cni/bin/multus-daemon" ]
resources:
requests:
cpu: "100m"
memory: "50Mi"
limits:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: true
volumeMounts:
- name: cni
mountPath: /host/etc/cni/net.d
- name: cnibin
mountPath: /host/opt/cni/bin
- name: host-run
mountPath: /host/run
- name: host-var-lib-cni-multus
mountPath: /var/lib/cni/multus
- name: host-run-netns
mountPath: /run/netns
mountPropagation: HostToContainer
- name: multus-daemon-config
mountPath: /etc/cni/net.d/multus.d
readOnly: true
- name: kubelet-pod-resources
mountPath: /var/lib/kubelet/pod-resources
readOnly: true
env:
- name: MULTUS_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
initContainers:
- name: install-multus-shim
image: localhost:5000/multus:e2e
command:
- "cp"
- "/usr/src/multus-cni/bin/multus-shim"
- "/host/opt/cni/bin/multus-shim"
resources:
requests:
cpu: "10m"
memory: "15Mi"
securityContext:
privileged: true
volumeMounts:
- name: cnibin
mountPath: /host/opt/cni/bin
mountPropagation: Bidirectional
volumes:
- name: cni
hostPath:
path: /etc/cni/net.d
- name: cnibin
hostPath:
path: /opt/cni/bin
- name: kubelet-pod-resources
hostPath:
path: /var/lib/kubelet/pod-resources
- name: multus-daemon-config
configMap:
name: multus-daemon-config
items:
- key: daemon-config.json
path: daemon-config.json
- name: host-run
hostPath:
path: /run
- name: host-var-lib-cni-multus
hostPath:
path: /var/lib/cni/multus
- name: host-run-netns
hostPath:
path: /run/netns/

View File

@@ -0,0 +1,198 @@
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: network-attachment-definitions.k8s.cni.cncf.io
spec:
group: k8s.cni.cncf.io
scope: Namespaced
names:
plural: network-attachment-definitions
singular: network-attachment-definition
kind: NetworkAttachmentDefinition
shortNames:
- net-attach-def
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
config:
type: string
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: multus
rules:
- apiGroups: ["k8s.cni.cncf.io"]
resources:
- '*'
verbs:
- '*'
- apiGroups:
- ""
resources:
- pods
- pods/status
verbs:
- get
- update
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: multus
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: multus
subjects:
- kind: ServiceAccount
name: multus
namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: multus
namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
name: multus-cni-config
namespace: kube-system
labels:
tier: node
app: multus
data:
# NOTE: If you'd prefer to manually apply a configuration file, you may create one here.
# In the case you'd like to customize the Multus installation, you should change the arguments to the Multus pod
# change the "args" line below from
# - "--multus-conf-file=auto"
# to:
# "--multus-conf-file=/tmp/multus-conf/70-multus.conf"
# Additionally -- you should ensure that the name "70-multus.conf" is the alphabetically first name in the
# /etc/cni/net.d/ directory on each node, otherwise, it will not be used by the Kubelet.
cni-conf.json: |
{
"name": "multus-cni-network",
"type": "multus",
"capabilities": {
"portMappings": true
},
"delegates": [
{
"cniVersion": "0.3.1",
"name": "default-cni-network",
"plugins": [
{
"type": "flannel",
"name": "flannel.1",
"delegate": {
"isDefaultGateway": true,
"hairpinMode": true
}
},
{
"type": "portmap",
"capabilities": {
"portMappings": true
}
}
]
}
],
"kubeconfig": "/etc/cni/net.d/multus.d/multus.kubeconfig"
}
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: kube-multus-ds-amd64
namespace: kube-system
labels:
tier: node
app: multus
name: multus
spec:
selector:
matchLabels:
name: multus
updateStrategy:
type: RollingUpdate
template:
metadata:
labels:
tier: node
app: multus
name: multus
spec:
hostNetwork: true
nodeSelector:
kubernetes.io/arch: amd64
tolerations:
- operator: Exists
effect: NoSchedule
serviceAccountName: multus
containers:
- name: kube-multus
image: localhost:5000/multus:e2e
command: ["/thin_entrypoint"]
args:
- "--multus-conf-file=auto"
- "--force-cni-version=true"
- "--cni-version={{ CNI_VERSION }}"
resources:
requests:
cpu: "100m"
memory: "50Mi"
limits:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: true
volumeMounts:
- name: cni
mountPath: /host/etc/cni/net.d
- name: cnibin
mountPath: /host/opt/cni/bin
- name: multus-cfg
mountPath: /tmp/multus-conf
initContainers:
- name: install-multus-binary
image: localhost:5000/multus:e2e
command: ["/install_multus"]
args:
- "--type"
- "thin"
resources:
requests:
cpu: "10m"
memory: "15Mi"
securityContext:
privileged: true
volumeMounts:
- name: cnibin
mountPath: /host/opt/cni/bin
mountPropagation: Bidirectional
volumes:
- name: cni
hostPath:
path: /etc/cni/net.d
- name: cnibin
hostPath:
path: /opt/cni/bin
- name: multus-cfg
configMap:
name: multus-cni-config
items:
- key: cni-conf.json
path: 70-multus.conf

View File

@@ -0,0 +1,63 @@
---
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan1-config
spec:
config: '{
"cniVersion": "{{ CNI_VERSION }}",
"plugins": [
{
"type": "macvlan",
"capabilities": { "ips": true },
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "static"
}
}, {
"type": "tuning"
} ]
}'
---
apiVersion: v1
kind: Pod
metadata:
name: macvlan1-worker1
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name": "macvlan1-config",
"ips": [ "10.1.1.11/24" ] }
]'
labels:
app: macvlan
spec:
containers:
- name: macvlan-worker1
image: centos:8
command: ["/bin/sleep", "10000"]
securityContext:
privileged: true
nodeSelector:
kubernetes.io/hostname: kind-worker
---
apiVersion: v1
kind: Pod
metadata:
name: macvlan1-worker2
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name": "macvlan1-config",
"ips": [ "10.1.1.12/24" ] }
]'
labels:
app: macvlan
spec:
containers:
- name: macvlan-worker2
image: centos:8
command: ["/bin/sleep", "10000"]
securityContext:
privileged: true
nodeSelector:
kubernetes.io/hostname: kind-worker2

View File

@@ -0,0 +1,15 @@
---
apiVersion: v1
kind: Pod
metadata:
name: simple-centos1
annotations:
labels:
app: simple
spec:
containers:
- name: simple-centos1
image: centos:8
command: ["/bin/sleep", "10000"]
securityContext:
privileged: true

50
e2e/test-default-route1.sh Executable file
View File

@@ -0,0 +1,50 @@
#!/bin/sh
set -o errexit
export PATH=${PATH}:./bin
kubectl create -f yamls/default-route1.yml
kubectl wait --for=condition=ready -l app=default-route1 --timeout=300s pod
echo "check default-route-worker1 interface: net1"
kubectl exec default-route-worker1 -- ip a show dev net1
if [ $? -ne 0 ];then
exit 1
fi
echo "check default-route-worker1 interface address: net1"
ipaddr=$(kubectl exec default-route-worker1 -- ip -j a show | jq -r \
'.[]|select(.ifname =="net1")|.addr_info[]|select(.family=="inet").local')
if [ $ipaddr != "10.1.1.21" ]; then
echo "default-route-worker1 IP address is different: ${ipaddr}"
fi
echo "check default-route-worker1 default route"
ipaddr=$(kubectl exec default-route-worker1 -- ip -j route | jq -r \
'.[]|select(.dst=="default")|.gateway')
if [ $ipaddr != "10.1.1.254" ]; then
echo "default-route-worker1 default route is different: ${ipaddr}"
fi
echo "check default-route-worker2 interface: net1"
kubectl exec default-route-worker2 -- ip a show dev net1
if [ $? -ne 0 ];then
exit 1
fi
echo "check default-route-worker2 interface address: net1"
ipaddr=$(kubectl exec default-route-worker2 -- ip -j a show | jq -r \
'.[]|select(.ifname =="net1")|.addr_info[]|select(.family=="inet").local')
if [ $ipaddr != "10.1.1.22" ]; then
echo "default-route-worker2 IP address is different: ${ipaddr}"
fi
echo "check default-route-worker2 default route"
ipaddr=$(kubectl exec default-route-worker2 -- ip -j route | jq -r \
'.[]|select(.dst=="default")|.gateway')
if [ $ipaddr != "10.244.1.1" ]; then
echo "default-route-worker2 default route is different: ${ipaddr}"
fi
echo "cleanup resources"
kubectl delete -f yamls/default-route1.yml

60
e2e/test-dra-integration.sh Executable file
View File

@@ -0,0 +1,60 @@
#!/bin/sh
set -o errexit
export PATH=${PATH}:./bin
# This test is using an example implementation of a DRA driver. This driver is mocking GPU resources. At our test we
# don't care about what these resources are. We want to ensure that such resource is correctly passed in the Pod using
# Multus configurations. A couple of notes:
# - We explitictly pin the revision of the dra-example-driver to the branch `classic-dra` to indicate that the
# integration continues to work even when the dra-example-driver is updated. We know that classic-dra is supported
# in Kubernetes versions 1.26 to 1.30. Multus supports DRA in the aforementioned Kubernetes versions.
# - The chart and latest is image is not published somewhere, therefore we have to build locally. This leads to slower
# e2e suite runs.
echo "installing dra-example-driver"
repo_path="repos/dra-example-driver"
rm -rf $repo_path || true
git clone --branch classic-dra https://github.com/kubernetes-sigs/dra-example-driver.git ${repo_path}
${repo_path}/demo/build-driver.sh
KIND_CLUSTER_NAME=kind ${repo_path}/demo/scripts/load-driver-image-into-kind.sh
chart_path=${repo_path}/deployments/helm/dra-example-driver/
overriden_values_path=${chart_path}/overriden_values.yaml
# With the thick plugin, in kind, the primary network on the control plane is not always working as expected. The pods
# sometimes are not able to communicate with the control plane and the error looks like this:
# failed to list *v1alpha2.PodSchedulingContext: Get "https://10.96.0.1:443/apis/resource.k8s.io/v1alpha2/podschedulingcontexts?limit=500&resourceVersion=0": dial tcp 10.96.0.1:443: connect: no route to host
# We override the values here to schedule the controller on the worker nodes where the network is working as expected.
cat <<EOF >> ${overriden_values_path}
controller:
nodeSelector: null
tolerations: null
EOF
helm install \
-n dra-example-driver \
--create-namespace \
-f ${overriden_values_path} \
dra-example-driver \
${chart_path}
echo "installing testing pods"
kubectl create -f yamls/dra-integration.yml
kubectl wait --for=condition=ready -l app=dra-integration --timeout=300s pod
echo "check dra-integration pod for DRA injected environment variable"
# We can validate that the resource is correctly injected by checking an environment variable this dra driver is injecting
# in the Pod.
# https://github.com/kubernetes-sigs/dra-example-driver/blob/be2b8b1db47b8c757440e955ce5ced88c23bfe86/cmd/dra-example-kubeletplugin/cdi.go#L71C20-L71C44
env_variable=$(kubectl exec dra-integration -- bash -c "echo \$DRA_RESOURCE_DRIVER_NAME | grep gpu.resource.example.com")
if [ $? -eq 0 ];then
echo "dra-integration pod has DRA injected environment variable"
else
echo "dra-integration pod doesn't have DRA injected environment variable"
exit 1
fi
echo "cleanup resources"
kubectl delete -f yamls/dra-integration.yml
helm uninstall -n dra-example-driver dra-example-driver

42
e2e/test-simple-macvlan1.sh Executable file
View File

@@ -0,0 +1,42 @@
#!/bin/sh
set -o errexit
export PATH=${PATH}:./bin
kubectl create -f yamls/simple-macvlan1.yml
kubectl wait --for=condition=ready -l app=macvlan --timeout=300s pod
echo "check macvlan1-worker1 interface: net1"
net=$(kubectl exec macvlan1-worker1 -- ip a show dev net1)
if [ $? -eq 0 ];then
echo "macvlan1-worker1 pod has net1 card"
else
echo "macvlan1-worker1 pod has no net1 card"
exit 1
fi
echo "check macvlan1-worker1 interface address: net1"
ipaddr=$(kubectl exec macvlan1-worker1 -- ip -j a show | jq -r \
'.[]|select(.ifname =="net1")|.addr_info[]|select(.family=="inet").local')
if [ $ipaddr != "10.1.1.11" ]; then
echo "macvlan1-worker1 IP address is different: ${ipaddr}"
fi
echo "check macvlan1-worker2 interface: net1"
net2=$(kubectl exec macvlan1-worker2 -- ip a show dev net1)
if [ $? -eq 0 ];then
echo "macvlan1-worker2 pod has net1 card"
else
echo "macvlan1-worker2 pod has no net1 card"
exit 1
fi
echo "check macvlan1-worker2 interface address: net1"
ipaddr=$(kubectl exec macvlan1-worker2 -- ip -j a show | jq -r \
'.[]|select(.ifname =="net1")|.addr_info[]|select(.family=="inet").local')
if [ $ipaddr != "10.1.1.12" ]; then
echo "macvlan1-worker2 IP address is different: ${ipaddr}"
fi
echo "cleanup resources"
kubectl delete -f yamls/simple-macvlan1.yml

10
e2e/test-simple-pod.sh Executable file
View File

@@ -0,0 +1,10 @@
#!/bin/sh
set -o errexit
export PATH=${PATH}:./bin
kubectl create -f yamls/simple-pod.yml
kubectl wait --for=condition=ready -l app=simple --timeout=300s pod
echo "cleanup resources"
kubectl delete -f yamls/simple-pod.yml

22
e2e/test-static-pod.sh Executable file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -o errexit
echo "Creating network attachment definition"
kubectl create -f static-pod-nad.yml
echo "Creating static pod config file"
docker cp simple-static-pod.yml kind-worker:/etc/kubernetes/manifests/static-web.yaml
echo "Waiting for static pod to start"
kubectl wait --for=condition=Ready --namespace=default pod/static-web-kind-worker
echo "Checking the pod annotation for net1 interface"
kubectl exec static-web-kind-worker --namespace=default -- ip a show dev net1
echo "Deleting static pod"
docker exec kind-worker /bin/bash -c "rm /etc/kubernetes/manifests/static-web.yaml"
echo "Deleting network attachment definition"
kubectl delete -f static-pod-nad.yml
echo "Test complete"

View File

@@ -62,9 +62,9 @@ A sample `cni-configuration.conf` is provided, typically this file is placed in
Primarily in this setup one thing that one should consider are the aspects of the `macvlan-conf.yml`, which is likely specific to the configuration of the node on which this resides.
## Passing down device information
Some CNI plugins require specific device information which maybe pre-allocated by K8s device plugin. This could be indicated by providing `k8s.v1.cni.cncf.io/resourceName` annotaton in its network attachment definition CRD. The file [`examples/sriov-net.yaml`](./sriov-net.yaml) shows an example on how to define a Network attachment definition with specific device allocation information. Multus will get allocated device information and make them available for CNI plugin to work on.
Some CNI plugins require specific device information which maybe pre-allocated by K8s device plugin. This could be indicated by providing `k8s.v1.cni.cncf.io/resourceName` annotation in its network attachment definition CRD. The file [`examples/sriov-net.yaml`](./sriov-net.yaml) shows an example on how to define a Network attachment definition with specific device allocation information. Multus will get allocated device information and make them available for CNI plugin to work on.
In this exmaple (shown below), it is expected that an [SRIOV Device Plugin](https://github.com/intel/sriov-network-device-plugin/) making a pool of SRIOV VFs available to the K8s with `intel.com/sriov` as their resourceName. Any device allocated from this resource pool will be passed down by Multus to the [sriov-cni](https://github.com/intel/sriov-cni/tree/dev/k8s-deviceid-model) plugin in `deviceID` field. This is up to the sriov-cni plugin to capture this information and work with this specific device information.
In this example (shown below), it is expected that an [SRIOV Device Plugin](https://github.com/intel/sriov-network-device-plugin/) making a pool of SRIOV VFs available to the K8s with `intel.com/sriov` as their resourceName. Any device allocated from this resource pool will be passed down by Multus to the [sriov-cni](https://github.com/intel/sriov-cni/tree/dev/k8s-deviceid-model) plugin in `deviceID` field. This is up to the sriov-cni plugin to capture this information and work with this specific device information.
```yaml
apiVersion: "k8s.cni.cncf.io/v1"
@@ -89,6 +89,6 @@ spec:
}
}'
```
The [net-resource-sample-pod.yaml](./net-resource-sample-pod.yaml) is an exmaple Pod manifest file that requesting a SRIOV device from a host which is then configured using the above network attachement definition.
The [sriov-pod.yml](./sriov-pod.yml) is an example Pod manifest file that requesting a SRIOV device from a host which is then configured using the above network attachment definition.
>For further information on how to configure SRIOV Device Plugin and SRIOV-CNI please refer to the links given above.
>For further information on how to configure SRIOV Device Plugin and SRIOV-CNI please refer to the links given above.

View File

@@ -1,19 +0,0 @@
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: multus-crd-overpowered
rules:
- apiGroups: ["k8s.cni.cncf.io"]
resources:
- '*'
verbs:
- '*'
- apiGroups:
- ""
resources:
- pods
- pods/status
verbs:
- get
- update

View File

@@ -1,13 +0,0 @@
{
"name": "multus-cni-network",
"type": "multus",
"delegates": [
{
"type": "flannel",
"delegate": {
"isDefaultGateway": true
}
}
],
"kubeconfig": "/etc/kubernetes/kubelet.conf"
}

View File

@@ -1,21 +0,0 @@
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: network-attachment-definitions.k8s.cni.cncf.io
spec:
group: k8s.cni.cncf.io
version: v1
scope: Namespaced
names:
plural: network-attachment-definitions
singular: network-attachment-definition
kind: NetworkAttachmentDefinition
shortNames:
- net-attach-def
validation:
openAPIV3Schema:
properties:
spec:
properties:
config:
type: string

View File

@@ -1,12 +0,0 @@
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: flannel-conf
spec:
config: '{
"cniVersion": "0.3.0",
"type": "flannel",
"delegate": {
"isDefaultGateway": true
}
}'

View File

@@ -1,21 +0,0 @@
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth0",
"mode": "bridge",
"ipam": {
"type": "host-local",
"subnet": "192.168.1.0/24",
"rangeStart": "192.168.1.200",
"rangeEnd": "192.168.1.216",
"routes": [
{ "dst": "0.0.0.0/0" }
],
"gateway": "192.168.1.1"
}
}'

57
examples/macvlan-pod.yml Normal file
View File

@@ -0,0 +1,57 @@
---
# This net-attach-def defines macvlan-conf with
# + ips capabilities to specify ip in pod annotation and
# + mac capabilities to specify mac address in pod annotation
# default gateway is defined as well
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf
spec:
config: '{
"cniVersion": "0.3.1",
"plugins": [
{
"type": "macvlan",
"capabilities": { "ips": true },
"master": "eth0",
"mode": "bridge",
"ipam": {
"type": "static",
"routes": [
{
"dst": "0.0.0.0/0",
"gw": "10.1.1.1"
}
]
}
}, {
"capabilities": { "mac": true },
"type": "tuning"
}
]
}'
---
# Define a pod with macvlan-conf, defined above, with ip address and mac, and
# "gateway" overrides default gateway to use macvlan-conf's one.
# without "gateway" in k8s.v1.cni.cncf.io/networks, default route will be cluster
# network interface, eth0, even tough macvlan-conf has default gateway config.
apiVersion: v1
kind: Pod
metadata:
name: samplepod
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name": "macvlan-conf",
"ips": [ "10.1.1.101/24" ],
"mac": "c2:b0:57:49:47:f1",
"gateway": [ "10.1.1.1" ]
}]'
spec:
containers:
- name: samplepod
command: ["/bin/bash", "-c", "trap : TERM INT; sleep infinity & wait"]
image: dougbtv/centos-network
ports:
- containerPort: 80
automountServiceAccountToken: false

View File

@@ -1,36 +0,0 @@
{
"name": "multus-cni-network",
"type": "multus"
"capabilities": {
"portMappings": true
},
"delegates": [
{
"cniVersion": "0.3.1",
"name": "ptp-tuning-conflist",
"plugins": [
{
"dns": {
"nameservers": [
"172.16.1.1"
]
},
"ipMasq": true,
"ipam": {
"subnet": "172.16.0.0/24",
"type": "host-local"
},
"mtu": 512,
"type": "ptp"
},
{
"capabilities": {
"portMappings": true
},
"externalSetMarkChain": "KUBE-MARK-MASQ",
"type": "portmap"
}
]
}
],
}

View File

@@ -1,163 +0,0 @@
# -----------------------------------------------
# - Example Configuration Deployment
# -----------------------------------------------
# - Deploys a .conf file on each node
# - Configured for Multus + Flannel.
# - As well as assets for Flannel
# - Based on https://github.com/coreos/flannel/blob/master/Documentation/kube-flannel.yml
# -----------------------------------------------
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: flannel
rules:
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- apiGroups:
- ""
resources:
- nodes
verbs:
- list
- watch
- apiGroups:
- ""
resources:
- nodes/status
verbs:
- patch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: flannel
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: flannel
subjects:
- kind: ServiceAccount
name: flannel
namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: flannel
namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
name: kube-multus-cfg
namespace: kube-system
labels:
tier: node
app: multus
data:
cni-conf.json: |
{
"name": "multus-cni-network",
"type": "multus",
"delegates": [
{
"type": "flannel",
"delegate": {
"isDefaultGateway": true
}
}
],
"kubeconfig": "/etc/kubernetes/kubelet.conf"
}
net-conf.json: |
{
"Network": "10.244.0.0/16",
"Backend": {
"Type": "vxlan"
}
}
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
name: kube-multus-ds
namespace: kube-system
labels:
tier: node
app: multus
spec:
updateStrategy:
type: RollingUpdate
template:
metadata:
labels:
tier: node
app: multus
spec:
hostNetwork: true
nodeSelector:
beta.kubernetes.io/arch: amd64
tolerations:
- operator: Exists
effect: NoSchedule
serviceAccountName: flannel
initContainers:
- name: install-cni
image: quay.io/coreos/flannel:v0.10.0-amd64
command:
- cp
args:
- -f
- /etc/kube-flannel/cni-conf.json
- /etc/cni/net.d/10-multus-with-flannel.conf
volumeMounts:
- name: cni
mountPath: /etc/cni/net.d
- name: multus-cfg
mountPath: /etc/kube-flannel/
containers:
- name: kube-flannel
image: quay.io/coreos/flannel:v0.10.0-amd64
command:
- /opt/bin/flanneld
args:
- --ip-masq
- --kube-subnet-mgr
resources:
requests:
cpu: "100m"
memory: "50Mi"
limits:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: true
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
volumeMounts:
- name: run
mountPath: /run
- name: multus-cfg
mountPath: /etc/kube-flannel/
volumes:
- name: run
hostPath:
path: /run
- name: cni
hostPath:
path: /etc/cni/net.d
- name: multus-cfg
configMap:
name: kube-multus-cfg

View File

@@ -1,21 +0,0 @@
apiVersion: v1
kind: Pod
metadata:
name: testpod1
labels:
env: test
annotations:
k8s.v1.cni.cncf.io/networks: sriov-net-a
spec:
containers:
- name: appcntr1
image: centos/tools
imagePullPolicy: IfNotPresent
command: [ "/bin/bash", "-c", "--" ]
args: [ "while true; do sleep 300000; done;" ]
resources:
requests:
intel.com/sriov: '1'
limits:
intel.com/sriov: '1'
restartPolicy: "Never"

View File

@@ -1,30 +0,0 @@
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
# name must match the spec fields below, and be in the form: <plural>.<group>
name: network-attachment-definitions.k8s.cni.cncf.io
spec:
# group name to use for REST API: /apis/<group>/<version>
group: k8s.cni.cncf.io
# version name to use for REST API: /apis/<group>/<version>
version: v1
# either Namespaced or Cluster
scope: Namespaced
names:
# plural name to be used in the URL: /apis/<group>/<version>/<plural>
plural: network-attachment-definitions
# singular name to be used as an alias on the CLI and for display
singular: network-attachment-definition
# kind is normally the CamelCased singular type. Your resource manifests use this.
kind: NetworkAttachmentDefinition
# shortNames allow shorter string to match your resource on the CLI
shortNames:
- net-attach-def
validation:
openAPIV3Schema:
properties:
spec:
properties:
config:
type: string

View File

@@ -1,16 +0,0 @@
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: multus
rules:
- apiGroups:
- '*'
resources:
- '*'
verbs:
- '*'
- nonResourceURLs:
- '*'
verbs:
- '*'

View File

@@ -1,5 +0,0 @@
---
apiVersion: v1
kind: Namespace
metadata:
name: testns1

View File

@@ -1,72 +0,0 @@
---
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf-1
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "static",
"addresses": [
{ "address": "10.1.1.101/24" }
]
}
}'
---
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf-2
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "static",
"addresses": [
{ "address": "10.1.1.102/24" }
]
}
}'
---
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf-3
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "static",
"addresses": [
{ "address": "10.1.1.103/24" }
]
}
}'
---
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: macvlan-conf-4
spec:
config: '{
"cniVersion": "0.3.0",
"type": "macvlan",
"master": "eth1",
"mode": "bridge",
"ipam": {
"type": "static",
"addresses": [
{ "address": "10.1.1.104/24" }
]
}
}'

View File

@@ -1,19 +0,0 @@
---
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: vlan-conf-1-1
namespace: testns1
spec:
config: '{
"cniVersion": "0.3.0",
"type": "vlan",
"master": "eth1",
"vlanid": 1,
"ipam": {
"type": "static",
"addresses": [
{ "address": "172.16.1.101/24"
} ]
}
}'

View File

@@ -1,196 +0,0 @@
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: flannel2
namespace: kube-system
rules:
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- apiGroups:
- ""
resources:
- nodes
verbs:
- list
- watch
- apiGroups:
- ""
resources:
- nodes/status
verbs:
- patch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: flannel2
namespace: kube-system
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: flannel2
subjects:
- kind: ServiceAccount
name: flannel2
namespace: kube-system
---
kind: ServiceAccount
apiVersion: v1
metadata:
name: flannel2
namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
name: kube-flannel2-cfg
namespace: kube-system
labels:
tier: node
app: flannel2
data:
flannel2-conf.json: |
{
"type": "flannel",
"name": "flannel-2",
"subnetFile": "/run/flannel/flannel2.env",
"dataDir": "/var/lib/cni/flannel2",
"delegate": {
"bridge": "kbr1"
}
}
net-conf.json: |
{
"Network": "10.144.0.0/16",
"SubnetLen": 24,
"SubnetMin": "10.144.0.0",
"Backend": {
"Type": "vxlan"
}
}
---
apiVersion: v1
kind: Pod
metadata:
name: flannel-etcd
namespace: kube-system
spec:
containers:
- command:
- etcd
- --advertise-client-urls=http://10.1.1.1:12379
- --listen-client-urls=http://0.0.0.0:12379
- --listen-peer-urls=http://localhost:12380
image: quay.io/coreos/etcd:latest
name: etcd
hostNetwork: true
nodeName: kube-master
---
apiVersion: batch/v1
kind: Job
metadata:
name: flannel-etcdctl
namespace: kube-system
spec:
template:
spec:
containers:
- name: flannel-etcdctl
image: quay.io/coreos/etcd:latest
command: ["etcdctl"]
args: ["--endpoints=http://10.1.1.1:12379", "set", "/flannel2/network/config", '{ "Network": "10.5.0.0/16", "Backend": {"Type": "vxlan", "VNI": 2}}']
hostNetwork: true
nodeName: kube-master
restartPolicy: Never
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
name: kube-flannel2-ds
namespace: kube-system
labels:
tier: node
app: flannel2
spec:
updateStrategy:
type: RollingUpdate
template:
metadata:
labels:
tier: node
app: flannel2
spec:
hostNetwork: true
nodeSelector:
beta.kubernetes.io/arch: amd64
tolerations:
- key: node-role.kubernetes.io/master
operator: Exists
effect: NoSchedule
serviceAccountName: flannel2
initContainers:
- name: install-cni
image: quay.io/coreos/flannel:v0.10.0-amd64
command:
- cp
args:
- -f
- /etc/kube-flannel/flannel2-conf.json
- /etc/cni/multus/net.d/10-flannel.conf
volumeMounts:
- name: cni
mountPath: /etc/cni/multus/net.d
- name: flannel2-cfg
mountPath: /etc/kube-flannel/
containers:
- name: kube-flannel2
image: quay.io/coreos/flannel:v0.10.0-amd64
command:
- /opt/bin/flanneld
args:
- --ip-masq
- --etcd-endpoints=http://10.1.1.1:12379
- -iface=eth1
- -subnet-file=/run/flannel/flannel2.env
- -etcd-prefix=/flannel2/network
resources:
requests:
cpu: "100m"
memory: "50Mi"
limits:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: true
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
volumeMounts:
- name: run
mountPath: /run
volumes:
- name: run
hostPath:
path: /run
- name: cni
hostPath:
path: /etc/cni/multus/net.d
- name: flannel2-cfg
configMap:
name: kube-flannel2-cfg
---
apiVersion: "kubernetes.cni.cncf.io/v1"
kind: Network
metadata:
name: flannel-2

View File

@@ -1,30 +0,0 @@
---
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: ptp-tuning-conflist
spec:
config: '{
"cniVersion": "0.3.1",
"name": "ptp-tuning-conflist",
"plugins": [{
"type": "ptp",
"ipMasq": true,
"mtu": 512,
"ipam": {
"type": "host-local",
"subnet": "172.16.0.0/24"
},
"dns": {
"nameservers": ["172.16.1.1"]
}
},
{
"name": "mytuning",
"type": "tuning",
"sysctl": {
"net.core.somaxconn": "500"
}
}
]
}'

View File

@@ -1,13 +0,0 @@
---
apiVersion: v1
kind: Pod
metadata:
name: pod-case-01
annotations:
k8s.v1.cni.cncf.io/networks: macvlan-conf-1
spec:
containers:
- name: pod-case-01
image: docker.io/centos/tools:latest
command:
- /sbin/init

View File

@@ -1,18 +0,0 @@
---
apiVersion: v1
kind: Pod
metadata:
name: pod-case-02
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name": "macvlan-conf-2" },
{ "name": "vlan-conf-1-1",
"namespace": "testns1",
"interface": "vlan1-1" }
]'
spec:
containers:
- name: pod-case-02
image: docker.io/centos/tools:latest
command:
- /sbin/init

View File

@@ -1,17 +0,0 @@
---
apiVersion: v1
kind: Pod
metadata:
name: pod-case-03
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name": "macvlan-conf-3" },
{ "name": "macvlan-conf-4" },
{ "name": "flannel-2" }
]'
spec:
containers:
- name: pod-case-03
image: docker.io/centos/tools:latest
command:
- /sbin/init

View File

@@ -1,11 +0,0 @@
---
apiVersion: v1
kind: Pod
metadata:
name: pod-case-04
spec:
containers:
- name: pod-case-04
image: docker.io/centos/tools:latest
command:
- /sbin/init

View File

@@ -1,15 +0,0 @@
---
apiVersion: v1
kind: Pod
metadata:
name: pod-case-05
annotations:
k8s.v1.cni.cncf.io/networks: '[
{ "name": "ptp-tuning-conflist" }
]'
spec:
containers:
- name: pod-case-05
image: docker.io/centos/tools:latest
command:
- /sbin/init

View File

@@ -1,14 +0,0 @@
---
apiVersion: v1
kind: Pod
metadata:
name: samplepod
annotations:
k8s.v1.cni.cncf.io/networks: macvlan-conf
spec:
containers:
- name: samplepod
command: ["/bin/bash", "-c", "trap : TERM INT; sleep infinity & wait"]
image: dougbtv/centos-network
ports:
- containerPort: 80

View File

@@ -1,21 +0,0 @@
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: sriov-net-a
annotations:
k8s.v1.cni.cncf.io/resourceName: intel.com/sriov
spec:
config: '{
"type": "sriov",
"vlan": 1000,
"ipam": {
"type": "host-local",
"subnet": "10.56.217.0/24",
"rangeStart": "10.56.217.171",
"rangeEnd": "10.56.217.181",
"routes": [{
"dst": "0.0.0.0/0"
}],
"gateway": "10.56.217.1"
}
}'

48
examples/sriov-pod.yml Normal file
View File

@@ -0,0 +1,48 @@
# This net-attach-def defines SR-IOV CNI config
# Please see https://github.com/intel/sriov-cni and https://github.com/intel/sriov-network-device-plugin
# for its detail.
---
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
name: sriov-net-a
annotations:
k8s.v1.cni.cncf.io/resourceName: intel.com/sriov
spec:
config: '{
"type": "sriov",
"vlan": 1000,
"ipam": {
"type": "host-local",
"subnet": "10.56.217.0/24",
"rangeStart": "10.56.217.171",
"rangeEnd": "10.56.217.181",
"routes": [{
"dst": "0.0.0.0/0"
}],
"gateway": "10.56.217.1"
}
}'
---
apiVersion: v1
kind: Pod
metadata:
name: testpod1
labels:
env: test
annotations:
k8s.v1.cni.cncf.io/networks: sriov-net-a
spec:
containers:
- name: appcntr1
image: centos/tools
imagePullPolicy: IfNotPresent
command: [ "/bin/bash", "-c", "--" ]
args: [ "while true; do sleep 300000; done;" ]
resources:
requests:
intel.com/sriov: '1'
limits:
intel.com/sriov: '1'
restartPolicy: "Never"
automountServiceAccountToken: false

146
go.mod
View File

@@ -1,42 +1,112 @@
module github.com/intel/multus-cni
module gopkg.in/k8snetworkplumbingwg/multus-cni.v4
go 1.12
go 1.21
require (
github.com/Microsoft/go-winio v0.4.14 // indirect
github.com/containernetworking/cni v0.7.1
github.com/containernetworking/plugins v0.8.2
github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680 // indirect
github.com/gogo/protobuf v0.0.0-20170330071051-c0656edd0d9e // indirect
github.com/golang/protobuf v1.3.2 // indirect
github.com/google/btree v0.0.0-20160524151835-7d79101e329e // indirect
github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367 // indirect
github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d // indirect
github.com/gregjones/httpcache v0.0.0-20170728041850-787624de3eb7 // indirect
github.com/imdario/mergo v0.0.0-20141206190957-6633656539c1 // indirect
github.com/json-iterator/go v0.0.0-20180612202835-f2b4162afba3 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v0.0.0-20180320133207-05fbef0ca5da // indirect
github.com/onsi/ginkgo v1.9.0
github.com/onsi/gomega v1.6.0
github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
github.com/pkg/errors v0.8.1
github.com/spf13/pflag v1.0.1 // indirect
github.com/stretchr/objx v0.2.0 // indirect
github.com/stretchr/testify v1.4.0 // indirect
github.com/vishvananda/netlink v0.0.0-20181108222139-023a6dafdcdf
github.com/vishvananda/netns v0.0.0-20190625233234-7109fa855b0f // indirect
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586 // indirect
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7
golang.org/x/sys v0.0.0-20190825160603-fb81701db80f // indirect
golang.org/x/text v0.3.2 // indirect
golang.org/x/time v0.0.0-20161028155119-f51c12702a4d // indirect
google.golang.org/grpc v1.23.0
gopkg.in/inf.v0 v0.9.0 // indirect
gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0 // indirect
k8s.io/api v0.0.0-20180712090710-2d6f90ab1293
k8s.io/apimachinery v0.0.0-20180621070125-103fd098999d
k8s.io/client-go v0.0.0-20180718001006-59698c7d9724
k8s.io/klog v0.0.0-20181108234604-8139d8cb77af // indirect
k8s.io/kubernetes v1.13.0
github.com/blang/semver v3.5.1+incompatible
github.com/containernetworking/cni v1.2.0-rc1
github.com/containernetworking/plugins v1.1.0
github.com/fsnotify/fsnotify v1.6.0
github.com/go-logr/logr v1.3.0 // indirect
github.com/k8snetworkplumbingwg/network-attachment-definition-client v1.7.4
github.com/onsi/ginkgo/v2 v2.13.2
github.com/onsi/gomega v1.30.0
github.com/pkg/errors v0.9.1 // indirect
github.com/vishvananda/netlink v1.1.1-0.20210330154013-f5de75959ad5
golang.org/x/net v0.23.0
golang.org/x/sys v0.18.0
google.golang.org/grpc v1.58.3
gopkg.in/natefinch/lumberjack.v2 v2.0.0
k8s.io/api v0.29.0
k8s.io/apimachinery v0.29.0
k8s.io/client-go v1.5.2
k8s.io/klog v1.0.0
k8s.io/klog/v2 v2.110.1
k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 // indirect
k8s.io/kubelet v0.27.5
sigs.k8s.io/yaml v1.3.0 // indirect
)
require (
github.com/prometheus/client_golang v1.16.0
github.com/spf13/pflag v1.0.5
)
require (
github.com/Masterminds/semver/v3 v3.2.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/emicklei/go-restful/v3 v3.11.0 // indirect
github.com/evanphx/json-patch v4.12.0+incompatible // indirect
github.com/go-openapi/jsonpointer v0.19.6 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.22.3 // indirect
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/gnostic v0.7.0 // indirect
github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/imdario/mergo v0.3.11 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/prometheus/client_model v0.4.0 // indirect
github.com/prometheus/common v0.44.0 // indirect
github.com/prometheus/procfs v0.10.1 // indirect
github.com/vishvananda/netns v0.0.4 // indirect
golang.org/x/oauth2 v0.10.0 // indirect
golang.org/x/term v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.3.0 // indirect
golang.org/x/tools v0.14.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect
)
replace (
github.com/gogo/protobuf => github.com/gogo/protobuf v1.3.2
k8s.io/api => k8s.io/api v0.29.0
k8s.io/apiextensions-apiserver => k8s.io/apiextensions-apiserver v0.29.0
k8s.io/apimachinery => k8s.io/apimachinery v0.29.0
k8s.io/apiserver => k8s.io/apiserver v0.29.0
k8s.io/cli-runtime => k8s.io/cli-runtime v0.29.0
k8s.io/client-go => k8s.io/client-go v0.29.0
k8s.io/cloud-provider => k8s.io/cloud-provider v0.29.0
k8s.io/cluster-bootstrap => k8s.io/cluster-bootstrap v0.29.0
k8s.io/code-generator => k8s.io/code-generator v0.29.0
k8s.io/component-base => k8s.io/component-base v0.29.0
k8s.io/component-helpers => k8s.io/component-helpers v0.29.0
k8s.io/controller-manager => k8s.io/controller-manager v0.29.0
k8s.io/cri-api => k8s.io/cri-api v0.29.0
k8s.io/csi-translation-lib => k8s.io/csi-translation-lib v0.29.0
k8s.io/kube-aggregator => k8s.io/kube-aggregator v0.29.0
k8s.io/kube-controller-manager => k8s.io/kube-controller-manager v0.29.0
k8s.io/kube-openapi => k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f
k8s.io/kube-proxy => k8s.io/kube-proxy v0.29.0
k8s.io/kube-scheduler => k8s.io/kube-scheduler v0.29.0
k8s.io/kubectl => k8s.io/kubectl v0.29.0
k8s.io/kubelet => k8s.io/kubelet v0.29.0
k8s.io/kubernetes => k8s.io/kubernetes v1.29.0
k8s.io/legacy-cloud-providers => k8s.io/legacy-cloud-providers v0.29.0
k8s.io/metrics => k8s.io/metrics v0.29.0
k8s.io/mount-utils => k8s.io/mount-utils v0.29.0
k8s.io/pod-security-admission => k8s.io/pod-security-admission v0.29.0
k8s.io/sample-apiserver => k8s.io/sample-apiserver v0.29.0
)

1738
go.sum

File diff suppressed because it is too large Load Diff

82
hack/build-go.sh Executable file
View File

@@ -0,0 +1,82 @@
#!/usr/bin/env bash
set -e
DEST_DIR="bin"
if [ ! -d ${DEST_DIR} ]; then
mkdir ${DEST_DIR}
fi
# Specify correspondingGOARCH from TARGETPLATFORM
if [ "$TARGETPLATFORM" = "linux/amd64" ]; then
export GOARCH=amd64
elif [ "$TARGETPLATFORM" = "linux/arm64" ]; then
export GOARCH=arm64
elif [ "$TARGETPLATFORM" = "linux/arm/v7" ]; then
export GOARCH=arm
elif [ "$TARGETPLATFORM" = "linux/ppc64le" ]; then
export GOARCH=ppc64le
elif [ "$TARGETPLATFORM" = "linux/s390x" ]; then
export GOARCH=s390x
fi
# version information
hasGit=true
git version > /dev/null 2>&1 || hasGit=false
GIT_SHA=""
GIT_TREE_STATE=""
GIT_TAG=""
GIT_TAG_LAST=""
RELEASE_STATUS=""
if $hasGit; then
set +e
GIT_SHA=$(git rev-parse --short HEAD)
# Tree state is "dirty" if there are uncommitted changes, untracked files are ignored
GIT_TREE_STATE=$(test -n "`git status --porcelain --untracked-files=no`" && echo "dirty" || echo "clean")
# Empty string if we are not building a tag
GIT_TAG=$(git describe --tags --abbrev=0 --exact-match 2>/dev/null || true)
# Find most recent tag
GIT_TAG_LAST=$(git describe --tags --abbrev=0 2>/dev/null || true)
set -e
fi
# VERSION override mechanism if needed
VERSION=${VERSION:-}
if [[ -n "${VERSION}" || -n "${GIT_TAG}" ]]; then
RELEASE_STATUS=",released"
fi
if [ -z "$VERSION" ]; then
VERSION=$GIT_TAG_LAST
fi
# Add version/commit/date into binary
DATE=$(date -u -d "@${SOURCE_DATE_EPOCH:-$(date +%s)}" --iso-8601=seconds)
COMMIT=${COMMIT:-$(git rev-parse --verify HEAD)}
LDFLAGS="-X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.version=${VERSION} \
-X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.commit=${COMMIT} \
-X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.gitTreeState=${GIT_TREE_STATE} \
-X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.releaseStatus=${RELEASE_STATUS} \
-X gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/multus.date=${DATE}"
export CGO_ENABLED=${CGO_ENABLED:-0}
# build with go modules
export GO111MODULE=on
if [ -n "$MODMODE" ]; then
BUILD_ARGS=(-mod "$MODMODE")
fi
echo "Building multus"
go build -o ${DEST_DIR}/multus ${BUILD_ARGS} -ldflags "${LDFLAGS}" "$@" ./cmd/multus
echo "Building multus-daemon"
go build -o "${DEST_DIR}"/multus-daemon ${BUILD_ARGS} -ldflags "${LDFLAGS}" ./cmd/multus-daemon
echo "Building multus-shim"
go build -o "${DEST_DIR}"/multus-shim ${BUILD_ARGS} -ldflags "${LDFLAGS}" ./cmd/multus-shim
echo "Building install_multus"
go build -o "${DEST_DIR}"/install_multus ${BUILD_ARGS} -ldflags "${LDFLAGS}" ./cmd/install_multus
echo "Building thin_entrypoint"
go build -o "${DEST_DIR}"/thin_entrypoint ${BUILD_ARGS} -ldflags "${LDFLAGS}" ./cmd/thin_entrypoint
echo "Building kubeconfig_generator"
go build -o "${DEST_DIR}"/kubeconfig_generator ${BUILD_ARGS} -ldflags "${LDFLAGS}" ./cmd/kubeconfig_generator
echo "Building cert-approver"
go build -o "${DEST_DIR}"/cert-approver ${BUILD_ARGS} -ldflags "${LDFLAGS}" ./cmd/cert-approver

23
hack/test-go.sh Executable file
View File

@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -e
# this if... will be removed when gomodules goes default
if [ "$GO111MODULE" == "off" ]; then
echo "Warning: this will be deprecated in near future so please use go modules!"
ORG_PATH="gopkg.in/k8snetworkplumbingwg"
REPO_PATH="${ORG_PATH}/multus-cni"
if [ ! -h gopath/src/${REPO_PATH} ]; then
mkdir -p gopath/src/${ORG_PATH}
ln -s ../../../.. gopath/src/${REPO_PATH} || exit 255
fi
export GO15VENDOREXPERIMENT=1
export GOBIN=${PWD}/bin
export GOPATH=${PWD}/gopath
bash -c "umask 0; cd ${GOPATH}/src/${REPO_PATH}; PATH=${GOROOT}/bin:$(pwd)/bin:${PATH} go test -v -covermode=count -coverprofile=coverage.out ./..."
else
# test with go modules
bash -c "umask 0; go test -v -race -covermode=atomic -coverprofile=coverage.out ./..."
fi

21
images/Dockerfile Normal file
View File

@@ -0,0 +1,21 @@
# This Dockerfile is used to build the image available on DockerHub
FROM --platform=$BUILDPLATFORM golang:1.21 as build
# Add everything
ADD . /usr/src/multus-cni
ARG TARGETPLATFORM
RUN cd /usr/src/multus-cni && \
./hack/build-go.sh
FROM gcr.io/distroless/base-debian11:latest
LABEL org.opencontainers.image.source https://github.com/k8snetworkplumbingwg/multus-cni
COPY --from=build /usr/src/multus-cni/bin /usr/src/multus-cni/bin
COPY --from=build /usr/src/multus-cni/LICENSE /usr/src/multus-cni/LICENSE
WORKDIR /
COPY --from=build /usr/src/multus-cni/bin/install_multus /
COPY --from=build /usr/src/multus-cni/bin/thin_entrypoint /
COPY --from=build /usr/src/multus-cni/bin/kubeconfig_generator /
COPY --from=build /usr/src/multus-cni/bin/cert-approver /
CMD ["/thin_entrypoint"]

21
images/Dockerfile.debug Normal file
View File

@@ -0,0 +1,21 @@
# This Dockerfile is used to build the image available on DockerHub
FROM --platform=$BUILDPLATFORM golang:1.21 as build
# Add everything
ADD . /usr/src/multus-cni
ARG TARGETPLATFORM
RUN cd /usr/src/multus-cni && \
./hack/build-go.sh
FROM gcr.io/distroless/base-debian11:debug
LABEL org.opencontainers.image.source https://github.com/k8snetworkplumbingwg/multus-cni
COPY --from=build /usr/src/multus-cni/bin /usr/src/multus-cni/bin
COPY --from=build /usr/src/multus-cni/LICENSE /usr/src/multus-cni/LICENSE
WORKDIR /
COPY --from=build /usr/src/multus-cni/bin/install_multus /
COPY --from=build /usr/src/multus-cni/bin/thin_entrypoint /
COPY --from=build /usr/src/multus-cni/bin/kubeconfig_generator /
COPY --from=build /usr/src/multus-cni/bin/cert-approver /
CMD ["/thin_entrypoint"]

View File

@@ -0,0 +1,23 @@
# This dockerfile is specific to building Multus for OpenShift
# The okd-builder image is locally built from https://raw.githubusercontent.com/okd-project/images/main/okd-builder.Dockerfile
FROM local/okdbuilder:latest as builder
ADD . /usr/src/multus-cni
WORKDIR /usr/src/multus-cni
ENV GO111MODULE=off
RUN ./hack/build-go.sh
FROM quay.io/openshift/origin-base:latest
LABEL org.opencontainers.image.source https://github.com/k8snetworkplumbingwg/multus-cni
RUN mkdir -p /usr/src/multus-cni/images && mkdir -p /usr/src/multus-cni/bin
COPY --from=builder /usr/src/multus-cni/bin/multus /usr/src/multus-cni/bin
COPY --from=builder /usr/src/multus-cni/bin/install_multus /
COPY --from=builder /usr/src/multus-cni/bin/thin_entrypoint /
LABEL io.k8s.display-name="Multus CNI" \
io.k8s.description="This is a component of OpenShift Container Platform and provides a meta CNI plugin." \
io.openshift.tags="openshift" \
maintainer="Doug Smith <dosmith@redhat.com>"
ENTRYPOINT ["/thin_entrypoint"]

17
images/Dockerfile.thick Normal file
View File

@@ -0,0 +1,17 @@
# This Dockerfile is used to build the image available on DockerHub
FROM golang:1.21 as build
# Add everything
ADD . /usr/src/multus-cni
RUN cd /usr/src/multus-cni && \
./hack/build-go.sh
FROM debian:stable-slim
LABEL org.opencontainers.image.source https://github.com/k8snetworkplumbingwg/multus-cni
COPY --from=build /usr/src/multus-cni/bin /usr/src/multus-cni/bin
COPY --from=build /usr/src/multus-cni/LICENSE /usr/src/multus-cni/LICENSE
COPY --from=build /usr/src/multus-cni/bin/cert-approver /
WORKDIR /
ENTRYPOINT [ "/usr/src/multus-cni/bin/multus-daemon" ]

View File

@@ -5,7 +5,7 @@ This is used for distribution of Multus in a Docker image.
Typically you'd build this from the root of your Multus clone, as such:
```
$ docker build -t dougbtv/multus .
$ docker build -t dougbtv/multus -f images/Dockerfile .
```
---
@@ -15,7 +15,7 @@ $ docker build -t dougbtv/multus .
You may wish to deploy Multus as a daemonset, you can do so by starting with the example Daemonset shown here:
```
$ kubectl create -f ./images/multus-daemonset.yml
$ kubectl create -f ./deployments/multus-daemonset.yml
```
Note: The likely best practice here is to build your own image given the Dockerfile, and then push it to your preferred registry, and change the `image` fields in the Daemonset YAML to reference that image.
@@ -41,9 +41,7 @@ in lexicographical order in cni-conf-dir).
./entrypoint.sh
-h --help
--cni-conf-dir=/host/etc/cni/net.d
--cni-bin-dir=/host/opt/cni/bin
--multus-conf-file=/usr/src/multus-cni/images/70-multus.conf
--multus-bin-file=/usr/src/multus-cni/bin/multus
--multus-kubeconfig-file-host=/etc/cni/net.d/multus.d/multus.kubeconfig
```
@@ -65,4 +63,4 @@ Example docker run command:
$ docker run -it -v /opt/cni/bin/:/host/opt/cni/bin/ -v /etc/cni/net.d/:/host/etc/cni/net.d/ --entrypoint=/bin/bash dougbtv/multus
```
Originally inspired by and is a portmanteau of the [Flannel daemonset](https://github.com/coreos/flannel/blob/master/Documentation/kube-flannel.yml), the [Calico Daemonset](https://github.com/projectcalico/calico/blob/master/v2.0/getting-started/kubernetes/installation/hosted/k8s-backend-addon-manager/calico-daemonset.yaml), and the [Calico CNI install bash script](https://github.com/projectcalico/cni-plugin/blob/be4df4db2e47aa7378b1bdf6933724bac1f348d0/k8s-install/scripts/install-cni.sh#L104-L153).
Originally inspired by and is a portmanteau of the [Flannel daemonset](https://github.com/coreos/flannel/blob/master/Documentation/kube-flannel.yml), the [Calico Daemonset](https://docs.projectcalico.org/manifests/calico.yaml), and the [Calico CNI install bash script](https://github.com/projectcalico/cni-plugin/blob/be4df4db2e47aa7378b1bdf6933724bac1f348d0/k8s-install/scripts/install-cni.sh#L104-L153).

View File

@@ -1,366 +0,0 @@
#!/bin/bash
# Always exit on errors.
set -e
# Run a clean up when we exit if configured to do so.
trap cleanup TERM
function cleanup {
if [ "$MULTUS_CLEANUP_CONFIG_ON_EXIT" == "true" ]; then
CONF=$(cat <<-EOF
{Multus configuration intentionally invalidated to prevent pods from being scheduled.}
EOF
)
echo $CONF > $CNI_CONF_DIR/00-multus.conf
log "Multus configuration intentionally invalidated to prevent pods from being scheduled."
fi
}
# Set our known directories.
CNI_CONF_DIR="/host/etc/cni/net.d"
CNI_BIN_DIR="/host/opt/cni/bin"
ADDITIONAL_BIN_DIR=""
MULTUS_CONF_FILE="/usr/src/multus-cni/images/70-multus.conf"
MULTUS_AUTOCONF_DIR="/host/etc/cni/net.d"
MULTUS_BIN_FILE="/usr/src/multus-cni/bin/multus"
MULTUS_KUBECONFIG_FILE_HOST="/etc/cni/net.d/multus.d/multus.kubeconfig"
MULTUS_NAMESPACE_ISOLATION=false
MULTUS_LOG_LEVEL=""
MULTUS_LOG_FILE=""
OVERRIDE_NETWORK_NAME=false
MULTUS_CLEANUP_CONFIG_ON_EXIT=false
RESTART_CRIO=false
CRIO_RESTARTED_ONCE=false
RENAME_SOURCE_CONFIG_FILE=false
# Give help text for parameters.
function usage()
{
echo -e "This is an entrypoint script for Multus CNI to overlay its binary and "
echo -e "configuration into locations in a filesystem. The configuration & binary file "
echo -e "will be copied to the corresponding configuration directory. When "
echo -e "'--multus-conf-file=auto' is used, 00-multus.conf will be automatically "
echo -e "generated from the CNI configuration file of the master plugin (the first file "
echo -e "in lexicographical order in cni-conf-dir)."
echo -e ""
echo -e "./entrypoint.sh"
echo -e "\t-h --help"
echo -e "\t--cni-conf-dir=$CNI_CONF_DIR"
echo -e "\t--cni-bin-dir=$CNI_BIN_DIR"
echo -e "\t--cni-version=<cniVersion (e.g. 0.3.1)>"
echo -e "\t--multus-conf-file=$MULTUS_CONF_FILE"
echo -e "\t--multus-bin-file=$MULTUS_BIN_FILE"
echo -e "\t--multus-kubeconfig-file-host=$MULTUS_KUBECONFIG_FILE_HOST"
echo -e "\t--namespace-isolation=$MULTUS_NAMESPACE_ISOLATION"
echo -e "\t--multus-autoconfig-dir=$MULTUS_AUTOCONF_DIR (used only with --multus-conf-file=auto)"
echo -e "\t--multus-log-level=$MULTUS_LOG_LEVEL (empty by default, used only with --multus-conf-file=auto)"
echo -e "\t--multus-log-file=$MULTUS_LOG_FILE (empty by default, used only with --multus-conf-file=auto)"
echo -e "\t--override-network-name=false (used only with --multus-conf-file=auto)"
echo -e "\t--cleanup-config-on-exit=false (used only with --multus-conf-file=auto)"
echo -e "\t--rename-conf-file=false (used only with --multus-conf-file=auto)"
echo -e "\t--additional-bin-dir=$ADDITIONAL_BIN_DIR (adds binDir option to configuration, used only with --multus-conf-file=auto)"
echo -e "\t--restart-crio=false (restarts CRIO after config file is generated)"
}
function log()
{
echo "$(date --iso-8601=seconds) ${1}"
}
function error()
{
log "ERR: {$1}"
}
function warn()
{
log "WARN: {$1}"
}
# Parse parameters given as arguments to this script.
while [ "$1" != "" ]; do
PARAM=`echo $1 | awk -F= '{print $1}'`
VALUE=`echo $1 | awk -F= '{print $2}'`
case $PARAM in
-h | --help)
usage
exit
;;
--cni-version)
CNI_VERSION=$VALUE
;;
--cni-conf-dir)
CNI_CONF_DIR=$VALUE
;;
--cni-bin-dir)
CNI_BIN_DIR=$VALUE
;;
--multus-conf-file)
MULTUS_CONF_FILE=$VALUE
;;
--multus-bin-file)
MULTUS_BIN_FILE=$VALUE
;;
--multus-kubeconfig-file-host)
MULTUS_KUBECONFIG_FILE_HOST=$VALUE
;;
--namespace-isolation)
MULTUS_NAMESPACE_ISOLATION=$VALUE
;;
--multus-log-level)
MULTUS_LOG_LEVEL=$VALUE
;;
--multus-log-file)
MULTUS_LOG_FILE=$VALUE
;;
--multus-autoconfig-dir)
MULTUS_AUTOCONF_DIR=$VALUE
;;
--override-network-name)
OVERRIDE_NETWORK_NAME=$VALUE
;;
--cleanup-config-on-exit)
MULTUS_CLEANUP_CONFIG_ON_EXIT=$VALUE
;;
--restart-crio)
RESTART_CRIO=$VALUE
;;
--rename-conf-file)
RENAME_SOURCE_CONFIG_FILE=$VALUE
;;
--additional-bin-dir)
ADDITIONAL_BIN_DIR=$VALUE
;;
*)
warn "unknown parameter \"$PARAM\""
;;
esac
shift
done
# Create array of known locations
declare -a arr=($CNI_CONF_DIR $CNI_BIN_DIR $MULTUS_BIN_FILE)
if [ "$MULTUS_CONF_FILE" != "auto" ]; then
arr+=($MULTUS_CONF_FILE)
fi
# Loop through and verify each location each.
for i in "${arr[@]}"
do
if [ ! -e "$i" ]; then
warn "Location $i does not exist"
exit 1;
fi
done
# Copy files into place and atomically move into final binary name
cp -f $MULTUS_BIN_FILE $CNI_BIN_DIR/_multus
mv -f $CNI_BIN_DIR/_multus $CNI_BIN_DIR/multus
if [ "$MULTUS_CONF_FILE" != "auto" ]; then
cp -f $MULTUS_CONF_FILE $CNI_CONF_DIR
fi
# Make a multus.d directory (for our kubeconfig)
mkdir -p $CNI_CONF_DIR/multus.d
MULTUS_KUBECONFIG=$CNI_CONF_DIR/multus.d/multus.kubeconfig
# ------------------------------- Generate a "kube-config"
# Inspired by: https://tinyurl.com/y7r2knme
SERVICE_ACCOUNT_PATH=/var/run/secrets/kubernetes.io/serviceaccount
KUBE_CA_FILE=${KUBE_CA_FILE:-$SERVICE_ACCOUNT_PATH/ca.crt}
SERVICEACCOUNT_TOKEN=$(cat $SERVICE_ACCOUNT_PATH/token)
SKIP_TLS_VERIFY=${SKIP_TLS_VERIFY:-false}
# Check if we're running as a k8s pod.
if [ -f "$SERVICE_ACCOUNT_PATH/token" ]; then
# We're running as a k8d pod - expect some variables.
if [ -z ${KUBERNETES_SERVICE_HOST} ]; then
error "KUBERNETES_SERVICE_HOST not set"; exit 1;
fi
if [ -z ${KUBERNETES_SERVICE_PORT} ]; then
error "KUBERNETES_SERVICE_PORT not set"; exit 1;
fi
if [ "$SKIP_TLS_VERIFY" == "true" ]; then
TLS_CFG="insecure-skip-tls-verify: true"
elif [ -f "$KUBE_CA_FILE" ]; then
TLS_CFG="certificate-authority-data: $(cat $KUBE_CA_FILE | base64 | tr -d '\n')"
fi
# Write a kubeconfig file for the CNI plugin. Do this
# to skip TLS verification for now. We should eventually support
# writing more complete kubeconfig files. This is only used
# if the provided CNI network config references it.
touch $MULTUS_KUBECONFIG
chmod ${KUBECONFIG_MODE:-600} $MULTUS_KUBECONFIG
cat > $MULTUS_KUBECONFIG <<EOF
# Kubeconfig file for Multus CNI plugin.
apiVersion: v1
kind: Config
clusters:
- name: local
cluster:
server: ${KUBERNETES_SERVICE_PROTOCOL:-https}://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}
$TLS_CFG
users:
- name: multus
user:
token: "${SERVICEACCOUNT_TOKEN}"
contexts:
- name: multus-context
context:
cluster: local
user: multus
current-context: multus-context
EOF
else
warn "Doesn't look like we're running in a kubernetes environment (no serviceaccount token)"
fi
# ---------------------- end Generate a "kube-config".
# ------------------------------- Generate "00-multus.conf"
function generateMultusConf {
if [ "$MULTUS_CONF_FILE" == "auto" ]; then
log "Generating Multus configuration file using files in $MULTUS_AUTOCONF_DIR..."
found_master=false
tries=0
while [ $found_master == false ]; do
MASTER_PLUGIN="$(ls $MULTUS_AUTOCONF_DIR | grep -E '\.conf(list)?$' | grep -Ev '00-multus\.conf' | head -1)"
if [ "$MASTER_PLUGIN" == "" ]; then
if [ $tries -lt 600 ]; then
if ! (($tries % 5)); then
log "Attemping to find master plugin configuration, attempt $tries"
fi
let "tries+=1"
# See if the Multus configuration file exists, if it does then clean it up.
if [ "$MULTUS_CLEANUP_CONFIG_ON_EXIT" == true ] && [ -f "$CNI_CONF_DIR/00-multus.conf" ]; then
# But first, check if it has the invalidated configuration in it (otherwise we keep doing this over and over.)
if ! grep -q "invalidated" $CNI_CONF_DIR/00-multus.conf; then
cleanup
fi
fi
sleep 1;
else
error "Multus could not be configured: no master plugin was found."
exit 1;
fi
else
found_master=true
ISOLATION_STRING=""
if [ "$MULTUS_NAMESPACE_ISOLATION" == true ]; then
ISOLATION_STRING="\"namespaceIsolation\": true,"
fi
LOG_LEVEL_STRING=""
if [ ! -z "${MULTUS_LOG_LEVEL// }" ]; then
case "$MULTUS_LOG_LEVEL" in
debug)
;;
error)
;;
panic)
;;
verbose)
;;
*)
error "Log levels should be one of: debug/verbose/error/panic, did not understand $MULTUS_LOG_LEVEL"
usage
exit 1
esac
LOG_LEVEL_STRING="\"logLevel\": \"$MULTUS_LOG_LEVEL\","
fi
LOG_FILE_STRING=""
if [ ! -z "${MULTUS_LOG_FILE// }" ]; then
LOG_FILE_STRING="\"logFile\": \"$MULTUS_LOG_FILE\","
fi
CNI_VERSION_STRING=""
if [ ! -z "${CNI_VERSION// }" ]; then
CNI_VERSION_STRING="\"cniVersion\": \"$CNI_VERSION\","
fi
ADDITIONAL_BIN_DIR_STRING=""
if [ ! -z "${ADDITIONAL_BIN_DIR// }" ]; then
ADDITIONAL_BIN_DIR_STRING="\"binDir\": \"$ADDITIONAL_BIN_DIR\","
fi
if [ "$OVERRIDE_NETWORK_NAME" == "true" ]; then
MASTER_PLUGIN_NET_NAME="$(cat $MULTUS_AUTOCONF_DIR/$MASTER_PLUGIN | \
python -c 'import json,sys;print json.load(sys.stdin)["name"]')"
else
MASTER_PLUGIN_NET_NAME="multus-cni-network"
fi
MASTER_PLUGIN_LOCATION=$MULTUS_AUTOCONF_DIR/$MASTER_PLUGIN
MASTER_PLUGIN_JSON="$(cat $MASTER_PLUGIN_LOCATION)"
log "Using $MASTER_PLUGIN_LOCATION as a source to generate the Multus configuration"
CONF=$(cat <<-EOF
{
$CNI_VERSION_STRING
"name": "$MASTER_PLUGIN_NET_NAME",
"type": "multus",
$ISOLATION_STRING
$LOG_LEVEL_STRING
$LOG_FILE_STRING
$ADDITIONAL_BIN_DIR_STRING
"kubeconfig": "$MULTUS_KUBECONFIG_FILE_HOST",
"delegates": [
$MASTER_PLUGIN_JSON
]
}
EOF
)
echo $CONF > $CNI_CONF_DIR/00-multus.conf
log "Config file created @ $CNI_CONF_DIR/00-multus.conf"
echo $CONF
# If we're not performing the cleanup on exit, we can safely rename the config file.
if [ "$RENAME_SOURCE_CONFIG_FILE" == true ]; then
mv ${MULTUS_AUTOCONF_DIR}/${MASTER_PLUGIN} ${MULTUS_AUTOCONF_DIR}/${MASTER_PLUGIN}.old
log "Original master file moved to ${MULTUS_AUTOCONF_DIR}/${MASTER_PLUGIN}.old"
fi
if [ "$RESTART_CRIO" == true ]; then
# Restart CRIO only once.
if [ "$CRIO_RESTARTED_ONCE" == false ]; then
log "Restarting crio"
systemctl restart crio
CRIO_RESTARTED_ONCE=true
fi
fi
fi
done
fi
}
generateMultusConf
# ---------------------- end Generate "00-multus.conf".
# Enter either sleep loop, or watch loop...
if [ "$MULTUS_CLEANUP_CONFIG_ON_EXIT" == true ]; then
log "Entering watch loop..."
while true; do
# Check and see if the original master plugin configuration exists...
if [ ! -f "$MASTER_PLUGIN_LOCATION" ]; then
log "Master plugin @ $MASTER_PLUGIN_LOCATION has been deleted. Performing cleanup..."
cleanup
generateMultusConf
log "Continuing watch loop after configuration regeneration..."
fi
sleep 1
done
else
log "Entering sleep (success)..."
sleep infinity
fi

View File

@@ -1,244 +0,0 @@
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: network-attachment-definitions.k8s.cni.cncf.io
spec:
group: k8s.cni.cncf.io
version: v1
scope: Namespaced
names:
plural: network-attachment-definitions
singular: network-attachment-definition
kind: NetworkAttachmentDefinition
shortNames:
- net-attach-def
validation:
openAPIV3Schema:
properties:
spec:
properties:
config:
type: string
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: multus
rules:
- apiGroups: ["k8s.cni.cncf.io"]
resources:
- '*'
verbs:
- '*'
- apiGroups:
- ""
resources:
- pods
- pods/status
verbs:
- get
- update
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: multus
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: multus
subjects:
- kind: ServiceAccount
name: multus
namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: multus
namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
name: multus-cni-config
namespace: kube-system
labels:
tier: node
app: multus
data:
# NOTE: If you'd prefer to manually apply a configuration file, you may create one here.
# In the case you'd like to customize the Multus installation, you should change the arguments to the Multus pod
# change the "args" line below from
# - "--multus-conf-file=auto"
# to:
# "--multus-conf-file=/tmp/multus-conf/70-multus.conf"
# Additionally -- you should ensure that the name "70-multus.conf" is the alphabetically first name in the
# /etc/cni/net.d/ directory on each node, otherwise, it will not be used by the Kubelet.
cni-conf.json: |
{
"name": "multus-cni-network",
"type": "multus",
"capabilities": {
"portMappings": true
},
"delegates": [
{
"cniVersion": "0.3.1",
"name": "default-cni-network",
"plugins": [
{
"type": "flannel",
"name": "flannel.1",
"delegate": {
"isDefaultGateway": true,
"hairpinMode": true
}
},
{
"type": "portmap",
"capabilities": {
"portMappings": true
}
}
]
}
],
"kubeconfig": "/etc/cni/net.d/multus.d/multus.kubeconfig"
}
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
name: kube-multus-ds-amd64
namespace: kube-system
labels:
tier: node
app: multus
spec:
updateStrategy:
type: RollingUpdate
template:
metadata:
labels:
tier: node
app: multus
spec:
hostNetwork: true
nodeSelector:
beta.kubernetes.io/arch: amd64
tolerations:
- operator: Exists
effect: NoSchedule
serviceAccountName: multus
containers:
- name: kube-multus
# crio support requires multus:latest for now. support 3.3 or later.
image: nfvpe/multus:latest
command: ["/entrypoint.sh"]
args:
- "--cni-bin-dir=/host/usr/libexec/cni"
- "--multus-conf-file=auto"
- "--override-network-name=true"
- "--restart-crio=true"
resources:
requests:
cpu: "100m"
memory: "50Mi"
limits:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: true
capabilities:
add: ["SYS_ADMIN"]
volumeMounts:
- name: run
mountPath: /run
- name: cni
mountPath: /host/etc/cni/net.d
- name: cnibin
mountPath: /host/usr/libexec/cni
- name: multus-cfg
mountPath: /tmp/multus-conf
volumes:
- name: run
hostPath:
path: /run
- name: cni
hostPath:
path: /etc/cni/net.d
- name: cnibin
hostPath:
path: /usr/libexec/cni
- name: multus-cfg
configMap:
name: multus-cni-config
items:
- key: cni-conf.json
path: 70-multus.conf
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
name: kube-multus-ds-ppc64le
namespace: kube-system
labels:
tier: node
app: multus
spec:
updateStrategy:
type: RollingUpdate
template:
metadata:
labels:
tier: node
app: multus
spec:
hostNetwork: true
nodeSelector:
beta.kubernetes.io/arch: ppc64le
tolerations:
- operator: Exists
effect: NoSchedule
serviceAccountName: multus
containers:
- name: kube-multus
# crio support requires multus:latest for now. support 3.3 or later.
image: nfvpe/multus:latest-ppc64le
command: ["/entrypoint.sh"]
args:
- "--cni-bin-dir=/host/usr/libexec/cni"
- "--multus-conf-file=auto"
- "--override-network-name=true"
- "--restart-crio=true"
resources:
requests:
cpu: "100m"
memory: "90Mi"
limits:
cpu: "100m"
memory: "90Mi"
securityContext:
privileged: true
volumeMounts:
- name: cni
mountPath: /host/etc/cni/net.d
- name: cnibin
mountPath: /host/usr/libexec/cni
- name: multus-cfg
mountPath: /tmp/multus-conf
volumes:
- name: cni
hostPath:
path: /etc/cni/net.d
- name: cnibin
hostPath:
path: /usr/libexec/cni
- name: multus-cfg
configMap:
name: multus-cni-config
items:
- key: cni-conf.json
path: 70-multus.conf

Some files were not shown because too many files have changed in this diff Show More