# Path: cirque/common/cirquelog.py
# class CirqueLog:
# 
#   logger = None
# 
#   @classmethod
#   def setup_cirque_logger(cls, level=logging.INFO):
#     if cls.logger:
#       return
#     cls.logger = logging.getLogger('cirque')
#     cls.logger.setLevel(level)
#     sh = logging.StreamHandler()
#     sh.setFormatter(
#         logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s'))
#     cls.logger.addHandler(sh)
# 
#   @classmethod
#   def get_cirque_logger(cls, name=None):
#     name = 'cirque' if not name else 'cirque.{}'.format(name)
#     return logging.getLogger(name)
# 
# Path: cirque/common/utils.py
# def host_run(logger,
#              command,
#              namespace=None,
#              stdin=None,
#              stdout=subprocess.PIPE,
#              stderr=subprocess.PIPE):
#   if not isinstance(command, (list, str)):
#     logger.error(
#         'unable to parse desired commands..Supporting only list or str!')
#     return -1
#   exec_command = ' '.join(command) if isinstance(command, list) else command
# 
#   logger.debug('CMD RUN: {}'.format(exec_command))
# 
#   if namespace and 'ip netns exec' not in exec_command:
#     exec_command = 'ip netns exec {} '.format(namespace) + exec_command
# 
#   process = None
#   for command in exec_command.split('|'):
#     stdin = process.stdout if process else None
#     process = subprocess.Popen(
#         shlex.split(command), stdin=stdin, stdout=stdout, stderr=stderr)
#   stdout, stderr = process.communicate()
#   returncode = process.returncode
#   logger.debug('CMD RESULT: \n'
#                'ReturnCode: {},\nStdout: {},\nStdin: {}'.format(
#                    returncode, stdout, stderr))
# 
#   return Return(returncode, stdout, stderr)
# 
# def manipulate_iptable_src_dst_rule(logger, src, dst, action, add=True):
#   chain = 'DOCKER-USER'
#   manipulate_action = '-I' if add else '-D'
#   ret = host_run(logger, 'iptables -L DOCKER-USER')
#   if b'No chain/target/match by that name' in ret.stderr:
#     chain = 'INPUT'
#   cmd = [
#       'iptables', manipulate_action, chain, '-s', src, '-d', dst, '-j', action
#   ]
#   ret = host_run(logger, cmd)
#   if ret.returncode != 0:
#     logger.error('Failed to add iptables rule %s', ' '.join(cmd))


import ipaddress
import json
from cirque.common.cirquelog import CirqueLog
from cirque.common.utils import host_run, manipulate_iptable_src_dst_rule
  def __create_ipvlan_network(self):
    interface_command = "route | awk '/default / {print $8}'"
    ret = host_run(self.logger, interface_command)
    if ret.returncode != 0:
      self.logger.error('Failed to get network interface for creating '
                        'ipvlan %s: %s' % (self.__name, ret.stderr))
    interface = ret.stdout.rstrip().decode('utf-8')
    subnet_command = "ip addr show %s | awk '/inet / {print $2}'" % interface
    ret = host_run(self.logger, subnet_command)
    if ret.returncode != 0:
      self.logger.error('Failed to get subnetwork for create '
                        'ipvalen %s: %s' % (self.__name, ret.stderr))
    subnet = ret.stdout.rstrip().decode('utf-8')
    gateway_command = "ip r | awk '/default via/ {print $3}'"
    ret = host_run(self.logger, gateway_command)
    if ret.returncode != 0:
      self.logger.error('Failed to retrieve gateway for create '
                        'ipvalen %s: %s' % (self.__name, ret.stderr))
    gateway = ret.stdout.rstrip().decode('utf-8')
    ipvlan_command = 'docker network create -d ipvlan --subnet=%s'\
        ' --gateway=%s -o parent=%s %s' % (
            subnet, gateway, interface, self.__name)
    ret = host_run(self.logger, ipvlan_command)
    if ret.returncode != 0:
      self.logger.error('Failed to create ipvlan %s: %s' %
                        (self.__name, ret.stderr))
    self.__inspect_network_properties()

  def __disable_container_mutual_access(self):
    self.__inspect_network_properties()

# Path: cirque/common/cirquelog.py
# class CirqueLog:
# 
#   logger = None
# 
#   @classmethod
#   def setup_cirque_logger(cls, level=logging.INFO):
#     if cls.logger:
#       return
#     cls.logger = logging.getLogger('cirque')
#     cls.logger.setLevel(level)
#     sh = logging.StreamHandler()
#     sh.setFormatter(
#         logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s'))
#     cls.logger.addHandler(sh)
# 
#   @classmethod
#   def get_cirque_logger(cls, name=None):
#     name = 'cirque' if not name else 'cirque.{}'.format(name)
#     return logging.getLogger(name)
# 
# Path: cirque/common/utils.py
# def host_run(logger,
#              command,
#              namespace=None,
#              stdin=None,
#              stdout=subprocess.PIPE,
#              stderr=subprocess.PIPE):
#   if not isinstance(command, (list, str)):
#     logger.error(
#         'unable to parse desired commands..Supporting only list or str!')
#     return -1
#   exec_command = ' '.join(command) if isinstance(command, list) else command
# 
#   logger.debug('CMD RUN: {}'.format(exec_command))
# 
#   if namespace and 'ip netns exec' not in exec_command:
#     exec_command = 'ip netns exec {} '.format(namespace) + exec_command
# 
#   process = None
#   for command in exec_command.split('|'):
#     stdin = process.stdout if process else None
#     process = subprocess.Popen(
#         shlex.split(command), stdin=stdin, stdout=stdout, stderr=stderr)
#   stdout, stderr = process.communicate()
#   returncode = process.returncode
#   logger.debug('CMD RESULT: \n'
#                'ReturnCode: {},\nStdout: {},\nStdin: {}'.format(
#                    returncode, stdout, stderr))
# 
#   return Return(returncode, stdout, stderr)
# 
# def manipulate_iptable_src_dst_rule(logger, src, dst, action, add=True):
#   chain = 'DOCKER-USER'
#   manipulate_action = '-I' if add else '-D'
#   ret = host_run(logger, 'iptables -L DOCKER-USER')
#   if b'No chain/target/match by that name' in ret.stderr:
#     chain = 'INPUT'
#   cmd = [
#       'iptables', manipulate_action, chain, '-s', src, '-d', dst, '-j', action
#   ]
#   ret = host_run(logger, cmd)
#   if ret.returncode != 0:
#     logger.error('Failed to add iptables rule %s', ' '.join(cmd))


# Path: cirque/connectivity/homelan.py
import ipaddress
import json
from cirque.common.cirquelog import CirqueLog
from cirque.common.utils import host_run, manipulate_iptable_src_dst_rule

  def __create_ipvlan_network(self):
    interface_command = "route | awk '/default / {print $8}'"
    ret = host_run(self.logger, interface_command)
    if ret.returncode != 0:
      self.logger.error('Failed to get network interface for creating '
                        'ipvlan %s: %s' % (self.__name, ret.stderr))
    interface = ret.stdout.rstrip().decode('utf-8')
    subnet_command = "ip addr show %s | awk '/inet / {print $2}'" % interface
    ret = host_run(self.logger, subnet_command)
    if ret.returncode != 0:
      self.logger.error('Failed to get subnetwork for create '
                        'ipvalen %s: %s' % (self.__name, ret.stderr))
    subnet = ret.stdout.rstrip().decode('utf-8')
    gateway_command = "ip r | awk '/default via/ {print $3}'"
    ret = host_run(self.logger, gateway_command)
    if ret.returncode != 0:
      self.logger.error('Failed to retrieve gateway for create '
                        'ipvalen %s: %s' % (self.__name, ret.stderr))
    gateway = ret.stdout.rstrip().decode('utf-8')
    ipvlan_command = 'docker network create -d ipvlan --subnet=%s'\
        ' --gateway=%s -o parent=%s %s' % (
            subnet, gateway, interface, self.__name)
    ret = host_run(self.logger, ipvlan_command)
    if ret.returncode != 0:
      self.logger.error('Failed to create ipvlan %s: %s' %
                        (self.__name, ret.stderr))
    self.__inspect_network_properties()

  def __disable_container_mutual_access(self):
    self.__inspect_network_properties()

    manipulate_iptable_src_dst_rule(self.logger, self.subnet, self.subnet,