utils.py 1.93 KB
Newer Older
1 2 3 4 5 6 7
import os
from os import getenv
import subprocess as sp
import logging
import json
import re

8 9 10 11 12
try:
  basestring
except NameError:
  basestring = str

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

NETNS = getenv('NETNS', 'fw')
ADDRESSES = json.loads(getenv('ADDRESSES', '{}'))
HA = bool(getenv('HA', False))


def get_network_type():
    from ovs import Switch, Bridge
    if getenv('BRIDGE_TYPE', 'OVS') == 'BRIDGE':
        return Bridge
    elif getenv('BRIDGE_TYPE', 'OVS') == 'NONE':
        return None
    else:
        return Switch

# 2013-06-26 12:16:59 DHCPACK on 10.4.0.14 to 5c:b5:24:e6:5c:81
#      (android_b555bfdba7c837d) via vlan0004

dhcp_ack_re = re.compile(r'\S DHCPACK on (?P<ip>[0-9.]+) to '
                         r'(?P<mac>[a-zA-Z0-9:]+) '
                         r'(\((?P<hostname>[^)]+)\) )?'
                         r'via (?P<interface>[a-zA-Z0-9]+)')

# 2013-06-25 11:08:38 DHCPDISCOVER from 48:5b:39:8e:82:78
#      via vlan0005: network 10.5.0.0/16: no free leases

dhcp_no_free_re = re.compile(r'\S DHCPDISCOVER '
                             r'from (?P<mac>[a-zA-Z0-9:]+) '
                             r'via (?P<interface>[a-zA-Z0-9]+):')


def sudo(args, stdin=None):
    args = ('/usr/bin/sudo', ) + args
    logger.debug('EXEC {}'.format(' '.join(args)))

    p = sp.Popen(args, stdin=sp.PIPE, stderr=sp.PIPE, stdout=sp.PIPE)
    if isinstance(stdin, basestring):
54
        stdout, stderr = p.communicate(bytes(stdin, 'utf-8'))
55 56 57 58 59
    else:
        stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise sp.CalledProcessError(
            p.returncode, sp.list2cmdline(args), stderr)
60
    return str(stdout)
61 62 63 64 65 66 67 68 69 70 71 72 73


def ns_exec(args, stdin=None):
    if get_network_type() is None:
        return sudo(args, stdin)
    else:
        return sudo(('/sbin/ip', 'netns', 'exec',
                    NETNS) + args, stdin)


def is_there_systemd():

    return os.path.isfile("/bin/systemctl")