Compare commits

..

259 Commits

Author SHA1 Message Date
5c3c171642 Merge pull request #239 from steveeJ/master
MAINTAINERS: remove @zachgersh, add @dcbw
2016-06-02 09:00:07 -07:00
4a292cd451 Merge pull request #218 from steveeJ/roadmap
Add ROADMAP document
2016-06-02 16:51:57 +01:00
f82af22b10 ROADMAP: initial version 2016-06-02 17:50:14 +02:00
4f9faf60bb MAINTAINERS: remove @zachgersh, add @dcbw
Thank you Zach for all the great work done on CNI, farewell!
At the same time we are happy to welcome Dan amongst us who has already
contributed lots of valuable work!
2016-06-02 01:15:24 +02:00
f44f4cf953 Merge pull request #219 from squaremo/more-contrib
docs: details on PR acceptance policy
2016-06-01 16:03:17 +02:00
ddc0ca4791 docs: details on PR acceptance policy 2016-06-01 12:23:21 +01:00
e90d8c12b1 Merge pull request #228 from jieyu/add_mesos
Added Mesos to CNI users.
2016-05-30 11:13:34 +01:00
ffff8ac2fd Merge pull request #231 from steveeJ/ns-verifiy-errors
pkg/ns: introduce error types to indicate NS verification
2016-05-27 15:57:40 +02:00
35f3a090b2 pkg/ns: introduce error types indicate NS verification 2016-05-27 13:50:16 +02:00
131ecc4055 Merge pull request #230 from steveeJ/netns-optional-on-del
plugins: don't require CNI_NETNS for DEL command
2016-05-27 13:49:05 +02:00
d582c9ce8f skel/test: add case for empty NETNS 2016-05-27 12:26:42 +02:00
72337159c1 plugins: don't require CNI_NETNS for DEL command
This will allow to free up the IPAM allocations when the caller doesn't
have access to the network namespace anymore, e.g. due to a reboot.
2016-05-27 10:57:39 +02:00
7f90f9d559 pkg/skel: allow arg requriements specified by CMD 2016-05-27 10:56:24 +02:00
d6674e0f49 README: add Mesos as CNI users 2016-05-26 09:42:10 -07:00
6f63d9d707 Merge pull request #227 from steveeJ/ns-verify
pkg/ns: consider PROCFS during NS verification
2016-05-26 13:22:29 +02:00
3bab8a2805 pkg/ns: consider PROCFS during NS verification
This is an attempt to bring compatibility with Kernel <3.19, where NSFS
where PROCFS was used for network namespaces.
2016-05-26 12:42:50 +02:00
6fb30a6700 Merge pull request #222 from steveeJ/ns-check-path
pkg/ns: verify netns when initialized with GetNS
2016-05-25 08:54:10 +02:00
d6751cea24 pkg/ns: test IsNSFS() 2016-05-24 22:30:49 +02:00
c43ccc703a pkg/ns: test case for rejecting a non-ns nspath 2016-05-24 22:30:49 +02:00
76ea259ff9 pkg/ns: verify netns when initialized with GetNS 2016-05-24 22:30:49 +02:00
c29cd52628 Merge pull request #223 from steveeJ/ns-respect-close
pkg/ns: don't allow operations after Close()
2016-05-24 22:16:09 +02:00
2de97b7e98 pkg/ns: add tests cases for Close()'d NS 2016-05-24 21:15:51 +02:00
b23895a7c7 pkg/ns: don't allow operations after Close() 2016-05-24 20:52:00 +02:00
984ef8117a Merge pull request #217 from steveeJ/fix-go-tip
build: don't be verbose / test: fix bash variable escaping in sudo command
2016-05-21 01:55:57 +02:00
54c0cd2cad build: remove -x bash flag 2016-05-21 01:48:26 +02:00
232d7c095d test: fix bash variable escaping in sudo command 2016-05-21 01:48:26 +02:00
20fa3d35e8 Merge pull request #50 from steveeJ/gwfix
bridge: add isDefaultGateway field
2016-05-21 01:34:21 +02:00
8afda5faed tests/bridge: ensure isDefaultGateway works 2016-05-21 01:07:05 +02:00
534768fcd4 bridge: add isDefaultGateway field
When isDefaultGateway is true it automatically sets isGateway to true.
The default route will be added via the (bridge's) gateway IP.
If a default gateway has been configured via IPAM in the same
configuration file, the plugin will error out.
2016-05-21 00:38:42 +02:00
d30040f9f7 Merge pull request #211 from dcbw/e2e-testing
Fix namespace switch issues and add ipvlan, macvlan, and bridge e2e testing
2016-05-21 00:17:45 +02:00
ebf83ffde5 bridge: add e2e testing 2016-05-20 17:10:25 -05:00
552dc43168 macvlan: add e2e testing 2016-05-20 17:10:25 -05:00
185e33ebe9 ipvlan: add e2e testing 2016-05-20 17:10:25 -05:00
31da322f6e testutils: add e2e testing helper code 2016-05-20 17:10:25 -05:00
c0d34c692f ns: add interface, use it, and fix thread-related namespace switch issues
Add a namespace object interface for somewhat cleaner code when
creating and switching between network namespaces.  All created
namespaces are now mounted in /var/run/netns to ensure they
have persistent inodes and paths that can be passed around
between plugin components without relying on the current namespace
being correct.

Also remove the thread-locking arguments from the ns package
per https://github.com/appc/cni/issues/183 by doing all the namespace
changes in a separate goroutine that locks/unlocks itself, instead of
the caller having to track OS thread locking.
2016-05-20 17:10:25 -05:00
3e1c3c60da Merge pull request #199 from dcbw/fix-bridge-tx-queue-length
bridge: leave TX queue length as kernel default, not 0
2016-05-19 23:05:08 +02:00
d29b895932 Merge pull request #212 from squaremo/more-contrib
docs: Mention license headers and doc contributions
2016-05-19 18:38:57 +02:00
398710b3c4 Merge pull request #214 from steveeJ/merge-v0.2
Merge v0.2
2016-05-19 15:45:07 +02:00
5fa06a39f0 release script: don't run the tests
For two reasons:

1. They're not functional within rkt
2. They rebuild the binaries dynamically
2016-05-19 15:05:29 +02:00
c72dea5a20 build/release: link all release binaries statically 2016-05-19 15:05:29 +02:00
4aaffc2069 scripts: build static releases and create an ACI
* use SHA1 instead of MD5
2016-05-19 15:05:29 +02:00
e145c60337 scripts: add "release with rkt"
This script uses rkt and a fedora image to build release tarballs.
2016-05-19 15:05:29 +02:00
bcc189e1e6 docs: Mention license headers and doc contributions
Closes #174.
2016-05-19 13:42:36 +01:00
991176a64a Merge pull request #200 from squaremo/simplify-readme
Simplify README preamble
2016-05-19 13:21:40 +01:00
8db1f0d503 README: Simplify preamble 2016-05-19 12:52:09 +01:00
74790e55ef Merge pull request #175. 2016-05-19 12:08:41 +02:00
89ab9299ab plugins/bridge: add support to set hairpin mode 2016-05-19 12:06:37 +02:00
f4eb76318e macvlan: sysctl must be set in macvlan interface's namespace
The macvlan is initially created in a separate network namespace
and the sysctl must be set in that namespace too.
2016-05-19 12:06:37 +02:00
a80bcc0371 pkg/ns: evaluate syscall number at compile-time
Previously this code used a run-time map lookup keyed by
runtime.GOOS/GOARCH.  This version uses conditional compilation to make
this choice at compile time, giving immediate feedback for unsupported
platforms.
2016-05-19 12:06:37 +02:00
979044ad2f pkg/ns: use correct syscall number on arm 2016-05-19 12:06:37 +02:00
ec78e7cf1e MAINTAINERS: add Tom Denham and Gabe Rosenhouse 2016-05-19 12:06:37 +02:00
5d67d22caa plugins/{ptp,bridge}: teardown first
This will allow the IPAM allocations to be cleared in case the
interfaces and iptables rules are non-existent.
2016-05-19 12:06:37 +02:00
2c482f433c *: appc/cni -> containernetworking/cni
The project has been moved so internally we simply rename everything.
Consumers are recommended to update their vendored version of cni.
2016-05-19 12:06:36 +02:00
419711fee3 README: fix badge links 2016-05-19 12:06:36 +02:00
04dbf7ce45 README: fix badges 2016-05-19 12:06:36 +02:00
61f20da4f2 README: add contiv to cni supported networking 2016-05-19 12:06:36 +02:00
a993ef5f7f plugins/bridge: clean masquerading rules
In the Add command we set up masquerading rules that didn't have a
corresponding clean-up code in Del.

Add the clean-up code.
2016-05-19 12:06:36 +02:00
41a5dfac33 Remove reference to policy on accepting PRs
There is to policy
2016-05-19 12:06:36 +02:00
a1dab0aa40 macvlan: set proxy_arp in time of creating interface
Resolves CNI part of https://github.com/coreos/rkt/issues/1765
Second part would be adding similar lines into kvm flavored macvlan
support (in time of creating macvtap device).
2016-05-19 12:06:16 +02:00
4298aa94a5 pkg/utils: add functions to work with sysctl 2016-05-19 12:06:16 +02:00
d53ffe1b40 README: clarify what CNI is
The word "standard" does not represent what CNI is actually trying to
be.
2016-05-19 12:06:16 +02:00
b5e56b3dab Document use of goroutine and lockosthread in test helpers 2016-05-19 12:06:16 +02:00
260c7f96bf ns: fix reading net namespace in multi-threaded processes
/proc/self/ns/net gives the main thread's namespace, not necessarily
the namespace of the thread that's running the testcases.  This causes
sporadic failures of the tests.

For example, with a testcase reading inodes after switching netns:

/proc/27686/task/27689/ns/net 4026532565
/proc/self/ns/net 4026531969
/proc/27686/task/27689/ns/net 4026532565

See also:
008d17ae00

Running Suite: pkg/ns Suite
===========================
Random Seed: 1459953577
Will run 6 of 6 specs

• Failure [0.028 seconds]
Linux namespace operations
/cni/gopath/src/github.com/appc/cni/pkg/ns/ns_test.go:167
  WithNetNS
  /cni/gopath/src/github.com/appc/cni/pkg/ns/ns_test.go:166
    executes the callback within the target network namespace [It]
    /cni/gopath/src/github.com/appc/cni/pkg/ns/ns_test.go:97

    Expected
        <uint64>: 4026531969
    to equal
        <uint64>: 4026532565

    /cni/gopath/src/github.com/appc/cni/pkg/ns/ns_test.go:96
------------------------------
•••••

Summarizing 1 Failure:

[Fail] Linux namespace operations WithNetNS [It] executes the callback within the target network namespace
/cni/gopath/src/github.com/appc/cni/pkg/ns/ns_test.go:96

Ran 6 of 6 Specs in 0.564 seconds
FAIL! -- 5 Passed | 1 Failed | 0 Pending | 0 Skipped --- FAIL: TestNs (0.56s)
FAIL
2016-05-19 12:06:16 +02:00
b09af2ff91 Fix issues with MakeNetworkNS test helper 2016-05-19 12:06:16 +02:00
1bbc87ab54 Add basic unit tests of testhelpers 2016-05-19 12:06:16 +02:00
4fc8a90277 Extract inode inspection functions into testhelpers 2016-05-19 12:06:16 +02:00
9044dc2831 Extract testhelpers from loopback test suite 2016-05-19 12:06:16 +02:00
5019e283b1 README: add some material on what CNI isn't
We get some questions about this stuff from time to time and I want to
acknowledge we have thought about them but aren't currently tackling
them.
2016-05-19 12:06:16 +02:00
e7ae43e517 README: add some more details on what CNI is
We needed a bit more intro material to scope what CNI does. Here is my
attempt.
2016-05-19 12:06:16 +02:00
72e98b97d6 The macvlan is initially created in a separate network namespaceand the sysctl must be set in that namespace too.Fixes #208.
The macvlan is initially created in a separate network namespace
and the sysctl must be set in that namespace too.

Fixes #208.
2016-05-17 21:11:21 +02:00
8f5194d9b5 pkg/ns: setns syscall number on arm and evaluate them at build time.
Dummy merge due to previous manual merge.
2016-05-17 18:44:33 +02:00
31379b8a41 Merge branch 'anguslees-master' 2016-05-17 18:36:38 +02:00
2b019bfde1 pkg/ns: evaluate syscall number at compile-time
Previously this code used a run-time map lookup keyed by
runtime.GOOS/GOARCH.  This version uses conditional compilation to make
this choice at compile time, giving immediate feedback for unsupported
platforms.
2016-05-17 18:36:29 +02:00
a2f23f5a84 pkg/ns: use correct syscall number on arm 2016-05-17 18:36:22 +02:00
899c0efd42 bridge: leave TX queue length as kernel default, not 0
Not using NewLinkAttrs() or not initializing TxQLen leaves
the value as 0, which tells the kernel to set a zero-length
tx_queue_len.  That messes up FIFO traffic shapers (like pfifo)
that use the device TX queue length as the default packet
limit.  This leads to a default packet limit of 0, which drops
all packets.
2016-05-12 10:35:50 -05:00
e1907bdab7 Merge pull request #201 from jonboulle/master
MAINTAINERS: add Tom Denham and Gabe Rosenhouse
2016-05-12 14:51:37 +01:00
463e171614 Merge pull request #205 from steveeJ/teardown-fix
plugins/{ptp,bridge}: teardown first
2016-05-12 10:54:47 +02:00
d91971cbe0 plugins/{ptp,bridge}: teardown first
This will allow the IPAM allocations to be cleared in case the
interfaces and iptables rules are non-existent.
2016-05-11 19:47:55 +02:00
bf8bde8256 MAINTAINERS: add Tom Denham and Gabe Rosenhouse 2016-05-10 12:12:05 +02:00
64791dd233 Merge pull request #198 from steveeJ/org-move
*: appc/cni -> containernetworking/cni
2016-05-06 17:58:44 +02:00
e021964819 README: fix badge links 2016-05-06 08:39:55 -07:00
56ddbfd522 README: fix badges 2016-05-06 08:39:21 -07:00
ed5f8dfeb2 *: appc/cni -> containernetworking/cni
The project has been moved so internally we simply rename everything.
Consumers are recommended to update their vendored version of cni.
2016-05-06 16:40:27 +02:00
fb34e4a21d Merge pull request #197 from jainvipin/master
Add Contiv to CNI supported networking
2016-05-05 09:15:15 +01:00
914a85c544 README: add contiv to cni supported networking 2016-05-04 20:29:13 -07:00
dbcecbcec6 Merge branch 'pr195' (clean up masq rules) 2016-05-04 13:50:09 +01:00
6aa26f9fd2 plugins/bridge: clean masquerading rules
In the Add command we set up masquerading rules that didn't have a
corresponding clean-up code in Del.

Add the clean-up code.
2016-05-03 12:21:58 +02:00
99ca41457e macvlan: sysctl must be set in macvlan interface's namespace
The macvlan is initially created in a separate network namespace
and the sysctl must be set in that namespace too.
2016-04-28 11:26:47 -05:00
cae660409f Merge pull request #189 from tomdee/patch-2
Remove reference to policy on accepting PRs
2016-04-27 15:47:42 +01:00
902ee8b992 Remove reference to policy on accepting PRs
There is to policy
2016-04-22 12:52:28 -07:00
911d941794 Merge pull request #187 from appc/v0.3.0
merge unneeded branch v0.3.0 into master
2016-04-22 19:25:54 +02:00
8bb41b9d6f Merge pull request #186 from steveeJ/project-clarification
README: clarify what CNI is
2016-04-21 11:54:52 +01:00
ef251cc6ce README: clarify what CNI is
The word "standard" does not represent what CNI is actually trying to
be.
2016-04-20 20:00:50 +02:00
57b28f3936 Merge pull request #182 from rosenhouse/document-lockosthread
Document use of goroutine and LockOSThread in test helpers
2016-04-18 10:45:46 -07:00
7383809048 Merge pull request #176 from dcbw/ns-test-fix
ns: fix reading net namespace in multi-threaded processes
2016-04-18 10:44:08 -07:00
07a993dc7d ns: fix reading net namespace in multi-threaded processes
/proc/self/ns/net gives the main thread's namespace, not necessarily
the namespace of the thread that's running the testcases.  This causes
sporadic failures of the tests.

For example, with a testcase reading inodes after switching netns:

/proc/27686/task/27689/ns/net 4026532565
/proc/self/ns/net 4026531969
/proc/27686/task/27689/ns/net 4026532565

See also:
008d17ae00

Running Suite: pkg/ns Suite
===========================
Random Seed: 1459953577
Will run 6 of 6 specs

• Failure [0.028 seconds]
Linux namespace operations
/cni/gopath/src/github.com/appc/cni/pkg/ns/ns_test.go:167
  WithNetNS
  /cni/gopath/src/github.com/appc/cni/pkg/ns/ns_test.go:166
    executes the callback within the target network namespace [It]
    /cni/gopath/src/github.com/appc/cni/pkg/ns/ns_test.go:97

    Expected
        <uint64>: 4026531969
    to equal
        <uint64>: 4026532565

    /cni/gopath/src/github.com/appc/cni/pkg/ns/ns_test.go:96
------------------------------
•••••

Summarizing 1 Failure:

[Fail] Linux namespace operations WithNetNS [It] executes the callback within the target network namespace
/cni/gopath/src/github.com/appc/cni/pkg/ns/ns_test.go:96

Ran 6 of 6 Specs in 0.564 seconds
FAIL! -- 5 Passed | 1 Failed | 0 Pending | 0 Skipped --- FAIL: TestNs (0.56s)
FAIL
2016-04-18 10:35:23 -05:00
94c4b25698 Document use of goroutine and lockosthread in test helpers 2016-04-17 20:27:02 -07:00
616702bcf3 Merge pull request #181 from rosenhouse/testhelpers-extraction
Extract and improve test helpers
2016-04-17 20:20:43 -07:00
e3fb7ce3a7 Fix issues with MakeNetworkNS test helper 2016-04-17 19:47:54 -07:00
dd3b85c9cc Add basic unit tests of testhelpers 2016-04-17 19:25:39 -07:00
54d7f73092 Extract inode inspection functions into testhelpers 2016-04-17 18:35:49 -07:00
5d932e4716 Extract testhelpers from loopback test suite 2016-04-17 18:28:10 -07:00
9a2801085b Merge pull request #180 from philips/add-more-intro
README: add some more introductory material
2016-04-11 10:12:22 +01:00
4c778a63a7 README: add some material on what CNI isn't
We get some questions about this stuff from time to time and I want to
acknowledge we have thought about them but aren't currently tackling
them.
2016-04-10 18:23:06 -07:00
d5a8ec9029 README: add some more details on what CNI is
We needed a bit more intro material to scope what CNI does. Here is my
attempt.
2016-04-10 18:22:38 -07:00
41ee449fb2 Merge pull request #177 from steveeJ/macvlan-arp-proxy
Macvlan arp proxy
2016-04-08 14:53:48 +02:00
a06a464235 Merge pull request #178 from steveeJ/master
travis: don't go get vet
2016-04-08 14:35:58 +02:00
27d37cbdf1 travis: don't go get vet 2016-04-08 14:29:04 +02:00
bc482febfb travis: don't go get vet 2016-04-08 14:22:20 +02:00
b2f492e8b5 macvlan: set proxy_arp in time of creating interface
Resolves CNI part of https://github.com/coreos/rkt/issues/1765
Second part would be adding similar lines into kvm flavored macvlan
support (in time of creating macvtap device).
2016-04-07 21:40:58 +02:00
72bec92851 pkg/utils: add functions to work with sysctl 2016-04-07 21:40:51 +02:00
a15a372021 Merge pull request #173 from jonboulle/master
*: add missing license headers + check
2016-04-02 15:22:40 +02:00
f6135c7ba3 *: add missing license headers + check 2016-04-01 15:35:21 +02:00
0046767be7 Merge pull request #172 from squaremo/readme_more
Readme improvements
2016-04-01 13:23:28 +01:00
fcbde68d32 docs: add brief section on contributing, to README 2016-04-01 12:51:39 +01:00
8c860a832f docs: cosmetic edits to README.md 2016-04-01 12:37:39 +01:00
42c4cb842d Merge pull request #168 from steveeJ/chain-len
attempt to ensure chain name is unique and at most 29 chars long
2016-03-31 19:25:13 +02:00
897766d74b pkg/utils: correct the test's expected chain names 2016-03-31 18:01:32 +02:00
6aad63055c *: add comment to iptables rules for ipmasq 2016-03-31 18:01:32 +02:00
bcef17daac pkg/utils: remove unneeded condition in tests 2016-03-31 18:01:32 +02:00
77759626a8 pkg/utils: fix docstring 2016-03-31 18:01:32 +02:00
53d9cee00a pkg/utils: split and unexport constants 2016-03-31 18:01:32 +02:00
bc44d1227d pkg/utils: fix docstring 2016-03-31 18:01:32 +02:00
3e6069cab5 pkg/utils: use constant for chain prefix 2016-03-31 18:01:32 +02:00
09248dfad9 pkg/utils: use name+id for hash and extend tests 2016-03-31 18:01:32 +02:00
c33daf6706 pkg: add a function to generate chain names
Adds a function to generate chain names for use in iptables and
ports all drivers to use that function. Also adds tests for the
said function.
2016-03-31 18:01:32 +02:00
bacaa11d2d Merge pull request #171 from steveeJ/bump-cni
vendoring: bump coreos/go-iptables to 0.1.0
2016-03-31 08:46:55 -07:00
88d974c562 vendoring: bump coreos/go-iptables to 0.1.0 2016-03-31 17:33:50 +02:00
5362e90c8a Merge pull request #170 from jonboulle/master
README: add Calico and Weave as CNI users
2016-03-31 14:51:30 +01:00
77a5bf44f4 README: add Calico and Weave as CNI users 2016-03-31 15:44:03 +02:00
1e0e105b36 Merge pull request #169 from philips/add-users
README: add a list of CNI users
2016-03-31 10:21:13 +02:00
0b4f7d849f README: add a list of CNI users 2016-03-30 15:59:16 -07:00
4146443942 Merge pull request #165 from dcbw/go15-vendor
scripts: fix build with go-1.5 after switch to vendor/
2016-03-24 10:44:00 -07:00
ae2f64ec40 scripts: fix build with go-1.5 after switch to vendor/
go-1.6 enables vendor by default, but go-1.5 needs an environment variable.
2016-03-24 11:33:19 -05:00
5c79f8bd5d Merge pull request #158 from steveeJ/loadargs
Add generic IgnoreUnknown to valid CNI_ARGS
2016-03-22 22:05:57 -07:00
8916a7ea5f pkg/types: add tests for args 2016-03-21 20:40:39 +01:00
b91aec9a62 Godeps: bump ginkgo for table extensions 2016-03-21 20:36:05 +01:00
5a39a168f7 pkg/types: add IgnoreUnknown arg and logic
This commit adds a struct type CommonArgs that is to be embedded in
every plugin's argument struct. It contains a field named
"IgnoreUnknown" which will be parsed as a boolean and can be provided to
ignore unknown arguments passed to the plugin.
2016-03-21 20:36:05 +01:00
05c5aea77b plugins/host-local: only call LoadArgs() once 2016-03-21 20:17:47 +01:00
122abae03a Merge pull request #162 from zachgersh/remove-workspace
build script: remove the _workspace from GOPATH
2016-03-21 17:48:25 +01:00
8817b1b946 build script: remove the _workspace from GOPATH
Now that we no longer use godeps to manage
dependencies we can safely remove this.
Dependencies in the vendor directory will
automagically be picked up.
2016-03-21 09:32:09 -07:00
6ef5ef1ec1 Merge pull request #161 from steveeJ/skel-tests
pkg/skel: add rudimentary unit tests
2016-03-19 18:09:07 -07:00
a6c5d80661 pkg/skel: add rudimentary unit tests
This is an attempt to testing the PluginMain() function of the skel pkg.
We should be able to do better by using a mockable interface for the
plugins, but this is a start.
2016-03-18 22:34:29 +01:00
e72674949e Merge pull request #156 from zachgersh/vendor
Moves to go team vendoring solution
2016-03-17 10:02:30 +01:00
a3038a5bec Merge pull request #157 from achanda/vet
Fix govet warnings
2016-03-16 17:01:57 -07:00
72eddd1cf1 Let go tip fail, add vendor flag for 1.5 2016-03-16 17:00:51 -07:00
9b2f3380c1 Fix govet warnings 2016-03-16 16:25:41 -07:00
48ff0e472a Moves to official vendoring solution 2016-03-16 08:38:20 -07:00
d19044896e Merge pull request #154 from rosenhouse/withnetns-errors
WithNetNS restores original namespace when callback errors
2016-03-15 08:39:01 -07:00
2251ee1d0c Update docstring on WithNetNS 2016-03-15 08:37:00 -07:00
9356e23554 WithNetNS restores original namespace when callback errors
- adds test coverage of WithNetNS in BDD-style
2016-03-15 01:51:58 -07:00
2b6448f487 Merge pull request #146 from achanda/trusty
Use Ubuntu Trusty in travis
2016-03-14 17:42:03 -07:00
78337dcc42 Merge pull request #153 from steveeJ/maintainer-add-zach
MAINTAINERS: welcome Zach!
2016-03-14 15:52:21 -07:00
2511a57cb4 MAINTAINERS: welcome Zach!
We are pleased to welcome Zach on board as CNI maintainer.
Happy collaboration!
2016-03-14 22:56:25 +01:00
d497d6069a Merge pull request #148 from steveeJ/coverage-batches
travis & README: add coveralls coverage report
2016-03-09 17:30:41 +01:00
c1ee5d00df travis & README: add coveralls coverage report
Also, don't use sudo for the entire test script
2016-03-05 19:07:31 +01:00
cde7088cbe Merge pull request #144 from squaremo/rename-delegate-execs
Add invoke.Delegate{Add,Del} for use by meta-plugins
2016-03-04 13:20:35 +01:00
719a1db54b Add invoke.Delegate{Add,Del} for use by meta-plugins
The 'flannel' meta plugin delegates to other plugins to do the actual
OS-level work. It used the ipam.Exec{Add,Del} procedures for this
delegation, since those do precisely what's needed.

However this is a bit misleading, since the flannel plugin _isn't_
doing this for IPAM, and the ipam.Exec* procedures aren't doing
something specific to IPAM plugins.

So: anticipating that there may be more meta plugins that want to
delegate in the same way, this commit moves generic delegation
procedures to `pkg/invoke`, and makes the `pkg/ipam` procedures (still
used, accurately, in the non-meta plugins) shims.
2016-03-04 11:01:22 +00:00
36c6bcd106 Merge pull request #142 from steveeJ/fix-loopback-result
Fix loopback result
2016-03-03 09:03:51 +01:00
230a555359 Use Ubuntu Trusty in travis
This boots faster
2016-03-02 20:00:11 -08:00
2b278529e5 Merge pull request #143 from zachgersh/more-tests
More tests
2016-03-02 19:01:13 +01:00
4a5426b77a tests: loopback DEL 2016-03-02 17:56:44 +01:00
f48bd43d8c Adds travis badge, now we have more tests 2016-03-02 11:43:27 -05:00
f3f999c20a Make sure invoke tests are running 2016-03-02 11:38:33 -05:00
80ab40470c tests: loopback stdout must be JSON 2016-03-02 15:27:05 +01:00
52be8aa615 plugins/loopback: take lo down on CmdDel 2016-03-02 15:27:05 +01:00
e282f6939d plugins/loopback: return empty result
This is needed to conform to the specification and allow successful
unmarshalling in the invoker.
2016-03-02 15:27:00 +01:00
c44bc010ab Merge pull request #120 from zachgersh/find-better-error
Better error messages when plugin is not found
2016-03-02 11:14:50 +01:00
68259e3388 Merge pull request #121 from zachgersh/loopback-plugin
Loopback plugin
2016-03-02 09:32:01 +01:00
1e3d680d13 Handle namespaces with care
- After creating new netns, switch back to main netns
- Lock thread during test and test setup
2016-02-29 12:29:06 -05:00
2708bdf2f5 Create a plugin for up'ing a lo device
- Believe we need sudo to create netns
- Use syscall instead of relying on ip netns
- Add sudo to .travis.yml
- Needs more -E
- Revert Godeps GoVersion to 1.4.2
- in travis, test command is run with all necessary env vars
- Loopback plugin only works on 'lo' interface
- Update README, add loopback plugin config
- note script dependency on jq

Signed-off-by: Gabe Rosenhouse <grosenhouse@pivotal.io>
2016-02-29 12:29:06 -05:00
ebd5be8475 Adds ginkgo / gomega as a dependency 2016-02-29 12:27:11 -05:00
67f6672414 Merge pull request #135 from achanda/travis
Tweak the travis file
2016-02-25 23:00:00 +01:00
c5f7cc8501 Tweak the travis file
- Build against more versions of Go
- Explicitely specify go versions
2016-02-24 22:32:08 -08:00
b7ff8ab158 Merge pull request #132 from steveeJ/scripts
scripts: add DEBUG option
2016-02-24 18:28:47 +01:00
1461909bcd Merge pull request #117 from kinvolk/alban/net-tuning
new plugin: tuning
2016-02-24 18:12:18 +01:00
06ea8c1e1f scripts: add DEBUG option 2016-02-23 19:22:48 +01:00
224ac412da Merge pull request #107 from aanm/pretty-result
added the String method to Result type
2016-02-19 18:46:55 +01:00
7b53bb9455 added the String method to Result type
Signed-off-by: André Martins <aanm90@gmail.com>
2016-02-19 17:40:46 +00:00
f49145d5ff new plugin: tuning
Allow users to tune net network parameters such as somaxconn.

With this patch, users can add a new network configuration:

> {
>   "name": "mytuning",
>   "type": "tuning",
>   "sysctl": {
>           "net.core.somaxconn": "500"
>   }
> }

The value /proc/sys/net/core/somaxconn will be set to 500 in the network
namespace but will remain unchanged on the host.

Only sysctl parameters that belong to the network subsystem can be
modified.

Related to: https://github.com/coreos/rkt/pull/2140
2016-02-18 15:29:12 +01:00
48849bd3e3 Merge pull request #108 from aanm/fix-ip-json-tag
fixed ipam host-local IP json tag
2016-02-18 14:12:20 +01:00
290717d6fe Better error message when plugin cannot be found 2016-02-10 13:42:10 -08:00
2d9695e976 Merge pull request #119 from jonboulle/master
MAINTAINERS: remove Eugene from list
2016-02-10 15:54:58 +01:00
2ac72cbb12 MAINTAINERS: remove Eugene from list
Eugene is no longer with CoreOS or actively involved with CNI, so remove
him from the current list of maintainers. He'll be gladly welcomed back
if he decides to rejoin the project.
2016-02-10 15:51:11 +01:00
33b2de44af fixed ipam host-local IP json tag
Signed-off-by: André Martins <aanm90@gmail.com>
2016-01-31 03:14:53 +00:00
f04661aca1 Merge pull request #105 from steveeJ/scripts
script/priv-net-run: improve shebang compatibility
2016-01-29 11:20:55 +01:00
d5c56b8d42 script/priv-net-run: improve shebang compatibility 2016-01-29 11:17:55 +01:00
b589f29108 Merge pull request #103 from steveeJ/dns
*: DNS information as dictionary, adding domain, search domains and options
2016-01-29 11:16:50 +01:00
137dc8a673 *: reflect SPEC's DNS changes in implementation
* DNS is now a type which will result in a JSON dictionary in
  configurations and results
* Minor refactoring, making use of type embedding
2016-01-29 10:39:28 +01:00
abb6ee1dd1 docs/ptp: update example and DNS description 2016-01-29 10:39:28 +01:00
092e8f5c4d SPEC: DNS information as dictionary, adding domain, search domains, options 2016-01-29 10:39:22 +01:00
09214926ea Merge pull request #104 from dcbw/revendor-go-iptables
Revendor go-iptables to get --wait behavior
2016-01-27 21:18:44 +01:00
6017d5c8b9 Revendor go-iptables to get --wait behavior 2016-01-27 13:56:53 -06:00
a4f8407150 Merge pull request #102 from steveeJ/scripts
scripts/exec-plugins: print plugin results if DEBUG>0
2016-01-27 11:14:57 +01:00
67e6f68343 scripts/priv-net-run: print plugin results if DEBUG>0 2016-01-27 10:58:01 +01:00
59f8bb361a Merge pull request #101 from steveeJ/shebangs
scripts: improve shebang compatibility
2016-01-27 10:51:32 +01:00
28d18d3e73 scripts: improve shebang compatibility 2016-01-27 10:31:16 +01:00
1da421150c Merge pull request #99 from kinvolk/alban/dns-config
*: add "dns" field to the configuration
2016-01-27 08:49:16 +01:00
2f9ef4adb7 *: add "dns" field to the configuration
appc/cni#76 added a "dns" field in the result JSON. But before this
patch, the plugins had no way of knowing which name server to return.

There could be two ways of knowing which name server to return:
1. add it as an extra argument ("CNI_ARGS")
2. add it in the network configuration as a convenience (received via
   stdin)

I chose the second way because it is easier. In the case of rkt, it
means the user could just add the DNS name servers in
/etc/rkt/net.d/mynetwork.conf.
2016-01-26 18:54:56 +01:00
03d4ba4ffb Merge pull request #98 from apcera/remove-addif
spec: Removed reference to unsupported addIf attribute
2016-01-22 20:33:22 +01:00
65060a0e14 spec: Removed reference to unsupported addIf attribute
Removes the "addIf" attribute from the example of a bridge network
definition. This doesn't appear to exist in the implementation.
2016-01-22 10:45:05 -08:00
6fc3874d57 Merge pull request #92 from ChengTiesheng/patch-1
Update README.md
2016-01-06 18:08:25 +01:00
54286af90f Update README.md
Highlight bash/shell code in markdown for readability.

Signed-off-by: chengtiesheng <chengtiesheng@huawei.com>
2016-01-06 16:25:02 +08:00
4fcf18cb88 Merge pull request #91 from tomdee/patch-1
Fix docker example in README.md
2016-01-05 09:05:09 +01:00
0a289316d6 Update README.md
No need for full path to ifconfig (and the given path doesn't work...)
2016-01-04 17:06:30 -08:00
80f87ceb14 Merge pull request #90 from dgonyeo/master
pkg/ip: fix typo in error message, s/iptabes/iptables/
2015-12-16 22:46:05 +01:00
fd64ee6ade pkg/ip: fix typo in error message, s/iptabes/iptables/ 2015-12-16 13:20:19 -08:00
11e121cdd5 Merge pull request #80 from eyakubovich/add-version
spec: add cniVersion to results and config
2015-12-09 13:59:47 -08:00
420a145719 spec: add cniVersion to results and config
Version all artifacts using semantic versioning
so that plugins and container runtimes coded against
different versions of the spec can interoperate.

Fixes #44
2015-12-02 13:06:20 -08:00
f777ca50e5 Merge pull request #78 from steveeJ/improve-errormsg-missing-subnet
host-local: detect missing subnet and error out
2015-11-30 20:56:25 +01:00
753b10503c host-local: detect missing subnet and error out 2015-11-25 21:18:48 +01:00
19c18abdb1 Merge pull request #82 from steveeJ/dhcp-linkfix
dhcp: detect if link is down and attempt to set up
2015-11-20 12:18:18 -08:00
6f23757868 dhcp: detect if link is down and attempt to set up
With this we still get the "network is down" error, but after the 2nd
retry the interface is up and the dhcp request works.
2015-11-19 11:11:32 +01:00
c3388070c3 Merge pull request #76 from eyakubovich/dns
spec: add "dns" field to the result JSON
2015-11-10 16:59:31 -08:00
8aeb066a58 spec: add "dns" field to the result JSON
This adds an ability for networks to communicate
about the DNS nameservers they know about to the
container runtime.

Fixes #67
2015-11-10 16:58:01 -08:00
442852a861 Merge pull request #73 from eyakubovich/flannel-fix
flannel: doc fix and check for missing subnet.env fields
2015-10-07 18:03:54 -07:00
20f1b8694f flannel: doc fix and check for missing subnet.env fields
- Document that flannel outputs FLANNEL_NETWORK b/c we use it
- Check and error out if expecited fields are missing in subnetEnv file

Fixes #72
2015-10-07 15:38:12 -07:00
e727d10746 Merge pull request #71 from jonboulle/master
README/CONTRIBUTING: mention cni-dev@ list
2015-10-05 12:10:56 +01:00
d3ca177ee4 README/CONTRIBUTING: mention cni-dev@ list 2015-10-01 12:43:43 -07:00
f885288a2d Merge pull request #69 from eyakubovich/err-msgs
Route del would fail due to wrong scope; better errors
2015-09-30 11:56:56 -07:00
b2b2597506 Merge pull request #70 from eyakubovich/copyright
Change copyright from CoreOS to CNI authors
2015-09-30 11:03:46 -07:00
0becca2e96 Change copyright from CoreOS to CNI authors
CNI is developed by more than just CoreOS, Inc
and the copyright is retained by all CNI
contributors (for their respective contributed code).
2015-09-29 11:51:33 -07:00
5efd3ba883 Route del would fail due to wrong scope; better errors
In some cases the route deletion would fail due to wrong
scope. It should be NOWHERE when deleting (per iproute2).
This also adds more verbose error messages.
2015-09-29 11:27:49 -07:00
f0266a2717 Merge pull request #65 from steveeJ/fix-veth-setup
Fix veth setup

Fixes #61 #64
2015-09-24 21:53:54 +02:00
5b7aa09e52 link: switch to host netns to set up host veth end 2015-09-24 18:49:27 +02:00
f1c9c632e1 Revert "plugins/ptp: allow host veth to be UP"
This reverts commit 231d2d5a27.
2015-09-24 18:32:18 +02:00
39ea97f99d Merge pull request #63 from steveeJ/no-host-local-ptp
Merge host-local and host-local-ptp
2015-09-24 13:10:47 +02:00
231d2d5a27 plugins/ptp: allow host veth to be UP 2015-09-24 10:57:36 +02:00
6737bc8207 update ptp docs to reflect changes in plugin 2015-09-24 09:43:55 +02:00
60be55a7d1 remove host-local-ptp plugin 2015-09-23 11:04:38 +02:00
7d8d6b2a7e Use single IP on the host for ptp veths
Instead of allocating a /31 for each container,
use the same IP on the host side for all veths.
This is very similar how real point-to-point
devices work (using donor IPs).
2015-09-23 11:04:38 +02:00
94be1cfaab revendoring netlink 2015-09-23 11:04:38 +02:00
2a58bd9379 Merge pull request #60 from eyakubovich/fix-plugin-del
bug fix: exec of DEL cmd caused JSON decode error
2015-09-22 16:39:59 +01:00
9ea56937d4 bug fix: exec of DEL cmd caused JSON decode error
When plugin is executed with a DEL command, it does not
print result to stdout unless there is an error. Therefore
it stdout bytes should not be passed to json.Unmarshal.
2015-09-18 10:30:10 -07:00
cc918a1aea Merge pull request #59 from squaremo/factor-out-libcni
Factor an API out into a module
2015-09-17 00:06:54 +01:00
b88f173c43 Factor an API out into a module
This takes some of the machinery from CNI and from the rkt networking
code, and turns it into a library that can be linked into go apps.

Included is an example command-line application that uses the library,
called `cnitool`.

Other headline changes:

 * Plugin exec'ing is factored out

The motivation here is to factor out the protocol for invoking
plugins. To that end, a generalisation of the code from api.go and
pkg/plugin/ipam.go goes into pkg/invoke/exec.go.

 * Move argument-handling and conf-loading into public API

The fact that the arguments get turned into an environment for the
plugin is incidental to the API; so, provide a way of supplying them
as a struct or saying "just use the same arguments as I got" (the
latter is for IPAM plugins).
2015-09-16 10:14:39 +01:00
5da5738456 Merge pull request #58 from steveeJ/remove-ipmasq-ifneedbe
ipvlan/macvlan: remove ipMasq related code
2015-09-10 22:08:57 +02:00
d896b82816 ipvlan/macvlan: remove ipMasq related code
Luckily the docs haven't mentioned support for ipMasq for both plugins so far.
Even if anyone has attempted to enable the feature in their configuration files it didn't have the desired effect for the network.
2015-09-09 14:16:39 +02:00
75657b0aac Merge pull request #57 from eyakubovich/maintainers
Add MAINTAINERS file
2015-09-09 12:05:35 +02:00
c4808e616d Add MAINTAINERS file 2015-09-08 15:58:00 -07:00
06967ea734 Merge pull request #53 from NeilW/master
IPAM plugin: improve error messages
2015-09-08 14:26:11 -07:00
2d0d4b35e1 plugin/ipam: correct formatting of error message 2015-09-08 18:08:15 +00:00
8462a3f607 IPAM plugin: improve error messages
Make it more clear that we failed to find an IPAM plugin.
Check for a missing plugin name and issue a more helpful error.
2015-09-08 18:08:15 +00:00
fb9b8ad1bc Merge pull request #55 from jonboulle/travis
*: add basic test script + travis hook
2015-09-07 16:28:35 -07:00
d10d1a148e *: add basic test script + travis hook
Adds a simple test script, mostly to perform gofmt and govet checking;
currently tests only exist for the DHCP plugin.
2015-09-07 16:21:53 -07:00
69d50f545d Merge pull request #54 from jonboulle/master
plugin/ipam: fix typo in error message
2015-09-08 00:49:28 +02:00
7478744cf5 plugin/ipam: fix typo in error message 2015-09-07 15:43:34 -07:00
ef820646c5 Merge pull request #51 from steveeJ/plugins-args
CNI_ARGS: use ';' to split args as documented
2015-09-05 19:00:53 +02:00
8b634b90da CNI_ARGS: use ';' to split args as documented 2015-09-05 18:58:58 +02:00
fbd828cf60 Merge pull request #42 from steveeJ/plugins-args
host-local: allow ip request via CNI_ARGS
2015-09-04 01:42:11 +02:00
1d398af124 host-local: allow ip request via CNI_ARGS
A specific IP can now be requested via the environment variable CNI_ARGS, e.g.
`CNI_ARGS=ip=1.2.3.4`.
The plugin will try to reserve the specified IP.
If this is not successful the execution will fail.
2015-09-04 01:38:22 +02:00
59f58fb974 Merge pull request #49 from eyakubovich/dco
Add DCO and CONTRIBUTING.md
2015-09-02 11:01:42 -07:00
d1ccecf88f Add DCO and CONTRIBUTING.md 2015-09-02 11:00:27 -07:00
4f6ab3c2ad Merge pull request #43 from alexwlchan/master
Fix a few spelling mistakes in the docs
2015-08-20 09:17:56 -07:00
ac0b5177a4 Fix a few spelling mistakes in the docs 2015-08-20 16:41:25 +01:00
34be862dc3 Merge pull request #41 from eyakubovich/flannel-route
flannel: set up route for the entire flannel network
2015-08-15 16:28:09 -07:00
e38572b967 flannel: set up route for the entire flannel network
Without it, packets leave via default route iface
and come back via interface added by flannel plugin.
If rp_filter=1, the packets are dropped.
2015-08-10 14:13:06 -07:00
4be9a4f771 Merge pull request #37 from steveeJ/fix-docs
host-local: fix routes in README examples
2015-08-03 15:12:07 -07:00
d961f6cd39 host-local: fix routes in README examples 2015-08-03 15:37:14 +02:00
442 changed files with 19627 additions and 3338 deletions

29
.travis.yml Normal file
View File

@ -0,0 +1,29 @@
language: go
sudo: required
dist: trusty
go:
- 1.5.3
- 1.6
- tip
matrix:
allow_failures:
- go: tip
env:
global:
- TOOLS_CMD=golang.org/x/tools/cmd
- PATH=$GOROOT/bin:$PATH
- GO15VENDOREXPERIMENT=1
install:
- go get ${TOOLS_CMD}/cover
- go get github.com/modocache/gover
- go get github.com/mattn/goveralls
script:
- ./test
notifications:
email: false

86
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,86 @@
# How to Contribute
CNI is [Apache 2.0 licensed](LICENSE) and accepts contributions via GitHub
pull requests. This document outlines some of the conventions on development
workflow, commit message formatting, contact points and other resources to make
it easier to get your contribution accepted.
We gratefully welcome improvements to documentation as well as to code.
# Certificate of Origin
By contributing to this project you agree to the Developer Certificate of
Origin (DCO). This document was created by the Linux Kernel community and is a
simple statement that you, as a contributor, have the legal right to make the
contribution. See the [DCO](DCO) file for details.
# Email and Chat
The project uses the the cni-dev email list and IRC chat:
- Email: [cni-dev](https://groups.google.com/forum/#!forum/cni-dev)
- IRC: #[containernetworking](irc://irc.freenode.org:6667/#containernetworking) channel on freenode.org
Please avoid emailing maintainers found in the MAINTAINERS file directly. They
are very busy and read the mailing lists.
## Getting Started
- Fork the repository on GitHub
- Read the [README](README.md) for build and test instructions
- Play with the project, submit bugs, submit pull requests!
## Contribution workflow
This is a rough outline of how to prepare a contribution:
- Create a topic branch from where you want to base your work (usually branched from master).
- Make commits of logical units.
- Make sure your commit messages are in the proper format (see below).
- Push your changes to a topic branch in your fork of the repository.
- If you changed code, make sure the tests pass, and add any new tests as appropriate.
- Make sure any new code files have a license header.
- Submit a pull request to the original repository.
# Acceptance policy
These things will make a PR more likely to be accepted:
* a well-described requirement
* tests for new code
* tests for old code!
* new code follows the conventions in old code
* a good commit message (see below)
In general, we will merge a PR once two maintainers have endorsed it.
Trivial changes (e.g., corrections to spelling) may get waved through.
For substantial changes, more people may become involved, and you might get asked to resubmit the PR or divide the changes into more than one PR.
### Format of the Commit Message
We follow a rough convention for commit messages that is designed to answer two
questions: what changed and why. The subject line should feature the what and
the body of the commit should describe the why.
```
scripts: add the test-cluster command
this uses tmux to setup a test cluster that you can easily kill and
start for debugging.
Fixes #38
```
The format can be described more formally as follows:
```
<subsystem>: <what changed>
<BLANK LINE>
<why this change was made>
<BLANK LINE>
<footer>
```
The first line is the subject and should be no longer than 70 characters, the
second line is always blank, and other lines should be wrapped at 80 characters.
This allows the message to be easier to read on GitHub as well as in various
git tools.

36
DCO Normal file
View File

@ -0,0 +1,36 @@
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.

View File

@ -17,8 +17,9 @@ If the bridge is missing, the plugin will create one on first use and, if gatewa
"name": "mynet",
"type": "bridge",
"bridge": "mynet0",
"isGateway": true,
"isDefaultGateway": true,
"ipMasq": true,
"hairpinMode": true,
"ipam": {
"type": "host-local",
"subnet": "10.10.0.0/16"
@ -32,6 +33,8 @@ If the bridge is missing, the plugin will create one on first use and, if gatewa
* `type` (string, required): "bridge".
* `bridge` (string, optional): name of the bridge to use/create. Defaults to "cni0".
* `isGateway` (boolean, optional): assign an IP address to the bridge. Defaults to false.
* `isDefaultGateway` (boolean, optional): Sets isGateway to true and makes the assigned IP the default route. Defaults to false.
* `ipMasq` (boolean, optional): set up IP Masquerade on the host for traffic originating from this network and destined outside of it. Defaults to false.
* `mtu` (integer, optional): explicitly set MTU to the specified value. Defaults to the value chosen by the kernel.
* `hairpinMode` (boolean, optional): set hairpin mode for interfaces on the bridge. Defaults to false.
* `ipam` (dictionary, required): IPAM configuration to be used for this network.

View File

@ -3,7 +3,7 @@
## Overview
With dhcp plugin the containers can get an IP allocated by a DHCP server already running on your network.
This can be especially useful with plugin types such as [macvlan](https://github.com/appc/cni/blob/master/Documentation/macvlan.md).
This can be especially useful with plugin types such as [macvlan](https://github.com/containernetworking/cni/blob/master/Documentation/macvlan.md).
Because a DHCP lease must be periodically renewed for the duration of container lifetime, a separate daemon is required to be running.
The same plugin binary can also be run in the daemon mode.

View File

@ -4,7 +4,8 @@
This plugin is designed to work in conjunction with [flannel](https://github.com/coreos/flannel), a network fabric for containers.
When flannel daemon is started, it outputs a `/run/flannel/subnet.env` file that looks like this:
```
FLANNEL_SUBNET=10.1.17.0/24
FLANNEL_NETWORK=10.1.0.0/16
FLANNEL_SUBNET=10.1.17.1/24
FLANNEL_MTU=1472
FLANNEL_IPMASQ=true
```
@ -54,7 +55,7 @@ This supplies a configuration parameter to the bridge plugin -- the created brid
Notice that `mtu` has also been specified and this value will not be overwritten by flannel plugin.
Additionally, the `delegate` field can be used to select a different kind of plugin altogether.
To use `ipvlan` instead of `bridge`, the following configuratoin can be specified:
To use `ipvlan` instead of `bridge`, the following configuration can be specified:
```
{

View File

@ -31,6 +31,11 @@ It stores the state locally on the host filesystem, therefore ensuring uniquenes
* `gateway` (string, optional): IP inside of "subnet" to designate as the gateway. Defaults to ".1" IP inside of the "subnet" block.
* `routes` (string, optional): list of routes to add to the container namespace. Each route is a dictionary with "dst" and optional "gw" fields. If "gw" is omitted, value of "gateway" will be used.
## Supported arguments
The following [CNI_ARGS](https://github.com/containernetworking/cni/blob/master/SPEC.md#parameters) are supported:
* `ip`: request a specific IP address from the subnet. If it's not available, the plugin will exit with an error
## Files
Allocated IP addresses are stored as files in /var/lib/cni/networks/$NETWORK_NAME.

View File

@ -4,7 +4,7 @@
[macvlan](http://backreference.org/2014/03/20/some-notes-on-macvlanmacvtap/) functions like a switch that is already connected to the host interface.
A host interface gets "enslaved" with the virtual interfaces sharing the physical device but having distinct MAC addresses.
Since each macvlan interface has its own MAC address, it makes it easy to use with exising DHCP servers already present on the network.
Since each macvlan interface has its own MAC address, it makes it easy to use with existing DHCP servers already present on the network.
## Example configuration

View File

@ -3,10 +3,8 @@
## Overview
The ptp plugin creates a point-to-point link between a container and the host by using a veth device.
One end of the veth pair is placed inside a container and the other end resides on the host.
Both ends receive an IP address out of a /31 range.
The IP of the host end becomes the gateway address inside the container.
Because ptp plugin requires a pair of IP addresses for each container, it should be used in conjuction with host-local-ptp IPAM plugin.
The host-local IPAM plugin can be used to allocate an IP address to the container.
The traffic of the container interface will be routed through the interface of the host.
## Example network configuration
```
@ -14,8 +12,11 @@ Because ptp plugin requires a pair of IP addresses for each container, it should
"name": "mynet",
"type": "ptp",
"ipam": {
"type": "host-local-ptp",
"type": "host-local",
"subnet": "10.1.1.0/24"
},
"dns": {
"nameservers": [ "10.1.1.1", "8.8.8.8" ]
}
}
@ -26,3 +27,4 @@ Because ptp plugin requires a pair of IP addresses for each container, it should
* `ipMasq` (boolean, optional): set up IP Masquerade on the host for traffic originating from this network and destined outside of it. Defaults to false.
* `mtu` (integer, optional): explicitly set MTU to the specified value. Defaults to value chosen by the kernel.
* `ipam` (dictionary, required): IPAM configuration to be used for this network.
* `dns` (dictionary, optional): DNS information to return as described in the [Result](/SPEC.md#result).

36
Documentation/tuning.md Normal file
View File

@ -0,0 +1,36 @@
# tuning plugin
## Overview
This plugin can change some system controls (sysctls) in the network namespace.
It does not create any network interfaces and therefore does not bring connectivity by itself.
It is only useful when used in addition to other plugins.
## Operation
The following network configuration file
```
{
"name": "mytuning",
"type": "tuning",
"sysctl": {
"net.core.somaxconn": "500"
}
}
```
will set /proc/sys/net/core/somaxconn to 500.
Other sysctls can be modified as long as they belong to the network namespace (`/proc/sys/net/*`).
A successful result would simply be:
```
{
"cniVersion": "0.1.0"
}
```
## Network sysctls documentation
Some network sysctls are documented in the Linux sources:
- [Documentation/sysctl/net.txt](https://www.kernel.org/doc/Documentation/sysctl/net.txt)
- [Documentation/networking/ip-sysctl.txt](https://www.kernel.org/doc/Documentation/networking/ip-sysctl.txt)
- [Documentation/networking/](https://www.kernel.org/doc/Documentation/networking/)

158
Godeps/Godeps.json generated
View File

@ -1,13 +1,14 @@
{
"ImportPath": "github.com/appc/cni",
"GoVersion": "go1.4.2",
"ImportPath": "github.com/containernetworking/cni",
"GoVersion": "go1.6",
"Packages": [
"./..."
],
"Deps": [
{
"ImportPath": "github.com/coreos/go-iptables/iptables",
"Rev": "83dfad0f13fd7310fb3c1cb8563248d8d604b95b"
"Comment": "v0.1.0",
"Rev": "fbb73372b87f6e89951c2b6b31470c2c9d5cfae3"
},
{
"ImportPath": "github.com/coreos/go-systemd/activation",
@ -22,9 +23,158 @@
"ImportPath": "github.com/d2g/dhcp4client",
"Rev": "bed07e1bc5b85f69c6f0fd73393aa35ec68ed892"
},
{
"ImportPath": "github.com/onsi/ginkgo",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/config",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/internal/codelocation",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/internal/containernode",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/internal/failer",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/internal/leafnodes",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/internal/remote",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/internal/spec",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/internal/specrunner",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/internal/suite",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/internal/testingtproxy",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/internal/writer",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/reporters",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/reporters/stenographer",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/ginkgo/types",
"Comment": "v1.2.0-29-g7f8ab55",
"Rev": "7f8ab55aaf3b86885aa55b762e803744d1674700"
},
{
"ImportPath": "github.com/onsi/gomega",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/format",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/gbytes",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/gexec",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/internal/assertion",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/internal/asyncassertion",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/internal/oraclematcher",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/internal/testingtsupport",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/matchers",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/matchers/support/goraph/bipartitegraph",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/matchers/support/goraph/edge",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/matchers/support/goraph/node",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/matchers/support/goraph/util",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/onsi/gomega/types",
"Comment": "v1.0-71-g2152b45",
"Rev": "2152b45fa28a361beba9aab0885972323a444e28"
},
{
"ImportPath": "github.com/vishvananda/netlink",
"Rev": "ae3e7dba57271b4e976c4f91637861ee477135e2"
"Rev": "ecf47fd5739b3d2c3daf7c89c4b9715a2605c21b"
},
{
"ImportPath": "github.com/vishvananda/netlink/nl",
"Rev": "ecf47fd5739b3d2c3daf7c89c4b9715a2605c21b"
},
{
"ImportPath": "golang.org/x/sys/unix",

2
Godeps/_workspace/.gitignore generated vendored
View File

@ -1,2 +0,0 @@
/pkg
/bin

View File

@ -1,136 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// 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 iptables
import (
"crypto/rand"
"math/big"
"reflect"
"testing"
)
func randChain(t *testing.T) string {
n, err := rand.Int(rand.Reader, big.NewInt(1000000))
if err != nil {
t.Fatalf("Failed to generate random chain name: %v", err)
}
return "TEST-" + n.String()
}
func TestChain(t *testing.T) {
chain := randChain(t)
ipt, err := New()
if err != nil {
t.Fatalf("New failed: %v", err)
}
// chain shouldn't exist, this will create new
err = ipt.ClearChain("filter", chain)
if err != nil {
t.Fatalf("ClearChain (of missing) failed: %v", err)
}
// chain now exists
err = ipt.ClearChain("filter", chain)
if err != nil {
t.Fatalf("ClearChain (of empty) failed: %v", err)
}
// put a simple rule in
err = ipt.Append("filter", chain, "-s", "0.0.0.0/0", "-j", "ACCEPT")
if err != nil {
t.Fatalf("Append failed: %v", err)
}
// can't delete non-empty chain
err = ipt.DeleteChain("filter", chain)
if err == nil {
t.Fatalf("DeleteChain of non-empty chain did not fail")
}
err = ipt.ClearChain("filter", chain)
if err != nil {
t.Fatalf("ClearChain (of non-empty) failed: %v", err)
}
// chain empty, should be ok
err = ipt.DeleteChain("filter", chain)
if err != nil {
t.Fatalf("DeleteChain of empty chain failed: %v", err)
}
}
func TestRules(t *testing.T) {
chain := randChain(t)
ipt, err := New()
if err != nil {
t.Fatalf("New failed: %v", err)
}
// chain shouldn't exist, this will create new
err = ipt.ClearChain("filter", chain)
if err != nil {
t.Fatalf("ClearChain (of missing) failed: %v", err)
}
err = ipt.Append("filter", chain, "-s", "10.1.0.0/16", "-d", "8.8.8.8/32", "-j", "ACCEPT")
if err != nil {
t.Fatalf("Append failed: %v", err)
}
err = ipt.AppendUnique("filter", chain, "-s", "10.1.0.0/16", "-d", "8.8.8.8/32", "-j", "ACCEPT")
if err != nil {
t.Fatalf("AppendUnique failed: %v", err)
}
err = ipt.Append("filter", chain, "-s", "10.2.0.0/16", "-d", "8.8.8.8/32", "-j", "ACCEPT")
if err != nil {
t.Fatalf("Append failed: %v", err)
}
err = ipt.Insert("filter", chain, 2, "-s", "10.2.0.0/16", "-d", "9.9.9.9/32", "-j", "ACCEPT")
if err != nil {
t.Fatalf("Insert failed: %v", err)
}
err = ipt.Insert("filter", chain, 1, "-s", "10.1.0.0/16", "-d", "9.9.9.9/32", "-j", "ACCEPT")
if err != nil {
t.Fatalf("Insert failed: %v", err)
}
err = ipt.Delete("filter", chain, "-s", "10.1.0.0/16", "-d", "9.9.9.9/32", "-j", "ACCEPT")
if err != nil {
t.Fatalf("Insert failed: %v", err)
}
rules, err := ipt.List("filter", chain)
if err != nil {
t.Fatalf("List failed: %v", err)
}
expected := []string{
"-N " + chain,
"-A " + chain + " -s 10.1.0.0/16 -d 8.8.8.8/32 -j ACCEPT",
"-A " + chain + " -s 10.2.0.0/16 -d 9.9.9.9/32 -j ACCEPT",
"-A " + chain + " -s 10.2.0.0/16 -d 8.8.8.8/32 -j ACCEPT",
}
if !reflect.DeepEqual(rules, expected) {
t.Fatalf("List mismatch: \ngot %#v \nneed %#v", rules, expected)
}
}

View File

@ -1,82 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// 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 activation
import (
"bytes"
"io"
"os"
"os/exec"
"testing"
)
// correctStringWritten fails the text if the correct string wasn't written
// to the other side of the pipe.
func correctStringWritten(t *testing.T, r *os.File, expected string) bool {
bytes := make([]byte, len(expected))
io.ReadAtLeast(r, bytes, len(expected))
if string(bytes) != expected {
t.Fatalf("Unexpected string %s", string(bytes))
}
return true
}
// TestActivation forks out a copy of activation.go example and reads back two
// strings from the pipes that are passed in.
func TestActivation(t *testing.T) {
cmd := exec.Command("go", "run", "../examples/activation/activation.go")
r1, w1, _ := os.Pipe()
r2, w2, _ := os.Pipe()
cmd.ExtraFiles = []*os.File{
w1,
w2,
}
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "LISTEN_FDS=2", "FIX_LISTEN_PID=1")
err := cmd.Run()
if err != nil {
t.Fatalf(err.Error())
}
correctStringWritten(t, r1, "Hello world")
correctStringWritten(t, r2, "Goodbye world")
}
func TestActivationNoFix(t *testing.T) {
cmd := exec.Command("go", "run", "../examples/activation/activation.go")
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "LISTEN_FDS=2")
out, _ := cmd.CombinedOutput()
if bytes.Contains(out, []byte("No files")) == false {
t.Fatalf("Child didn't error out as expected")
}
}
func TestActivationNoFiles(t *testing.T) {
cmd := exec.Command("go", "run", "../examples/activation/activation.go")
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "LISTEN_FDS=0", "FIX_LISTEN_PID=1")
out, _ := cmd.CombinedOutput()
if bytes.Contains(out, []byte("No files")) == false {
t.Fatalf("Child didn't error out as expected")
}
}

View File

@ -1,86 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// 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 activation
import (
"io"
"net"
"os"
"os/exec"
"testing"
)
// correctStringWritten fails the text if the correct string wasn't written
// to the other side of the pipe.
func correctStringWrittenNet(t *testing.T, r net.Conn, expected string) bool {
bytes := make([]byte, len(expected))
io.ReadAtLeast(r, bytes, len(expected))
if string(bytes) != expected {
t.Fatalf("Unexpected string %s", string(bytes))
}
return true
}
// TestActivation forks out a copy of activation.go example and reads back two
// strings from the pipes that are passed in.
func TestListeners(t *testing.T) {
cmd := exec.Command("go", "run", "../examples/activation/listen.go")
l1, err := net.Listen("tcp", ":9999")
if err != nil {
t.Fatalf(err.Error())
}
l2, err := net.Listen("tcp", ":1234")
if err != nil {
t.Fatalf(err.Error())
}
t1 := l1.(*net.TCPListener)
t2 := l2.(*net.TCPListener)
f1, _ := t1.File()
f2, _ := t2.File()
cmd.ExtraFiles = []*os.File{
f1,
f2,
}
r1, err := net.Dial("tcp", "127.0.0.1:9999")
if err != nil {
t.Fatalf(err.Error())
}
r1.Write([]byte("Hi"))
r2, err := net.Dial("tcp", "127.0.0.1:1234")
if err != nil {
t.Fatalf(err.Error())
}
r2.Write([]byte("Hi"))
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "LISTEN_FDS=2", "FIX_LISTEN_PID=1")
out, err := cmd.Output()
if err != nil {
println(string(out))
t.Fatalf(err.Error())
}
correctStringWrittenNet(t, r1, "Hello world")
correctStringWrittenNet(t, r2, "Goodbye world")
}

View File

@ -1,68 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// 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 activation
import (
"net"
"os"
"os/exec"
"testing"
)
// TestActivation forks out a copy of activation.go example and reads back two
// strings from the pipes that are passed in.
func TestPacketConns(t *testing.T) {
cmd := exec.Command("go", "run", "../examples/activation/udpconn.go")
u1, err := net.ListenUDP("udp", &net.UDPAddr{Port: 9999})
if err != nil {
t.Fatalf(err.Error())
}
u2, err := net.ListenUDP("udp", &net.UDPAddr{Port: 1234})
if err != nil {
t.Fatalf(err.Error())
}
f1, _ := u1.File()
f2, _ := u2.File()
cmd.ExtraFiles = []*os.File{
f1,
f2,
}
r1, err := net.Dial("udp", "127.0.0.1:9999")
if err != nil {
t.Fatalf(err.Error())
}
r1.Write([]byte("Hi"))
r2, err := net.Dial("udp", "127.0.0.1:1234")
if err != nil {
t.Fatalf(err.Error())
}
r2.Write([]byte("Hi"))
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "LISTEN_FDS=2", "FIX_LISTEN_PID=1")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Cmd output '%s', err: '%s'\n", out, err)
}
correctStringWrittenNet(t, r1, "Hello world")
correctStringWrittenNet(t, r2, "Goodbye world")
}

View File

@ -1,69 +0,0 @@
package dhcp4client
import (
"log"
"net"
"testing"
)
/*
* Example Client
*/
func Test_ExampleClient(test *testing.T) {
var err error
m, err := net.ParseMAC("08-00-27-00-A8-E8")
if err != nil {
log.Printf("MAC Error:%v\n", err)
}
//Create a connection to use
//We need to set the connection ports to 1068 and 1067 so we don't need root access
c, err := NewInetSock(SetLocalAddr(net.UDPAddr{IP: net.IPv4(0, 0, 0, 0), Port: 1068}), SetRemoteAddr(net.UDPAddr{IP: net.IPv4bcast, Port: 1067}))
if err != nil {
test.Error("Client Conection Generation:" + err.Error())
}
exampleClient, err := New(HardwareAddr(m), Connection(c))
if err != nil {
test.Fatalf("Error:%v\n", err)
}
success, acknowledgementpacket, err := exampleClient.Request()
test.Logf("Success:%v\n", success)
test.Logf("Packet:%v\n", acknowledgementpacket)
if err != nil {
networkError, ok := err.(*net.OpError)
if ok && networkError.Timeout() {
test.Log("Test Skipping as it didn't find a DHCP Server")
test.SkipNow()
}
test.Fatalf("Error:%v\n", err)
}
if !success {
test.Error("We didn't sucessfully get a DHCP Lease?")
} else {
log.Printf("IP Received:%v\n", acknowledgementpacket.YIAddr().String())
}
test.Log("Start Renewing Lease")
success, acknowledgementpacket, err = exampleClient.Renew(acknowledgementpacket)
if err != nil {
networkError, ok := err.(*net.OpError)
if ok && networkError.Timeout() {
test.Log("Renewal Failed! Because it didn't find the DHCP server very Strange")
test.Errorf("Error" + err.Error())
}
test.Fatalf("Error:%v\n", err)
}
if !success {
test.Error("We didn't sucessfully Renew a DHCP Lease?")
} else {
log.Printf("IP Received:%v\n", acknowledgementpacket.YIAddr().String())
}
}

View File

@ -1,45 +0,0 @@
package netlink
import (
"testing"
)
func TestAddrAddDel(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
link, err := LinkByName("lo")
if err != nil {
t.Fatal(err)
}
addr, err := ParseAddr("127.1.1.1/24 local")
if err != nil {
t.Fatal(err)
}
if err = AddrAdd(link, addr); err != nil {
t.Fatal(err)
}
addrs, err := AddrList(link, FAMILY_ALL)
if err != nil {
t.Fatal(err)
}
if len(addrs) != 1 || !addr.Equal(addrs[0]) || addrs[0].Label != addr.Label {
t.Fatal("Address not added properly")
}
if err = AddrDel(link, addr); err != nil {
t.Fatal(err)
}
addrs, err = AddrList(link, FAMILY_ALL)
if err != nil {
t.Fatal(err)
}
if len(addrs) != 0 {
t.Fatal("Address not removed properly")
}
}

View File

@ -1,544 +0,0 @@
package netlink
import (
"bytes"
"net"
"testing"
"github.com/vishvananda/netns"
)
const testTxQLen uint32 = 100
func testLinkAddDel(t *testing.T, link Link) {
links, err := LinkList()
if err != nil {
t.Fatal(err)
}
num := len(links)
if err := LinkAdd(link); err != nil {
t.Fatal(err)
}
base := link.Attrs()
result, err := LinkByName(base.Name)
if err != nil {
t.Fatal(err)
}
rBase := result.Attrs()
if vlan, ok := link.(*Vlan); ok {
other, ok := result.(*Vlan)
if !ok {
t.Fatal("Result of create is not a vlan")
}
if vlan.VlanId != other.VlanId {
t.Fatal("Link.VlanId id doesn't match")
}
}
if rBase.ParentIndex == 0 && base.ParentIndex != 0 {
t.Fatal("Created link doesn't have a Parent but it should")
} else if rBase.ParentIndex != 0 && base.ParentIndex == 0 {
t.Fatal("Created link has a Parent but it shouldn't")
} else if rBase.ParentIndex != 0 && base.ParentIndex != 0 {
if rBase.ParentIndex != base.ParentIndex {
t.Fatal("Link.ParentIndex doesn't match")
}
}
if veth, ok := link.(*Veth); ok {
if veth.TxQLen != testTxQLen {
t.Fatalf("TxQLen is %d, should be %d", veth.TxQLen, testTxQLen)
}
if rBase.MTU != base.MTU {
t.Fatalf("MTU is %d, should be %d", rBase.MTU, base.MTU)
}
if veth.PeerName != "" {
var peer *Veth
other, err := LinkByName(veth.PeerName)
if err != nil {
t.Fatalf("Peer %s not created", veth.PeerName)
}
if peer, ok = other.(*Veth); !ok {
t.Fatalf("Peer %s is incorrect type", veth.PeerName)
}
if peer.TxQLen != testTxQLen {
t.Fatalf("TxQLen of peer is %d, should be %d", peer.TxQLen, testTxQLen)
}
}
}
if vxlan, ok := link.(*Vxlan); ok {
other, ok := result.(*Vxlan)
if !ok {
t.Fatal("Result of create is not a vxlan")
}
compareVxlan(t, vxlan, other)
}
if ipv, ok := link.(*IPVlan); ok {
other, ok := result.(*IPVlan)
if !ok {
t.Fatal("Result of create is not a ipvlan")
}
if ipv.Mode != other.Mode {
t.Fatalf("Got unexpected mode: %d, expected: %d", other.Mode, ipv.Mode)
}
}
if macv, ok := link.(*Macvlan); ok {
other, ok := result.(*Macvlan)
if !ok {
t.Fatal("Result of create is not a macvlan")
}
if macv.Mode != other.Mode {
t.Fatalf("Got unexpected mode: %d, expected: %d", other.Mode, macv.Mode)
}
}
if err = LinkDel(link); err != nil {
t.Fatal(err)
}
links, err = LinkList()
if err != nil {
t.Fatal(err)
}
if len(links) != num {
t.Fatal("Link not removed properly")
}
}
func compareVxlan(t *testing.T, expected, actual *Vxlan) {
if actual.VxlanId != expected.VxlanId {
t.Fatal("Vxlan.VxlanId doesn't match")
}
if expected.SrcAddr != nil && !actual.SrcAddr.Equal(expected.SrcAddr) {
t.Fatal("Vxlan.SrcAddr doesn't match")
}
if expected.Group != nil && !actual.Group.Equal(expected.Group) {
t.Fatal("Vxlan.Group doesn't match")
}
if expected.TTL != -1 && actual.TTL != expected.TTL {
t.Fatal("Vxlan.TTL doesn't match")
}
if expected.TOS != -1 && actual.TOS != expected.TOS {
t.Fatal("Vxlan.TOS doesn't match")
}
if actual.Learning != expected.Learning {
t.Fatal("Vxlan.Learning doesn't match")
}
if actual.Proxy != expected.Proxy {
t.Fatal("Vxlan.Proxy doesn't match")
}
if actual.RSC != expected.RSC {
t.Fatal("Vxlan.RSC doesn't match")
}
if actual.L2miss != expected.L2miss {
t.Fatal("Vxlan.L2miss doesn't match")
}
if actual.L3miss != expected.L3miss {
t.Fatal("Vxlan.L3miss doesn't match")
}
if expected.NoAge {
if !actual.NoAge {
t.Fatal("Vxlan.NoAge doesn't match")
}
} else if expected.Age > 0 && actual.Age != expected.Age {
t.Fatal("Vxlan.Age doesn't match")
}
if expected.Limit > 0 && actual.Limit != expected.Limit {
t.Fatal("Vxlan.Limit doesn't match")
}
if expected.Port > 0 && actual.Port != expected.Port {
t.Fatal("Vxlan.Port doesn't match")
}
if expected.PortLow > 0 || expected.PortHigh > 0 {
if actual.PortLow != expected.PortLow {
t.Fatal("Vxlan.PortLow doesn't match")
}
if actual.PortHigh != expected.PortHigh {
t.Fatal("Vxlan.PortHigh doesn't match")
}
}
}
func TestLinkAddDelDummy(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
testLinkAddDel(t, &Dummy{LinkAttrs{Name: "foo"}})
}
func TestLinkAddDelBridge(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
testLinkAddDel(t, &Bridge{LinkAttrs{Name: "foo", MTU: 1400}})
}
func TestLinkAddDelVlan(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
parent := &Dummy{LinkAttrs{Name: "foo"}}
if err := LinkAdd(parent); err != nil {
t.Fatal(err)
}
testLinkAddDel(t, &Vlan{LinkAttrs{Name: "bar", ParentIndex: parent.Attrs().Index}, 900})
if err := LinkDel(parent); err != nil {
t.Fatal(err)
}
}
func TestLinkAddDelMacvlan(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
parent := &Dummy{LinkAttrs{Name: "foo"}}
if err := LinkAdd(parent); err != nil {
t.Fatal(err)
}
testLinkAddDel(t, &Macvlan{
LinkAttrs: LinkAttrs{Name: "bar", ParentIndex: parent.Attrs().Index},
Mode: MACVLAN_MODE_PRIVATE,
})
if err := LinkDel(parent); err != nil {
t.Fatal(err)
}
}
func TestLinkAddDelVeth(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
testLinkAddDel(t, &Veth{LinkAttrs{Name: "foo", TxQLen: testTxQLen, MTU: 1400}, "bar"})
}
func TestLinkAddDelBridgeMaster(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
master := &Bridge{LinkAttrs{Name: "foo"}}
if err := LinkAdd(master); err != nil {
t.Fatal(err)
}
testLinkAddDel(t, &Dummy{LinkAttrs{Name: "bar", MasterIndex: master.Attrs().Index}})
if err := LinkDel(master); err != nil {
t.Fatal(err)
}
}
func TestLinkSetUnsetResetMaster(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
master := &Bridge{LinkAttrs{Name: "foo"}}
if err := LinkAdd(master); err != nil {
t.Fatal(err)
}
newmaster := &Bridge{LinkAttrs{Name: "bar"}}
if err := LinkAdd(newmaster); err != nil {
t.Fatal(err)
}
slave := &Dummy{LinkAttrs{Name: "baz"}}
if err := LinkAdd(slave); err != nil {
t.Fatal(err)
}
if err := LinkSetMaster(slave, master); err != nil {
t.Fatal(err)
}
link, err := LinkByName("baz")
if err != nil {
t.Fatal(err)
}
if link.Attrs().MasterIndex != master.Attrs().Index {
t.Fatal("Master not set properly")
}
if err := LinkSetMaster(slave, newmaster); err != nil {
t.Fatal(err)
}
link, err = LinkByName("baz")
if err != nil {
t.Fatal(err)
}
if link.Attrs().MasterIndex != newmaster.Attrs().Index {
t.Fatal("Master not reset properly")
}
if err := LinkSetMaster(slave, nil); err != nil {
t.Fatal(err)
}
link, err = LinkByName("baz")
if err != nil {
t.Fatal(err)
}
if link.Attrs().MasterIndex != 0 {
t.Fatal("Master not unset properly")
}
if err := LinkDel(slave); err != nil {
t.Fatal(err)
}
if err := LinkDel(newmaster); err != nil {
t.Fatal(err)
}
if err := LinkDel(master); err != nil {
t.Fatal(err)
}
}
func TestLinkSetNs(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
basens, err := netns.Get()
if err != nil {
t.Fatal("Failed to get basens")
}
defer basens.Close()
newns, err := netns.New()
if err != nil {
t.Fatal("Failed to create newns")
}
defer newns.Close()
link := &Veth{LinkAttrs{Name: "foo"}, "bar"}
if err := LinkAdd(link); err != nil {
t.Fatal(err)
}
peer, err := LinkByName("bar")
if err != nil {
t.Fatal(err)
}
LinkSetNsFd(peer, int(basens))
if err != nil {
t.Fatal("Failed to set newns for link")
}
_, err = LinkByName("bar")
if err == nil {
t.Fatal("Link bar is still in newns")
}
err = netns.Set(basens)
if err != nil {
t.Fatal("Failed to set basens")
}
peer, err = LinkByName("bar")
if err != nil {
t.Fatal("Link is not in basens")
}
if err := LinkDel(peer); err != nil {
t.Fatal(err)
}
err = netns.Set(newns)
if err != nil {
t.Fatal("Failed to set newns")
}
_, err = LinkByName("foo")
if err == nil {
t.Fatal("Other half of veth pair not deleted")
}
}
func TestLinkAddDelVxlan(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
parent := &Dummy{
LinkAttrs{Name: "foo"},
}
if err := LinkAdd(parent); err != nil {
t.Fatal(err)
}
vxlan := Vxlan{
LinkAttrs: LinkAttrs{
Name: "bar",
},
VxlanId: 10,
VtepDevIndex: parent.Index,
Learning: true,
L2miss: true,
L3miss: true,
}
testLinkAddDel(t, &vxlan)
if err := LinkDel(parent); err != nil {
t.Fatal(err)
}
}
func TestLinkAddDelIPVlanL2(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
parent := &Dummy{LinkAttrs{Name: "foo"}}
if err := LinkAdd(parent); err != nil {
t.Fatal(err)
}
ipv := IPVlan{
LinkAttrs: LinkAttrs{
Name: "bar",
ParentIndex: parent.Index,
},
Mode: IPVLAN_MODE_L2,
}
testLinkAddDel(t, &ipv)
}
func TestLinkAddDelIPVlanL3(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
parent := &Dummy{LinkAttrs{Name: "foo"}}
if err := LinkAdd(parent); err != nil {
t.Fatal(err)
}
ipv := IPVlan{
LinkAttrs: LinkAttrs{
Name: "bar",
ParentIndex: parent.Index,
},
Mode: IPVLAN_MODE_L3,
}
testLinkAddDel(t, &ipv)
}
func TestLinkAddDelIPVlanNoParent(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
ipv := IPVlan{
LinkAttrs: LinkAttrs{
Name: "bar",
},
Mode: IPVLAN_MODE_L3,
}
err := LinkAdd(&ipv)
if err == nil {
t.Fatal("Add should fail if ipvlan creating without ParentIndex")
}
if err.Error() != "Can't create ipvlan link without ParentIndex" {
t.Fatalf("Error should be about missing ParentIndex, got %q", err)
}
}
func TestLinkByIndex(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
dummy := &Dummy{LinkAttrs{Name: "dummy"}}
if err := LinkAdd(dummy); err != nil {
t.Fatal(err)
}
found, err := LinkByIndex(dummy.Index)
if err != nil {
t.Fatal(err)
}
if found.Attrs().Index != dummy.Attrs().Index {
t.Fatalf("Indices don't match: %v != %v", found.Attrs().Index, dummy.Attrs().Index)
}
LinkDel(dummy)
// test not found
_, err = LinkByIndex(dummy.Attrs().Index)
if err == nil {
t.Fatalf("LinkByIndex(%v) found deleted link", err)
}
}
func TestLinkSet(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
iface := &Dummy{LinkAttrs{Name: "foo"}}
if err := LinkAdd(iface); err != nil {
t.Fatal(err)
}
link, err := LinkByName("foo")
if err != nil {
t.Fatal(err)
}
err = LinkSetName(link, "bar")
if err != nil {
t.Fatalf("Could not change interface name: %v", err)
}
link, err = LinkByName("bar")
if err != nil {
t.Fatalf("Interface name not changed: %v", err)
}
err = LinkSetMTU(link, 1400)
if err != nil {
t.Fatalf("Could not set MTU: %v", err)
}
link, err = LinkByName("bar")
if err != nil {
t.Fatal(err)
}
if link.Attrs().MTU != 1400 {
t.Fatal("MTU not changed!")
}
addr, err := net.ParseMAC("00:12:34:56:78:AB")
if err != nil {
t.Fatal(err)
}
err = LinkSetHardwareAddr(link, addr)
if err != nil {
t.Fatal(err)
}
link, err = LinkByName("bar")
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(link.Attrs().HardwareAddr, addr) {
t.Fatalf("hardware address not changed!")
}
}

View File

@ -1,104 +0,0 @@
package netlink
import (
"net"
"testing"
)
type arpEntry struct {
ip net.IP
mac net.HardwareAddr
}
func parseMAC(s string) net.HardwareAddr {
m, err := net.ParseMAC(s)
if err != nil {
panic(err)
}
return m
}
func dumpContains(dump []Neigh, e arpEntry) bool {
for _, n := range dump {
if n.IP.Equal(e.ip) && (n.State&NUD_INCOMPLETE) == 0 {
return true
}
}
return false
}
func TestNeighAddDel(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
dummy := Dummy{LinkAttrs{Name: "neigh0"}}
if err := LinkAdd(&dummy); err != nil {
t.Fatal(err)
}
ensureIndex(dummy.Attrs())
arpTable := []arpEntry{
{net.ParseIP("10.99.0.1"), parseMAC("aa:bb:cc:dd:00:01")},
{net.ParseIP("10.99.0.2"), parseMAC("aa:bb:cc:dd:00:02")},
{net.ParseIP("10.99.0.3"), parseMAC("aa:bb:cc:dd:00:03")},
{net.ParseIP("10.99.0.4"), parseMAC("aa:bb:cc:dd:00:04")},
{net.ParseIP("10.99.0.5"), parseMAC("aa:bb:cc:dd:00:05")},
}
// Add the arpTable
for _, entry := range arpTable {
err := NeighAdd(&Neigh{
LinkIndex: dummy.Index,
State: NUD_REACHABLE,
IP: entry.ip,
HardwareAddr: entry.mac,
})
if err != nil {
t.Errorf("Failed to NeighAdd: %v", err)
}
}
// Dump and see that all added entries are there
dump, err := NeighList(dummy.Index, 0)
if err != nil {
t.Errorf("Failed to NeighList: %v", err)
}
for _, entry := range arpTable {
if !dumpContains(dump, entry) {
t.Errorf("Dump does not contain: %v", entry)
}
}
// Delete the arpTable
for _, entry := range arpTable {
err := NeighDel(&Neigh{
LinkIndex: dummy.Index,
IP: entry.ip,
HardwareAddr: entry.mac,
})
if err != nil {
t.Errorf("Failed to NeighDel: %v", err)
}
}
// TODO: seems not working because of cache
//// Dump and see that none of deleted entries are there
//dump, err = NeighList(dummy.Index, 0)
//if err != nil {
//t.Errorf("Failed to NeighList: %v", err)
//}
//for _, entry := range arpTable {
//if dumpContains(dump, entry) {
//t.Errorf("Dump contains: %v", entry)
//}
//}
if err := LinkDel(&dummy); err != nil {
t.Fatal(err)
}
}

View File

@ -1,34 +0,0 @@
package netlink
import (
"log"
"os"
"runtime"
"testing"
"github.com/vishvananda/netns"
)
type tearDownNetlinkTest func()
func setUpNetlinkTest(t *testing.T) tearDownNetlinkTest {
if os.Getuid() != 0 {
msg := "Skipped test because it requires root privileges."
log.Printf(msg)
t.Skip(msg)
}
// new temporary namespace so we don't pollute the host
// lock thread since the namespace is thread local
runtime.LockOSThread()
var err error
ns, err := netns.New()
if err != nil {
t.Fatal("Failed to create newns", ns)
}
return func() {
ns.Close()
runtime.UnlockOSThread()
}
}

View File

@ -1,39 +0,0 @@
package nl
import (
"bytes"
"crypto/rand"
"encoding/binary"
"syscall"
"testing"
)
func (msg *IfAddrmsg) write(b []byte) {
native := NativeEndian()
b[0] = msg.Family
b[1] = msg.Prefixlen
b[2] = msg.Flags
b[3] = msg.Scope
native.PutUint32(b[4:8], msg.Index)
}
func (msg *IfAddrmsg) serializeSafe() []byte {
len := syscall.SizeofIfAddrmsg
b := make([]byte, len)
msg.write(b)
return b
}
func deserializeIfAddrmsgSafe(b []byte) *IfAddrmsg {
var msg = IfAddrmsg{}
binary.Read(bytes.NewReader(b[0:syscall.SizeofIfAddrmsg]), NativeEndian(), &msg)
return &msg
}
func TestIfAddrmsgDeserializeSerialize(t *testing.T) {
var orig = make([]byte, syscall.SizeofIfAddrmsg)
rand.Read(orig)
safemsg := deserializeIfAddrmsgSafe(orig)
msg := DeserializeIfAddrmsg(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}

View File

@ -1,60 +0,0 @@
package nl
import (
"bytes"
"crypto/rand"
"encoding/binary"
"reflect"
"syscall"
"testing"
)
type testSerializer interface {
serializeSafe() []byte
Serialize() []byte
}
func testDeserializeSerialize(t *testing.T, orig []byte, safemsg testSerializer, msg testSerializer) {
if !reflect.DeepEqual(safemsg, msg) {
t.Fatal("Deserialization failed.\n", safemsg, "\n", msg)
}
safe := msg.serializeSafe()
if !bytes.Equal(safe, orig) {
t.Fatal("Safe serialization failed.\n", safe, "\n", orig)
}
b := msg.Serialize()
if !bytes.Equal(b, safe) {
t.Fatal("Serialization failed.\n", b, "\n", safe)
}
}
func (msg *IfInfomsg) write(b []byte) {
native := NativeEndian()
b[0] = msg.Family
b[1] = msg.X__ifi_pad
native.PutUint16(b[2:4], msg.Type)
native.PutUint32(b[4:8], uint32(msg.Index))
native.PutUint32(b[8:12], msg.Flags)
native.PutUint32(b[12:16], msg.Change)
}
func (msg *IfInfomsg) serializeSafe() []byte {
length := syscall.SizeofIfInfomsg
b := make([]byte, length)
msg.write(b)
return b
}
func deserializeIfInfomsgSafe(b []byte) *IfInfomsg {
var msg = IfInfomsg{}
binary.Read(bytes.NewReader(b[0:syscall.SizeofIfInfomsg]), NativeEndian(), &msg)
return &msg
}
func TestIfInfomsgDeserializeSerialize(t *testing.T) {
var orig = make([]byte, syscall.SizeofIfInfomsg)
rand.Read(orig)
safemsg := deserializeIfInfomsgSafe(orig)
msg := DeserializeIfInfomsg(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}

View File

@ -1,43 +0,0 @@
package nl
import (
"bytes"
"crypto/rand"
"encoding/binary"
"syscall"
"testing"
)
func (msg *RtMsg) write(b []byte) {
native := NativeEndian()
b[0] = msg.Family
b[1] = msg.Dst_len
b[2] = msg.Src_len
b[3] = msg.Tos
b[4] = msg.Table
b[5] = msg.Protocol
b[6] = msg.Scope
b[7] = msg.Type
native.PutUint32(b[8:12], msg.Flags)
}
func (msg *RtMsg) serializeSafe() []byte {
len := syscall.SizeofRtMsg
b := make([]byte, len)
msg.write(b)
return b
}
func deserializeRtMsgSafe(b []byte) *RtMsg {
var msg = RtMsg{}
binary.Read(bytes.NewReader(b[0:syscall.SizeofRtMsg]), NativeEndian(), &msg)
return &msg
}
func TestRtMsgDeserializeSerialize(t *testing.T) {
var orig = make([]byte, syscall.SizeofRtMsg)
rand.Read(orig)
safemsg := deserializeRtMsgSafe(orig)
msg := DeserializeRtMsg(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}

View File

@ -1,161 +0,0 @@
package nl
import (
"bytes"
"crypto/rand"
"encoding/binary"
"testing"
)
func (msg *XfrmAddress) write(b []byte) {
copy(b[0:SizeofXfrmAddress], msg[:])
}
func (msg *XfrmAddress) serializeSafe() []byte {
b := make([]byte, SizeofXfrmAddress)
msg.write(b)
return b
}
func deserializeXfrmAddressSafe(b []byte) *XfrmAddress {
var msg = XfrmAddress{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmAddress]), NativeEndian(), &msg)
return &msg
}
func TestXfrmAddressDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmAddress)
rand.Read(orig)
safemsg := deserializeXfrmAddressSafe(orig)
msg := DeserializeXfrmAddress(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmSelector) write(b []byte) {
const AddrEnd = SizeofXfrmAddress * 2
native := NativeEndian()
msg.Daddr.write(b[0:SizeofXfrmAddress])
msg.Saddr.write(b[SizeofXfrmAddress:AddrEnd])
native.PutUint16(b[AddrEnd:AddrEnd+2], msg.Dport)
native.PutUint16(b[AddrEnd+2:AddrEnd+4], msg.DportMask)
native.PutUint16(b[AddrEnd+4:AddrEnd+6], msg.Sport)
native.PutUint16(b[AddrEnd+6:AddrEnd+8], msg.SportMask)
native.PutUint16(b[AddrEnd+8:AddrEnd+10], msg.Family)
b[AddrEnd+10] = msg.PrefixlenD
b[AddrEnd+11] = msg.PrefixlenS
b[AddrEnd+12] = msg.Proto
copy(b[AddrEnd+13:AddrEnd+16], msg.Pad[:])
native.PutUint32(b[AddrEnd+16:AddrEnd+20], uint32(msg.Ifindex))
native.PutUint32(b[AddrEnd+20:AddrEnd+24], msg.User)
}
func (msg *XfrmSelector) serializeSafe() []byte {
length := SizeofXfrmSelector
b := make([]byte, length)
msg.write(b)
return b
}
func deserializeXfrmSelectorSafe(b []byte) *XfrmSelector {
var msg = XfrmSelector{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmSelector]), NativeEndian(), &msg)
return &msg
}
func TestXfrmSelectorDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmSelector)
rand.Read(orig)
safemsg := deserializeXfrmSelectorSafe(orig)
msg := DeserializeXfrmSelector(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmLifetimeCfg) write(b []byte) {
native := NativeEndian()
native.PutUint64(b[0:8], msg.SoftByteLimit)
native.PutUint64(b[8:16], msg.HardByteLimit)
native.PutUint64(b[16:24], msg.SoftPacketLimit)
native.PutUint64(b[24:32], msg.HardPacketLimit)
native.PutUint64(b[32:40], msg.SoftAddExpiresSeconds)
native.PutUint64(b[40:48], msg.HardAddExpiresSeconds)
native.PutUint64(b[48:56], msg.SoftUseExpiresSeconds)
native.PutUint64(b[56:64], msg.HardUseExpiresSeconds)
}
func (msg *XfrmLifetimeCfg) serializeSafe() []byte {
length := SizeofXfrmLifetimeCfg
b := make([]byte, length)
msg.write(b)
return b
}
func deserializeXfrmLifetimeCfgSafe(b []byte) *XfrmLifetimeCfg {
var msg = XfrmLifetimeCfg{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmLifetimeCfg]), NativeEndian(), &msg)
return &msg
}
func TestXfrmLifetimeCfgDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmLifetimeCfg)
rand.Read(orig)
safemsg := deserializeXfrmLifetimeCfgSafe(orig)
msg := DeserializeXfrmLifetimeCfg(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmLifetimeCur) write(b []byte) {
native := NativeEndian()
native.PutUint64(b[0:8], msg.Bytes)
native.PutUint64(b[8:16], msg.Packets)
native.PutUint64(b[16:24], msg.AddTime)
native.PutUint64(b[24:32], msg.UseTime)
}
func (msg *XfrmLifetimeCur) serializeSafe() []byte {
length := SizeofXfrmLifetimeCur
b := make([]byte, length)
msg.write(b)
return b
}
func deserializeXfrmLifetimeCurSafe(b []byte) *XfrmLifetimeCur {
var msg = XfrmLifetimeCur{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmLifetimeCur]), NativeEndian(), &msg)
return &msg
}
func TestXfrmLifetimeCurDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmLifetimeCur)
rand.Read(orig)
safemsg := deserializeXfrmLifetimeCurSafe(orig)
msg := DeserializeXfrmLifetimeCur(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmId) write(b []byte) {
native := NativeEndian()
msg.Daddr.write(b[0:SizeofXfrmAddress])
native.PutUint32(b[SizeofXfrmAddress:SizeofXfrmAddress+4], msg.Spi)
b[SizeofXfrmAddress+4] = msg.Proto
copy(b[SizeofXfrmAddress+5:SizeofXfrmAddress+8], msg.Pad[:])
}
func (msg *XfrmId) serializeSafe() []byte {
b := make([]byte, SizeofXfrmId)
msg.write(b)
return b
}
func deserializeXfrmIdSafe(b []byte) *XfrmId {
var msg = XfrmId{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmId]), NativeEndian(), &msg)
return &msg
}
func TestXfrmIdDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmId)
rand.Read(orig)
safemsg := deserializeXfrmIdSafe(orig)
msg := DeserializeXfrmId(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}

View File

@ -1,109 +0,0 @@
package nl
import (
"bytes"
"crypto/rand"
"encoding/binary"
"testing"
)
func (msg *XfrmUserpolicyId) write(b []byte) {
native := NativeEndian()
msg.Sel.write(b[0:SizeofXfrmSelector])
native.PutUint32(b[SizeofXfrmSelector:SizeofXfrmSelector+4], msg.Index)
b[SizeofXfrmSelector+4] = msg.Dir
copy(b[SizeofXfrmSelector+5:SizeofXfrmSelector+8], msg.Pad[:])
}
func (msg *XfrmUserpolicyId) serializeSafe() []byte {
b := make([]byte, SizeofXfrmUserpolicyId)
msg.write(b)
return b
}
func deserializeXfrmUserpolicyIdSafe(b []byte) *XfrmUserpolicyId {
var msg = XfrmUserpolicyId{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmUserpolicyId]), NativeEndian(), &msg)
return &msg
}
func TestXfrmUserpolicyIdDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmUserpolicyId)
rand.Read(orig)
safemsg := deserializeXfrmUserpolicyIdSafe(orig)
msg := DeserializeXfrmUserpolicyId(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmUserpolicyInfo) write(b []byte) {
const CfgEnd = SizeofXfrmSelector + SizeofXfrmLifetimeCfg
const CurEnd = CfgEnd + SizeofXfrmLifetimeCur
native := NativeEndian()
msg.Sel.write(b[0:SizeofXfrmSelector])
msg.Lft.write(b[SizeofXfrmSelector:CfgEnd])
msg.Curlft.write(b[CfgEnd:CurEnd])
native.PutUint32(b[CurEnd:CurEnd+4], msg.Priority)
native.PutUint32(b[CurEnd+4:CurEnd+8], msg.Index)
b[CurEnd+8] = msg.Dir
b[CurEnd+9] = msg.Action
b[CurEnd+10] = msg.Flags
b[CurEnd+11] = msg.Share
copy(b[CurEnd+12:CurEnd+16], msg.Pad[:])
}
func (msg *XfrmUserpolicyInfo) serializeSafe() []byte {
b := make([]byte, SizeofXfrmUserpolicyInfo)
msg.write(b)
return b
}
func deserializeXfrmUserpolicyInfoSafe(b []byte) *XfrmUserpolicyInfo {
var msg = XfrmUserpolicyInfo{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmUserpolicyInfo]), NativeEndian(), &msg)
return &msg
}
func TestXfrmUserpolicyInfoDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmUserpolicyInfo)
rand.Read(orig)
safemsg := deserializeXfrmUserpolicyInfoSafe(orig)
msg := DeserializeXfrmUserpolicyInfo(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmUserTmpl) write(b []byte) {
const AddrEnd = SizeofXfrmId + 4 + SizeofXfrmAddress
native := NativeEndian()
msg.XfrmId.write(b[0:SizeofXfrmId])
native.PutUint16(b[SizeofXfrmId:SizeofXfrmId+2], msg.Family)
copy(b[SizeofXfrmId+2:SizeofXfrmId+4], msg.Pad1[:])
msg.Saddr.write(b[SizeofXfrmId+4 : AddrEnd])
native.PutUint32(b[AddrEnd:AddrEnd+4], msg.Reqid)
b[AddrEnd+4] = msg.Mode
b[AddrEnd+5] = msg.Share
b[AddrEnd+6] = msg.Optional
b[AddrEnd+7] = msg.Pad2
native.PutUint32(b[AddrEnd+8:AddrEnd+12], msg.Aalgos)
native.PutUint32(b[AddrEnd+12:AddrEnd+16], msg.Ealgos)
native.PutUint32(b[AddrEnd+16:AddrEnd+20], msg.Calgos)
}
func (msg *XfrmUserTmpl) serializeSafe() []byte {
b := make([]byte, SizeofXfrmUserTmpl)
msg.write(b)
return b
}
func deserializeXfrmUserTmplSafe(b []byte) *XfrmUserTmpl {
var msg = XfrmUserTmpl{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmUserTmpl]), NativeEndian(), &msg)
return &msg
}
func TestXfrmUserTmplDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmUserTmpl)
rand.Read(orig)
safemsg := deserializeXfrmUserTmplSafe(orig)
msg := DeserializeXfrmUserTmpl(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}

View File

@ -1,207 +0,0 @@
package nl
import (
"bytes"
"crypto/rand"
"encoding/binary"
"testing"
)
func (msg *XfrmUsersaId) write(b []byte) {
native := NativeEndian()
msg.Daddr.write(b[0:SizeofXfrmAddress])
native.PutUint32(b[SizeofXfrmAddress:SizeofXfrmAddress+4], msg.Spi)
native.PutUint16(b[SizeofXfrmAddress+4:SizeofXfrmAddress+6], msg.Family)
b[SizeofXfrmAddress+6] = msg.Proto
b[SizeofXfrmAddress+7] = msg.Pad
}
func (msg *XfrmUsersaId) serializeSafe() []byte {
b := make([]byte, SizeofXfrmUsersaId)
msg.write(b)
return b
}
func deserializeXfrmUsersaIdSafe(b []byte) *XfrmUsersaId {
var msg = XfrmUsersaId{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmUsersaId]), NativeEndian(), &msg)
return &msg
}
func TestXfrmUsersaIdDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmUsersaId)
rand.Read(orig)
safemsg := deserializeXfrmUsersaIdSafe(orig)
msg := DeserializeXfrmUsersaId(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmStats) write(b []byte) {
native := NativeEndian()
native.PutUint32(b[0:4], msg.ReplayWindow)
native.PutUint32(b[4:8], msg.Replay)
native.PutUint32(b[8:12], msg.IntegrityFailed)
}
func (msg *XfrmStats) serializeSafe() []byte {
b := make([]byte, SizeofXfrmStats)
msg.write(b)
return b
}
func deserializeXfrmStatsSafe(b []byte) *XfrmStats {
var msg = XfrmStats{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmStats]), NativeEndian(), &msg)
return &msg
}
func TestXfrmStatsDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmStats)
rand.Read(orig)
safemsg := deserializeXfrmStatsSafe(orig)
msg := DeserializeXfrmStats(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmUsersaInfo) write(b []byte) {
const IdEnd = SizeofXfrmSelector + SizeofXfrmId
const AddressEnd = IdEnd + SizeofXfrmAddress
const CfgEnd = AddressEnd + SizeofXfrmLifetimeCfg
const CurEnd = CfgEnd + SizeofXfrmLifetimeCur
const StatsEnd = CurEnd + SizeofXfrmStats
native := NativeEndian()
msg.Sel.write(b[0:SizeofXfrmSelector])
msg.Id.write(b[SizeofXfrmSelector:IdEnd])
msg.Saddr.write(b[IdEnd:AddressEnd])
msg.Lft.write(b[AddressEnd:CfgEnd])
msg.Curlft.write(b[CfgEnd:CurEnd])
msg.Stats.write(b[CurEnd:StatsEnd])
native.PutUint32(b[StatsEnd:StatsEnd+4], msg.Seq)
native.PutUint32(b[StatsEnd+4:StatsEnd+8], msg.Reqid)
native.PutUint16(b[StatsEnd+8:StatsEnd+10], msg.Family)
b[StatsEnd+10] = msg.Mode
b[StatsEnd+11] = msg.ReplayWindow
b[StatsEnd+12] = msg.Flags
copy(b[StatsEnd+13:StatsEnd+20], msg.Pad[:])
}
func (msg *XfrmUsersaInfo) serializeSafe() []byte {
b := make([]byte, SizeofXfrmUsersaInfo)
msg.write(b)
return b
}
func deserializeXfrmUsersaInfoSafe(b []byte) *XfrmUsersaInfo {
var msg = XfrmUsersaInfo{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmUsersaInfo]), NativeEndian(), &msg)
return &msg
}
func TestXfrmUsersaInfoDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmUsersaInfo)
rand.Read(orig)
safemsg := deserializeXfrmUsersaInfoSafe(orig)
msg := DeserializeXfrmUsersaInfo(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmAlgo) write(b []byte) {
native := NativeEndian()
copy(b[0:64], msg.AlgName[:])
native.PutUint32(b[64:68], msg.AlgKeyLen)
copy(b[68:msg.Len()], msg.AlgKey[:])
}
func (msg *XfrmAlgo) serializeSafe() []byte {
b := make([]byte, msg.Len())
msg.write(b)
return b
}
func deserializeXfrmAlgoSafe(b []byte) *XfrmAlgo {
var msg = XfrmAlgo{}
copy(msg.AlgName[:], b[0:64])
binary.Read(bytes.NewReader(b[64:68]), NativeEndian(), &msg.AlgKeyLen)
msg.AlgKey = b[68:msg.Len()]
return &msg
}
func TestXfrmAlgoDeserializeSerialize(t *testing.T) {
// use a 32 byte key len
var orig = make([]byte, SizeofXfrmAlgo+32)
rand.Read(orig)
// set the key len to 256 bits
orig[64] = 0
orig[65] = 1
orig[66] = 0
orig[67] = 0
safemsg := deserializeXfrmAlgoSafe(orig)
msg := DeserializeXfrmAlgo(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmAlgoAuth) write(b []byte) {
native := NativeEndian()
copy(b[0:64], msg.AlgName[:])
native.PutUint32(b[64:68], msg.AlgKeyLen)
native.PutUint32(b[68:72], msg.AlgTruncLen)
copy(b[72:msg.Len()], msg.AlgKey[:])
}
func (msg *XfrmAlgoAuth) serializeSafe() []byte {
b := make([]byte, msg.Len())
msg.write(b)
return b
}
func deserializeXfrmAlgoAuthSafe(b []byte) *XfrmAlgoAuth {
var msg = XfrmAlgoAuth{}
copy(msg.AlgName[:], b[0:64])
binary.Read(bytes.NewReader(b[64:68]), NativeEndian(), &msg.AlgKeyLen)
binary.Read(bytes.NewReader(b[68:72]), NativeEndian(), &msg.AlgTruncLen)
msg.AlgKey = b[72:msg.Len()]
return &msg
}
func TestXfrmAlgoAuthDeserializeSerialize(t *testing.T) {
// use a 32 byte key len
var orig = make([]byte, SizeofXfrmAlgoAuth+32)
rand.Read(orig)
// set the key len to 256 bits
orig[64] = 0
orig[65] = 1
orig[66] = 0
orig[67] = 0
safemsg := deserializeXfrmAlgoAuthSafe(orig)
msg := DeserializeXfrmAlgoAuth(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}
func (msg *XfrmEncapTmpl) write(b []byte) {
native := NativeEndian()
native.PutUint16(b[0:2], msg.EncapType)
native.PutUint16(b[2:4], msg.EncapSport)
native.PutUint16(b[4:6], msg.EncapDport)
copy(b[6:8], msg.Pad[:])
msg.EncapOa.write(b[8:SizeofXfrmAddress])
}
func (msg *XfrmEncapTmpl) serializeSafe() []byte {
b := make([]byte, SizeofXfrmEncapTmpl)
msg.write(b)
return b
}
func deserializeXfrmEncapTmplSafe(b []byte) *XfrmEncapTmpl {
var msg = XfrmEncapTmpl{}
binary.Read(bytes.NewReader(b[0:SizeofXfrmEncapTmpl]), NativeEndian(), &msg)
return &msg
}
func TestXfrmEncapTmplDeserializeSerialize(t *testing.T) {
var orig = make([]byte, SizeofXfrmEncapTmpl)
rand.Read(orig)
safemsg := deserializeXfrmEncapTmplSafe(orig)
msg := DeserializeXfrmEncapTmpl(orig)
testDeserializeSerialize(t, orig, safemsg, msg)
}

View File

@ -1,98 +0,0 @@
package netlink
import "testing"
func TestProtinfo(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
master := &Bridge{LinkAttrs{Name: "foo"}}
if err := LinkAdd(master); err != nil {
t.Fatal(err)
}
iface1 := &Dummy{LinkAttrs{Name: "bar1", MasterIndex: master.Index}}
iface2 := &Dummy{LinkAttrs{Name: "bar2", MasterIndex: master.Index}}
iface3 := &Dummy{LinkAttrs{Name: "bar3"}}
if err := LinkAdd(iface1); err != nil {
t.Fatal(err)
}
if err := LinkAdd(iface2); err != nil {
t.Fatal(err)
}
if err := LinkAdd(iface3); err != nil {
t.Fatal(err)
}
oldpi1, err := LinkGetProtinfo(iface1)
if err != nil {
t.Fatal(err)
}
oldpi2, err := LinkGetProtinfo(iface2)
if err != nil {
t.Fatal(err)
}
if err := LinkSetHairpin(iface1, true); err != nil {
t.Fatal(err)
}
if err := LinkSetRootBlock(iface1, true); err != nil {
t.Fatal(err)
}
pi1, err := LinkGetProtinfo(iface1)
if err != nil {
t.Fatal(err)
}
if !pi1.Hairpin {
t.Fatalf("Hairpin mode is not enabled for %s, but should", iface1.Name)
}
if !pi1.RootBlock {
t.Fatalf("RootBlock is not enabled for %s, but should", iface1.Name)
}
if pi1.Guard != oldpi1.Guard {
t.Fatalf("Guard field was changed for %s but shouldn't", iface1.Name)
}
if pi1.FastLeave != oldpi1.FastLeave {
t.Fatalf("FastLeave field was changed for %s but shouldn't", iface1.Name)
}
if pi1.Learning != oldpi1.Learning {
t.Fatalf("Learning field was changed for %s but shouldn't", iface1.Name)
}
if pi1.Flood != oldpi1.Flood {
t.Fatalf("Flood field was changed for %s but shouldn't", iface1.Name)
}
if err := LinkSetGuard(iface2, true); err != nil {
t.Fatal(err)
}
if err := LinkSetLearning(iface2, false); err != nil {
t.Fatal(err)
}
pi2, err := LinkGetProtinfo(iface2)
if err != nil {
t.Fatal(err)
}
if pi2.Hairpin {
t.Fatalf("Hairpin mode is enabled for %s, but shouldn't", iface2.Name)
}
if !pi2.Guard {
t.Fatalf("Guard is not enabled for %s, but should", iface2.Name)
}
if pi2.Learning {
t.Fatalf("Learning is enabled for %s, but shouldn't", iface2.Name)
}
if pi2.RootBlock != oldpi2.RootBlock {
t.Fatalf("RootBlock field was changed for %s but shouldn't", iface2.Name)
}
if pi2.FastLeave != oldpi2.FastLeave {
t.Fatalf("FastLeave field was changed for %s but shouldn't", iface2.Name)
}
if pi2.Flood != oldpi2.Flood {
t.Fatalf("Flood field was changed for %s but shouldn't", iface2.Name)
}
if err := LinkSetHairpin(iface3, true); err == nil || err.Error() != "operation not supported" {
t.Fatalf("Set protinfo attrs for link without master is not supported, but err: %s", err)
}
}

View File

@ -1,84 +0,0 @@
package netlink
import (
"net"
"testing"
)
func TestRouteAddDel(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
// get loopback interface
link, err := LinkByName("lo")
if err != nil {
t.Fatal(err)
}
// bring the interface up
if err = LinkSetUp(link); err != nil {
t.Fatal(err)
}
// add a gateway route
_, dst, err := net.ParseCIDR("192.168.0.0/24")
ip := net.ParseIP("127.1.1.1")
route := Route{LinkIndex: link.Attrs().Index, Dst: dst, Src: ip}
err = RouteAdd(&route)
if err != nil {
t.Fatal(err)
}
routes, err := RouteList(link, FAMILY_V4)
if err != nil {
t.Fatal(err)
}
if len(routes) != 1 {
t.Fatal("Link not added properly")
}
dstIP := net.ParseIP("192.168.0.42")
routeToDstIP, err := RouteGet(dstIP)
if err != nil {
t.Fatal(err)
}
if len(routeToDstIP) == 0 {
t.Fatal("Default route not present")
}
err = RouteDel(&route)
if err != nil {
t.Fatal(err)
}
routes, err = RouteList(link, FAMILY_V4)
if err != nil {
t.Fatal(err)
}
if len(routes) != 0 {
t.Fatal("Route not removed properly")
}
}
func TestRouteAddIncomplete(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
// get loopback interface
link, err := LinkByName("lo")
if err != nil {
t.Fatal(err)
}
// bring the interface up
if err = LinkSetUp(link); err != nil {
t.Fatal(err)
}
route := Route{LinkIndex: link.Attrs().Index}
if err := RouteAdd(&route); err == nil {
t.Fatal("Adding incomplete route should fail")
}
}

View File

@ -1,49 +0,0 @@
package netlink
import (
"net"
"testing"
)
func TestXfrmPolicyAddDel(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
src, _ := ParseIPNet("127.1.1.1/32")
dst, _ := ParseIPNet("127.1.1.2/32")
policy := XfrmPolicy{
Src: src,
Dst: dst,
Dir: XFRM_DIR_OUT,
}
tmpl := XfrmPolicyTmpl{
Src: net.ParseIP("127.0.0.1"),
Dst: net.ParseIP("127.0.0.2"),
Proto: XFRM_PROTO_ESP,
Mode: XFRM_MODE_TUNNEL,
}
policy.Tmpls = append(policy.Tmpls, tmpl)
if err := XfrmPolicyAdd(&policy); err != nil {
t.Fatal(err)
}
policies, err := XfrmPolicyList(FAMILY_ALL)
if err != nil {
t.Fatal(err)
}
if len(policies) != 1 {
t.Fatal("Policy not added properly")
}
if err = XfrmPolicyDel(&policy); err != nil {
t.Fatal(err)
}
policies, err = XfrmPolicyList(FAMILY_ALL)
if err != nil {
t.Fatal(err)
}
if len(policies) != 0 {
t.Fatal("Policy not removed properly")
}
}

View File

@ -1,50 +0,0 @@
package netlink
import (
"net"
"testing"
)
func TestXfrmStateAddDel(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
state := XfrmState{
Src: net.ParseIP("127.0.0.1"),
Dst: net.ParseIP("127.0.0.2"),
Proto: XFRM_PROTO_ESP,
Mode: XFRM_MODE_TUNNEL,
Spi: 1,
Auth: &XfrmStateAlgo{
Name: "hmac(sha256)",
Key: []byte("abcdefghijklmnopqrstuvwzyzABCDEF"),
},
Crypt: &XfrmStateAlgo{
Name: "cbc(aes)",
Key: []byte("abcdefghijklmnopqrstuvwzyzABCDEF"),
},
}
if err := XfrmStateAdd(&state); err != nil {
t.Fatal(err)
}
policies, err := XfrmStateList(FAMILY_ALL)
if err != nil {
t.Fatal(err)
}
if len(policies) != 1 {
t.Fatal("State not added properly")
}
if err = XfrmStateDel(&state); err != nil {
t.Fatal(err)
}
policies, err = XfrmStateList(FAMILY_ALL)
if err != nil {
t.Fatal(err)
}
if len(policies) != 0 {
t.Fatal("State not removed properly")
}
}

View File

@ -1,115 +0,0 @@
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build linux
package unix_test
import (
"bytes"
"net"
"os"
"syscall"
"testing"
"golang.org/x/sys/unix"
)
// TestSCMCredentials tests the sending and receiving of credentials
// (PID, UID, GID) in an ancillary message between two UNIX
// sockets. The SO_PASSCRED socket option is enabled on the sending
// socket for this to work.
func TestSCMCredentials(t *testing.T) {
fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
if err != nil {
t.Fatalf("Socketpair: %v", err)
}
defer unix.Close(fds[0])
defer unix.Close(fds[1])
err = unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_PASSCRED, 1)
if err != nil {
t.Fatalf("SetsockoptInt: %v", err)
}
srvFile := os.NewFile(uintptr(fds[0]), "server")
defer srvFile.Close()
srv, err := net.FileConn(srvFile)
if err != nil {
t.Errorf("FileConn: %v", err)
return
}
defer srv.Close()
cliFile := os.NewFile(uintptr(fds[1]), "client")
defer cliFile.Close()
cli, err := net.FileConn(cliFile)
if err != nil {
t.Errorf("FileConn: %v", err)
return
}
defer cli.Close()
var ucred unix.Ucred
if os.Getuid() != 0 {
ucred.Pid = int32(os.Getpid())
ucred.Uid = 0
ucred.Gid = 0
oob := unix.UnixCredentials(&ucred)
_, _, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil)
if err.(*net.OpError).Err != syscall.EPERM {
t.Fatalf("WriteMsgUnix failed with %v, want EPERM", err)
}
}
ucred.Pid = int32(os.Getpid())
ucred.Uid = uint32(os.Getuid())
ucred.Gid = uint32(os.Getgid())
oob := unix.UnixCredentials(&ucred)
// this is going to send a dummy byte
n, oobn, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil)
if err != nil {
t.Fatalf("WriteMsgUnix: %v", err)
}
if n != 0 {
t.Fatalf("WriteMsgUnix n = %d, want 0", n)
}
if oobn != len(oob) {
t.Fatalf("WriteMsgUnix oobn = %d, want %d", oobn, len(oob))
}
oob2 := make([]byte, 10*len(oob))
n, oobn2, flags, _, err := srv.(*net.UnixConn).ReadMsgUnix(nil, oob2)
if err != nil {
t.Fatalf("ReadMsgUnix: %v", err)
}
if flags != 0 {
t.Fatalf("ReadMsgUnix flags = 0x%x, want 0", flags)
}
if n != 1 {
t.Fatalf("ReadMsgUnix n = %d, want 1 (dummy byte)", n)
}
if oobn2 != oobn {
// without SO_PASSCRED set on the socket, ReadMsgUnix will
// return zero oob bytes
t.Fatalf("ReadMsgUnix oobn = %d, want %d", oobn2, oobn)
}
oob2 = oob2[:oobn2]
if !bytes.Equal(oob, oob2) {
t.Fatal("ReadMsgUnix oob bytes don't match")
}
scm, err := unix.ParseSocketControlMessage(oob2)
if err != nil {
t.Fatalf("ParseSocketControlMessage: %v", err)
}
newUcred, err := unix.ParseUnixCredentials(&scm[0])
if err != nil {
t.Fatalf("ParseUnixCredentials: %v", err)
}
if *newUcred != ucred {
t.Fatalf("ParseUnixCredentials = %+v, want %+v", newUcred, ucred)
}
}

View File

@ -1,23 +0,0 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd
package unix_test
import (
"testing"
"golang.org/x/sys/unix"
)
func TestMmap(t *testing.T) {
b, err := unix.Mmap(-1, 0, unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE)
if err != nil {
t.Fatalf("Mmap: %v", err)
}
if err := unix.Munmap(b); err != nil {
t.Fatalf("Munmap: %v", err)
}
}

View File

@ -1,35 +0,0 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd openbsd
package unix_test
import (
"testing"
"golang.org/x/sys/unix"
)
const MNT_WAIT = 1
func TestGetfsstat(t *testing.T) {
n, err := unix.Getfsstat(nil, MNT_WAIT)
if err != nil {
t.Fatal(err)
}
data := make([]unix.Statfs_t, n)
n, err = unix.Getfsstat(data, MNT_WAIT)
if err != nil {
t.Fatal(err)
}
empty := unix.Statfs_t{}
for _, stat := range data {
if stat == empty {
t.Fatal("an empty Statfs_t struct was returned")
}
}
}

View File

@ -1,33 +0,0 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
package unix_test
import (
"testing"
"golang.org/x/sys/unix"
)
func testSetGetenv(t *testing.T, key, value string) {
err := unix.Setenv(key, value)
if err != nil {
t.Fatalf("Setenv failed to set %q: %v", value, err)
}
newvalue, found := unix.Getenv(key)
if !found {
t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value)
}
if newvalue != value {
t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value)
}
}
func TestEnv(t *testing.T) {
testSetGetenv(t, "TESTENV", "AVALUE")
// make sure TESTENV gets set to "", not deleted
testSetGetenv(t, "TESTENV", "")
}

View File

@ -1,318 +0,0 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
package unix_test
import (
"flag"
"fmt"
"io/ioutil"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"time"
"golang.org/x/sys/unix"
)
// Tests that below functions, structures and constants are consistent
// on all Unix-like systems.
func _() {
// program scheduling priority functions and constants
var (
_ func(int, int, int) error = unix.Setpriority
_ func(int, int) (int, error) = unix.Getpriority
)
const (
_ int = unix.PRIO_USER
_ int = unix.PRIO_PROCESS
_ int = unix.PRIO_PGRP
)
// termios constants
const (
_ int = unix.TCIFLUSH
_ int = unix.TCIOFLUSH
_ int = unix.TCOFLUSH
)
// fcntl file locking structure and constants
var (
_ = unix.Flock_t{
Type: int16(0),
Whence: int16(0),
Start: int64(0),
Len: int64(0),
Pid: int32(0),
}
)
const (
_ = unix.F_GETLK
_ = unix.F_SETLK
_ = unix.F_SETLKW
)
}
// TestFcntlFlock tests whether the file locking structure matches
// the calling convention of each kernel.
func TestFcntlFlock(t *testing.T) {
name := filepath.Join(os.TempDir(), "TestFcntlFlock")
fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
if err != nil {
t.Fatalf("Open failed: %v", err)
}
defer unix.Unlink(name)
defer unix.Close(fd)
flock := unix.Flock_t{
Type: unix.F_RDLCK,
Start: 0, Len: 0, Whence: 1,
}
if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
t.Fatalf("FcntlFlock failed: %v", err)
}
}
// TestPassFD tests passing a file descriptor over a Unix socket.
//
// This test involved both a parent and child process. The parent
// process is invoked as a normal test, with "go test", which then
// runs the child process by running the current test binary with args
// "-test.run=^TestPassFD$" and an environment variable used to signal
// that the test should become the child process instead.
func TestPassFD(t *testing.T) {
switch runtime.GOOS {
case "dragonfly":
// TODO(jsing): Figure out why sendmsg is returning EINVAL.
t.Skip("skipping test on dragonfly")
case "solaris":
// TODO(aram): Figure out why ReadMsgUnix is returning empty message.
t.Skip("skipping test on solaris, see issue 7402")
}
if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
passFDChild()
return
}
tempDir, err := ioutil.TempDir("", "TestPassFD")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
if err != nil {
t.Fatalf("Socketpair: %v", err)
}
defer unix.Close(fds[0])
defer unix.Close(fds[1])
writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
defer writeFile.Close()
defer readFile.Close()
cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
}
cmd.ExtraFiles = []*os.File{writeFile}
out, err := cmd.CombinedOutput()
if len(out) > 0 || err != nil {
t.Fatalf("child process: %q, %v", out, err)
}
c, err := net.FileConn(readFile)
if err != nil {
t.Fatalf("FileConn: %v", err)
}
defer c.Close()
uc, ok := c.(*net.UnixConn)
if !ok {
t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
}
buf := make([]byte, 32) // expect 1 byte
oob := make([]byte, 32) // expect 24 bytes
closeUnix := time.AfterFunc(5*time.Second, func() {
t.Logf("timeout reading from unix socket")
uc.Close()
})
_, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
closeUnix.Stop()
scms, err := unix.ParseSocketControlMessage(oob[:oobn])
if err != nil {
t.Fatalf("ParseSocketControlMessage: %v", err)
}
if len(scms) != 1 {
t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
}
scm := scms[0]
gotFds, err := unix.ParseUnixRights(&scm)
if err != nil {
t.Fatalf("unix.ParseUnixRights: %v", err)
}
if len(gotFds) != 1 {
t.Fatalf("wanted 1 fd; got %#v", gotFds)
}
f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
defer f.Close()
got, err := ioutil.ReadAll(f)
want := "Hello from child process!\n"
if string(got) != want {
t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
}
}
// passFDChild is the child process used by TestPassFD.
func passFDChild() {
defer os.Exit(0)
// Look for our fd. It should be fd 3, but we work around an fd leak
// bug here (http://golang.org/issue/2603) to let it be elsewhere.
var uc *net.UnixConn
for fd := uintptr(3); fd <= 10; fd++ {
f := os.NewFile(fd, "unix-conn")
var ok bool
netc, _ := net.FileConn(f)
uc, ok = netc.(*net.UnixConn)
if ok {
break
}
}
if uc == nil {
fmt.Println("failed to find unix fd")
return
}
// Make a file f to send to our parent process on uc.
// We make it in tempDir, which our parent will clean up.
flag.Parse()
tempDir := flag.Arg(0)
f, err := ioutil.TempFile(tempDir, "")
if err != nil {
fmt.Printf("TempFile: %v", err)
return
}
f.Write([]byte("Hello from child process!\n"))
f.Seek(0, 0)
rights := unix.UnixRights(int(f.Fd()))
dummyByte := []byte("x")
n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
if err != nil {
fmt.Printf("WriteMsgUnix: %v", err)
return
}
if n != 1 || oobn != len(rights) {
fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
return
}
}
// TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
// and ParseUnixRights are able to successfully round-trip lists of file descriptors.
func TestUnixRightsRoundtrip(t *testing.T) {
testCases := [...][][]int{
{{42}},
{{1, 2}},
{{3, 4, 5}},
{{}},
{{1, 2}, {3, 4, 5}, {}, {7}},
}
for _, testCase := range testCases {
b := []byte{}
var n int
for _, fds := range testCase {
// Last assignment to n wins
n = len(b) + unix.CmsgLen(4*len(fds))
b = append(b, unix.UnixRights(fds...)...)
}
// Truncate b
b = b[:n]
scms, err := unix.ParseSocketControlMessage(b)
if err != nil {
t.Fatalf("ParseSocketControlMessage: %v", err)
}
if len(scms) != len(testCase) {
t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
}
for i, scm := range scms {
gotFds, err := unix.ParseUnixRights(&scm)
if err != nil {
t.Fatalf("ParseUnixRights: %v", err)
}
wantFds := testCase[i]
if len(gotFds) != len(wantFds) {
t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
}
for j, fd := range gotFds {
if fd != wantFds[j] {
t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
}
}
}
}
}
func TestRlimit(t *testing.T) {
var rlimit, zero unix.Rlimit
err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
if err != nil {
t.Fatalf("Getrlimit: save failed: %v", err)
}
if zero == rlimit {
t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
}
set := rlimit
set.Cur = set.Max - 1
err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
if err != nil {
t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
}
var get unix.Rlimit
err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
if err != nil {
t.Fatalf("Getrlimit: get failed: %v", err)
}
set = rlimit
set.Cur = set.Max - 1
if set != get {
// Seems like Darwin requires some privilege to
// increase the soft limit of rlimit sandbox, though
// Setrlimit never reports an error.
switch runtime.GOOS {
case "darwin":
default:
t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
}
}
err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
if err != nil {
t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
}
}
func TestSeekFailure(t *testing.T) {
_, err := unix.Seek(-1, 0, 0)
if err == nil {
t.Fatalf("Seek(-1, 0, 0) did not fail")
}
str := err.Error() // used to crash on Linux
t.Logf("Seek: %v", str)
if str == "" {
t.Fatalf("Seek(-1, 0, 0) return error with empty message")
}
}

5
MAINTAINERS Normal file
View File

@ -0,0 +1,5 @@
Dan Williams <dcbw@redhat.com> (@dcbw)
Gabe Rosenhouse <grosenhouse@pivotal.io> (@rosenhouse)
Michael Bridgen <michael@weave.works> (@squaremo)
Stefan Junker <stefan.junker@coreos.com> (@steveeJ)
Tom Denham <tom.denham@metaswitch.com> (@tomdee)

103
README.md
View File

@ -1,33 +1,65 @@
# cni - the Container Network Interface
[![Build Status](https://travis-ci.org/containernetworking/cni.svg?branch=master)](https://travis-ci.org/containernetworking/cni)
[![Coverage Status](https://coveralls.io/repos/github/containernetworking/cni/badge.svg?branch=master)](https://coveralls.io/github/containernetworking/cni?branch=master)
# CNI - the Container Network Interface
## What is CNI?
CNI, the _Container Network Interface_, is a proposed standard for configuring network interfaces for Linux application containers.
The standard consists of a simple specification for how executable plugins can be used to configure network namespaces.
The specification itself is contained in [SPEC.md](SPEC.md)
The CNI (_Container Network Interface_) project consists of a specification and libraries for writing plugins to configure network interfaces in Linux containers, along with a number of supported plugins.
CNI concerns itself only with network connectivity of containers and removing allocated resources when the container is deleted.
Because of this focus CNI has a wide range of support and the specification is simple to implement.
As well as the [specification](SPEC.md), this repository contains the Go source code of a library for integrating CNI into applications, an example command-line tool, a template for making new plugins, and the supported plugins.
The template code makes it straight-forward to create a CNI plugin for an existing container networking project.
CNI also makes a good framework for creating a new container networking project from scratch.
## Why develop CNI?
Application containers on Linux are a rapidly evolving area, and within this space networking is a particularly unsolved problem, as it is highly environment-specific.
We believe that every container runtime will seek to solve the same problem of making the network layer pluggable.
In order to avoid duplication, we think it is prudent to define a common interface between the network plugins and container execution.
Hence we are proposing this specification, along with an initial set of plugins that can be used by different container runtime systems.
Application containers on Linux are a rapidly evolving area, and within this area networking is not well addressed as it is highly environment-specific.
We believe that many container runtimes and orchestrators will seek to solve the same problem of making the network layer pluggable.
To avoid duplication, we think it is prudent to define a common interface between the network plugins and container execution: hence we put forward this specification, along with libraries for Go and a set of plugins.
## Who is using CNI?
- [rkt - container engine](https://coreos.com/blog/rkt-cni-networking.html)
- [Kurma - container runtime](http://kurma.io/)
- [Kubernetes - a system to simplify container operations](http://kubernetes.io/docs/admin/network-plugins/)
- [Cloud Foundry - a platform for cloud applications](https://github.com/cloudfoundry-incubator/guardian-cni-adapter)
- [Weave - a multi-host Docker network](https://github.com/weaveworks/weave)
- [Project Calico - a layer 3 virtual network](https://github.com/projectcalico/calico-cni)
- [Contiv Networking - policy networking for various use cases](https://github.com/contiv/netplugin)
- [Mesos - a distributed systems kernel](https://github.com/apache/mesos/blob/master/docs/cni.md)
## Contributing to CNI
We welcome contributions, including [bug reports](https://github.com/containernetworking/cni/issues), and code and documentation improvements.
If you intend to contribute to code or documentation, please read [CONTRIBUTING.md](CONTRIBUTING.md). Also see the [contact section](#contact) in this README.
## How do I use CNI?
## Requirements
CNI requires Go 1.4+ to build.
### Requirements
## Included Plugins
This repository includes a number of common plugins that can be found in plugins/ directory.
Please see Documentation/ folder for documentation about particular plugins.
CNI requires Go 1.5+ to build.
## Running the plugins
The scripts/ directory contains two scripts, priv-net-run.sh and docker-run.sh, that can be used to excercise the plugins.
Go 1.5 users will need to set GO15VENDOREXPERIMENT=1 to get vendored
dependencies. This flag is set by default in 1.6.
### Included Plugins
This repository includes a number of common plugins in the `plugins/` directory.
Please see the [Documentation/](Documentation/) directory for documentation about particular plugins.
### Running the plugins
The scripts/ directory contains two scripts, `priv-net-run.sh` and `docker-run.sh`, that can be used to exercise the plugins.
**note - priv-net-run.sh depends on `jq`**
Start out by creating a netconf file to describe a network:
```
```bash
$ mkdir -p /etc/cni/net.d
$ cat >/etc/cni/net.d/10-mynet.conf <<EOF
{
@ -45,17 +77,24 @@ $ cat >/etc/cni/net.d/10-mynet.conf <<EOF
}
}
EOF
$ cat >/etc/cni/net.d/99-loopback.conf <<EOF
{
"type": "loopback"
}
EOF
```
The directory `/etc/cni/net.d` is the default location in which the scripts will look for net configurations.
Next, build the plugins:
```
```bash
$ ./build
```
Finally, execute a command (`ifconfig` in this example) in a private network namespace that has joined `mynet` network:
Finally, execute a command (`ifconfig` in this example) in a private network namespace that has joined the `mynet` network:
```
```bash
$ CNI_PATH=`pwd`/bin
$ cd scripts
$ sudo CNI_PATH=$CNI_PATH ./priv-net-run.sh ifconfig
@ -78,15 +117,17 @@ lo Link encap:Local Loopback
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
```
The environment variable `CNI_PATH` tells the scripts and library where to look for plugin executables.
## Running a Docker container with network namespace set up by CNI plugins
Use instructions in the previous section to define a netconf and build the plugins.
Next, docker-run.sh script wraps `docker run` command to execute the plugins prior to entering the container:
Use the instructions in the previous section to define a netconf and build the plugins.
Next, docker-run.sh script wraps `docker run`, to execute the plugins prior to entering the container:
```
```bash
$ CNI_PATH=`pwd`/bin
$ cd scripts
$ sudo CNI_PATH=$CNI_PATH ./docker-run.sh --rm busybox:latest /sbin/ifconfig
$ sudo CNI_PATH=$CNI_PATH ./docker-run.sh --rm busybox:latest ifconfig
eth0 Link encap:Ethernet HWaddr fa:60:70:aa:07:d1
inet addr:10.22.0.2 Bcast:0.0.0.0 Mask:255.255.0.0
inet6 addr: fe80::f860:70ff:feaa:7d1/64 Scope:Link
@ -105,3 +146,19 @@ lo Link encap:Local Loopback
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
```
## What might CNI do in the future?
CNI currently covers a wide range of needs for network configuration due to it simple model and API.
However, in the future CNI might want to branch out into other directions:
- Dynamic updates to existing network configuration
- Dynamic policies for network bandwidth and firewall rules
If these topics of are interest please contact the team via the mailing list or IRC and find some like minded people in the community to put a proposal together.
## Contact
For any questions about CNI, please reach out on the mailing list:
- Email: [cni-dev](https://groups.google.com/forum/#!forum/cni-dev)
- IRC: #[containernetworking](irc://irc.freenode.org:6667/#containernetworking) channel on freenode.org

33
ROADMAP.md Normal file
View File

@ -0,0 +1,33 @@
# CNI Roadmap
This document defines a high level roadmap for CNI development.
The list below is not complete, and we advise to get the current project state from the [milestones defined in GitHub](https://github.com/containernetworking/cni/milestones).
## CNI Milestones
### [v0.2.0](https://github.com/containernetworking/cni/milestones/v0.2.0)
* Signed release binaries
* Introduction of a testing strategy/framework
### [v0.3.0](https://github.com/containernetworking/cni/milestones/v0.3.0)
* Further increase test coverage
* Simpler default route handling in bridge plugin
* Clarify project description, documentation and contribution guidelines
### [v0.4.0](https://github.com/containernetworking/cni/milestones/v0.4.0)
* Further increase test coverage
* Simpler bridging of host interface
* Improve IPAM allocator predictability
* Allow in- and output of arbitrary K/V pairs for plugins
### [v1.0.0](https://github.com/containernetworking/cni/milestones/v1.0.0)
- Plugin composition functionality
- IPv6 support
- Stable SPEC
- Strategy and tooling for backwards compatibility
- Complete test coverage
- Integrate build artefact generation with CI

64
SPEC.md
View File

@ -2,7 +2,8 @@
## Overview
This document proposes a generic plugin-based networking solution for application containers on Linux, the _Container Networking Interface_, or _CNI_. It is derived from the [rkt Networking Proposal][rkt-networking-proposal], which aimed to satisfy many of the [design considerations][rkt-networking-design] for networking in [rkt][rkt-github].
This document proposes a generic plugin-based networking solution for application containers on Linux, the _Container Networking Interface_, or _CNI_.
It is derived from the [rkt Networking Proposal][rkt-networking-proposal], which aimed to satisfy many of the [design considerations][rkt-networking-design] for networking in [rkt][rkt-github].
For the purposes of this proposal, we define two terms very specifically:
- _container_ can be considered synonymous with a [Linux _network namespace_][namespaces]. What unit this corresponds to depends on a particular container runtime implementation: for example, in implementations of the [App Container Spec][appc-github] like rkt, each _pod_ runs in a unique network namespace. In [Docker][docker], on the other hand, network namespaces generally exist for each separate Docker container.
@ -41,6 +42,7 @@ The operations that the CNI plugin needs to support are:
- Add container to network
- Parameters:
- **Version**. The version of CNI spec that the caller is using (container management system or the invoking plugin).
- **Container ID**. This is optional but recommended, and should be unique across an administrative domain while the container is live (it may be reused in the future). For example, an environment with an IPAM system may require that each container is allocated a unique ID and that each IP allocation can thus be correlated back to a particular container. As another example, in appc implementations this would be the _pod ID_.
- **Network namespace path**. This represents the path to the network namespace to be added, i.e. /proc/[pid]/ns/net or a bind-mount/link to it.
- **Network configuration**. This is a JSON document describing a network to which a container can be joined. The schema is described below.
@ -48,16 +50,20 @@ The operations that the CNI plugin needs to support are:
- **Name of the interface inside the container**. This is the name that should be assigned to the interface created inside the container (network namespace); consequently it must comply with the standard Linux restrictions on interface names.
- Result:
- **IPs assigned to the interface**. This is either an IPv4 address, an IPv6 address, or both.
- **DNS information**. Dictionary that includes DNS information for nameservers, domain, search domains and options.
- Delete container from network
- Parameters:
- **Version**. The version of CNI spec that the caller is using (container management system or the invoking plugin).
- **Container ID**, as defined above.
- **Network namespace path**, as defined above.
- **Network configuration**, as defined above.
- **Extra arguments**, as defined above.
- **Name of the interface inside the container**, as defined above.
The executable command-line API uses the type of network (see [Network Configuration](#network-configuration) below) as the name of the executable to invoke. It will then look for this executable in a list of predefined directories. Once found, it will invoke the executable using the following environment variables for argument passing:
The executable command-line API uses the type of network (see [Network Configuration](#network-configuration) below) as the name of the executable to invoke.
It will then look for this executable in a list of predefined directories. Once found, it will invoke the executable using the following environment variables for argument passing:
- `CNI_VERSION`: [Semantic Version 2.0](http://semver.org) of CNI specification. This effectively versions the CNI_XXX environment variables.
- `CNI_COMMAND`: indicates the desired operation; either `ADD` or `DEL`
- `CNI_CONTAINERID`: Container ID
- `CNI_NETNS`: Path to network namespace file
@ -74,6 +80,7 @@ Success is indicated by a return code of zero and the following JSON printed to
```
{
"cniVersion": "0.1.0",
"ip4": {
"ip": <ipv4-and-subnet-in-CIDR>,
"gateway": <ipv4-of-the-gateway>, (optional)
@ -83,20 +90,34 @@ Success is indicated by a return code of zero and the following JSON printed to
"ip": <ipv6-and-subnet-in-CIDR>,
"gateway": <ipv6-of-the-gateway>, (optional)
"routes": <list-of-ipv6-routes> (optional)
},
"dns": {
"nameservers": <list-of-nameservers> (optional)
"domain": <name-of-local-domain> (optional)
"search": <list-of-additional-search-domains> (optional)
"options": <list-of-options> (optional)
}
}
```
`cniVersion` specifies a [Semantic Version 2.0](http://semver.org) of CNI specification used by the plugin.
`dns` field contains a dictionary consisting of common DNS information that this network is aware of.
The result is returned in the same format as specified in the [configuration](#network-configuration).
The specification does not declare how this information must be processed by CNI consumers.
Examples include generating an `/etc/resolv.conf` file to be injected into the container filesystem or running a DNS forwarder on the host.
Errors are indicated by a non-zero return code and the following JSON being printed to stdout:
```
{
"cniVersion": "0.1.0",
"code": <numeric-error-code>,
"msg": <short-error-message>,
"details": <long-error-message> (optional)
}
```
Error codes 0-99 are reserved for well-known errors (to be defined later).
`cniVersion` specifies a [Semantic Version 2.0](http://semver.org) of CNI specification used by the plugin.
Error codes 0-99 are reserved for well-known errors (see [Well-known Error Codes](#well-known-error-codes) section).
Values of 100+ can be freely used for plugin specific errors.
In addition, stderr can be used for unstructured output such as logs.
@ -104,6 +125,7 @@ In addition, stderr can be used for unstructured output such as logs.
### Network Configuration
The network configuration is described in JSON form. The configuration can be stored on disk or generated from other sources by the container runtime. The following fields are well-known and have the following meaning:
- `cniVersion` (string): [Semantic Version 2.0](http://semver.org) of CNI specification to which this configuration conforms.
- `name` (string): Network name. This should be unique across all containers on the host (or other administrative domain).
- `type` (string): Refers to the filename of the CNI plugin executable.
- `ipMasq` (boolean): Optional (if supported by the plugin). Set up an IP masquerade on the host for this network. This is necessary if the host will act as a gateway to subnets that are not able to route to the IP assigned to the container.
@ -112,27 +134,36 @@ The network configuration is described in JSON form. The configuration can be st
- `routes` (list): List of subnets (in CIDR notation) that the CNI plugin should ensure are reachable by routing them through the network. Each entry is a dictionary containing:
- `dst` (string): subnet in CIDR notation
- `gw` (string): IP address of the gateway to use. If not specified, the default gateway for the subnet is assumed (as determined by the IPAM plugin).
- `dns`: Dictionary with DNS specific values:
- `nameservers` (list of strings): list of a priority-ordered list of DNS nameservers that this network is aware of. Each entry in the list is a string containing either an IPv4 or an IPv6 address.
- `domain` (string): the local domain used for short hostname lookups.
- `search` (list of strings): list of priority ordered search domains for short hostname lookups. Will be preferred over `domain` by most resolvers.
- `options` (list of strings): list of options that can be passed to the resolver
### Example configurations
```json
{
"cniVersion": "0.1.0",
"name": "dbnet",
"type": "bridge",
// type (plugin) specific
"bridge": "cni0",
"addIf": "eth0",
"ipam": {
"type": "host-local",
// ipam specific
"subnet": "10.1.0.0/16",
"gateway": "10.1.0.1"
},
"dns": {
"nameservers": [ "10.1.0.1" ]
}
}
```
```json
{
"cniVersion": "0.1.0",
"name": "pci",
"type": "ovs",
// type (plugin) specific
@ -147,6 +178,7 @@ The network configuration is described in JSON form. The configuration can be st
```json
{
"cniVersion": "0.1",
"name": "wan",
"type": "macvlan",
// ipam specific
@ -154,6 +186,9 @@ The network configuration is described in JSON form. The configuration can be st
"type": "dhcp",
"routes": [ { "dst": "10.0.0.0/8", "gw": "10.0.0.1" } ]
},
"dns": {
"nameservers": [ "10.0.0.1" ]
}
}
```
@ -172,6 +207,7 @@ Success is indicated by a zero return code and the following JSON being printed
```
{
"cniVersion": "0.1.0",
"ip4": {
"ip": <ipv4-and-subnet-in-CIDR>,
"gateway": <ipv4-of-the-gateway>, (optional)
@ -181,10 +217,17 @@ Success is indicated by a zero return code and the following JSON being printed
"ip": <ipv6-and-subnet-in-CIDR>,
"gateway": <ipv6-of-the-gateway>, (optional)
"routes": <list-of-ipv6-routes> (optional)
},
"dns": {
"nameservers": <list-of-nameservers> (optional)
"domain": <name-of-local-domain> (optional)
"search": <list-of-search-domains> (optional)
"options": <list-of-options> (optional)
}
}
```
`cniVersion` specifies a [Semantic Version 2.0](http://semver.org) of CNI specification used by the plugin.
`gateway` is the default gateway for this subnet, if one exists.
It does not instruct the CNI plugin to add any routes with this gateway: routes to add are specified separately via the `routes` field.
An example use of this value is for the CNI plugin to add this IP address to the linux-bridge to make it a gateway.
@ -193,6 +236,13 @@ Each route entry is a dictionary with the following fields:
- `dst` (string): Destination subnet specified in CIDR notation.
- `gw` (string): IP of the gateway. If omitted, a default gateway is assumed (as determined by the CNI plugin).
The "dns" field contains a dictionary consisting of common DNS information.
- `nameservers` (list of strings): list of a priority-ordered list of DNS nameservers that this network is aware of. Each entry in the list is a string containing either an IPv4 or an IPv6 address.
- `domain` (string): the local domain used for short hostname lookups.
- `search` (list of strings): list of priority ordered search domains for short hostname lookups. Will be preferred over `domain` by most resolvers.
- `options` (list of strings): list of options that can be passed to the resolver
See [CNI Plugin Result](#result) section for more information.
Errors and logs are communicated in the same way as the CNI plugin. See [CNI Plugin Result](#result) section for details.
IPAM plugin examples:
@ -200,10 +250,8 @@ IPAM plugin examples:
- **dhcp**: Use DHCP protocol to acquire and maintain a lease. The DHCP requests will be sent via the created container interface; therefore, the associated network must support broadcast.
#### Notes
- Routes are expected to be added with a 0 metric.
- A default route may be specified via "0.0.0.0/0". Since another network might have already configured the default route, the CNI plugin should be prepared to skip over its default route definition.
## Open Questions
- Should CNI define anything regarding DNS? For example, generating /etc/resolv.conf
- Should CNI provide /etc/hosts?
## Well-known Error Codes
- `1` - Incompatible CNI version

21
build
View File

@ -1,6 +1,7 @@
#!/bin/bash -e
#!/usr/bin/env bash
set -e
ORG_PATH="github.com/appc"
ORG_PATH="github.com/containernetworking"
REPO_PATH="${ORG_PATH}/cni"
if [ ! -h gopath/src/${REPO_PATH} ]; then
@ -8,20 +9,22 @@ if [ ! -h gopath/src/${REPO_PATH} ]; then
ln -s ../../../.. gopath/src/${REPO_PATH} || exit 255
fi
export GO15VENDOREXPERIMENT=1
export GOBIN=${PWD}/bin
export GOPATH=${PWD}/gopath:$(pwd)/Godeps/_workspace
export GOPATH=${PWD}/gopath
echo "Building API"
go build "$@" ${REPO_PATH}/libcni
echo "Building reference CLI"
go install "$@" ${REPO_PATH}/cnitool
echo "Building plugins"
PLUGINS="plugins/meta/* plugins/main/* plugins/ipam/*"
for d in $PLUGINS; do
if [ -d $d ]; then
plugin=$(basename $d)
echo " " $plugin
go install ${REPO_PATH}/$d
go install "$@" ${REPO_PATH}/$d
fi
done
if [ ! -h $GOBIN/host-local-ptp ]; then
ln -s host-local $GOBIN/host-local-ptp
fi

87
cnitool/cni.go Normal file
View File

@ -0,0 +1,87 @@
// Copyright 2015 CoreOS, Inc.
//
// 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 main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/containernetworking/cni/libcni"
)
const (
EnvCNIPath = "CNI_PATH"
EnvNetDir = "NETCONFPATH"
DefaultNetDir = "/etc/cni/net.d"
CmdAdd = "add"
CmdDel = "del"
)
func main() {
if len(os.Args) < 3 {
usage()
return
}
netdir := os.Getenv(EnvNetDir)
if netdir == "" {
netdir = DefaultNetDir
}
netconf, err := libcni.LoadConf(netdir, os.Args[2])
if err != nil {
exit(err)
}
netns := os.Args[3]
cninet := &libcni.CNIConfig{
Path: strings.Split(os.Getenv(EnvCNIPath), ":"),
}
rt := &libcni.RuntimeConf{
ContainerID: "cni",
NetNS: netns,
IfName: "eth0",
}
switch os.Args[1] {
case CmdAdd:
_, err := cninet.AddNetwork(netconf, rt)
exit(err)
case CmdDel:
exit(cninet.DelNetwork(netconf, rt))
}
}
func usage() {
exe := filepath.Base(os.Args[0])
fmt.Fprintf(os.Stderr, "%s: Add or remove network interfaces from a network namespace\n", exe)
fmt.Fprintf(os.Stderr, " %s %s <net> <netns>\n", exe, CmdAdd)
fmt.Fprintf(os.Stderr, " %s %s <net> <netns>\n", exe, CmdDel)
os.Exit(1)
}
func exit(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
os.Exit(0)
}

73
libcni/api.go Normal file
View File

@ -0,0 +1,73 @@
// Copyright 2015 CNI 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.
package libcni
import (
"strings"
"github.com/containernetworking/cni/pkg/invoke"
"github.com/containernetworking/cni/pkg/types"
)
type RuntimeConf struct {
ContainerID string
NetNS string
IfName string
Args [][2]string
}
type NetworkConfig struct {
Network *types.NetConf
Bytes []byte
}
type CNI interface {
AddNetwork(net *NetworkConfig, rt *RuntimeConf) (*types.Result, error)
DelNetwork(net *NetworkConfig, rt *RuntimeConf) error
}
type CNIConfig struct {
Path []string
}
func (c *CNIConfig) AddNetwork(net *NetworkConfig, rt *RuntimeConf) (*types.Result, error) {
pluginPath, err := invoke.FindInPath(net.Network.Type, c.Path)
if err != nil {
return nil, err
}
return invoke.ExecPluginWithResult(pluginPath, net.Bytes, c.args("ADD", rt))
}
func (c *CNIConfig) DelNetwork(net *NetworkConfig, rt *RuntimeConf) error {
pluginPath, err := invoke.FindInPath(net.Network.Type, c.Path)
if err != nil {
return err
}
return invoke.ExecPluginWithoutResult(pluginPath, net.Bytes, c.args("DEL", rt))
}
// =====
func (c *CNIConfig) args(action string, rt *RuntimeConf) *invoke.Args {
return &invoke.Args{
Command: action,
ContainerID: rt.ContainerID,
NetNS: rt.NetNS,
PluginArgs: rt.Args,
IfName: rt.IfName,
Path: strings.Join(c.Path, ":"),
}
}

85
libcni/conf.go Normal file
View File

@ -0,0 +1,85 @@
// Copyright 2015 CNI 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.
package libcni
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
)
func ConfFromBytes(bytes []byte) (*NetworkConfig, error) {
conf := &NetworkConfig{Bytes: bytes}
if err := json.Unmarshal(bytes, &conf.Network); err != nil {
return nil, fmt.Errorf("error parsing configuration: %s", err)
}
return conf, nil
}
func ConfFromFile(filename string) (*NetworkConfig, error) {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("error reading %s: %s", filename, err)
}
return ConfFromBytes(bytes)
}
func ConfFiles(dir string) ([]string, error) {
// In part, adapted from rkt/networking/podenv.go#listFiles
files, err := ioutil.ReadDir(dir)
switch {
case err == nil: // break
case os.IsNotExist(err):
return nil, nil
default:
return nil, err
}
confFiles := []string{}
for _, f := range files {
if f.IsDir() {
continue
}
if filepath.Ext(f.Name()) == ".conf" {
confFiles = append(confFiles, filepath.Join(dir, f.Name()))
}
}
return confFiles, nil
}
func LoadConf(dir, name string) (*NetworkConfig, error) {
files, err := ConfFiles(dir)
switch {
case err != nil:
return nil, err
case len(files) == 0:
return nil, fmt.Errorf("no net configurations found")
}
sort.Strings(files)
for _, confFile := range files {
conf, err := ConfFromFile(confFile)
if err != nil {
return nil, err
}
if conf.Network.Name == name {
return conf, nil
}
}
return nil, fmt.Errorf(`no net configuration with name "%s" in %s`, name, dir)
}

76
pkg/invoke/args.go Normal file
View File

@ -0,0 +1,76 @@
// Copyright 2015 CNI 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.
package invoke
import (
"os"
"strings"
)
type CNIArgs interface {
// For use with os/exec; i.e., return nil to inherit the
// environment from this process
AsEnv() []string
}
type inherited struct{}
var inheritArgsFromEnv inherited
func (_ *inherited) AsEnv() []string {
return nil
}
func ArgsFromEnv() CNIArgs {
return &inheritArgsFromEnv
}
type Args struct {
Command string
ContainerID string
NetNS string
PluginArgs [][2]string
PluginArgsStr string
IfName string
Path string
}
func (args *Args) AsEnv() []string {
env := os.Environ()
pluginArgsStr := args.PluginArgsStr
if pluginArgsStr == "" {
pluginArgsStr = stringify(args.PluginArgs)
}
env = append(env,
"CNI_COMMAND="+args.Command,
"CNI_CONTAINERID="+args.ContainerID,
"CNI_NETNS="+args.NetNS,
"CNI_ARGS="+pluginArgsStr,
"CNI_IFNAME="+args.IfName,
"CNI_PATH="+args.Path)
return env
}
// taken from rkt/networking/net_plugin.go
func stringify(pluginArgs [][2]string) string {
entries := make([]string, len(pluginArgs))
for i, kv := range pluginArgs {
entries[i] = strings.Join(kv[:], "=")
}
return strings.Join(entries, ";")
}

53
pkg/invoke/delegate.go Normal file
View File

@ -0,0 +1,53 @@
// Copyright 2016 CNI 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.
package invoke
import (
"fmt"
"os"
"strings"
"github.com/containernetworking/cni/pkg/types"
)
func DelegateAdd(delegatePlugin string, netconf []byte) (*types.Result, error) {
if os.Getenv("CNI_COMMAND") != "ADD" {
return nil, fmt.Errorf("CNI_COMMAND is not ADD")
}
paths := strings.Split(os.Getenv("CNI_PATH"), ":")
pluginPath, err := FindInPath(delegatePlugin, paths)
if err != nil {
return nil, err
}
return ExecPluginWithResult(pluginPath, netconf, ArgsFromEnv())
}
func DelegateDel(delegatePlugin string, netconf []byte) error {
if os.Getenv("CNI_COMMAND") != "DEL" {
return fmt.Errorf("CNI_COMMAND is not DEL")
}
paths := strings.Split(os.Getenv("CNI_PATH"), ":")
pluginPath, err := FindInPath(delegatePlugin, paths)
if err != nil {
return err
}
return ExecPluginWithoutResult(pluginPath, netconf, ArgsFromEnv())
}

75
pkg/invoke/exec.go Normal file
View File

@ -0,0 +1,75 @@
// Copyright 2015 CNI 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.
package invoke
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"github.com/containernetworking/cni/pkg/types"
)
func pluginErr(err error, output []byte) error {
if _, ok := err.(*exec.ExitError); ok {
emsg := types.Error{}
if perr := json.Unmarshal(output, &emsg); perr != nil {
return fmt.Errorf("netplugin failed but error parsing its diagnostic message %q: %v", string(output), perr)
}
details := ""
if emsg.Details != "" {
details = fmt.Sprintf("; %v", emsg.Details)
}
return fmt.Errorf("%v%v", emsg.Msg, details)
}
return err
}
func ExecPluginWithResult(pluginPath string, netconf []byte, args CNIArgs) (*types.Result, error) {
stdoutBytes, err := execPlugin(pluginPath, netconf, args)
if err != nil {
return nil, err
}
res := &types.Result{}
err = json.Unmarshal(stdoutBytes, res)
return res, err
}
func ExecPluginWithoutResult(pluginPath string, netconf []byte, args CNIArgs) error {
_, err := execPlugin(pluginPath, netconf, args)
return err
}
func execPlugin(pluginPath string, netconf []byte, args CNIArgs) ([]byte, error) {
stdout := &bytes.Buffer{}
c := exec.Cmd{
Env: args.AsEnv(),
Path: pluginPath,
Args: []string{pluginPath},
Stdin: bytes.NewBuffer(netconf),
Stdout: stdout,
Stderr: os.Stderr,
}
if err := c.Run(); err != nil {
return nil, pluginErr(err, stdout.Bytes())
}
return stdout.Bytes(), nil
}

47
pkg/invoke/find.go Normal file
View File

@ -0,0 +1,47 @@
// Copyright 2015 CNI 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.
package invoke
import (
"fmt"
"os"
"path/filepath"
)
// FindInPath returns the full path of the plugin by searching in the provided path
func FindInPath(plugin string, paths []string) (string, error) {
if plugin == "" {
return "", fmt.Errorf("no plugin name provided")
}
if len(paths) == 0 {
return "", fmt.Errorf("no paths provided")
}
var fullpath string
for _, path := range paths {
full := filepath.Join(path, plugin)
if fi, err := os.Stat(full); err == nil && fi.Mode().IsRegular() {
fullpath = full
break
}
}
if fullpath == "" {
return "", fmt.Errorf("failed to find plugin %q in path %s", plugin, paths)
}
return fullpath, nil
}

78
pkg/invoke/find_test.go Normal file
View File

@ -0,0 +1,78 @@
// Copyright 2016 CNI 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.
package invoke_test
import (
"fmt"
"io/ioutil"
"path/filepath"
"github.com/containernetworking/cni/pkg/invoke"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("FindInPath", func() {
var (
multiplePaths []string
pluginName string
pluginDir string
anotherTempDir string
)
BeforeEach(func() {
tempDir, err := ioutil.TempDir("", "cni-find")
Expect(err).NotTo(HaveOccurred())
plugin, err := ioutil.TempFile(tempDir, "a-cni-plugin")
anotherTempDir, err = ioutil.TempDir("", "nothing-here")
multiplePaths = []string{anotherTempDir, tempDir}
pluginDir, pluginName = filepath.Split(plugin.Name())
})
Context("when multiple paths are provided", func() {
It("returns only the path to the plugin", func() {
pluginPath, err := invoke.FindInPath(pluginName, multiplePaths)
Expect(err).NotTo(HaveOccurred())
Expect(pluginPath).To(Equal(filepath.Join(pluginDir, pluginName)))
})
})
Context("when an error occurs", func() {
Context("when no paths are provided", func() {
It("returns an error noting no paths were provided", func() {
_, err := invoke.FindInPath(pluginName, []string{})
Expect(err).To(MatchError("no paths provided"))
})
})
Context("when no plugin is provided", func() {
It("returns an error noting the plugin name wasn't found", func() {
_, err := invoke.FindInPath("", multiplePaths)
Expect(err).To(MatchError("no plugin name provided"))
})
})
Context("when the plugin cannot be found", func() {
It("returns an error noting the path", func() {
pathsWithNothing := []string{anotherTempDir}
_, err := invoke.FindInPath(pluginName, pathsWithNothing)
Expect(err).To(MatchError(fmt.Sprintf("failed to find plugin %q in path %s", pluginName, pathsWithNothing)))
})
})
})
})

View File

@ -0,0 +1,27 @@
// Copyright 2016 CNI 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.
package invoke_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestInvoke(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Invoke Suite")
}

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -15,23 +15,10 @@
package ip
import (
"encoding/json"
"math/big"
"net"
)
// ParseCIDR takes a string like "10.2.3.1/24" and
// return IPNet with "10.2.3.1" and /24 mask
func ParseCIDR(s string) (*net.IPNet, error) {
ip, ipn, err := net.ParseCIDR(s)
if err != nil {
return nil, err
}
ipn.IP = ip
return ipn, nil
}
// NextIP returns IP incremented by 1
func NextIP(ip net.IP) net.IP {
i := ipToInt(ip)
@ -62,25 +49,3 @@ func Network(ipn *net.IPNet) *net.IPNet {
Mask: ipn.Mask,
}
}
// like net.IPNet but adds JSON marshalling and unmarshalling
type IPNet net.IPNet
func (n IPNet) MarshalJSON() ([]byte, error) {
return json.Marshal((*net.IPNet)(&n).String())
}
func (n *IPNet) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
tmp, err := ParseCIDR(s)
if err != nil {
return err
}
*n = IPNet(*tmp)
return nil
}

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -23,10 +23,10 @@ import (
// SetupIPMasq installs iptables rules to masquerade traffic
// coming from ipn and going outside of it
func SetupIPMasq(ipn *net.IPNet, chain string) error {
func SetupIPMasq(ipn *net.IPNet, chain string, comment string) error {
ipt, err := iptables.New()
if err != nil {
return fmt.Errorf("failed to locate iptabes: %v", err)
return fmt.Errorf("failed to locate iptables: %v", err)
}
if err = ipt.NewChain("nat", chain); err != nil {
@ -36,25 +36,25 @@ func SetupIPMasq(ipn *net.IPNet, chain string) error {
}
}
if err = ipt.AppendUnique("nat", chain, "-d", ipn.String(), "-j", "ACCEPT"); err != nil {
if err = ipt.AppendUnique("nat", chain, "-d", ipn.String(), "-j", "ACCEPT", "-m", "comment", "--comment", comment); err != nil {
return err
}
if err = ipt.AppendUnique("nat", chain, "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE"); err != nil {
if err = ipt.AppendUnique("nat", chain, "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE", "-m", "comment", "--comment", comment); err != nil {
return err
}
return ipt.AppendUnique("nat", "POSTROUTING", "-s", ipn.String(), "-j", chain)
return ipt.AppendUnique("nat", "POSTROUTING", "-s", ipn.String(), "-j", chain, "-m", "comment", "--comment", comment)
}
// TeardownIPMasq undoes the effects of SetupIPMasq
func TeardownIPMasq(ipn *net.IPNet, chain string) error {
func TeardownIPMasq(ipn *net.IPNet, chain string, comment string) error {
ipt, err := iptables.New()
if err != nil {
return fmt.Errorf("failed to locate iptabes: %v", err)
return fmt.Errorf("failed to locate iptables: %v", err)
}
if err = ipt.Delete("nat", "POSTROUTING", "-s", ipn.String(), "-j", chain); err != nil {
if err = ipt.Delete("nat", "POSTROUTING", "-s", ipn.String(), "-j", chain, "-m", "comment", "--comment", comment); err != nil {
return err
}

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -20,6 +20,7 @@ import (
"net"
"os"
"github.com/containernetworking/cni/pkg/ns"
"github.com/vishvananda/netlink"
)
@ -78,8 +79,9 @@ func RandomVethName() (string, error) {
}
// SetupVeth sets up a virtual ethernet link.
// Should be in container netns.
func SetupVeth(contVethName string, mtu int, hostNS *os.File) (hostVeth, contVeth netlink.Link, err error) {
// Should be in container netns, and will switch back to hostNS to set the host
// veth end up.
func SetupVeth(contVethName string, mtu int, hostNS ns.NetNS) (hostVeth, contVeth netlink.Link, err error) {
var hostVethName string
hostVethName, contVeth, err = makeVeth(contVethName, mtu)
if err != nil {
@ -97,16 +99,22 @@ func SetupVeth(contVethName string, mtu int, hostNS *os.File) (hostVeth, contVet
return
}
if err = netlink.LinkSetUp(hostVeth); err != nil {
err = fmt.Errorf("failed to set %q up: %v", contVethName, err)
return
}
if err = netlink.LinkSetNsFd(hostVeth, int(hostNS.Fd())); err != nil {
err = fmt.Errorf("failed to move veth to host netns: %v", err)
return
}
err = hostNS.Do(func(_ ns.NetNS) error {
hostVeth, err := netlink.LinkByName(hostVethName)
if err != nil {
return fmt.Errorf("failed to lookup %q in %q: %v", hostVethName, hostNS.Path(), err)
}
if err = netlink.LinkSetUp(hostVeth); err != nil {
return fmt.Errorf("failed to set %q up: %v", hostVethName, err)
}
return nil
})
return
}

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

68
pkg/ipam/ipam.go Normal file
View File

@ -0,0 +1,68 @@
// Copyright 2015 CNI 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.
package ipam
import (
"fmt"
"os"
"github.com/containernetworking/cni/pkg/invoke"
"github.com/containernetworking/cni/pkg/ip"
"github.com/containernetworking/cni/pkg/types"
"github.com/vishvananda/netlink"
)
func ExecAdd(plugin string, netconf []byte) (*types.Result, error) {
return invoke.DelegateAdd(plugin, netconf)
}
func ExecDel(plugin string, netconf []byte) error {
return invoke.DelegateDel(plugin, netconf)
}
// ConfigureIface takes the result of IPAM plugin and
// applies to the ifName interface
func ConfigureIface(ifName string, res *types.Result) error {
link, err := netlink.LinkByName(ifName)
if err != nil {
return fmt.Errorf("failed to lookup %q: %v", ifName, err)
}
if err := netlink.LinkSetUp(link); err != nil {
return fmt.Errorf("failed to set %q UP: %v", ifName, err)
}
// TODO(eyakubovich): IPv6
addr := &netlink.Addr{IPNet: &res.IP4.IP, Label: ""}
if err = netlink.AddrAdd(link, addr); err != nil {
return fmt.Errorf("failed to add IP addr to %q: %v", ifName, err)
}
for _, r := range res.IP4.Routes {
gw := r.GW
if gw == nil {
gw = res.IP4.Gateway
}
if err = ip.AddRoute(&r.Dst, gw, link); err != nil {
// we skip over duplicate routes as we assume the first one wins
if !os.IsExist(err) {
return fmt.Errorf("failed to add route '%v via %v dev %v': %v", r.Dst, gw, ifName, err)
}
}
}
return nil
}

31
pkg/ns/README.md Normal file
View File

@ -0,0 +1,31 @@
### Namespaces, Threads, and Go
On Linux each OS thread can have a different network namespace. Go's thread scheduling model switches goroutines between OS threads based on OS thread load and whether the goroutine would block other goroutines. This can result in a goroutine switching network namespaces without notice and lead to errors in your code.
### Namespace Switching
Switching namespaces with the `ns.Set()` method is not recommended without additional strategies to prevent unexpected namespace changes when your goroutines switch OS threads.
Go provides the `runtime.LockOSThread()` function to ensure a specific goroutine executes on its current OS thread and prevents any other goroutine from running in that thread until the locked one exits. Careful usage of `LockOSThread()` and goroutines can provide good control over which network namespace a given goroutine executes in.
For example, you cannot rely on the `ns.Set()` namespace being the current namespace after the `Set()` call unless you do two things. First, the goroutine calling `Set()` must have previously called `LockOSThread()`. Second, you must ensure `runtime.UnlockOSThread()` is not called somewhere in-between. You also cannot rely on the initial network namespace remaining the current network namespace if any other code in your program switches namespaces, unless you have already called `LockOSThread()` in that goroutine. Note that `LockOSThread()` prevents the Go scheduler from optimally scheduling goroutines for best performance, so `LockOSThread()` should only be used in small, isolated goroutines that release the lock quickly.
### Do() The Recommended Thing
The `ns.Do()` method provides control over network namespaces for you by implementing these strategies. All code dependent on a particular network namespace should be wrapped in the `ns.Do()` method to ensure the correct namespace is selected for the duration of your code. For example:
```go
targetNs, err := ns.NewNS()
if err != nil {
return err
}
err = targetNs.Do(func(hostNs ns.NetNS) error {
dummy := &netlink.Dummy{
LinkAttrs: netlink.LinkAttrs{
Name: "dummy0",
},
}
return netlink.LinkAdd(dummy)
})
```
### Further Reading
- https://github.com/golang/go/wiki/LockOSThread
- http://morsmachine.dk/go-scheduler

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -15,78 +15,301 @@
package ns
import (
"crypto/rand"
"fmt"
"os"
"path"
"runtime"
"strings"
"sync"
"syscall"
"golang.org/x/sys/unix"
)
var setNsMap = map[string]uintptr{
"386": 346,
"amd64": 308,
"arm": 374,
type NetNS interface {
// Executes the passed closure in this object's network namespace,
// attemtping to restore the original namespace before returning.
// However, since each OS thread can have a different network namespace,
// and Go's thread scheduling is highly variable, callers cannot
// guarantee any specific namespace is set unless operations that
// require that namespace are wrapped with Do(). Also, no code called
// from Do() should call runtime.UnlockOSThread(), or the risk
// of executing code in an incorrect namespace will be greater. See
// https://github.com/golang/go/wiki/LockOSThread for further details.
Do(toRun func(NetNS) error) error
// Sets the current network namespace to this object's network namespace.
// Note that since Go's thread scheduling is highly variable, callers
// cannot guarantee the requested namespace will be the current namespace
// after this function is called; to ensure this wrap operations that
// require the namespace with Do() instead.
Set() error
// Returns the filesystem path representing this object's network namespace
Path() string
// Returns a file descriptor representing this object's network namespace
Fd() uintptr
// Cleans up this instance of the network namespace; if this instance
// is the last user the namespace will be destroyed
Close() error
}
// SetNS sets the network namespace on a target file.
func SetNS(f *os.File, flags uintptr) error {
if runtime.GOOS != "linux" {
return fmt.Errorf("unsupported OS: %s", runtime.GOOS)
}
type netNS struct {
file *os.File
mounted bool
closed bool
}
trap, ok := setNsMap[runtime.GOARCH]
if !ok {
return fmt.Errorf("unsupported arch: %s", runtime.GOARCH)
}
func getCurrentThreadNetNSPath() string {
// /proc/self/ns/net returns the namespace of the main thread, not
// of whatever thread this goroutine is running on. Make sure we
// use the thread's net namespace since the thread is switching around
return fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), unix.Gettid())
}
_, _, err := syscall.RawSyscall(trap, f.Fd(), flags, 0)
if err != 0 {
// Returns an object representing the current OS thread's network namespace
func GetCurrentNS() (NetNS, error) {
return GetNS(getCurrentThreadNetNSPath())
}
const (
// https://github.com/torvalds/linux/blob/master/include/uapi/linux/magic.h
NSFS_MAGIC = 0x6e736673
PROCFS_MAGIC = 0x9fa0
)
type NSPathNotExistErr struct{ msg string }
func (e NSPathNotExistErr) Error() string { return e.msg }
type NSPathNotNSErr struct{ msg string }
func (e NSPathNotNSErr) Error() string { return e.msg }
func IsNSorErr(nspath string) error {
stat := syscall.Statfs_t{}
if err := syscall.Statfs(nspath, &stat); err != nil {
if os.IsNotExist(err) {
err = NSPathNotExistErr{msg: fmt.Sprintf("failed to Statfs %q: %v", nspath, err)}
} else {
err = fmt.Errorf("failed to Statfs %q: %v", nspath, err)
}
return err
}
switch stat.Type {
case PROCFS_MAGIC:
// Kernel < 3.19
validPathContent := "ns/"
validName := strings.Contains(nspath, validPathContent)
if !validName {
return NSPathNotNSErr{msg: fmt.Sprintf("path %q doesn't contain %q", nspath, validPathContent)}
}
return nil
case NSFS_MAGIC:
// Kernel >= 3.19
return nil
default:
return NSPathNotNSErr{msg: fmt.Sprintf("unknown FS magic on %q: %x", nspath, stat.Type)}
}
}
// Returns an object representing the namespace referred to by @path
func GetNS(nspath string) (NetNS, error) {
err := IsNSorErr(nspath)
if err != nil {
return nil, err
}
fd, err := os.Open(nspath)
if err != nil {
return nil, err
}
return &netNS{file: fd}, nil
}
// Creates a new persistent network namespace and returns an object
// representing that namespace, without switching to it
func NewNS() (NetNS, error) {
const nsRunDir = "/var/run/netns"
b := make([]byte, 16)
_, err := rand.Reader.Read(b)
if err != nil {
return nil, fmt.Errorf("failed to generate random netns name: %v", err)
}
err = os.MkdirAll(nsRunDir, 0755)
if err != nil {
return nil, err
}
// create an empty file at the mount point
nsName := fmt.Sprintf("cni-%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
nsPath := path.Join(nsRunDir, nsName)
mountPointFd, err := os.Create(nsPath)
if err != nil {
return nil, err
}
mountPointFd.Close()
// Ensure the mount point is cleaned up on errors; if the namespace
// was successfully mounted this will have no effect because the file
// is in-use
defer os.RemoveAll(nsPath)
var wg sync.WaitGroup
wg.Add(1)
// do namespace work in a dedicated goroutine, so that we can safely
// Lock/Unlock OSThread without upsetting the lock/unlock state of
// the caller of this function
var fd *os.File
go (func() {
defer wg.Done()
runtime.LockOSThread()
var origNS NetNS
origNS, err = GetNS(getCurrentThreadNetNSPath())
if err != nil {
return
}
defer origNS.Close()
// create a new netns on the current thread
err = unix.Unshare(unix.CLONE_NEWNET)
if err != nil {
return
}
defer origNS.Set()
// bind mount the new netns from the current thread onto the mount point
err = unix.Mount(getCurrentThreadNetNSPath(), nsPath, "none", unix.MS_BIND, "")
if err != nil {
return
}
fd, err = os.Open(nsPath)
if err != nil {
return
}
})()
wg.Wait()
if err != nil {
unix.Unmount(nsPath, unix.MNT_DETACH)
return nil, fmt.Errorf("failed to create namespace: %v", err)
}
return &netNS{file: fd, mounted: true}, nil
}
func (ns *netNS) Path() string {
return ns.file.Name()
}
func (ns *netNS) Fd() uintptr {
return ns.file.Fd()
}
func (ns *netNS) errorIfClosed() error {
if ns.closed {
return fmt.Errorf("%q has already been closed", ns.file.Name())
}
return nil
}
func (ns *netNS) Close() error {
if err := ns.errorIfClosed(); err != nil {
return err
}
if err := ns.file.Close(); err != nil {
return fmt.Errorf("Failed to close %q: %v", ns.file.Name(), err)
}
ns.closed = true
if ns.mounted {
if err := unix.Unmount(ns.file.Name(), unix.MNT_DETACH); err != nil {
return fmt.Errorf("Failed to unmount namespace %s: %v", ns.file.Name(), err)
}
if err := os.RemoveAll(ns.file.Name()); err != nil {
return fmt.Errorf("Failed to clean up namespace %s: %v", ns.file.Name(), err)
}
ns.mounted = false
}
return nil
}
func (ns *netNS) Do(toRun func(NetNS) error) error {
if err := ns.errorIfClosed(); err != nil {
return err
}
containedCall := func(hostNS NetNS) error {
threadNS, err := GetNS(getCurrentThreadNetNSPath())
if err != nil {
return fmt.Errorf("failed to open current netns: %v", err)
}
defer threadNS.Close()
// switch to target namespace
if err = ns.Set(); err != nil {
return fmt.Errorf("error switching to ns %v: %v", ns.file.Name(), err)
}
defer threadNS.Set() // switch back
return toRun(hostNS)
}
// save a handle to current network namespace
hostNS, err := GetNS(getCurrentThreadNetNSPath())
if err != nil {
return fmt.Errorf("Failed to open current namespace: %v", err)
}
defer hostNS.Close()
var wg sync.WaitGroup
wg.Add(1)
var innerError error
go func() {
defer wg.Done()
runtime.LockOSThread()
innerError = containedCall(hostNS)
}()
wg.Wait()
return innerError
}
func (ns *netNS) Set() error {
if err := ns.errorIfClosed(); err != nil {
return err
}
if _, _, err := unix.Syscall(unix.SYS_SETNS, ns.Fd(), uintptr(unix.CLONE_NEWNET), 0); err != 0 {
return fmt.Errorf("Error switching to ns %v: %v", ns.file.Name(), err)
}
return nil
}
// WithNetNSPath executes the passed closure under the given network
// namespace, restoring the original namespace afterwards.
// Changing namespaces must be done on a goroutine that has been
// locked to an OS thread. If lockThread arg is true, this function
// locks the goroutine prior to change namespace and unlocks before
// returning
func WithNetNSPath(nspath string, lockThread bool, f func(*os.File) error) error {
ns, err := os.Open(nspath)
func WithNetNSPath(nspath string, toRun func(NetNS) error) error {
ns, err := GetNS(nspath)
if err != nil {
return fmt.Errorf("Failed to open %v: %v", nspath, err)
}
defer ns.Close()
return WithNetNS(ns, lockThread, f)
}
// WithNetNS executes the passed closure under the given network
// namespace, restoring the original namespace afterwards.
// Changing namespaces must be done on a goroutine that has been
// locked to an OS thread. If lockThread arg is true, this function
// locks the goroutine prior to change namespace and unlocks before
// returning
func WithNetNS(ns *os.File, lockThread bool, f func(*os.File) error) error {
if lockThread {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
}
// save a handle to current (host) network namespace
thisNS, err := os.Open("/proc/self/ns/net")
if err != nil {
return fmt.Errorf("Failed to open /proc/self/ns/net: %v", err)
}
defer thisNS.Close()
if err = SetNS(ns, syscall.CLONE_NEWNET); err != nil {
return fmt.Errorf("Error switching to ns %v: %v", ns.Name(), err)
}
if err = f(thisNS); err != nil {
return err
}
// switch back
return SetNS(thisNS, syscall.CLONE_NEWNET)
defer ns.Close()
return ns.Do(toRun)
}

34
pkg/ns/ns_suite_test.go Normal file
View File

@ -0,0 +1,34 @@
// Copyright 2016 CNI 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.
package ns_test
import (
"math/rand"
"runtime"
. "github.com/onsi/ginkgo"
"github.com/onsi/ginkgo/config"
. "github.com/onsi/gomega"
"testing"
)
func TestNs(t *testing.T) {
rand.Seed(config.GinkgoConfig.RandomSeed)
runtime.LockOSThread()
RegisterFailHandler(Fail)
RunSpecs(t, "pkg/ns Suite")
}

252
pkg/ns/ns_test.go Normal file
View File

@ -0,0 +1,252 @@
// Copyright 2016 CNI 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.
package ns_test
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/containernetworking/cni/pkg/ns"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"golang.org/x/sys/unix"
)
func getInodeCurNetNS() (uint64, error) {
curNS, err := ns.GetCurrentNS()
if err != nil {
return 0, err
}
defer curNS.Close()
return getInodeNS(curNS)
}
func getInodeNS(netns ns.NetNS) (uint64, error) {
return getInodeFd(int(netns.Fd()))
}
func getInode(path string) (uint64, error) {
file, err := os.Open(path)
if err != nil {
return 0, err
}
defer file.Close()
return getInodeFd(int(file.Fd()))
}
func getInodeFd(fd int) (uint64, error) {
stat := &unix.Stat_t{}
err := unix.Fstat(fd, stat)
return stat.Ino, err
}
var _ = Describe("Linux namespace operations", func() {
Describe("WithNetNS", func() {
var (
originalNetNS ns.NetNS
targetNetNS ns.NetNS
)
BeforeEach(func() {
var err error
originalNetNS, err = ns.NewNS()
Expect(err).NotTo(HaveOccurred())
targetNetNS, err = ns.NewNS()
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
Expect(targetNetNS.Close()).To(Succeed())
Expect(originalNetNS.Close()).To(Succeed())
})
It("executes the callback within the target network namespace", func() {
expectedInode, err := getInodeNS(targetNetNS)
Expect(err).NotTo(HaveOccurred())
err = targetNetNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
actualInode, err := getInodeCurNetNS()
Expect(err).NotTo(HaveOccurred())
Expect(actualInode).To(Equal(expectedInode))
return nil
})
Expect(err).NotTo(HaveOccurred())
})
It("provides the original namespace as the argument to the callback", func() {
// Ensure we start in originalNetNS
err := originalNetNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
origNSInode, err := getInodeNS(originalNetNS)
Expect(err).NotTo(HaveOccurred())
err = targetNetNS.Do(func(hostNS ns.NetNS) error {
defer GinkgoRecover()
hostNSInode, err := getInodeNS(hostNS)
Expect(err).NotTo(HaveOccurred())
Expect(hostNSInode).To(Equal(origNSInode))
return nil
})
return nil
})
Expect(err).NotTo(HaveOccurred())
})
Context("when the callback returns an error", func() {
It("restores the calling thread to the original namespace before returning", func() {
err := originalNetNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
preTestInode, err := getInodeCurNetNS()
Expect(err).NotTo(HaveOccurred())
_ = targetNetNS.Do(func(ns.NetNS) error {
return errors.New("potato")
})
postTestInode, err := getInodeCurNetNS()
Expect(err).NotTo(HaveOccurred())
Expect(postTestInode).To(Equal(preTestInode))
return nil
})
Expect(err).NotTo(HaveOccurred())
})
It("returns the error from the callback", func() {
err := targetNetNS.Do(func(ns.NetNS) error {
return errors.New("potato")
})
Expect(err).To(MatchError("potato"))
})
})
Describe("validating inode mapping to namespaces", func() {
It("checks that different namespaces have different inodes", func() {
origNSInode, err := getInodeNS(originalNetNS)
Expect(err).NotTo(HaveOccurred())
testNsInode, err := getInodeNS(targetNetNS)
Expect(err).NotTo(HaveOccurred())
Expect(testNsInode).NotTo(Equal(0))
Expect(testNsInode).NotTo(Equal(origNSInode))
})
It("should not leak a closed netns onto any threads in the process", func() {
By("creating a new netns")
createdNetNS, err := ns.NewNS()
Expect(err).NotTo(HaveOccurred())
By("discovering the inode of the created netns")
createdNetNSInode, err := getInodeNS(createdNetNS)
Expect(err).NotTo(HaveOccurred())
createdNetNS.Close()
By("comparing against the netns inode of every thread in the process")
for _, netnsPath := range allNetNSInCurrentProcess() {
netnsInode, err := getInode(netnsPath)
Expect(err).NotTo(HaveOccurred())
Expect(netnsInode).NotTo(Equal(createdNetNSInode))
}
})
It("fails when the path is not a namespace", func() {
tempFile, err := ioutil.TempFile("", "nstest")
Expect(err).NotTo(HaveOccurred())
defer tempFile.Close()
nspath := tempFile.Name()
defer os.Remove(nspath)
_, err = ns.GetNS(nspath)
Expect(err).To(HaveOccurred())
Expect(err).To(BeAssignableToTypeOf(ns.NSPathNotNSErr{}))
Expect(err).NotTo(BeAssignableToTypeOf(ns.NSPathNotExistErr{}))
})
})
Describe("closing a network namespace", func() {
It("should prevent further operations", func() {
createdNetNS, err := ns.NewNS()
Expect(err).NotTo(HaveOccurred())
err = createdNetNS.Close()
Expect(err).NotTo(HaveOccurred())
err = createdNetNS.Do(func(ns.NetNS) error { return nil })
Expect(err).To(HaveOccurred())
err = createdNetNS.Set()
Expect(err).To(HaveOccurred())
})
It("should only work once", func() {
createdNetNS, err := ns.NewNS()
Expect(err).NotTo(HaveOccurred())
err = createdNetNS.Close()
Expect(err).NotTo(HaveOccurred())
err = createdNetNS.Close()
Expect(err).To(HaveOccurred())
})
})
})
Describe("IsNSorErr", func() {
It("should detect a namespace", func() {
createdNetNS, err := ns.NewNS()
err = ns.IsNSorErr(createdNetNS.Path())
Expect(err).NotTo(HaveOccurred())
})
It("should refuse other paths", func() {
tempFile, err := ioutil.TempFile("", "nstest")
Expect(err).NotTo(HaveOccurred())
defer tempFile.Close()
nspath := tempFile.Name()
defer os.Remove(nspath)
err = ns.IsNSorErr(nspath)
Expect(err).To(HaveOccurred())
Expect(err).To(BeAssignableToTypeOf(ns.NSPathNotNSErr{}))
Expect(err).NotTo(BeAssignableToTypeOf(ns.NSPathNotExistErr{}))
})
It("should error on non-existing paths", func() {
err := ns.IsNSorErr("/tmp/IDoNotExist")
Expect(err).To(HaveOccurred())
Expect(err).To(BeAssignableToTypeOf(ns.NSPathNotExistErr{}))
Expect(err).NotTo(BeAssignableToTypeOf(ns.NSPathNotNSErr{}))
})
})
})
func allNetNSInCurrentProcess() []string {
pid := unix.Getpid()
paths, err := filepath.Glob(fmt.Sprintf("/proc/%d/task/*/ns/net", pid))
Expect(err).NotTo(HaveOccurred())
return paths
}

View File

@ -1,148 +0,0 @@
// Copyright 2015 CoreOS, Inc.
//
// 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 plugin
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/appc/cni/pkg/ip"
"github.com/vishvananda/netlink"
)
// Find returns the full path of the plugin by searching in CNI_PATH
func Find(plugin string) string {
paths := strings.Split(os.Getenv("CNI_PATH"), ":")
for _, p := range paths {
fullname := filepath.Join(p, plugin)
if fi, err := os.Stat(fullname); err == nil && fi.Mode().IsRegular() {
return fullname
}
}
return ""
}
func pluginErr(err error, output []byte) error {
if _, ok := err.(*exec.ExitError); ok {
emsg := Error{}
if perr := json.Unmarshal(output, &emsg); perr != nil {
return fmt.Errorf("netplugin failed but error parsing its diagnostic message %q: %v", string(output), perr)
}
details := ""
if emsg.Details != "" {
details = fmt.Sprintf("; %v", emsg.Details)
}
return fmt.Errorf("%v%v", emsg.Msg, details)
}
return err
}
// ExecAdd executes IPAM plugin, assuming CNI_COMMAND == ADD.
// Parses and returns resulting IPConfig
func ExecAdd(plugin string, netconf []byte) (*Result, error) {
if os.Getenv("CNI_COMMAND") != "ADD" {
return nil, fmt.Errorf("CNI_COMMAND is not ADD")
}
pluginPath := Find(plugin)
if pluginPath == "" {
return nil, fmt.Errorf("could not find %q plugin", plugin)
}
stdout := &bytes.Buffer{}
c := exec.Cmd{
Path: pluginPath,
Args: []string{pluginPath},
Stdin: bytes.NewBuffer(netconf),
Stdout: stdout,
Stderr: os.Stderr,
}
if err := c.Run(); err != nil {
return nil, pluginErr(err, stdout.Bytes())
}
res := &Result{}
err := json.Unmarshal(stdout.Bytes(), res)
return res, err
}
// ExecDel executes IPAM plugin, assuming CNI_COMMAND == DEL.
func ExecDel(plugin string, netconf []byte) error {
if os.Getenv("CNI_COMMAND") != "DEL" {
return fmt.Errorf("CNI_COMMAND is not DEL")
}
pluginPath := Find(plugin)
if pluginPath == "" {
return fmt.Errorf("could not find %q plugin", plugin)
}
stdout := &bytes.Buffer{}
c := exec.Cmd{
Path: pluginPath,
Args: []string{pluginPath},
Stdin: bytes.NewBuffer(netconf),
Stdout: stdout,
Stderr: os.Stderr,
}
if err := c.Run(); err != nil {
return pluginErr(err, stdout.Bytes())
}
return nil
}
// ConfigureIface takes the result of IPAM plugin and
// applies to the ifName interface
func ConfigureIface(ifName string, res *Result) error {
link, err := netlink.LinkByName(ifName)
if err != nil {
return fmt.Errorf("failed to lookup %q: %v", ifName, err)
}
if err := netlink.LinkSetUp(link); err != nil {
return fmt.Errorf("failed too set %q UP: %v", ifName, err)
}
// TODO(eyakubovich): IPv6
addr := &netlink.Addr{IPNet: &res.IP4.IP, Label: ""}
if err = netlink.AddrAdd(link, addr); err != nil {
return fmt.Errorf("failed to add IP addr to %q: %v", ifName, err)
}
for _, r := range res.IP4.Routes {
gw := r.GW
if gw == nil {
gw = res.IP4.Gateway
}
if err = ip.AddRoute(&r.Dst, gw, link); err != nil {
// we skip over duplicate routes as we assume the first one wins
if !os.IsExist(err) {
return fmt.Errorf("failed to add route '%v via %v dev %v': %v", r.Dst, gw, ifName, err)
}
}
}
return nil
}

View File

@ -1,4 +1,4 @@
// Copyright 2014 CoreOS, Inc.
// Copyright 2014 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -22,7 +22,7 @@ import (
"log"
"os"
"github.com/appc/cni/pkg/plugin"
"github.com/containernetworking/cni/pkg/types"
)
// CmdArgs captures all the arguments passed in to the plugin
@ -36,28 +36,72 @@ type CmdArgs struct {
StdinData []byte
}
type reqForCmdEntry map[string]bool
// PluginMain is the "main" for a plugin. It accepts
// two callback functions for add and del commands.
func PluginMain(cmdAdd, cmdDel func(_ *CmdArgs) error) {
var cmd, contID, netns, ifName, args, path string
vars := []struct {
name string
val *string
req bool
name string
val *string
reqForCmd reqForCmdEntry
}{
{"CNI_COMMAND", &cmd, true},
{"CNI_CONTAINERID", &contID, false},
{"CNI_NETNS", &netns, true},
{"CNI_IFNAME", &ifName, true},
{"CNI_ARGS", &args, false},
{"CNI_PATH", &path, true},
{
"CNI_COMMAND",
&cmd,
reqForCmdEntry{
"ADD": true,
"DEL": true,
},
},
{
"CNI_CONTAINERID",
&contID,
reqForCmdEntry{
"ADD": false,
"DEL": false,
},
},
{
"CNI_NETNS",
&netns,
reqForCmdEntry{
"ADD": true,
"DEL": false,
},
},
{
"CNI_IFNAME",
&ifName,
reqForCmdEntry{
"ADD": true,
"DEL": true,
},
},
{
"CNI_ARGS",
&args,
reqForCmdEntry{
"ADD": false,
"DEL": false,
},
},
{
"CNI_PATH",
&path,
reqForCmdEntry{
"ADD": true,
"DEL": true,
},
},
}
argsMissing := false
for _, v := range vars {
*v.val = os.Getenv(v.name)
if v.req && *v.val == "" {
if v.reqForCmd[cmd] && *v.val == "" {
log.Printf("%v env variable missing", v.name)
argsMissing = true
}
@ -93,7 +137,7 @@ func PluginMain(cmdAdd, cmdDel func(_ *CmdArgs) error) {
}
if err != nil {
if e, ok := err.(*plugin.Error); ok {
if e, ok := err.(*types.Error); ok {
// don't wrap Error in Error
dieErr(e)
}
@ -102,14 +146,14 @@ func PluginMain(cmdAdd, cmdDel func(_ *CmdArgs) error) {
}
func dieMsg(f string, args ...interface{}) {
e := &plugin.Error{
e := &types.Error{
Code: 100,
Msg: fmt.Sprintf(f, args...),
}
dieErr(e)
}
func dieErr(e *plugin.Error) {
func dieErr(e *types.Error) {
if err := e.Print(); err != nil {
log.Print("Error writing error JSON to stdout: ", err)
}

View File

@ -0,0 +1,27 @@
// Copyright 2016 CNI 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.
package skel
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestSkel(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Skel Suite")
}

84
pkg/skel/skel_test.go Normal file
View File

@ -0,0 +1,84 @@
// Copyright 2016 CNI 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.
package skel
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Skel", func() {
var (
fNoop = func(_ *CmdArgs) error { return nil }
// fErr = func(_ *CmdArgs) error { return errors.New("dummy") }
envVars = []struct {
name string
val string
}{
{"CNI_CONTAINERID", "dummy"},
{"CNI_NETNS", "dummy"},
{"CNI_IFNAME", "dummy"},
{"CNI_ARGS", "dummy"},
{"CNI_PATH", "dummy"},
}
)
It("Must be possible to set the env vars", func() {
for _, v := range envVars {
err := os.Setenv(v.name, v.val)
Expect(err).NotTo(HaveOccurred())
}
})
Context("When dummy environment variables are passed", func() {
It("should not fail with ADD and noop callback", func() {
err := os.Setenv("CNI_COMMAND", "ADD")
Expect(err).NotTo(HaveOccurred())
PluginMain(fNoop, nil)
})
// TODO: figure out howto mock printing and os.Exit()
// It("should fail with ADD and error callback", func() {
// err := os.Setenv("CNI_COMMAND", "ADD")
// Expect(err).NotTo(HaveOccurred())
// PluginMain(fErr, nil)
// })
It("should not fail with DEL and noop callback", func() {
err := os.Setenv("CNI_COMMAND", "DEL")
Expect(err).NotTo(HaveOccurred())
PluginMain(nil, fNoop)
})
// TODO: figure out howto mock printing and os.Exit()
// It("should fail with DEL and error callback", func() {
// err := os.Setenv("CNI_COMMAND", "DEL")
// Expect(err).NotTo(HaveOccurred())
// PluginMain(fErr, nil)
// })
It("should not fail with DEL and no NETNS and noop callback", func() {
err := os.Setenv("CNI_COMMAND", "DEL")
Expect(err).NotTo(HaveOccurred())
err = os.Unsetenv("CNI_NETNS")
Expect(err).NotTo(HaveOccurred())
PluginMain(nil, fNoop)
})
})
})

77
pkg/testutils/cmd.go Normal file
View File

@ -0,0 +1,77 @@
// Copyright 2016 CNI 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.
package testutils
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/containernetworking/cni/pkg/types"
)
func envCleanup() {
os.Unsetenv("CNI_COMMAND")
os.Unsetenv("CNI_PATH")
os.Unsetenv("CNI_NETNS")
os.Unsetenv("CNI_IFNAME")
}
func CmdAddWithResult(cniNetns, cniIfname string, f func() error) (*types.Result, error) {
os.Setenv("CNI_COMMAND", "ADD")
os.Setenv("CNI_PATH", os.Getenv("PATH"))
os.Setenv("CNI_NETNS", cniNetns)
os.Setenv("CNI_IFNAME", cniIfname)
defer envCleanup()
// Redirect stdout to capture plugin result
oldStdout := os.Stdout
r, w, err := os.Pipe()
if err != nil {
return nil, err
}
os.Stdout = w
err = f()
w.Close()
if err != nil {
return nil, err
}
// parse the result
out, err := ioutil.ReadAll(r)
os.Stdout = oldStdout
if err != nil {
return nil, err
}
result := types.Result{}
err = json.Unmarshal(out, &result)
if err != nil {
return nil, err
}
return &result, nil
}
func CmdDelWithResult(cniNetns, cniIfname string, f func() error) error {
os.Setenv("CNI_COMMAND", "DEL")
os.Setenv("CNI_PATH", os.Getenv("PATH"))
os.Setenv("CNI_NETNS", cniNetns)
os.Setenv("CNI_IFNAME", cniIfname)
defer envCleanup()
return f()
}

91
pkg/types/args.go Normal file
View File

@ -0,0 +1,91 @@
// Copyright 2015 CNI 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.
package types
import (
"encoding"
"fmt"
"reflect"
"strings"
)
// UnmarshallableBool typedef for builtin bool
// because builtin type's methods can't be declared
type UnmarshallableBool bool
// UnmarshalText implements the encoding.TextUnmarshaler interface.
// Returns boolean true if the string is "1" or "[Tt]rue"
// Returns boolean false if the string is "0" or "[Ff]alse"
func (b *UnmarshallableBool) UnmarshalText(data []byte) error {
s := strings.ToLower(string(data))
switch s {
case "1", "true":
*b = true
case "0", "false":
*b = false
default:
return fmt.Errorf("Boolean unmarshal error: invalid input %s", s)
}
return nil
}
// CommonArgs contains the IgnoreUnknown argument
// and must be embedded by all Arg structs
type CommonArgs struct {
IgnoreUnknown UnmarshallableBool `json:"ignoreunknown,omitempty"`
}
// GetKeyField is a helper function to receive Values
// Values that represent a pointer to a struct
func GetKeyField(keyString string, v reflect.Value) reflect.Value {
return v.Elem().FieldByName(keyString)
}
// LoadArgs parses args from a string in the form "K=V;K2=V2;..."
func LoadArgs(args string, container interface{}) error {
if args == "" {
return nil
}
containerValue := reflect.ValueOf(container)
pairs := strings.Split(args, ";")
unknownArgs := []string{}
for _, pair := range pairs {
kv := strings.Split(pair, "=")
if len(kv) != 2 {
return fmt.Errorf("ARGS: invalid pair %q", pair)
}
keyString := kv[0]
valueString := kv[1]
keyField := GetKeyField(keyString, containerValue)
if !keyField.IsValid() {
unknownArgs = append(unknownArgs, pair)
continue
}
u := keyField.Addr().Interface().(encoding.TextUnmarshaler)
err := u.UnmarshalText([]byte(valueString))
if err != nil {
return fmt.Errorf("ARGS: error parsing value of pair %q: %v)", pair, err)
}
}
isIgnoreUnknown := GetKeyField("IgnoreUnknown", containerValue).Bool()
if len(unknownArgs) > 0 && !isIgnoreUnknown {
return fmt.Errorf("ARGS: unknown args %q", unknownArgs)
}
return nil
}

106
pkg/types/args_test.go Normal file
View File

@ -0,0 +1,106 @@
// Copyright 2016 CNI 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.
package types_test
import (
"reflect"
. "github.com/containernetworking/cni/pkg/types"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
)
var _ = Describe("UnmarshallableBool UnmarshalText", func() {
DescribeTable("string to bool detection should succeed in all cases",
func(inputs []string, expected bool) {
for _, s := range inputs {
var ub UnmarshallableBool
err := ub.UnmarshalText([]byte(s))
Expect(err).ToNot(HaveOccurred())
Expect(ub).To(Equal(UnmarshallableBool(expected)))
}
},
Entry("parse to true", []string{"True", "true", "1"}, true),
Entry("parse to false", []string{"False", "false", "0"}, false),
)
Context("When passed an invalid value", func() {
It("should result in an error", func() {
var ub UnmarshallableBool
err := ub.UnmarshalText([]byte("invalid"))
Expect(err).To(HaveOccurred())
})
})
})
var _ = Describe("GetKeyField", func() {
type testcontainer struct {
Valid string `json:"valid,omitempty"`
}
var (
container = testcontainer{Valid: "valid"}
containerInterface = func(i interface{}) interface{} { return i }(&container)
containerValue = reflect.ValueOf(containerInterface)
)
Context("When a valid field is provided", func() {
It("should return the correct field", func() {
field := GetKeyField("Valid", containerValue)
Expect(field.String()).To(Equal("valid"))
})
})
})
var _ = Describe("LoadArgs", func() {
Context("When no arguments are passed", func() {
It("LoadArgs should succeed", func() {
err := LoadArgs("", struct{}{})
Expect(err).NotTo(HaveOccurred())
})
})
Context("When unknown arguments are passed and ignored", func() {
It("LoadArgs should succeed", func() {
ca := CommonArgs{}
err := LoadArgs("IgnoreUnknown=True;Unk=nown", &ca)
Expect(err).NotTo(HaveOccurred())
})
})
Context("When unknown arguments are passed and not ignored", func() {
It("LoadArgs should fail", func() {
ca := CommonArgs{}
err := LoadArgs("Unk=nown", &ca)
Expect(err).To(HaveOccurred())
})
})
Context("When unknown arguments are passed and explicitly not ignored", func() {
It("LoadArgs should fail", func() {
ca := CommonArgs{}
err := LoadArgs("IgnoreUnknown=0, Unk=nown", &ca)
Expect(err).To(HaveOccurred())
})
})
Context("When known arguments are passed", func() {
It("LoadArgs should succeed", func() {
ca := CommonArgs{}
err := LoadArgs("IgnoreUnknown=1", &ca)
Expect(err).NotTo(HaveOccurred())
})
})
})

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -12,16 +12,49 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package plugin
package types
import (
"encoding/json"
"fmt"
"net"
"os"
"github.com/appc/cni/pkg/ip"
)
// like net.IPNet but adds JSON marshalling and unmarshalling
type IPNet net.IPNet
// ParseCIDR takes a string like "10.2.3.1/24" and
// return IPNet with "10.2.3.1" and /24 mask
func ParseCIDR(s string) (*net.IPNet, error) {
ip, ipn, err := net.ParseCIDR(s)
if err != nil {
return nil, err
}
ipn.IP = ip
return ipn, nil
}
func (n IPNet) MarshalJSON() ([]byte, error) {
return json.Marshal((*net.IPNet)(&n).String())
}
func (n *IPNet) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
tmp, err := ParseCIDR(s)
if err != nil {
return err
}
*n = IPNet(*tmp)
return nil
}
// NetConf describes a network.
type NetConf struct {
Name string `json:"name,omitempty"`
@ -29,18 +62,34 @@ type NetConf struct {
IPAM struct {
Type string `json:"type,omitempty"`
} `json:"ipam,omitempty"`
DNS DNS `json:"dns"`
}
// Result is what gets returned from the plugin (via stdout) to the caller
type Result struct {
IP4 *IPConfig `json:"ip4,omitempty"`
IP6 *IPConfig `json:"ip6,omitempty"`
DNS DNS `json:"dns,omitempty"`
}
func (r *Result) Print() error {
return prettyPrint(r)
}
// String returns a formatted string in the form of "[IP4: $1,][ IP6: $2,] DNS: $3" where
// $1 represents the receiver's IPv4, $2 represents the receiver's IPv6 and $3 the
// receiver's DNS. If $1 or $2 are nil, they won't be present in the returned string.
func (r *Result) String() string {
var str string
if r.IP4 != nil {
str = fmt.Sprintf("IP4:%+v, ", *r.IP4)
}
if r.IP6 != nil {
str += fmt.Sprintf("IP6:%+v, ", *r.IP6)
}
return fmt.Sprintf("%sDNS:%+v", str, r.DNS)
}
// IPConfig contains values necessary to configure an interface
type IPConfig struct {
IP net.IPNet
@ -48,6 +97,14 @@ type IPConfig struct {
Routes []Route
}
// DNS contains values interesting for DNS resolvers
type DNS struct {
Nameservers []string `json:"nameservers,omitempty"`
Domain string `json:"domain,omitempty"`
Search []string `json:"search,omitempty"`
Options []string `json:"options,omitempty"`
}
type Route struct {
Dst net.IPNet
GW net.IP
@ -68,23 +125,23 @@ func (e *Error) Print() error {
}
// net.IPNet is not JSON (un)marshallable so this duality is needed
// for our custom ip.IPNet type
// for our custom IPNet type
// JSON (un)marshallable types
type ipConfig struct {
IP ip.IPNet `json:"ip"`
Gateway net.IP `json:"gateway,omitempty"`
Routes []Route `json:"routes,omitempty"`
IP IPNet `json:"ip"`
Gateway net.IP `json:"gateway,omitempty"`
Routes []Route `json:"routes,omitempty"`
}
type route struct {
Dst ip.IPNet `json:"dst"`
GW net.IP `json:"gw,omitempty"`
Dst IPNet `json:"dst"`
GW net.IP `json:"gw,omitempty"`
}
func (c *IPConfig) MarshalJSON() ([]byte, error) {
ipc := ipConfig{
IP: ip.IPNet(c.IP),
IP: IPNet(c.IP),
Gateway: c.Gateway,
Routes: c.Routes,
}
@ -117,7 +174,7 @@ func (r *Route) UnmarshalJSON(data []byte) error {
func (r *Route) MarshalJSON() ([]byte, error) {
rt := route{
Dst: ip.IPNet(r.Dst),
Dst: IPNet(r.Dst),
GW: r.GW,
}

View File

@ -0,0 +1,27 @@
// Copyright 2016 CNI 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.
package types_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestTypes(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Types Suite")
}

View File

@ -0,0 +1,58 @@
// Copyright 2016 CNI 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.
// build +linux
package sysctl
import (
"fmt"
"io/ioutil"
"path/filepath"
"strings"
)
// Sysctl provides a method to set/get values from /proc/sys - in linux systems
// new interface to set/get values of variables formerly handled by sysctl syscall
// If optional `params` have only one string value - this function will
// set this value into coresponding sysctl variable
func Sysctl(name string, params ...string) (string, error) {
if len(params) > 1 {
return "", fmt.Errorf("unexcepted additional parameters")
} else if len(params) == 1 {
return setSysctl(name, params[0])
}
return getSysctl(name)
}
func getSysctl(name string) (string, error) {
fullName := filepath.Join("/proc/sys", strings.Replace(name, ".", "/", -1))
fullName = filepath.Clean(fullName)
data, err := ioutil.ReadFile(fullName)
if err != nil {
return "", err
}
return string(data[:len(data)-1]), nil
}
func setSysctl(name, value string) (string, error) {
fullName := filepath.Join("/proc/sys", strings.Replace(name, ".", "/", -1))
fullName = filepath.Clean(fullName)
if err := ioutil.WriteFile(fullName, []byte(value), 0644); err != nil {
return "", err
}
return getSysctl(name)
}

41
pkg/utils/utils.go Normal file
View File

@ -0,0 +1,41 @@
// Copyright 2016 CNI 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.
package utils
import (
"crypto/sha512"
"fmt"
)
const (
maxChainLength = 28
chainPrefix = "CNI-"
prefixLength = len(chainPrefix)
)
// Generates a chain name to be used with iptables.
// Ensures that the generated chain name is exactly
// maxChainLength chars in length
func FormatChainName(name string, id string) string {
chainBytes := sha512.Sum512([]byte(name + id))
chain := fmt.Sprintf("%s%x", chainPrefix, chainBytes)
return chain[:maxChainLength]
}
// FormatComment returns a comment used for easier
// rule identification within iptables.
func FormatComment(name string, id string) string {
return fmt.Sprintf("name: %q id: %q", name, id)
}

View File

@ -0,0 +1,27 @@
// Copyright 2016 CNI 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.
package utils_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestUtils(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Utils Suite")
}

51
pkg/utils/utils_test.go Normal file
View File

@ -0,0 +1,51 @@
// Copyright 2016 CNI 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.
package utils
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Utils", func() {
It("must format a short name", func() {
chain := FormatChainName("test", "1234")
Expect(len(chain)).To(Equal(maxChainLength))
Expect(chain).To(Equal("CNI-2bbe0c48b91a7d1b8a6753a8"))
})
It("must truncate a long name", func() {
chain := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
Expect(len(chain)).To(Equal(maxChainLength))
Expect(chain).To(Equal("CNI-374f33fe84ab0ed84dcdebe3"))
})
It("must be predictable", func() {
chain1 := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
chain2 := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
Expect(len(chain1)).To(Equal(maxChainLength))
Expect(len(chain2)).To(Equal(maxChainLength))
Expect(chain1).To(Equal(chain2))
})
It("must change when a character changes", func() {
chain1 := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
chain2 := FormatChainName("testalongnamethatdoesnotmakesense", "1235")
Expect(len(chain1)).To(Equal(maxChainLength))
Expect(len(chain2)).To(Equal(maxChainLength))
Expect(chain1).To(Equal("CNI-374f33fe84ab0ed84dcdebe3"))
Expect(chain1).NotTo(Equal(chain2))
})
})

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -27,8 +27,8 @@ import (
"runtime"
"sync"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/coreos/go-systemd/activation"
)
@ -50,8 +50,8 @@ func newDHCP() *DHCP {
// Allocate acquires an IP from a DHCP server for a specified container.
// The acquired lease will be maintained until Release() is called.
func (d *DHCP) Allocate(args *skel.CmdArgs, result *plugin.Result) error {
conf := plugin.NetConf{}
func (d *DHCP) Allocate(args *skel.CmdArgs, result *types.Result) error {
conf := types.NetConf{}
if err := json.Unmarshal(args.StdinData, &conf); err != nil {
return fmt.Errorf("error parsing netconf: %v", err)
}
@ -70,7 +70,7 @@ func (d *DHCP) Allocate(args *skel.CmdArgs, result *plugin.Result) error {
d.setLease(args.ContainerID, conf.Name, l)
result.IP4 = &plugin.IPConfig{
result.IP4 = &types.IPConfig{
IP: *ipn,
Gateway: l.Gateway(),
Routes: l.Routes(),
@ -82,7 +82,7 @@ func (d *DHCP) Allocate(args *skel.CmdArgs, result *plugin.Result) error {
// Release stops maintenance of the lease acquired in Allocate()
// and sends a release msg to the DHCP server.
func (d *DHCP) Release(args *skel.CmdArgs, reply *struct{}) error {
conf := plugin.NetConf{}
conf := types.NetConf{}
if err := json.Unmarshal(args.StdinData, &conf); err != nil {
return fmt.Errorf("error parsing netconf: %v", err)
}

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -19,7 +19,6 @@ import (
"log"
"math/rand"
"net"
"os"
"sync"
"time"
@ -27,8 +26,8 @@ import (
"github.com/d2g/dhcp4client"
"github.com/vishvananda/netlink"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/plugin"
"github.com/containernetworking/cni/pkg/ns"
"github.com/containernetworking/cni/pkg/types"
)
// RFC 2131 suggests using exponential backoff, starting with 4sec
@ -74,7 +73,7 @@ func AcquireLease(clientID, netns, ifName string) (*DHCPLease, error) {
l.wg.Add(1)
go func() {
errCh <- ns.WithNetNSPath(netns, true, func(_ *os.File) error {
errCh <- ns.WithNetNSPath(netns, func(_ ns.NetNS) error {
defer l.wg.Done()
link, err := netlink.LinkByName(ifName)
@ -118,6 +117,13 @@ func (l *DHCPLease) acquire() error {
}
defer c.Close()
if (l.link.Attrs().Flags & net.FlagUp) != net.FlagUp {
log.Printf("Link %q down. Attempting to set up", l.link.Attrs().Name)
if err = netlink.LinkSetUp(l.link); err != nil {
return err
}
}
pkt, err := backoffRetry(func() (*dhcp4.Packet, error) {
ok, ack, err := c.Request()
switch {
@ -285,7 +291,7 @@ func (l *DHCPLease) Gateway() net.IP {
return parseRouter(l.opts)
}
func (l *DHCPLease) Routes() []plugin.Route {
func (l *DHCPLease) Routes() []types.Route {
routes := parseRoutes(l.opts)
return append(routes, parseCIDRRoutes(l.opts)...)
}

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -20,8 +20,8 @@ import (
"os"
"path/filepath"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
)
const socketPath = "/run/cni/dhcp.sock"
@ -35,7 +35,7 @@ func main() {
}
func cmdAdd(args *skel.CmdArgs) error {
result := plugin.Result{}
result := types.Result{}
if err := rpcCall("DHCP.Allocate", args, &result); err != nil {
return err
}

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -20,7 +20,7 @@ import (
"net"
"time"
"github.com/appc/cni/pkg/plugin"
"github.com/containernetworking/cni/pkg/types"
"github.com/d2g/dhcp4"
)
@ -40,17 +40,17 @@ func classfulSubnet(sn net.IP) net.IPNet {
}
}
func parseRoutes(opts dhcp4.Options) []plugin.Route {
func parseRoutes(opts dhcp4.Options) []types.Route {
// StaticRoutes format: pairs of:
// Dest = 4 bytes; Classful IP subnet
// Router = 4 bytes; IP address of router
routes := []plugin.Route{}
routes := []types.Route{}
if opt, ok := opts[dhcp4.OptionStaticRoute]; ok {
for len(opt) >= 8 {
sn := opt[0:4]
r := opt[4:8]
rt := plugin.Route{
rt := types.Route{
Dst: classfulSubnet(sn),
GW: r,
}
@ -62,10 +62,10 @@ func parseRoutes(opts dhcp4.Options) []plugin.Route {
return routes
}
func parseCIDRRoutes(opts dhcp4.Options) []plugin.Route {
func parseCIDRRoutes(opts dhcp4.Options) []types.Route {
// See RFC4332 for format (http://tools.ietf.org/html/rfc3442)
routes := []plugin.Route{}
routes := []types.Route{}
if opt, ok := opts[dhcp4.OptionClasslessRouteFormat]; ok {
for len(opt) >= 5 {
width := int(opt[0])
@ -89,7 +89,7 @@ func parseCIDRRoutes(opts dhcp4.Options) []plugin.Route {
gw := net.IP(opt[octets+1 : octets+5])
rt := plugin.Route{
rt := types.Route{
Dst: net.IPNet{
IP: net.IP(sn),
Mask: net.CIDRMask(width, 32),

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -18,20 +18,20 @@ import (
"net"
"testing"
"github.com/appc/cni/pkg/plugin"
"github.com/containernetworking/cni/pkg/types"
"github.com/d2g/dhcp4"
)
func validateRoutes(t *testing.T, routes []plugin.Route) {
expected := []plugin.Route{
plugin.Route{
func validateRoutes(t *testing.T, routes []types.Route) {
expected := []types.Route{
types.Route{
Dst: net.IPNet{
IP: net.IPv4(10, 0, 0, 0),
Mask: net.CIDRMask(8, 32),
},
GW: net.IPv4(10, 1, 2, 3),
},
plugin.Route{
types.Route{
Dst: net.IPNet{
IP: net.IPv4(192, 168, 1, 0),
Mask: net.CIDRMask(24, 32),

View File

@ -64,7 +64,7 @@ f81d4fae-7dec-11d0-a765-00a0c91e6bf6
"range-start": "3ffe:ffff:0:01ff::0010",
"range-end": "3ffe:ffff:0:01ff::0020",
"routes": [
"3ffe:ffff:0:01ff::1/64"
{ "dst": "3ffe:ffff:0:01ff::1/64" }
]
}
}
@ -79,7 +79,7 @@ f81d4fae-7dec-11d0-a765-00a0c91e6bf6
"range-start": "203.0.113.10",
"range-end": "203.0.113.20",
"routes": [
"203.0.113.0/24"
{ "dst": "203.0.113.0/24" }
]
}
}

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -18,9 +18,9 @@ import (
"fmt"
"net"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/plugins/ipam/host-local/backend"
"github.com/containernetworking/cni/pkg/ip"
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/plugins/ipam/host-local/backend"
)
type IPAllocator struct {
@ -69,7 +69,7 @@ func validateRangeIP(ip net.IP, ipnet *net.IPNet) error {
}
// Returns newly allocated IP along with its config
func (a *IPAllocator) Get(id string) (*plugin.IPConfig, error) {
func (a *IPAllocator) Get(id string) (*types.IPConfig, error) {
a.store.Lock()
defer a.store.Unlock()
@ -78,6 +78,40 @@ func (a *IPAllocator) Get(id string) (*plugin.IPConfig, error) {
gw = ip.NextIP(a.conf.Subnet.IP)
}
var requestedIP net.IP
if a.conf.Args != nil {
requestedIP = a.conf.Args.IP
}
if requestedIP != nil {
if gw != nil && gw.Equal(a.conf.Args.IP) {
return nil, fmt.Errorf("requested IP must differ gateway IP")
}
subnet := net.IPNet{
IP: a.conf.Subnet.IP,
Mask: a.conf.Subnet.Mask,
}
err := validateRangeIP(requestedIP, &subnet)
if err != nil {
return nil, err
}
reserved, err := a.store.Reserve(id, requestedIP)
if err != nil {
return nil, err
}
if reserved {
return &types.IPConfig{
IP: net.IPNet{IP: requestedIP, Mask: a.conf.Subnet.Mask},
Gateway: gw,
Routes: a.conf.Routes,
}, nil
}
return nil, fmt.Errorf("requested IP address %q is not available in network: %s", requestedIP, a.conf.Name)
}
for cur := a.start; !cur.Equal(a.end); cur = ip.NextIP(cur) {
// don't allocate gateway IP
if gw != nil && cur.Equal(gw) {
@ -89,61 +123,16 @@ func (a *IPAllocator) Get(id string) (*plugin.IPConfig, error) {
return nil, err
}
if reserved {
return &plugin.IPConfig{
IP: net.IPNet{cur, a.conf.Subnet.Mask},
return &types.IPConfig{
IP: net.IPNet{IP: cur, Mask: a.conf.Subnet.Mask},
Gateway: gw,
Routes: a.conf.Routes,
}, nil
}
}
return nil, fmt.Errorf("no IP addresses available in network: %s", a.conf.Name)
}
// Allocates both an IP and the Gateway IP, i.e. a /31
// This is used for Point-to-Point links
func (a *IPAllocator) GetPtP(id string) (*plugin.IPConfig, error) {
a.store.Lock()
defer a.store.Unlock()
for cur := a.start; !cur.Equal(a.end); cur = ip.NextIP(cur) {
// we're looking for unreserved even, odd pair
if !evenIP(cur) {
continue
}
gw := cur
reserved, err := a.store.Reserve(id, gw)
if err != nil {
return nil, err
}
if reserved {
cur = ip.NextIP(cur)
if cur.Equal(a.end) {
break
}
reserved, err := a.store.Reserve(id, cur)
if err != nil {
return nil, err
}
if reserved {
// found them both!
_, bits := a.conf.Subnet.Mask.Size()
mask := net.CIDRMask(bits-1, bits)
return &plugin.IPConfig{
IP: net.IPNet{cur, mask},
Gateway: gw,
Routes: a.conf.Routes,
}, nil
}
}
}
return nil, fmt.Errorf("no ip addresses available in network: %s", a.conf.Name)
}
// Releases all IPs allocated for the container with given ID
func (a *IPAllocator) Release(id string) error {
a.store.Lock()
@ -153,6 +142,9 @@ func (a *IPAllocator) Release(id string) error {
}
func networkRange(ipnet *net.IPNet) (net.IP, net.IP, error) {
if ipnet.IP == nil {
return nil, nil, fmt.Errorf("missing field %q in IPAM configuration", "subnet")
}
ip := ipnet.IP.To4()
if ip == nil {
ip = ipnet.IP.To16()
@ -171,15 +163,3 @@ func networkRange(ipnet *net.IPNet) (net.IP, net.IP, error) {
}
return ipnet.IP, end, nil
}
func evenIP(ip net.IP) bool {
i := ip.To4()
if i == nil {
i = ip.To16()
if i == nil {
panic("IP is not v4 or v6")
}
}
return i[len(i)-1]%2 == 0
}

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -19,19 +19,24 @@ import (
"fmt"
"net"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/plugin"
"github.com/containernetworking/cni/pkg/types"
)
// IPAMConfig represents the IP related network configuration.
type IPAMConfig struct {
Name string
Type string `json:"type"`
RangeStart net.IP `json:"rangeStart"`
RangeEnd net.IP `json:"rangeEnd"`
Subnet ip.IPNet `json:"subnet"`
Gateway net.IP `json:"gateway"`
Routes []plugin.Route `json:"routes"`
Type string `json:"type"`
RangeStart net.IP `json:"rangeStart"`
RangeEnd net.IP `json:"rangeEnd"`
Subnet types.IPNet `json:"subnet"`
Gateway net.IP `json:"gateway"`
Routes []types.Route `json:"routes"`
Args *IPAMArgs `json:"-"`
}
type IPAMArgs struct {
types.CommonArgs
IP net.IP `json:"ip,omitempty"`
}
type Net struct {
@ -40,12 +45,20 @@ type Net struct {
}
// NewIPAMConfig creates a NetworkConfig from the given network name.
func LoadIPAMConfig(bytes []byte) (*IPAMConfig, error) {
func LoadIPAMConfig(bytes []byte, args string) (*IPAMConfig, error) {
n := Net{}
if err := json.Unmarshal(bytes, &n); err != nil {
return nil, err
}
if args != "" {
n.IPAM.Args = &IPAMArgs{}
err := types.LoadArgs(args, n.IPAM.Args)
if err != nil {
return nil, err
}
}
if n.IPAM == nil {
return nil, fmt.Errorf("%q missing 'ipam' key")
}

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -15,12 +15,10 @@
package main
import (
"errors"
"github.com/containernetworking/cni/plugins/ipam/host-local/backend/disk"
"github.com/appc/cni/plugins/ipam/host-local/backend/disk"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
)
func main() {
@ -28,7 +26,7 @@ func main() {
}
func cmdAdd(args *skel.CmdArgs) error {
ipamConf, err := LoadIPAMConfig(args.StdinData)
ipamConf, err := LoadIPAMConfig(args.StdinData, args.Args)
if err != nil {
return err
}
@ -44,29 +42,19 @@ func cmdAdd(args *skel.CmdArgs) error {
return err
}
var ipConf *plugin.IPConfig
switch ipamConf.Type {
case "host-local":
ipConf, err = allocator.Get(args.ContainerID)
case "host-local-ptp":
ipConf, err = allocator.GetPtP(args.ContainerID)
default:
return errors.New("Unsupported IPAM plugin type")
}
ipConf, err := allocator.Get(args.ContainerID)
if err != nil {
return err
}
r := &plugin.Result{
r := &types.Result{
IP4: ipConf,
}
return r.Print()
}
func cmdDel(args *skel.CmdArgs) error {
ipamConf, err := LoadIPAMConfig(args.StdinData)
ipamConf, err := LoadIPAMConfig(args.StdinData, args.Args)
if err != nil {
return err
}

View File

@ -1,4 +1,4 @@
// Copyright 2014 CoreOS, Inc.
// Copyright 2014 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -19,25 +19,28 @@ import (
"errors"
"fmt"
"net"
"os"
"runtime"
"syscall"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/ip"
"github.com/containernetworking/cni/pkg/ipam"
"github.com/containernetworking/cni/pkg/ns"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/utils"
"github.com/vishvananda/netlink"
)
const defaultBrName = "cni0"
type NetConf struct {
plugin.NetConf
BrName string `json:"bridge"`
IsGW bool `json:"isGateway"`
IPMasq bool `json:"ipMasq"`
MTU int `json:"mtu"`
types.NetConf
BrName string `json:"bridge"`
IsGW bool `json:"isGateway"`
IsDefaultGW bool `json:"isDefaultGateway"`
IPMasq bool `json:"ipMasq"`
MTU int `json:"mtu"`
HairpinMode bool `json:"hairpinMode"`
}
func init() {
@ -99,6 +102,11 @@ func ensureBridge(brName string, mtu int) (*netlink.Bridge, error) {
LinkAttrs: netlink.LinkAttrs{
Name: brName,
MTU: mtu,
// Let kernel use default txqueuelen; leaving it unset
// means 0, and a zero-length TX queue messes up FIFO
// traffic shapers which use TX queue length as the
// default packet limit
TxQLen: -1,
},
}
@ -121,10 +129,10 @@ func ensureBridge(brName string, mtu int) (*netlink.Bridge, error) {
return br, nil
}
func setupVeth(netns string, br *netlink.Bridge, ifName string, mtu int) error {
func setupVeth(netns ns.NetNS, br *netlink.Bridge, ifName string, mtu int, hairpinMode bool) error {
var hostVethName string
err := ns.WithNetNSPath(netns, false, func(hostNS *os.File) error {
err := netns.Do(func(hostNS ns.NetNS) error {
// create the veth pair in the container and move host end into host netns
hostVeth, _, err := ip.SetupVeth(ifName, mtu, hostNS)
if err != nil {
@ -149,6 +157,11 @@ func setupVeth(netns string, br *netlink.Bridge, ifName string, mtu int) error {
return fmt.Errorf("failed to connect %q to bridge %v: %v", hostVethName, br.Attrs().Name, err)
}
// set hairpin mode
if err = netlink.LinkSetHairpin(hostVeth, hairpinMode); err != nil {
return fmt.Errorf("failed to setup hairpin mode for %v: %v", hostVethName, err)
}
return nil
}
@ -173,21 +186,32 @@ func cmdAdd(args *skel.CmdArgs) error {
return err
}
if n.IsDefaultGW {
n.IsGW = true
}
br, err := setupBridge(n)
if err != nil {
return err
}
if err = setupVeth(args.Netns, br, args.IfName, n.MTU); err != nil {
netns, err := ns.GetNS(args.Netns)
if err != nil {
return fmt.Errorf("failed to open netns %q: %v", args.Netns, err)
}
defer netns.Close()
if err = setupVeth(netns, br, args.IfName, n.MTU, n.HairpinMode); err != nil {
return err
}
// run the IPAM plugin and get back the config to apply
result, err := plugin.ExecAdd(n.IPAM.Type, args.StdinData)
result, err := ipam.ExecAdd(n.IPAM.Type, args.StdinData)
if err != nil {
return err
}
// TODO: make this optional when IPv6 is supported
if result.IP4 == nil {
return errors.New("IPAM plugin returned missing IPv4 config")
}
@ -196,10 +220,35 @@ func cmdAdd(args *skel.CmdArgs) error {
result.IP4.Gateway = calcGatewayIP(&result.IP4.IP)
}
err = ns.WithNetNSPath(args.Netns, false, func(hostNS *os.File) error {
return plugin.ConfigureIface(args.IfName, result)
})
if err != nil {
if err := netns.Do(func(_ ns.NetNS) error {
// set the default gateway if requested
if n.IsDefaultGW {
_, defaultNet, err := net.ParseCIDR("0.0.0.0/0")
if err != nil {
return err
}
for _, route := range result.IP4.Routes {
if defaultNet.String() == route.Dst.String() {
if route.GW != nil && !route.GW.Equal(result.IP4.Gateway) {
return fmt.Errorf(
"isDefaultGateway ineffective because IPAM sets default route via %q",
route.GW,
)
}
}
}
result.IP4.Routes = append(
result.IP4.Routes,
types.Route{Dst: *defaultNet, GW: result.IP4.Gateway},
)
// TODO: IPV6
}
return ipam.ConfigureIface(args.IfName, result)
}); err != nil {
return err
}
@ -219,12 +268,14 @@ func cmdAdd(args *skel.CmdArgs) error {
}
if n.IPMasq {
chain := "CNI-" + n.Name
if err = ip.SetupIPMasq(ip.Network(&result.IP4.IP), chain); err != nil {
chain := utils.FormatChainName(n.Name, args.ContainerID)
comment := utils.FormatComment(n.Name, args.ContainerID)
if err = ip.SetupIPMasq(ip.Network(&result.IP4.IP), chain, comment); err != nil {
return err
}
}
result.DNS = n.DNS
return result.Print()
}
@ -234,14 +285,33 @@ func cmdDel(args *skel.CmdArgs) error {
return err
}
err = plugin.ExecDel(n.IPAM.Type, args.StdinData)
if err := ipam.ExecDel(n.IPAM.Type, args.StdinData); err != nil {
return err
}
if args.Netns == "" {
return nil
}
var ipn *net.IPNet
err = ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error {
var err error
ipn, err = ip.DelLinkByNameAddr(args.IfName, netlink.FAMILY_V4)
return err
})
if err != nil {
return err
}
return ns.WithNetNSPath(args.Netns, false, func(hostNS *os.File) error {
return ip.DelLinkByName(args.IfName)
})
if n.IPMasq {
chain := utils.FormatChainName(n.Name, args.ContainerID)
comment := utils.FormatComment(n.Name, args.ContainerID)
if err = ip.TeardownIPMasq(ipn, chain, comment); err != nil {
return err
}
}
return nil
}
func main() {

View File

@ -0,0 +1,27 @@
// Copyright 2016 CNI 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.
package main
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestBridge(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "bridge Suite")
}

View File

@ -0,0 +1,239 @@
// Copyright 2015 CNI 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.
package main
import (
"fmt"
"net"
"syscall"
"github.com/containernetworking/cni/pkg/ns"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/testutils"
"github.com/containernetworking/cni/pkg/types"
"github.com/vishvananda/netlink"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("bridge Operations", func() {
var originalNS ns.NetNS
BeforeEach(func() {
// Create a new NetNS so we don't modify the host
var err error
originalNS, err = ns.NewNS()
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
Expect(originalNS.Close()).To(Succeed())
})
It("creates a bridge", func() {
const IFNAME = "bridge0"
conf := &NetConf{
NetConf: types.NetConf{
Name: "testConfig",
Type: "bridge",
},
BrName: IFNAME,
IsGW: false,
IPMasq: false,
MTU: 5000,
}
err := originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
bridge, err := setupBridge(conf)
Expect(err).NotTo(HaveOccurred())
Expect(bridge.Attrs().Name).To(Equal(IFNAME))
// Double check that the link was added
link, err := netlink.LinkByName(IFNAME)
Expect(err).NotTo(HaveOccurred())
Expect(link.Attrs().Name).To(Equal(IFNAME))
return nil
})
Expect(err).NotTo(HaveOccurred())
})
It("handles an existing bridge", func() {
const IFNAME = "bridge0"
err := originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
err := netlink.LinkAdd(&netlink.Bridge{
LinkAttrs: netlink.LinkAttrs{
Name: IFNAME,
},
})
Expect(err).NotTo(HaveOccurred())
link, err := netlink.LinkByName(IFNAME)
Expect(err).NotTo(HaveOccurred())
Expect(link.Attrs().Name).To(Equal(IFNAME))
ifindex := link.Attrs().Index
conf := &NetConf{
NetConf: types.NetConf{
Name: "testConfig",
Type: "bridge",
},
BrName: IFNAME,
IsGW: false,
IPMasq: false,
}
bridge, err := setupBridge(conf)
Expect(err).NotTo(HaveOccurred())
Expect(bridge.Attrs().Name).To(Equal(IFNAME))
Expect(bridge.Attrs().Index).To(Equal(ifindex))
// Double check that the link has the same ifindex
link, err = netlink.LinkByName(IFNAME)
Expect(err).NotTo(HaveOccurred())
Expect(link.Attrs().Name).To(Equal(IFNAME))
Expect(link.Attrs().Index).To(Equal(ifindex))
return nil
})
Expect(err).NotTo(HaveOccurred())
})
It("configures and deconfigures a bridge and veth with default route with ADD/DEL", func() {
const BRNAME = "cni0"
const IFNAME = "eth0"
gwaddr, subnet, err := net.ParseCIDR("10.1.2.1/24")
Expect(err).NotTo(HaveOccurred())
conf := fmt.Sprintf(`{
"name": "mynet",
"type": "bridge",
"bridge": "%s",
"isDefaultGateway": true,
"ipMasq": false,
"ipam": {
"type": "host-local",
"subnet": "%s"
}
}`, BRNAME, subnet.String())
targetNs, err := ns.NewNS()
Expect(err).NotTo(HaveOccurred())
defer targetNs.Close()
args := &skel.CmdArgs{
ContainerID: "dummy",
Netns: targetNs.Path(),
IfName: IFNAME,
StdinData: []byte(conf),
}
err = originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
_, err := testutils.CmdAddWithResult(targetNs.Path(), IFNAME, func() error {
return cmdAdd(args)
})
Expect(err).NotTo(HaveOccurred())
// Make sure bridge link exists
link, err := netlink.LinkByName(BRNAME)
Expect(err).NotTo(HaveOccurred())
Expect(link.Attrs().Name).To(Equal(BRNAME))
// Ensure bridge has gateway address
addrs, err := netlink.AddrList(link, syscall.AF_INET)
Expect(err).NotTo(HaveOccurred())
Expect(len(addrs)).To(BeNumerically(">", 0))
found := false
subnetPrefix, subnetBits := subnet.Mask.Size()
for _, a := range addrs {
aPrefix, aBits := a.IPNet.Mask.Size()
if a.IPNet.IP.Equal(gwaddr) && aPrefix == subnetPrefix && aBits == subnetBits {
found = true
break
}
}
Expect(found).To(Equal(true))
// Check for the veth link in the main namespace
links, err := netlink.LinkList()
Expect(err).NotTo(HaveOccurred())
Expect(len(links)).To(Equal(3)) // Bridge, veth, and loopback
for _, l := range links {
if l.Attrs().Name != BRNAME && l.Attrs().Name != "lo" {
_, isVeth := l.(*netlink.Veth)
Expect(isVeth).To(Equal(true))
}
}
Expect(err).NotTo(HaveOccurred())
return nil
})
Expect(err).NotTo(HaveOccurred())
// Find the veth peer in the container namespace and the default route
err = targetNs.Do(func(ns.NetNS) error {
defer GinkgoRecover()
link, err := netlink.LinkByName(IFNAME)
Expect(err).NotTo(HaveOccurred())
Expect(link.Attrs().Name).To(Equal(IFNAME))
// Ensure the default route
routes, err := netlink.RouteList(link, 0)
Expect(err).NotTo(HaveOccurred())
var defaultRouteFound bool
for _, route := range routes {
defaultRouteFound = (route.Dst == nil && route.Src == nil && route.Gw.Equal(gwaddr))
if defaultRouteFound {
break
}
}
Expect(defaultRouteFound).To(Equal(true))
return nil
})
Expect(err).NotTo(HaveOccurred())
err = originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
err := testutils.CmdDelWithResult(targetNs.Path(), IFNAME, func() error {
return cmdDel(args)
})
Expect(err).NotTo(HaveOccurred())
return nil
})
Expect(err).NotTo(HaveOccurred())
// Make sure macvlan link has been deleted
err = targetNs.Do(func(ns.NetNS) error {
defer GinkgoRecover()
link, err := netlink.LinkByName(IFNAME)
Expect(err).To(HaveOccurred())
Expect(link).To(BeNil())
return nil
})
Expect(err).NotTo(HaveOccurred())
})
})

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -18,21 +18,20 @@ import (
"encoding/json"
"errors"
"fmt"
"os"
"runtime"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/ip"
"github.com/containernetworking/cni/pkg/ipam"
"github.com/containernetworking/cni/pkg/ns"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/vishvananda/netlink"
)
type NetConf struct {
plugin.NetConf
types.NetConf
Master string `json:"master"`
Mode string `json:"mode"`
IPMasq bool `json:"ipMasq"`
MTU int `json:"mtu"`
}
@ -65,7 +64,7 @@ func modeFromString(s string) (netlink.IPVlanMode, error) {
}
}
func createIpvlan(conf *NetConf, ifName string, netns *os.File) error {
func createIpvlan(conf *NetConf, ifName string, netns ns.NetNS) error {
mode, err := modeFromString(conf.Mode)
if err != nil {
return err
@ -97,7 +96,7 @@ func createIpvlan(conf *NetConf, ifName string, netns *os.File) error {
return fmt.Errorf("failed to create ipvlan: %v", err)
}
return ns.WithNetNS(netns, false, func(_ *os.File) error {
return netns.Do(func(_ ns.NetNS) error {
err := renameLink(tmpName, ifName)
if err != nil {
return fmt.Errorf("failed to rename ipvlan to %q: %v", ifName, err)
@ -112,9 +111,9 @@ func cmdAdd(args *skel.CmdArgs) error {
return err
}
netns, err := os.Open(args.Netns)
netns, err := ns.GetNS(args.Netns)
if err != nil {
return fmt.Errorf("failed to open netns %q: %v", netns, err)
return fmt.Errorf("failed to open netns %q: %v", args.Netns, err)
}
defer netns.Close()
@ -123,7 +122,7 @@ func cmdAdd(args *skel.CmdArgs) error {
}
// run the IPAM plugin and get back the config to apply
result, err := plugin.ExecAdd(n.IPAM.Type, args.StdinData)
result, err := ipam.ExecAdd(n.IPAM.Type, args.StdinData)
if err != nil {
return err
}
@ -131,20 +130,14 @@ func cmdAdd(args *skel.CmdArgs) error {
return errors.New("IPAM plugin returned missing IPv4 config")
}
err = ns.WithNetNS(netns, false, func(_ *os.File) error {
return plugin.ConfigureIface(args.IfName, result)
err = netns.Do(func(_ ns.NetNS) error {
return ipam.ConfigureIface(args.IfName, result)
})
if err != nil {
return err
}
if n.IPMasq {
chain := "CNI-" + n.Name
if err = ip.SetupIPMasq(ip.Network(&result.IP4.IP), chain); err != nil {
return err
}
}
result.DNS = n.DNS
return result.Print()
}
@ -154,12 +147,16 @@ func cmdDel(args *skel.CmdArgs) error {
return err
}
err = plugin.ExecDel(n.IPAM.Type, args.StdinData)
err = ipam.ExecDel(n.IPAM.Type, args.StdinData)
if err != nil {
return err
}
return ns.WithNetNSPath(args.Netns, false, func(hostNS *os.File) error {
if args.Netns == "" {
return nil
}
return ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error {
return ip.DelLinkByName(args.IfName)
})
}

View File

@ -0,0 +1,27 @@
// Copyright 2016 CNI 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.
package main
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestIpvlan(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "ipvlan Suite")
}

View File

@ -0,0 +1,168 @@
// Copyright 2015 CNI 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.
package main
import (
"fmt"
"github.com/containernetworking/cni/pkg/ns"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/testutils"
"github.com/containernetworking/cni/pkg/types"
"github.com/vishvananda/netlink"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
const MASTER_NAME = "eth0"
var _ = Describe("ipvlan Operations", func() {
var originalNS ns.NetNS
BeforeEach(func() {
// Create a new NetNS so we don't modify the host
var err error
originalNS, err = ns.NewNS()
Expect(err).NotTo(HaveOccurred())
err = originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
// Add master
err = netlink.LinkAdd(&netlink.Dummy{
LinkAttrs: netlink.LinkAttrs{
Name: MASTER_NAME,
},
})
Expect(err).NotTo(HaveOccurred())
_, err = netlink.LinkByName(MASTER_NAME)
Expect(err).NotTo(HaveOccurred())
return nil
})
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
Expect(originalNS.Close()).To(Succeed())
})
It("creates an ipvlan link in a non-default namespace", func() {
conf := &NetConf{
NetConf: types.NetConf{
Name: "testConfig",
Type: "ipvlan",
},
Master: MASTER_NAME,
Mode: "l2",
MTU: 1500,
}
// Create ipvlan in other namespace
targetNs, err := ns.NewNS()
Expect(err).NotTo(HaveOccurred())
defer targetNs.Close()
err = originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
err := createIpvlan(conf, "foobar0", targetNs)
Expect(err).NotTo(HaveOccurred())
return nil
})
Expect(err).NotTo(HaveOccurred())
// Make sure ipvlan link exists in the target namespace
err = targetNs.Do(func(ns.NetNS) error {
defer GinkgoRecover()
link, err := netlink.LinkByName("foobar0")
Expect(err).NotTo(HaveOccurred())
Expect(link.Attrs().Name).To(Equal("foobar0"))
return nil
})
Expect(err).NotTo(HaveOccurred())
})
It("configures and deconfigures an iplvan link with ADD/DEL", func() {
const IFNAME = "ipvl0"
conf := fmt.Sprintf(`{
"name": "mynet",
"type": "ipvlan",
"master": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.1.2.0/24"
}
}`, MASTER_NAME)
targetNs, err := ns.NewNS()
Expect(err).NotTo(HaveOccurred())
defer targetNs.Close()
args := &skel.CmdArgs{
ContainerID: "dummy",
Netns: targetNs.Path(),
IfName: IFNAME,
StdinData: []byte(conf),
}
err = originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
_, err := testutils.CmdAddWithResult(targetNs.Path(), IFNAME, func() error {
return cmdAdd(args)
})
Expect(err).NotTo(HaveOccurred())
return nil
})
Expect(err).NotTo(HaveOccurred())
// Make sure ipvlan link exists in the target namespace
err = targetNs.Do(func(ns.NetNS) error {
defer GinkgoRecover()
link, err := netlink.LinkByName(IFNAME)
Expect(err).NotTo(HaveOccurred())
Expect(link.Attrs().Name).To(Equal(IFNAME))
return nil
})
Expect(err).NotTo(HaveOccurred())
err = originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
err = testutils.CmdDelWithResult(targetNs.Path(), IFNAME, func() error {
return cmdDel(args)
})
Expect(err).NotTo(HaveOccurred())
return nil
})
Expect(err).NotTo(HaveOccurred())
// Make sure ipvlan link has been deleted
err = targetNs.Do(func(ns.NetNS) error {
defer GinkgoRecover()
link, err := netlink.LinkByName(IFNAME)
Expect(err).To(HaveOccurred())
Expect(link).To(BeNil())
return nil
})
Expect(err).NotTo(HaveOccurred())
})
})

View File

@ -0,0 +1,71 @@
// Copyright 2016 CNI 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.
package main
import (
"github.com/containernetworking/cni/pkg/ns"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/vishvananda/netlink"
)
func cmdAdd(args *skel.CmdArgs) error {
args.IfName = "lo" // ignore config, this only works for loopback
err := ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error {
link, err := netlink.LinkByName(args.IfName)
if err != nil {
return err // not tested
}
err = netlink.LinkSetUp(link)
if err != nil {
return err // not tested
}
return nil
})
if err != nil {
return err // not tested
}
result := types.Result{}
return result.Print()
}
func cmdDel(args *skel.CmdArgs) error {
args.IfName = "lo" // ignore config, this only works for loopback
err := ns.WithNetNSPath(args.Netns, func(ns.NetNS) error {
link, err := netlink.LinkByName(args.IfName)
if err != nil {
return err // not tested
}
err = netlink.LinkSetDown(link)
if err != nil {
return err // not tested
}
return nil
})
if err != nil {
return err // not tested
}
return nil
}
func main() {
skel.PluginMain(cmdAdd, cmdDel)
}

View File

@ -0,0 +1,41 @@
// Copyright 2016 CNI 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.
package main_test
import (
"github.com/onsi/gomega/gexec"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
var pathToLoPlugin string
func TestLoopback(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Loopback Suite")
}
var _ = BeforeSuite(func() {
var err error
pathToLoPlugin, err = gexec.Build("github.com/containernetworking/cni/plugins/main/loopback")
Expect(err).NotTo(HaveOccurred())
})
var _ = AfterSuite(func() {
gexec.CleanupBuildArtifacts()
})

View File

@ -0,0 +1,100 @@
// Copyright 2016 CNI 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.
package main_test
import (
"fmt"
"net"
"os/exec"
"strings"
"github.com/containernetworking/cni/pkg/ns"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/gexec"
)
var _ = Describe("Loopback", func() {
var (
networkNS ns.NetNS
containerID string
command *exec.Cmd
environ []string
)
BeforeEach(func() {
command = exec.Command(pathToLoPlugin)
var err error
networkNS, err = ns.NewNS()
Expect(err).NotTo(HaveOccurred())
environ = []string{
fmt.Sprintf("CNI_CONTAINERID=%s", containerID),
fmt.Sprintf("CNI_NETNS=%s", networkNS.Path()),
fmt.Sprintf("CNI_IFNAME=%s", "this is ignored"),
fmt.Sprintf("CNI_ARGS=%s", "none"),
fmt.Sprintf("CNI_PATH=%s", "/some/test/path"),
}
command.Stdin = strings.NewReader("this doesn't matter")
})
AfterEach(func() {
Expect(networkNS.Close()).To(Succeed())
})
Context("when given a network namespace", func() {
It("sets the lo device to UP", func() {
command.Env = append(environ, fmt.Sprintf("CNI_COMMAND=%s", "ADD"))
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gbytes.Say(`{.*}`))
Eventually(session).Should(gexec.Exit(0))
var lo *net.Interface
err = networkNS.Do(func(ns.NetNS) error {
var err error
lo, err = net.InterfaceByName("lo")
return err
})
Expect(err).NotTo(HaveOccurred())
Expect(lo.Flags & net.FlagUp).To(Equal(net.FlagUp))
})
It("sets the lo device to DOWN", func() {
command.Env = append(environ, fmt.Sprintf("CNI_COMMAND=%s", "DEL"))
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gbytes.Say(``))
Eventually(session).Should(gexec.Exit(0))
var lo *net.Interface
err = networkNS.Do(func(ns.NetNS) error {
var err error
lo, err = net.InterfaceByName("lo")
return err
})
Expect(err).NotTo(HaveOccurred())
Expect(lo.Flags & net.FlagUp).NotTo(Equal(net.FlagUp))
})
})
})

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -18,21 +18,25 @@ import (
"encoding/json"
"errors"
"fmt"
"os"
"runtime"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/ip"
"github.com/containernetworking/cni/pkg/ipam"
"github.com/containernetworking/cni/pkg/ns"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/utils/sysctl"
"github.com/vishvananda/netlink"
)
const (
IPv4InterfaceArpProxySysctlTemplate = "net.ipv4.conf.%s.proxy_arp"
)
type NetConf struct {
plugin.NetConf
types.NetConf
Master string `json:"master"`
Mode string `json:"mode"`
IPMasq bool `json:"ipMasq"`
MTU int `json:"mtu"`
}
@ -69,7 +73,7 @@ func modeFromString(s string) (netlink.MacvlanMode, error) {
}
}
func createMacvlan(conf *NetConf, ifName string, netns *os.File) error {
func createMacvlan(conf *NetConf, ifName string, netns ns.NetNS) error {
mode, err := modeFromString(conf.Mode)
if err != nil {
return err
@ -80,7 +84,7 @@ func createMacvlan(conf *NetConf, ifName string, netns *os.File) error {
return fmt.Errorf("failed to lookup master %q: %v", conf.Master, err)
}
// due to kernel bug we have to create with tmpname or it might
// due to kernel bug we have to create with tmpName or it might
// collide with the name on the host and error out
tmpName, err := ip.RandomVethName()
if err != nil {
@ -101,9 +105,18 @@ func createMacvlan(conf *NetConf, ifName string, netns *os.File) error {
return fmt.Errorf("failed to create macvlan: %v", err)
}
return ns.WithNetNS(netns, false, func(_ *os.File) error {
return netns.Do(func(_ ns.NetNS) error {
// TODO: duplicate following lines for ipv6 support, when it will be added in other places
ipv4SysctlValueName := fmt.Sprintf(IPv4InterfaceArpProxySysctlTemplate, tmpName)
if _, err := sysctl.Sysctl(ipv4SysctlValueName, "1"); err != nil {
// remove the newly added link and ignore errors, because we already are in a failed state
_ = netlink.LinkDel(mv)
return fmt.Errorf("failed to set proxy_arp on newly added interface %q: %v", tmpName, err)
}
err := renameLink(tmpName, ifName)
if err != nil {
_ = netlink.LinkDel(mv)
return fmt.Errorf("failed to rename macvlan to %q: %v", ifName, err)
}
return nil
@ -116,7 +129,7 @@ func cmdAdd(args *skel.CmdArgs) error {
return err
}
netns, err := os.Open(args.Netns)
netns, err := ns.GetNS(args.Netns)
if err != nil {
return fmt.Errorf("failed to open netns %q: %v", netns, err)
}
@ -127,7 +140,7 @@ func cmdAdd(args *skel.CmdArgs) error {
}
// run the IPAM plugin and get back the config to apply
result, err := plugin.ExecAdd(n.IPAM.Type, args.StdinData)
result, err := ipam.ExecAdd(n.IPAM.Type, args.StdinData)
if err != nil {
return err
}
@ -135,20 +148,14 @@ func cmdAdd(args *skel.CmdArgs) error {
return errors.New("IPAM plugin returned missing IPv4 config")
}
err = ns.WithNetNS(netns, false, func(_ *os.File) error {
return plugin.ConfigureIface(args.IfName, result)
err = netns.Do(func(_ ns.NetNS) error {
return ipam.ConfigureIface(args.IfName, result)
})
if err != nil {
return err
}
if n.IPMasq {
chain := "CNI-" + n.Name
if err = ip.SetupIPMasq(ip.Network(&result.IP4.IP), chain); err != nil {
return err
}
}
result.DNS = n.DNS
return result.Print()
}
@ -158,12 +165,16 @@ func cmdDel(args *skel.CmdArgs) error {
return err
}
err = plugin.ExecDel(n.IPAM.Type, args.StdinData)
err = ipam.ExecDel(n.IPAM.Type, args.StdinData)
if err != nil {
return err
}
return ns.WithNetNSPath(args.Netns, false, func(hostNS *os.File) error {
if args.Netns == "" {
return nil
}
return ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error {
return ip.DelLinkByName(args.IfName)
})
}

View File

@ -0,0 +1,27 @@
// Copyright 2016 CNI 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.
package main
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestMacvlan(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "macvlan Suite")
}

View File

@ -0,0 +1,168 @@
// Copyright 2015 CNI 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.
package main
import (
"fmt"
"github.com/containernetworking/cni/pkg/ns"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/testutils"
"github.com/containernetworking/cni/pkg/types"
"github.com/vishvananda/netlink"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
const MASTER_NAME = "eth0"
var _ = Describe("macvlan Operations", func() {
var originalNS ns.NetNS
BeforeEach(func() {
// Create a new NetNS so we don't modify the host
var err error
originalNS, err = ns.NewNS()
Expect(err).NotTo(HaveOccurred())
err = originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
// Add master
err = netlink.LinkAdd(&netlink.Dummy{
LinkAttrs: netlink.LinkAttrs{
Name: MASTER_NAME,
},
})
Expect(err).NotTo(HaveOccurred())
_, err = netlink.LinkByName(MASTER_NAME)
Expect(err).NotTo(HaveOccurred())
return nil
})
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
Expect(originalNS.Close()).To(Succeed())
})
It("creates an macvlan link in a non-default namespace", func() {
conf := &NetConf{
NetConf: types.NetConf{
Name: "testConfig",
Type: "macvlan",
},
Master: MASTER_NAME,
Mode: "bridge",
MTU: 1500,
}
targetNs, err := ns.NewNS()
Expect(err).NotTo(HaveOccurred())
defer targetNs.Close()
err = originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
err = createMacvlan(conf, "foobar0", targetNs)
Expect(err).NotTo(HaveOccurred())
return nil
})
Expect(err).NotTo(HaveOccurred())
// Make sure macvlan link exists in the target namespace
err = targetNs.Do(func(ns.NetNS) error {
defer GinkgoRecover()
link, err := netlink.LinkByName("foobar0")
Expect(err).NotTo(HaveOccurred())
Expect(link.Attrs().Name).To(Equal("foobar0"))
return nil
})
Expect(err).NotTo(HaveOccurred())
})
It("configures and deconfigures a macvlan link with ADD/DEL", func() {
const IFNAME = "macvl0"
conf := fmt.Sprintf(`{
"name": "mynet",
"type": "macvlan",
"master": "%s",
"ipam": {
"type": "host-local",
"subnet": "10.1.2.0/24"
}
}`, MASTER_NAME)
targetNs, err := ns.NewNS()
Expect(err).NotTo(HaveOccurred())
defer targetNs.Close()
args := &skel.CmdArgs{
ContainerID: "dummy",
Netns: targetNs.Path(),
IfName: IFNAME,
StdinData: []byte(conf),
}
// Make sure macvlan link exists in the target namespace
err = originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
_, err := testutils.CmdAddWithResult(targetNs.Path(), IFNAME, func() error {
return cmdAdd(args)
})
Expect(err).NotTo(HaveOccurred())
return nil
})
Expect(err).NotTo(HaveOccurred())
// Make sure macvlan link exists in the target namespace
err = targetNs.Do(func(ns.NetNS) error {
defer GinkgoRecover()
link, err := netlink.LinkByName(IFNAME)
Expect(err).NotTo(HaveOccurred())
Expect(link.Attrs().Name).To(Equal(IFNAME))
return nil
})
Expect(err).NotTo(HaveOccurred())
err = originalNS.Do(func(ns.NetNS) error {
defer GinkgoRecover()
err := testutils.CmdDelWithResult(targetNs.Path(), IFNAME, func() error {
return cmdDel(args)
})
Expect(err).NotTo(HaveOccurred())
return nil
})
Expect(err).NotTo(HaveOccurred())
// Make sure macvlan link has been deleted
err = targetNs.Do(func(ns.NetNS) error {
defer GinkgoRecover()
link, err := netlink.LinkByName(IFNAME)
Expect(err).To(HaveOccurred())
Expect(link).To(BeNil())
return nil
})
Expect(err).NotTo(HaveOccurred())
})
})

View File

@ -1,4 +1,4 @@
// Copyright 2015 CoreOS, Inc.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -15,7 +15,6 @@
package main
import (
"crypto/sha512"
"encoding/json"
"errors"
"fmt"
@ -25,10 +24,12 @@ import (
"github.com/vishvananda/netlink"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/ip"
"github.com/containernetworking/cni/pkg/ipam"
"github.com/containernetworking/cni/pkg/ns"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/utils"
)
func init() {
@ -39,24 +40,79 @@ func init() {
}
type NetConf struct {
plugin.NetConf
types.NetConf
IPMasq bool `json:"ipMasq"`
MTU int `json:"mtu"`
}
func setupContainerVeth(netns, ifName string, mtu int, pr *plugin.Result) (string, error) {
func setupContainerVeth(netns, ifName string, mtu int, pr *types.Result) (string, error) {
// The IPAM result will be something like IP=192.168.3.5/24, GW=192.168.3.1.
// What we want is really a point-to-point link but veth does not support IFF_POINTOPONT.
// Next best thing would be to let it ARP but set interface to 192.168.3.5/32 and
// add a route like "192.168.3.0/24 via 192.168.3.1 dev $ifName".
// Unfortunately that won't work as the GW will be outside the interface's subnet.
// Our solution is to configure the interface with 192.168.3.5/24, then delete the
// "192.168.3.0/24 dev $ifName" route that was automatically added. Then we add
// "192.168.3.1/32 dev $ifName" and "192.168.3.0/24 via 192.168.3.1 dev $ifName".
// In other words we force all traffic to ARP via the gateway except for GW itself.
var hostVethName string
err := ns.WithNetNSPath(netns, false, func(hostNS *os.File) error {
err := ns.WithNetNSPath(netns, func(hostNS ns.NetNS) error {
hostVeth, _, err := ip.SetupVeth(ifName, mtu, hostNS)
if err != nil {
return err
}
err = plugin.ConfigureIface(ifName, pr)
if err != nil {
if err = ipam.ConfigureIface(ifName, pr); err != nil {
return err
}
contVeth, err := netlink.LinkByName(ifName)
if err != nil {
return fmt.Errorf("failed to look up %q: %v", ifName, err)
}
// Delete the route that was automatically added
route := netlink.Route{
LinkIndex: contVeth.Attrs().Index,
Dst: &net.IPNet{
IP: pr.IP4.IP.IP.Mask(pr.IP4.IP.Mask),
Mask: pr.IP4.IP.Mask,
},
Scope: netlink.SCOPE_NOWHERE,
}
if err := netlink.RouteDel(&route); err != nil {
return fmt.Errorf("failed to delete route %v: %v", route, err)
}
for _, r := range []netlink.Route{
netlink.Route{
LinkIndex: contVeth.Attrs().Index,
Dst: &net.IPNet{
IP: pr.IP4.Gateway,
Mask: net.CIDRMask(32, 32),
},
Scope: netlink.SCOPE_LINK,
Src: pr.IP4.IP.IP,
},
netlink.Route{
LinkIndex: contVeth.Attrs().Index,
Dst: &net.IPNet{
IP: pr.IP4.IP.IP.Mask(pr.IP4.IP.Mask),
Mask: pr.IP4.IP.Mask,
},
Scope: netlink.SCOPE_UNIVERSE,
Gw: pr.IP4.Gateway,
Src: pr.IP4.IP.IP,
},
} {
if err := netlink.RouteAdd(&r); err != nil {
return fmt.Errorf("failed to add route %v: %v", r, err)
}
}
hostVethName = hostVeth.Attrs().Name
return nil
@ -64,7 +120,7 @@ func setupContainerVeth(netns, ifName string, mtu int, pr *plugin.Result) (strin
return hostVethName, err
}
func setupHostVeth(vethName string, ipConf *plugin.IPConfig) error {
func setupHostVeth(vethName string, ipConf *types.IPConfig) error {
// hostVeth moved namespaces and may have a new ifindex
veth, err := netlink.LinkByName(vethName)
if err != nil {
@ -74,13 +130,17 @@ func setupHostVeth(vethName string, ipConf *plugin.IPConfig) error {
// TODO(eyakubovich): IPv6
ipn := &net.IPNet{
IP: ipConf.Gateway,
Mask: net.CIDRMask(31, 32),
Mask: net.CIDRMask(32, 32),
}
addr := &netlink.Addr{IPNet: ipn, Label: ""}
if err = netlink.AddrAdd(veth, addr); err != nil {
return fmt.Errorf("failed to add IP addr (%#v) to veth: %v", ipn, err)
}
ipn = &net.IPNet{
IP: ipConf.IP.IP,
Mask: net.CIDRMask(32, 32),
}
// dst happens to be the same as IP/net of host veth
if err = ip.AddHostRoute(ipn, nil, veth); err != nil && !os.IsExist(err) {
return fmt.Errorf("failed to add route on host: %v", err)
@ -100,7 +160,7 @@ func cmdAdd(args *skel.CmdArgs) error {
}
// run the IPAM plugin and get back the config to apply
result, err := plugin.ExecAdd(conf.IPAM.Type, args.StdinData)
result, err := ipam.ExecAdd(conf.IPAM.Type, args.StdinData)
if err != nil {
return err
}
@ -118,13 +178,14 @@ func cmdAdd(args *skel.CmdArgs) error {
}
if conf.IPMasq {
h := sha512.Sum512([]byte(args.ContainerID))
chain := fmt.Sprintf("CNI-%s-%x", conf.Name, h[:8])
if err = ip.SetupIPMasq(&result.IP4.IP, chain); err != nil {
chain := utils.FormatChainName(conf.Name, args.ContainerID)
comment := utils.FormatComment(conf.Name, args.ContainerID)
if err = ip.SetupIPMasq(&result.IP4.IP, chain, comment); err != nil {
return err
}
}
result.DNS = conf.DNS
return result.Print()
}
@ -134,8 +195,16 @@ func cmdDel(args *skel.CmdArgs) error {
return fmt.Errorf("failed to load netconf: %v", err)
}
if err := ipam.ExecDel(conf.IPAM.Type, args.StdinData); err != nil {
return err
}
if args.Netns == "" {
return nil
}
var ipn *net.IPNet
err := ns.WithNetNSPath(args.Netns, false, func(hostNS *os.File) error {
err := ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error {
var err error
ipn, err = ip.DelLinkByNameAddr(args.IfName, netlink.FAMILY_V4)
return err
@ -145,14 +214,14 @@ func cmdDel(args *skel.CmdArgs) error {
}
if conf.IPMasq {
h := sha512.Sum512([]byte(args.ContainerID))
chain := fmt.Sprintf("CNI-%s-%x", conf.Name, h[:8])
if err = ip.TeardownIPMasq(ipn, chain); err != nil {
chain := utils.FormatChainName(conf.Name, args.ContainerID)
comment := utils.FormatComment(conf.Name, args.ContainerID)
if err = ip.TeardownIPMasq(ipn, chain, comment); err != nil {
return err
}
}
return plugin.ExecDel(conf.IPAM.Type, args.StdinData)
return nil
}
func main() {

View File

@ -1,4 +1,4 @@
// Copyright 2015 CNI Authors.
// Copyright 2015 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -29,8 +29,9 @@ import (
"strconv"
"strings"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/invoke"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
)
const (
@ -39,15 +40,34 @@ const (
)
type NetConf struct {
plugin.NetConf
types.NetConf
SubnetFile string `json:"subnetFile"`
Delegate map[string]interface{} `json:"delegate"`
}
type subnetEnv struct {
nw *net.IPNet
sn *net.IPNet
mtu uint
ipmasq bool
mtu *uint
ipmasq *bool
}
func (se *subnetEnv) missing() string {
m := []string{}
if se.nw == nil {
m = append(m, "FLANNEL_NETWORK")
}
if se.sn == nil {
m = append(m, "FLANNEL_SUBNET")
}
if se.mtu == nil {
m = append(m, "FLANNEL_MTU")
}
if se.ipmasq == nil {
m = append(m, "FLANNEL_IPMASQ")
}
return strings.Join(m, ", ")
}
func loadFlannelNetConf(bytes []byte) (*NetConf, error) {
@ -73,6 +93,12 @@ func loadFlannelSubnetEnv(fn string) (*subnetEnv, error) {
for s.Scan() {
parts := strings.SplitN(s.Text(), "=", 2)
switch parts[0] {
case "FLANNEL_NETWORK":
_, se.nw, err = net.ParseCIDR(parts[1])
if err != nil {
return nil, err
}
case "FLANNEL_SUBNET":
_, se.sn, err = net.ParseCIDR(parts[1])
if err != nil {
@ -84,16 +110,22 @@ func loadFlannelSubnetEnv(fn string) (*subnetEnv, error) {
if err != nil {
return nil, err
}
se.mtu = uint(mtu)
se.mtu = new(uint)
*se.mtu = uint(mtu)
case "FLANNEL_IPMASQ":
se.ipmasq = parts[1] == "true"
ipmasq := parts[1] == "true"
se.ipmasq = &ipmasq
}
}
if err := s.Err(); err != nil {
return nil, err
}
if m := se.missing(); m != "" {
return nil, fmt.Errorf("%v is missing %v", fn, m)
}
return se, nil
}
@ -123,7 +155,7 @@ func delegateAdd(cid string, netconf map[string]interface{}) error {
return err
}
result, err := plugin.ExecAdd(netconf["type"].(string), netconfBytes)
result, err := invoke.DelegateAdd(netconf["type"].(string), netconfBytes)
if err != nil {
return err
}
@ -174,7 +206,7 @@ func cmdAdd(args *skel.CmdArgs) error {
if !hasKey(n.Delegate, "ipMasq") {
// if flannel is not doing ipmasq, we should
ipmasq := !fenv.ipmasq
ipmasq := !*fenv.ipmasq
n.Delegate["ipMasq"] = ipmasq
}
@ -189,9 +221,14 @@ func cmdAdd(args *skel.CmdArgs) error {
}
}
n.Delegate["ipam"] = map[string]string{
n.Delegate["ipam"] = map[string]interface{}{
"type": "host-local",
"subnet": fenv.sn.String(),
"routes": []types.Route{
types.Route{
Dst: *fenv.nw,
},
},
}
return delegateAdd(args.ContainerID, n.Delegate)
@ -203,12 +240,12 @@ func cmdDel(args *skel.CmdArgs) error {
return err
}
n := &plugin.NetConf{}
n := &types.NetConf{}
if err = json.Unmarshal(netconfBytes, n); err != nil {
return fmt.Errorf("failed to parse netconf: %v", err)
}
return plugin.ExecDel(n.Type, netconfBytes)
return invoke.DelegateDel(n.Type, netconfBytes)
}
func main() {

View File

@ -0,0 +1,82 @@
// Copyright 2016 CNI 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 "meta-plugin". It reads in its own netconf, it does not create
// any network interface but just changes the network sysctl.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"github.com/containernetworking/cni/pkg/ns"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
)
// TuningConf represents the network tuning configuration.
type TuningConf struct {
types.NetConf
SysCtl map[string]string `json:"sysctl"`
}
func cmdAdd(args *skel.CmdArgs) error {
tuningConf := TuningConf{}
if err := json.Unmarshal(args.StdinData, &tuningConf); err != nil {
return fmt.Errorf("failed to load netconf: %v", err)
}
// The directory /proc/sys/net is per network namespace. Enter in the
// network namespace before writing on it.
err := ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error {
for key, value := range tuningConf.SysCtl {
fileName := filepath.Join("/proc/sys", strings.Replace(key, ".", "/", -1))
fileName = filepath.Clean(fileName)
// Refuse to modify sysctl parameters that don't belong
// to the network subsystem.
if !strings.HasPrefix(fileName, "/proc/sys/net/") {
return fmt.Errorf("invalid net sysctl key: %q", key)
}
content := []byte(value)
err := ioutil.WriteFile(fileName, content, 0644)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
result := types.Result{}
return result.Print()
}
func cmdDel(args *skel.CmdArgs) error {
// TODO: the settings are not reverted to the previous values. Reverting the
// settings is not useful when the whole container goes away but it could be
// useful in scenarios where plugins are added and removed at runtime.
return nil
}
func main() {
skel.PluginMain(cmdAdd, cmdDel)
}

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