Compare commits

...

173 Commits

Author SHA1 Message Date
Bob Lantz 703c6b102f Clean up makeIntfPair to prepare for pid namespaces, chroot 2013-07-04 18:38:57 -07:00
Bob Lantz b6a1084326 Don't use mnexec if we're not attaching to a cgroup. 2013-04-26 18:01:11 -07:00
Bob Lantz 93085f1cad Clean up shutdown messages, and remove stale namespaces
Note that we can't actually use ip netns del to remove the namespaces
untill ALL of the processes are gone, necessitating this cleanup.
2013-04-26 14:48:46 -07:00
Bob Lantz f69664cd90 Remove redundant intf delete, and try (!) to delete netns 2013-04-26 14:47:29 -07:00
Bob Lantz 1e41c8342c Change to use ip netns exec 2013-04-26 14:46:59 -07:00
Bob Lantz 99f08f98e2 Look for mininet: and print error rather than exception 2013-04-26 14:46:25 -07:00
Bob Lantz 947337c1dc Let Mininet() explicitly delete links. 2013-04-25 17:24:57 -07:00
Bob Lantz 0a176439ab More robust bash and namespace cleanup 2013-04-25 14:30:16 -07:00
Bob Lantz 0de8d94673 Basic support for using ip netns for mnexec and link creation 2013-04-24 18:44:19 -07:00
Bob Lantz 6c22e057cc Avoid false matches and detect multiple host processes 2013-04-12 13:30:50 -07:00
Bob Lantz 7bc10ebc7a Fix X11 forwarding (broken by no IPv6) for real 2013-04-09 23:26:08 -07:00
Bob Lantz c3f975aef8 Move IPv6 disable to 'other', and fix X11 forwarding
should fix #128
2013-04-09 22:46:49 -07:00
Bob Lantz 0f6bf4ce84 start xterm with TERM=ansi to preserve title from bash.bashrc
fixes #128
2013-04-09 20:10:55 -07:00
Bob Lantz 33c7e46492 Use __NR_setns so that setns has the right syscall # in 32-bit mode
fixes #127
2013-04-09 19:38:36 -07:00
Bob 7c920edc29 Merge pull request #125 from adferguson/adf-tc-renumber
Adjust numbering to support tc-based switch QoS

This looks fine to me - probably we want to change the way this works eventually, but for now renumbering it is fine and we can change the numbering later if desired.
2013-04-09 14:59:41 -07:00
Andrew Ferguson e09254eea3 Adjust numbering to support tc-based switch QoS
both the reference switch and Open vSwitch assume ids with major 1
can be used for tc-based QoS
2013-03-30 17:50:28 -04:00
Bob Lantz e5a15ced01 Change popen() to detach from terminal/process group.
This may or may not be the right thing to do - an alternative
would be to ignore SIGINT, but that would make the popen()
job unkillable by normal means! So we'll try this and see
how well it works.
Fixes #124
2013-03-28 18:14:24 -07:00
Bob Lantz c771b2d75a Add source node option to moveIntf() (note: low-level API!!)
In the future we may wish to enable moving interfaces across
nodes which are not in the root NS, and this would provide
the low-level mechanism to do so.
closes #122
2013-03-24 16:14:04 -07:00
Bob Lantz 477e84adba More code check nits. 2013-03-24 15:58:48 -07:00
Bob Lantz 3482d941e1 Fix code check. 2013-03-24 14:48:20 -07:00
Bob Lantz 1bf1a4d5e9 Tag node bash processes and add attach script
Try invoking bash processes with -s mininet:host,
for easy identification of hosts. This enables
easy attachment using the util/m script.
closes #121
2013-03-22 18:38:33 -07:00
Bob Lantz a0f69d98df Change makeTerm() to tunnel X11 using socat if needed
For local display, allow local root access
For remote display, tunnel with socat/mnexec
This should enable *wireshark in hosts* and fix #119
2013-03-22 15:48:51 -07:00
Bob Lantz 4b8b4b73e1 Clean up options and fix of13 to use sudo for netbee 2013-03-21 16:44:44 -07:00
ederlf 5b14cc2937 Add options to install OpenFlow 1.3 switch and compatible NOX controller.
Signed-off-by: Bob Lantz <rlantz@cs.stanford.edu>
2013-03-21 16:08:05 -07:00
Bob Lantz eca5a151a4 Fix usage message to note correct options and OS compatibility.
closes #85
2013-03-21 14:38:46 -07:00
Bob 4efd372223 Merge pull request #116 from yamahata/install-test-mar-2013
tools/install.sh: catch up oftest change
Looks fine to me.
2013-03-21 14:12:50 -07:00
Isaku Yamahata 356e9d8a92 tools/install.sh: update oftest
Since oftest removed tools/munger directory, install.sh fails as follows
> mininet/util/install.sh: line 399: cd: tools/mnuger: No such file or directory

oftest change set
> commit be8503a69d609d0aee844a91f3f5d66f4e2666c7
> Author: Rich Lane <rlane@bigswitch.com>
> Date:   Tue Mar 12 10:16:33 2013 -0700
>
>     remove pylibopenflow tools

Signed-off-by: Isaku Yamahata <yamahata@valinux.co.jp>
2013-03-15 10:40:51 +09:00
Bob Lantz 8838c30ea1 Remove non-functional --prefixlen (use --ipbase instead) 2013-03-13 16:18:04 -07:00
Bob Lantz 8204a1b694 fix --ipbase: fix ipAdd() and remove unused default from ipStr() 2013-03-13 16:16:20 -07:00
Bob Lantz bd558875f3 Add net['h1'] and for node in net support
thanks to Brian O'Connor for reminder + suggestion
closes #114
2013-03-08 18:28:21 -08:00
Bob Lantz 31fe4f1bd0 Fix pmonitor() to not return blank lines on EOF
fixes #109 (hopefully)
2013-03-06 17:26:52 -08:00
Bob Lantz dcb3036b70 Change to use addLink() interface for symmetry/consistency. 2013-03-06 16:55:47 -08:00
Bob Lantz 9734d9d7fa Add configuration to disable IPv6, since old method no longer works.
fixes #108
2013-03-06 16:06:59 -08:00
Bob Lantz 23c70f609d Add px command which uses exec() vs. py's eval()
This is necessary since exec() isn't really a function, and
eval can't evaluate statements.
fixes #104
2013-02-28 19:14:37 -08:00
Bob Lantz f018137207 Updated to reflect new controllers.py and old controllers2.py 2013-02-28 17:59:14 -08:00
Bob Lantz ad09c1e086 Add new example of making a custom Switch() class. 2013-02-28 17:56:36 -08:00
Bob Lantz 31e1ff7154 Rename controllers.py to controllers2.py since it's less convenient. 2013-02-28 17:55:41 -08:00
Bob Lantz 8b8bb37598 Remove unnecessary addHost() function, and clarify things a bit.
Fixes #102
2013-02-28 17:40:48 -08:00
Bob Lantz 0aefb0e036 Fix Node.MAC(intf) to return intf.MAC() rather than intf.IP()
Fixes #89 ; Thanks to Nikhil S. Menon for the bug report
2012-12-19 16:11:57 -08:00
Bob Lantz 5879c492d8 Minor clarifications. 2012-12-02 15:39:17 -08:00
Bob Lantz ee66d53c54 Clean up INSTALL and make it markdown-friendly
Also fixed a few errors like the time it takes to install,
some references to NOX, etc..

Left in noxcore ref, since you can still install it.
2012-12-02 15:29:53 -08:00
Bob f95c4a4712 Update INSTALL: git clone from github.com
Thanks to @xdhanz for the catch, and pull request
closes #84
2012-12-02 15:00:46 -08:00
Bob Lantz c8b857465b pass code check 2012-11-30 21:00:23 -08:00
Bob Lantz 21366afc54 2.0.0rc1 -> 2.0.0 final 2012-11-30 20:57:53 -08:00
Brandon Heller b453e0068f node: verify telnet installation for controller checking
Reported-by: Julius Bachnick

https://mailman.stanford.edu/pipermail/mininet-discuss/2012-November/001349.html
2012-11-26 15:22:07 -08:00
Brandon Heller 1e9b5f61fc install.sh: add Telnet
Reported-by: Julius Bachnick

https://mailman.stanford.edu/pipermail/mininet-discuss/2012-November/001349.html
2012-11-26 15:22:07 -08:00
Bob Lantz 0ce366b5d2 Add sudoers entry for current user using whoami 2012-11-19 17:30:09 -08:00
Brandon Heller 3744638e5c node: add OVS passive listening support 2012-11-15 00:50:25 -08:00
Brandon Heller 915c6d4a60 node: Use space, rather than comma, to separate controllers
for OVS

Otherwise, OVS thinks the second controller is a parameter of the first, and
only creates one controller entry as seen in 'ovs-vsctl show'.
2012-11-15 00:50:25 -08:00
Brandon Heller bd964adb57 mn: change default passive listening port to 6634
Becomes consistent with the OpenFlow walkthrough & MN walkthrough web pages.
2012-11-15 00:50:25 -08:00
Brandon Heller dec1f402ed custom topo: remove author name
No need for this here, especially because this file is in the walkthrough
and will be found by web crawlers.
2012-11-15 00:50:25 -08:00
Bob Lantz b96e1596b2 Change to use Intf() class rather than string for interface.
Was broken in 2.0.0rc1
2012-11-19 15:02:38 -08:00
Bob Lantz 3569838542 Updated for new Topo API 2012-11-19 12:32:50 -08:00
Bob Lantz 8c7c4812b2 Remove vmware easy install leftovers 2012-11-19 12:31:50 -08:00
Brandon Heller 987fd7555e Fix custom topology example; outdated import
Reported-by: Julius Bachnick
2012-11-14 21:28:42 -08:00
Bob Lantz 63d669f712 Update to match launchpad. 2012-11-18 20:54:47 -08:00
Bob Lantz 078b982be1 Sync with packaging on launchpad. 2012-11-17 23:14:10 -08:00
Bob Lantz d402c66af2 Update debian copyright. ;-/ 2012-11-16 23:11:59 -08:00
Brandon Heller 03c3123bb8 test_hifi: Fix occasional test breakage
Source of error: regex to parse ps output had a single space, rather
than handling any amount of whitespace before the CPU percentage.  When
that percentage would drop below 10.0, an space would be printed,
confusing the regex.

Fixed by handling arbitrary whitespace before the percentage.
2012-11-14 10:47:00 -08:00
Bob Lantz 82c8bdaf0d Remove redundant wireshark install. 2012-11-15 22:59:43 -08:00
Bob Lantz 163a6cf3dd Fix whitespace error. 2012-11-15 22:56:24 -08:00
Bob Lantz ab594b6afe Merge branch '2.0dev' into 2.0merge
Conflicts:
	.gitignore
	.pylint
	examples/miniedit.py
	mininet/node.py
	mininet/util.py
	util/install.sh
	util/vm/install-mininet-vm.sh
2012-11-15 22:54:27 -08:00
Brandon Heller 1f1d590c7a test: Improve unit tests to verify basic functionality
Also a more complete ping test that parses all output to the CLI.

These tests expand the hifi-specific ones to not just cover whether
a topology can be created with options, but whether those options
are properly implemented within some tolerance, like CPU limits,
link bandwidth, delays, and even drops.
2012-11-14 07:57:17 -08:00
Brandon Heller fcd01592e1 Move CPU limit into net, to be reused in future unit tests 2012-11-14 07:55:10 -08:00
Brandon Heller e1205a8a49 Add a simple unit test for link/host creation with options 2012-11-14 00:43:46 -08:00
Brandon Heller d7768ab228 examples/simpleperf: Warn in docstring about effects of link settings
These include dropped pings and iperf hanging.
2012-11-13 23:28:24 -08:00
Brandon Heller bf208cdeb6 Fix SSHD example by generalizing input intf args
A number of functions in node.py look like this:
   return self.intf( intf ).<other stuff>

Previously, self.intf(...) in Node would expect a string name for an
interface and return None if an object was passed in instead of a
string name.

Now, be more permissive and assume that objects passed in are for Intf
objects.  This makes all such functions in node.py handle more flexible
input args, either name or actual Intf object.

An alternative and equally valid approach would be to raise an Exception
whenever a non-string, non-falsy value was passed in to Node.intf(), and
to modify the code in at least one place - examples/sshd.py - to pass
the interface name, rather than the interface object.

Also fix input args for examples/scratchnetuser.py - the interface name
was being passed in as the prefix len, which makes no sense.
2012-11-13 22:44:47 -08:00
Brandon Heller 12fea0f6d5 examples/baresshd: ensure root permissions
Prevent idiots like me from getting confused by non-obvious 'broken pipe'
errors when they forget to put 'sudo' in front  :-)
2012-11-13 21:33:44 -08:00
Brandon Heller bcfb3009c0 small refactor: put function to ensure root in util
Two benefits:
- One place to change if in the future, a more granular method of
  root access is used (like the BigSwitch patch).
- Makes this reusable by stuff like examples/baresshd.py that use
  the low-level Mininet API.
2012-11-13 21:32:41 -08:00
Brandon Heller 8a1264e266 Fix 'cgroups not mounted' error in U12.10
'mount' shows something slightly different in Ubuntu 12.10:

cgroup on /sys/fs/cgroup type tmpfs (rw,uid=0,gid=0,mode=0755)

Note the lack of a plural on first word cgroup, which has changed.

Still mounted at /sys/fs/cgroup, so check for both possibilities
when instantiated CPU-limited hosts.
2012-11-13 20:53:13 -08:00
Brandon Heller 36c9b040ca examples: Add new tests to README 2012-11-13 18:33:10 -08:00
Brandon Heller 2eb0593cd2 examples/cpu: Fix typo, note existence in README 2012-11-13 18:06:19 -08:00
Brandon Heller d40003e0cd examples: Make simpleperf.py executable 2012-11-13 18:05:10 -08:00
Brandon Heller 9330a33fe5 pep8: Fix E501 line-too-long errors incurred fixing other pep8 stuff :-) 2012-11-13 17:21:36 -08:00
Brandon Heller 2e089b5e4a pep8: Fix E127 continuation line over-indented
There are a bunch of these remaining, but I don't think the right course is
to 'fix' all of them to make pep8 happy, but instead to either change
the test in pep8 to consider that a continuation line may itself
be continued halfway, OR, to change the code in these lines to be more
readable by removing the need for all those nested continuations.

Personally, I find multiply-broken lines (aka nested continuations) really
hard to read.
2012-11-13 17:17:51 -08:00
Brandon Heller edf6003217 pep8: fix E128 continuation line under-indented errors
I wasn't sure this was worth fixing at first, but it does look more readable
now.
2012-11-13 16:59:10 -08:00
Brandon Heller c0095746af pep8: Fix E121/126, continuation line indention 2012-11-13 16:08:26 -08:00
Brandon Heller 33d548b412 pep8: Fix E121 continuation line indentation is not a multiple of four 2012-11-13 15:01:11 -08:00
Brandon Heller 615ebb7afa pep8: Fix E125 continuation line does not distinguish itself from next logical line 2012-11-13 14:56:49 -08:00
Brandon Heller 7a5060478b pep8: Fix E711, comparisons to None should use 'is' or 'is not'
Lengthy discussion of why this is a good thing (I didn't know) at SO:

http://stackoverflow.com/questions/2209755/python-operation-vs-is-not
2012-11-13 14:46:58 -08:00
Brandon Heller 0bd5c6519c pep8: Fix E203 whitespace before punctutation 2012-11-13 14:39:31 -08:00
Brandon Heller 1052f8a0d4 pep8: Fix E271/E272, spaces before/after keyword 2012-11-13 14:36:56 -08:00
Brandon Heller 03d211f2a9 codecheck: Make codecheck happy with a consistent version num 2012-11-12 18:08:59 -08:00
Brandon Heller f6c4239409 install: Add 'make codecheck' deps
These total to only ~200KB.
2012-11-12 18:07:19 -08:00
Brandon Heller 59897168d4 install: Update OFTest repo location
This repo has moved to git://github.com/floodlight/oftest.git
2012-11-12 16:46:29 -08:00
Brandon Heller b597ef5d55 install: Add help2man to MN deps
'make install' calls help2man, so apt-get install it beforehand.
2012-11-12 16:46:22 -08:00
Bob Lantz e3c8066a9e OK, github is broken - reverting to old spacing. 2012-11-09 00:09:41 -08:00
Bob Lantz 78e3e18c42 trying to fix list spacing 2012-11-09 00:09:11 -08:00
Bob Lantz 01e028c19f Add Mininet-HiFi comment 2012-11-09 00:07:56 -08:00
Bob Lantz d49aaf0f70 Hmm, maybe this is better. 2012-11-09 00:04:40 -08:00
Bob Lantz f7d6c9e7a1 Another attempt. 2012-11-09 00:03:36 -08:00
Bob Lantz 015aaa2107 That didn't work... 2012-11-09 00:02:54 -08:00
Bob Lantz bad8656361 More header madness. 2012-11-09 00:02:17 -08:00
Bob Lantz eb3b74ea34 sudo mn seems lonely if it takes up the whole line 2012-11-08 23:58:54 -08:00
Bob Lantz dabc0b812a Bash in tt, abolish forward single quotes. 2012-11-08 23:57:39 -08:00
Bob Lantz dd1a450b50 Mars needs commas! 2012-11-08 23:55:31 -08:00
Bob Lantz ead9f83050 Reflow text and try crazy idea for heading. 2012-11-08 23:52:07 -08:00
Bob Lantz 0fb91f186e More minor tweaks.... 2012-11-08 23:47:48 -08:00
Bob Lantz 3e38a959c3 Moved installation instructions and prereqs into INSTALL. 2012-11-08 23:31:31 -08:00
Bob Lantz 535e61d2be Still trying to fix the typeface and spacing... 2012-11-08 23:18:56 -08:00
Bob 4885cb24ed Update README.md
File and command names in typewriter text.
2012-11-08 22:05:52 -08:00
Brandon Heller 73da7204e6 Update README 2012-11-08 15:31:10 -08:00
Bob Lantz ff4b41439a Minor changes. 2012-11-03 21:59:04 -07:00
Bob Lantz 21b2c2c4aa VERSION -> 2.0.0rc1 2012-11-03 21:38:59 -07:00
Bob Lantz e2b799b815 Fix/work around setuptools' evil PYTHONPATH madness. 2012-11-03 21:36:03 -07:00
Bob Lantz 4744aa2b78 Updated README to reflect Mininet 2.0. 2012-11-03 16:53:26 -07:00
Bob Lantz c04ef88e5c Add note regarding removing old OVS junk. 2012-11-03 16:10:57 -07:00
Bob Lantz 4b1dc93bcc Avoid modifying keyword parameter dictionary in customized() 2012-10-30 16:58:51 -07:00
Bob Lantz f58f83c043 Allow controller to optionally be a list of constructors/classes 2012-10-30 16:50:12 -07:00
Bob Lantz 22b8e5e427 Add custom name to customized functions.
Note: we could probably use functools.partial.
2012-10-30 16:45:11 -07:00
Angad Singh cec4476303 Merge pull request - closes #36 2012-10-29 16:10:00 -07:00
Bob Lantz 31015ef5d8 Make doc a real subdirectory so we can put other things there. 2012-10-29 15:36:19 -07:00
Bob Lantz 600dad2498 Added package installation "instructions" 2012-10-04 19:08:37 -07:00
Bob Lantz 4ff6243fd6 Update version number to 2.0.0d3 (and pass version check) 2012-10-04 19:02:44 -07:00
Bob Lantz 9c0ed88c72 Create version check utility and add to code check.
Fixes #70
2012-10-04 19:02:27 -07:00
Bob Lantz 93f9b956e4 Updated copyright to fix #68 2012-10-01 18:01:29 -07:00
Bob Lantz b69ef234ac Fix multi-controller/failover support on User, OVSLegacy switches 2012-09-14 18:23:30 -07:00
Bob Lantz 2988429747 show method names in git diff output 2012-09-14 15:18:17 -07:00
Bob Lantz d4ece25ba6 Deprecate NOX-classic; "install" POX. Fixes #61 2012-09-11 06:49:11 -07:00
Bob ad85e44d78 Update util/install.sh
Update to reflect new NOX classic repo on github and default branch.
2012-08-29 16:00:33 -07:00
Bob 655194d3e1 Update util/install.sh
Update to reflect new NOX classic repo on github and default branch.
2012-08-29 15:10:36 -07:00
Bob Lantz 6eb01d7923 Minor formatting changes. 2012-08-23 18:36:50 -07:00
Bob Lantz ae6475598f Change README to README.md for github presentation.
This isn't the final README text, of course, but it should
show up formatted now on github.
2012-08-23 18:28:15 -07:00
Bob Lantz 62499d96df Adjust README slightly to be markdown-compatible. 2012-08-23 18:27:48 -07:00
Bob Lantz 4f33cad025 Ignore more stuff, notably generated docs and man pages. 2012-08-17 18:20:22 -07:00
Bob Lantz 2aafefc2fa Fix typo in RemoteController.__init__ comment.
Thanks to Isaku Yamahata.
2012-08-17 15:26:19 -07:00
Bob Lantz 9d5a21a799 Fix typo MANPAGE->MANPAGES
Thanks to Isaku Yamahata.
2012-08-17 15:25:06 -07:00
Bob Lantz ce15c4f67d rename Topo() methods for consistency: add_node() -> addNode() 2012-08-16 18:48:41 -07:00
Bob Lantz 01e0758e5d Add 'type mn -h for details' to usage message. 2012-08-16 16:12:55 -07:00
Bob Lantz e8238d185d Use Mininet version number from mininet.net
Contributing toward issue #46.
2012-08-10 12:47:35 -07:00
Bob Lantz 54c51c0299 Fix whitespace and change no controller exception to warning. 2012-08-06 11:41:00 -07:00
James Page 2b35a2caeb Override remote controller check to ensure that remote controller is contactable 2012-08-06 03:08:41 -07:00
James Page 9b11238467 Observe build environment flags and use PYTHONPATH when generating version number 2012-08-06 03:08:41 -07:00
Bob Lantz fa24f22d4d Re-enable slicing in UserSwitch since it's fixed with newer kernels. 2012-07-31 17:23:08 -07:00
Bob Lantz ce823507cd Fix man page install. 2012-07-31 17:22:13 -07:00
Bob Lantz cd580debb6 Removed redundant debian/mininet.manpages 2012-07-07 22:29:46 -07:00
Bob Lantz 1e9106badb Add option to mangle github tarball filename. 2012-07-07 22:23:53 -07:00
Bob Lantz 232acc8261 Track tagged versions on github directly. 2012-07-07 19:07:20 -07:00
Bob Lantz 55179737f9 Change version to 2.0.0d2 - there has to be a better way. 2012-07-06 23:44:27 -07:00
Bob Lantz 28c2cdc2c4 Workaround for openvswitch_mod rename and pass code check. 2012-07-06 23:30:14 -07:00
Bob Lantz d85a58feeb Autogenerate man page for mnexec. 2012-07-06 23:18:24 -07:00
Bob Lantz 89a6dea7f9 Remove unnecessary copy to bin/ 2012-07-06 22:43:11 -07:00
Bob Lantz 9a518b1eee Add missing packaging files from launchpad. 2012-07-06 22:30:19 -07:00
Bob Lantz d54cde46e0 Add PYTHONPATH=. to allow "make man" to work if Mininet is not installed. 2012-07-06 19:54:42 -07:00
Bob Lantz 320df7fe28 Merging in James Page's packaging tweaks for quantal. 2012-07-06 16:06:19 -07:00
Bob Lantz 0ab282400e update maintainer for ppa submission to work 2012-07-04 10:46:25 -07:00
Bob Lantz 8aa7e05d83 Added missing help2man to build deps. 2012-07-04 00:23:06 -07:00
Bob Lantz b43a67edbd Pass lintian. This is still annoyingly redundant. ;-(
y
2012-07-03 23:53:47 -07:00
Bob Lantz 9c4d047462 Ugh, it looks like lintian wants a duplication of the license in debian/copyright.... 2012-07-03 23:19:08 -07:00
Bob Lantz ccc0b1a1cf Fixed debian/copyright 2012-07-03 23:09:37 -07:00
Bob Lantz 78b2f585ae Fixed support for adding man page to debian package - to pass lintian! 2012-07-03 22:50:53 -07:00
Bob Lantz 39128f8cf8 Add VERSION string. 2012-07-03 22:08:33 -07:00
Bob Lantz 7fe847967d clean up "make man" slightly 2012-07-03 22:08:25 -07:00
Bob Lantz f2e7884ade Add support for generating man page from mn --help. 2012-07-01 23:23:56 -07:00
Bob Lantz 0809105bed Fixing some lintian problems. 2012-07-01 23:22:44 -07:00
Bob Lantz 93bf7793cb Debian copyright wants a real file, so change LICENSE to symlink. 2012-07-01 23:22:05 -07:00
Bob Lantz ec969b7f99 Change default controller for mn to ovsc (ovs-controller.)
Also add check to see if another controller is running -
eventually we should really detect errors from starting the
controller!!
2012-07-01 20:31:30 -07:00
Bob Lantz cb859243a5 Added Debian/Ubuntu packaging - thanks to James Page. 2012-07-01 19:16:41 -07:00
Bob Lantz e04c207c3c Update for Mininet 2.0.0 development. 2012-07-01 19:08:20 -07:00
Brandon Heller 496cd25d37 Update oftest repo location
Fixes Issue 41: https://github.com/mininet/mininet/issues/41

Reported-by: sublinhado on GitHub
2012-06-14 11:10:39 -07:00
Bob Lantz d9fd4ea245 Add VM install script 2012-05-23 22:37:53 -07:00
Bob Lantz 88dd4f7329 Change wireshark install to reflect new repository location. 2012-05-13 14:37:45 -07:00
Bob Lantz 49d84f7cfc Fix poller to only check if stdin and node are readable.
Fixes busy waiting and excessive CPU usage in CLI.
Thanks to James Zeng for pointing this out!
2012-05-10 17:35:34 -07:00
Bob Lantz 7676c17f27 Add missing libconfig-dev dependency for oflops. 2012-04-25 17:39:55 -07:00
Brandon Heller 6143bb1395 Merge pull request #31 from mininet/devel/wireshark
Devel/wireshark
2012-04-12 10:12:53 -07:00
Bob Lantz a8c1965b90 Fix typo. 2012-04-11 13:21:07 -07:00
Bob Lantz 4bd1a61353 Add install message for wireshark dissector. 2012-04-10 21:47:29 -07:00
Bob Lantz edd1d0f3a4 Support libwireshark[0,1] for 11.04 and 11.10 2012-04-10 21:34:07 -07:00
Bob Lantz 0919b7ca67 Use correct non-authenticated clone for of-dissector. 2012-04-10 21:23:26 -07:00
Bob Lantz 1902dd2e3a Add support for updated wireshark plugin.
Need to verify this works with 11.04.
2012-04-10 21:14:11 -07:00
Brandon Heller 99222e70f7 Merge pull request #26 from mininet/devel/install-oneiric
Devel/install oneiric
2012-03-13 15:11:29 -07:00
Bob Lantz 5562e66a2d Ignore build, dist and emacs backup~ files. 2012-03-12 16:14:00 -07:00
Bob Lantz 28f46c8d2d Pass code check. 2012-03-12 16:12:38 -07:00
55 changed files with 1561 additions and 871 deletions
+1
View File
@@ -0,0 +1 @@
*.py diff=python
+8 -2
View File
@@ -1,8 +1,14 @@
mnexec
*.pyc
*~
*.1
*.xcodeproj
*.xcworkspace
\#*\#
mininet.egg-info
build/*
dist/*
build
dist
doc/html
doc/latex
trunk
+75 -225
View File
@@ -1,273 +1,123 @@
Mininet Installation/Configuration Notes
----------------------------------------
Mininet 1.0.0
Mininet 2.0.0
---
The supported installation methods for Mininet are 1) using
a pre-built VM image, and 2) native installation on Ubuntu or Debian.
The supported installation methods for Mininet are 1) using a
pre-built VM image, and 2) native installation on Ubuntu. You can also
easily create your own Mininet VM image (4).
(Other distributions may be supported in the future - if you would
like to contribute an installation script, we would welcome it!)
1. Easiest "install" - use our pre-built VM image!
1. Easiest "installation" - use our pre-built VM image!
The easiest way to get Mininet running is to start with one of our pre-built
virtual machine images from http://openflow.org/mininet
The easiest way to get Mininet running is to start with one of our
pre-built virtual machine images from <http://openflow.org/mininet>
Boot up the VM image, log in, and follow the instructions on the wiki page.
Boot up the VM image, log in, and follow the instructions on the
Mininet web site.
An additional advantage of using the VM image is that it doesn't mess with
your native OS installation or damage it in any way.
One advantage of using the VM image is that it doesn't mess with
your native OS installation or damage it in any way.
2. Native installation (experimental!) for Ubuntu 10.04 LTS
Although a single Mininet instance can simulate multiple networks
with multiple controllers, only one Mininet instance may currently
be run at a time, and Mininet requires root access in the machine
it's running on. Therefore, if you have a multiuser system, you
may wish to consider running Mininet in a VM.
If you are running Ubuntu 10.04 LTS (or possibly Debian 5), you may be
able to use our handy install.sh script, which is in mininet/util.
2. Next-easiest option: use our Ubuntu package!
WARNING: USE AT YOUR OWN RISK!
To install Mininet itself (i.e. `mn` and the Python API) on Ubuntu
12.10+:
install.sh is a bit intrusive and may possibly damage your OS and/or
home directory, by creating/modifying several directories such as
mininet, openflow, openvswitch and noxcore. Although we hope it won't
do anything completely terrible, you may want to look at the script
before you run it, and you should make sure your system and home
directory are backed up just in case!
sudo apt-get install mininet
To install ALL of the software which we use for OpenFlow tutorials,
you may use
Note: if you are upgrading from an older version of Mininet, make
sure you remove the old OVS from `/usr/local`:
$ mininet/util/install.sh
sudo rm /usr/local/bin/ovs*
sudo rm /usr/local/sbin/ovs*
This takes about 20-30 minutes.
3. Native installation from source on Ubuntu 11.10+
Alternately, you can install just the pieces you need.
If you're reading this, you've probably already done so, but the
command to download the Mininet source code is:
We recommend the following steps, in order:
git clone git://github.com/mininet/mininet.git
[a) On Debian 5, first install a Mininet-compatible kernel:
$ mininet/util/install.sh -k
Reboot and run 'uname -r' to make sure you're running the new kernel.]
If you are running Ubuntu, you may be able to use our handy
`install.sh` script, which is in `mininet/util`.
b) Install mininet and its dependencies:
$ mininet/util/install.sh -n
c) Install OpenFlow 1.0 and associated useful software
$ mininet/util/install.sh -f
*WARNING: USE AT YOUR OWN RISK!*
d) Install Open vSwitch and its kernel module
$ mininet/util/install.sh -vm
`install.sh` is a bit intrusive and may possibly damage your OS
and/or home directory, by creating/modifying several directories
such as `mininet`, `openflow`, `oftest`, `pox`, or `noxcosre`.
Although we hope it won't do anything completely terrible, you may
want to look at the script before you run it, and you should make
sure your system and home directory are backed up just in case!
e) If you wish to install the version of NOX we use in the tutorial:
$ mininet/util/install.sh -x
To install Mininet itself, the OpenFlow reference implementation, and
Open vSwitch, you may use:
Note: NOX development is progressing over time, so after you complete
the tutorial you may wish to install the latest and greatest NOX from
noxrepo.org.
mininet/util/install.sh -fnv
Good luck! Some additional installation notes are provided below, for
the brave and/or Linux-savvy, or those who are trying to understand what
is installed and why.
This should be reasonably quick, and the following command should
work after the installation:
p.s. Note that only one instance of Mininet is currently supported on a single
machine - that's one reason we recommend using a VM to run it.
sudo mn --test pingall
---
To install ALL of the software which we use for OpenFlow tutorials,
including POX, the OpenFlow WireShark dissector, the `oftest`
framework, and other potentially useful software (and to add some
stuff to `/etc/sysctl.conf` which may or may not be useful) you may
use:
Mininet Manual Installation Notes
mininet/util/install.sh -a
These installation notes assume you understand how to do things like
compile kernels, apply patches, configure networks, write code, etc.. If
this is unfamiliar territory, or if you run into trouble, we recommend
using one of our pre-built virtual machine images (see above.)
This takes about 4 minutes on our test system.
If you wish to try to create a VM to run Mininet, you may also wish
to look at the Wiki page:
4. Creating your own Mininet/OpenFlow tutorial VM
http://openflow.org/foswiki/bin/view/OpenFlow/MininetVMCreationNotes
Creating your own Ubuntu Mininet VM for use with the OpenFlow tutorial
is easy! First, create a new Ubuntu VM. Next, run two commands in it:
0. Obtaining Mininet
wget https://raw.github.com/mininet/mininet/master/util/vm/install-mininet-vm.sh
time install-mininet-vm.sh
If you're reading this, you've already done it, but the command to
download mininet is:
git clone git://openflow.org/mininet.git
1. Core Mininet installation
Finally, verify that Mininet is installed and working in the VM:
The core Mininet installation requires gcc, make, python,
and setuptools. On Ubuntu and Debian you may install them with:
# aptitude install gcc make python setuptools
sudo mn --test pingall
To install Mininet itself, with root privileges:
# cd mininet
# make install
5. Installation on other Linux distributions
This places the mininet package in /usr/lib/python-*/site-packages/,
so that 'import mininet' will work, and installs the primary mn
script (mn) as well as its helper utility (mnexec.)
On Ubuntu and Debian, Mininet's dependencies and core files may also be
installed using mininet/util/install.sh -n
Although we don't support other Linux distributions directly, it
should be possible to install and run Mininet with some degree of
manual effort.
2. Installation script for Ubuntu/Debian Lenny
In general, you must have:
If you are running Ubuntu 10.04 or Debian Lenny, you may be able to use the
util/install.sh script to install a compatible Linux kernel as well as
other software including the OpenFlow reference implementation, the Open
vSwitch switch implementation, and the NOX OpenFlow controller.
* A Linux kernel compiled with network namespace support enabled
Many different installation options are possible by passing different
options to install.sh; install.sh -h lists them all.
Assuming the mininet source tree is installed in ~/mininet, the steps to run
install.sh to install EVERYTHING we use for OpenFlow tutorials are:
% cd
% time ~/mininet/util/install.sh # installs tons of stuff
% sudo reboot # to load new kernel
% ~/mininet/util/install.sh -c # to clean out unneeded kernel stuff
* An OpenFlow implementation (either the reference user or kernel
space implementations, or Open vSwitch.) Appropriate kernel
modules (e.g. tun and ofdatapath for the reference kernel
implementation) must be loaded.
This installs a lot of useful software, but it will take a while (30
minutes or more, depending on your network connection, computer, etc..)
Probably the minimal semi-useful configuration would be to install
Mininet itself, kernel support if necessary, and either the
reference OpenFlow switch or Open vSwitch. This could be installed
as follows:
% sudo ~/mininet/util/install.sh -knvm
Respectively, this installs kernel support, core mininet dependencies,
Open vSwitch, and the Open vSwitch kernel module. If a new kernel was
installed, then a reboot may be required.
* Python, `bash`, `ping`, `iperf`, etc.`
If install.sh cannot be used for some reason (e.g. you're on Fedora
or some other Linux - please don't say CentOS) or if you don't want to
install all of these components (they're useful!), the kernel and
OpenFlow software requirements are described in steps [3] and [4],
which follow.
* Root privileges (required for network device access)
If you successfully used install.sh, congratulations! You're basically
done. Proceed to step [6] for additional advice.
3. Linux Kernel requirements
We encourage contribution of patches to the `install.sh` script to
support other Linux distributions.
Mininet requires a kernel built with network namespace support enabled,
i.e. with CONFIG_NET_NS=Y, such as the kernel shipped with
Ubuntu 10.04 LTS, currently 2.6.32. On Ubuntu 10.04, you should not need
to install or build a custom kernel, although 2.6.33+ is faster at
tearing down virtual ethernet pairs.
For Ubuntu and Debian, we provide a 2.6.33 kernel package which you may be
able to install using "util/install.sh -k". Note our kernel package
requires an ext2 or ext3 root file system, so it won't work if you have
a default Ubuntu install, which uses ext4.
If your kernel wasn't compiled with CONFIG_NET_NS=Y, you will need to
build and install a kernel that does! >= 2.6.33 works better, but may
be harder to get working, depending on your Linux distribution.
A script for building Debian packages for 2.6.33.1 is provided in
mininet/util/kbuild. You may wish to read it, as it applies patches
to enable 2.6.33.1 to build under debian-stable, and to enable the
tun driver to work correctly with Mininet.
Earlier kernels (e.g. 2.6.29) work with CONFIG_NET_NS enabled and no
additional patches, but are much slower at removing veth interfaces,
resulting in much slower switch shutdown.
For scalable configurations, you might need to increase some of your
kernel limits. Sample params are in util/sysctl_addon, which can be
appended to /etc/sysctl.conf (and modified as necessary for your
desired configuration):
sudo su -c "cat sysctl_addon >> /etc/sysctl.conf"
To save the config change, run:
sudo sysctl -p
4. OpenFlow software and configuration requirements
Mininet requires either the reference OpenFlow switch implementation
(from openflowswitch.org) or Open vSwitch (openvswitch.org) to be
installed. "make test" requires the reference user space
implementations as well as Open vSwitch. Note the reference kernel
implementation is not currently included in OpenFlow 1.0.
On Ubuntu and Debian, the install.sh script may be used with the '-f'
option to install the OpenFlow reference implementation, the '-v' option
to build Open vSwitch, and the '-m' option to install the Open vSwitch
kernel module into /lib/modules (note: you must build Open vSwitch first!)
Mininet will automatically load and remove kernel module dependencies
for supported switch types, using modprobe and rmmod - but these
modules must be in a location where modprobe can find them (e.g.
something like /lib/modules/`uname -r`/kernel/drivers/net/)
The reference OpenFlow controller (controller(8)) only supports 16
switches by default! If you wish to run a network with more than 16
switches, please recompile controller(8) with larger limits, or use a
different controller such as nox. A patch to controller(8) is included
as util/openflow-patches/controller.patch.
5. Other software dependencies
On Ubuntu and Debian, other Mininet dependencies may be installed using
the '-n' option of the install.sh script.
To run the iperf test, you need to install iperf:
sudo aptitude/yum install iperf
We assume you already have ping installed. ;-)
To use xterm or sshd with Mininet, you need the following:
sudo aptitude/yum install sshd xterm screen
Some examples may have additional requirements - consult the specific
example file for details.
The install.sh script has an '-x' option to install the version of
NOX from the OpenFlow tutorial.
6. Other notes and recommendations
If you did not install certain useful packages and you wish to later,
it may be possible to install them using install.sh.
Mininet should be run either on a machine with
no other important processes, or on a virtual machine (recommended!)
Multiple concurrent Mininet instances are not supported!
Good luck!
Mininet Team
---
Historical information on OpenFlow 0.8.9 and the reference kernel module:
The kernel reference implementation has been deprecated, but it may
be possible to get it work with Mininet.
To switch to the most recent OpenFlow 0.8.9 release branch (the most
recent one with full NOX support and kernel datapath support) in your
OpenFlow git tree:
git checkout -b release/0.8.9 remotes/origin/release/0.8.9
A patch to enable datapath.c to compile with recent kernels
is included in util/openflow-patches/datapath.patch.
In OpenFlow 1.0, switch port numbering starts at 1 (for better or for worse.)
To run with previous versions of OpenFlow, it may be necessary
to change SWITCH_PORT_BASE from 1 to 0 in node.py.
+6 -2
View File
@@ -1,6 +1,10 @@
Mininet 1.0.0 License
Mininet 2.0.0 License
Copyright (c) 2009-2011 Bob Lantz and Brandon Heller
Copyright (c) 2012 Open Networking Laboratory
Copyright (c) 2009-2012 Bob Lantz and The Board of Trustees of
The Leland Stanford Junior University
Original authors: Bob Lantz and Brandon Heller
We are making Mininet available for public use and benefit with the
expectation that others will use, modify and enhance the Software and
+34 -8
View File
@@ -1,18 +1,25 @@
MININET = mininet/*.py
TEST = mininet/test/*.py
EXAMPLES = examples/*.py
BIN = bin/mn
MN = bin/mn
BIN = $(MN)
PYSRC = $(MININET) $(TEST) $(EXAMPLES) $(BIN)
MNEXEC = mnexec
MANPAGES = mn.1 mnexec.1
P8IGN = E251,E201,E302,E202
BINDIR = /usr/bin
MANDIR = /usr/share/man/man1
DOCDIRS = doc/html doc/latex
PDF = doc/latex/refman.pdf
all: codecheck test
clean:
rm -rf build dist *.egg-info *.pyc $(MNEXEC)
rm -rf build dist *.egg-info *.pyc $(MNEXEC) $(MANPAGES) $(DOCDIRS)
codecheck: $(PYSRC)
-echo "Running code check"
util/versioncheck.py
pyflakes $(PYSRC)
pylint --rcfile=.pylint $(PYSRC)
pep8 --repeat --ignore=$(P8IGN) $(PYSRC)
@@ -25,15 +32,34 @@ errcheck: $(PYSRC)
test: $(MININET) $(TEST)
-echo "Running tests"
mininet/test/test_nets.py
mininet/test/test_hifi.py
install: $(MNEXEC)
install $(MNEXEC) /usr/local/bin/
mnexec: mnexec.c $(MN) mininet/net.py
cc $(CFLAGS) $(LDFLAGS) -DVERSION=\"`PYTHONPATH=. $(MN) --version`\" $< -o $@
install: $(MNEXEC) $(MANPAGES)
install $(MNEXEC) $(BINDIR)
install $(MANPAGES) $(MANDIR)
python setup.py install
develop: $(MNEXEC)
install $(MNEXEC) /usr/local/bin/
develop: $(MNEXEC) $(MANPAGES)
# Perhaps we should link these as well
install $(MNEXEC) $(BINDIR)
install $(MANPAGES) $(MANDIR)
python setup.py develop
doc:
doxygen doxygen.cfg
man: $(MANPAGES)
mn.1: $(MN)
PYTHONPATH=. help2man -N -n "create a Mininet network." \
--no-discard-stderr $< -o $@
mnexec.1: mnexec
help2man -N -n "execution utility for Mininet." \
-h "-h" -v "-v" --no-discard-stderr ./$< -o $@
.PHONY: doc
doc: man
doxygen doc/doxygen.cfg
make -C doc/latex
-86
View File
@@ -1,86 +0,0 @@
Mininet: A Simple Virtual Testbed for OpenFlow/SDN
or
How to Squeeze a 1024-node OpenFlow Network onto your Laptop
Mininet 1.0.0
---
Welcome to Mininet!
Mininet creates OpenFlow test networks by using process-based
virtualization and network namespaces.
Simulated hosts (as well as switches and controllers with the user
datapath) are created as processes in separate network namespaces. This
allows a complete OpenFlow network to be simulated on top of a single
Linux kernel.
Mininet may be invoked directly from the command line, and also provides a
handy Python API for creating networks of varying sizes and topologies.
Mininet is currently in *limited alpha release*. We encourage you to
experiment with it and hope that you will provide us with feedback on
features, documentation, and how you're using it. We plan to make it
available publicly via a GPL or BSD license (probably in April), but please
don't distribute the code or URLs yet! The feedback you provide will help
us improve Mininet for general release.
In order to run Mininet, you must have:
* A Linux 2.6.26 or greater kernel compiled with network namespace support
enabled (see INSTALL for additional information.)
* An OpenFlow implementation (either the reference user or kernel
space implementations, or Open vSwitch.) Appropriate kernel modules
(e.g. tun and ofdatapath for the reference kernel implementation) must
be loaded.
* Python, bash, ping, iperf, etc.
* Root privileges (required for network device access)
Currently Mininet includes:
- A simple node infrastructure (Host, Switch, Controller classes) for
creating virtual OpenFlow networks
- A simple network infrastructure (Mininet class) supporting parametrized
topologies (Topo subclasses.) For example, a tree network may be created
with the command
# mn --topo tree,depth=2,fanout=3
- Basic tests, including connectivity (ping) and bandwidth (iperf)
- A command-line interface (CLI class) which provides useful
diagnostic commands, as well as the ability to send a command to a
node. For example,
mininet> h11 ifconfig -a
tells host h11 to run the command 'ifconfig -a'
- A 'cleanup' command to get rid of junk (interfaces, processes, files in
/tmp, etc.) which might be left around by Mininet or Linux. Try this if
things stop working!
# mn -c
- Examples (in the examples/ directory) to help you get started.
Batteries are not included (yet!)
However, some preliminary installation notes are included in the INSTALL
file.
Additionally, much useful information, including a Mininet tutorial,
is available on the Mininet wiki:
http://openflow.org/mininet
Enjoy, and good luck!
---
Bob Lantz
rlantz@cs.stanford.edu
+134
View File
@@ -0,0 +1,134 @@
Mininet: Rapid Prototyping for Software Defined Networks
========================================================
*The best way to emulate almost any network on your laptop!*
Version 2.0.0
### What is Mininet?
Mininet emulates a complete network of hosts, links, and switches
on a single machine. To create a sample two-host, one-switch network,
just run:
`sudo mn`
Mininet is useful for interactive development, testing, and demos,
especially those using OpenFlow and SDN. OpenFlow-based network
controllers prototyped in Mininet can usually be transferred to
hardware with minimal changes for full line-rate execution.
### How does it work?
Mininet creates virtual networks using process-based virtualization
and network namespaces - features that are available in recent Linux
kernels. In Mininet, hosts are emulated as `bash` processes running in
a network namespace, so any code that would normally run on a Linux
server (like a web server or client program) should run just fine
within a Mininet "Host". The Mininet "Host" will have its own private
network interface and can only see its own processes. Switches in
Mininet are software-based switches like Open vSwitch or the OpenFlow
reference switch. Links are virtual ethernet pairs, which live in the
Linux kernel and connect our emulated switches to emulated hosts
(processes).
### Features
Mininet includes:
* A command-line launcher (`mn`) to instantiate networks.
* A handy Python API for creating networks of varying sizes and
topologies.
* Examples (in the `examples/` directory) to help you get started.
* Full API documentation via Python `help()` docstrings, as well as
the ability to generate PDF/HTML documentation with `make doc`.
* Parametrized topologies (`Topo` subclasses) using the Mininet
object. For example, a tree network may be created with the
command:
`mn --topo tree,depth=2,fanout=3`
* A command-line interface (`CLI` class) which provides useful
diagnostic commands (like `iperf` and `ping`), as well as the
ability to run a command to a node. For example,
`mininet> h11 ifconfig -a`
tells host h11 to run the command `ifconfig -a`
* A "cleanup" command to get rid of junk (interfaces, processes, files
in /tmp, etc.) which might be left around by Mininet or Linux. Try
this if things stop working!
`mn -c`
### New features in 2.0.0
Mininet 2.0.0 is a major upgrade and provides
a number of enhancements and new features, including:
* "Mininet-HiFi" functionality:
* Link bandwidth limits using `tc` (`TCIntf` and `TCLink` classes)
* CPU isolation and bandwidth limits (`CPULimitedHost` class)
* Support for Open vSwitch 1.4+ (including Ubuntu OVS packages)
* Debian packaging (and `apt-get install mininet` in Ubuntu 12.10)
* First-class Interface (`Intf`) and Link (`Link`) classes for easier
extensibility
* An upgraded Topology (`Topo`) class which supports node and link
customization
* Man pages for the `mn` and `mnexec` utilities.
[Since the API (most notably the topology) has changed, existing code
that runs in Mininet 1.0 will need to be changed to run with Mininet
2.0. This is the primary reason for the major version number change.]
### Installation
See `INSTALL` for installation instructions and details.
### Documentation
In addition to the API documentation (`make doc`), much useful
information, including a Mininet walkthrough and an introduction
to the Python API, is available on the
[Mininet Web Site](http://openflow.org/mininet).
There is also a wiki which you are encouraged to read and to
contribute to, particularly the Frequently Asked Questions (FAQ.)
### Support
Mininet is community-supported. We encourage you to join the
Mininet mailing list, `mininet-discuss` at:
<https://mailman.stanford.edu/mailman/listinfo/mininet-discuss>
### Contributing
Mininet is an open-source project and is currently hosted at
<https://github.com/mininet>. You are encouraged to download the code,
examine it, modify it, and submit bug reports, bug fixes, feature
requests, and enhancements!
Best wishes, and we look forward to seeing what you can do with
Mininet to change the networking world!
### Credits
The Mininet Team:
* Bob Lantz
* Brandon Heller
* Nikhil Handigol
* Vimal Jeyakumar
+54 -36
View File
@@ -12,35 +12,39 @@ Example to pull custom params (topo, switch, etc.) from a file:
"""
from optparse import OptionParser
import os.path
import os
import sys
import time
# Fix setuptools' evil madness, and open up (more?) security holes
if 'PYTHONPATH' in os.environ:
sys.path = os.environ[ 'PYTHONPATH' ].split( ':' ) + sys.path
from mininet.clean import cleanup
from mininet.cli import CLI
from mininet.log import lg, LEVELS, info, warn
from mininet.net import Mininet, MininetWithControlNet
from mininet.log import lg, LEVELS, info
from mininet.net import Mininet, MininetWithControlNet, VERSION
from mininet.node import ( Host, CPULimitedHost, Controller, OVSController,
NOX, RemoteController, UserSwitch, OVSKernelSwitch,
OVSLegacyKernelSwitch )
from mininet.link import Link, TCLink
from mininet.topo import SingleSwitchTopo, LinearTopo, SingleSwitchReversedTopo
from mininet.topolib import TreeTopo
from mininet.util import makeNumeric, custom, customConstructor, splitArgs
from mininet.util import custom, customConstructor
from mininet.util import buildTopo
# built in topologies, created only when run
TOPODEF = 'minimal'
TOPOS = { 'minimal': lambda: SingleSwitchTopo( k=2 ),
'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': SingleSwitchTopo,
'tree': TreeTopo }
'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': SingleSwitchTopo,
'tree': TreeTopo }
SWITCHDEF = 'ovsk'
SWITCHES = { 'user': UserSwitch,
'ovsk': OVSKernelSwitch,
'ovsk': OVSKernelSwitch,
'ovsl': OVSLegacyKernelSwitch }
HOSTDEF = 'proc'
@@ -48,7 +52,7 @@ HOSTS = { 'proc': Host,
'rt': custom( CPULimitedHost, sched='rt' ),
'cfs': custom( CPULimitedHost, sched='cfs' ) }
CONTROLLERDEF = 'ref'
CONTROLLERDEF = 'ovsc'
CONTROLLERS = { 'ref': Controller,
'ovsc': OVSController,
'nox': NOX,
@@ -62,10 +66,12 @@ LINKS = { 'default': Link,
# optional tests to run
TESTS = [ 'cli', 'build', 'pingall', 'pingpair', 'iperf', 'all', 'iperfudp',
'none' ]
'none' ]
ALTSPELLING = { 'pingall': 'pingAll', 'pingpair': 'pingPair',
'iperfudp': 'iperfUdp', 'iperfUDP': 'iperfUdp', 'prefixlen': 'prefixLen' }
ALTSPELLING = { 'pingall': 'pingAll',
'pingpair': 'pingPair',
'iperfudp': 'iperfUdp',
'iperfUDP': 'iperfUdp' }
def addDictOption( opts, choicesDict, default, name, helpStr=None ):
@@ -77,16 +83,21 @@ def addDictOption( opts, choicesDict, default, name, helpStr=None ):
help: string"""
if default not in choicesDict:
raise Exception( 'Invalid default %s for choices dict: %s' %
( default, name ) )
( default, name ) )
if not helpStr:
helpStr = ( '|'.join( sorted( choicesDict.keys() ) ) +
'[,param=value...]' )
'[,param=value...]' )
opts.add_option( '--' + name,
type='string',
default = default,
help = helpStr )
type='string',
default = default,
help = helpStr )
def version( *_args ):
"Print Mininet version and exit"
print "%s" % VERSION
exit()
class MininetRunner( object ):
"Build, setup, and run Mininet."
@@ -134,7 +145,14 @@ class MininetRunner( object ):
else:
raise Exception( 'Custom file name not found' )
opts = OptionParser()
desc = ( "The %prog utility creates Mininet network from the\n"
"command line. It can create parametrized topologies,\n"
"invoke the Mininet CLI, and run tests." )
usage = ( '%prog [options]\n'
'(type %prog -h for details)' )
opts = OptionParser( description=desc, usage=usage )
addDictOption( opts, SWITCHES, SWITCHDEF, 'switch' )
addDictOption( opts, HOSTS, HOSTDEF, 'host' )
addDictOption( opts, CONTROLLERS, CONTROLLERDEF, 'controller' )
@@ -142,39 +160,39 @@ class MininetRunner( object ):
addDictOption( opts, TOPOS, TOPODEF, 'topo' )
opts.add_option( '--clean', '-c', action='store_true',
default=False, help='clean and exit' )
default=False, help='clean and exit' )
opts.add_option( '--custom', type='string', default=None,
help='read custom topo and node params from .py file' )
help='read custom topo and node params from .py' +
'file' )
opts.add_option( '--test', type='choice', choices=TESTS,
default=TESTS[ 0 ],
help='|'.join( TESTS ) )
default=TESTS[ 0 ],
help='|'.join( TESTS ) )
opts.add_option( '--xterms', '-x', action='store_true',
default=False, help='spawn xterms for each node' )
default=False, help='spawn xterms for each node' )
opts.add_option( '--ipbase', '-i', type='string', default='10.0.0.0/8',
help='base IP address for hosts' )
opts.add_option( '--mac', action='store_true',
default=False, help='automatically set host MACs' )
default=False, help='automatically set host MACs' )
opts.add_option( '--arp', action='store_true',
default=False, help='set all-pairs ARP entries' )
default=False, help='set all-pairs ARP entries' )
opts.add_option( '--verbosity', '-v', type='choice',
choices=LEVELS.keys(), default = 'info',
help = '|'.join( LEVELS.keys() ) )
choices=LEVELS.keys(), default = 'info',
help = '|'.join( LEVELS.keys() ) )
opts.add_option( '--innamespace', action='store_true',
default=False, help='sw and ctrl in namespace?' )
opts.add_option( '--listenport', type='int', default=6635,
default=False, help='sw and ctrl in namespace?' )
opts.add_option( '--listenport', type='int', default=6634,
help='base port for passive switch listening' )
opts.add_option( '--nolistenport', action='store_true',
default=False, help="don't use passive listening port")
default=False, help="don't use passive listening " +
"port")
opts.add_option( '--pre', type='string', default=None,
help='CLI script to run before tests' )
help='CLI script to run before tests' )
opts.add_option( '--post', type='string', default=None,
help='CLI script to run after tests' )
opts.add_option( '--prefixlen', type='int', default=8,
help='prefix length (e.g. /8) for automatic '
'network configuration' )
help='CLI script to run after tests' )
opts.add_option( '--pin', action='store_true',
default=False, help="pin hosts to CPU cores "
"(requires --host cfs or --host rt)" )
opts.add_option( '--version', action='callback', callback=version )
self.options, self.args = opts.parse_args()
+13 -24
View File
@@ -1,7 +1,5 @@
"""Custom topology example
author: Brandon Heller (brandonh@stanford.edu)
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
@@ -10,36 +8,27 @@ Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo, Node
from mininet.topo import Topo
class MyTopo( Topo ):
"Simple topology example."
def __init__( self, enable_all = True ):
def __init__( self ):
"Create custom topo."
# Add default members to class.
super( MyTopo, self ).__init__()
# Initialize topology
Topo.__init__( self )
# Set Node IDs for hosts and switches
leftHost = 1
leftSwitch = 2
rightSwitch = 3
rightHost = 4
# Add hosts and switches
leftHost = self.addHost( 'h1' )
rightHost = self.addHost( 'h2' )
leftSwitch = self.addSwitch( 's3' )
rightSwitch = self.addSwitch( 's4' )
# Add nodes
self.add_node( leftSwitch, Node( is_switch=True ) )
self.add_node( rightSwitch, Node( is_switch=True ) )
self.add_node( leftHost, Node( is_switch=False ) )
self.add_node( rightHost, Node( is_switch=False ) )
# Add edges
self.add_edge( leftHost, leftSwitch )
self.add_edge( leftSwitch, rightSwitch )
self.add_edge( rightSwitch, rightHost )
# Consider all switches and hosts 'on'
self.enable_all()
# Add links
self.addLink( leftHost, leftSwitch )
self.addLink( leftSwitch, rightSwitch )
self.addLink( rightSwitch, rightHost )
topos = { 'mytopo': ( lambda: MyTopo() ) }
+13
View File
@@ -0,0 +1,13 @@
mininet (2.0.0~rc1-0ubuntu1) quantal; urgency=low
* New upstream release.
* Update copyright to match upstream release
* Fix this message
-- Bob Lantz <rlantz@cs.stanford.edu> Sun, 18 Nov 2012 00:15:09 -0800
mininet (2.0.0~d4-0ubuntu1) quantal; urgency=low
* Initial release.
-- Bob Lantz <rlantz@cs.stanford.edu> Tue, 07 Aug 2012 14:11:27 -0700
+1
View File
@@ -0,0 +1 @@
9
+30
View File
@@ -0,0 +1,30 @@
Source: mininet
Section: net
Priority: extra
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
XSBC-Original-Maintainer: Bob Lantz <rlantz@cs.stanford.edu>
Standards-Version: 3.9.3
Build-Depends:
debhelper (>= 9~),
help2man,
python-dev,
python-pkg-resources,
python-setuptools,
python-networkx
Homepage: http://openflow.org/mininet
Package: mininet
Architecture: any
Depends:
openvswitch-switch,
python-networkx,
telnet,
${misc:Depends},
${python:Depends},
${shlibs:Depends}
Recommends: iperf, openvswitch-controller, socat
Description: Process-based network emulator
Mininet is a network emulator which uses lightweight
virtualization to create virtual networks for rapid
prototyping of Software-Defined Network (SDN) designs
using OpenFlow.
+37
View File
@@ -0,0 +1,37 @@
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0
Upstream-Name: mininet
Source: https://github.com/mininet/mininet
Files: *
Copyright: 2012 Open Networking Laboratory,
2009-2012 Bob Lantz,
2009-2012 The Board of Trustees of the Leland Stanford Junior
University
License:
Original authors: Bob Lantz and Brandon Heller
.
We are making Mininet available for public use and benefit with the
expectation that others will use, modify and enhance the Software and
contribute those enhancements back to the community. However, since we
would like to make the Software available for broadest use, with as few
restrictions as possible permission is hereby granted, free of charge, to
any person obtaining a copy of this Software to deal in the Software
under the copyrights without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
.
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
.
The name and trademarks of copyright holder(s) may NOT be used in
advertising or publicity pertaining to the Software or any derivatives
without specific, written prior permission.
Vendored
+1
View File
@@ -0,0 +1 @@
README.md
+1
View File
@@ -0,0 +1 @@
examples/*
+1
View File
@@ -0,0 +1 @@
mnexec /usr/bin
+1
View File
@@ -0,0 +1 @@
*.1
Vendored Executable
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/make -f
%:
dh $@ --buildsystem=python_distutils --with=python2
override_dh_auto_build:
make man
make mnexec
dh_auto_build
get-orig-source:
uscan --force-download --rename
+1
View File
@@ -0,0 +1 @@
3.0 (quilt)
+3
View File
@@ -0,0 +1,3 @@
version=3
opts=filenamemangle=s/(.*)\/archive/$1/,uversionmangle=s/([abdr].*)\.tar\.gz/~$1/ \
https://github.com/mininet/mininet/tags .*/archive\/(\d.*\.tar\.gz)
+3 -3
View File
@@ -25,7 +25,7 @@ DOXYFILE_ENCODING = UTF-8
# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
# by quotes) that should identify the project.
PROJECT_NAME = Mininet
PROJECT_NAME = "Mininet Python API Reference Manual"
# The PROJECT_NUMBER tag can be used to enter a project or revision number.
# This could be handy for archiving the generated documentation or
@@ -114,7 +114,7 @@ FULL_PATH_NAMES = YES
# If left blank the directory from which doxygen is run is used as the
# path to strip.
STRIP_FROM_PATH =
STRIP_FROM_PATH =
# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
# the path mentioned in the documentation of a class, which tells
@@ -919,7 +919,7 @@ COMPACT_LATEX = NO
# by the printer. Possible values are: a4, a4wide, letter, legal and
# executive. If left blank a4wide will be used.
PAPER_TYPE = a4wide
PAPER_TYPE = letter
# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
# packages that should be included in the LaTeX output.
+26 -1
View File
@@ -19,13 +19,33 @@ graphical monitoring.
controllers.py:
This example creates a network and adds multiple controllers to it.
This example creates a network with multiple controllers, by
using a custom Switch() subclass.
controllers2.py:
This example creates a network with multiple controllers by
creating an empty network, adding nodes to it, and manually
starting the switches.
cpu.py:
This example tests iperf bandwidth for varying CPU limits.
emptynet.py:
This example demonstrates creating an empty network (i.e. with no
topology object) and adding nodes to it.
hwintf.py:
This example shows how to add an interface (for example a real
hardware interface) to a network after the network is created.
limit.py:
This example shows how to use link and CPU limits.
linearbandwidth.py:
This example shows how to create a custom topology programatically
@@ -48,6 +68,11 @@ multitest.py:
This example creates a network and runs multiple tests on it.
popen.py:
This example monitors a number of hosts using host.popen() and
pmonitor().
popenpoll.py:
This example demonstrates monitoring output from multiple hosts using
+3
View File
@@ -3,6 +3,9 @@
"This example doesn't use OpenFlow, but attempts to run sshd in a namespace."
from mininet.node import Host
from mininet.util import ensureRoot
ensureRoot()
print "*** Creating nodes"
h1 = Host( 'h1' )
+9 -12
View File
@@ -74,11 +74,11 @@ class Console( Frame ):
"Pop up a new terminal window for a node."
net.terms += makeTerms( [ node ], title )
label = Button( self, text=self.node.name, command=newTerm,
**self.buttonStyle )
**self.buttonStyle )
label.pack( side='top', fill='x' )
text = Text( self, wrap='word', **self.textStyle )
ybar = Scrollbar( self, orient='vertical', width=7,
command=text.yview )
command=text.yview )
text.configure( yscrollcommand=ybar.set )
text.pack( side='left', expand=True, fill='both' )
ybar.pack( side='right', fill='y' )
@@ -95,7 +95,7 @@ class Console( Frame ):
# way to trigger a file event handler from Tk's
# event loop!
self.tk.createfilehandler( self.node.stdout, READABLE,
self.handleReadable )
self.handleReadable )
# We're not a terminal (yet?), so we ignore the following
# control characters other than [\b\n\r]
@@ -169,11 +169,8 @@ class Graph( Frame ):
"Graph that we can add bars to over time."
def __init__( self, parent=None,
bg = 'white',
gheight=200, gwidth=500,
barwidth=10,
ymax=3.5,):
def __init__( self, parent=None, bg = 'white', gheight=200, gwidth=500,
barwidth=10, ymax=3.5,):
Frame.__init__( self, parent )
@@ -195,7 +192,7 @@ class Graph( Frame ):
width = 25
ymax = self.ymax
scale = Canvas( self, width=width, height=height,
background=self.bg )
background=self.bg )
opts = { 'fill': 'red' }
# Draw scale line
scale.create_line( width - 1, height, width - 1, 0, **opts )
@@ -211,7 +208,7 @@ class Graph( Frame ):
ofs = 20
height = self.gheight + ofs
self.graph.configure( scrollregion=( 0, -ofs,
self.xpos * self.barwidth, height ) )
self.xpos * self.barwidth, height ) )
self.scale.configure( scrollregion=( 0, -ofs, 0, height ) )
def yview( self, *args ):
@@ -231,7 +228,7 @@ class Graph( Frame ):
xbar = Scrollbar( self, orient='horizontal', command=graph.xview )
ybar = Scrollbar( self, orient='vertical', command=self.yview )
graph.configure( xscrollcommand=xbar.set, yscrollcommand=ybar.set,
scrollregion=(0, 0, width, height ) )
scrollregion=(0, 0, width, height ) )
scale.configure( yscrollcommand=ybar.set )
# Layout
@@ -252,7 +249,7 @@ class Graph( Frame ):
x1 = x0 + self.barwidth
y0 = self.gheight
y1 = ( 1 - percent ) * self.gheight
c.create_rectangle( x0 , y0, x1, y1, fill='green' )
c.create_rectangle( x0, y0, x1, y1, fill='green' )
self.xpos += 1
self.updateScrollRegions()
self.graph.xview( 'moveto', '1.0' )
+18 -54
View File
@@ -1,64 +1,28 @@
#!/usr/bin/python
"""
This example creates a multi-controller network from
semi-scratch; note a topo object could also be used and
would be passed into the Mininet() constructor.
Create a network where different switches are connected to
different controllers, by creating a custom Switch() subclass.
"""
from mininet.net import Mininet
from mininet.node import Controller, OVSKernelSwitch
from mininet.node import OVSSwitch, Controller
from mininet.topolib import TreeTopo
from mininet.cli import CLI
from mininet.log import setLogLevel
Switch = OVSKernelSwitch
c0 = Controller( 'c0' )
c1 = Controller( 'c1', ip='127.0.0.2' )
cmap = { 's1': c0, 's2': c1, 's3': c1 }
def addHost( net, N ):
"Create host hN and add to net."
name = 'h%d' % N
ip = '10.0.0.%d' % N
return net.addHost( name, ip=ip )
class MultiSwitch( OVSSwitch ):
"Custom Switch() subclass that connects to different controllers"
def start( self, controllers ):
return OVSSwitch.start( self, [ cmap[ self.name ] ] )
def multiControllerNet():
"Create a network with multiple controllers."
net = Mininet( controller=Controller, switch=Switch)
print "*** Creating controllers"
c1 = net.addController( 'c1', port=6633 )
c2 = net.addController( 'c2', port=6634 )
print "*** Creating switches"
s1 = net.addSwitch( 's1' )
s2 = net.addSwitch( 's2' )
print "*** Creating hosts"
hosts1 = [ addHost( net, n ) for n in 3, 4 ]
hosts2 = [ addHost( net, n ) for n in 5, 6 ]
print "*** Creating links"
for h in hosts1:
s1.linkTo( h )
for h in hosts2:
s2.linkTo( h )
s1.linkTo( s2 )
print "*** Starting network"
net.build()
c1.start()
c2.start()
s1.start( [ c1 ] )
s2.start( [ c2 ] )
print "*** Testing network"
net.pingAll()
print "*** Running CLI"
CLI( net )
print "*** Stopping network"
net.stop()
if __name__ == '__main__':
setLogLevel( 'info' ) # for CLI output
multiControllerNet()
topo = TreeTopo( depth=2, fanout=2 )
net = Mininet( topo=topo, switch=MultiSwitch, build=False )
net.controllers = [ c0, c1 ]
net.build()
net.start()
CLI( net )
net.stop()
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/python
"""
This example creates a multi-controller network from semi-scratch by
using the net.add*() API and manually starting the switches and controllers.
This is the "mid-level" API, which is an alternative to the "high-level"
Topo() API which supports parametrized topology classes.
Note that one could also create a custom switch class and pass it into
the Mininet() constructor.
"""
from mininet.net import Mininet
from mininet.node import Controller, OVSSwitch
from mininet.cli import CLI
from mininet.log import setLogLevel
def multiControllerNet():
"Create a network from semi-scratch with multiple controllers."
net = Mininet( controller=Controller, switch=OVSSwitch, build=False )
print "*** Creating (reference) controllers"
c1 = net.addController( 'c1', port=6633 )
c2 = net.addController( 'c2', port=6634 )
print "*** Creating switches"
s1 = net.addSwitch( 's1' )
s2 = net.addSwitch( 's2' )
print "*** Creating hosts"
hosts1 = [ net.addHost( 'h%d' % n ) for n in 3, 4 ]
hosts2 = [ net.addHost( 'h%d' % n ) for n in 5, 6 ]
print "*** Creating links"
for h in hosts1:
net.addLink( s1, h )
for h in hosts2:
net.addLink( s2, h )
net.addLink( s1, s2 )
print "*** Starting network"
net.build()
c1.start()
c2.start()
s1.start( [ c1 ] )
s2.start( [ c2 ] )
print "*** Testing network"
net.pingAll()
print "*** Running CLI"
CLI( net )
print "*** Stopping network"
net.stop()
if __name__ == '__main__':
setLogLevel( 'info' ) # for CLI output
multiControllerNet()
+2 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/python
"""
cpu.py: test iperf bandwidth for varying cpu limtis
cpu.py: test iperf bandwidth for varying cpu limits
"""
from mininet.net import Mininet
@@ -46,7 +46,7 @@ def bwtest( cpuLimits, period_us=100000, seconds=5 ):
server.cmd( 'iperf -s -p 5001 &' )
waitListening( client, server, 5001 )
result = client.cmd( 'iperf -yc -t %s -c %s' % (
seconds, server.IP() ) ).split( ',' )
seconds, server.IP() ) ).split( ',' )
bps = float( result[ -1 ] )
server.cmdPrint( 'kill %iperf' )
net.stop()
+11 -6
View File
@@ -10,6 +10,7 @@ import re
from mininet.cli import CLI
from mininet.log import setLogLevel, info, error
from mininet.net import Mininet
from mininet.link import Intf
from mininet.topolib import TreeTopo
from mininet.util import quietRun
@@ -21,22 +22,26 @@ def checkIntf( intf ):
ips = re.findall( r'\d+\.\d+\.\d+\.\d+', quietRun( 'ifconfig ' + intf ) )
if ips:
error( 'Error:', intf, 'has an IP address,'
'and is probably in use!\n' )
'and is probably in use!\n' )
exit( 1 )
if __name__ == '__main__':
setLogLevel( 'info' )
newIntf = 'eth1'
info( '*** Checking', newIntf, '\n' )
checkIntf( newIntf )
intfName = 'eth1'
info( '*** Checking', intfName, '\n' )
checkIntf( intfName )
info( '*** Creating network\n' )
net = Mininet( topo=TreeTopo( depth=1, fanout=2 ) )
switch = net.switches[ 0 ]
info( '*** Adding', newIntf, 'to switch', switch.name, '\n' )
switch.addIntf( newIntf )
info( '*** Adding hardware interface', intfName, 'to switch',
switch.name, '\n' )
_intf = Intf( intfName, node=switch )
info( '*** Note: you may need to reconfigure the interfaces for '
'the Mininet hosts:\n', net.hosts, '\n' )
net.start()
CLI( net )
+4 -20
View File
@@ -8,33 +8,17 @@ from mininet.net import Mininet
from mininet.link import TCIntf
from mininet.node import CPULimitedHost
from mininet.topolib import TreeTopo
from mininet.util import custom, quietRun
from mininet.util import custom
from mininet.log import setLogLevel
from time import sleep
def testLinkLimit( net, bw ):
"Run bandwidth limit test"
print '*** Testing network %.2f Mbps bandwidth limit' % bw
net.iperf( )
def testCpuLimit( net, cpu ):
"run CPU limit test"
pct = cpu * 100
print '*** Testing CPU %.0f%% bandwidth limit' % pct
h1, h2 = net.hosts
h1.cmd( 'while true; do a=1; done &' )
h2.cmd( 'while true; do a=1; done &' )
pid1 = h1.cmd( 'echo $!' ).strip()
pid2 = h2.cmd( 'echo $!' ).strip()
cmd = 'ps -p %s,%s -o pid,%%cpu,args' % ( pid1, pid2 )
# It's a shame that this is what pylint prefers
for _ in range( 5 ):
sleep( 1 )
print quietRun( cmd ).strip()
h1.cmd( 'kill %1')
h2.cmd( 'kill %1')
def limit( bw=10, cpu=.4 ):
def limit( bw=10, cpu=.1 ):
"""Example/test of link and CPU bandwidth limits
bw: interface bandwidth limit in Mbps
cpu: cpu limit as fraction of overall CPU time"""
@@ -46,7 +30,7 @@ def limit( bw=10, cpu=.4 ):
net = Mininet( topo=myTopo, intf=intf, host=host )
net.start()
testLinkLimit( net, bw=bw )
testCpuLimit( net, cpu=cpu )
net.runCpuLimitTest( cpu=cpu )
net.stop()
def verySimpleLimit( bw=150 ):
+6 -6
View File
@@ -41,22 +41,22 @@ class LinearTestTopo( Topo ):
Topo.__init__( self, **params )
# Create switches and hosts
hosts = [ self.add_host( 'h%s' % h )
hosts = [ self.addHost( 'h%s' % h )
for h in irange( 1, N ) ]
switches = [ self.add_switch( 's%s' % s )
switches = [ self.addSwitch( 's%s' % s )
for s in irange( 1, N - 1 ) ]
# Wire up switches
last = None
for switch in switches:
if last:
self.add_link( last, switch )
self.addLink( last, switch )
last = switch
# Wire up hosts
self.add_link( hosts[ 0 ], switches[ 0 ] )
self.addLink( hosts[ 0 ], switches[ 0 ] )
for host, switch in zip( hosts[ 1: ], switches ):
self.add_link( host, switch )
self.addLink( host, switch )
def linearBandwidthTest( lengths ):
@@ -68,7 +68,7 @@ def linearBandwidthTest( lengths ):
hostCount = switchCount + 1
switches = { 'reference user': UserSwitch,
'Open vSwitch kernel': OVSKernelSwitch }
'Open vSwitch kernel': OVSKernelSwitch }
topo = LinearTestTopo( hostCount )
+12 -12
View File
@@ -112,7 +112,7 @@ class MiniEdit( Frame ):
appMenu = Menu( mbar, tearoff=False )
mbar.add_cascade( label=self.appName, font=font, menu=appMenu )
appMenu.add_command( label='About MiniEdit', command=self.about,
font=font)
font=font)
appMenu.add_separator()
appMenu.add_command( label='Quit', command=self.quit, font=font )
@@ -127,7 +127,7 @@ class MiniEdit( Frame ):
editMenu = Menu( mbar, tearoff=False )
mbar.add_cascade( label="Edit", font=font, menu=editMenu )
editMenu.add_command( label="Cut", font=font,
command=lambda: self.deleteSelection( None ) )
command=lambda: self.deleteSelection( None ) )
runMenu = Menu( mbar, tearoff=False )
mbar.add_cascade( label="Run", font=font, menu=runMenu )
@@ -143,7 +143,7 @@ class MiniEdit( Frame ):
f = Frame( self )
canvas = Canvas( f, width=self.cwidth, height=self.cheight,
bg=self.bg )
bg=self.bg )
# Scroll bars
xbar = Scrollbar( f, orient='horizontal', command=canvas.xview )
@@ -177,7 +177,7 @@ class MiniEdit( Frame ):
bbox = self.canvas.bbox( 'all' )
if bbox is not None:
self.canvas.configure( scrollregion=( 0, 0, bbox[ 2 ],
bbox[ 3 ] ) )
bbox[ 3 ] ) )
def canvasx( self, x_root ):
"Convert root x coordinate to canvas coordinate."
@@ -223,7 +223,7 @@ class MiniEdit( Frame ):
for cmd, color in [ ( 'Stop', 'darkRed' ), ( 'Run', 'darkGreen' ) ]:
doCmd = getattr( self, 'do' + cmd )
b = Button( toolbar, text=cmd, font=self.smallFont,
fg=color, command=doCmd )
fg=color, command=doCmd )
b.pack( fill='x', side='bottom' )
return toolbar
@@ -289,7 +289,7 @@ class MiniEdit( Frame ):
def deleteItem( self, item ):
"Delete an item."
# Don't delete while network is running
if self.buttons[ 'Select' ][ 'state' ] == 'disabled' :
if self.buttons[ 'Select' ][ 'state' ] == 'disabled':
return
# Delete from model
if item in self.links:
@@ -308,7 +308,7 @@ class MiniEdit( Frame ):
def nodeIcon( self, node, name ):
"Create a new node icon."
icon = Button( self.canvas, image=self.images[ node ],
text=name, compound='top' )
text=name, compound='top' )
# Unfortunately bindtags wants a tuple
bindtags = [ str( self.nodeBindings ) ]
bindtags += list( icon.bindtags() )
@@ -322,8 +322,8 @@ class MiniEdit( Frame ):
self.nodeCount += 1
name = self.nodePrefixes[ node ] + str( self.nodeCount )
icon = self.nodeIcon( node, name )
item = self.canvas.create_window( x, y, anchor='c',
window=icon, tags=node )
item = self.canvas.create_window( x, y, anchor='c', window=icon,
tags=node )
self.widgetToItem[ icon ] = item
self.itemToWidget[ item ] = icon
self.selectItem( item )
@@ -437,7 +437,7 @@ class MiniEdit( Frame ):
item = self.widgetToItem[ w ]
x, y = self.canvas.coords( item )
self.link = self.canvas.create_line( x, y, x, y, width=4,
fill='blue', tag='link' )
fill='blue', tag='link' )
self.linkx, self.linky = x, y
self.linkWidget = w
self.linkItem = item
@@ -475,7 +475,7 @@ class MiniEdit( Frame ):
target = self.findItem( x, y )
dest = self.itemToWidget.get( target, None )
if ( source is None or dest is None or source == dest
or dest in source.links or source in dest.links ):
or dest in source.links or source in dest.links ):
self.releaseLink( event )
return
# For now, don't allow hosts to be directly linked
@@ -591,7 +591,7 @@ class MiniEdit( Frame ):
cleanUpScreens()
self.net = None
def xterm( self, _=None ):
def xterm( self, _ignore=None ):
"Make an xterm when a button is pressed."
if ( self.selection is None or
self.net is None or
+2 -2
View File
@@ -18,7 +18,7 @@ from time import time
def chunks( l, n ):
"Divide list l into chunks of size n - thanks Stackoverflow"
return [ l[ i : i + n ] for i in range( 0, len( l ), n ) ]
return [ l[ i: i + n ] for i in range( 0, len( l ), n ) ]
def startpings( host, targetips ):
"Tell host to repeatedly ping targets"
@@ -40,7 +40,7 @@ def startpings( host, targetips ):
'done &' )
print ( '*** Host %s (%s) will be pinging ips: %s' %
( host.name, host.IP(), targetips ) )
( host.name, host.IP(), targetips ) )
host.cmd( cmd )
+1 -1
View File
@@ -19,7 +19,7 @@ def monitorFiles( outfiles, seconds, timeoutms ):
tails, fdToFile, fdToHost = {}, {}, {}
for h, outfile in outfiles.iteritems():
tail = Popen( [ 'tail', '-f', outfile ],
stdout=PIPE, stderr=devnull )
stdout=PIPE, stderr=devnull )
fd = tail.stdout.fileno()
tails[ h ] = tail
fdToFile[ fd ] = tail.stdout
+4 -4
View File
@@ -38,12 +38,12 @@ def scratchNetUser( cname='controller', cargs='ptcp:' ):
h1intf, sintf2 = linkIntfs( h1, switch )
info( '*** Configuring control network\n' )
controller.setIP( '10.0.123.1/24', cintf )
switch.setIP( '10.0.123.2/24', sintf)
controller.setIP( '10.0.123.1/24', intf=cintf )
switch.setIP( '10.0.123.2/24', intf=sintf)
info( '*** Configuring hosts\n' )
h0.setIP( '192.168.123.1/24', h0intf )
h1.setIP( '192.168.123.2/24', h1intf )
h0.setIP( '192.168.123.1/24', intf=h0intf )
h1.setIP( '192.168.123.2/24', intf=h1intf )
info( '*** Network state:\n' )
for node in controller, switch, h0, h1:
Regular → Executable
+10 -5
View File
@@ -2,6 +2,11 @@
"""
Simple example of setting network and CPU parameters
NOTE: link params limit BW, add latency, and loss.
There is a high chance that pings WILL fail and that
iperf will hang indefinitely if the TCP handshake fails
to complete.
"""
from mininet.topo import Topo
@@ -15,14 +20,14 @@ class SingleSwitchTopo(Topo):
"Single switch connected to n hosts."
def __init__(self, n=2, **opts):
Topo.__init__(self, **opts)
switch = self.add_switch('s1')
switch = self.addSwitch('s1')
for h in range(n):
# Each host gets 50%/n of system CPU
host = self.add_host('h%s' % (h + 1),
cpu=.5 / n)
host = self.addHost('h%s' % (h + 1),
cpu=.5 / n)
# 10 Mbps, 5ms delay, 10% loss
self.add_link(host, switch,
bw=10, delay='5ms', loss=10, use_htb=True)
self.addLink(host, switch,
bw=10, delay='5ms', loss=10, use_htb=True)
def perfTest():
"Create network and run simple performance test"
+2 -2
View File
@@ -11,8 +11,8 @@ def treePing64():
results = {}
switches = { # 'reference kernel': KernelSwitch,
'reference user': UserSwitch,
'Open vSwitch kernel': OVSKernelSwitch }
'reference user': UserSwitch,
'Open vSwitch kernel': OVSKernelSwitch }
for name in switches:
print "*** Testing", name, "datapath"
+50 -18
View File
@@ -10,51 +10,83 @@ It may also get rid of 'false positives', but hopefully
nothing irreplaceable!
"""
from subprocess import Popen, PIPE
from subprocess import Popen, PIPE, STDOUT, check_output as co
from sys import stdout, exit
from time import sleep
from mininet.log import info
from mininet.log import info, error
from mininet.term import cleanUpScreens
def sh( cmd ):
"Print a command and send it to the shell"
"Run a command in the shell and return non-empty output lines"
info( cmd + '\n' )
return Popen( [ '/bin/sh', '-c', cmd ], stdout=PIPE ).communicate()[ 0 ]
output = ( Popen( [ '/bin/sh', '-c', cmd ], stdout=PIPE )
.communicate()[ 0 ]
.strip()
.split( '\n' ) )
return [ s for s in output if s ]
def cleanup():
"""Clean up junk which might be left over from old runs;
do fast stuff before slow dp and link removal!"""
info("*** Removing excess controllers/ofprotocols/ofdatapaths/pings/noxes"
"\n")
info( "*** Removing excess "
"controllers/ofprotocols/ofdatapaths/pings/noxes\n" )
zombies = 'controller ofprotocol ofdatapath ping nox_core lt-nox_core '
zombies += 'ovs-openflowd udpbwtest'
zombies += 'ovs-openflowd ovs-controller udpbwtest mnexec'
# Note: real zombie processes can't actually be killed, since they
# are already (un)dead. Then again,
# you can't connect to them either, so they're mostly harmless.
sh( 'killall -9 ' + zombies + ' 2> /dev/null' )
# And kill off sudo mnexec
sh( 'pkill -9 -f "sudo mnexec"')
info( "*** Removing junk from /tmp\n" )
sh( 'rm -f /tmp/vconn* /tmp/vlogs* /tmp/*.out /tmp/*.log' )
info( "*** Removing old screen sessions\n" )
info( "*** Removing old X11 tunnels\n" )
cleanUpScreens()
info( "*** Removing excess kernel datapaths\n" )
dps = sh( "ps ax | egrep -o 'dp[0-9]+' | sed 's/dp/nl:/'" ).split( '\n' )
dps = sh( "ps ax | egrep -o 'dp[0-9]+' | sed 's/dp/nl:/'" )
for dp in dps:
if dp != '':
sh( 'dpctl deldp ' + dp )
sh( 'dpctl deldp ' + dp )
info( "*** Removing OVS datapaths" )
dps = sh("ovs-vsctl list-br").split( '\n' )
info( "*** Removing OVS datapaths\n" )
dps = sh("ovs-vsctl list-br")
for dp in dps:
if dp:
sh( 'ovs-vsctl del-br ' + dp )
sh( 'ovs-vsctl del-br ' + dp )
if co( 'ovs-vsctl list-br', shell=True ):
raise Excpetion( "Error: could not remove all OVS datapaths" )
info( "*** Removing all links of the pattern foo-ethX\n" )
links = sh( "ip link show | egrep -o '(\w+-eth\w+)'" ).split( '\n' )
links = sh( "ip link show | egrep -o '(\w+-eth\w+)'" )
for link in links:
if link != '':
sh( "ip link del " + link )
sh( "ip link del " + link )
if sh( "ip link show | egrep -o '(\w+-eth\w+)'" ):
raise Exception( "Error could not remove stale links")
info( "*** Killing stale mininet node processes\n" )
sh( 'pkill -9 -f mininet:' )
# Make sure they are gone
while True:
try:
pids = co( 'pgrep -f mininet:'.split() )
except:
pids = ''
if pids:
sh( 'pkill -f 9 mininet:' )
sleep( .5 )
else:
break
info( "*** Removing stale namespaces\n" )
nses = sh( "ip netns list" )
for ns in nses:
sh( "ip netns del " + ns )
if co( "ip netns list", shell=True ):
error( "Error: could not remove all namespaces - exiting\n" )
exit( 1 )
info( "*** Cleanup complete.\n" )
+25 -6
View File
@@ -121,12 +121,12 @@ class CLI( Cmd ):
"Run an external shell command"
call( line, shell=True )
# do_py() needs to catch any exception during eval()
# do_py() and do_px() need to catch any exception during eval()/exec()
# pylint: disable-msg=W0703
def do_py( self, line ):
"""Evaluate a Python expression.
Node names may be used, e.g.: h1.cmd('ls')"""
Node names may be used, e.g.: py h1.cmd('ls')"""
try:
result = eval( line, globals(), self.locals )
if not result:
@@ -138,7 +138,18 @@ class CLI( Cmd ):
except Exception, e:
output( str( e ) + '\n' )
# pylint: enable-msg=W0703
# We are in fact using the exec() pseudo-function
# pylint: disable-msg=W0122
def do_px( self, line ):
"""Execute a Python statement.
Node names may be used, e.g.: px print h1.cmd('ls')"""
try:
exec( line, globals(), self.locals )
except Exception, e:
output( str( e ) + '\n' )
# pylint: enable-msg=W0703,W0122
def do_pingall( self, _line ):
"Ping between all hosts."
@@ -148,6 +159,14 @@ class CLI( Cmd ):
"Ping between first two hosts, useful for testing."
self.mn.pingPair()
def do_pingallfull( self, _line ):
"Ping between first two hosts, returns all ping results."
self.mn.pingAllFull()
def do_pingpairfull( self, _line ):
"Ping between first two hosts, returns all ping results."
self.mn.pingPairFull()
def do_iperf( self, line ):
"Simple iperf TCP test between two (optionally specified) hosts."
args = line.split()
@@ -192,7 +211,7 @@ class CLI( Cmd ):
"List interfaces."
for node in self.nodelist:
output( '%s: %s\n' %
( node.name, ','.join( node.intfNames() ) ) )
( node.name, ','.join( node.intfNames() ) ) )
def do_dump( self, _line ):
"Dump node info."
@@ -303,8 +322,8 @@ class CLI( Cmd ):
node = self.nodemap[ first ]
# Substitute IP addresses for node names in command
rest = [ self.nodemap[ arg ].IP()
if arg in self.nodemap else arg
for arg in rest ]
if arg in self.nodemap else arg
for arg in rest ]
rest = ' '.join( rest )
# Run cmd on node:
builtin = isShellBuiltin( first )
+60 -38
View File
@@ -25,7 +25,7 @@ Link: basic link class for creating veth pairs
"""
from mininet.log import info, error, debug
from mininet.util import makeIntfPair
from mininet.util import makeIntfPair, errFail, quietRun
from time import sleep
import re
@@ -109,7 +109,7 @@ class Intf( object ):
def rename( self, newname ):
"Rename interface"
self.ifconfig( 'down' )
result = self.cmd( 'ip link set', self.name, 'name', newname )
result = self.cmd( 'ip link set dev', self.name, 'name', newname )
self.name = newname
self.ifconfig( 'up' )
return result
@@ -178,7 +178,7 @@ class TCIntf( Intf ):
as well as delay, loss and max queue length"""
def bwCmds( self, bw=None, speedup=0, use_hfsc=False, use_tbf=False,
enable_ecn=False, enable_red=False ):
latency_ms=None, enable_ecn=False, enable_red=False ):
"Return tc commands to set bandwidth"
cmds, parent = [], ' root '
@@ -196,58 +196,63 @@ class TCIntf( Intf ):
# are specifying the correct sizes. For now I have used
# the same settings we had in the mininet-hifi code.
if use_hfsc:
cmds += [ '%s qdisc add dev %s root handle 1:0 hfsc default 1',
'%s class add dev %s parent 1:0 classid 1:1 hfsc sc '
cmds += [ '%s qdisc add dev %s root handle 5:0 hfsc default 1',
'%s class add dev %s parent 5:0 classid 5:1 hfsc sc '
+ 'rate %fMbit ul rate %fMbit' % ( bw, bw ) ]
elif use_tbf:
latency_us = 10 * 1500 * 8 / bw
cmds += ['%s qdisc add dev %s root handle 1: tbf ' +
'rate %fMbit burst 15000 latency %fus' %
( bw, latency_us ) ]
if latency_ms is None:
latency_ms = 15 * 8 / bw
cmds += [ '%s qdisc add dev %s root handle 5: tbf ' +
'rate %fMbit burst 15000 latency %fms' %
( bw, latency_ms ) ]
else:
cmds += [ '%s qdisc add dev %s root handle 1:0 htb default 1',
'%s class add dev %s parent 1:0 classid 1:1 htb ' +
'rate %fMbit burst 15k' % bw ]
parent = ' parent 1:1 '
cmds += [ '%s qdisc add dev %s root handle 5:0 htb default 1',
'%s class add dev %s parent 5:0 classid 5:1 htb ' +
'rate %fMbit burst 15k' % bw ]
parent = ' parent 5:1 '
# ECN or RED
if enable_ecn:
cmds += [ '%s qdisc add dev %s' + parent +
'handle 10: red limit 1000000 ' +
'handle 6: red limit 1000000 ' +
'min 30000 max 35000 avpkt 1500 ' +
'burst 20 ' +
'bandwidth %fmbit probability 1 ecn' % bw ]
parent = ' parent 10: '
parent = ' parent 6: '
elif enable_red:
cmds += [ '%s qdisc add dev %s' + parent +
'handle 10: red limit 1000000 ' +
'handle 6: red limit 1000000 ' +
'min 30000 max 35000 avpkt 1500 ' +
'burst 20 ' +
'bandwidth %fmbit probability 1' % bw ]
parent = ' parent 10: '
parent = ' parent 6: '
return cmds, parent
@staticmethod
def delayCmds( parent, delay=None, loss=None,
max_queue_size=None ):
def delayCmds( parent, delay=None, jitter=None,
loss=None, max_queue_size=None ):
"Internal method: return tc commands for delay and loss"
cmds = []
if delay and delay < 0:
error( 'Negative delay', delay, '\n' )
elif jitter and jitter < 0:
error( 'Negative jitter', jitter, '\n' )
elif loss and ( loss < 0 or loss > 100 ):
error( 'Bad loss percentage', loss, '%%\n' )
else:
# Delay/loss/max queue size
netemargs = '%s%s%s' % (
# Delay/jitter/loss/max queue size
netemargs = '%s%s%s%s' % (
'delay %s ' % delay if delay is not None else '',
'%s ' % jitter if jitter is not None else '',
'loss %d ' % loss if loss is not None else '',
'limit %d' % max_queue_size if max_queue_size is not None
else '' )
else '' )
if netemargs:
cmds = [ '%s qdisc add dev %s ' + parent +
' handle 10: netem ' +
netemargs ]
return cmds
netemargs ]
parent = ' parent 10:1 '
return cmds, parent
def tc( self, cmd, tc='tc' ):
"Execute tc command for our interface"
@@ -255,9 +260,10 @@ class TCIntf( Intf ):
debug(" *** executing command: %s\n" % c)
return self.cmd( c )
def config( self, bw=None, delay=None, loss=None, disable_gro=True,
speedup=0, use_hfsc=False, use_tbf=False, enable_ecn=False,
enable_red=False, max_queue_size=None, **params ):
def config( self, bw=None, delay=None, jitter=None, loss=None,
disable_gro=True, speedup=0, use_hfsc=False, use_tbf=False,
latency_ms=None, enable_ecn=False, enable_red=False,
max_queue_size=None, **params ):
"Configure the port and set its properties."
result = Intf.config( self, **params)
@@ -277,21 +283,24 @@ class TCIntf( Intf ):
# Bandwidth limits via various methods
bwcmds, parent = self.bwCmds( bw=bw, speedup=speedup,
use_hfsc=use_hfsc, use_tbf=use_tbf,
enable_ecn=enable_ecn,
enable_red=enable_red )
use_hfsc=use_hfsc, use_tbf=use_tbf,
latency_ms=latency_ms,
enable_ecn=enable_ecn,
enable_red=enable_red )
cmds += bwcmds
# Delay/loss/max_queue_size using netem
cmds += self.delayCmds( delay=delay, loss=loss,
max_queue_size=max_queue_size,
parent=parent )
# Delay/jitter/loss/max_queue_size using netem
delaycmds, parent = self.delayCmds( delay=delay, jitter=jitter, loss=loss,
max_queue_size=max_queue_size,
parent=parent )
cmds += delaycmds
# Ugly but functional: display configuration info
stuff = ( ( [ '%.2fMbit' % bw ] if bw is not None else [] ) +
( [ '%s delay' % delay ] if delay is not None else [] ) +
( [ '%s jitter' % jitter ] if jitter is not None else [] ) +
( ['%d%% loss' % loss ] if loss is not None else [] ) +
( [ 'ECN' ] if enable_ecn else [ 'RED' ]
( [ 'ECN' ] if enable_ecn else [ 'RED' ]
if enable_red else [] ) )
info( '(' + ' '.join( stuff ) + ') ' )
@@ -301,6 +310,7 @@ class TCIntf( Intf ):
debug( "cmds:", cmds, '\n' )
debug( "outputs:", tcoutputs, '\n' )
result[ 'tcoutputs'] = tcoutputs
result[ 'parent' ] = parent
return result
@@ -337,7 +347,7 @@ class Link( object ):
if not intfName2:
intfName2 = self.intfName( node2, port2 )
self.makeIntfPair( intfName1, intfName2 )
self.makeIntfPair( intfName1, intfName2, node1, node2 )
if not cls1:
cls1 = intf
@@ -362,13 +372,24 @@ class Link( object ):
return node.name + '-eth' + repr( n )
@classmethod
def makeIntfPair( cls, intf1, intf2 ):
def makeIntfPair( cls, intf1, intf2, node1=None, node2=None ):
"""Create pair of interfaces
intf1: name of interface 1
intf2: name of interface 2
(override this class method [and possibly delete()]
to change link type)"""
makeIntfPair( intf1, intf2 )
# To be compatible with pid namespaces and chroot in the future
# we create links in the root namespace and then move
# the ends as needed.
# First, make sure there aren't stale links sitting around
quietRun( 'ip link delete %s type veth' % intf1 )
quietRun( 'ip link delete %s type veth' % intf2 )
cmd = 'ip link add %s type veth peer name %s' % ( intf1, intf2 )
if node2 and node2.inNamespace:
cmd += ' netns %s' % node2
errFail( cmd )
if node1 and node1.inNamespace:
errFail( 'ip link set dev %s netns %s' % ( intf1, node1 ) )
def delete( self ):
"Delete this link"
@@ -378,6 +399,7 @@ class Link( object ):
def __str__( self ):
return '%s<->%s' % ( self.intf1, self.intf2 )
class TCLink( Link ):
"Link with symmetric TC interfaces configured via opts"
def __init__( self, node1, node2, port1=None, port2=None,
+6 -6
View File
@@ -11,11 +11,11 @@ import types
OUTPUT = 25
LEVELS = { 'debug': logging.DEBUG,
'info': logging.INFO,
'output': OUTPUT,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL }
'info': logging.INFO,
'output': OUTPUT,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL }
# change this to logging.INFO to get printouts when running unit tests
LOGLEVELDEFAULT = OUTPUT
@@ -117,7 +117,7 @@ class MininetLogger( Logger, object ):
Convenience function to support lowercase names.
levelName: level name from LEVELS"""
level = LOGLEVELDEFAULT
if levelname != None:
if levelname is not None:
if levelname not in LEVELS:
raise Exception( 'unknown levelname seen in setLogLevel' )
else:
+5 -5
View File
@@ -19,7 +19,7 @@ def modprobe( mod ):
return quietRun( [ 'modprobe', mod ] )
OF_KMOD = 'ofdatapath'
OVS_KMOD = 'openvswitch_mod'
OVS_KMOD = 'openvswitch_mod' # Renamed 'openvswitch' in OVS 1.7+/Linux 3.5+
TUN = 'tun'
def moduleDeps( subtract=None, add=None ):
@@ -48,8 +48,8 @@ def moduleDeps( subtract=None, add=None ):
modprobeOutput = modprobe( mod )
if modprobeOutput:
error( 'Error inserting ' + mod +
' - is it installed and available via modprobe?\n' +
'Error was: "%s"\n' % modprobeOutput )
' - is it installed and available via modprobe?\n' +
'Error was: "%s"\n' % modprobeOutput )
if mod not in lsmod():
error( 'Failed to insert ' + mod + ' - quitting.\n' )
exit( 1 )
@@ -63,6 +63,6 @@ def pathCheck( *args, **kwargs ):
for arg in args:
if not quietRun( 'which ' + arg ):
error( 'Cannot find required executable %s.\n' % arg +
'Please make sure that %s is installed ' % moduleName +
'and available in your $PATH:\n(%s)\n' % environ[ 'PATH' ] )
'Please make sure that %s is installed ' % moduleName +
'and available in your $PATH:\n(%s)\n' % environ[ 'PATH' ] )
exit( 1 )
+169 -34
View File
@@ -91,24 +91,28 @@ import re
import select
import signal
from time import sleep
from itertools import chain
from mininet.cli import CLI
from mininet.log import info, error, debug, output
from mininet.node import Host, OVSKernelSwitch, Controller
from mininet.link import Link, Intf
from mininet.util import quietRun, fixLimits, numCores
from mininet.util import quietRun, errFail, fixLimits, numCores, ensureRoot
from mininet.util import macColonHex, ipStr, ipParse, netParse, ipAdd
from mininet.term import cleanUpScreens, makeTerms
# Mininet version: should be consistent with README and LICENSE
VERSION = "2.0.0"
class Mininet( object ):
"Network emulation with hosts spawned in network namespaces."
def __init__( self, topo=None, switch=OVSKernelSwitch, host=Host,
controller=Controller, link=Link, intf=Intf,
build=True, xterms=False, cleanup=False, ipBase='10.0.0.0/8',
inNamespace=False,
autoSetMacs=False, autoStaticArp=False, autoPinCpus=False,
listenPort=None ):
controller=Controller, link=Link, intf=Intf,
build=True, xterms=False, cleanup=False, ipBase='10.0.0.0/8',
inNamespace=False,
autoSetMacs=False, autoStaticArp=False, autoPinCpus=False,
listenPort=None ):
"""Create Mininet object.
topo: Topo (topology) object or None
switch: default Switch class
@@ -148,7 +152,8 @@ class Mininet( object ):
self.hosts = []
self.switches = []
self.controllers = []
self.links = []
self.nameToNode = {} # name to Node (Host/Switch) objects
self.terms = [] # list of spawned xterm processes
@@ -213,8 +218,8 @@ class Mininet( object ):
self.nameToNode[ name ] = controller_new
return controller_new
# BL: is this better than just using nameToNode[] ?
# Should it have a better name?
# BL: We now have four ways to look up nodes
# This may (should?) be cleaned up in the future.
def getNodeByName( self, *args ):
"Return node(s) with given name(s)"
if len( args ) == 1:
@@ -225,6 +230,15 @@ class Mininet( object ):
"Convenience alias for getNodeByName"
return self.getNodeByName( *args )
# Even more convenient syntax for node lookup and iteration
def __getitem__( self, *args ):
"""net [ name ] operator: Return node(s) with given name(s)"""
return self.getNodeByName( *args )
def __iter__( self ):
"return iterator over nodes"
return chain( self.hosts, self.switches, self.controllers )
def addLink( self, node1, node2, port1=None, port2=None,
cls=None, **params ):
""""Add a link from node1 to node2
@@ -239,7 +253,9 @@ class Mininet( object ):
defaults.update( params )
if not cls:
cls = self.link
return cls( node1, node2, **defaults )
link = cls( node1, node2, **defaults )
self.links.append( link )
return link
def configHosts( self ):
"Configure a set of hosts."
@@ -275,7 +291,11 @@ class Mininet( object ):
if not self.controllers:
# Add a default controller
info( '*** Adding controller\n' )
self.addController( 'c0' )
classes = self.controller
if type( classes ) is not list:
classes = [ classes ]
for i, cls in enumerate( classes ):
self.addController( 'c%d' % i, cls )
info( '*** Adding hosts:\n' )
for hostName in topo.hosts():
@@ -300,7 +320,7 @@ class Mininet( object ):
def configureControlNetwork( self ):
"Control net config hook: override in subclass"
raise Exception( 'configureControlNetwork: '
'should be overriden in subclass', self )
'should be overriden in subclass', self )
def build( self ):
"Build mininet."
@@ -355,20 +375,34 @@ class Mininet( object ):
if self.terms:
info( '*** Stopping %i terms\n' % len( self.terms ) )
self.stopXterms()
info( '*** Stopping %i controllers\n' % len( self.controllers ) )
for controller in self.controllers:
info( controller.name + ' ' )
controller.stop()
info( '\n' )
info( '*** Stopping %i switches\n' % len( self.switches ) )
for switch in self.switches:
info( switch.name + ' ' )
switch.stop( deleteIntfs=False )
info( '\n' )
info( '*** Removing links\n' )
for link in self.links:
info( '.' )
link.delete()
info( '\n*** Terminating switches\n' )
for switch in self.switches:
info( '.' )
switch.terminate()
info( '\n' )
info( '*** Stopping %i hosts\n' % len( self.hosts ) )
for host in self.hosts:
info( host.name + ' ' )
host.terminate()
info( '\n' )
info( '*** Stopping %i switches\n' % len( self.switches ) )
for switch in self.switches:
info( switch.name + ' ' )
switch.stop()
info( '\n' )
info( '*** Stopping %i controllers\n' % len( self.controllers ) )
for controller in self.controllers:
info( controller.name + ' ' )
controller.stop()
nses = quietRun( 'ip netns list').strip().split()
info( '*** Removing namespaces' )
for ns in nses:
errFail( 'ip netns del ' + ns )
info( '\n*** Done\n' )
def run( self, test, *args, **kwargs ):
@@ -414,16 +448,17 @@ class Mininet( object ):
return (1, 0)
r = r'(\d+) packets transmitted, (\d+) received'
m = re.search( r, pingOutput )
if m == None:
if m is None:
error( '*** Error: could not parse ping output: %s\n' %
pingOutput )
pingOutput )
return (1, 0)
sent, received = int( m.group( 1 ) ), int( m.group( 2 ) )
return sent, received
def ping( self, hosts=None ):
def ping( self, hosts=None, timeout=None ):
"""Ping between all specified hosts.
hosts: list of hosts
timeout: time to wait for a response, as string
returns: ploss packet loss percentage"""
# should we check if running?
packets = 0
@@ -436,7 +471,10 @@ class Mininet( object ):
output( '%s -> ' % node.name )
for dest in hosts:
if node != dest:
result = node.cmd( 'ping -c1 ' + dest.IP() )
opts = ''
if timeout:
opts = '-W %s' % timeout
result = node.cmd( 'ping -c1 %s %s' % (opts, dest.IP()) )
sent, received = self._parsePing( result )
packets += sent
if received > sent:
@@ -452,6 +490,61 @@ class Mininet( object ):
( ploss, lost, packets ) )
return ploss
@staticmethod
def _parsePingFull( pingOutput ):
"Parse ping output and return all data."
# Check for downed link
if 'connect: Network is unreachable' in pingOutput:
return (1, 0)
r = r'(\d+) packets transmitted, (\d+) received'
m = re.search( r, pingOutput )
if m is None:
error( '*** Error: could not parse ping output: %s\n' %
pingOutput )
return (1, 0, 0, 0, 0, 0)
sent, received = int( m.group( 1 ) ), int( m.group( 2 ) )
r = r'rtt min/avg/max/mdev = '
r += r'(\d+\.\d+)/(\d+\.\d+)/(\d+\.\d+)/(\d+\.\d+) ms'
m = re.search( r, pingOutput )
rttmin = float( m.group( 1 ) )
rttavg = float( m.group( 2 ) )
rttmax = float( m.group( 3 ) )
rttdev = float( m.group( 4 ) )
return sent, received, rttmin, rttavg, rttmax, rttdev
def pingFull( self, hosts=None, timeout=None ):
"""Ping between all specified hosts and return all data.
hosts: list of hosts
timeout: time to wait for a response, as string
returns: all ping data; see function body."""
# should we check if running?
# Each value is a tuple: (src, dsd, [all ping outputs])
all_outputs = []
if not hosts:
hosts = self.hosts
output( '*** Ping: testing ping reachability\n' )
for node in hosts:
output( '%s -> ' % node.name )
for dest in hosts:
if node != dest:
opts = ''
if timeout:
opts = '-W %s' % timeout
result = node.cmd( 'ping -c1 %s %s' % (opts, dest.IP()) )
outputs = self._parsePingFull( result )
sent, received, rttmin, rttavg, rttmax, rttdev = outputs
all_outputs.append( (node, dest, outputs) )
output( ( '%s ' % dest.name ) if received else 'X ' )
output( '\n' )
output( "*** Results: \n" )
for outputs in all_outputs:
src, dest, ping_outputs = outputs
sent, received, rttmin, rttavg, rttmax, rttdev = ping_outputs
output( " %s->%s: %s/%s, " % (src, dest, sent, received ) )
output( "rtt min/avg/max/mdev %0.3f/%0.3f/%0.3f/%0.3f ms\n" %
(rttmin, rttavg, rttmax, rttdev) )
return all_outputs
def pingAll( self ):
"""Ping between all hosts.
returns: ploss packet loss percentage"""
@@ -463,6 +556,17 @@ class Mininet( object ):
hosts = [ self.hosts[ 0 ], self.hosts[ 1 ] ]
return self.ping( hosts=hosts )
def pingAllFull( self ):
"""Ping between all hosts.
returns: ploss packet loss percentage"""
return self.pingFull()
def pingPairFull( self ):
"""Ping between first two hosts, useful for testing.
returns: ploss packet loss percentage"""
hosts = [ self.hosts[ 0 ], self.hosts[ 1 ] ]
return self.pingFull( hosts=hosts )
@staticmethod
def _parseIperf( iperfOutput ):
"""Parse iperf output and return bandwidth.
@@ -508,11 +612,11 @@ class Mininet( object ):
servout += server.monitor()
if l4Type == 'TCP':
while 'Connected' not in client.cmd(
'sh -c "echo A | telnet -e A %s 5001"' % server.IP()):
'sh -c "echo A | telnet -e A %s 5001"' % server.IP()):
output('waiting for iperf to start up...')
sleep(.5)
cliout = client.cmd( iperfArgs + '-t 5 -c ' + server.IP() + ' ' +
bwArgs )
bwArgs )
debug( 'Client output: %s\n' % cliout )
server.sendInt()
servout += server.waitOutput()
@@ -523,6 +627,42 @@ class Mininet( object ):
output( '*** Results: %s\n' % result )
return result
def runCpuLimitTest( self, cpu, duration=5 ):
"""run CPU limit test with 'while true' processes.
cpu: desired CPU fraction of each host
duration: test duration in seconds
returns a single list of measured CPU fractions as floats.
"""
pct = cpu * 100
info('*** Testing CPU %.0f%% bandwidth limit\n' % pct)
hosts = self.hosts
for h in hosts:
h.cmd( 'while true; do a=1; done &' )
pids = [h.cmd( 'echo $!' ).strip() for h in hosts]
pids_str = ",".join(["%s" % pid for pid in pids])
cmd = 'ps -p %s -o pid,%%cpu,args' % pids_str
# It's a shame that this is what pylint prefers
outputs = []
for _ in range( duration ):
sleep( 1 )
outputs.append( quietRun( cmd ).strip() )
for h in hosts:
h.cmd( 'kill %1' )
cpu_fractions = []
for test_output in outputs:
# Split by line. Ignore first line, which looks like this:
# PID %CPU COMMAND\n
for line in test_output.split('\n')[1:]:
r = r'\d+\s*(\d+\.\d+)'
m = re.search( r, line )
if m is None:
error( '*** Error: could not extract CPU fraction: %s\n' %
line )
return None
cpu_fractions.append( float( m.group( 1 ) ) )
output( '*** Results: %s\n' % cpu_fractions )
return cpu_fractions
# BL: I think this can be rewritten now that we have
# a real link class.
def configLinkStatus( self, src, dst, status ):
@@ -564,12 +704,7 @@ class Mininet( object ):
"Initialize Mininet"
if cls.inited:
return
if os.getuid() != 0:
# Note: this script must be run as root
# Probably we should only sudo when we need
# to as per Big Switch's patch
print "*** Mininet must run as root."
exit( 1 )
ensureRoot()
fixLimits()
cls.inited = True
@@ -610,7 +745,7 @@ class MininetWithControlNet( Mininet ):
# in the control network location.
def configureRoutedControlNetwork( self, ip='192.168.123.1',
prefixLen=16 ):
prefixLen=16 ):
"""Configure a routed control network on controller and switches.
For use with the user datapath only right now."""
controller = self.controllers[ 0 ]
+131 -74
View File
@@ -49,10 +49,12 @@ import re
import signal
import select
from subprocess import Popen, PIPE, STDOUT
from sys import stdout
from time import sleep
from mininet.log import info, error, warn, debug
from mininet.util import ( quietRun, errRun, errFail, moveIntf, isShellBuiltin,
numCores, retry, mountCgroups )
numCores, retry, mountCgroups )
from mininet.moduledeps import moduleDeps, pathCheck, OVS_KMOD, OF_KMOD, TUN
from mininet.link import Link, Intf, TCIntf
@@ -83,8 +85,8 @@ class Node( object ):
# Make pylint happy
( self.shell, self.execed, self.pid, self.stdin, self.stdout,
self.lastPid, self.lastCmd, self.pollOut ) = (
None, None, None, None, None, None, None, None )
self.lastPid, self.lastCmd, self.pollOut ) = (
None, None, None, None, None, None, None, None )
self.waiting = False
self.readbuf = ''
@@ -107,20 +109,27 @@ class Node( object ):
# Command support via shell process in namespace
def _popen( self, *args, **kwargs ):
"Internal wrapper for Popen"
old = signal.signal( signal.SIGINT, signal.SIG_IGN )
result = Popen( *args, **kwargs )
signal.signal( signal.SIGINT, old )
return result
def startShell( self ):
"Start a shell process for running commands"
if self.shell:
error( "%s: shell is already running" )
return
# mnexec: (c)lose descriptors, (d)etach from tty,
# (p)rint pid, and run in (n)amespace
opts = '-cdp'
if self.inNamespace:
opts += 'n'
# bash -m: enable job control
cmd = [ 'mnexec', opts, 'bash', '-m' ]
self.shell = Popen( cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT,
close_fds=True )
# -s: pass $* to shell, and make process easy to find in ps
cmd = [ 'bash', '-ms', 'mininet:' + self.name ]
if self.inNamespace:
quietRun( 'ip netns del ' + self.name )
errFail( 'ip netns add ' + self.name )
cmd = [ 'ip', 'netns', 'exec', self.name ] + cmd
self.shell = self._popen( cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT,
close_fds=True )
self.stdin = self.shell.stdin
self.stdout = self.shell.stdout
self.pid = self.shell.pid
@@ -139,11 +148,16 @@ class Node( object ):
def cleanup( self ):
"Help python collect its garbage."
if not self.inNamespace:
for intfName in self.intfNames():
if self.name in intfName:
quietRun( 'ip link del ' + intfName )
self.shell = None
if self.shell:
self.shell.terminate()
self.shell.wait()
self.shell = None
if self.inNamespace:
# Note: this will only work if there are no other
# processes running in namespaces, but we'll do it anyway
quietRun( 'ip netns del ' + self.name )
# Subshell I/O, commands and control
def read( self, maxbytes=1024 ):
"""Buffered read from node, non-blocking.
@@ -167,7 +181,7 @@ class Node( object ):
if '\n' not in self.readbuf:
return None
pos = self.readbuf.find( '\n' )
line = self.readbuf[ 0 : pos ]
line = self.readbuf[ 0: pos ]
self.readbuf = self.readbuf[ pos + 1: ]
return line
@@ -288,7 +302,7 @@ class Node( object ):
kwargs: Popen() keyword args"""
defaults = { 'stdout': PIPE, 'stderr': PIPE,
'mncmd':
[ 'mnexec', '-a', str( self.pid ) ] }
[ 'mnexec', '-da', str( self.pid ) ] }
defaults.update( kwargs )
if len( args ) == 1:
if type( args[ 0 ] ) is list:
@@ -309,7 +323,7 @@ class Node( object ):
# Shell requires a string, not a list!
if defaults.get( 'shell', False ):
cmd = ' '.join( cmd )
return Popen( cmd, **defaults )
return self._popen( cmd, **defaults )
def pexec( self, *args, **kwargs ):
"""Execute a command using popen
@@ -343,10 +357,8 @@ class Node( object ):
self.ports[ intf ] = port
self.nameToIntf[ intf.name ] = intf
debug( '\n' )
assert intf.name in self.cmd( 'ip link show' )
debug( 'added intf %s:%d to node %s\n' % ( intf, port, self.name ) )
if self.inNamespace:
debug( 'moving', intf, 'into namespace for', self.name, '\n' )
moveIntf( intf.name, self )
def defaultIntf( self ):
"Return interface for lowest port"
@@ -355,17 +367,23 @@ class Node( object ):
return self.intfs[ min( ports ) ]
else:
warn( '*** defaultIntf: warning:', self.name,
'has no interfaces\n' )
'has no interfaces\n' )
def intf( self, intf='' ):
"""Return our interface object with given name,
or default intf if name is empty"""
"""Return our interface object with given string name,
default intf if name is falsy (None, empty string, etc).
or the input intf arg.
Having this fcn return its arg for Intf objects makes it
easier to construct functions with flexible input args for
interfaces (those that accept both string names and Intf objects).
"""
if not intf:
return self.defaultIntf()
elif type( intf) is str:
return self.nameToIntf[ intf ]
else:
return None
return intf
def connectionsTo( self, node):
"Return [ intf1, intf2... ] for all intfs that connect self to node."
@@ -391,6 +409,7 @@ class Node( object ):
for intf in self.intfs.values():
intf.delete()
info( '.' )
stdout.flush()
# Routing support
@@ -425,7 +444,7 @@ class Node( object ):
def setIP( self, ip, prefixLen=8, intf=None ):
"""Set the IP address for an interface.
intf: interface name
intf: intf or intf name
ip: IP address as a string
prefixLen: prefix length, e.g. 8 for /8 or 16M addrs"""
# This should probably be rethought
@@ -439,7 +458,7 @@ class Node( object ):
def MAC( self, intf=None ):
"Return MAC address of a node or specific interface."
return self.intf( intf ).IP()
return self.intf( intf ).MAC()
def intfIsUp( self, intf=None ):
"Check if an interface is up."
@@ -513,9 +532,9 @@ class Node( object ):
def __repr__( self ):
"More informative string representation"
intfs = ( ','.join( [ '%s:%s' % ( i.name, i.IP() )
for i in self.intfList() ] ) )
for i in self.intfList() ] ) )
return '<%s %s: %s pid=%s> ' % (
self.__class__.__name__, self.name, intfs, self.pid )
self.__class__.__name__, self.name, intfs, self.pid )
def __str__( self ):
"Abbreviated string representation"
@@ -596,7 +615,7 @@ class CPULimitedHost( Host ):
args: Popen() args, single list, or string
kwargs: Popen() keyword args"""
# Tell mnexec to execute command in our cgroup
mncmd = [ 'mnexec', '-a', str( self.pid ),
mncmd = [ 'mnexec', '-da', str( self.pid ),
'-g', self.name ]
if self.sched == 'rt':
mncmd += [ '-r', str( self.rtprio ) ]
@@ -683,7 +702,7 @@ class CPULimitedHost( Host ):
# We have to do this here after we've specified
# cpus and mems
errFail( 'cgclassify -g cpuset:/%s %s' % (
self.name, self.pid ) )
self.name, self.pid ) )
def config( self, cpu=None, cores=None, **params ):
"""cpu: desired overall system CPU fraction
@@ -770,14 +789,14 @@ class Switch( Node ):
return Node.sendCmd( self, *cmd, **kwargs )
else:
error( '*** Error: %s has execed and cannot accept commands' %
self.name )
self.name )
def __repr__( self ):
"More informative string representation"
intfs = ( ','.join( [ '%s:%s' % ( i.name, i.IP() )
for i in self.intfList() ] ) )
for i in self.intfList() ] ) )
return '<%s %s: %s pid=%s> ' % (
self.__class__.__name__, self.name, intfs, self.pid )
self.__class__.__name__, self.name, intfs, self.pid )
class UserSwitch( Switch ):
"User-space switch."
@@ -789,7 +808,8 @@ class UserSwitch( Switch ):
name: name for the switch"""
Switch.__init__( self, name, **kwargs )
pathCheck( 'ofdatapath', 'ofprotocol',
moduleName='the OpenFlow reference user switch (openflow.org)' )
moduleName='the OpenFlow reference user switch' +
'(openflow.org)' )
if self.listenPort:
self.opts += ' --listen=ptcp:%i ' % self.listenPort
@@ -810,25 +830,27 @@ class UserSwitch( Switch ):
"""Start OpenFlow reference user datapath.
Log to /tmp/sN-{ofd,ofp}.log.
controllers: list of controller objects"""
controller = controllers[ 0 ]
# Add controllers
clist = ','.join( [ 'tcp:%s:%d' % ( c.IP(), c.port )
for c in controllers ] )
ofdlog = '/tmp/' + self.name + '-ofd.log'
ofplog = '/tmp/' + self.name + '-ofp.log'
self.cmd( 'ifconfig lo up' )
intfs = [ str( i ) for i in self.intfList() if not i.IP() ]
self.cmd( 'ofdatapath -i ' + ','.join( intfs ) +
' punix:/tmp/' + self.name + ' -d ' + self.dpid +
' --no-slicing ' +
' 1> ' + ofdlog + ' 2> ' + ofdlog + ' &' )
' punix:/tmp/' + self.name + ' -d ' + self.dpid +
' 1> ' + ofdlog + ' 2> ' + ofdlog + ' &' )
self.cmd( 'ofprotocol unix:/tmp/' + self.name +
' tcp:%s:%d' % ( controller.IP(), controller.port ) +
' --fail=closed ' + self.opts +
' 1> ' + ofplog + ' 2>' + ofplog + ' &' )
' ' + clist +
' --fail=closed ' + self.opts +
' 1> ' + ofplog + ' 2>' + ofplog + ' &' )
def stop( self ):
def stop( self, deleteIntfs=True ):
"Stop OpenFlow reference user datapath."
self.cmd( 'kill %ofdatapath' )
self.cmd( 'kill %ofprotocol' )
self.deleteIntfs()
if deleteIntfs:
self.deleteIntfs()
class OVSLegacyKernelSwitch( Switch ):
@@ -845,14 +867,14 @@ class OVSLegacyKernelSwitch( Switch ):
self.intf = self.dp
if self.inNamespace:
error( "OVSKernelSwitch currently only works"
" in the root namespace.\n" )
" in the root namespace.\n" )
exit( 1 )
@classmethod
def setup( cls ):
"Ensure any dependencies are loaded; if not, try to load them."
pathCheck( 'ovs-dpctl', 'ovs-openflowd',
moduleName='Open vSwitch (openvswitch.org)')
moduleName='Open vSwitch (openvswitch.org)')
moduleDeps( subtract=OF_KMOD, add=OVS_KMOD )
def start( self, controllers ):
@@ -866,19 +888,21 @@ class OVSLegacyKernelSwitch( Switch ):
intfs = [ str( i ) for i in self.intfList() if not i.IP() ]
self.cmd( 'ovs-dpctl', 'add-if', self.dp, ' '.join( intfs ) )
# Run protocol daemon
controller = controllers[ 0 ]
clist = ','.join( [ 'tcp:%s:%d' % ( c.IP(), c.port )
for c in controllers ] )
self.cmd( 'ovs-openflowd ' + self.dp +
' tcp:%s:%d' % ( controller.IP(), controller.port ) +
' --fail=secure ' + self.opts +
' --datapath-id=' + self.dpid +
' 1>' + ofplog + ' 2>' + ofplog + '&' )
' ' + clist +
' --fail=secure ' + self.opts +
' --datapath-id=' + self.dpid +
' 1>' + ofplog + ' 2>' + ofplog + '&' )
self.execed = False
def stop( self ):
def stop( self, deleteIntfs=True ):
"Terminate kernel datapath."
quietRun( 'ovs-dpctl del-dp ' + self.dp )
self.cmd( 'kill %ovs-openflowd' )
self.deleteIntfs()
if deleteIntfs:
self.deleteIntfs()
class OVSSwitch( Switch ):
@@ -895,8 +919,10 @@ class OVSSwitch( Switch ):
def setup( cls ):
"Make sure Open vSwitch is installed and working"
pathCheck( 'ovs-vsctl',
moduleName='Open vSwitch (openvswitch.org)')
moduleDeps( subtract=OF_KMOD, add=OVS_KMOD )
moduleName='Open vSwitch (openvswitch.org)')
# This should no longer be needed, and it breaks
# with OVS 1.7 which has renamed the kernel module:
# moduleDeps( subtract=OF_KMOD, add=OVS_KMOD )
out, err, exitcode = errRun( 'ovs-vsctl -t 1 show' )
if exitcode:
error( out + err +
@@ -949,14 +975,17 @@ class OVSSwitch( Switch ):
if not intf.IP():
self.attach( intf )
# Add controllers
clist = ','.join( [ 'tcp:%s:%d' % ( c.IP(), c.port )
clist = ' '.join( [ 'tcp:%s:%d' % ( c.IP(), c.port )
for c in controllers ] )
if self.listenPort:
clist += ' ptcp:%s' % self.listenPort
self.cmd( 'ovs-vsctl set-controller', self, clist )
def stop( self ):
"Terminate OVS switch."
def stop( self, deleteIntfs=True ):
"Stop OVS switch."
self.cmd( 'ovs-vsctl del-br', self )
self.deleteIntfs()
if deleteIntfs:
self.deleteIntfs()
OVSKernelSwitch = OVSSwitch
@@ -966,15 +995,35 @@ class Controller( Node ):
OpenFlow controller."""
def __init__( self, name, inNamespace=False, command='controller',
cargs='-v ptcp:%d', cdir=None, ip="127.0.0.1",
port=6633, **params ):
cargs='-v ptcp:%d', cdir=None, ip="127.0.0.1",
port=6633, **params ):
self.command = command
self.cargs = cargs
self.cdir = cdir
self.ip = ip
self.port = port
Node.__init__( self, name, inNamespace=inNamespace,
ip=ip, **params )
ip=ip, **params )
self.cmd( 'ifconfig lo up' ) # Shouldn't be necessary
self.checkListening()
def checkListening( self ):
"Make sure no controllers are running on our port"
# Verify that Telnet is installed first:
out, _err, returnCode = errRun( "which telnet" )
if 'telnet' not in out or returnCode != 0:
raise Exception( "Error running telnet to check for listening "
"controllers; please check that it is "
"installed." )
listening = self.cmd( "echo A | telnet -e A %s %d" %
( self.ip, self.port ) )
if 'Unable' not in listening:
servers = self.cmd( 'netstat -atp' ).split( '\n' )
pstr = ':%d ' % self.port
clist = servers[ 0:1 ] + [ s for s in servers if pstr in s ]
raise Exception( "Please shut down the controller which is"
" running on port %d:\n" % self.port +
'\n'.join( clist ) )
def start( self ):
"""Start <controller> <args> on controller.
@@ -984,7 +1033,7 @@ class Controller( Node ):
if self.cdir is not None:
self.cmd( 'cd ' + self.cdir )
self.cmd( self.command + ' ' + self.cargs % self.port +
' 1>' + cout + ' 2>' + cout + '&' )
' 1>' + cout + ' 2>' + cout + '&' )
self.execed = False
def stop( self ):
@@ -1003,8 +1052,8 @@ class Controller( Node ):
def __repr__( self ):
"More informative string representation"
return '<%s %s: %s:%s pid=%s> ' % (
self.__class__.__name__, self.name,
self.IP(), self.port, self.pid )
self.__class__.__name__, self.name,
self.IP(), self.port, self.pid )
class OVSController( Controller ):
@@ -1032,24 +1081,24 @@ class NOX( Controller ):
noxCoreDir = os.environ[ 'NOX_CORE_DIR' ]
Controller.__init__( self, name,
command=noxCoreDir + '/nox_core',
cargs='--libdir=/usr/local/lib -v -i ptcp:%s ' +
' '.join( noxArgs ),
cdir=noxCoreDir, **kwargs )
command=noxCoreDir + '/nox_core',
cargs='--libdir=/usr/local/lib -v -i ptcp:%s ' +
' '.join( noxArgs ),
cdir=noxCoreDir,
**kwargs )
class RemoteController( Controller ):
"Controller running outside of Mininet's control."
def __init__( self, name, ip='127.0.0.1',
port=6633, **kwargs):
port=6633, **kwargs):
"""Init.
name: name to give controller
defaultIP: the IP address where the remote controller is
ip: the IP address where the remote controller is
listening
port: the port where the remote controller is listening"""
Controller.__init__( self, name, ip=ip, port=port,
**kwargs )
Controller.__init__( self, name, ip=ip, port=port, **kwargs )
def start( self ):
"Overridden to do nothing."
@@ -1058,3 +1107,11 @@ class RemoteController( Controller ):
def stop( self ):
"Overridden to do nothing."
return
def checkListening( self ):
"Warn if remote controller is not accessible"
listening = self.cmd( "echo A | telnet -e A %s %d" %
( self.ip, self.port ) )
if 'Unable' in listening:
warn( "Unable to contact the remote controller"
" at %s:%d\n" % ( self.ip, self.port ) )
+39 -32
View File
@@ -1,60 +1,67 @@
"""
Terminal creation and cleanup.
Utility functions to run a term (connected via screen(1)) on each host.
Utility functions to run a terminal (connected via socat(1)) on each host.
Requires GNU screen(1) and xterm(1).
Requires socat(1) and xterm(1).
Optionally uses gnome-terminal.
"""
import re
from subprocess import Popen
from os import environ
from mininet.log import error
from mininet.util import quietRun
from mininet.util import quietRun, errRun
def quoteArg( arg ):
"Quote an argument if it contains spaces."
return repr( arg ) if ' ' in arg else arg
def tunnelX11( node, display=None):
"""Create an X11 tunnel from node:6000 to the root host
display: display on root host (optional)
returns: node $DISPLAY, Popen object for tunnel"""
if display is None:
display = environ[ 'DISPLAY' ]
host, screen = display.split( ':' )
# Unix sockets should work
if not host or host == 'unix':
# GDM3 doesn't put credentials in .Xauthority,
# so allow root to just connect
quietRun( 'xhost +si:localuser:root' )
return display, None
else:
# Create a tunnel for the TCP connection
port = 6000 + int( float( screen ) )
connection = r'TCP\:%s\:%s' % ( host, port )
cmd = [ "socat", "TCP-LISTEN:%d,fork,reuseaddr" % port,
"EXEC:'mnexec -a 1 socat STDIO %s'" % connection ]
return 'localhost:' + screen, node.popen( cmd )
def makeTerm( node, title='Node', term='xterm' ):
"""Run screen on a node, and hook up a terminal.
def makeTerm( node, title='Node', term='xterm', display=None ):
"""Create an X11 tunnel to the node and start up a terminal.
node: Node object
title: base title
term: 'xterm' or 'gterm'
returns: process created"""
returns: two Popen objects, tunnel and terminal"""
title += ': ' + node.name
if not node.inNamespace:
title += ' (root)'
cmds = {
'xterm': [ 'xterm', '-title', title, '-e' ],
'gterm': [ 'gnome-terminal', '--title', title, '-e' ]
'xterm': [ 'xterm', '-title', title, '-display' ],
'gterm': [ 'gnome-terminal', '--title', title, '--display' ]
}
if term not in cmds:
error( 'invalid terminal type: %s' % term )
return
if not node.execed:
node.cmd( 'screen -dmS ' + 'mininet.' + node.name)
args = [ 'screen', '-D', '-RR', '-S', 'mininet.' + node.name ]
else:
args = [ 'sh', '-c', 'exec tail -f /tmp/' + node.name + '*.log' ]
if term == 'gterm':
# Compress these for gnome-terminal, which expects one token
# to follow the -e option
args = [ ' '.join( [ quoteArg( arg ) for arg in args ] ) ]
return Popen( cmds[ term ] + args )
display, tunnel = tunnelX11( node, display )
term = node.popen( cmds[ term ] + [ display, '-e', 'env TERM=ansi bash'] )
return [ tunnel, term ] if tunnel else [ term ]
def cleanUpScreens():
"Remove moldy old screen sessions."
r = r'(\d+\.mininet\.[hsc]\d+)'
output = quietRun( 'screen -ls' ).split( '\n' )
for line in output:
m = re.search( r, line )
if m:
quietRun( 'screen -S ' + m.group( 1 ) + ' -X quit' )
"Remove moldy socat X11 tunnels."
errRun( "pkill -9 -f mnexec.*socat" )
def makeTerms( nodes, title='Node', term='xterm' ):
"""Create terminals.
nodes: list of Node objects
title: base title for each
returns: list of created terminal processes"""
return [ makeTerm( node, title, term ) for node in nodes ]
returns: list of created tunnel/terminal processes"""
terms = []
for node in nodes:
terms += makeTerm( node, title, term )
return terms
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python
"""Package: mininet
Test creation and pings for topologies with link and/or CPU options."""
import unittest
from mininet.net import Mininet
from mininet.node import OVSKernelSwitch
from mininet.node import CPULimitedHost
from mininet.link import TCLink
from mininet.topo import Topo
from mininet.log import setLogLevel
SWITCH = OVSKernelSwitch
# Number of hosts for each test
N = 2
class SingleSwitchOptionsTopo(Topo):
"Single switch connected to n hosts."
def __init__(self, n=2, hopts=None, lopts=None):
if not hopts:
hopts = {}
if not lopts:
lopts = {}
Topo.__init__(self, hopts=hopts, lopts=lopts)
switch = self.addSwitch('s1')
for h in range(n):
host = self.addHost('h%s' % (h + 1))
self.addLink(host, switch)
class testOptionsTopo( unittest.TestCase ):
"Verify ability to create networks with host and link options."
def runOptionsTopoTest( self, n, hopts=None, lopts=None ):
"Generic topology-with-options test runner."
mn = Mininet( topo=SingleSwitchOptionsTopo( n=n, hopts=hopts,
lopts=lopts ),
host=CPULimitedHost, link=TCLink )
dropped = mn.run( mn.ping )
self.assertEqual( dropped, 0 )
def assertWithinTolerance(self, measured, expected, tolerance_frac):
"""Check that a given value is within a tolerance of expected
tolerance_frac: less-than-1.0 value; 0.8 would yield 20% tolerance.
"""
self.assertTrue( float(measured) >= float(expected) * tolerance_frac )
self.assertTrue( float(measured) >= float(expected) * tolerance_frac )
def testCPULimits( self ):
"Verify topology creation with CPU limits set for both schedulers."
CPU_FRACTION = 0.1
CPU_TOLERANCE = 0.8 # CPU fraction below which test should fail
hopts = { 'cpu': CPU_FRACTION }
#self.runOptionsTopoTest( N, hopts=hopts )
mn = Mininet( SingleSwitchOptionsTopo( n=N, hopts=hopts ),
host=CPULimitedHost )
mn.start()
results = mn.runCpuLimitTest( cpu=CPU_FRACTION )
mn.stop()
for cpu in results:
self.assertWithinTolerance( cpu, CPU_FRACTION, CPU_TOLERANCE )
def testLinkBandwidth( self ):
"Verify that link bandwidths are accurate within a bound."
BW = 5 # Mbps
BW_TOLERANCE = 0.8 # BW fraction below which test should fail
# Verify ability to create limited-link topo first;
lopts = { 'bw': BW, 'use_htb': True }
# Also verify correctness of limit limitng within a bound.
mn = Mininet( SingleSwitchOptionsTopo( n=N, lopts=lopts ),
link=TCLink )
bw_strs = mn.run( mn.iperf )
for bw_str in bw_strs:
bw = float( bw_str.split(' ')[0] )
self.assertWithinTolerance( bw, BW, BW_TOLERANCE )
def testLinkDelay( self ):
"Verify that link delays are accurate within a bound."
DELAY_MS = 15
DELAY_TOLERANCE = 0.8 # Delay fraction below which test should fail
lopts = { 'delay': '%sms' % DELAY_MS, 'use_htb': True }
mn = Mininet( SingleSwitchOptionsTopo( n=N, lopts=lopts ),
link=TCLink )
ping_delays = mn.run( mn.pingFull )
test_outputs = ping_delays[0]
# Ignore unused variables below
# pylint: disable-msg=W0612
node, dest, ping_outputs = test_outputs
sent, received, rttmin, rttavg, rttmax, rttdev = ping_outputs
self.assertEqual( sent, received )
# pylint: enable-msg=W0612
for rttval in [rttmin, rttavg, rttmax]:
# Multiply delay by 4 to cover there & back on two links
self.assertWithinTolerance( rttval, DELAY_MS * 4.0,
DELAY_TOLERANCE)
def testLinkLoss( self ):
"Verify that we see packet drops with a high configured loss rate."
LOSS_PERCENT = 99
REPS = 1
lopts = { 'loss': LOSS_PERCENT, 'use_htb': True }
mn = Mininet( topo=SingleSwitchOptionsTopo( n=N, lopts=lopts ),
host=CPULimitedHost, link=TCLink )
# Drops are probabilistic, but the chance of no dropped packets is
# 1 in 100 million with 4 hops for a link w/99% loss.
dropped_total = 0
mn.start()
for _ in range(REPS):
dropped_total += mn.ping(timeout='1')
mn.stop()
self.assertTrue(dropped_total > 0)
def testMostOptions( self ):
"Verify topology creation with most link options and CPU limits."
lopts = { 'bw': 10, 'delay': '5ms', 'use_htb': True }
hopts = { 'cpu': 0.5 / N }
self.runOptionsTopoTest( N, hopts=hopts, lopts=lopts )
if __name__ == '__main__':
setLogLevel( 'warning' )
unittest.main()
+26 -26
View File
@@ -34,7 +34,7 @@ class Topo(object):
self.lopts = {} if lopts is None else lopts
self.ports = {} # ports[src][dst] is port on src that connects to dst
def add_node(self, name, **opts):
def addNode(self, name, **opts):
"""Add Node to graph.
name: name
opts: node options
@@ -43,40 +43,40 @@ class Topo(object):
self.node_info[name] = opts
return name
def add_host(self, name, **opts):
def addHost(self, name, **opts):
"""Convenience method: Add host to graph.
name: host name
opts: host options
returns: host name"""
if not opts and self.hopts:
opts = self.hopts
return self.add_node(name, **opts)
return self.addNode(name, **opts)
def add_switch(self, name, **opts):
def addSwitch(self, name, **opts):
"""Convenience method: Add switch to graph.
name: switch name
opts: switch options
returns: switch name"""
if not opts and self.sopts:
opts = self.sopts
result = self.add_node(name, is_switch=True, **opts)
result = self.addNode(name, isSwitch=True, **opts)
return result
def add_link(self, node1, node2, port1=None, port2=None,
**opts):
def addLink(self, node1, node2, port1=None, port2=None,
**opts):
"""node1, node2: nodes to link together
port1, port2: ports (optional)
opts: link options (optional)
returns: link info key"""
if not opts and self.lopts:
opts = self.lopts
self.add_port(node1, node2, port1, port2)
self.addPort(node1, node2, port1, port2)
key = tuple(self.sorted([node1, node2]))
self.link_info[key] = opts
self.g.add_edge(*key)
return key
def add_port(self, src, dst, sport=None, dport=None):
def addPort(self, src, dst, sport=None, dport=None):
'''Generate port mapping for new edge.
@param src source switch name
@param dst destination switch name
@@ -84,8 +84,8 @@ class Topo(object):
self.ports.setdefault(src, {})
self.ports.setdefault(dst, {})
# New port: number of outlinks + base
src_base = 1 if self.is_switch(src) else 0
dst_base = 1 if self.is_switch(dst) else 0
src_base = 1 if self.isSwitch(src) else 0
dst_base = 1 if self.isSwitch(dst) else 0
if sport is None:
sport = len(self.ports[src]) + src_base
if dport is None:
@@ -100,24 +100,24 @@ class Topo(object):
else:
return self.g.nodes()
def is_switch(self, n):
def isSwitch(self, n):
'''Returns true if node is a switch.'''
info = self.node_info[n]
return info and info.get('is_switch', False)
return info and info.get('isSwitch', False)
def switches(self, sort=True):
'''Return switches.
sort: sort switches alphabetically
@return dpids list of dpids
'''
return [n for n in self.nodes(sort) if self.is_switch(n)]
return [n for n in self.nodes(sort) if self.isSwitch(n)]
def hosts(self, sort=True):
'''Return hosts.
sort: sort hosts alphabetically
@return dpids list of dpids
'''
return [n for n in self.nodes(sort) if not self.is_switch(n)]
return [n for n in self.nodes(sort) if not self.isSwitch(n)]
def links(self, sort=True):
'''Return links.
@@ -180,10 +180,10 @@ class SingleSwitchTopo(Topo):
self.k = k
switch = self.add_switch('s1')
switch = self.addSwitch('s1')
for h in irange(1, k):
host = self.add_host('h%s' % h)
self.add_link(host, switch)
host = self.addHost('h%s' % h)
self.addLink(host, switch)
class SingleSwitchReversedTopo(Topo):
@@ -201,11 +201,11 @@ class SingleSwitchReversedTopo(Topo):
'''
super(SingleSwitchReversedTopo, self).__init__(**opts)
self.k = k
switch = self.add_switch('s1')
switch = self.addSwitch('s1')
for h in irange(1, k):
host = self.add_host('h%s' % h)
self.add_link(host, switch,
port1=0, port2=(k - h + 1))
host = self.addHost('h%s' % h)
self.addLink(host, switch,
port1=0, port2=(k - h + 1))
class LinearTopo(Topo):
"Linear topology of k switches, with one host per switch."
@@ -222,9 +222,9 @@ class LinearTopo(Topo):
lastSwitch = None
for i in irange(1, k):
host = self.add_host('h%s' % i)
switch = self.add_switch('s%s' % i)
self.add_link( host, switch)
host = self.addHost('h%s' % i)
switch = self.addSwitch('s%s' % i)
self.addLink( host, switch)
if lastSwitch:
self.add_link( switch, lastSwitch)
self.addLink( switch, lastSwitch)
lastSwitch = switch
+3 -3
View File
@@ -19,13 +19,13 @@ class TreeTopo( Topo ):
returns: last node added"""
isSwitch = depth > 0
if isSwitch:
node = self.add_switch( 's%s' % self.switchNum )
node = self.addSwitch( 's%s' % self.switchNum )
self.switchNum += 1
for _ in range( fanout ):
child = self.addTree( depth - 1, fanout )
self.add_link( node, child )
self.addLink( node, child )
else:
node = self.add_host( 'h%s' % self.hostNum )
node = self.addHost( 'h%s' % self.hostNum )
self.hostNum += 1
return node
+61 -41
View File
@@ -1,14 +1,15 @@
"Utility functions for Mininet."
from mininet.log import output, info, error
from mininet.log import output, info, error, warn
from time import sleep
from resource import setrlimit, RLIMIT_NPROC, RLIMIT_NOFILE
from select import poll, POLLIN
from select import poll, POLLIN, POLLHUP
from subprocess import call, check_call, Popen, PIPE, STDOUT
import re
from fcntl import fcntl, F_GETFL, F_SETFL
from os import O_NONBLOCK
import os
# Command execution support
@@ -46,7 +47,7 @@ def oldQuietRun( *cmd ):
break
out += data
popen.poll()
if popen.returncode != None:
if popen.returncode is not None:
break
return out
@@ -170,27 +171,35 @@ def retry( retries, delaySecs, fn, *args, **keywords ):
error( "*** gave up after %i retries\n" % tries )
exit( 1 )
def moveIntfNoRetry( intf, node, printError=False ):
def moveIntfNoRetry( intf, dstNode, srcNode=None, printError=False ):
"""Move interface to node, without retrying.
intf: string, interface
node: Node object
printError: if true, print error"""
cmd = 'ip link set ' + intf + ' netns ' + repr( node.pid )
quietRun( cmd )
links = node.cmd( 'ip link show' )
dstNode: destination Node
srcNode: source Node or None (default) for root ns
printError: if true, print error"""
intf = str( intf )
cmd = 'ip link set %s netns %s' % ( intf, dstNode.pid )
if srcNode:
srcNode.cmd( cmd )
else:
quietRun( cmd )
links = dstNode.cmd( 'ip link show' )
if not ( ' %s:' % intf ) in links:
if printError:
error( '*** Error: moveIntf: ' + intf +
' not successfully moved to ' + node.name + '\n' )
' not successfully moved to ' + dstNode.name + '\n' )
return False
return True
def moveIntf( intf, node, printError=False, retries=3, delaySecs=0.001 ):
def moveIntf( intf, dstNode, srcNode=None, printError=False,
retries=3, delaySecs=0.001 ):
"""Move interface to node, retrying on failure.
intf: string, interface
node: Node object
dstNode: destination Node
srcNode: source Node or None (default) for root ns
printError: if true, print error"""
retry( retries, delaySecs, moveIntfNoRetry, intf, node, printError )
retry( retries, delaySecs, moveIntfNoRetry, intf, dstNode,
srcNode=srcNode, printError=printError )
# Support for dumping network
@@ -223,7 +232,7 @@ def dumpNetConnections( net ):
def _colonHex( val, bytecount ):
"""Generate colon-hex string.
val: input as unsigned int
bytescount: number of bytes to convert
bytecount: number of bytes to convert
returns: chStr colon-hex string"""
pieces = []
for i in range( bytecount - 1, -1, -1 ):
@@ -241,9 +250,8 @@ def macColonHex( mac ):
def ipStr( ip ):
"""Generate IP address string from an unsigned int.
ip: unsigned int of form w << 24 | x << 16 | y << 8 | z
returns: ip address string w.x.y.z, or 10.x.y.z if w==0"""
returns: ip address string w.x.y.z"""
w = ( ip >> 24 ) & 0xff
w = 10 if w == 0 else w
x = ( ip >> 16 ) & 0xff
y = ( ip >> 8 ) & 0xff
z = ip & 0xff
@@ -252,7 +260,7 @@ def ipStr( ip ):
def ipNum( w, x, y, z ):
"""Generate unsigned int from components of IP address
returns: w << 24 | x << 16 | y << 8 | z"""
return ( w << 24 ) | ( x << 16 ) | ( y << 8 ) | z
return ( w << 24 ) | ( x << 16 ) | ( y << 8 ) | z
def ipAdd( i, prefixLen=8, ipBaseNum=0x0a000000 ):
"""Return IP address string from ints
@@ -260,10 +268,10 @@ def ipAdd( i, prefixLen=8, ipBaseNum=0x0a000000 ):
prefixLen: optional IP prefix length
ipBaseNum: option base IP address as int
returns IP address as string"""
# Ugly but functional
assert i < ( 1 << ( 32 - prefixLen ) )
mask = 0xffffffff ^ ( ( 1 << prefixLen ) - 1 )
ipnum = i + ( ipBaseNum & mask )
imax = 0xffffffff >> prefixLen
assert i <= imax
mask = 0xffffffff ^ imax
ipnum = ( ipBaseNum & mask ) + i
return ipStr( ipnum )
def ipParse( ip ):
@@ -325,27 +333,24 @@ def pmonitor(popens, timeoutms=500, readline=True,
# Use non-blocking reads
flags = fcntl( fd, F_GETFL )
fcntl( fd, F_SETFL, flags | O_NONBLOCK )
while True:
while popens:
fds = poller.poll( timeoutms )
if fds:
for fd, _event in fds:
for fd, event in fds:
host = fdToHost[ fd ]
popen = popens[ host ]
if readline:
# Attempt to read a line of output
# This blocks until we receive a newline!
line = popen.stdout.readline()
else:
line = popen.stdout.read( readmax )
yield host, line
if event & POLLIN:
if readline:
# Attempt to read a line of output
# This blocks until we receive a newline!
line = popen.stdout.readline()
else:
line = popen.stdout.read( readmax )
yield host, line
# Check for EOF
if not line:
popen.poll()
if popen.returncode is not None:
poller.unregister( fd )
del popens[ host ]
if not popens:
return
elif event & POLLHUP:
poller.unregister( fd )
del popens[ host ]
else:
yield None, ''
@@ -361,7 +366,8 @@ def mountCgroups():
mounts = quietRun( 'mount' )
cgdir = '/sys/fs/cgroup'
csdir = cgdir + '/cpuset'
if 'cgroups on %s' % cgdir not in mounts:
if ('cgroup on %s' % cgdir not in mounts and
'cgroups on %s' % cgdir not in mounts):
raise Exception( "cgroups not mounted on " + cgdir )
if 'cpuset on %s' % csdir not in mounts:
errRun( 'mkdir -p ' + csdir )
@@ -395,10 +401,14 @@ def irange(start, end):
def custom( cls, **params ):
"Returns customized constructor for class cls."
# Note: we may wish to see if we can use functools.partial() here
# and in customConstructor
def customized( *args, **kwargs):
"Customized constructor"
kwargs = kwargs.copy()
kwargs.update( params )
return cls( *args, **kwargs )
customized.__name__ = 'custom(%s,%s)' % ( cls, params )
return customized
def splitArgs( argstr ):
@@ -419,7 +429,6 @@ def splitArgs( argstr ):
def customConstructor( constructors, argStr ):
"""Return custom constructor based on argStr
The args and key/val pairs in argsStr will be automatically applied
when the generated constructor is later used.
"""
@@ -428,10 +437,11 @@ def customConstructor( constructors, argStr ):
if not constructor:
raise Exception( "error: %s is unknown - please specify one of %s" %
( cname, constructors.keys() ) )
( cname, constructors.keys() ) )
def customized( name, *args, **params ):
"Customized constructor, useful for Node, Link, and other classes"
params = params.copy()
params.update( kwargs )
if not newargs:
return constructor( name, *args, **params )
@@ -440,14 +450,24 @@ def customConstructor( constructors, argStr ):
constructor, args, newargs ) )
return constructor( name, *newargs, **params )
customized.__name__ = 'customConstructor(%s)' % argStr
return customized
def buildTopo( topos, topoStr ):
"""Create topology from string with format (object, arg1, arg2,...).
input topos is a dict of topo names to constructors, possibly w/args.
"""
topo, args, kwargs = splitArgs( topoStr )
if topo not in topos:
raise Exception( 'Invalid topo name %s' % topo )
return topos[ topo ]( *args, **kwargs )
def ensureRoot():
"""Ensure that we are running as root.
Probably we should only sudo when needed as per Big Switch's patch.
"""
if os.getuid() != 0:
print "*** Mininet must run as root."
exit( 1 )
return
+24 -12
View File
@@ -23,24 +23,30 @@
#include <limits.h>
#include <sched.h>
#if !defined(VERSION)
#define VERSION "(devel)"
#endif
void usage(char *name)
{
printf("Execution utility for Mininet.\n"
"usage: %s [-cdnp] [-a pid] [-g group] [-r rtprio] cmd args...\n"
"-c: close all file descriptors except stdin/out/error\n"
"-d: detach from tty by calling setsid()\n"
"-n: run in new network namespace\n"
"-p: print ^A + pid\n"
"-a pid: attach to pid's network namespace\n"
"-g group: add to cgroup\n"
"-r rtprio: run with SCHED_RR (usually requires -g)\n",
printf("Execution utility for Mininet\n\n"
"Usage: %s [-cdnp] [-a pid] [-g group] [-r rtprio] cmd args...\n\n"
"Options:\n"
" -c: close all file descriptors except stdin/out/error\n"
" -d: detach from tty by calling setsid()\n"
" -n: run in new network namespace\n"
" -p: print ^A + pid\n"
" -a pid: attach to pid's network namespace\n"
" -g group: add to cgroup\n"
" -r rtprio: run with SCHED_RR (usually requires -g)\n"
" -v: print version\n",
name);
}
int setns(int fd, int nstype)
{
return syscall(308, fd, nstype);
return syscall(__NR_setns, fd, nstype);
}
/* Validate alphanumeric path foo1/bar2/baz */
@@ -92,7 +98,7 @@ int main(int argc, char *argv[])
int nsid;
int pid;
static struct sched_param sp;
while ((c = getopt(argc, argv, "+cdnpa:g:r:")) != -1)
while ((c = getopt(argc, argv, "+cdnpa:g:r:vh")) != -1)
switch(c) {
case 'c':
/* close file descriptors except stdin/out/error */
@@ -152,9 +158,15 @@ int main(int argc, char *argv[])
return 1;
}
break;
case 'v':
printf("%s\n", VERSION);
exit(0);
case 'h':
usage(argv[0]);
exit(0);
default:
usage(argv[0]);
break;
exit(1);
}
if (optind < argc) {
+15 -7
View File
@@ -5,29 +5,37 @@
from setuptools import setup, find_packages
from os.path import join
# Get version number from source tree
import sys
sys.path.append( '.' )
from mininet.net import VERSION
scripts = [ join( 'bin', filename ) for filename in [ 'mn' ] ]
modname = distname = 'mininet'
setup(
name=distname,
version='0.0.0',
version=VERSION,
description='Process-based OpenFlow emulator',
author='Bob Lantz',
author_email='rlantz@cs.stanford.edu',
packages=find_packages(exclude='test'),
long_description="""
Insert longer description here.
""",
Mininet is a network emulator which uses lightweight
virtualization to create virtual networks for rapid
prototyping of Software-Defined Network (SDN) designs
using OpenFlow. http://openflow.org/mininet
""",
classifiers=[
"License :: OSI Approved :: GNU General Public License (GPL)",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Developers",
"Topic :: Internet",
],
keywords='networking protocol Internet OpenFlow',
license='unspecified',
keywords='networking emulator protocol Internet OpenFlow SDN',
license='BSD',
install_requires=[
'setuptools',
'networkx'
+155 -46
View File
@@ -5,7 +5,7 @@
# Fail on error
set -e
# Fail on unset var usage
set -o nounset
@@ -33,7 +33,7 @@ if [ "$DIST" = "Ubuntu" ] || [ "$DIST" = "Debian" ]; then
fi
if ! which bc &> /dev/null; then
$install bc
fi
fi
fi
if which lsb_release &> /dev/null; then
DIST=`lsb_release -is`
@@ -97,11 +97,11 @@ function kernel {
if ! test -e /boot/initrd.img-${KERNEL_NAME}; then
sudo update-initramfs -c -k ${KERNEL_NAME}
fi
# Ensure /boot/grub/menu.lst boots with initrd image:
sudo update-grub
# The default should be the new kernel. Otherwise, you may need to modify
# The default should be the new kernel. Otherwise, you may need to modify
# /boot/grub/menu.lst to set the default to the entry corresponding to the
# kernel you just installed.
fi
@@ -122,21 +122,24 @@ function kernel_clean {
# Install Mininet deps
function mn_deps {
echo "Installing Mininet dependencies"
$install gcc make screen psmisc xterm ssh iperf iproute \
python-setuptools python-networkx cgroup-bin ethtool
$install gcc make socat psmisc xterm ssh iperf iproute telnet \
python-setuptools python-networkx cgroup-bin ethtool help2man \
pyflakes pylint pep8
if [ "$DIST" = "Ubuntu" ] && [ "$RELEASE" = "10.04" ]; then
echo "Upgrading networkx to avoid deprecation warning"
sudo easy_install --upgrade networkx
fi
# Add sysctl parameters as noted in the INSTALL file to increase kernel
# Add sysctl parameters as noted in the INSTALL file to increase kernel
# limits to support larger setups:
sudo su -c "cat $HOME/mininet/util/sysctl_addon >> /etc/sysctl.conf"
if ! grep Mininet /etc/sysctl.conf; then
echo "Adding Mininet sysctl settings"
sudo su -c "cat $HOME/mininet/util/sysctl_addon >> /etc/sysctl.conf"
fi
# Load new sysctl settings:
sudo sysctl -p
echo "Installing Mininet core"
pushd ~/mininet
sudo make install
@@ -152,7 +155,7 @@ function of {
echo "Installing OpenFlow reference implementation..."
cd ~/
$install git-core autoconf automake autotools-dev pkg-config \
make gcc libtool libc6-dev
make gcc libtool libc6-dev
git clone git://openflowswitch.org/openflow.git
cd ~/openflow
@@ -164,25 +167,44 @@ function of {
./configure
make
sudo make install
cd ~
}
# Remove avahi-daemon, which may cause unwanted discovery packets to be
# sent during tests, near link status changes:
$remove avahi-daemon
function of13 {
echo "Installing OpenFlow 1.3 soft switch implementation..."
cd ~/
$install git-core autoconf automake autotools-dev pkg-config \
make gcc g++ libtool libc6-dev cmake libpcap-dev libxerces-c2-dev \
unzip libpcre3-dev flex bison libboost-dev
# Disable IPv6. Add to /etc/modprobe.d/blacklist:
if [ "$DIST" = "Ubuntu" ]; then
BLACKLIST=/etc/modprobe.d/blacklist.conf
else
BLACKLIST=/etc/modprobe.d/blacklist
if [ ! -d "ofsoftswitch13" ]; then
git clone https://github.com/CPqD/ofsoftswitch13.git
fi
sudo sh -c "echo 'blacklist net-pf-10\nblacklist ipv6' >> $BLACKLIST"
# Install netbee
wget -nc http://www.nbee.org/download/nbeesrc-12-05-16.zip
unzip nbeesrc-12-05-16.zip
cd ~/nbeesrc/src
cmake .
make
cd ~/
sudo cp nbeesrc/bin/libn*.so /usr/local/lib
sudo ldconfig
sudo cp -R nbeesrc/include/ /usr/
# Resume the install:
cd ~/ofsoftswitch13
./boot.sh
./configure
make
sudo make install
cd ~
}
function wireshark {
echo "Installing Wireshark dissector..."
sudo apt-get install -y wireshark libgtk2.0-dev
sudo apt-get install -y wireshark tshark libgtk2.0-dev
if [ "$DIST" = "Ubuntu" ] && [ "$RELEASE" != "10.04" ]; then
# Install newer version
@@ -254,7 +276,7 @@ function ovs {
ovspresent=1
fi
# Switch can run on its own, but
# Switch can run on its own, but
# Mininet should control the controller
if [ -e /etc/init.d/openvswitch-controller ]; then
if sudo service openvswitch-controller stop; then
@@ -285,7 +307,7 @@ function ovs {
fi
else
$install git
fi
fi
# Install OVS from release
cd ~/
@@ -339,7 +361,7 @@ function nox {
if [ "$DIST" = "Debian" ]; then
$install libboost1.35-dev
elif [ "$DIST" = "Ubuntu" ]; then
$install python-dev libboost-dev
$install python-dev libboost-dev
$install libboost-filesystem-dev
$install libboost-test-dev
fi
@@ -348,9 +370,11 @@ function nox {
# Fetch NOX destiny
cd ~/
git clone git://noxrepo.org/nox noxcore
git clone https://github.com/noxrepo/nox-classic.git noxcore
cd noxcore
git checkout -b destiny remotes/origin/destiny
if ! git checkout -b destiny remotes/origin/destiny ; then
echo "Did not check out a new destiny branch - assuming current branch is destiny"
fi
# Apply patches
git checkout -b tutorial-destiny
@@ -375,6 +399,47 @@ function nox {
#./nox_core -v -i ptcp:
}
# Install NOX Classic/Zaku for OpenFlow 1.3
function nox13 {
echo "Installing NOX w/tutorial files..."
# Install NOX deps:
$install autoconf automake g++ libtool python python-twisted \
swig libssl-dev make
if [ "$DIST" = "Debian" ]; then
$install libboost1.35-dev
elif [ "$DIST" = "Ubuntu" ]; then
$install python-dev libboost-dev
$install libboost-filesystem-dev
$install libboost-test-dev
fi
# Fetch NOX destiny
cd ~/
git clone https://github.com/CPqD/nox13oflib.git
cd nox13oflib
# Build
./boot.sh
mkdir build
cd build
../configure
make -j3
#make check
# To verify this install:
#cd ~/nox13oflib/build/src
#./nox_core -v -i ptcp:
}
# "Install" POX
function pox {
echo "Installing POX into $HOME/pox..."
cd ~
git clone https://github.com/noxrepo/pox.git
}
# Install OFtest
function oftest {
echo "Installing oftest..."
@@ -384,16 +449,13 @@ function oftest {
# Install oftest:
cd ~/
git clone git://openflow.org/oftest
cd oftest
cd tools/munger
sudo make install
git clone git://github.com/floodlight/oftest
}
# Install cbench
function cbench {
echo "Installing cbench..."
$install libsnmp-dev libpcap-dev libconfig-dev
cd ~/
git clone git://openflow.org/oflops.git
@@ -406,14 +468,45 @@ function cbench {
}
function other {
echo "Doing other setup tasks..."
echo "Doing other Mininet VM setup tasks..."
# Remove avahi-daemon, which may cause unwanted discovery packets to be
# sent during tests, near link status changes:
echo "Removing avahi-daemon"
$remove avahi-daemon
# was: Disable IPv6. Add to /etc/modprobe.d/blacklist:
#echo "Attempting to disable IPv6"
#if [ "$DIST" = "Ubuntu" ]; then
# BLACKLIST=/etc/modprobe.d/blacklist.conf
#else
# BLACKLIST=/etc/modprobe.d/blacklist
#fi
#sudo sh -c "echo 'blacklist net-pf-10\nblacklist ipv6' >> $BLACKLIST"
# Disable IPv6
if ! grep 'disable IPv6' /etc/sysctl.conf; then
echo 'Disabling IPv6'
echo '
# Mininet: disable IPv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1' | sudo tee -a /etc/sysctl.conf > /dev/null
fi
# Disabling IPv6 breaks X11 forwarding via ssh
line='AddressFamily inet'
file='/etc/ssh/sshd_config'
echo "Adding $line to $file"
if ! grep "$line" $file > /dev/null; then
echo "$line" | sudo tee -a $file > /dev/null
fi
# Enable command auto completion using sudo; modify ~/.bashrc:
sed -i -e 's|# for examples$|&\ncomplete -cf sudo|' ~/.bashrc
# Install tcpdump and tshark, cmd-line packet dump tools. Also install gitk,
# Install tcpdump, cmd-line packet dump tool. Also install gitk,
# a graphical git history viewer.
$install tcpdump tshark gitk
$install tcpdump gitk
# Install common text editors
$install vim nano emacs
@@ -456,7 +549,9 @@ function all {
of
wireshark
ovs
nox
# NOX-classic is deprecated, but you can install it manually if desired.
# nox
pox
oftest
cbench
other
@@ -493,11 +588,11 @@ function vm_clean {
}
function usage {
printf 'Usage: %s [-acdfhkmntvxy]\n\n' $(basename $0) >&2
printf '\nUsage: %s [-abcdfhkmnprtvwx03]\n\n' $(basename $0) >&2
printf 'This install script attempts to install useful packages\n' >&2
printf 'for Mininet. It should (hopefully) work on Ubuntu 10.04, 11.10\n' >&2
printf 'and Debian 5.0 (Lenny). If you run into trouble, try\n' >&2
printf 'for Mininet. It should (hopefully) work on Ubuntu 11.10+\n' >&2
printf 'If you run into trouble, try\n' >&2
printf 'installing one thing at a time, and looking at the \n' >&2
printf 'specific installation function in this script.\n\n' >&2
@@ -505,43 +600,57 @@ function usage {
printf -- ' -a: (default) install (A)ll packages - good luck!\n' >&2
printf -- ' -b: install controller (B)enchmark (oflops)\n' >&2
printf -- ' -c: (C)lean up after kernel install\n' >&2
printf -- ' -d: (D)elete some sensitive files from a VM image\n' >&2
printf -- ' -d: (D)elete some sensitive files from a VM image\n' >&2
printf -- ' -f: install open(F)low\n' >&2
printf -- ' -h: print this (H)elp message\n' >&2
printf -- ' -k: install new (K)ernel\n' >&2
printf -- ' -m: install Open vSwitch kernel (M)odule from source dir\n' >&2
printf -- ' -n: install mini(N)et dependencies + core files\n' >&2
printf -- ' -p: install (P)OX OpenFlow Controller\n' >&2
printf -- ' -r: remove existing Open vSwitch packages\n' >&2
printf -- ' -t: install o(T)her stuff\n' >&2
printf -- ' -v: install open (V)switch\n' >&2
printf -- ' -w: install OpenFlow (w)ireshark dissector\n' >&2
printf -- ' -x: install NO(X) OpenFlow controller\n' >&2
printf -- ' -y: install (A)ll packages\n' >&2
printf -- ' -x: install NO(X) Classic OpenFlow controller\n' >&2
printf -- ' -0: (default) -0[fx] installs OpenFlow 1.0 versions\n' >&2
printf -- ' -3: -3[fx] installs OpenFlow 1.3 versions\n' >&2
exit 2
}
OF_VERSION=1.0
if [ $# -eq 0 ]
then
all
else
while getopts 'abcdfhkmnrtvwx' OPTION
while getopts 'abcdfhkmnprtvwx03' OPTION
do
case $OPTION in
a) all;;
b) cbench;;
c) kernel_clean;;
d) vm_clean;;
f) of;;
f) case $OF_VERSION in
1.0) of;;
1.3) of13;;
*) echo "Invalid OpenFlow version $OF_VERSION";;
esac;;
h) usage;;
k) kernel;;
m) modprobe;;
n) mn_deps;;
p) pox;;
r) remove_ovs;;
t) other;;
v) ovs;;
w) wireshark;;
x) nox;;
x) case $OF_VERSION in
1.0) nox;;
1.3) nox13;;
*) echo "Invalid OpenFlow version $OF_VERSION";;
esac;;
0) OF_VERSION=1.0;;
3) OF_VERSION=1.3;;
?) usage;;
esac
done
Executable
+26
View File
@@ -0,0 +1,26 @@
#!/bin/bash
# Attach to a Mininet host and run a command
if [ -z $1 ]; then
echo "usage: $0 host cmd [args...]"
exit 1
else
host=$1
fi
if [ -z $2 ]; then
cmd='bash'
else
shift
cmd=$*
fi
# We could do this in this script, and we may want to eventually,
# but for now we'll use mnexec to attach to the host's cgroup
cgroup=/sys/fs/cgroup/cpu/$host
if [ -d "$cgroup" ]; then
cg="mnexec -g $host"
fi
exec sudo ip netns exec $host $cg $cmd
+1
View File
@@ -15,3 +15,4 @@ net.ipv4.neigh.default.gc_thresh3 = 16384
# Mininet: increase routing table size
net.ipv4.route.max_size=32768
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/python
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "grep -or 'Mininet \w\.\w\.\w\w*' *", shell=True )
error = False
for line in lines.split( '\n' ):
if line and 'Binary' not in line:
fname, fversion = line.split( ':' )
if version != fversion:
print "%s: incorrect version '%s' (should be '%s')" % (
fname, fversion, version )
error = True
if error:
exit( 1 )
Regular → Executable
+14 -10
View File
@@ -1,13 +1,10 @@
#!/bin/bash
# This script is intended to install Mininet into
# a brand-new Ubuntu (10.04 or 11.10) virtual machine,
# a brand-new Ubuntu virtual machine,
# to create a fully usable "tutorial" VM.
set -e
sudo sh -c 'cat >> /etc/sudoers' <<EOF
openflow ALL=NOPASSWD: ALL
EOF
echo `whoami` ALL=NOPASSWD: ALL | sudo tee -a /etc/sudoers
sudo sed -i -e 's/Default/#Default/' /etc/sudoers
sudo sed -i -e 's/ubuntu/mininet-vm/' /etc/hostname
sudo sed -i -e 's/ubuntu/mininet-vm/g' /etc/hosts
@@ -17,16 +14,23 @@ sudo update-grub
sudo sed -i -e 's/us.archive.ubuntu.com/mirrors.kernel.org/' \
/etc/apt/sources.list
sudo apt-get update
# Clean up vmware easy install junk if present
if [ -e /etc/issue.backup ]; then
sudo mv /etc/issue.backup /etc/issue
fi
if [ -e /etc/rc.local.backup ]; then
sudo mv /etc/rc.local.backup /etc/rc.local
fi
# Install Mininet
sudo apt-get -y install git-core openssh-server
git clone git://github.com/mininet/mininet
cd mininet
# Check out branch for cs244
git checkout -b cs244 origin/class/cs244
cd
time mininet/util/install.sh
if ! grep NOX_CORE_DIR .bashrc; then
echo "export NOX_CORE_DIR=~/noxcore/build/src/" >> .bashrc
fi
# Ignoring this since NOX classic is deprecated
#if ! grep NOX_CORE_DIR .bashrc; then
# echo "export NOX_CORE_DIR=~/noxcore/build/src/" >> .bashrc
#fi
echo <<EOF
You may need to reboot and then:
sudo dpkg-reconfigure openvswitch-datapath-dkms