Beispiel #1
0
def _get_nics(vm_):
    '''
    Create network interfaces on appropriate LANs as defined in cloud profile.
    '''
    nics = []
    if 'public_lan' in vm_:
        firewall_rules = []
        # Set LAN to public if it already exists, otherwise create a new
        # public LAN.
        lan_id = set_public_lan(int(vm_['public_lan']))
        if 'public_firewall_rules' in vm_:
            firewall_rules = _get_firewall_rules(vm_['public_firewall_rules'])
        nics.append(NIC(lan=lan_id,
                        name='public',
                        firewall_rules=firewall_rules))

    if 'private_lan' in vm_:
        firewall_rules = []
        if 'private_firewall_rules' in vm_:
            firewall_rules = _get_firewall_rules(vm_['private_firewall_rules'])
        nic = NIC(lan=int(vm_['private_lan']),
                  name='private',
                  firewall_rules=firewall_rules)
        if 'nat' in vm_:
            nic.nat = vm_['nat']
        nics.append(nic)
    return nics
def describe_datacenter(client):
    """ Creates a detailed description of the Datacenter according to the requirements"""
    # Define a public NIC
    public_nic = NIC(name=PUBLIC_NIC_NAME, dhcp=True, lan=1, nat=False)

    # Define a private NIC
    private_nic = NIC(name=PRIVATE_NIC_NAME, dhcp=True, lan=2)

    # get existing image with specific name
    images = find_images(client=client,
                         name=UBUNTU_IMAGE_NAME,
                         location=LOCATION)
    if images:
        ubuntu_image = images[0]
    else:
        raise Exception("There are no existing Ubuntu images")

    # Define a volume for backend
    backend_volume = Volume(name='Backend Volume',
                            size=20,
                            image=ubuntu_image['id'],
                            image_password='******',
                            ssh_keys=[get_public_key()],
                            availability_zone='ZONE_3')

    # Define volume for frontend
    frontend_volume = Volume(name='Data Volume 1',
                             size=20,
                             image=ubuntu_image['id'],
                             image_password='******',
                             ssh_keys=[get_public_key()],
                             availability_zone='ZONE_3')

    # Define a server with associated NICs and volumes
    backend_server = Server(name=BACKEND_NAME,
                            ram=DEFAULT_RAM_VALUE,
                            cores=DEFAULT_CORES_VALUES,
                            cpu_family='INTEL_XEON',
                            nics=[private_nic],
                            create_volumes=[backend_volume])

    # Define a server with associated NICs and volumes
    frontend_server = Server(name=FRONTEND_NAME,
                             ram=DEFAULT_RAM_VALUE,
                             cores=DEFAULT_CORES_VALUES,
                             cpu_family='INTEL_XEON',
                             nics=[public_nic, private_nic],
                             create_volumes=[frontend_volume])

    # Define a data center with the server
    datacenter = Datacenter(name=DATACENTER_NAME,
                            description="Yulia's test assignment datacenter",
                            location=LOCATION,
                            servers=[frontend_server, backend_server])

    return datacenter
    def setUpClass(cls):
        cls.resource = resource()
        cls.client = ProfitBricksService(username=configuration.USERNAME,
                                         password=configuration.PASSWORD,
                                         headers=configuration.HEADERS)

        # Create test datacenter.
        cls.datacenter = cls.client.create_datacenter(datacenter=Datacenter(
            **cls.resource['datacenter']))
        cls.client.wait_for_completion(cls.datacenter)

        # Create test LAN.
        cls.lan = cls.client.create_lan(datacenter_id=cls.datacenter['id'],
                                        lan=LAN(**cls.resource['lan']))
        cls.client.wait_for_completion(cls.lan)

        # Create test server.
        cls.server = cls.client.create_server(
            datacenter_id=cls.datacenter['id'],
            server=Server(**cls.resource['server']))
        cls.client.wait_for_completion(cls.server)

        # Create test NIC1.
        nic1 = NIC(**cls.resource['nic'])
        nic1.lan = cls.lan['id']
        cls.nic1 = cls.client.create_nic(datacenter_id=cls.datacenter['id'],
                                         server_id=cls.server['id'],
                                         nic=nic1)
        cls.client.wait_for_completion(cls.nic1)

        # Create test Firewall Rule
        fwrule = FirewallRule(**cls.resource['fwrule'])
        cls.fwrule = cls.client.create_firewall_rule(
            datacenter_id=cls.datacenter['id'],
            server_id=cls.server['id'],
            nic_id=cls.nic1['id'],
            firewall_rule=fwrule)
        cls.client.wait_for_completion(cls.fwrule)

        # Create test Firewall Rule 2
        fwrule2 = FirewallRule(**cls.resource['fwrule'])
        fwrule2.port_range_start = 8080
        fwrule2.port_range_end = 8080
        fwrule2.name = "8080"
        cls.fwrule2 = cls.client.create_firewall_rule(
            datacenter_id=cls.datacenter['id'],
            server_id=cls.server['id'],
            nic_id=cls.nic1['id'],
            firewall_rule=fwrule2)
        cls.client.wait_for_completion(cls.fwrule2)
Beispiel #4
0
    def test_create_complex_lan(self):
        resource = NIC(**self.resource['nic'])

        nic1 = self.client.create_nic(
            datacenter_id=self.datacenter['id'],
            server_id=self.server['id'],
            nic=resource)
        self.client.wait_for_completion(nic1)
        self.assertFalse(nic1['properties']['nat'])
        self.assertEqual(nic1['properties']['name'], 'Python SDK Test')
        self.assertTrue(nic1['properties']['dhcp'])
        self.assertEqual(nic1['properties']['lan'], 1)
        self.assertTrue(nic1['properties']['firewallActive'])

        nics = [nic1['id']]
        lan = LAN(nics=nics, **self.resource['lan'])

        response = self.client.create_lan(
            datacenter_id=self.datacenter['id'],
            lan=lan)
        self.client.wait_for_completion(response)

        self.assertEqual(response['type'], 'lan')
        self.assertEqual(response['properties']['name'], self.resource['lan']['name'])
        self.assertTrue(response['properties']['public'])
Beispiel #5
0
def create_network_interfaces(conn, datacenter_id, server_id, vm_):
    '''
    Create network interface on appropriate LAN as defined in cloud profile.
    '''
    lans = {}

    if 'public_lan' in vm_:
        lans['public_lan'] = vm_['public_lan']

    if 'private_lan' in vm_:
        lans['private_lan'] = vm_['private_lan']

    for lan, lan_id in six.iteritems(lans):
        response = None
        nic = NIC(lan=lan_id, name=lan.split('_')[0])
        try:
            response = conn.create_nic(datacenter_id=datacenter_id,
                                       server_id=server_id,
                                       nic=nic)
            _wait_for_completion(conn, response, get_wait_timeout(vm_),
                                 "create_nic")
            log.info('Cloud VM {0} connected to LAN ID {1}'.format(
                vm_['name'], lan_id))
        except Exception as exc:
            log.error(
                'Error creating network interface on VM {0} connected to LAN '
                '{1}\n\nThe following exception was thrown by the '
                'profitbricks library when trying to run the initial '
                'deployment: \n{2}'.format(vm_['name'], lan_id, exc.message),
                # Show the traceback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG)

    return True
Beispiel #6
0
def _get_nics(vm_):
    """
    Create network interfaces on appropriate LANs as defined in cloud profile.
    """
    nics = []
    if "public_lan" in vm_:
        firewall_rules = []
        # Set LAN to public if it already exists, otherwise create a new
        # public LAN.
        if "public_firewall_rules" in vm_:
            firewall_rules = _get_firewall_rules(vm_["public_firewall_rules"])
        nic = NIC(
            lan=set_public_lan(int(vm_["public_lan"])),
            name="public",
            firewall_rules=firewall_rules,
        )
        if "public_ips" in vm_:
            nic.ips = _get_ip_addresses(vm_["public_ips"])
        nics.append(nic)

    if "private_lan" in vm_:
        firewall_rules = []
        if "private_firewall_rules" in vm_:
            firewall_rules = _get_firewall_rules(vm_["private_firewall_rules"])
        nic = NIC(lan=int(vm_["private_lan"]),
                  name="private",
                  firewall_rules=firewall_rules)
        if "private_ips" in vm_:
            nic.ips = _get_ip_addresses(vm_["private_ips"])
        if "nat" in vm_ and "private_ips" not in vm_:
            nic.nat = vm_["nat"]
        nics.append(nic)
    return nics
Beispiel #7
0
 def test_create_failure(self):
     try:
         nic = NIC(name=self.resource['nic']['name'])
         self.client.create_nic(
             datacenter_id=self.datacenter['id'],
             server_id=self.server['id'],
             nic=nic)
     except PBError as e:
         self.assertIn(self.resource['missing_attribute_error'] % 'lan',
                       e.content[0]['message'])
    def setUpClass(self):
        self.resource = resource()
        self.client = ProfitBricksService(
            username=configuration.USERNAME,
            password=configuration.PASSWORD,
            headers=configuration.HEADERS)

        # Create test datacenter.
        self.datacenter = self.client.create_datacenter(
            datacenter=Datacenter(**self.resource['datacenter']))
        wait_for_completion(self.client, self.datacenter, 'create_datacenter')

        # Create test LAN.
        self.lan = self.client.create_lan(
            datacenter_id=self.datacenter['id'],
            lan=LAN(**self.resource['lan']))
        wait_for_completion(self.client, self.lan, 'create_lan')

        # Create test server.
        self.server = self.client.create_server(
            datacenter_id=self.datacenter['id'],
            server=Server(**self.resource['server']))
        wait_for_completion(self.client, self.server, 'create_server')

        # Create test NIC1.
        nic1 = NIC(**self.resource['nic'])
        nic1.lan = self.lan['id']
        self.nic1 = self.client.create_nic(
            datacenter_id=self.datacenter['id'],
            server_id=self.server['id'],
            nic=nic1)
        wait_for_completion(self.client, self.nic1, 'create_nic1')

        # Create test NIC2.
        nic2 = NIC(**self.resource['nic'])
        nic2.lan = self.lan['id']
        self.nic2 = self.client.create_nic(
            datacenter_id=self.datacenter['id'],
            server_id=self.server['id'],
            nic=nic2)
        wait_for_completion(self.client, self.nic2, 'create_nic2')
def create_nic(module, profitbricks):
    """
    Creates a NIC.

    module : AnsibleModule object
    profitbricks: authenticated profitbricks object.

    Returns:
        True if the nic creates, false otherwise
    """
    datacenter = module.params.get('datacenter')
    server = module.params.get('server')
    lan = module.params.get('lan')
    nat = module.params.get('nat')
    name = module.params.get('name')
    wait = module.params.get('wait')
    wait_timeout = module.params.get('wait_timeout')

    # Locate UUID for Datacenter
    if not (uuid_match.match(datacenter)):
        datacenter_list = profitbricks.list_datacenters()
        for d in datacenter_list['items']:
            dc = profitbricks.get_datacenter(d['id'])
            if datacenter == dc['properties']['name']:
                datacenter = d['id']
                break

    # Locate UUID for Server
    if not (uuid_match.match(server)):
        server_list = profitbricks.list_servers(datacenter)
        for s in server_list['items']:
            if server == s['properties']['name']:
                server = s['id']
                break

    try:
        n = NIC(name=name, lan=lan, nat=nat)

        nic_response = profitbricks.create_nic(datacenter, server, n)

        if wait:
            _wait_for_completion(profitbricks, nic_response, wait_timeout,
                                 'create_nic')

        # Refresh NIC properties
        nic_response = profitbricks.get_nic(datacenter, server,
                                            nic_response['id'])

        return nic_response

    except Exception as e:
        module.fail_json(msg="failed to create the NIC: %s" % str(e))
def getNICObject(defdict=None):
    if not defdict or not isinstance(defdict, dict):
        raise ValueError("argument 'defdict' must be non-empty dict")
    # AARGH! some of NIC's fields have different names -> need to convert manually
    # so make a copy and let source as is
    props = dict()
    for k, v in defdict['properties'].items():
        if k == 'firewallActive':
            props['firewall_active'] = v
            continue
        if k == 'firewallrules':
            # this needs more to do:
            # if we have rules we must get rules objects too, irrespective of being active
            if v:
                rules = [getFwRuleObject(rule) for rule in v]
                props['firewall_rules'] = rules
                continue
        props[k] = v
    # end for(defdict)
    apiobj = NIC(**props)
    return apiobj
Beispiel #11
0
    def setUpClass(cls):
        cls.resource = resource()
        cls.client = ProfitBricksService(
            username=configuration.USERNAME,
            password=configuration.PASSWORD,
            headers=configuration.HEADERS)

        # Create test datacenter.
        cls.datacenter = cls.client.create_datacenter(
            datacenter=Datacenter(**cls.resource['datacenter']))
        cls.client.wait_for_completion(cls.datacenter)

        # Create test LAN.
        cls.lan = cls.client.create_lan(
            datacenter_id=cls.datacenter['id'],
            lan=LAN(name=cls.resource['lan']['name'], public=False))
        cls.client.wait_for_completion(cls.lan)

        # Create test server.
        cls.server = cls.client.create_server(
            datacenter_id=cls.datacenter['id'],
            server=Server(**cls.resource['server']))
        cls.client.wait_for_completion(cls.server)

        # Create test NIC1.
        nic1 = NIC(**cls.resource['nic'])
        nic1.lan = cls.lan['id']
        cls.ips = ['10.0.0.1']
        nic1.ips = cls.ips
        cls.nic1 = cls.client.create_nic(
            datacenter_id=cls.datacenter['id'],
            server_id=cls.server['id'],
            nic=nic1)
        cls.client.wait_for_completion(cls.nic1)

        # Create test NIC2.
        nic2 = NIC(**cls.resource['nic'])
        nic2.lan = cls.lan['id']
        cls.nic2 = cls.client.create_nic(
            datacenter_id=cls.datacenter['id'],
            server_id=cls.server['id'],
            nic=nic2)
        cls.client.wait_for_completion(cls.nic2)
    def test_create_composite(self):
        fwrule = FirewallRule(**self.resource['fwrule'])
        nic = NIC(firewall_rules=[fwrule], **self.resource['nic'])
        volume = Volume(image=self.image['id'],
                        image_password='******',
                        ssh_keys=['ssh-rsa AAAAB3NzaC1'],
                        **self.resource['volume'])
        volume.availability_zone = 'ZONE_3'

        server = Server(nics=[nic],
                        create_volumes=[volume],
                        **self.resource['server'])

        composite_server = self.client.create_server(
            datacenter_id=self.datacenter['id'], server=server)
        self.client.wait_for_completion(composite_server, timeout=600)

        composite_server = self.client.get_server(
            datacenter_id=self.datacenter['id'],
            server_id=composite_server['id'])

        assertRegex(self, composite_server['id'], self.resource['uuid_match'])
        self.assertEqual(composite_server['properties']['name'],
                         self.resource['server']['name'])
        self.assertEqual(composite_server['properties']['cores'],
                         self.resource['server']['cores'])
        self.assertEqual(composite_server['properties']['ram'],
                         self.resource['server']['ram'])
        self.assertEqual(composite_server['properties']['availabilityZone'],
                         'ZONE_1')
        self.assertIn(composite_server['properties']['vmState'],
                      self.resource['vm_states'])
        self.assertGreater(
            len(composite_server['entities']['volumes']['items']), 0)
        self.assertGreater(len(composite_server['entities']['nics']['items']),
                           0)
Beispiel #13
0
    def setUpClass(self):
        self.resource = resource()
        self.client = ProfitBricksService(
            username=configuration.USERNAME,
            password=configuration.PASSWORD,
            headers=configuration.HEADERS)

        # Create test datacenter.
        self.datacenter = self.client.create_datacenter(
            datacenter=Datacenter(**self.resource['datacenter']))
        self.client.wait_for_completion(self.datacenter)

        # Create test LAN.
        self.lan = self.client.create_lan(
            datacenter_id=self.datacenter['id'],
            lan=LAN(**self.resource['lan']))
        self.client.wait_for_completion(self.lan)

        # Create test server.
        self.server = self.client.create_server(
            datacenter_id=self.datacenter['id'],
            server=Server(**self.resource['server']))
        self.client.wait_for_completion(self.server)

        # Create test NIC1.
        nic1 = NIC(**self.resource['nic'])
        nic1.lan = self.lan['id']
        self.nic1 = self.client.create_nic(
            datacenter_id=self.datacenter['id'],
            server_id=self.server['id'],
            nic=nic1)
        self.client.wait_for_completion(self.nic1)

        # Create test NIC2.
        nic2 = NIC(**self.resource['nic'])
        nic2.lan = self.lan['id']
        self.nic2 = self.client.create_nic(
            datacenter_id=self.datacenter['id'],
            server_id=self.server['id'],
            nic=nic2)
        self.client.wait_for_completion(self.nic2)
Beispiel #14
0
def main(argv=None):
    '''Parse command line options and create a server/volume composite.'''

    if argv is None:
        argv = sys.argv
    else:
        sys.argv.extend(argv)

    program_name = os.path.basename(sys.argv[0])
    program_version = "v%s" % __version__
    program_build_date = str(__updated__)
    program_version_message = '%%(prog)s %s (%s)' % (program_version,
                                                     program_build_date)
    program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
    program_license = '''%s

  Created by J. Buchhammer on %s.
  Copyright 2016 ProfitBricks GmbH. All rights reserved.

  Licensed under the Apache License 2.0
  http://www.apache.org/licenses/LICENSE-2.0

  Distributed on an "AS IS" basis without warranties
  or conditions of any kind, either express or implied.

USAGE
''' % (program_shortdesc, str(__date__))

    try:
        # Setup argument parser
        parser = ArgumentParser(description=program_license,
                                formatter_class=RawDescriptionHelpFormatter)
        parser.add_argument('-u', '--user', dest='user', help='the login name')
        parser.add_argument('-p', '--password', dest='password',
                            help='the login password')
        parser.add_argument('-L', '--Login', dest='loginfile', default=None,
                            help='the login file to use')
        parser.add_argument('-d', '--datacenterid', dest='datacenterid',
                            required=True, default=None,
                            help='datacenter of the new server')
        parser.add_argument('-l', '--lanid', dest='lanid', required=True,
                            default=None, help='LAN of the new server')
        parser.add_argument('-n', '--name', dest='servername',
                            default="SRV_"+datetime.now().isoformat(),
                            help='name of the new server')
        parser.add_argument('-c', '--cores', dest='cores', type=int,
                            default=2, help='CPU cores')
        parser.add_argument('-r', '--ram', dest='ram', type=int, default=4,
                            help='RAM in GB')
        parser.add_argument('-s', '--storage', dest='storage', type=int,
                            default=4, help='storage in GB')
        parser.add_argument('-b', '--boot', dest='bootdevice', default="HDD",
                            help='boot device')
        parser.add_argument('-i', '--imageid', dest='imageid', default=None,
                            help='installation image')
        parser.add_argument('-P', '--imagepassword', dest='imgpassword',
                            default=None, help='the image password')
        parser.add_argument('-v', '--verbose', dest="verbose", action="count",
                            help="set verbosity level [default: %(default)s]")
        parser.add_argument('-V', '--version', action='version',
                            version=program_version_message)

        # Process arguments
        args = parser.parse_args()
        global verbose
        verbose = args.verbose
        dc_id = args.datacenterid
        lan_id = args.lanid
        servername = args.servername

        if verbose > 0:
            print("Verbose mode on")
            print("start {} with args {}".format(program_name, str(args)))

        # Test images (location de/fra)
        # CDROM: 7fc885b3-c9a6-11e5-aa10-52540005ab80   # debian-8.3.0-amd64-netinst.iso
        # HDD:   28007a6d-c88a-11e5-aa10-52540005ab80   # CentOS-7-server-2016-02-01
        hdimage = args.imageid
        cdimage = None
        if args.bootdevice == "CDROM":
            hdimage = None
            cdimage = args.imageid
        print("using boot device {} with image {}"
              .format(args.bootdevice, args.imageid))

        (user, password) = getLogin(args.loginfile, args.user, args.password)
        if user is None or password is None:
            raise ValueError("user or password resolved to None")
        pbclient = ProfitBricksService(user, password)

        first_nic = NIC(name="local", ips=[], dhcp=True, lan=lan_id)
        volume = Volume(name=servername+"-Disk", size=args.storage,
                        image=hdimage, image_password=args.imgpassword)
        server = Server(name=servername, cores=args.cores, ram=args.ram*1024,
                        create_volumes=[volume], nics=[first_nic],
                        boot_cdrom=cdimage)
        print("creating server..")
        if verbose > 0:
            print("SERVER: {}".format(str(server)))
        response = pbclient.create_server(dc_id, server)
        print("wait for provisioning..")
        wait_for_request(pbclient, response["requestId"])
        server_id = response['id']
        print("Server provisioned with ID {}".format(server_id))
        nics = pbclient.list_nics(dc_id, server_id, 1)
        # server should have exactly one nic, but we only test empty nic list
        if len(nics['items']) == 0:
            raise CLIError("No NICs found for newly created server {}"
                           .format(server_id))
        nic0 = nics['items'][0]
        if verbose > 0:
            print("NIC0: {}".format(str(nic0)))
        (nic_id, nic_mac) = (nic0['id'], nic0['properties']['mac'])
        print("NIC of new Server has ID {} and MAC {}".format(nic_id, nic_mac))
        print("{} finished w/o errors".format(program_name))
        return 0

    except KeyboardInterrupt:
        # handle keyboard interrupt #
        return 0
    except Exception:
        traceback.print_exc()
        sys.stderr.write("\n" + program_name + ":  for help use --help\n")
        return 2
Beispiel #15
0
def main(argv=None):
    '''Command line options.'''

    if argv is None:
        argv = sys.argv
    else:
        sys.argv.extend(argv)

    program_name = os.path.basename(sys.argv[0])
    program_version = "v%s" % __version__
    program_build_date = str(__updated__)
    program_version_message = '%%(prog)s %s (%s)' % (program_version,
                                                     program_build_date)
    program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
    program_license = '''%s

  Created by Jürgen Buchhammer on %s.
  Copyright 2016 ProfitBricks GmbH. All rights reserved.

  Licensed under the Apache License 2.0
  http://www.apache.org/licenses/LICENSE-2.0

  Distributed on an "AS IS" basis without warranties
  or conditions of any kind, either express or implied.

USAGE
''' % (program_shortdesc, str(__date__))

    try:
        # Setup argument parser
        parser = ArgumentParser(description=program_license,
                                formatter_class=RawDescriptionHelpFormatter)
        parser.add_argument('-u', '--user', dest='user', help='the login name')
        parser.add_argument('-p',
                            '--password',
                            dest='password',
                            help='the login password')
        parser.add_argument('-L',
                            '--Login',
                            dest='loginfile',
                            default=None,
                            help='the login file to use')
        parser.add_argument('-t',
                            '--type',
                            dest='metatype',
                            default="OVF",
                            help='type of VM meta data')
        parser.add_argument('-m',
                            '--metadata',
                            dest='metafile',
                            required=True,
                            default=None,
                            help='meta data file')
        parser.add_argument('-d',
                            '--datacenterid',
                            dest='datacenterid',
                            default=None,
                            help='datacenter of the new server')
        parser.add_argument('-D',
                            '--DCname',
                            dest='dcname',
                            default=None,
                            help='new datacenter name')
        parser.add_argument('-l',
                            '--location',
                            dest='location',
                            default=None,
                            help='location for new datacenter')
        parser.add_argument('-v',
                            '--verbose',
                            dest="verbose",
                            action="count",
                            default=0,
                            help="set verbosity level [default: %(default)s]")
        parser.add_argument('-V',
                            '--version',
                            action='version',
                            version=program_version_message)

        # Process arguments
        args = parser.parse_args()
        global verbose
        verbose = args.verbose

        if verbose > 0:
            print("Verbose mode on")
            print("start {} with args {}".format(program_name, str(args)))

        (user, password) = getLogin(args.loginfile, args.user, args.password)
        if user is None or password is None:
            raise ValueError("user or password resolved to None")
        pbclient = ProfitBricksService(user, password)

        if args.metatype == 'OVF':
            metadata = OFVData(args.metafile)
            metadata.parse()
        else:
            sys.stderr.write("Metadata type '{}' is not supported".format(
                args.metatype))
            return 1

        # we need the DC first to have the location defined
        dc_id = None
        if args.datacenterid is None:
            if args.dcname is None or args.location is None:
                sys.stderr.write(
                    "Either '-d <id>' or '-D <name> -l <loc>'  must be specified"
                )
                return 1
            # else: we will create the DC later after parsing the meta data
        else:
            dc_id = args.datacenterid

        if dc_id is None:
            location = args.location
            dc = Datacenter(name=args.dcname,
                            location=location,
                            description="created by pb_importVM")
            print("create new DC {}".format(str(dc)))
            response = pbclient.create_datacenter(dc)
            dc_id = response['id']
            result = wait_for_request(pbclient, response['requestId'])
            print("wait loop returned {}".format(result))
        else:
            dc = pbclient.get_datacenter(dc_id)
            location = dc['properties']['location']
            print("use existing DC {} in location {}".format(
                dc['properties']['name'], location))

        # check if images exist
        for disk in metadata.disks:
            disk_name = disk['file']
            images = get_disk_image_by_name(pbclient, location, disk_name)
            if len(images) == 0:
                raise ValueError(
                    "No HDD image with name '{}' found in location {}".format(
                        disk_name, location))
            if len(images) > 1:
                raise ValueError(
                    "Ambigous image name '{}' in location {}".format(
                        disk_name, location))
            disk['image'] = images[0]['id']

        # now we're ready to create the VM
        # Server
        server = Server(name=metadata.name,
                        cores=metadata.cpus,
                        ram=metadata.ram)
        print("create server {}".format(str(Server)))
        response = pbclient.create_server(dc_id, server)
        srv_id = response['id']
        result = wait_for_request(pbclient, response['requestId'])
        print("wait loop returned {}".format(str(result)))
        # NICs (note that createing LANs may be implicit)
        for nic in metadata.nics:
            dcnic = NIC(name=nic['nic'], lan=nic['lanid'])
            print("create NIC {}".format(str(dcnic)))
            response = pbclient.create_nic(dc_id, srv_id, dcnic)
            nic_id = response['id']
            result = wait_for_request(pbclient, response['requestId'])
            print("wait loop returned {}".format(str(result)))
            response = pbclient.get_nic(dc_id, srv_id, nic_id, 2)
            mac = response['properties']['mac']
            print("dcnic has MAC {} for {}".format(mac, nic_id))
        # end for(nics)
        # Volumes (we use the image name as volume name too
        requests = []
        for disk in metadata.disks:
            dcvol = Volume(name=disk['file'],
                           size=disk['capacity'],
                           image=disk['image'],
                           licence_type=metadata.licenseType)
            print("create Volume {}".format(str(dcvol)))
            response = pbclient.create_volume(dc_id, dcvol)
            requests.append(response['requestId'])
            disk['volume_id'] = response['id']
        # end for(disks)
        if len(requests) != 0:
            result = wait_for_requests(pbclient,
                                       requests,
                                       initial_wait=10,
                                       scaleup=15)
            print("wait loop returned {}".format(str(result)))
        for disk in metadata.disks:
            print("attach volume {}".format(disk))
            response = pbclient.attach_volume(dc_id, srv_id, disk['volume_id'])
            result = wait_for_request(pbclient, response['requestId'])
            print("wait loop returned {}".format(str(result)))
        # end for(disks)

        print("import of VM succesfully finished")
        return 0

    except KeyboardInterrupt:
        # handle keyboard interrupt
        return 0
    except Exception:
        traceback.print_exc()
        sys.stderr.write("\n" + program_name + ":  for help use --help\n")
        return 2
Beispiel #16
0
def _create_machine(module, profitbricks, datacenter, name):
    image = module.params.get('image')
    cores = module.params.get('cores')
    ram = module.params.get('ram')
    volume_size = module.params.get('volume_size')
    bus = module.params.get('bus')
    lan = module.params.get('lan')
    assign_public_ip = module.params.get('assign_public_ip')
    subscription_user = module.params.get('subscription_user')
    subscription_password = module.params.get('subscription_password')
    location = module.params.get('location')
    image = module.params.get('image')
    assign_public_ip = module.boolean(module.params.get('assign_public_ip'))
    wait = module.params.get('wait')
    wait_timeout = module.params.get('wait_timeout')

    try:
        # Generate name, but grab first 10 chars so we don't
        # screw up the uuid match routine.
        v = Volume(
            name=str(uuid.uuid4()).replace('-','')[:10],
            size=volume_size,
            image=image,
            bus=bus)

        volume_response = profitbricks.create_volume(
            datacenter_id=datacenter, volume=v)

        # We're forced to wait on the volume creation since
        # server create relies upon this existing.

        _wait_for_completion(profitbricks, volume_response,
                             wait_timeout, "create_volume")
    except Exception as e:
        module.fail_json(msg="failed to create the new volume: %s" % str(e))

    if assign_public_ip:
        public_found = False

        lans = profitbricks.list_lans(datacenter)
        for lan in lans['items']:
            if lan['properties']['public']:
                public_found = True
                lan = lan['id']

        if not public_found:
            i = LAN(
                name='public',
                public=True)

            lan_response = profitbricks.create_lan(datacenter, i)

            lan = lan_response['id']

            _wait_for_completion(profitbricks, lan_response,
                                 wait_timeout, "_create_machine")

    try:
        n = NIC(
            lan=int(lan)
            )

        nics = [n]

        s = Server(
            name=name,
            ram=ram,
            cores=cores,
            nics=nics,
            boot_volume_id=volume_response['id']
            )

        server_response = profitbricks.create_server(
            datacenter_id=datacenter, server=s)

        if wait:
            _wait_for_completion(profitbricks, server_response,
                                 wait_timeout, "create_virtual_machine")


        return (server_response)
    except Exception as e:
        module.fail_json(msg="failed to create the new server: %s" % str(e))
def _create_machine(module, profitbricks, datacenter, name):
    cores = module.params.get('cores')
    ram = module.params.get('ram')
    cpu_family = module.params.get('cpu_family')
    volume_size = module.params.get('volume_size')
    disk_type = module.params.get('disk_type')
    availability_zone = module.params.get('availability_zone')
    volume_availability_zone = module.params.get('volume_availability_zone')
    image_password = module.params.get('image_password')
    ssh_keys = module.params.get('ssh_keys')
    bus = module.params.get('bus')
    lan = module.params.get('lan')
    nat = module.params.get('nat')
    image = module.params.get('image')
    assign_public_ip = module.boolean(module.params.get('assign_public_ip'))
    wait = module.params.get('wait')
    wait_timeout = module.params.get('wait_timeout')

    nics = []

    if assign_public_ip:
        public_lan = _get_lan_by_id_or_properties(
            profitbricks.list_lans(datacenter)['items'], public=True)

        public_ip_lan_id = public_lan['id'] if public_lan is not None else None

        if public_ip_lan_id is None:
            i = LAN(name='public', public=True)

            lan_response = profitbricks.create_lan(datacenter, i)
            _wait_for_completion(profitbricks, lan_response, wait_timeout,
                                 "_create_machine")

            public_ip_lan_id = lan_response['id']

        nics.append(
            NIC(name=str(uuid4()).replace('-', '')[:10],
                nat=nat,
                lan=int(public_ip_lan_id)))

    if lan is not None:
        matching_lan = _get_lan_by_id_or_properties(
            profitbricks.list_lans(datacenter)['items'], lan, name=lan)

        nics.append(
            NIC(name=str(uuid4()).replace('-', '')[:10],
                nat=nat,
                lan=int(matching_lan['id'])))

    v = Volume(name=str(uuid4()).replace('-', '')[:10],
               size=volume_size,
               image_password=image_password,
               ssh_keys=ssh_keys,
               disk_type=disk_type,
               availability_zone=volume_availability_zone,
               bus=bus)

    try:
        UUID(image)
    except Exception:
        v.image_alias = image
    else:
        v.image = image

    s = Server(
        name=name,
        ram=ram,
        cores=cores,
        cpu_family=cpu_family,
        availability_zone=availability_zone,
        create_volumes=[v],
        nics=nics,
    )

    try:
        create_server_response = profitbricks.create_server(
            datacenter_id=datacenter, server=s)

        _wait_for_completion(profitbricks, create_server_response,
                             wait_timeout, "create_virtual_machine")

        server_response = profitbricks.get_server(
            datacenter_id=datacenter,
            server_id=create_server_response['id'],
            depth=3)
    except Exception as e:
        module.fail_json(msg="failed to create the new server: %s" %
                         to_native(e))
    else:
        server_response['nic'] = server_response['entities']['nics']['items'][
            0]
        return server_response
    def setUpClass(cls):
        cls.resource = resource()
        cls.client = ProfitBricksService(username=configuration.USERNAME,
                                         password=configuration.PASSWORD,
                                         headers=configuration.HEADERS)

        # Create test datacenter.
        cls.datacenter = cls.client.create_datacenter(datacenter=Datacenter(
            **cls.resource['datacenter']))
        cls.client.wait_for_completion(cls.datacenter)

        # Create test volume1.
        cls.volume1 = cls.client.create_volume(
            datacenter_id=cls.datacenter['id'],
            volume=Volume(**cls.resource['volume']))
        cls.client.wait_for_completion(cls.volume1)

        # Create test volume2 (attach volume test).
        cls.volume2 = cls.client.create_volume(
            datacenter_id=cls.datacenter['id'],
            volume=Volume(**cls.resource['volume']))
        cls.client.wait_for_completion(cls.volume2)

        # Create test server.
        server = Server(**cls.resource['server'])
        server.attach_volumes = [cls.volume1['id']]
        cls.server = cls.client.create_server(
            datacenter_id=cls.datacenter['id'], server=server)
        cls.client.wait_for_completion(cls.server)

        # Create test NIC.
        cls.nic = cls.client.create_nic(datacenter_id=cls.datacenter['id'],
                                        server_id=cls.server['id'],
                                        nic=NIC(**cls.resource['nic']))
        cls.client.wait_for_completion(cls.nic)

        # Find an Ubuntu image for testing.
        for item in cls.client.list_images()['items']:
            if (configuration.IMAGE_NAME in item['properties']['name'] and
                    item['properties']['location'] == configuration.LOCATION):
                cls.image = item
        # Find a cdrom image
        images = cls.client.list_images(depth=5)
        usedIndex = 0
        for index, image in enumerate(images['items']):
            if (image['metadata']['state'] == "AVAILABLE"
                    and image['properties']['public'] is True
                    and image['properties']['imageType'] == "CDROM" and
                    image['properties']['location'] == configuration.LOCATION
                    and image['properties']['licenceType'] == "LINUX"):
                if usedIndex == 0:
                    cls.test_image1 = image
                    usedIndex = index
                else:
                    cls.test_image2 = image
                    break
        # Create test cdrom
        cls.cdrom = cls.client.attach_cdrom(datacenter_id=cls.datacenter['id'],
                                            server_id=cls.server['id'],
                                            cdrom_id=cls.test_image1['id'])
        cls.client.wait_for_completion(cls.cdrom)
Beispiel #19
0
"""Create Complex Server
"""

from profitbricks.client import ProfitBricksService  # noqa
from profitbricks.client import Server, NIC, Volume  # noqa

server_id = '700e1cab-99b2-4c30-ba8c-1d273ddba023'
datacenter_id = '700e1cab-99b2-4c30-ba8c-1d273ddba022'
image_id = '226ed8c0-a2fe-11e4-b187-5f1f641608c8'

client = ProfitBricksService(username='******', password='******')

nic1 = NIC(
    name='nic1',
    ips=['10.2.2.5'],
    dhcp='true',
    lan=1,
    firewall_active=True,
)

nic2 = NIC(
    name='nic2',
    ips=['10.2.3.6'],
    dhcp='true',
    lan=1,
    firewall_active=True,
)

volume1 = Volume(name='volume6', size=56, image=image_id, bus='VIRTIO')

volume2 = Volume(name='volume7', size=56, image=image_id, bus='VIRTIO')
def _create_machine(module, profitbricks, datacenter, name):
    cores = module.params.get('cores')
    ram = module.params.get('ram')
    cpu_family = module.params.get('cpu_family')
    volume_size = module.params.get('volume_size')
    disk_type = module.params.get('disk_type')
    availability_zone = module.params.get('availability_zone')
    volume_availability_zone = module.params.get('volume_availability_zone')
    image_password = module.params.get('image_password')
    ssh_keys = module.params.get('ssh_keys')
    bus = module.params.get('bus')
    lan = module.params.get('lan')
    nat = module.params.get('nat')
    assign_public_ip = module.params.get('assign_public_ip')
    subscription_user = module.params.get('subscription_user')
    subscription_password = module.params.get('subscription_password')
    location = module.params.get('location')
    image = module.params.get('image')
    assign_public_ip = module.boolean(module.params.get('assign_public_ip'))
    wait = module.params.get('wait')
    wait_timeout = module.params.get('wait_timeout')

    if assign_public_ip:
        public_found = False

        lans = profitbricks.list_lans(datacenter)
        for lan in lans['items']:
            if lan['properties']['public']:
                public_found = True
                lan = lan['id']

        if not public_found:
            i = LAN(name='public', public=True)

            lan_response = profitbricks.create_lan(datacenter, i)
            _wait_for_completion(profitbricks, lan_response, wait_timeout,
                                 "_create_machine")
            lan = lan_response['id']

    v = Volume(name=str(uuid.uuid4()).replace('-', '')[:10],
               size=volume_size,
               image=image,
               image_password=image_password,
               ssh_keys=ssh_keys,
               disk_type=disk_type,
               availability_zone=volume_availability_zone,
               bus=bus)

    n = NIC(name=str(uuid.uuid4()).replace('-', '')[:10],
            nat=nat,
            lan=int(lan))

    s = Server(
        name=name,
        ram=ram,
        cores=cores,
        cpu_family=cpu_family,
        availability_zone=availability_zone,
        create_volumes=[v],
        nics=[n],
    )

    try:
        create_server_response = profitbricks.create_server(
            datacenter_id=datacenter, server=s)

        _wait_for_completion(profitbricks, create_server_response,
                             wait_timeout, "create_virtual_machine")

        server_response = profitbricks.get_server(
            datacenter_id=datacenter,
            server_id=create_server_response['id'],
            depth=3)
    except Exception as e:
        module.fail_json(msg="failed to create the new server: %s" % str(e))
    else:
        server_response['nic'] = server_response['entities']['nics']['items'][
            0]
        return server_response
fwrule1 = FirewallRule(name='Open SSH port',
                       protocol='TCP',
                       source_mac='01:23:45:67:89:00',
                       port_range_start=22,
                       port_range_end=22)

fwrule2 = FirewallRule(name='Allow PING',
                       protocol='ICMP',
                       icmp_type=8,
                       icmp_code=0)

fw_rules = [fwrule1, fwrule2]

nic1 = NIC(name='nic1',
           ips=['10.2.2.3'],
           dhcp='true',
           lan=1,
           firewall_active=True,
           firewall_rules=fw_rules)

nic2 = NIC(name='nic2',
           ips=['10.2.3.4'],
           dhcp='true',
           lan=1,
           firewall_active=True,
           firewall_rules=fw_rules)

nics = [nic1, nic2]

volume1 = Volume(name='volume1',
                 size=56,
                 image=image_id,
Beispiel #22
0
def create_nic(module, profitbricks):
    """
    Creates a NIC.

    module : AnsibleModule object
    profitbricks: authenticated profitbricks object.

    Returns:
        The NIC instance being created
    """
    datacenter = module.params.get('datacenter')
    server = module.params.get('server')
    lan = module.params.get('lan')
    dhcp = module.params.get('dhcp') or False
    nat = module.params.get('nat') or False
    firewall_active = module.params.get('firewall_active')
    ips = module.params.get('ips')
    name = module.params.get('name')
    wait = module.params.get('wait')
    wait_timeout = module.params.get('wait_timeout')

    # Locate UUID for Datacenter
    if not (uuid_match.match(datacenter)):
        datacenter_list = profitbricks.list_datacenters()
        for d in datacenter_list['items']:
            dc = profitbricks.get_datacenter(d['id'])
            if datacenter == dc['properties']['name']:
                datacenter = d['id']
                break

    # Locate UUID for Server
    if not (uuid_match.match(server)):
        server_list = profitbricks.list_servers(datacenter)
        for s in server_list['items']:
            if server == s['properties']['name']:
                server = s['id']
                break

    nic_list = profitbricks.list_nics(datacenter, server)
    nic = None
    for n in nic_list['items']:
        if name == n['properties']['name']:
            nic = n
            break

    should_change = nic is None

    if module.check_mode:
        module.exit_json(changed=should_change)

    if not should_change:
        return {'changed': should_change, 'nic': nic}

    try:
        n = NIC(name=name,
                lan=lan,
                nat=nat,
                dhcp=dhcp,
                ips=ips,
                firewall_active=firewall_active)

        nic_response = profitbricks.create_nic(datacenter, server, n)

        if wait:
            _wait_for_completion(profitbricks, nic_response, wait_timeout,
                                 'create_nic')

        # Refresh NIC properties
        nic_response = profitbricks.get_nic(datacenter, server,
                                            nic_response['id'])

        return {'changed': True, 'nic': nic_response}

    except Exception as e:
        module.fail_json(msg="failed to create the NIC: %s" % to_native(e))
    def setUpClass(self):
        self.resource = resource()
        self.client = ProfitBricksService(username=configuration.USERNAME,
                                          password=configuration.PASSWORD,
                                          headers=configuration.HEADERS)

        # Create test datacenter.
        self.datacenter = self.client.create_datacenter(datacenter=Datacenter(
            **self.resource['datacenter']))
        self.client.wait_for_completion(self.datacenter)

        # Create test LAN.
        self.lan = self.client.create_lan(datacenter_id=self.datacenter['id'],
                                          lan=LAN(**self.resource['lan']))
        self.client.wait_for_completion(self.lan)

        # Create test server.
        self.server = self.client.create_server(
            datacenter_id=self.datacenter['id'],
            server=Server(**self.resource['server']))
        self.client.wait_for_completion(self.server)

        # Create test NIC1.
        nic1 = NIC(**self.resource['nic'])
        nic1.lan = self.lan['id']
        self.nic1 = self.client.create_nic(datacenter_id=self.datacenter['id'],
                                           server_id=self.server['id'],
                                           nic=nic1)
        self.client.wait_for_completion(self.nic1)

        # Create test NIC2.
        # nic2 = NIC(**self.resource['nic'])
        # nic2.lan = self.lan['id']
        # self.nic2 = self.client.create_nic(
        #     datacenter_id=self.datacenter['id'],
        #     server_id=self.server['id'],
        #     nic=nic2)
        # self.client.wait_for_completion(self.nic2)

        # Create test LoadBalancer
        loadbalancer = LoadBalancer(**self.resource['loadbalancer'])
        loadbalancer.balancednics = [self.nic1['id']]
        self.loadbalancer = self.client.create_loadbalancer(
            datacenter_id=self.datacenter['id'], loadbalancer=loadbalancer)

        self.client.wait_for_completion(self.loadbalancer)

        # Create test LoadBalancer2
        loadbalancer2 = LoadBalancer(**self.resource['loadbalancer'])
        loadbalancer2.name = "Python SDK Test 2"
        self.loadbalancer2 = self.client.create_loadbalancer(
            datacenter_id=self.datacenter['id'], loadbalancer=loadbalancer2)

        self.client.wait_for_completion(self.loadbalancer2)

        # Create test LoadBalancer3
        loadbalancer3 = LoadBalancer(**self.resource['loadbalancer'])
        loadbalancer3.balancednics = [self.nic1['id']]
        loadbalancer3.name = "Python SDK Test 3"
        self.loadbalancer3 = self.client.create_loadbalancer(
            datacenter_id=self.datacenter['id'], loadbalancer=loadbalancer3)

        self.client.wait_for_completion(self.loadbalancer3)