Compare commits

..

150 Commits

Author SHA1 Message Date
a721ce6bbf build/release: link all release binaries statically 2016-04-28 22:40:59 +02:00
5ab94d6e50 scripts: build static releases and create an ACI
* use SHA1 instead of MD5
2016-04-23 00:53:20 +02:00
2ea9379fa4 travis: don't go get vet 2016-04-22 20:13:37 +02:00
cf43d2f78f scripts: add "release with rkt"
This script uses rkt and a fedora image to build release tarballs.
2016-04-22 19:36:38 +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
430 changed files with 17992 additions and 3217 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

73
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,73 @@
# 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.
For more information on the policy for accepting contributions, see [POLICY](POLICY.md)
# 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 #appc on Freenode for chat:
- Email: [cni-dev](https://groups.google.com/forum/#!forum/cni-dev)
- IRC: #[appc](irc://irc.freenode.org:6667/#appc) IRC 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 patches!
## Contribution Flow
This is a rough outline of what a contributor's workflow looks like:
- Create a topic branch from where you want to base your work (usually 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.
- Make sure the tests pass, and add any new tests as appropriate.
- Submit a pull request to the original repository.
Thanks for your contributions!
### 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

@ -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/appc/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/)

156
Godeps/Godeps.json generated
View File

@ -1,13 +1,14 @@
{
"ImportPath": "github.com/appc/cni",
"GoVersion": "go1.4.2",
"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")
}
}

3
MAINTAINERS Normal file
View File

@ -0,0 +1,3 @@
Michael Bridgen <michael@weave.works> (@squaremo)
Stefan Junker <stefan.junker@coreos.com> (@steveeJ)
Zach Gershman <zachgersh@gmail.com> (@zachgersh)

View File

@ -1,33 +1,57 @@
# cni - the Container Network Interface
[![Build Status](https://travis-ci.org/appc/cni.svg?branch=master)](https://travis-ci.org/appc/cni)
[![Coverage Status](https://coveralls.io/repos/github/appc/cni/badge.svg?branch=master)](https://coveralls.io/github/appc/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 standard consists of a simple specification for how executable plugins can be used to configure network namespaces; this repository also contains a go library implementing that specification.
The specification itself is contained in [SPEC.md](SPEC.md).
## 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.
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.
## 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)
## Contributing to CNI
We welcome contributions, including [bug reports](https://github.com/appc/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
CNI requires Go 1.5+ to build.
## 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.
Go 1.5 users will need to set GO15VENDOREXPERIMENT=1 to get vendored
dependencies. This flag is set by default in 1.6.
## 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.
### 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 +69,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 +109,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 +138,9 @@ lo Link encap:Local Loopback
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
```
## Contact
For any questions about CNI, please reach out on the mailing list or IRC:
- Email: [cni-dev](https://groups.google.com/forum/#!forum/cni-dev)
- IRC: #[appc](irc://irc.freenode.org:6667/#appc) IRC channel on freenode.org

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

19
build
View File

@ -1,4 +1,5 @@
#!/bin/bash -e
#!/usr/bin/env bash
set -xe
ORG_PATH="github.com/appc"
REPO_PATH="${ORG_PATH}/cni"
@ -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/appc/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/appc/cni/pkg/invoke"
"github.com/appc/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, ";")
}

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

@ -0,0 +1,39 @@
package invoke
import (
"fmt"
"os"
"strings"
"github.com/appc/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/appc/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
}

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

@ -0,0 +1,64 @@
package invoke_test
import (
"fmt"
"io/ioutil"
"path/filepath"
"github.com/appc/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,13 @@
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/appc/cni/pkg/ns"
"github.com/vishvananda/netlink"
)
@ -78,7 +79,8 @@ func RandomVethName() (string, error) {
}
// SetupVeth sets up a virtual ethernet link.
// Should be in container netns.
// 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 *os.File) (hostVeth, contVeth netlink.Link, err error) {
var hostVethName string
hostVethName, contVeth, err = makeVeth(contVethName, mtu)
@ -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 = ns.WithNetNS(hostNS, false, func(_ *os.File) error {
hostVeth, err := netlink.LinkByName(hostVethName)
if err != nil {
return fmt.Errorf("failed to lookup %q in %q: %v", hostVethName, hostNS.Name(), 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/appc/cni/pkg/invoke"
"github.com/appc/cni/pkg/ip"
"github.com/appc/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
}

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.
@ -66,7 +66,8 @@ func WithNetNSPath(nspath string, lockThread bool, f func(*os.File) error) error
// 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
// returning. If the closure returns an error, WithNetNS attempts to
// restore the original namespace before returning.
func WithNetNS(ns *os.File, lockThread bool, f func(*os.File) error) error {
if lockThread {
runtime.LockOSThread()
@ -82,11 +83,11 @@ func WithNetNS(ns *os.File, lockThread bool, f func(*os.File) error) error {
if err = SetNS(ns, syscall.CLONE_NEWNET); err != nil {
return fmt.Errorf("Error switching to ns %v: %v", ns.Name(), err)
}
defer SetNS(thisNS, syscall.CLONE_NEWNET) // switch back
if err = f(thisNS); err != nil {
return err
}
// switch back
return SetNS(thisNS, syscall.CLONE_NEWNET)
return nil
}

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

@ -0,0 +1,20 @@
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")
}

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

@ -0,0 +1,153 @@
package ns_test
import (
"errors"
"fmt"
"math/rand"
"os"
"os/exec"
"path/filepath"
"golang.org/x/sys/unix"
"github.com/appc/cni/pkg/ns"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func getInode(path string) (uint64, error) {
file, err := os.Open(path)
if err != nil {
return 0, err
}
defer file.Close()
return getInodeF(file)
}
func getInodeF(file *os.File) (uint64, error) {
stat := &unix.Stat_t{}
err := unix.Fstat(int(file.Fd()), stat)
return stat.Ino, err
}
const CurrentNetNS = "/proc/self/ns/net"
var _ = Describe("Linux namespace operations", func() {
Describe("WithNetNS", func() {
var (
originalNetNS *os.File
targetNetNSName string
targetNetNSPath string
targetNetNS *os.File
)
BeforeEach(func() {
var err error
originalNetNS, err = os.Open(CurrentNetNS)
Expect(err).NotTo(HaveOccurred())
targetNetNSName = fmt.Sprintf("test-netns-%d", rand.Int())
err = exec.Command("ip", "netns", "add", targetNetNSName).Run()
Expect(err).NotTo(HaveOccurred())
targetNetNSPath = filepath.Join("/var/run/netns/", targetNetNSName)
targetNetNS, err = os.Open(targetNetNSPath)
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
Expect(targetNetNS.Close()).To(Succeed())
err := exec.Command("ip", "netns", "del", targetNetNSName).Run()
Expect(err).NotTo(HaveOccurred())
Expect(originalNetNS.Close()).To(Succeed())
})
It("executes the callback within the target network namespace", func() {
expectedInode, err := getInode(targetNetNSPath)
Expect(err).NotTo(HaveOccurred())
var actualInode uint64
var innerErr error
err = ns.WithNetNS(targetNetNS, false, func(*os.File) error {
actualInode, innerErr = getInode(CurrentNetNS)
return nil
})
Expect(err).NotTo(HaveOccurred())
Expect(innerErr).NotTo(HaveOccurred())
Expect(actualInode).To(Equal(expectedInode))
})
It("provides the original namespace as the argument to the callback", func() {
hostNSInode, err := getInode(CurrentNetNS)
Expect(err).NotTo(HaveOccurred())
var inputNSInode uint64
var innerErr error
err = ns.WithNetNS(targetNetNS, false, func(inputNS *os.File) error {
inputNSInode, err = getInodeF(inputNS)
return nil
})
Expect(err).NotTo(HaveOccurred())
Expect(innerErr).NotTo(HaveOccurred())
Expect(inputNSInode).To(Equal(hostNSInode))
})
It("restores the calling thread to the original network namespace", func() {
preTestInode, err := getInode(CurrentNetNS)
Expect(err).NotTo(HaveOccurred())
err = ns.WithNetNS(targetNetNS, false, func(*os.File) error {
return nil
})
Expect(err).NotTo(HaveOccurred())
postTestInode, err := getInode(CurrentNetNS)
Expect(err).NotTo(HaveOccurred())
Expect(postTestInode).To(Equal(preTestInode))
})
Context("when the callback returns an error", func() {
It("restores the calling thread to the original namespace before returning", func() {
preTestInode, err := getInode(CurrentNetNS)
Expect(err).NotTo(HaveOccurred())
_ = ns.WithNetNS(targetNetNS, false, func(*os.File) error {
return errors.New("potato")
})
postTestInode, err := getInode(CurrentNetNS)
Expect(err).NotTo(HaveOccurred())
Expect(postTestInode).To(Equal(preTestInode))
})
It("returns the error from the callback", func() {
err := ns.WithNetNS(targetNetNS, false, func(*os.File) 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() {
hostNSInode, err := getInode(CurrentNetNS)
Expect(err).NotTo(HaveOccurred())
testNsInode, err := getInode(targetNetNSPath)
Expect(err).NotTo(HaveOccurred())
Expect(hostNSInode).NotTo(Equal(0))
Expect(testNsInode).NotTo(Equal(0))
Expect(testNsInode).NotTo(Equal(hostNSInode))
})
})
})
})

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/appc/cni/pkg/types"
)
// CmdArgs captures all the arguments passed in to the plugin
@ -93,7 +93,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 +102,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,13 @@
package skel
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestSkel(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Skel Suite")
}

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

@ -0,0 +1,61 @@
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)
// })
})
})

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
}

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

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

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

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

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

@ -0,0 +1,37 @@
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/appc/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.
@ -28,7 +28,7 @@ import (
"github.com/vishvananda/netlink"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/types"
)
// RFC 2131 suggests using exponential backoff, starting with 4sec
@ -118,6 +118,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 +292,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/appc/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/appc/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/appc/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.
@ -19,7 +19,7 @@ import (
"net"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/types"
"github.com/appc/cni/plugins/ipam/host-local/backend"
)
@ -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/appc/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/appc/cni/plugins/ipam/host-local/backend/disk"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/appc/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.
@ -24,16 +24,18 @@ import (
"syscall"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/ipam"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/appc/cni/pkg/types"
"github.com/appc/cni/pkg/utils"
"github.com/vishvananda/netlink"
)
const defaultBrName = "cni0"
type NetConf struct {
plugin.NetConf
types.NetConf
BrName string `json:"bridge"`
IsGW bool `json:"isGateway"`
IPMasq bool `json:"ipMasq"`
@ -183,7 +185,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
}
@ -197,7 +199,7 @@ func cmdAdd(args *skel.CmdArgs) error {
}
err = ns.WithNetNSPath(args.Netns, false, func(hostNS *os.File) error {
return plugin.ConfigureIface(args.IfName, result)
return ipam.ConfigureIface(args.IfName, result)
})
if err != nil {
return err
@ -219,12 +221,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,7 +238,7 @@ 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
}

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.
@ -22,17 +22,17 @@ import (
"runtime"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/ipam"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/appc/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"`
}
@ -123,7 +123,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
}
@ -132,19 +132,13 @@ func cmdAdd(args *skel.CmdArgs) error {
}
err = ns.WithNetNS(netns, false, func(_ *os.File) error {
return plugin.ConfigureIface(args.IfName, result)
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,7 +148,7 @@ 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
}

View File

@ -0,0 +1,59 @@
package main
import (
"os"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/skel"
"github.com/appc/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, false, func(hostNS *os.File) 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, false, func(hostNS *os.File) 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,77 @@
package main_test
import (
"fmt"
"os"
"runtime"
"github.com/onsi/gomega/gexec"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
"golang.org/x/sys/unix"
)
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/appc/cni/plugins/main/loopback")
Expect(err).NotTo(HaveOccurred())
})
var _ = AfterSuite(func() {
gexec.CleanupBuildArtifacts()
})
func makeNetworkNS(containerID string) string {
namespace := "/var/run/netns/" + containerID
pid := unix.Getpid()
tid := unix.Gettid()
err := os.MkdirAll("/var/run/netns", 0600)
Expect(err).NotTo(HaveOccurred())
runtime.LockOSThread()
defer runtime.UnlockOSThread()
go (func() {
defer GinkgoRecover()
err = unix.Unshare(unix.CLONE_NEWNET)
Expect(err).NotTo(HaveOccurred())
fd, err := os.Create(namespace)
Expect(err).NotTo(HaveOccurred())
defer fd.Close()
err = unix.Mount("/proc/self/ns/net", namespace, "none", unix.MS_BIND, "")
Expect(err).NotTo(HaveOccurred())
})()
Eventually(namespace).Should(BeAnExistingFile())
fd, err := unix.Open(fmt.Sprintf("/proc/%d/task/%d/ns/net", pid, tid), unix.O_RDONLY, 0)
Expect(err).NotTo(HaveOccurred())
defer unix.Close(fd)
_, _, e1 := unix.Syscall(unix.SYS_SETNS, uintptr(fd), uintptr(unix.CLONE_NEWNET), 0)
Expect(e1).To(BeZero())
return namespace
}
func removeNetworkNS(networkNS string) error {
err := unix.Unmount(networkNS, unix.MNT_DETACH)
err = os.RemoveAll(networkNS)
return err
}

View File

@ -0,0 +1,85 @@
package main_test
import (
"fmt"
"net"
"os"
"os/exec"
"strings"
"github.com/appc/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 string
containerID string
command *exec.Cmd
environ []string
)
BeforeEach(func() {
command = exec.Command(pathToLoPlugin)
containerID = "some-container-id"
networkNS = makeNetworkNS(containerID)
environ = []string{
fmt.Sprintf("CNI_CONTAINERID=%s", containerID),
fmt.Sprintf("CNI_NETNS=%s", networkNS),
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(removeNetworkNS(networkNS)).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 = ns.WithNetNSPath(networkNS, true, func(hostNS *os.File) 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 = ns.WithNetNSPath(networkNS, true, func(hostNS *os.File) 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.
@ -22,17 +22,17 @@ import (
"runtime"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/ipam"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/appc/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"`
}
@ -127,7 +127,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
}
@ -136,19 +136,13 @@ func cmdAdd(args *skel.CmdArgs) error {
}
err = ns.WithNetNS(netns, false, func(_ *os.File) error {
return plugin.ConfigureIface(args.IfName, result)
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,7 +152,7 @@ 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
}

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"
@ -26,9 +25,11 @@ import (
"github.com/vishvananda/netlink"
"github.com/appc/cni/pkg/ip"
"github.com/appc/cni/pkg/ipam"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/plugin"
"github.com/appc/cni/pkg/skel"
"github.com/appc/cni/pkg/types"
"github.com/appc/cni/pkg/utils"
)
func init() {
@ -39,12 +40,23 @@ 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 {
hostVeth, _, err := ip.SetupVeth(ifName, mtu, hostNS)
@ -52,11 +64,55 @@ func setupContainerVeth(netns, ifName string, mtu int, pr *plugin.Result) (strin
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()
}
@ -145,14 +206,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 ipam.ExecDel(conf.IPAM.Type, args.StdinData)
}
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/invoke"
"github.com/appc/cni/pkg/skel"
"github.com/appc/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,83 @@
// 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"
"os"
"path/filepath"
"strings"
"github.com/appc/cni/pkg/ns"
"github.com/appc/cni/pkg/skel"
"github.com/appc/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, false, func(hostNS *os.File) 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)
}

View File

@ -1,4 +1,6 @@
#!/bin/bash
#!/usr/bin/env bash
if [[ ${DEBUG} -gt 0 ]]; then set -x; fi
NETCONFPATH=${NETCONFPATH-/etc/cni/net.d}
@ -25,6 +27,8 @@ function exec_plugins() {
echo "${name} : error executing $CNI_COMMAND: $errmsg"
exit 1
elif [[ ${DEBUG} -gt 0 ]]; then
echo ${res} | jq -r .
fi
let "i=i+1"

View File

@ -1,4 +1,6 @@
#!/bin/bash -e
#!/usr/bin/env bash
set -e
if [[ ${DEBUG} -gt 0 ]]; then set -x; fi
# Run a command in a private network namespace
# set up by CNI plugins
@ -6,7 +8,6 @@ contid=$(printf '%x%x%x%x' $RANDOM $RANDOM $RANDOM $RANDOM)
netnspath=/var/run/netns/$contid
ip netns add $contid
ip netns exec $contid ip link set lo up
./exec-plugins.sh add $contid $netnspath

44
scripts/release-with-rkt.sh Executable file
View File

@ -0,0 +1,44 @@
#!/usr/bin/env bash
set -xe
SRC_DIR="${SRC_DIR:-$PWD}"
FEDORA_INSTALL="dnf install -y golang tar xz bzip2 gzip sudo iproute wget"
FEDORA_IMAGE="docker://fedora:23"
ACBUILD_URL="https://github.com/appc/acbuild/releases/download/v0.2.2/acbuild.tar.gz"
ACBUILD="acbuild --debug"
BUILDFLAGS="-a --ldflags '-extldflags \"-static\"'"
TAG=$(git describe --exact-match --abbrev=0) || TAG=$(git describe)
RELEASE_DIR=release-${TAG}
OUTPUT_DIR=bin
rm -Rf ${SRC_DIR}/${RELEASE_DIR}
mkdir -p ${SRC_DIR}/${RELEASE_DIR}
sudo -E rkt run \
--volume rslvconf,kind=host,source=/etc/resolv.conf \
--mount volume=rslvconf,target=/etc/resolv.conf \
--volume src-dir,kind=host,source=$SRC_DIR \
--mount volume=src-dir,target=/opt/src \
--interactive \
--insecure-options=image \
${FEDORA_IMAGE} \
--exec /bin/bash \
-- -xe -c "\
${FEDORA_INSTALL}; cd /opt/src; umask 0022; CGO_ENABLED=0 ./build ${BUILDFLAGS}; ./test || true; \
for format in txz tbz2 tgz; do \
FILENAME=cni-${TAG}.\$format; \
FILEPATH=${RELEASE_DIR}/\$FILENAME; \
tar -C ${OUTPUT_DIR} --owner=0 --group=0 -caf \$FILEPATH .; \
done; \
wget -O - ${ACBUILD_URL} | tar -C /usr/bin -xzvf -; \
${ACBUILD} begin; \
${ACBUILD} set-name coreos.com/cni; \
${ACBUILD} label add version ${TAG}; \
${ACBUILD} copy --to-dir ${OUTPUT_DIR} /opt/cni/; \
${ACBUILD} write ${RELEASE_DIR}/cni-${TAG}.aci; \
${ACBUILD} end; \
pushd ${RELEASE_DIR}; for f in \$(ls); do sha1sum \$f > \$f.sha1; done; popd; \
chown -R ${UID} ${OUTPUT_DIR} ${RELEASE_DIR}; \
:"

68
test Executable file
View File

@ -0,0 +1,68 @@
#!/usr/bin/env bash
#
# Run all CNI tests
# ./test
# ./test -v
#
# Run tests for one package
# PKG=./plugins/ipam/dhcp ./test
#
set -e
source ./build
TESTABLE="plugins/ipam/dhcp plugins/main/loopback pkg/invoke pkg/ns pkg/skel pkg/types pkg/utils"
FORMATTABLE="$TESTABLE libcni pkg/ip pkg/ns pkg/types pkg/ipam plugins/ipam/host-local plugins/main/bridge plugins/meta/flannel plugins/meta/tuning"
# user has not provided PKG override
if [ -z "$PKG" ]; then
TEST=$TESTABLE
FMT=$FORMATTABLE
# user has provided PKG override
else
# strip out slashes and dots from PKG=./foo/
TEST=${PKG//\//}
TEST=${TEST//./}
# only run gofmt on packages provided by user
FMT="$TEST"
fi
# split TEST into an array and prepend REPO_PATH to each local package
split=(${TEST// / })
TEST=${split[@]/#/${REPO_PATH}/}
echo -n "Running tests "
function testrun {
sudo -E bash -c "umask 0; PATH=\$GOROOT/bin:\$PATH go test -covermode set $@"
}
if [ ! -z "${COVERALLS}" ]; then
echo "with coverage profile generation..."
i=0
for t in ${TEST}; do
testrun "-coverprofile ${i}.coverprofile ${t}"
i=$((i+1))
done
gover
goveralls -service=travis-ci -coverprofile=gover.coverprofile -repotoken=$COVERALLS_TOKEN
else
echo "without coverage profile generation..."
testrun "${TEST}"
fi
echo "Checking gofmt..."
fmtRes=$(gofmt -l $FMT)
if [ -n "${fmtRes}" ]; then
echo -e "gofmt checking failed:\n${fmtRes}"
exit 255
fi
echo "Checking govet..."
vetRes=$(go vet $TEST)
if [ -n "${vetRes}" ]; then
echo -e "govet checking failed:\n${vetRes}"
exit 255
fi
echo "Success"

191
vendor/github.com/coreos/go-iptables/LICENSE generated vendored Normal file
View File

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of
this License; and
You must cause any modified files to carry prominent notices stating that You
changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -17,7 +17,7 @@ package iptables
import (
"bytes"
"fmt"
"log"
"io"
"os/exec"
"regexp"
"strconv"
@ -40,7 +40,9 @@ func (e *Error) Error() string {
}
type IPTables struct {
path string
path string
hasCheck bool
hasWait bool
}
func New() (*IPTables, error) {
@ -48,33 +50,34 @@ func New() (*IPTables, error) {
if err != nil {
return nil, err
}
return &IPTables{path}, nil
checkPresent, waitPresent, err := getIptablesCommandSupport()
if err != nil {
return nil, fmt.Errorf("error checking iptables version: %v", err)
}
ipt := IPTables{
path: path,
hasCheck: checkPresent,
hasWait: waitPresent,
}
return &ipt, nil
}
// Exists checks if given rulespec in specified table/chain exists
func (ipt *IPTables) Exists(table, chain string, rulespec...string) (bool, error) {
checkPresent, err := getIptablesHasCheckCommand()
if err != nil {
log.Printf("Error checking iptables version, assuming version at least 1.4.11: %v", err)
checkPresent = true
func (ipt *IPTables) Exists(table, chain string, rulespec ...string) (bool, error) {
if !ipt.hasCheck {
return ipt.existsForOldIptables(table, chain, rulespec)
}
if !checkPresent {
cmd := append([]string{"-A", chain}, rulespec...)
return existsForOldIpTables(table, strings.Join(cmd, " "))
} else {
cmd := append([]string{"-t", table, "-C", chain}, rulespec...)
err := ipt.run(cmd...)
switch {
case err == nil:
return true, nil
case err.(*Error).ExitStatus() == 1:
return false, nil
default:
return false, err
}
cmd := append([]string{"-t", table, "-C", chain}, rulespec...)
err := ipt.run(cmd...)
eerr, eok := err.(*Error)
switch {
case err == nil:
return true, nil
case eok && eerr.ExitStatus() == 1:
return false, nil
default:
return false, err
}
}
@ -112,16 +115,10 @@ func (ipt *IPTables) Delete(table, chain string, rulespec ...string) error {
// List rules in specified table/chain
func (ipt *IPTables) List(table, chain string) ([]string, error) {
var stdout, stderr bytes.Buffer
cmd := exec.Cmd{
Path: ipt.path,
Args: []string{ipt.path, "-t", table, "-S", chain},
Stdout: &stdout,
Stderr: &stderr,
}
if err := cmd.Run(); err != nil {
return nil, &Error{*(err.(*exec.ExitError)), stderr.String()}
args := []string{"-t", table, "-S", chain}
var stdout bytes.Buffer
if err := ipt.runWithOutput(args, &stdout); err != nil {
return nil, err
}
rules := strings.Split(stdout.String(), "\n")
@ -136,15 +133,16 @@ func (ipt *IPTables) NewChain(table, chain string) error {
return ipt.run("-t", table, "-N", chain)
}
// ClearChain flushed (deletes all rules) in the specifed table/chain.
// If the chain does not exist, new one will be created
// ClearChain flushed (deletes all rules) in the specified table/chain.
// If the chain does not exist, a new one will be created
func (ipt *IPTables) ClearChain(table, chain string) error {
err := ipt.NewChain(table, chain)
eerr, eok := err.(*Error)
switch {
case err == nil:
return nil
case err.(*Error).ExitStatus() == 1:
case eok && eerr.ExitStatus() == 1:
// chain already exists. Flush (clear) it.
return ipt.run("-t", table, "-F", chain)
default:
@ -152,17 +150,46 @@ func (ipt *IPTables) ClearChain(table, chain string) error {
}
}
// RenameChain renames the old chain to the new one.
func (ipt *IPTables) RenameChain(table, oldChain, newChain string) error {
return ipt.run("-t", table, "-E", oldChain, newChain)
}
// DeleteChain deletes the chain in the specified table.
// The chain must be empty
func (ipt *IPTables) DeleteChain(table, chain string) error {
return ipt.run("-t", table, "-X", chain)
}
func (ipt *IPTables) run(args... string) error {
// run runs an iptables command with the given arguments, ignoring
// any stdout output
func (ipt *IPTables) run(args ...string) error {
return ipt.runWithOutput(args, nil)
}
// runWithOutput runs an iptables command with the given arguments,
// writing any stdout output to the given writer
func (ipt *IPTables) runWithOutput(args []string, stdout io.Writer) error {
args = append([]string{ipt.path}, args...)
if ipt.hasWait {
args = append(args, "--wait")
} else {
fmu, err := newXtablesFileLock()
if err != nil {
return err
}
ul, err := fmu.tryLock()
if err != nil {
return err
}
defer ul.Unlock()
}
var stderr bytes.Buffer
cmd := exec.Cmd{
Path: ipt.path,
Args: append([]string{ipt.path}, args...),
Path: ipt.path,
Args: args,
Stdout: stdout,
Stderr: &stderr,
}
@ -173,19 +200,19 @@ func (ipt *IPTables) run(args... string) error {
return nil
}
// Checks if iptables has the "-C" flag
func getIptablesHasCheckCommand() (bool, error) {
// Checks if iptables has the "-C" and "--wait" flag
func getIptablesCommandSupport() (bool, bool, error) {
vstring, err := getIptablesVersionString()
if err != nil {
return false, err
return false, false, err
}
v1, v2, v3, err := extractIptablesVersion(vstring)
if err != nil {
return false, err
return false, false, err
}
return iptablesHasCheckCommand(v1, v2, v3), nil
return iptablesHasCheckCommand(v1, v2, v3), iptablesHasWaitCommand(v1, v2, v3), nil
}
// getIptablesVersion returns the first three components of the iptables version.
@ -241,15 +268,28 @@ func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
return false
}
// Checks if an iptables version is after 1.4.20, when --wait was added
func iptablesHasWaitCommand(v1 int, v2 int, v3 int) bool {
if v1 > 1 {
return true
}
if v1 == 1 && v2 > 4 {
return true
}
if v1 == 1 && v2 == 4 && v3 >= 20 {
return true
}
return false
}
// Checks if a rule specification exists for a table
func existsForOldIpTables(table string, ruleSpec string) (bool, error) {
cmd := exec.Command("iptables", "-t", table, "-S")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
func (ipt *IPTables) existsForOldIptables(table, chain string, rulespec []string) (bool, error) {
rs := strings.Join(append([]string{"-A", chain}, rulespec...), " ")
args := []string{"-t", table, "-S"}
var stdout bytes.Buffer
err := ipt.runWithOutput(args, &stdout)
if err != nil {
return false, err
}
rules := out.String()
return strings.Contains(rules, ruleSpec), nil
return strings.Contains(stdout.String(), rs), nil
}

84
vendor/github.com/coreos/go-iptables/iptables/lock.go generated vendored Normal file
View File

@ -0,0 +1,84 @@
// 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 (
"os"
"sync"
"syscall"
)
const (
// In earlier versions of iptables, the xtables lock was implemented
// via a Unix socket, but now flock is used via this lockfile:
// http://git.netfilter.org/iptables/commit/?id=aa562a660d1555b13cffbac1e744033e91f82707
// Note the LSB-conforming "/run" directory does not exist on old
// distributions, so assume "/var" is symlinked
xtablesLockFilePath = "/var/run/xtables.lock"
defaultFilePerm = 0600
)
type Unlocker interface {
Unlock() error
}
type nopUnlocker struct{}
func (_ nopUnlocker) Unlock() error { return nil }
type fileLock struct {
// mu is used to protect against concurrent invocations from within this process
mu sync.Mutex
fd int
}
// tryLock takes an exclusive lock on the xtables lock file without blocking.
// This is best-effort only: if the exclusive lock would block (i.e. because
// another process already holds it), no error is returned. Otherwise, any
// error encountered during the locking operation is returned.
// The returned Unlocker should be used to release the lock when the caller is
// done invoking iptables commands.
func (l *fileLock) tryLock() (Unlocker, error) {
l.mu.Lock()
err := syscall.Flock(l.fd, syscall.LOCK_EX|syscall.LOCK_NB)
switch err {
case syscall.EWOULDBLOCK:
l.mu.Unlock()
return nopUnlocker{}, nil
case nil:
return l, nil
default:
l.mu.Unlock()
return nil, err
}
}
// Unlock closes the underlying file, which implicitly unlocks it as well. It
// also unlocks the associated mutex.
func (l *fileLock) Unlock() error {
defer l.mu.Unlock()
return syscall.Close(l.fd)
}
// newXtablesFileLock opens a new lock on the xtables lockfile without
// acquiring the lock
func newXtablesFileLock() (*fileLock, error) {
fd, err := syscall.Open(xtablesLockFilePath, os.O_CREATE, defaultFilePerm)
if err != nil {
return nil, err
}
return &fileLock{fd: fd}, nil
}

191
vendor/github.com/coreos/go-systemd/LICENSE generated vendored Normal file
View File

@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of
this License; and
You must cause any modified files to carry prominent notices stating that You
changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

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