Doc updates + cleanup

Ticket: CM-2297
Reviewed By:
Testing Done: compile tested

more updates coming ...
This commit is contained in:
Roopa Prabhu 2014-07-17 11:44:36 -07:00
parent 09a304ca24
commit 2c0ad8b338
21 changed files with 1246 additions and 87 deletions

View File

@ -3,6 +3,4 @@
- `ifquery -r` status is success for success case and also for cases where there
is no support for query yet
- setup.py has ifupdown listed in data section instead of scripts: This is because default location for scripts is /usr/bin/. And ifupdown default location is /sbin. With newer versions we can specify --install-scripts directory. This needs to be fixed then.
-
- and more :)

View File

@ -2,7 +2,7 @@ python-ifupdown2
================
This package is a replacement for the debian ifupdown package.
It is completely re-written in python. It maintains the original ifupdown
It is ifupdown re-written in python. It maintains the original ifupdown
pluggable architecture and extends it further.
The python-ifupdown2 package provides the infrastructure for
@ -17,8 +17,8 @@ To make the transition smoother, a python module under
/etc/network/.
It publishes an interface object which is passed to all loadble python
modules (more details about the interface object is available in the
python docs).
modules. For more details on adding a addon module, see the section on
adding python modules.
pluggable python modules:
@ -26,40 +26,53 @@ pluggable python modules:
Unlike original ifupdown, all interface configuration is moved to external
python modules. That includes inet, inet6 and dhcp configurations.
It expects a few things from the pluggable modules:
A set of default modules are provided by the python-ifupdown2-addons deb.
python-ifupdown2 expects a few things from the pluggable modules:
- the module should implement a class by the same name
- the interface object (class iface) and the operation to be performed is
passed to the modules
- the python class should provide a few methods:
- the python addon class should provide a few methods:
- run() : method to configure the interface.
- get_ops() : must return a list of operations it supports.
eg: 'pre-up', 'post-down'
- get_dependent_ifacenames() : must return a list of interfaces the
interface is dependent on. This is used to build the dependency list
for sorting and executing interfaces in parallel.
for sorting and executing interfaces in dependency order.
- if the module supports -r option to ifquery, ie ability to construct the
ifaceobj from running state, it can optionally implement the
get_dependent_ifacenames_running() method, to return the list of
dependent interfaces derived from running state of the interface.
This is different from get_dependent_ifacenames() where the dependent
interfaces are derived from the interfaces config file (provided by the
user).
Example: Address handling module /usr/share/ifupdownaddons/address.py
build
=====
- get source
- install build dependencies:
apt-get install python-stdeb
apt-get install python-docutils
- cd <python-ifupdown2 sourcedir> && ./build.sh
(generates python-ifupdown2-<ver>.deb)
install
=======
install instructions
====================
- remove existing ifupdown package
dpkg -r ifupdown
dpkg -r ifupdown
- download python-ifupdown2*.deb's and install
- or apt-get from testing repo
apt-get install python-ifupdown2
apt-get install python-ifupdown2-addons
- install python-ifupdown2 using `dpkg -i`
- or install from deb
dpkg -i python-ifupdown2-<ver>.deb
dpkg -i python-ifupdown2-addons-<ver>.deb
extra packages to use addional packages:
======================================
To use templates install python-mako (from wheezy):
apt-get install python-mako
To generate dot files install python-gvgen (from wheezy):
apt-get install python-gvgen
- note that python-ifupdown2 requires python-ifupdown2-addons package to
function. And python-ifupdown2-addons deb has an install dependency on
python-ifupdown2

18
TODO
View File

@ -1,20 +1,15 @@
TODO:
====
- support old ifupdown state file /run/network/ifstate. Because some app's seem to use it
- support -i interfaces file
- support for debian ifupdown methods: tunnel, v4tunnel, 6to4, ppp, wvdial, ipv4ll
- support for debian ifupdown ipv6 auto method
- support for debian ifupdown CAN address family
- Compat : support for LOGICAL interfaces
- dry-run improvement: It skips the cache completely. Which means It tells you the commands it would execute if the system is clean. Its not smart enought to say what it will really execute given the state of the system
- included gvgen in the package. Need to check if there are any license issues
- bash completion for options
- Ifquery does not report link status, mainly because it reports only in terms of /etc/network/interfaces attributes. Plan to fix that
- update man-pages with new options. Convert them to rst
- Documentation
- more Documentation
- Priorities for addon modules
- syslog support
- have ability to also run uninstall on interfaces that dont have any config
- ifup hotplug support (basically needs some testing and fixing broken things)
- -q quiet option
@ -25,7 +20,7 @@ TODO:
/etc/network/interfaces
--no-mappings don't run any mappings
--no-scripts don't run any hook scripts
- Fix parallel implementation
- parallel implementation
- Test all original ifupdown options for compatibility
- Test with ifupdown-extra, ifmetric, ifupdown-scripts-zg2
- export other environment variables to bash scripts (for backward compatibility):
@ -39,12 +34,3 @@ TODO:
VERBOSITY indicates whether --verbose was used; set to 1 if so, 0 if not.
PATH the command search path: /usr/local/sbin:/usr/local/bin:
/usr/sbin:/usr/bin:/sbin:/bin
- ifquery -r shows bridge-pathcosts
auto bridge100
iface bridge100
bridge-ports swp13.100 swp14.100
bridge-pathcosts swp13.100=2 swp14.100=2
- Does not purge old addresses

8
build.sh Normal file
View File

@ -0,0 +1,8 @@
#!/bin/bash
TOPDIR=.
${TOPDIR}/scripts/genmanpages.sh ${TOPDIR}/man.rst ${TOPDIR}/man
python setup.py --command-packages=stdeb.command sdist_dsc bdist_deb

153
docs/Makefile Normal file
View File

@ -0,0 +1,153 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ifupdown2.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ifupdown2.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/ifupdown2"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ifupdown2"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

68
docs/source/apiref.rst Normal file
View File

@ -0,0 +1,68 @@
Documentation for the Code
**************************
ifupdownmain -- explicit members
================================
ifupdownmain is the main ifupdown module.
.. automodule:: ifupdownmain
.. autoclass:: ifupdownMain
:members: up, down, reload, query
iface -- explicit members
=========================
iface is the class that represents an ifupdown iface object.
.. automodule:: iface
.. autoclass:: iface
:members: state, status, flags, priv_flags, refcnt, lowerifaces, upperifaces, add_to_upperifaces, get_attr_value, get_attr_value_first, get_attr_value_n, update_config, update_config_with_status, get_config_attr_status, compare, dump_raw, dump, dump_pretty
.. autoclass:: ifaceState
.. autoclass:: ifaceStatus
.. autoclass:: ifaceJsonEncoder
scheduler -- explicit members
=============================
.. automodule:: scheduler
.. autoclass:: ifaceScheduler
:members: sched_ifaces
.. autoclass:: ifaceSchedulerFlags
networkinterfaces -- explicit members
=====================================
.. automodule:: networkinterfaces
.. autoclass:: networkInterfaces
:members: load, subscribe
statemanager -- explicit members
================================
.. automodule:: statemanager
.. autoclass:: pickling
:members: save, save_obj, load
.. autoclass:: stateManager
:members: read_saved_state, save_state
graph -- explicit members
=========================
.. automodule:: graph
.. autoclass:: graph
:members: topological_sort_graphs_all, generate_dots

247
docs/source/conf.py Normal file
View File

@ -0,0 +1,247 @@
# -*- coding: utf-8 -*-
#
# ifupdown2 documentation build configuration file, created by
# sphinx-quickstart on Sun Jul 6 23:49:20 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('/work/monster-03/roopa/cumulus-2.1-ifupdown2/packages/ifupdown2/pkg'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'ifupdown2'
copyright = u'2014, Roopa Prabhu'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'ifupdown2doc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'ifupdown2.tex', u'ifupdown2 Documentation',
u'Roopa Prabhu', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'ifupdown2', u'ifupdown2 Documentation',
[u'Roopa Prabhu'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'ifupdown2', u'ifupdown2 Documentation',
u'Roopa Prabhu', 'ifupdown2', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}

View File

@ -0,0 +1,18 @@
Development Corner
==================
getting started
---------------
Unlike original ifupdown, all interface configuration is moved to external
python modules. That includes inet, inet6 and dhcp configurations.
* if you are looking at fixing bugs or adding new features to the ifupdown2
infrastructure package, pls look at the apiref, documentation and code
for python-ifupdown2
* if you are looking at developing a new module, pls look at writing a addon
module in the python-ifupdown2 documentation
Apiref
------
:doc:`apiref.rst`

View File

@ -0,0 +1,22 @@
Getting Started
===============
Prerequisites
-------------
* python-ifupdown2 is current only tested on a debian release wheezy or greater
* python-ifupdown2 needs python version 2.6 or greater
* build depends on: python-stdeb (for deb builds), python-docutils (for rst2man)
* depends on python-gvgen package for printing interface graphs (this will be made optional soon)
* optional dependency for template engine: python-mako
Building
--------
git clone <ifupdown2 git url>
cd ifupdown2
./build.sh
Installing
----------
install generated python-ifupdown2-<ver>.deb

25
docs/source/index.rst Normal file
View File

@ -0,0 +1,25 @@
.. ifupdown2 documentation master file, created by
sphinx-quickstart on Sun Jul 6 23:49:20 2014.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to ifupdown2's documentation!
=====================================
Contents:
.. toctree::
:maxdepth: 2
intro.rst
gettingstarted.rst
userguide.rst
developmentcorner.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

55
docs/source/intro.rst Normal file
View File

@ -0,0 +1,55 @@
Introduction
============
ifupdown2 is a replacement for the debian network interface
management package ifupdown. It is ifupdown re-written in python. It
maintains the original ifupdown pluggable architecture and extends it further.
It comes as two packages:
* python-ifupdown2
* python-ifupdown2-addons
(Packaging may change in the future)
python-ifupdown2
----------------
The python-ifupdown2 package provides the infrastructure for
parsing /etc/network/interfaces file, loading, scheduling, template parsing,
state management and interface dependency generation of interfaces.
It dynamically loads python modules from /usr/share/ifupdownmodules (provided
by the python-ifupdown2-addons package). To remain compatible with other
packages that depend on ifupdown, it also executes scripts under /etc/network/.
To make the transition smoother, a python module under
/usr/share/ifupdownmodules will override a script by the same name under
/etc/network/.
It publishes an interface object which is passed to all loadble python
modules. For more details on adding a addon module, see the section on
adding python modules.
ifupdown2 module calls all modules for every interface declared in the
/etc/network/interfaces file.
python-ifupdown2-addons
-----------------------
The python-ifupdown2-addons package contains ifupdown2 addon modules.
addon modules are responsible for applying interface configuration.
The modules are installed under /usr/share/ifupdownmodules.
Each module can declare its own set of supported attributes. Each module
is passed the iface object (which is a representation of /etc/network/interfaces
iface entry). Each module is also passed the operation to be performed.
Example modules are /usr/share/ifupdownmodules/address.py,
/usr/share/ifupdownmodules/bridge.py etc
The order in which these modules are invoked is listed in
/var/lib/ifupdownaddons/addons.conf. There is a ifaddon utility in the works
to better manage the module ordering.
For details on how to add a module, see the api reference and development
documentation.

447
docs/source/userguide.rst Normal file
View File

@ -0,0 +1,447 @@
.. index:: ifupdown
.. _ifupdown:
**********
User Guide
**********
Keep the following points in mind before you start configuring interfaces using
``ifupdown2``:
* IPv4 and IPv6 addresses for an interface can be listed in the same ``iface``
section. For examples, see ``/usr/share/doc/python-ifupdown2/examples/``.
* Do not use a legacy interface alias. They are only supported for backward
compatibility with ``ifupdown``. They do get configured, but ``ifquery`` has
problems recognizing them.
* ``ifupdown`` only understands interfaces that were configured using
``ifupdown``. Any interfaces created with a command other than ``ifupdown``
(like ``brctl``) must be de-configured in the same manner.
* Use globs for port lists wherever applicable. Regular expressions work as well,
however regular expressions require all matching interfaces to be present in
the ``interfaces`` file. And declaring all interfaces in the ``interfaces``
file leads to losing all the advantages that built-in interfaces provide.
* Extensions to ``ifquery`` help with validation and debugging.
* By default, ``ifupdown`` is quiet; use the verbose option ``-v`` when you want
to know what is going on when bringing an interface down or up.
Contents
========
* `Commands`_
* `Man Pages`_
* `Configuration Files`_
* `ifupdown Built-in Interfaces`_
* `ifupdown Interface Dependencies`_
* `Configuring IP Addresses`_
* `Specifying User Commands`_
* `Sourcing Interface File Snippets`_
* `Using Globs for Port Lists`_
* `Using Templates`_
* `Using ifquery to Validate and Debug Interface Configurations`_
* `Useful Links`_
Commands
========
* ifdown
* ifquery
* ifreload
* ifup
Man Pages
=========
* man ifdown(8)
* man ifquery(8)
* man ifreload
* man ifup(8)
* man ifupdown-addons-interfaces(5)
* man interfaces(5)
Configuration Files
===================
* /etc/network/interfaces
ifupdown Built-in Interfaces
============================
``ifupdown`` understands VLAN interfaces and physical interfaces that may appear
as dependents. There is no need to list them unless they need the specific
configuration or they need to match a regular expression used in the
``interfaces`` file. Use globs to avoid limitations with regular expressions.
For example, swp1.100 and swp2.100 below do not need an entry in the
``interfaces`` file::
auto br-100
iface br-100
address 10.0.12.2/24
address 2001:dad:beef::3/64
bridge-ports swp1.100 swp2.100
bridge-stp on
ifupdown Interface Dependencies
===============================
``ifupdown`` understands interface dependency relationships. When ``ifup`` and
``ifdown`` are run with all interfaces, they always run with all interfaces
in dependency order. When run with the interface list on the command line, the
default behavior is to not run with dependents. But if there are any built-in
dependents, they will be brought up or down.
To run with dependents when you specify the interface list, use the
``--with-depends`` option. ``--with-depends`` walks through all dependents
in the dependency tree rooted at the interface you specify. Consider the
following example configuration::
auto bond1
iface bond1
address 100.0.0.2/16
bond-slaves swp29 swp30
bond-mode 802.3ad
bond-miimon 100
bond-use-carrier 1
bond-lacp-rate 1
bond-min-links 1
bond-xmit-hash-policy layer3+4
auto bond2
iface bond2
address 100.0.0.5/16
bond-slaves swp31 swp32
bond-mode 802.3ad
bond-miimon 100
bond-use-carrier 1
bond-lacp-rate 1
bond-min-links 1
bond-xmit-hash-policy layer3+4
auto br2001
iface br2001
address 12.0.1.3/24
bridge-ports bond1.2001 bond2.2001
bridge-stp on
Specifying ``ifup --with-depends br2001`` brings up all dependents: bond1.2001,
bond2.2001, bond1, bond2, bond1.2001, bond2.2001, swp29, swp30, swp31, swp32.
Similarly, specifying ``ifdown --with-depends br2001`` brings down all
dependents: bond1.2001, bond2.2001, bond1, bond2, bond1.2001, bond2.2001, swp29,
swp30, swp31, swp32.
.. warning:: ``ifdown`` always deletes logical interfaces after bringing them
down. Use the ``--admin-state`` option if you only want to administratively
bring the interface up or down. In terms of the above example,
``ifdown br2001`` deletes ``br2001``.
To guide you through which interfaces will be brought down and up, use the
``--print-dependency`` option to get the list of dependents.
Use ``ifup --print-dependency=list -a`` to get the dependency list of all
interfaces::
cumulus@switch:~$ sudo ifup --print-dependency=list -a
lo : None
eth0 : None
bond0 : ['swp25', 'swp26']
bond1 : ['swp29', 'swp30']
bond2 : ['swp31', 'swp32']
br0 : ['bond1', 'bond2']
bond1.2000 : ['bond1']
bond2.2000 : ['bond2']
br2000 : ['bond1.2000', 'bond2.2000']
bond1.2001 : ['bond1']
bond2.2001 : ['bond2']
br2001 : ['bond1.2001', 'bond2.2001']
swp40 : None
swp25 : None
swp26 : None
swp29 : None
swp30 : None
swp31 : None
swp32 : None
To print the dependency list of a single interface, use::
cumulus@switch:~$ sudo ifup --print-dependency=list br2001
br2001 : ['bond1.2001', 'bond2.2001']
bond1.2001 : ['bond1']
bond2.2001 : ['bond2']
bond1 : ['swp29', 'swp30']
bond2 : ['swp31', 'swp32']
swp29 : None
swp30 : None
swp31 : None
swp32 : None
To print the dependency information of an interface in ``dot`` format::
cumulus@switch:~$ sudo ifup --print-dependency=dot br2001
/* Generated by GvGen v.0.9 (http://software.inl.fr/trac/wiki/GvGen) */
digraph G {
compound=true;
node1 [label="br2001"];
node2 [label="bond1.2001"];
node3 [label="bond2.2001"];
node4 [label="bond1"];
node5 [label="bond2"];
node6 [label="swp29"];
node7 [label="swp30"];
node8 [label="swp31"];
node9 [label="swp32"];
node1->node2;
node1->node3;
node2->node4;
node3->node5;
node4->node6;
node4->node7;
node5->node8;
node5->node9;
}
You can use ``dot`` to render the graph on an external system where ``dot`` is
installed.
.. image:: images/interfaces.png
To print the dependency information of the entire ``interfaces`` file::
cumulus@switch:~$ sudo ifup --print-dependency=dot -a >interfaces_all.dot
.. image:: images/interfaces_all.png
:width: 800px
.. note: The '--print-dependency' option is available with the ``ifup``,
``ifdown`` and ``ifquery`` commands.
Configuring IP Addresses
========================
In ``/etc/network/interfaces``, list all IP addresses as shown below under the
``iface`` section (see ``man interfaces`` for more information)::
auto swp1
iface swp1
address 12.0.0.1/30
address 12.0.0.2/30
The address method and address family are not mandatory. They default to
``inet``/``inet6`` and ``static`` by default, but ``inet``/``inet6`` **must** be
specified if you need to specify ``dhcp`` or ``loopback``.
You can specify both IPv4 and IPv6 addresses under the same ``iface`` section::
auto swp1
iface swp1
address 12.0.0.1/30
address 12.0.0.2/30
address 2001:dee:eeef:2::1/64
Specifying User Commands
========================
You can specify additional user commands in the ``interfaces`` file. As shown in
the example below, the interface stanzas in ``/etc/network/interfaces`` can have
a command that runs at pre-up, up, post-up, pre-down, down, and post-down::
auto swp1
iface swp1
address 12.0.0.1/30
up /sbin/foo bar
Any valid command can be hooked in the sequencing of bringing an interface up or
down, although commands should be limited in scope to network-related commands
associated with the particular interface.
For example, it wouldn't make sense to install some Debian package on ``ifup``
of swp1, even though that is technically possible. See ``man interfaces`` for
more details.
Sourcing Interface File Snippets
================================
Sourcing interface files helps organize and manage the ``interfaces(5)`` file.
For example::
cumulus@switch:~$ cat /etc/network/interfaces
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto eth0
iface eth0 inet dhcp
source /etc/network/interfaces.d/bond0
The contents of the sourced file used above are::
cumulus@switch:~$ cat /etc/network/interfaces.d/bond0
auto bond0
iface bond0
address 14.0.0.9/30
address 2001:ded:beef:2::1/64
bond-slaves swp25 swp26
bond-mode 802.3ad
bond-miimon 100
bond-use-carrier 1
bond-lacp-rate 1
bond-min-links 1
bond-xmit-hash-policy layer3+4
Using Globs for Port Lists
==========================
Some modules support globs to describe port lists. You can use globs to specify
bridge ports and bond slaves::
auto br0
iface br0
bridge-ports glob swp1-6.100
auto br1
iface br1
bridge-ports glob swp7-9.100 swp11.100 glob swp15-18.100
Using Templates
===============
``ifupdown2`` supports Mako-style templates. For more information see
`www.makotemplates.org <http://www.makotemplates.org/>`_. The Mako template
engine is run over the ``interfaces`` file before parsing.
Use the template to declare cookie-cutter bridges in the ``interfaces`` file::
%for v in [11,12]:
auto vlan${v}
iface vlan${v}
address 10.20.${v}.3/24
bridge-ports glob swp19-20.${v}
bridge-stp on
%endfor
And use it to declare addresses in the ``interfaces`` file::
%for i in [1,12]:
auto swp${i}
iface swp${i}
address 10.20.${i}.3/24
Using ifquery to Validate and Debug Interface Configurations
============================================================
You use ``ifquery`` to print parsed ``interfaces`` file entries.
To use ``ifquery`` to pretty print ``iface`` entries from the ``interfaces``
file, run::
cumulus@switch:~$ sudo ifquery bond0
auto bond0
iface bond0
address 14.0.0.9/30
address 2001:ded:beef:2::1/64
bond-slaves swp25 swp26
bond-mode 802.3ad
bond-miimon 100
bond-use-carrier 1
bond-lacp-rate 1
bond-min-links 1
bond-xmit-hash-policy layer3+4
.. Use ``ifquery -a`` to pretty print all ``iface`` entries from the
``interfaces`` file.
Use ``ifquery --check`` to check the current running state of an interface within
the ``interfaces`` file. It returns exit code ``0`` or ``1`` if the configuration
does not match::
cumulus@switch:~$ sudo ifquery --check bond0
iface bond0
bond-mode 802.3ad (✓)
bond-miimon 100 (✓)
bond-use-carrier 1 (✓)
bond-lacp-rate 1 (✓)
bond-min-links 1 (✓)
bond-xmit-hash-policy layer3+4 (✓)
bond-slaves swp25 swp26 (✓)
address 14.0.0.9/30 (✓)
address 2001:ded:beef:2::1/64 (✓)
.. note:: ``ifquery --check`` is an experimental feature.
.. Use ``ifquery --check -a`` to check all interfaces.
Use ``ifquery --running`` to print the running state of interfaces in the
``interfaces`` file format::
cumulus@switch:~$ sudo ifquery --running bond0
auto bond0
iface bond0
bond-xmit-hash-policy layer3+4
bond-miimon 100
bond-lacp-rate 1
bond-min-links 1
bond-slaves swp25 swp26
bond-mode 802.3ad
address 14.0.0.9/30
address 2001:ded:beef:2::1/64
``ifquery --syntax-help`` provides help on all possible attributes supported in
the ``interfaces`` file. For complete syntax on the ``interfaces`` file, see
``man interfaces`` and ``man ifupdown-addons-interfaces``.
``ifquery`` can dump information in JSON format::
cumulus@switch:~$ sudo ifquery --format=json bond0
{
"auto": true,
"config": {
"bond-use-carrier": "1",
"bond-xmit-hash-policy": "layer3+4",
"bond-miimon": "100",
"bond-lacp-rate": "1",
"bond-min-links": "1",
"bond-slaves": "swp25 swp26",
"bond-mode": "802.3ad",
"address": [
"14.0.0.9/30",
"2001:ded:beef:2::1/64"
]
},
"addr_method": null,
"name": "bond0",
"addr_family": null
}
.. By default ``ifquery`` outputs information in the ``interfaces`` format. Some
options do take the ``--format`` option and can output in JSON format.
Useful Links
============
* `<http://wiki.debian.org/NetworkConfiguration>`_
* `<http://www.linuxfoundation.org/collaborate/workgroups/networking/bonding>`_
* `<http://www.linuxfoundation.org/collaborate/workgroups/networking/bridge>`_
* `<http://www.linuxfoundation.org/collaborate/workgroups/networking/vlan>`_
.. Caveats and Errata
.. ==================

View File

@ -0,0 +1,5 @@
""" ifupdown2 package.
.. moduleauthor:: Roopa Prabhu <roopa@cumulusnetworks.com>
"""

View File

@ -16,6 +16,7 @@ except ImportError, e:
pass
class graph():
""" graph functions to sort and print interface graph """
def __init__(self):
self.logger = logging.getLogger('ifupdown.' +
@ -23,6 +24,12 @@ class graph():
@classmethod
def topological_sort_graphs_all(cls, dependency_graphs, indegrees_arg):
""" runs topological sort on interface list passed as dependency graph
Args:
dependency_graphs (dict): dependency graph with dependency lists for interfaces
indegrees_arg (dict): indegrees array for all interfaces
"""
S = []
Q = deque()
@ -57,6 +64,13 @@ class graph():
@classmethod
def generate_dots(cls, dependency_graph, indegrees):
""" spits out interface dependency graph in dot format
Args:
dependency_graphs (dict): dependency graph with dependency lists for interfaces
indegrees_arg (dict): indegrees array for all interfaces
"""
gvgraph = GvGen()
graphnodes = {}
for v in dependency_graph.keys():

View File

@ -11,18 +11,6 @@
It closely resembles the 'iface' object in /etc/network/interfaces
file. But can be extended to include any other network interface format
The module contains the following public classes:
- ifaceState -- enumerates iface object state
- ifaceStatus -- enumerates iface object status (success/error)
- ifaceJsonEncoder -- Json encoder for the iface object
- iface -- network in terface object class
"""
from collections import OrderedDict
@ -176,17 +164,29 @@ class iface():
def __init__(self, attrsdict={}):
self._set_attrs_from_dict(attrsdict)
self._config_status = {}
"""dict with config status of iface attributes"""
self.state = ifaceState.NEW
"""iface state (of type ifaceState) """
self.status = ifaceStatus.UNKNOWN
"""iface status (of type ifaceStatus) """
self.flags = 0x0
"""iface flags """
self.priv_flags = 0x0
"""iface priv flags. can be used by the external object manager """
self.refcnt = 0
"""iface refcnt (incremented for each dependent this interface has) """
self.lowerifaces = None
"""lower iface list (in other words: slaves of this interface """
self.upperifaces = None
"""upper iface list (in other words: master of this interface """
self.classes = []
"""interface classes this iface belongs to """
self.env = None
"""environment variable dict required for this interface to run"""
self.raw_config = []
"""interface config/attributes in raw format (eg: as it appeared in the interfaces file)"""
self.linkstate = None
"""linkstate of the interface"""
def _set_attrs_from_dict(self, attrdict):
self.auto = attrdict.get('auto', False)
@ -196,12 +196,18 @@ class iface():
self.config = attrdict.get('config', OrderedDict())
def inc_refcnt(self):
""" increment refcnt of the interface. Usually used to indicate that
it has dependents """
self.refcnt += 1
def dec_refcnt(self):
""" decrement refcnt of the interface. Usually used to indicate that
it has lost its dependent """
self.refcnt -= 1
def is_config_present(self):
""" returns true if the interface has user provided config,
false otherwise """
addr_method = self.addr_method
if addr_method and addr_method in ['dhcp', 'dhcp6', 'loopback']:
return True
@ -211,10 +217,11 @@ class iface():
return True
def set_class(self, classname):
""" Appends a class to the list """
""" appends class to the interfaces class list """
self.classes.append(classname)
def set_state_n_status(self, state, status):
""" sets state and status of an interface """
self.state = state
self.status = status
@ -225,6 +232,7 @@ class iface():
self.flags &= ~flag
def add_to_upperifaces(self, upperifacename):
""" add to the list of upperifaces """
if self.upperifaces:
if upperifacename not in self.upperifaces:
self.upperifaces.append(upperifacename)
@ -232,15 +240,18 @@ class iface():
self.upperifaces = [upperifacename]
def get_attr_value(self, attr_name):
""" add to the list of upperifaces """
return self.config.get(attr_name)
def get_attr_value_first(self, attr_name):
""" get first value of the specified attr name """
attr_value_list = self.config.get(attr_name)
if attr_value_list:
return attr_value_list[0]
return None
def get_attr_value_n(self, attr_name, attr_index):
""" get n'th value of the specified attr name """
attr_value_list = self.config.get(attr_name)
if attr_value_list:
try:
@ -251,11 +262,15 @@ class iface():
@property
def get_env(self):
""" get shell environment variables the interface must execute in """
if not self.env:
self.generate_env()
return self.env
def generate_env(self):
""" generate shell environment variables dict interface must execute
in. This is used to support legacy ifupdown scripts
"""
env = {}
config = self.config
env['IFACE'] = self.name
@ -266,15 +281,17 @@ class iface():
self.env = env
def update_config(self, attr_name, attr_value):
""" add attribute name and value to the interface config """
self.config.setdefault(attr_name, []).append(attr_value)
def update_config_dict(self, attrdict):
self.config.update(attrdict)
def update_config_with_status(self, attr_name, attr_value, attr_status=0):
""" add attribute name and value to the interface config and also
update the config_status dict with status of this attribute config """
if not attr_value:
attr_value = ''
self.config.setdefault(attr_name, []).append(attr_value)
self._config_status.setdefault(attr_name, []).append(attr_status)
@ -286,10 +303,13 @@ class iface():
self.status = ifaceStatus.SUCCESS
def get_config_attr_status(self, attr_name, idx=0):
""" get status of a attribute config on this interface.
Looks at the iface _config_status dict"""
return self._config_status.get(attr_name, [])[idx]
def compare(self, dstiface):
""" Compares two objects
""" compares iface object with iface object passed as argument
Returns True if object self is same as dstiface and False otherwise """

View File

@ -11,7 +11,7 @@ import logging
import subprocess
import re
import os
from ifupdown.iface import *
from iface import *
class ifupdownBase(object):

View File

@ -24,6 +24,14 @@ from collections import OrderedDict
from graph import *
from sets import Set
"""
.. module:: ifupdownmain
:synopsis: main module for ifupdown package
.. moduleauthor:: Roopa Prabhu <roopa@cumulusnetworks.com>
"""
_tickmark = u'\u2713'
_crossmark = u'\u2717'
_success_sym = _tickmark
@ -120,6 +128,19 @@ class ifupdownMain(ifupdownBase):
interfacesfile='/etc/network/interfaces',
interfacesfileiobuf=None,
interfacesfileformat='native'):
"""This member function initializes the ifupdownmain object.
Kwargs:
config (dict): config dict from /etc/network/ifupdown2/ifupdown2.conf
force (bool): force interface configuration
dryrun (bool): dryrun interface configuration
withdepends (bool): apply interface configuration on all depends
interfacesfile (str): interfaces file. default is /etc/network/interfaces
interfacesfileformat (str): default is 'native'. Other choices are 'json'
Raises:
AttributeError, KeyError """
self.logger = logging.getLogger('ifupdown')
self.FORCE = force
self.DRYRUN = dryrun
@ -624,7 +645,18 @@ class ifupdownMain(ifupdownBase):
def up(self, ops, auto=False, allow_classes=None, ifacenames=None,
excludepats=None, printdependency=None, syntaxcheck=False):
""" up an interface """
"""This brings the interface(s) up
Args:
ops (list): list of ops to perform on the interface(s). Eg: ['pre-up', 'up', 'post-up'
Kwargs:
auto (bool): act on interfaces marked auto
allow_classes (list): act on interfaces belonging to classes in the list
ifacenames (list): act on interfaces specified in this list
excludepats (list): list of patterns of interfaces to exclude
syntaxcheck (bool): only perform syntax check
"""
if allow_classes:
self.IFACE_CLASS = True

View File

@ -18,6 +18,7 @@ from template import templateEngine
whitespaces = '\n\t\r '
class networkInterfaces():
""" debian ifupdown /etc/network/interfaces file parser """
hotplugs = {}
auto_ifaces = []
@ -29,6 +30,18 @@ class networkInterfaces():
def __init__(self, interfacesfile='/etc/network/interfaces',
interfacesfileiobuf=None, interfacesfileformat='native',
template_engine=None, template_lookuppath=None):
"""This member function initializes the networkinterfaces parser object.
Kwargs:
interfacesfile (str): path to the interfaces file (default is /etc/network/interfaces)
interfacesfileiobuf (object): interfaces file io stream
interfacesfileformat (str): format of interfaces file (choices are 'native' and 'json'. 'native' being the default)
template_engine (str): template engine name
template_lookuppath (str): template lookup path
Raises:
AttributeError, KeyError """
self.logger = logging.getLogger('ifupdown.' +
self.__class__.__name__)
self.callbacks = {'iface_found' : None,
@ -76,6 +89,15 @@ class networkInterfaces():
ifaceobj.addr_method = 'static'
def subscribe(self, callback_name, callback_func):
"""This member function registers callback functions
Args:
callback_name (str): callback function name (supported names: 'iface_found', 'validateifaceattr', 'validateifaceobj')
callback_func (function pointer): callback function pointer
Warns on error
"""
if callback_name not in self.callbacks.keys():
print 'warning: invalid callback ' + callback_name
return -1
@ -321,6 +343,11 @@ class networkInterfaces():
self.callbacks.get('iface_found')(ifaceobj)
def load(self):
""" This member function loads the networkinterfaces file.
Assumes networkinterfaces parser object is initialized with the
parser arguments
"""
if self.interfacesfileformat == 'json':
return self.read_file_json(self.interfacesfile,
self.interfacesfileiobuf)

View File

@ -30,20 +30,6 @@ class ifaceScheduler():
supports scheduling of interfaces serially in plain interface list
or dependency graph format.
Algo:
- run topological sort on the iface objects
- In the sorted iface object list, pick up interfaces with no parents
and run ops on them and their children.
- If operation is up and user gave interface list (ie not all)
option, also see if there were upper-devices and run ops on them.
- if operation is down, dont down the interface if it still
has upperifaces present. The down operation is executed when the
last upperiface goes away. If force option is set, this rule does not
apply.
- run ops calls addon modules run operation passing the iface
object and op to each module.
- ops are [pre-up, up, post-up, pre-down, down,
post-down, query-running, query-check]
"""
_STATE_CHECK = True
@ -334,18 +320,20 @@ class ifaceScheduler():
dependency_graph=None, indegrees=None,
order=ifaceSchedulerFlags.POSTORDER,
followdependents=True):
""" Runs iface dependeny graph by visiting all the nodes
Parameters:
-----------
ifupdownobj : ifupdown object (used for getting and updating iface
object state)
dependency_graph : dependency graph in adjacency list
format (contains more than one dependency graph)
ops : list of operations to perform eg ['pre-up', 'up', 'post-up']
""" runs interface configuration modules on interfaces passed as
argument. Runs topological sort on interface dependency graph.
Args:
ifupdownobj (object): ifupdownMain object
ifacenames (list): list of interface names
ops : list of operations to perform eg ['pre-up', 'up', 'post-up']
dependency_graph (dict): dependency graph in adjacency list format
Kwargs:
indegrees (dict): indegree array of the dependency graph
order (int): ifaceSchedulerFlags (POSTORDER, INORDER)
followdependents (bool): follow dependent interfaces if true
indegrees : indegree array if present is used to topologically sort
the graphs in the dependency_graph
"""
#
# Algo:

View File

@ -17,6 +17,7 @@ class pickling():
@classmethod
def save(cls, filename, list_of_objects):
""" pickle a list of iface objects """
try:
with open(filename, 'w') as f:
for obj in list_of_objects:
@ -26,6 +27,7 @@ class pickling():
@classmethod
def save_obj(cls, f, obj):
""" pickle iface object """
try:
cPickle.dump(obj, f, cPickle.HIGHEST_PROTOCOL)
except:
@ -33,6 +35,7 @@ class pickling():
@classmethod
def load(cls, filename):
""" load picked iface object """
with open(filename, 'r') as f:
while True:
try: yield cPickle.load(f)
@ -40,12 +43,26 @@ class pickling():
except: raise
class stateManager():
""" state manager for managing ifupdown iface obj state """
""" state manager for managing ifupdown iface obj state
ifupdown2 has to maitain old objects for down operation on
interfaces. ie to down or delete old configuration.
This class uses pickle to store iface objects.
"""
state_dir = '/var/tmp/network/'
"""directory where the state file is stored """
state_filename = 'ifstatenew'
"""name of the satefile """
def __init__(self):
""" Initializes statemanager internal state
which includes a dictionary of last pickled iface objects
"""
self.ifaceobjdict = OrderedDict()
self.logger = logging.getLogger('ifupdown.' +
self.__class__.__name__)
@ -58,6 +75,12 @@ class stateManager():
[]).append(ifaceobj)
def read_saved_state(self, filename=None):
"""This member function reads saved iface objects
Kwargs:
filename (str): name of the state file
"""
pickle_filename = filename
if not pickle_filename:
pickle_filename = self.state_file
@ -70,6 +93,13 @@ class stateManager():
return self.ifaceobjdict.get(ifacename)
def ifaceobj_sync(self, ifaceobj, op):
"""This member function sync's new obj state to old statemanager state
Args:
ifaceobj (object): new iface object
op (str): ifupdown operation
"""
self.logger.debug('%s: statemanager sync state' %ifaceobj.name)
old_ifaceobjs = self.ifaceobjdict.get(ifaceobj.name)
if 'up' in op:
@ -105,6 +135,8 @@ class stateManager():
oidx += 1
def save_state(self):
""" saves state (ifaceobjects) to persistent state file """
try:
with open(self.state_file, 'w') as f:
if not len(self.ifaceobjdict):

View File

@ -5,6 +5,7 @@ import traceback
from utils import *
class templateEngine():
""" has template rendering methods """
def __init__(self, template_engine, template_lookuppath=None):
self.logger = logging.getLogger('ifupdown.' +