diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..cef5b1c --- /dev/null +++ b/.coveragerc @@ -0,0 +1,26 @@ +# .coveragerc to control coverage.py +[run] +branch = True + +[report] +# Regexes for lines to exclude from consideration +exclude_lines = + # Have to re-enable the standard pragma + pragma: no cover + + # Don't complain about missing debug-only code: + def __repr__ + if self\.debug + + # Don't complain if tests don't hit defensive assertion code: + raise AssertionError + raise NotImplementedError + + # Don't complain if non-runnable code isn't run: + if 0: + if __name__ == .__main__.: + +ignore_errors = True + +[html] +directory = coverage_html_report diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..db4561e --- /dev/null +++ b/.gitignore @@ -0,0 +1,54 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.cache +nosetests.xml +coverage.xml + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..de2028b --- /dev/null +++ b/.travis.yml @@ -0,0 +1,15 @@ +language: python +python: + - "2.7" +install: + - pip install -r requirements.txt + - pip install -r tests/requirements.txt +script: + - make pylint + - make test +after_success: + coveralls +notifications: + slack: + rooms: + - sys:yeTvjm0bw1tX6MBWrfkVL5RG#travis diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..8b85306 --- /dev/null +++ b/Makefile @@ -0,0 +1,69 @@ +NAME = $(shell cat bundle.json | sed -n 's/"name"//p' | tr -d '", :') +VERSION = $(shell cat bundle.json | sed -n 's/"version"//p' | tr -d '", :') + +PROJECT = sanji-bundle-$(NAME) + +DISTDIR = $(PROJECT)-$(VERSION) +ARCHIVE = $(CURDIR)/$(DISTDIR).tar.gz + +SANJI_VER ?= 1.0 +INSTALL_DIR = $(DESTDIR)/usr/lib/sanji-$(SANJI_VER)/$(NAME) +STAGING_DIR = $(CURDIR)/staging +PROJECT_STAGING_DIR = $(STAGING_DIR)/$(DISTDIR) + +TARGET_FILES = \ + bundle.json \ + requirements.txt \ + route.py \ + data/route.json.factory \ + ip/__init__.py \ + ip/addr.py \ + ip/route.py +DIST_FILES= \ + $(TARGET_FILES) \ + README.md \ + Makefile \ + tests/requirements.txt \ + tests/test_route.py \ + tests/data/route.json.factory \ + tests/test_e2e/bundle.json \ + tests/test_e2e/view_routes.py +INSTALL_FILES=$(addprefix $(INSTALL_DIR)/,$(TARGET_FILES)) +STAGING_FILES=$(addprefix $(PROJECT_STAGING_DIR)/,$(DIST_FILES)) + + +all: + +clean: + rm -rf $(DISTDIR)*.tar.gz $(STAGING_DIR) + @rm -rf .coverage + @find ./ -name *.pyc | xargs rm -rf + +distclean: clean + +pylint: + flake8 -v --exclude=.git,__init__.py . +test: + nosetests --with-coverage --cover-erase --cover-package=$(NAME) -v + +dist: $(ARCHIVE) + +$(ARCHIVE): distclean $(STAGING_FILES) + @mkdir -p $(STAGING_DIR) + cd $(STAGING_DIR) && \ + tar zcf $@ $(DISTDIR) + +$(PROJECT_STAGING_DIR)/%: % + @mkdir -p $(dir $@) + @cp -a $< $@ + +install: $(INSTALL_FILES) + +$(INSTALL_DIR)/%: % + @mkdir -p $(dir $@) + @cp -a $< $@ + +uninstall: + -rm $(addprefix $(INSTALL_DIR)/,$(TARGET_FILES)) + +.PHONY: clean dist pylint test diff --git a/build-deb/Makefile b/build-deb/Makefile new file mode 100644 index 0000000..a6fcaae --- /dev/null +++ b/build-deb/Makefile @@ -0,0 +1,46 @@ +PROJ_DIR = $(abspath ..) + +NAME = $(shell cat $(PROJ_DIR)/bundle.json | sed -n 's/"name"//p' | tr -d '", :') +VERSION = $(shell cat $(PROJ_DIR)/bundle.json | sed -n 's/"version"//p' | tr -d '", :') + +PROJECT = sanji-bundle-$(NAME) +DEBVERSION = 1 +DIST ?= unstable + +STAGING_DIR = $(abspath $(PROJECT)-$(VERSION)) +UPSTREAM_ARCHIVE = $(PROJECT)-$(VERSION).tar.gz +UPSTREAM_ORIG_ARCHIVE = $(PROJECT)_$(VERSION).orig.tar.gz + +FILES = \ + $(STAGING_DIR)/debian/changelog \ + $(STAGING_DIR)/debian/compat \ + $(STAGING_DIR)/debian/control \ + $(STAGING_DIR)/debian/copyright \ + $(STAGING_DIR)/debian/docs \ + $(STAGING_DIR)/debian/postinst \ + $(STAGING_DIR)/debian/README \ + $(STAGING_DIR)/debian/rules \ + $(STAGING_DIR)/debian/source/format + +.PHONY: all build + +all: build + +build: extract-upstream $(FILES) + cd $(STAGING_DIR) && \ + dpkg-buildpackage -us -uc -rfakeroot + +$(STAGING_DIR)/debian/%: $(PROJ_DIR)/build-deb/debian/% + mkdir -p $(dir $@) + cp $< $@ + +extract-upstream: + cp -a $(PROJ_DIR)/$(UPSTREAM_ARCHIVE) $(UPSTREAM_ORIG_ARCHIVE) + tar zxf $(UPSTREAM_ORIG_ARCHIVE) + +changelog: + dch -v $(VERSION)-$(DEBVERSION) -D $(DIST) -M -u low \ + --release-heuristic log + +clean: + rm -rf $(STAGING_DIR) $(PROJECT)-* $(PROJECT)_* diff --git a/build-deb/debian/README b/build-deb/debian/README new file mode 100644 index 0000000..e8881f1 --- /dev/null +++ b/build-deb/debian/README @@ -0,0 +1,6 @@ +The Debian Package route +---------------------------- + +Comments regarding the Package + + -- Aeluin Chen Fri, 12 Jun 2015 16:48:57 +0800 diff --git a/build-deb/debian/changelog b/build-deb/debian/changelog new file mode 100644 index 0000000..29fbc9f --- /dev/null +++ b/build-deb/debian/changelog @@ -0,0 +1,29 @@ +sanji-bundle-route (0.9.6-1) unstable; urgency=low + + * Add timeout to `grep` for preventing input without EOF. + + -- Aeluin Chen Thu, 05 Nov 2015 11:22:22 +0800 + +sanji-bundle-route (0.9.5-1) unstable; urgency=low + + * Bugfix: default gateway cannot be updated at some scenario. + + -- Aeluin Chen Fri, 23 Oct 2015 10:20:25 +0800 + +sanji-bundle-route (0.9.4-2) unstable; urgency=low + + * Update building policy for debian package. + + -- Aeluin Chen Fri, 12 Jun 2015 16:57:12 +0800 + +sanji-bundle-route (0.9.4-1) unstable; urgency=low + + * Use netifaces to speedup query time. + + -- Aeluin Chen Fri, 05 Jun 2015 18:32:58 +0800 + +sanji-bundle-route (0.9.0) unstable; urgency=low + + * Initial Release. + + -- Aeluin Chen Fri, 05 Jun 2015 18:27:19 +0800 diff --git a/build-deb/debian/compat b/build-deb/debian/compat new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/build-deb/debian/compat @@ -0,0 +1 @@ +8 diff --git a/build-deb/debian/control b/build-deb/debian/control new file mode 100644 index 0000000..786f5b0 --- /dev/null +++ b/build-deb/debian/control @@ -0,0 +1,18 @@ +Source: sanji-bundle-route +Priority: extra +Maintainer: Aeluin Chen +Build-Depends: debhelper (>= 8.0.0) +Build-Depends-Indep: python (>= 2.7) +Standards-Version: 3.9.3 +Section: libs +Homepage: http://www.moxa.com +#Vcs-Git: +#Vcs-Browser: +X-Python-Version: >= 2.5 + +Package: sanji-bundle-route +Section: libs +Architecture: all +Depends: ${shlibs:Depends}, ${misc:Depends}, python2.7, python-pip +Description: Handle the routing table + diff --git a/build-deb/debian/copyright b/build-deb/debian/copyright new file mode 100644 index 0000000..d6a9326 --- /dev/null +++ b/build-deb/debian/copyright @@ -0,0 +1,340 @@ +GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. + diff --git a/build-deb/debian/docs b/build-deb/debian/docs new file mode 100644 index 0000000..b43bf86 --- /dev/null +++ b/build-deb/debian/docs @@ -0,0 +1 @@ +README.md diff --git a/build-deb/debian/postinst b/build-deb/debian/postinst new file mode 100644 index 0000000..d032fb3 --- /dev/null +++ b/build-deb/debian/postinst @@ -0,0 +1,43 @@ +#!/bin/sh +# postinst script for route +# +# see: dh_installdeb(1) + +set -e + +# summary of how this script can be called: +# * `configure' +# * `abort-upgrade' +# * `abort-remove' `in-favour' +# +# * `abort-remove' +# * `abort-deconfigure' `in-favour' +# `removing' +# +# for details, see http://www.debian.org/doc/debian-policy/ or +# the debian-policy package + + +case "$1" in + configure) + pip install -r /tmp/sanji-bundle-route-packages/requirements.txt || \ + pip install --no-index --find-links file:/tmp/sanji-bundle-route-packages \ + -r /tmp/sanji-bundle-route-packages/requirements.txt + rm -rf /tmp/sanji-bundle-route-packages + ;; + + abort-upgrade|abort-remove|abort-deconfigure) + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +# dh_installdeb will replace this with shell code automatically +# generated by other debhelper scripts. + +#DEBHELPER# + +exit 0 diff --git a/build-deb/debian/rules b/build-deb/debian/rules new file mode 100755 index 0000000..895eafd --- /dev/null +++ b/build-deb/debian/rules @@ -0,0 +1,27 @@ +#!/usr/bin/make -f +# -*- makefile -*- +# Sample debian/rules that uses debhelper. +# This file was originally written by Joey Hess and Craig Small. +# As a special exception, when this file is copied by dh-make into a +# dh-make output file, you may use that output file without restriction. +# This special exception was added by Craig Small in version 0.37 of dh-make. + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + +DEB_PACKAGE := $(strip $(shell dh_listpackages -i 2>/dev/null || dh_listpackages -i)) +DEB_DESTDIR := $(CURDIR)/debian/$(DEB_PACKAGE) + +DEB_PYPDIR := $(DEB_DESTDIR)/tmp/$(DEB_PACKAGE)-packages + + +%: + dh $@ + +override_dh_auto_test: + +override_dh_auto_install: + dh_auto_install + mkdir -p $(DEB_PYPDIR) + cp -a requirements.txt $(DEB_PYPDIR) + pip install -r requirements.txt --download $(DEB_PYPDIR) diff --git a/build-deb/debian/source/format b/build-deb/debian/source/format new file mode 100644 index 0000000..163aaf8 --- /dev/null +++ b/build-deb/debian/source/format @@ -0,0 +1 @@ +3.0 (quilt) diff --git a/bundle.json b/bundle.json new file mode 100644 index 0000000..af0dcdb --- /dev/null +++ b/bundle.json @@ -0,0 +1,35 @@ +{ + "name": "route", + "version": "0.9.6", + "author": "Aeluin Chen", + "email": "aeluin.chen@moxa.com", + "description": "Handle the routing table", + "license": "MOXA", + "main": "route.py", + "argument": "", + "priority": 19, + "concurrent": false, + "hook": [], + "dependencies": {}, + "repository": "", + "role": "model", + "ttl": 10, + "resources": [ + { + "role": "view", + "resource": "/network/interface" + }, + { + "methods": ["get"], + "resource": "/network/routes/interfaces" + }, + { + "methods": ["get","put"], + "resource": "/network/routes/db" + }, + { + "methods": ["get","put"], + "resource": "/network/routes/default" + } + ] +} diff --git a/data/route.json.factory b/data/route.json.factory new file mode 100644 index 0000000..f0f970f --- /dev/null +++ b/data/route.json.factory @@ -0,0 +1,3 @@ +{ + "default": "eth0" +} diff --git a/ip/__init__.py b/ip/__init__.py new file mode 100644 index 0000000..83dc5af --- /dev/null +++ b/ip/__init__.py @@ -0,0 +1,2 @@ +import addr +import route diff --git a/ip/addr.py b/ip/addr.py new file mode 100755 index 0000000..9684e9c --- /dev/null +++ b/ip/addr.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- +import sh +import netifaces +import ipcalc +import copy +import logging + +# https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-net + +# Used python modules: +# setuptools +# https://pypi.python.org/pypi/setuptools +# +# ipcalc.py +# https://github.com/tehmaze/ipcalc/ +# +# sh.py +# https://pypi.python.org/pypi/sh + + +_logger = logging.getLogger("sanji.ethernet.ip.addr") + + +def interfaces(): + """List all interfaces. + + Returns: + A list of interface names. For example: + + ["eth0", "eth1", "wlan0"] + + Raises: + FIXME + """ + # ifaces=$(ip a show | grep -Eo "[0-9]: wlan[0-9]" | sed "s/.*wlan//g") + # ifaces=$(ip a show | grep -Eo '[0-9]: eth[0-9]' | awk '{print $2}') + try: + ifaces = netifaces.interfaces() + ifaces = [x for x in ifaces if not + (x.startswith("lo") or x.startswith("mon."))] + return ifaces + except Exception, e: + _logger.info("Cannot get interfaces: %s" % e) + raise e + + +def ifaddresses(iface): + """Retrieve the detail information for an interface. + + Args: + iface: interface name. + + Returns: + A dict format data will be return. For example: + + {"mac": "", + "link": 1, + "inet": [{ + "ip": "", + "netmask": "", + "subnet": "", + "broadcast": ""}]} + + Raises: + ValueError: You must specify a valid interface name. + """ + full = netifaces.ifaddresses(iface) + + info = {} + try: + info["mac"] = full[netifaces.AF_LINK][0]['addr'] + except: + info["mac"] = "" + + try: + info["link"] = open("/sys/class/net/%s/operstate" % iface).read() + if "down" == info["link"][:-1]: + info["link"] = 0 + else: + info["link"] = open("/sys/class/net/%s/carrier" % iface).read() + info["link"] = int(info["link"][:-1]) # convert to int + except: + info["link"] = 0 + + info["inet"] = [] + if netifaces.AF_INET not in full: + return info + + for ip in full[netifaces.AF_INET]: + item = copy.deepcopy(ip) + if "addr" in item: + item["ip"] = item.pop("addr") + net = ipcalc.Network("%s/%s" % (item["ip"], item["netmask"])) + item["subnet"] = str(net.network()) + info["inet"].append(item) + + return info + + +def ifupdown(iface, up): + """Set an interface to up or down status. + + Args: + iface: interface name. + up: status for the interface, True for up and False for down. + + Raises: + ValueError + """ + if not up: + try: + output = sh.awk( + sh.grep( + sh.grep(sh.ps("ax"), iface, _timeout=5), + "dhclient", _timeout=5), + "{print $1}") + dhclients = output().split() + for dhclient in dhclients: + sh.kill(dhclient) + except: + pass + try: + sh.ip("link", "set", iface, "up" if up else "down") + except: + raise ValueError("Cannot update the link status for \"%s\"." + % iface) + + +def ifconfig(iface, dhcpc, ip="", netmask="24", gateway="", script=None): + """Set the interface to static IP or dynamic IP (by dhcpclient). + + Args: + iface: interface name. + dhcpc: True for using dynamic IP and False for static. + ip: IP address for static IP + netmask: + gateway: + + Raises: + ValueError + """ + # TODO(aeluin) catch the exception? + # Check if interface exist + try: + sh.ip("addr", "show", iface) + except sh.ErrorReturnCode_1: + raise ValueError("Device \"%s\" does not exist." % iface) + except: + raise ValueError("Unknown error for \"%s\"." % iface) + + # Disable the dhcp client and flush interface + try: + dhclients = sh.awk( + sh.grep( + sh.grep(sh.ps("ax"), iface, _timeout=5), + "dhclient", _timeout=5), + "{print $1}") + dhclients = dhclients.split() + if 1 == len(dhclients): + sh.dhclient("-x", iface) + elif len(dhclients) > 1: + for dhclient in dhclients: + sh.kill(dhclient) + except: + pass + + try: + sh.ip("-4", "addr", "flush", "label", iface) + except: + raise ValueError("Unknown error for \"%s\"." % iface) + + if dhcpc: + if script: + sh.dhclient("-sf", script, iface) + else: + sh.dhclient(iface) + else: + if ip: + net = ipcalc.Network("%s/%s" % (ip, netmask)) + sh.ip("addr", "add", "%s/%s" % (ip, net.netmask()), "broadcast", + net.broadcast(), "dev", iface) + + +if __name__ == "__main__": + print interfaces() + + # ifconfig("eth0", True) + # time.sleep(10) + # ifconfig("eth1", False, "192.168.31.36") + eth0 = ifaddresses("eth0") + print eth0 + print "link: %d" % eth0["link"] + for ip in eth0["inet"]: + print "ip: %s" % ip["ip"] + print "netmask: %s" % ip["netmask"] + if "subnet" in ip: + print "subnet: %s" % ip["subnet"] + + ''' + ifupdown("eth1", True) + # ifconfig("eth1", True) + ifconfig("eth1", False, "192.168.31.39") + + eth1 = ifaddresses("eth1") + print "link: %d" % eth1["link"] + for ip in eth1["inet"]: + print "ip: %s" % ip["ip"] + print "netmask: %s" % ip["netmask"] + if "subnet" in ip: + print "subnet: %s" % ip["subnet"] + ''' diff --git a/ip/route.py b/ip/route.py new file mode 100755 index 0000000..a095e58 --- /dev/null +++ b/ip/route.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- +import sh + + +def show(): + """List all routing rules. + + Returns: + A list of dict for each routing rule. + + [ + {"dest": "", + "src": "", + "dev": ""}, + {"default": "", + "dev": ""} + ] + """ + rules = [] + routes = sh.ip("route", "show") + for route in routes: + rule = dict() + route = route.split() + if "default" == route[0]: + rule["default"] = "" + if "via" in route: + rule["default"] = route[route.index("via")+1] + rule["dev"] = route[route.index("dev")+1] + else: + rule["dest"] = route[0] + rule["dev"] = route[route.index("dev")+1] + if "src" in route: + src = route.index("src") + elif "via" in route: + src = route.index("via") + else: + src = -1 + if -1 != src: + rule["src"] = route[src+1] + rules.append(rule) + return rules + + +def add(dest, dev="", src=""): + """Add a routing rule. + + Args: + dest: destination for the routing rule, default for default route. + dev: routing device, could be empty + src: source for the routing rule, fill "gateway" if dest is "default" + + Raises: + FIXME + """ + if "" == src: + sh.ip("route", "add", dest, "dev", dev) + elif "default" == dest: + if dev: + sh.ip("route", "add", dest, "dev", dev, "via", src) + else: + sh.ip("route", "add", dest, "via", src) + else: + sh.ip("route", "add", dest, "dev", dev, "proto", "kernel", "scope", + "link", "src", src) + + +def delete(network="default"): + """Delete a routing rule. + + Args: + network: destination of the routing rule to be delete + + Raises: + FIXME + """ + try: + sh.ip("route", "del", network) + except sh.ErrorReturnCode_2: + pass + + +if __name__ == "__main__": + print show() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..dd55615 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +paho-mqtt==1.1 +sh +ipcalc +netifaces +sanji diff --git a/route.py b/route.py new file mode 100755 index 0000000..12eb0ef --- /dev/null +++ b/route.py @@ -0,0 +1,343 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- + +import os +import netifaces +import logging +from time import sleep +from sanji.core import Sanji +from sanji.core import Route +from sanji.connection.mqtt import Mqtt +from sanji.model_initiator import ModelInitiator +from voluptuous import Schema +from voluptuous import Any, Extra, Optional + +import ip + + +_logger = logging.getLogger("sanji.route") + + +class IPRoute(Sanji): + """ + A model to handle IP Route configuration. + + Attributes: + model: database with json format. + """ + + update_interval = 60 + + def init(self, *args, **kwargs): + try: # pragma: no cover + self.bundle_env = kwargs["bundle_env"] + except KeyError: + self.bundle_env = os.getenv("BUNDLE_ENV", "debug") + + path_root = os.path.abspath(os.path.dirname(__file__)) + if self.bundle_env == "debug": # pragma: no cover + path_root = "%s/tests" % path_root + + self.interfaces = [] + try: + self.load(path_root) + except: + self.stop() + raise IOError("Cannot load any configuration.") + + def run(self): + while True: + try: + self.try_update_default(self.model.db) + except: + pass + sleep(self.update_interval) + + def load(self, path): + """ + Load the configuration. If configuration is not installed yet, + initialise them with default value. + + Args: + path: Path for the bundle, the configuration should be located + under "data" directory. + """ + self.model = ModelInitiator("route", path, backup_interval=-1) + if self.model.db is None: + raise IOError("Cannot load any configuration.") + self.save() + + def save(self): + """ + Save and backup the configuration. + """ + self.model.save_db() + self.model.backup_db() + + def list_interfaces(self): + """ + List available interfaces. + """ + # retrieve all interfaces + try: + ifaces = ip.addr.interfaces() + except: + return {} + + # list connected interfaces + data = [] + for iface in ifaces: + try: + iface_info = ip.addr.ifaddresses(iface) + except: + continue + if 1 == iface_info["link"]: + data.append(iface) + return data + + def get_default(self): + """ + Retrieve the default gateway + + Return: + default: dict format with "interface" and/or "gateway" + """ + gws = netifaces.gateways() + default = {} + if gws['default'] != {} and netifaces.AF_INET in gws['default']: + gw = gws['default'][netifaces.AF_INET] + else: + return default + + default["gateway"] = gw[0] + default["interface"] = gw[1] + return default + + def update_dns(self, interface): + """ + Update DNS according to default gateway's interface. + + Args: + default: interface name + """ + res = self.publish.put("/network/dns", data={"interface": interface}) + if res.code != 200: + raise RuntimeWarning(res.data["message"]) + + def update_default(self, default): + """ + Update default gateway. If updated failed, should recover to previous + one. + + Args: + default: dict format with "interface" required and "gateway" + optional. + """ + # delete the default gateway + if not default or ("interface" not in default and + "gateway" not in default): + try: + ip.route.delete("default") + except Exception as e: + raise e + + # change the default gateway + # FIXME: only "gateway" without interface is also available + # FIXME: add "secondary" default route rule + else: + try: + ip.route.delete("default") + if "gateway" in default and "interface" in default: + ip.route.add("default", default["interface"], + default["gateway"]) + elif "interface" in default: + ip.route.add("default", default["interface"]) + elif "gateway" in default: + ip.route.add("default", "", default["gateway"]) + else: + raise ValueError("Invalid default route.") + + # update DNS + if "interface" in default: + self.update_dns(default["interface"]) + except Exception as e: + raise e + + def try_update_default(self, routes): + """ + Try to update the default gateway. + + Args: + routes: dict format including default gateway interface and + secondary default gateway interface. + For example: + { + "default": "wwan0", + "secondary": "eth0" + } + """ + ifaces = self.list_interfaces() + if not ifaces: + raise ValueError("Interfaces should be UP.") + + default = {} + if routes["default"] in ifaces: + default["interface"] = routes["default"] + elif routes["secondary"] in ifaces: + default["interface"] = routes["secondary"] + else: + return self.update_default({}) + + # find gateway by interface + for iface in self.interfaces: + if iface["interface"] == default["interface"]: + default = iface + break + + current = self.get_default() + try: + if current["interface"] != default["interface"] or \ + current["gateway"] != default["gateway"]: + self.update_default(default) + except: + self.update_default(default) + + def update_router(self, interface): + """ + Save the interface name with its gateway and update the default + gateway if needed. + + If gateway is not specified, use the previous value. Only delete the + gateway when gateway attribute is empty. + + Args: + interface: dict format with interface "name" and/or "gateway". + """ + # update the router information + for iface in self.interfaces: + if iface["interface"] == interface["name"]: + if "gateway" in interface: + iface["gateway"] = interface["gateway"] + break + else: + iface = {} + iface["interface"] = interface["name"] + if "gateway" in interface: + iface["gateway"] = interface["gateway"] + self.interfaces.append(iface) + + # check if the default gateway need to be modified + if iface["interface"] == self.model.db["default"]: + try: + self.try_update_default(self.model.db) + except: + pass + + def set_default(self, default, is_default=True): + """ + Update default / secondary gateway. + """ + if is_default: + def_type = "default" + else: + def_type = "secondary" + + # save the setting + # if no interface but has gateway, do not update anything + if "interface" in default: + self.model.db[def_type] = default["interface"] + elif "gateway" not in default: + self.model.db[def_type] = "" + self.save() + + try: + if is_default: + self.update_default(default) + except Exception as e: + # try database if failed + try: + self.try_update_default(self.model.db) + except: + _logger.info("Failed to recover the default gateway.") + error = "Update default gateway failed: %s" % e + _logger.error(error) + raise IOError(error) + + @Route(methods="get", resource="/network/routes/interfaces") + def _get_interfaces(self, message, response): + """ + Get available interfaces. + """ + return response(data=self.list_interfaces()) + + @Route(methods="get", resource="/network/routes/default") + def _get_default(self, message, response): + """ + Get default gateway. + """ + return response(data=self.get_default()) + + put_default_schema = Schema({ + Optional("interface"): Any(str, unicode), + Extra: object}) + + @Route(methods="put", resource="/network/routes/default") + def _put_default(self, message, response, schema=put_default_schema): + """ + Update the default gateway, delete default gateway if data is None or + empty. + """ + try: + self.set_default(message.data) + except Exception as e: + return response(code=404, + data={"message": e}) + return response(data=self.get_default()) + + @Route(methods="put", resource="/network/routes/secondary") + def _put_secondary(self, message, response, schema=put_default_schema): + """ + Update the secondary default gateway, delete default gateway if data + is None or empty. + """ + try: + self.set_default(message.data, False) + except Exception as e: + return response(code=404, + data={"message": e}) + return response(data=message.data) + + def set_router_db(self, message, response): + """ + Update router database batch or by interface. + """ + if type(message.data) is list: + for iface in message.data: + self.update_router(iface) + return response(data=self.interfaces) + elif type(message.data) is dict: + self.update_router(message.data) + return response(data=message.data) + return response(code=400, + data={"message": "Wrong type of router database."}) + + @Route(methods="put", resource="/network/routes/db") + def _set_router_db(self, message, response): + return self.set_router_db(message, response) + + @Route(methods="get", resource="/network/routes/db") + def _get_router_db(self, message, response): + return response(data=self.interfaces) + + @Route(methods="put", resource="/network/interface") + def _event_router_db(self, message): + self.update_router(message.data) + + +if __name__ == "__main__": + FORMAT = "%(asctime)s - %(levelname)s - %(lineno)s - %(message)s" + logging.basicConfig(level=0, format=FORMAT) + _logger = logging.getLogger("sanji.route") + + route = IPRoute(connection=Mqtt()) + route.start() diff --git a/tests/data/route.json.factory b/tests/data/route.json.factory new file mode 100644 index 0000000..f0f970f --- /dev/null +++ b/tests/data/route.json.factory @@ -0,0 +1,3 @@ +{ + "default": "eth0" +} diff --git a/tests/requirements.txt b/tests/requirements.txt new file mode 100644 index 0000000..7d0b1d0 --- /dev/null +++ b/tests/requirements.txt @@ -0,0 +1,2 @@ +flake8 +coveralls diff --git a/tests/test_e2e/bundle.json b/tests/test_e2e/bundle.json new file mode 100644 index 0000000..259708e --- /dev/null +++ b/tests/test_e2e/bundle.json @@ -0,0 +1,24 @@ +{ + "name": "view-routes", + "version": "1.0", + "author": "Aeluin Chen", + "email": "aeluin.chen@moxa.com", + "description": "A test view for routes bundle", + "license": "MOXA", + "main": "view_routes.py", + "argument": "", + "priority": 20, + "hook": [], + "dependencies": {}, + "repository": "", + "role": "view", + "ttl": 10, + "resources": [ + { + "resource": "/network/routes" + }, + { + "resource": "/network/routers" + } + ] +} diff --git a/tests/test_e2e/view_routes.py b/tests/test_e2e/view_routes.py new file mode 100755 index 0000000..a6a21e8 --- /dev/null +++ b/tests/test_e2e/view_routes.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- + +import logging +from time import sleep + +from sanji.core import Sanji +from sanji.connection.mqtt import Mqtt + + +REQ_RESOURCE = '/network/routes' +MANUAL_TEST = 0 + + +class View(Sanji): + + # This function will be executed after registered. + def run(self): + + for count in xrange(0, 100, 1): + # Normal CRUD Operation + # self.publish.[get, put, delete, post](...) + # One-to-One Messaging + # self.publish.direct.[get, put, delete, post](...) + # (if block=True return Message, else return mqtt mid number) + # Agruments + # (resource[, data=None, block=True, timeout=60]) + + # case 1: test GET available interfaces + resource = '%s/interfaces' % REQ_RESOURCE + print 'GET %s' % resource + res = self.publish.get(resource) + if res.code != 200: + print 'GET should be supported, code 200 is expected' + print res.to_json() + self.stop() + if 1 == MANUAL_TEST: + var = raw_input("Please enter any key to continue...") + + # case 2: test GET current default gateway setting + sleep(2) + resource = '%s/default' % REQ_RESOURCE + print 'GET %s' % resource + res = self.publish.get(resource) + if res.code != 200: + print 'GET should be supported, code 200 is expected' + print res.to_json() + self.stop() + if 1 == MANUAL_TEST: + var = raw_input("Please enter any key to continue...") + + # case 3: test PUT with no data (remove default gateway) + sleep(2) + resource = '%s/default' % REQ_RESOURCE + print 'PUT %s' % resource + res = self.publish.put(resource, None) + if res.code != 400: + print 'data is required, code 400 is expected' + print res.to_json() + self.stop() + if 1 == MANUAL_TEST: + var = raw_input("Please enter any key to continue...") + + # case 4: test PUT with empty data (remove default gateway) + sleep(2) + resource = '%s/default' % REQ_RESOURCE + print 'PUT %s' % resource + res = self.publish.put(resource, data={}) + if res.code != 200: + print 'data is not required, code 200 is expected' + print res.to_json() + self.stop() + if 1 == MANUAL_TEST: + var = raw_input("Please enter any key to continue...") + + # case 5: test PUT to update default gateway + sleep(2) + resource = '%s/default' % REQ_RESOURCE + print 'PUT %s' % resource + res = self.publish.put(resource, data={"interface": "eth0"}) + if res.code != 200: + print 'PUT with interface is supported, code 200 is expected' + print res.to_json() + self.stop() + if 1 == MANUAL_TEST: + var = raw_input("Please enter any key to continue...") + + # case 6: test PUT to update default gateway + sleep(2) + resource = '%s/default' % REQ_RESOURCE + print 'PUT %s' % resource + res = self.publish.put( + resource, + data={"interface": "eth0", "gateway": "192.168.3.254"}) + if res.code != 200: + print 'PUT with interface is supported, code 200 is expected' + print res.to_json() + self.stop() + if 1 == MANUAL_TEST: + var = raw_input("Please enter any key to continue...") + + # case 7: test PUT to update interface router + sleep(2) + resource = '/network/routers' + print 'PUT %s' % resource + res = self.publish.put( + resource, + data={"name": "eth1", "gateway": "192.168.4.254"}) + if res.code != 200: + print 'PUT with interface is supported, code 200 is expected' + print res.to_json() + self.stop() + if 1 == MANUAL_TEST: + var = raw_input("Please enter any key to continue...") + + # case 8: test PUT to update interface router + sleep(2) + resource = '/network/routers' + print 'PUT %s' % resource + res = self.publish.put( + resource, + data={"name": "eth0", "gateway": "192.168.31.254"}) + if res.code != 200: + print 'PUT with interface is supported, code 200 is expected' + print res.to_json() + self.stop() + if 1 == MANUAL_TEST: + print var + + # stop the test view + self.stop() + + +if __name__ == '__main__': + FORMAT = '%(asctime)s - %(levelname)s - %(lineno)s - %(message)s' + logging.basicConfig(level=0, format=FORMAT) + logger = logging.getLogger('IPRoute') + + view = View(connection=Mqtt()) + view.start() diff --git a/tests/test_route.py b/tests/test_route.py new file mode 100644 index 0000000..09504aa --- /dev/null +++ b/tests/test_route.py @@ -0,0 +1,659 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- + + +import os +import sys +import logging +import unittest + +from mock import patch +from mock import Mock +from sanji.connection.mockup import Mockup +from sanji.message import Message + +try: + sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../') + from route import IPRoute +except ImportError as e: + print os.path.dirname(os.path.realpath(__file__)) + '/../' + print sys.path + print e + print "Please check the python PATH for import test module. (%s)" \ + % __file__ + exit(1) + +dirpath = os.path.dirname(os.path.realpath(__file__)) + + +def mock_ip_addr_ifaddresses(iface): + if "eth0" == iface: + return {"mac": "78:ac:c0:c1:a8:fe", + "link": 1, + "inet": [{ + "broadcast": "192.168.31.255", + "ip": "192.168.31.36", + "netmask": "255.255.255.0", + "subnet": "192.168.31.0"}]} + elif "eth1" == iface: + return {"mac": "78:ac:c0:c1:a8:ff", + "link": 0, + "inet": [{ + "broadcast": "192.168.41.255", + "ip": "192.168.41.37", + "netmask": "255.255.255.0", + "subnet": "192.168.41.0"}]} + elif "ppp0" == iface: + return {"mac": "", + "link": 1, + "inet": [{ + "broadcast": "192.168.41.255", + "ip": "192.168.41.37", + "netmask": "255.255.255.0", + "subnet": "192.168.41.0"}]} + else: + raise ValueError + + +class TestIPRouteClass(unittest.TestCase): + + @patch.object(IPRoute, 'update_default') + def setUp(self, mock_update_default): + self.name = "route" + self.bundle = IPRoute(connection=Mockup()) + + def tearDown(self): + self.bundle.stop() + self.bundle = None + try: + os.remove("%s/data/%s.json" % (dirpath, self.name)) + except OSError: + pass + + try: + os.remove("%s/data/%s.json.backup" % (dirpath, self.name)) + except OSError: + pass + + @patch.object(IPRoute, 'update_default') + def test__init__no_conf(self, mock_update_default): + """ + init: no configuration file + """ + with self.assertRaises(IOError): + with patch("route.ModelInitiator") as mock_modelinit: + mock_modelinit.side_effect = IOError + self.bundle.init() + + def test__load__current_conf(self): + """ + load: load current configuration + """ + self.bundle.load(dirpath) + self.assertEqual("eth0", self.bundle.model.db["default"]) + + def test__load__backup_conf(self): + """ + load: load backup configuration + """ + os.remove("%s/data/%s.json" % (dirpath, self.name)) + self.bundle.load(dirpath) + self.assertEqual("eth0", self.bundle.model.db["default"]) + + def test__load__no_conf(self): + """ + load: cannot load any configuration + """ + with self.assertRaises(Exception): + self.bundle.load("%s/mock" % dirpath) + + def test__save(self): + """ + save + """ + # Already tested in init() + pass + + @patch("route.ip.addr.ifaddresses") + @patch("route.ip.addr.interfaces") + def test__list_interfaces(self, mock_interfaces, mock_ifaddresses): + """ + list_interfaces: list the available interfaces + """ + mock_interfaces.return_value = ["eth0", "eth1", "ppp0"] + mock_ifaddresses.side_effect = mock_ip_addr_ifaddresses + + ifaces = self.bundle.list_interfaces() + self.assertEqual(2, len(ifaces)) + self.assertIn("eth0", ifaces) + self.assertIn("ppp0", ifaces) + + @patch("route.ip.addr.interfaces") + def test__list_interfaces__failed_get_ifaces(self, mock_interfaces): + """ + list_interfaces: failed to list the available interfaces + """ + mock_interfaces.side_effect = IOError + + ifaces = self.bundle.list_interfaces() + self.assertEqual({}, ifaces) + + @patch("route.ip.addr.ifaddresses") + @patch("route.ip.addr.interfaces") + def test__list_interfaces__failed_get_status(self, mock_interfaces, + mock_ifaddresses): + """ + list_interfaces: cannot get some interface's status + """ + def mock_ip_addr_ifaddresses_ppp0_failed(iface): + if "eth0" == iface: + return {"mac": "78:ac:c0:c1:a8:fe", + "link": 1, + "inet": [{ + "broadcast": "192.168.31.255", + "ip": "192.168.31.36", + "netmask": "255.255.255.0", + "subnet": "192.168.31.0"}]} + elif "eth1" == iface: + return {"mac": "78:ac:c0:c1:a8:ff", + "link": 0, + "inet": [{ + "broadcast": "192.168.41.255", + "ip": "192.168.41.37", + "netmask": "255.255.255.0", + "subnet": "192.168.41.0"}]} + else: + raise ValueError + + mock_interfaces.return_value = ["eth0", "eth1", "ppp0"] + mock_ifaddresses.side_effect = mock_ip_addr_ifaddresses_ppp0_failed + + ifaces = self.bundle.list_interfaces() + self.assertEqual(1, len(ifaces)) + self.assertIn("eth0", ifaces) + + @patch("route.netifaces.gateways") + def test__get_default(self, mock_gateways): + """ + get_default: get current default gateway + """ + mock_gateways.return_value = { + 'default': {2: ('192.168.3.254', 'eth0')}, + 2: [('192.168.3.254', 'eth0', True)]} + + default = self.bundle.get_default() + self.assertEqual("eth0", default["interface"]) + self.assertEqual("192.168.3.254", default["gateway"]) + + @patch("route.netifaces.gateways") + def test__get_default__no_default(self, mock_gateways): + """ + get_default: no current default gateway + """ + mock_gateways.return_value = {'default': {}} + + default = self.bundle.get_default() + self.assertEqual({}, default) + + @patch.object(IPRoute, "update_dns") + @patch("route.ip.route.delete") + @patch("route.ip.route.add") + def test__update_default(self, mock_ip_route_add, mock_ip_route_del, + mock_update_dns): + """ + update_default: update the default gateway with both interface and + gateway + """ + default = {} + default["interface"] = "eth1" + default["gateway"] = "192.168.4.254" + + try: + self.bundle.update_default(default) + except: + self.fail("update_default raised exception unexpectedly!") + + @patch.object(IPRoute, "update_dns") + @patch("route.ip.route.delete") + @patch("route.ip.route.add") + def test__update_default__with_iface(self, mock_ip_route_add, + mock_ip_route_del, mock_update_dns): + """ + update_default: update the default gateway with interface + """ + default = {} + default["interface"] = "eth1" + + try: + self.bundle.update_default(default) + except: + self.fail("update_default raised exception unexpectedly!") + + @patch("route.ip.route.delete") + @patch("route.ip.route.add") + def test__update_default__with_gateway(self, mock_ip_route_add, + mock_ip_route_del): + """ + update_default: update the default gateway with gateway + """ + default = {} + default["gateway"] = "192.168.4.254" + + try: + self.bundle.update_default(default) + except: + self.fail("update_default raised exception unexpectedly!") + + @patch("route.ip.route.delete") + @patch("route.ip.route.add") + def test__update_default__failed(self, mock_ip_route_add, + mock_ip_route_del): + """ + update_default: failed to update the default gateway + """ + mock_ip_route_add.side_effect = IOError + default = {} + default["gateway"] = "192.168.4.254" + + with self.assertRaises(IOError): + self.bundle.update_default(default) + + @patch("route.ip.route.delete") + def test__update_default__delete(self, mock_ip_route_del): + """ + update_default: delete the default gateway + """ + default = {} + + try: + self.bundle.update_default(default) + except: + self.fail("update_default raised exception unexpectedly!") + + @patch("route.ip.route.delete") + def test__update_default__delete_failed(self, mock_ip_route_del): + """ + update_default: failed delete the default gateway + """ + mock_ip_route_del.side_effect = IOError + default = {} + + with self.assertRaises(IOError): + self.bundle.update_default(default) + + @patch.object(IPRoute, "list_interfaces") + def test__try_update_default__no_iface(self, mock_list_interfaces): + """ + try_update_default: no interfaces + """ + mock_list_interfaces.return_value = [] + + with self.assertRaises(ValueError): + self.bundle.try_update_default(self.bundle.model.db) + + @patch.object(IPRoute, "update_default") + @patch.object(IPRoute, "get_default") + @patch.object(IPRoute, "list_interfaces") + def test__try_update_default__by_default( + self, + mock_list_interfaces, + mock_get_default, + mock_update_default): + """ + try_update_default: update by default + """ + mock_list_interfaces.return_value = ["eth0", "eth1", "wwan0"] + mock_get_default.return_value = { + "interface": "eth1", + "gateway": "192.168.4.254" + } + + self.bundle.interfaces = [ + { + "interface": "eth0", + "gateway": "192.168.3.254" + }, + { + "interface": "eth1", + "gateway": "192.168.4.254" + } + ] + + routes = {} + routes["default"] = "eth0" + routes["secondary"] = "eth1" + + self.bundle.try_update_default(routes) + mock_update_default.assert_called_once_with(self.bundle.interfaces[0]) + + @patch.object(IPRoute, "update_default") + @patch.object(IPRoute, "get_default") + @patch.object(IPRoute, "list_interfaces") + def test__try_update_default__by_default_with_current_value( + self, + mock_list_interfaces, + mock_get_default, + mock_update_default): + """ + try_update_default: update by default (same with current setting) + """ + mock_list_interfaces.return_value = ["eth0", "eth1", "wwan0"] + mock_get_default.return_value = { + "interface": "eth0", + "gateway": "192.168.3.254" + } + + self.bundle.interfaces = [ + { + "interface": "eth0", + "gateway": "192.168.3.254" + }, + { + "interface": "eth1", + "gateway": "192.168.4.254" + } + ] + + routes = {} + routes["default"] = "eth0" + routes["secondary"] = "eth1" + + self.bundle.try_update_default(routes) + self.assertTrue(not mock_update_default.called) + + @patch.object(IPRoute, "update_default") + @patch.object(IPRoute, "get_default") + @patch.object(IPRoute, "list_interfaces") + def test__try_update_default__by_secondary( + self, + mock_list_interfaces, + mock_get_default, + mock_update_default): + """ + try_update_default: update by secondary + """ + # arrange + mock_list_interfaces.return_value = ["eth1", "wwan0"] + mock_get_default.return_value = { + "interface": "wwan0", + "gateway": "192.168.4.254" + } + + self.bundle.interfaces = [ + { + "interface": "eth0", + "gateway": "192.168.3.254" + }, + { + "interface": "eth1", + "gateway": "192.168.4.254" + }, + { + "interface": "wwan0", + "gateway": "192.168.5.254" + } + ] + + routes = {} + routes["default"] = "eth0" + routes["secondary"] = "wwan0" + + # act + self.bundle.try_update_default(routes) + + # assert + mock_update_default.assert_called_once_with(self.bundle.interfaces[2]) + + @patch.object(IPRoute, "update_default") + @patch.object(IPRoute, "list_interfaces") + def test__try_update_default__delete( + self, + mock_list_interfaces, + mock_update_default): + """ + try_update_default: delete default gateway + """ + mock_list_interfaces.return_value = ["eth1"] + + routes = {} + routes["default"] = "wwan0" + routes["secondary"] = "eth0" + + self.bundle.try_update_default(routes) + mock_update_default.assert_called_once_with({}) + + @patch.object(IPRoute, 'update_default') + def test__update_router__update_interface( + self, mock_update_default): + """ + update_router: update router info by interface + """ + # arrange + self.bundle.interfaces = [ + {"interface": "eth0", "gateway": "192.168.31.254"}, + {"interface": "eth1", "gateway": "192.168.4.254"}] + iface = {"name": "eth1", "gateway": "192.168.41.254"} + + # act + self.bundle.update_router(iface) + + # assert + self.assertEqual(2, len(self.bundle.interfaces)) + self.assertIn({"interface": "eth0", "gateway": "192.168.31.254"}, + self.bundle.interfaces) + self.assertIn({"interface": "eth1", "gateway": "192.168.41.254"}, + self.bundle.interfaces) + + @patch.object(IPRoute, 'update_default') + def test__update_router__add_interface_with_gateway( + self, mock_update_default): + """ + update_router: add a new interface with gateway + """ + # arrange + self.bundle.interfaces = [ + {"interface": "eth0", "gateway": "192.168.31.254"}] + iface = {"name": "eth1", "gateway": "192.168.41.254"} + + # act + self.bundle.update_router(iface) + + # assert + self.assertEqual(2, len(self.bundle.interfaces)) + self.assertIn({"interface": "eth0", "gateway": "192.168.31.254"}, + self.bundle.interfaces) + self.assertIn({"interface": "eth1", "gateway": "192.168.41.254"}, + self.bundle.interfaces) + + @patch.object(IPRoute, 'update_default') + def test__update_router__add_interface_without_gateway( + self, mock_update_default): + """ + update_router: add a new interface without gateway + """ + # arrange + self.bundle.interfaces = [ + {"interface": "eth0", "gateway": "192.168.31.254"}] + iface = {"name": "eth1"} + + # act + self.bundle.update_router(iface) + + # assert + self.assertEqual(2, len(self.bundle.interfaces)) + self.assertIn({"interface": "eth0", "gateway": "192.168.31.254"}, + self.bundle.interfaces) + self.assertIn({"interface": "eth1"}, + self.bundle.interfaces) + + @patch.object(IPRoute, "get_default") + @patch.object(IPRoute, 'try_update_default') + def test__update_router__update_default( + self, mock_try_update_default, mock_get_default): + """ + update_router: default gateway should also be updated + """ + # arrange + mock_get_default.return_value = { + "interface": "eth0", + "gateway": "192.168.3.254" + } + self.bundle.interfaces = [ + {"interface": "eth0", "gateway": "192.168.3.254"}, + {"interface": "eth1", "gateway": "192.168.4.254"}] + iface = {"name": "eth0", "gateway": "192.168.31.254"} + + # act + self.bundle.update_router(iface) + + # assert + self.assertEqual(2, len(self.bundle.interfaces)) + self.assertIn({"interface": "eth0", "gateway": "192.168.31.254"}, + self.bundle.interfaces) + self.assertIn({"interface": "eth1", "gateway": "192.168.4.254"}, + self.bundle.interfaces) + mock_try_update_default.assert_called_once_with(self.bundle.model.db) + + @patch.object(IPRoute, "update_default") + def test__set_default__default(self, mock_update_default): + """ + set_default: update default gateway + """ + # arrange + self.bundle.model.db["default"] = "eth1" + default = { + "interface": "eth0", + "gateway": "192.168.3.254" + } + + # act + self.bundle.set_default(default) + + # assert + self.assertEqual(self.bundle.model.db, {"default": "eth0"}) + mock_update_default.assert_called_once_with(default) + + @patch.object(IPRoute, "try_update_default") + @patch.object(IPRoute, "update_default") + def test__set_default__update_default_failed( + self, + mock_update_default, + mock_try_update_default): + """ + set_default: update default gateway failed + """ + # arrange + mock_update_default.side_effect = IOError + self.bundle.model.db["default"] = "eth1" + default = { + "interface": "eth0", + "gateway": "192.168.3.254" + } + + # act + with self.assertRaises(IOError): + self.bundle.set_default(default) + + # assert + self.assertEqual(self.bundle.model.db, {"default": "eth0"}) + mock_update_default.assert_called_once_with(default) + mock_try_update_default.assert_called_once_with(self.bundle.model.db) + + @patch.object(IPRoute, "try_update_default") + @patch.object(IPRoute, "update_default") + def test__set_default__update_default_and_recovery_failed( + self, + mock_update_default, + mock_try_update_default): + """ + set_default: update default gateway failed and recovery failed + """ + # arrange + mock_update_default.side_effect = IOError + mock_try_update_default.side_effect = IOError + self.bundle.model.db["default"] = "eth1" + default = { + "interface": "eth0", + "gateway": "192.168.3.254" + } + + # act + with self.assertRaises(IOError): + self.bundle.set_default(default) + + # assert + self.assertEqual(self.bundle.model.db, {"default": "eth0"}) + mock_update_default.assert_called_once_with(default) + mock_try_update_default.assert_called_once_with(self.bundle.model.db) + + def test__set_default__secondary(self): + """ + set_default: update secondary default gateway + """ + # arrange + self.bundle.model.db["default"] = "eth1" + default = { + "interface": "eth0", + "gateway": "192.168.3.254" + } + + # act + self.bundle.set_default(default, False) + + # assert + self.assertEqual(self.bundle.model.db, + {"default": "eth1", "secondary": "eth0"}) + + @patch("route.ip.route.delete") + def test__set_default__clear(self, mock_ip_route_del): + """ + set_default: clear default gateway + """ + # arrange + self.bundle.model.db["default"] = "eth1" + default = {} + + # act + self.bundle.set_default(default) + + # assert + self.assertEqual(self.bundle.model.db, {"default": ""}) + mock_ip_route_del.assert_called_once_with("default") + + @patch.object(IPRoute, "update_default") + def test__set_default__no_change(self, mock_update_default): + """ + set_default: default gateway doesn't change + """ + # arrange + self.bundle.model.db["default"] = "eth1" + default = {"gateway": "192.168.3.254"} + + # act + self.bundle.set_default(default) + + # assert + self.assertEqual(self.bundle.model.db, {"default": "eth1"}) + + @patch.object(IPRoute, "update_default") + def test__set_router_db__add(self, mock_update_default): + """ + set_router_db: add one interface's router info to database + """ + # arrange + iface = {"name": "eth0", "gateway": "192.168.3.127"} + message = Message({"data": iface}) + mock_func = Mock(code=200, data=None) + + # act + self.bundle.set_router_db(message=message, response=mock_func) + + # assert + self.assertEqual(mock_func.call_args_list[0][1]["data"], iface) + + +if __name__ == "__main__": + FORMAT = '%(asctime)s - %(levelname)s - %(lineno)s - %(message)s' + logging.basicConfig(level=20, format=FORMAT) + logger = logging.getLogger('IPRoute Test') + unittest.main()