def daemon_stop():
    parser = argparse.ArgumentParser()
    defaults = {
        'api-server': '127.0.0.1',
        'api-port': 8082,
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("daemon", help="Deamon Name")
    arguments = parser.parse_args(sys.argv[1:])

    manager = LxcManager()
    provisioner = Provisioner(api_server=arguments.api_server,
                              api_port=arguments.api_port)
    instance_name = '%s-%s' % (socket.gethostname(), arguments.daemon)
    vm = provisioner.virtual_machine_lookup(instance_name)

    vmi_list = vm.get_virtual_machine_interfaces()
    for ref in vmi_list:
        uuid = ref['uuid']
        interface_unregister(uuid)

    manager.clear_interfaces('ns-%s' % arguments.daemon)

    for ref in vmi_list:
        provisioner.vmi_delete(ref['uuid'])

    provisioner.virtual_machine_delete(vm)
    manager.namespace_delete(arguments.daemon)
def main():
    parser = argparse.ArgumentParser()
    defaults = {
        'api-server': '127.0.0.1',
        'api-port': 8082,
        'project': 'default-domain:default-project',
        'network': 'default-network',
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("-n", "--network", help="Primary network")
    parser.add_argument("--project", help="Network project")
    parser.add_argument("--start", action='store_true', help="Create namespace")
    parser.add_argument("--stop", action='store_true', help="Delete namespace")
    parser.add_argument("container_id", metavar='container-id', help="Container ID")

    args = parser.parse_args(sys.argv[1:])
    if not args.start and not args.stop:
        print "Please specify --start or --stop action"
        sys.exit(1)

    manager = LxcManager()
    provisioner = Provisioner(api_server=args.api_server, api_port=args.api_port)
    instance_name = '%s-%s' % (socket.gethostname(), args.container_id)
    pid_str = subprocess.check_output(
        'docker inspect -f \'{{.State.Pid}}\' %s' % args.container_id, shell=True)
    pid = int(pid_str)

    subprocess.check_output(
        'ln -sf /proc/%d/ns/net /var/run/netns/%s' % (pid, args.container_id), shell=True)

    if args.start:
        vm = provisioner.virtual_machine_locate(instance_name)
        network = build_network_name(args.project, args.network)
        vmi = provisioner.vmi_locate(vm, network, 'veth0')
        ifname = manager.create_interface(args.container_id, 'veth0', vmi)
        interface_register(vm, vmi, ifname)
        subprocess.check_output(
            'ip netns exec %s dhclient veth0' % args.container_id, shell=True)
    elif args.stop:
        vm = provisioner.virtual_machine_lookup(instance_name)

        vmi_list = vm.get_virtual_machine_interfaces()
        for ref in vmi_list:
            uuid = ref['uuid']
            interface_unregister(uuid)

        manager.clear_interfaces(args.container_id)

        for ref in vmi_list:
            provisioner.vmi_delete(ref['uuid'])

        provisioner.virtual_machine_delete(vm)
        subprocess.check_output(
            'ip netns delete %s' % args.container_id, shell=True)
示例#3
0
def daemon_start():
    """
    Creates a virtual-machine and vmi object in the API server.
    Creates a namespace and a veth interface pair.
    Associates the veth interface in the master instance with the vrouter.
    """
    parser = argparse.ArgumentParser()
    defaults = {
        'api-server': '127.0.0.1',
        'api-port': 8082,
        'project': 'default-domain:default-project',
        'network': 'default-network',
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("-n", "--network", help="Primary network")
    parser.add_argument("-o", "--outbound", help="Outbound traffic network")
    parser.add_argument("daemon", help="Deamon Name")

    arguments = parser.parse_args(sys.argv)

    manager = LxcManager()
    provisioner = Provisioner(api_server=arguments.api_server,
                              api_port=arguments.api_port)
    instance_name = '%s-%s' % (socket.gethostname(), arguments.daemon)
    vm = provisioner.virtual_machine_locate(instance_name)

    network = build_network_name(arguments.project, arguments.network)

    vmi = provisioner.vmi_locate(vm, network, 'veth0')
    vmi_out = None
    if arguments.outbound:
        outbound_name = build_network_name(arguments.project,
                                           arguments.outbound)
        vmi_out = provisioner.vmi_locate(vm, outbound_name, 'veth1')

    manager.namespace_init(arguments.daemon)
    ifname = manager.interface_update(arguments.daemon, vmi, 'veth0')
    interface_register(vm, vmi, ifname)

    if vmi_out:
        ifname = manager.interface_update(arguments.daemon, vmi_out, 'veth1')
        interface_register(vm, vmi_out, ifname)

    single_interface = (arguments.outbound is None)
    ip_prefix = provisioner.get_interface_ip_prefix(vmi)
    manager.interface_config(arguments.daemon,
                             'veth0',
                             advertise_default=single_interface,
                             ip_prefix=ip_prefix)
    if vmi_out:
        manager.interface_config(arguments.daemon, 'veth1')
def teardown(pod_namespace, pod_name, docker_id):
    manager = LxcManager()
    short_id = docker_id[0:12]

    api = ContrailVRouterApi()

    uid, podName = getDockerPod(docker_id)
    vmi, _ = vrouter_interface_by_name(podName)
    if vmi is not None:
        api.delete_port(vmi)

    manager.clear_interfaces(short_id)
    Shell.run('ip netns delete %s' % short_id)
示例#5
0
def teardown(pod_namespace, pod_name, docker_id):
    manager = LxcManager()
    short_id = docker_id[0:12]

    api = ContrailVRouterApi()

    uid, podName = getDockerPod(docker_id)
    vmi, _ = vrouter_interface_by_name(podName)
    if vmi is not None:
        api.delete_port(vmi)

    manager.clear_interfaces(short_id)
    Shell.run('ip netns delete %s' % short_id)
def daemon_start():
    """
    Creates a virtual-machine and vmi object in the API server.
    Creates a namespace and a veth interface pair.
    Associates the veth interface in the master instance with the vrouter.
    """
    parser = argparse.ArgumentParser()
    defaults = {
        'api-server': '127.0.0.1',
        'api-port': 8082,
        'project': 'default-domain:default-project',
        'network': 'default-network',
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("--project", help="OpenStack project name")
    parser.add_argument("-n", "--network", help="Primary network")
    parser.add_argument("-o", "--outbound", help="Outbound traffic network")
    parser.add_argument("daemon", help="Deamon Name")

    arguments = parser.parse_args(sys.argv[1:])

    manager = LxcManager()
    provisioner = Provisioner(api_server=arguments.api_server,
                              api_port=arguments.api_port)
    vrouter_name = socket.gethostname()
    instance_name = '%s-%s' % (vrouter_name, arguments.daemon)
    project_fq_name = arguments.project.split(':')
    project = provisioner.project_lookup(project_fq_name)
    vm = provisioner.virtual_machine_locate(vrouter_name, instance_name, project)

    network = build_network_name(arguments.project, arguments.network)

    vmi = provisioner.vmi_locate(vm, network, 'veth0', project)
    vmi_out = None
    if arguments.outbound:
        outbound_name = build_network_name(arguments.project,
                                           arguments.outbound)
        vmi_out = provisioner.vmi_locate(vm, outbound_name, 'veth1')

    manager.namespace_init(arguments.daemon)
    ifname = manager.interface_update(arguments.daemon, vmi, 'veth0')
    interface_register(vm, vmi, ifname, project=project)

    if vmi_out:
        ifname = manager.interface_update(arguments.daemon, vmi_out, 'veth1')
        interface_register(vm, vmi_out, ifname)

    single_interface = (arguments.outbound is None)
    ip_prefix = provisioner.get_interface_ip_prefix(vmi)
    manager.interface_config(arguments.daemon, 'veth0',
                             advertise_default=single_interface,
                             ip_prefix=ip_prefix)
    if vmi_out:
        manager.interface_config(arguments.daemon, 'veth1')
def daemon_stop():
    parser = argparse.ArgumentParser()
    defaults = {
        'username': None,
        'password': None,
        'api-server': '127.0.0.1',
        'api-port': 8082,
        'project': 'default-project',
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-U", "--username", help="Username of the tenant")
    parser.add_argument("-P", "--password", help="Password for the user")
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("--project", help="OpenStack project name")
    parser.add_argument("daemon", help="Deamon Name")
    arguments = parser.parse_args(sys.argv[1:])

    manager = LxcManager()
    provisioner = Provisioner(username=arguments.username,
                              password=arguments.password,
                              project=arguments.project,
                              api_server=arguments.api_server,
                              api_port=arguments.api_port)
    vrouter_name = socket.getfqdn()
    instance_name = '%s-%s' % (vrouter_name, arguments.daemon)
    vm = provisioner.virtual_machine_lookup(instance_name)

    vmi_list = vm.get_virtual_machine_interface_back_refs()
    for ref in vmi_list:
        uuid = ref['uuid']
        interface_unregister(uuid)

    manager.clear_interfaces('ns-%s' % arguments.daemon)

    for ref in vmi_list:
        provisioner.vmi_delete(ref['uuid'])

    provisioner.virtual_machine_delete(vrouter_name, vm)
    manager.namespace_delete(arguments.daemon)
def daemon_stop():
    parser = argparse.ArgumentParser()
    defaults = {
        'api-server': '127.0.0.1',
        'api-port': 8082,
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("daemon", help="Deamon Name")
    arguments = parser.parse_args(sys.argv)

    manager = LxcManager()
    provisioner = Provisioner(api_server=arguments.api_server,
                              api_port=arguments.api_port)
    instance_name = '%s-%s' % (socket.gethostname(), arguments.daemon)
    vm = provisioner.virtual_machine_lookup(instance_name)

    vmi_list = vm.get_virtual_machine_interfaces()
    for ref in vmi_list:
        uuid = ref['uuid']
        interface_unregister(uuid)

    manager.clear_interfaces(arguments.daemon)

    for ref in vmi_list:
        provisioner.vmi_delete(ref['uuid'])

    provisioner.virtual_machine_delete(vm)
    manager.namespace_delete(arguments.daemon)
def daemon_stop():
    parser = argparse.ArgumentParser()
    defaults = {
        'username': None,
        'password': None,
        'api-server': '127.0.0.1',
        'api-port': 8082,
        'project': 'default-project',
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-U", "--username", help="Username of the tenant")
    parser.add_argument("-P", "--password", help="Password for the user")
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("--project", help="OpenStack project name")
    parser.add_argument("daemon", help="Deamon Name")
    arguments = parser.parse_args(sys.argv[1:])

    manager = LxcManager()
    provisioner = Provisioner(username=arguments.username,
                              password=arguments.password,
                              project=arguments.project,
                              api_server=arguments.api_server,
                              api_port=arguments.api_port)
    vrouter_name = socket.gethostname()
    instance_name = '%s-%s' % (vrouter_name, arguments.daemon)
    vm = provisioner.virtual_machine_lookup(instance_name)

    vmi_list = vm.get_virtual_machine_interface_back_refs()
    for ref in vmi_list:
        uuid = ref['uuid']
        interface_unregister(uuid)

    manager.clear_interfaces('ns-%s' % arguments.daemon)

    for ref in vmi_list:
        provisioner.vmi_delete(ref['uuid'])

    provisioner.virtual_machine_delete(vrouter_name, vm)
    manager.namespace_delete(arguments.daemon)
示例#10
0
def setup(pod_namespace, pod_name, docker_id, retry=True):
    """
    project: pod_namespace
    network: pod_name
    netns: docker_id{12}
    """

    # Kubelet::createPodInfraContainer ensures that State.Pid is set
    pid = docker_get_pid(docker_id)
    if pid == 0:
        raise Exception('Unable to read State.Pid')

    short_id = docker_id[0:12]

    if not os.path.exists('/var/run/netns'):
        os.mkdir('/var/run/netns')

    Shell.run('ln -sf /proc/%d/ns/net /var/run/netns/%s' % (pid, short_id))

    manager = LxcManager()

    if opt_net_mode == 'none':
        instance_ifname = 'veth0'
    else:
        instance_ifname = 'eth0'

    uid, podName = getDockerPod(docker_id)
    podInfo = None
    podState = None
    for i in range(0, 30):
        podInfo = getPodInfo(pod_namespace, podName)
        if podInfo is None:
            return False
        if 'hostNetwork' in podInfo['spec'] and \
           podInfo['spec']['hostNetwork']:
            return True
        if 'annotations' in podInfo["metadata"] and \
           'opencontrail.org/pod-state' in podInfo["metadata"]["annotations"]:
            podState = json.loads(podInfo["metadata"]["annotations"]
                                  ["opencontrail.org/pod-state"])
            break
        if not retry:
            return False
        time.sleep(1)

    # The lxc_manager uses the mac_address to setup the container interface.
    # Additionally the ip-address, prefixlen and gateway are also used.
    if podState is None:
        logging.error('No annotations in pod %s', podInfo["metadata"]["name"])
        return False

    nic_uuid = podState["uuid"]
    mac_address = podState["macAddress"]
    if opt_net_mode == 'none':
        ifname = manager.create_interface(short_id, instance_ifname,
                                          mac_address)
    else:
        ifname = manager.move_interface(short_id, pid, mac_address)

    api = ContrailVRouterApi()
    api.add_port(uid,
                 nic_uuid,
                 ifname,
                 mac_address,
                 port_type='NovaVMPort',
                 display_name=podName,
                 hostname=podName + '.' + pod_namespace)

    ip_address = podState["ipAddress"]
    gateway = podState["gateway"]
    Shell.run('ip netns exec %s ip addr add %s/32 peer %s dev %s' %
              (short_id, ip_address, gateway, instance_ifname))
    Shell.run('ip netns exec %s ip route add default via %s' %
              (short_id, gateway))
    Shell.run('ip netns exec %s ip link set %s up' %
              (short_id, instance_ifname))
    return True
示例#11
0
def daemon_start():
    """
    Creates a virtual-machine and vmi object in the API server.
    Creates a namespace and a veth interface pair.
    Associates the veth interface in the master instance with the vrouter.
    """
    parser = argparse.ArgumentParser()
    defaults = {
        'username': None,
        'password': None,
        'api-server': '127.0.0.1',
        'api-port': 8082,
        'project': 'default-domain:default-project',
        'network': 'default-network',
        'monitor' : False,
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-U", "--username", help="Username of the tenant")
    parser.add_argument("-P", "--password", help="Password for the user")
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("--project", help="OpenStack project name")
    parser.add_argument("-n", "--network", help="Primary network")
    parser.add_argument("-o", "--outbound", help="Outbound traffic network")
    '''
    --monitor is maintained only for backward compatibility. Replug of vif's
    across vrouter-agent is not required anymore as vif info is persisted in
    files which are read upon vrouter-agent start.
    '''
    parser.add_argument("-M", "--monitor", action='store_true',
                        help="Monitor the vrouter agent connection to replug the vif's.")
    parser.add_argument("daemon", help="Deamon Name")

    arguments = parser.parse_args(sys.argv[1:])

    manager = LxcManager()
    project_name = get_project_name(arguments.project, arguments.network)
    provisioner = Provisioner(username=arguments.username,
                              password=arguments.password,
                              api_server=arguments.api_server,
                              api_port=arguments.api_port,
                              project=project_name)
    vrouter_name = socket.getfqdn()
    instance_name = '%s-%s' % (vrouter_name, arguments.daemon)
    vm = provisioner.virtual_machine_locate(vrouter_name, instance_name)

    network = build_network_name(arguments.project, arguments.network)

    vmi, project = provisioner.vmi_locate(vm, network, 'veth0')
    vmi_out = None
    if arguments.outbound:
        outbound_name = build_network_name(arguments.project,
                                           arguments.outbound)
        vmi_out, project = provisioner.vmi_locate(vm, outbound_name, 'veth1')

    manager.namespace_init(arguments.daemon)
    ifname = manager.interface_update(arguments.daemon, vmi, 'veth0')
    interface_register(vm, vmi, ifname, project=project)

    vmi_out_kwargs = {}
    if vmi_out:
        ifname = manager.interface_update(arguments.daemon, vmi_out, 'veth1')
        interface_register(vm, vmi_out, ifname, project=project)
        vmi_out_kwargs = {'vmi_out' : vmi_out,
                          'ifname_out' : ifname
                         }

    single_interface = (arguments.outbound is None)
    ip_prefix = provisioner.get_interface_ip_prefix(vmi)
    manager.interface_config(arguments.daemon, 'veth0',
                             advertise_default=single_interface,
                             ip_prefix=ip_prefix)
    if vmi_out:
        manager.interface_config(arguments.daemon, 'veth1')
示例#12
0
def daemon_start():
    """
    Creates a virtual-machine and vmi object in the API server.
    Creates a namespace and a veth interface pair.
    Associates the veth interface in the master instance with the vrouter.
    """
    parser = argparse.ArgumentParser()
    defaults = {
        'username': None,
        'password': None,
        'api-server': '127.0.0.1',
        'api-port': 8082,
        'project': 'default-domain:default-project',
        'network': 'default-network',
        'monitor': False,
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-U", "--username", help="Username of the tenant")
    parser.add_argument("-P", "--password", help="Password for the user")
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("--project", help="OpenStack project name")
    parser.add_argument("-n", "--network", help="Primary network")
    parser.add_argument("-o", "--outbound", help="Outbound traffic network")
    '''
    --monitor is maintained only for backward compatibility. Replug of vif's
    across vrouter-agent is not required anymore as vif info is persisted in
    files which are read upon vrouter-agent start.
    '''
    parser.add_argument(
        "-M",
        "--monitor",
        action='store_true',
        help="Monitor the vrouter agent connection to replug the vif's.")
    parser.add_argument("daemon", help="Deamon Name")

    arguments = parser.parse_args(sys.argv[1:])

    manager = LxcManager()
    project_name = get_project_name(arguments.project, arguments.network)
    provisioner = Provisioner(username=arguments.username,
                              password=arguments.password,
                              api_server=arguments.api_server,
                              api_port=arguments.api_port,
                              project=project_name)
    vrouter_name = socket.getfqdn()
    instance_name = '%s-%s' % (vrouter_name, arguments.daemon)
    vm = provisioner.virtual_machine_locate(vrouter_name, instance_name)

    network = build_network_name(arguments.project, arguments.network)

    vmi, project = provisioner.vmi_locate(vm, network, 'veth0')
    vmi_out = None
    if arguments.outbound:
        outbound_name = build_network_name(arguments.project,
                                           arguments.outbound)
        vmi_out, project = provisioner.vmi_locate(vm, outbound_name, 'veth1')

    manager.namespace_init(arguments.daemon)
    ifname = manager.interface_update(arguments.daemon, vmi, 'veth0')
    interface_register(vm, vmi, ifname, project=project)

    vmi_out_kwargs = {}
    if vmi_out:
        ifname = manager.interface_update(arguments.daemon, vmi_out, 'veth1')
        interface_register(vm, vmi_out, ifname, project=project)
        vmi_out_kwargs = {'vmi_out': vmi_out, 'ifname_out': ifname}

    single_interface = (arguments.outbound is None)
    ip_prefix = provisioner.get_interface_ip_prefix(vmi)
    manager.interface_config(arguments.daemon,
                             'veth0',
                             advertise_default=single_interface,
                             ip_prefix=ip_prefix)
    if vmi_out:
        manager.interface_config(arguments.daemon, 'veth1')
示例#13
0
def setup(pod_namespace, pod_name, docker_id, retry=True):
    """
    project: pod_namespace
    network: pod_name
    netns: docker_id{12}
    """

    # Kubelet::createPodInfraContainer ensures that State.Pid is set
    pid = docker_get_pid(docker_id)
    if pid == 0:
        raise Exception('Unable to read State.Pid')

    short_id = docker_id[0:12]

    if not os.path.exists('/var/run/netns'):
        os.mkdir('/var/run/netns')

    Shell.run('ln -sf /proc/%d/ns/net /var/run/netns/%s' % (pid, short_id))

    manager = LxcManager()

    if opt_net_mode == 'none':
        instance_ifname = 'veth0'
    else:
        instance_ifname = 'eth0'

    uid, podName = getDockerPod(docker_id)
    podInfo = None
    podState = None
    for i in range(0, 30):
        podInfo = getPodInfo(pod_namespace, podName)
        if podInfo is None:
            return False
        if 'hostNetwork' in podInfo['spec'] and \
           podInfo['spec']['hostNetwork']:
            return True
        if 'annotations' in podInfo["metadata"] and \
           'opencontrail.org/pod-state' in podInfo["metadata"]["annotations"]:
            podState = json.loads(
                podInfo["metadata"]["annotations"]
                ["opencontrail.org/pod-state"])
            break
        if not retry:
            return False
        time.sleep(1)

    # The lxc_manager uses the mac_address to setup the container interface.
    # Additionally the ip-address, prefixlen and gateway are also used.
    if podState is None:
        logging.error('No annotations in pod %s', podInfo["metadata"]["name"])
        return False

    nic_uuid = podState["uuid"]
    mac_address = podState["macAddress"]
    if opt_net_mode == 'none':
        ifname = manager.create_interface(short_id, instance_ifname,
                                          mac_address)
    else:
        ifname = manager.move_interface(short_id, pid, mac_address)

    api = ContrailVRouterApi()
    api.add_port(uid, nic_uuid, ifname, mac_address,
                 port_type='NovaVMPort',
                 display_name=podName,
                 hostname=podName+'.'+pod_namespace)

    ip_address = podState["ipAddress"]
    gateway = podState["gateway"]
    Shell.run('ip netns exec %s ip addr add %s/32 peer %s dev %s' %
              (short_id, ip_address, gateway, instance_ifname))
    Shell.run('ip netns exec %s ip route add default via %s' %
              (short_id, gateway))
    Shell.run('ip netns exec %s ip link set %s up' %
              (short_id, instance_ifname))
    return True
示例#14
0
def setup(pod_namespace, pod_name, docker_id):
    """
    project: pod_namespace
    network: pod_name
    netns: docker_id{12}
    """
    client = ContrailClient()

    # Kubelet::createPodInfraContainer ensures that State.Pid is set
    pid = docker_get_pid(docker_id)
    if pid == 0:
        raise Exception('Unable to read State.Pid')

    short_id = docker_id[0:11]

    if not os.path.exists('/var/run/netns'):
        os.mkdir('/var/run/netns')

    Shell.run('ln -sf /proc/%d/ns/net /var/run/netns/%s' % (pid, short_id))

    manager = LxcManager()

    if client._net_mode == 'none':
        instance_ifname = 'veth0'
    else:
        instance_ifname = 'eth0'

    uid, podName = getDockerPod(docker_id)

    podInfo = None
    for i in range(0, 120):
        podInfo = getPodInfo(podName)
        if 'annotations' in podInfo["metadata"] and \
           'nic_uuid' in podInfo["metadata"]["annotations"]:
            break
        time.sleep(1)
    
    # The lxc_manager uses the mac_address to setup the container interface.
    # Additionally the ip-address, prefixlen and gateway are also used.
    if not 'annotations' in podInfo["metadata"] or not 'nic_uuid' in podInfo["metadata"]["annotations"]:
        logging.error('No annotations in pod %s', podInfo["metadata"]["name"])
        sys.exit(1)


    podAnnotations = podInfo["metadata"]["annotations"]
    nic_uuid = podAnnotations["nic_uuid"]
    mac_address = podAnnotations["mac_address"]
    if client._net_mode == 'none':
        ifname = manager.create_interface(short_id, instance_ifname,
                                          mac_address)
    else:
        ifname = manager.move_interface(short_id, pid, instance_ifname,
                                        mac_address)

    api = ContrailVRouterApi()
    api.add_port(uid, nic_uuid, ifname, mac_address,
                 port_type='NovaVMPort',
                 display_name=podName,
                 hostname=podName+'.'+pod_namespace)

    ip_address = podAnnotations["ip_address"]
    gateway = podAnnotations["gateway"]
    Shell.run('ip netns exec %s ip addr add %s/32 peer %s dev %s' % \
              (short_id, ip_address, gateway, instance_ifname))
    Shell.run('ip netns exec %s ip route add default via %s' % \
              (short_id, gateway))
    Shell.run('ip netns exec %s ip link set %s up' %
              (short_id, instance_ifname))
示例#15
0
def setup(pod_namespace, pod_name, docker_id):
    """
    project: pod_namespace
    network: pod_name
    netns: docker_id{12}
    """
    client = ContrailClient()

    # Kubelet::createPodInfraContainer ensures that State.Pid is set
    pid = docker_get_pid(docker_id)
    if pid == 0:
        raise Exception('Unable to read State.Pid')

    short_id = docker_id[0:11]

    if not os.path.exists('/var/run/netns'):
        os.mkdir('/var/run/netns')

    Shell.run('ln -sf /proc/%d/ns/net /var/run/netns/%s' % (pid, short_id))

    manager = LxcManager()

    if client._net_mode == 'none':
        instance_ifname = 'veth0'
    else:
        instance_ifname = 'eth0'

    uid, podName = getDockerPod(docker_id)
    podInfo = None
    for i in range(0, 120):
        podInfo = getPodInfo(pod_namespace, podName)
        if 'annotations' in podInfo["metadata"] and \
           'nic_uuid' in podInfo["metadata"]["annotations"]:
            break
        time.sleep(1)
    
    # The lxc_manager uses the mac_address to setup the container interface.
    # Additionally the ip-address, prefixlen and gateway are also used.
    if not 'annotations' in podInfo["metadata"] or not 'nic_uuid' in podInfo["metadata"]["annotations"]:
        logging.error('No annotations in pod %s', podInfo["metadata"]["name"])
        sys.exit(1)


    podAnnotations = podInfo["metadata"]["annotations"]
    nic_uuid = podAnnotations["nic_uuid"]
    mac_address = podAnnotations["mac_address"]
    if client._net_mode == 'none':
        ifname = manager.create_interface(short_id, instance_ifname,
                                          mac_address)
    else:
        ifname = manager.move_interface(short_id, pid, instance_ifname,
                                        mac_address)

    api = ContrailVRouterApi()
    api.add_port(uid, nic_uuid, ifname, mac_address,
                 port_type='NovaVMPort',
                 display_name=podName,
                 hostname=podName+'.'+pod_namespace)

    ip_address = podAnnotations["ip_address"]
    gateway = podAnnotations["gateway"]
    Shell.run('ip netns exec %s ip addr add %s/32 peer %s dev %s' % \
              (short_id, ip_address, gateway, instance_ifname))
    Shell.run('ip netns exec %s ip route add default via %s' % \
              (short_id, gateway))
    Shell.run('ip netns exec %s ip link set %s up' %
              (short_id, instance_ifname))
    # TX checksum is broken on Fedora 21 testbed.
    # This may be an issue with kernel 3.17 or veth-pair code.
    if platform.linux_distribution()[0:2] == ('Fedora', '21'):
        Shell.run('nsenter -n -t %d ethtool -K %s tx off' % (pid, instance_ifname))
def main():
    parser = argparse.ArgumentParser()
    defaults = {
        'api-server': '127.0.0.1',
        'api-port': 8082,
        'project': 'default-domain:default-project',
        'network': 'default-network',
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("-n", "--network", help="Primary network")
    parser.add_argument("--project", help="Network project")
    parser.add_argument("--start",
                        action='store_true',
                        help="Create namespace")
    parser.add_argument("--stop", action='store_true', help="Delete namespace")
    parser.add_argument("container_id",
                        metavar='container-id',
                        help="Container ID")

    args = parser.parse_args(sys.argv[1:])
    if not args.start and not args.stop:
        print "Please specify --start or --stop action"
        sys.exit(1)

    manager = LxcManager()
    provisioner = Provisioner(api_server=args.api_server,
                              api_port=args.api_port)
    instance_name = '%s-%s' % (socket.getfqdn(), args.container_id)
    pid_str = subprocess.check_output(
        'docker inspect -f \'{{.State.Pid}}\' %s' % args.container_id,
        shell=True)
    pid = int(pid_str)

    subprocess.check_output('ln -sf /proc/%d/ns/net /var/run/netns/%s' %
                            (pid, args.container_id),
                            shell=True)

    if args.start:
        vm = provisioner.virtual_machine_locate(instance_name)
        network = build_network_name(args.project, args.network)
        vmi = provisioner.vmi_locate(vm, network, 'veth0')
        ifname = manager.create_interface(args.container_id, 'veth0', vmi)
        interface_register(vm, vmi, ifname)
        subprocess.check_output('ip netns exec %s dhclient veth0' %
                                args.container_id,
                                shell=True)
    elif args.stop:
        vm = provisioner.virtual_machine_lookup(instance_name)

        vmi_list = vm.get_virtual_machine_interfaces()
        for ref in vmi_list:
            uuid = ref['uuid']
            interface_unregister(uuid)

        manager.clear_interfaces(args.container_id)

        for ref in vmi_list:
            provisioner.vmi_delete(ref['uuid'])

        provisioner.virtual_machine_delete(vm)
        subprocess.check_output('ip netns delete %s' % args.container_id,
                                shell=True)