Exemplo n.º 1
0
    def __init__(self, config, environment):
        self.config = config
        """
        Dictionary representation of the config passed via stdin.
        """

        self.env = environment
        """
        Current environment (e.g os.environ)
        """

        self.command = None
        """
        Command indicating which action to take - one of "ADD" or "DEL".
        """

        self.container_id = None
        """
        Identifier for the container for which we are performing IPAM.
        """

        self.datastore_client = IPAMClient()
        """
        Access to the datastore client.  Relies on ETCD_AUTHORITY environment
        variable being set by the calling plugin.
        """

        # Validate the given config and environment and set fields
        # using the given config and environment.
        self._parse_config()
Exemplo n.º 2
0
    def __init__(self, environment, ipam_config):
        self.command = None
        """
        Command indicating which action to take - one of "ADD" or "DEL".
        """

        self.container_id = None
        """
        Identifier for the container for which we are performing IPAM.
        """

        self.datastore_client = IPAMClient()
        """
        Access to the datastore client.  Relies on ETCD_AUTHORITY environment
        variable being set by the calling plugin.
        """

        self.assign_ipv4 = ipam_config.get(ASSIGN_IPV4_KEY, "true") == "true"
        """
        Whether we should auto assign an IPv4 address - defaults to True.
        """

        self.assign_ipv6 = ipam_config.get(ASSIGN_IPV6_KEY, "false") == "true"
        """
        Whether we should auto assign an IPv6 address - defaults to False.
        """

        cni_args = parse_cni_args(environment.get(CNI_ARGS_ENV, ""))
        self.k8s_pod_name = cni_args.get(K8S_POD_NAME)
        self.k8s_namespace = cni_args.get(K8S_POD_NAMESPACE)
        """
        Only populated when running under Kubernetes.
        """
        """
        Only populated if the user requests a specific IP address.
        """
        self.ip = cni_args.get(CNI_ARGS_IP)

        # Validate the given environment and set fields.
        self._parse_environment(environment)

        if self.k8s_namespace and self.k8s_pod_name:
            self.workload_id = "%s.%s" % (self.k8s_namespace,
                                          self.k8s_pod_name)
        else:
            self.workload_id = self.container_id
        """
Exemplo n.º 3
0
    def __init__(self, config):
        self.pod_name = None
        self.profile_name = None
        self.namespace = None
        self.docker_id = None
        self.policy_parser = None

        # Get configuration from the given dictionary.
        logger.debug("Plugin running with config: %s", config)
        self.auth_token = config[KUBE_AUTH_TOKEN_VAR]
        self.api_root = config[KUBE_API_ROOT_VAR]
        self.calico_ipam = config[CALICO_IPAM_VAR].lower()
        self.default_policy = config[DEFAULT_POLICY_VAR].lower()

        self._datastore_client = IPAMClient()
        self._docker_client = Client(
            version=DOCKER_VERSION,
            base_url=os.getenv("DOCKER_HOST", "unix://var/run/docker.sock"))
Exemplo n.º 4
0
def delete(container_id):
    """Cleanup after a pod."""
    print_stderr('Deleting pod %s' % container_id, file=sys.stderr)

    _datastore_client = IPAMClient()

    # Remove the profile for the workload.
    _container_remove(hostname=HOSTNAME,
                      orchestrator_id=ORCHESTRATOR_ID,
                      container_id=container_id,
                      client=_datastore_client)

    # Delete profile
    try:
        _datastore_client.remove_profile(input_json['name'])
    except:
        print_stderr("Cannot remove profile %s; Profile cannot be found." %
                     container_id)
Exemplo n.º 5
0
def create(container_id):
    """"Handle rkt pod-create event."""
    print_stderr('Configuring pod %s' % container_id, file=sys.stderr)
    netns_path = '%s/%s/%s' % (NETNS_ROOT, container_id, env['CNI_NETNS'])
    _datastore_client = IPAMClient()

    try:
        endpoint, ip = _create_calico_endpoint(container_id=container_id,
                                               netns_path=netns_path,
                                               client=_datastore_client)

        _create_profile(endpoint=endpoint,
                        profile_name=input_json['name'],
                        ip=ip,
                        client=_datastore_client)
    except CalledProcessError as e:
        print_stderr('Error code %d creating pod networking: %s\n%s' %
                     (e.returncode, e.output, e))
        sys.exit(1)
    print_stderr('Finished Creating pod %s' % container_id)
Exemplo n.º 6
0
            client.add_ip_pool(6, DEFAULT_IPV6_POOL)

    client.ensure_global_config()
    client.create_host(hostname, ip, ip6, as_num)

    # If IPIP is enabled, the host requires an IP address for its tunnel
    # device, which is in an IPIP pool.  Without this, a host can't originate
    # traffic to a pool address because the response traffic would not be
    # routed via the tunnel (likely being dropped by RPF checks in the fabric).
    ipv4_pools = client.get_ip_pools(4)
    ipip_pools = [p for p in ipv4_pools if p.ipip]

    if ipip_pools:
        # IPIP is enabled, make sure the host has an address for its tunnel.
        _ensure_host_tunnel_addr(ipv4_pools, ipip_pools)
    else:
        # No IPIP pools, clean up any old address.
        _remove_host_tunnel_addr()


# Try the HOSTNAME environment variable, but default to
# the socket.gethostname() value if unset.
hostname = os.getenv("HOSTNAME")
if not hostname:
    hostname = socket.gethostname()

client = IPAMClient()

if __name__ == "__main__":
    main()
Exemplo n.º 7
0
def _get_client():
    os.environ[ETCD_SCHEME_ENV] = 'http'
    os.environ[ETCD_AUTHORITY_ENV] = ETCD
    return IPAMClient()
Exemplo n.º 8
0
import traceback
import re
from subprocess import check_output, CalledProcessError
from netaddr import IPNetwork

LOGFILE = "/var/log/calico/isolator.log"
ORCHESTRATOR_ID = "mesos"

ERROR_MISSING_COMMAND = "Missing command"
ERROR_MISSING_CONTAINER_ID = "Missing container_id"
ERROR_MISSING_HOSTNAME = "Missing hostname"
ERROR_MISSING_PID = "Missing pid"
ERROR_UNKNOWN_COMMAND = "Unknown command: %s"
ERROR_MISSING_ARGS = "Missing args"

datastore = IPAMClient()
_log = logging.getLogger("CALICOMESOS")


def calico_mesos():
    """
    Module function which parses JSON from stdin and calls the appropriate
    plugin function.
    :return:
    """
    stdin_raw_data = sys.stdin.read()
    _log.info("Received request: %s" % stdin_raw_data)

    # Convert input data to JSON object
    try:
        stdin_json = json.loads(stdin_raw_data)
Exemplo n.º 9
0
from pycalico import netns
from pycalico.ipam import IPAMClient, SequentialAssignment
from pycalico.netns import Namespace
from pycalico.datastore_datatypes import Rules, IPPool
from pycalico.datastore import IF_PREFIX
from pycalico.datastore_errors import PoolNotFound

ETCD_AUTHORITY_ENV = 'ETCD_AUTHORITY'
LOG_DIR = '/var/log/calico/calico-rkt'

ORCHESTRATOR_ID = "rkt"
HOSTNAME = socket.gethostname()
NETNS_ROOT = '/var/lib/rkt/pods/run'

_log = logging.getLogger(__name__)
datastore_client = IPAMClient()


def calico_rkt(args):
    """
    Orchestrate top level function

    :param args: dict of values to pass to other functions (see: validate_args)
    """
    if args['command'] == 'ADD':
        create(args)
    elif args['command'] == 'DEL':
        delete(args)


def create(args):