def on_get(self, req, resp, tenant_id): client = req.env['sl_client'] cci = CCIManager(client) params = get_list_params(req) sl_instances = cci.list_instances(**params) if not isinstance(sl_instances, list): sl_instances = [sl_instances] results = [] for instance in sl_instances: results.append({ 'id': instance['id'], 'links': [{ 'href': self.app.get_endpoint_url('compute', req, 'v2_server', server_id=id), 'rel': 'self', }], 'name': instance['hostname'], }) resp.status = 200 resp.body = {'servers': results}
def __init__(self, config, client=None): self.config = config if client is None: client = Client(auth=self.config['auth'], endpoint_url=self.config['endpoint_url']) self.client = client self.ssh = SshKeyManager(client) self.instances = CCIManager(client)
def on_get(self, req, resp, tenant_id, server_id): client = req.env['sl_client'] cci = CCIManager(client) instance = cci.get_instance(server_id, mask=get_virtual_guest_mask()) results = get_server_details_dict(self.app, req, instance) resp.body = {'server': results}
def global_search(search): client = get_client() match_string = '<span class="text-primary">%s</span>' % search term = re.compile(search, re.IGNORECASE) results = [] if 'vm' in app.config['installed_blueprints']: cci = CCIManager(client) # if hostname_regex.match(term): for vm in cci.list_instances(): if term.match(vm['hostname']) or \ term.match(vm.get('primaryIpAddress', '')): text = '%s (%s)' % (vm['fullyQualifiedDomainName'], vm.get('primaryIpAddress', 'No Public IP')) text = term.sub(match_string, text) results.append({ 'label': '<strong>VM:</strong> ' + text, 'value': url_for('vm_module.view', vm_id=vm['id']) }) if 'servers' in app.config['installed_blueprints']: hw = HardwareManager(client) for svr in hw.list_hardware(): if term.match(svr['hostname']) or \ term.match(svr.get('primaryIpAddress', '')): text = '%s (%s)' % (svr['fullyQualifiedDomainName'], svr.get('primaryIpAddress', 'No Public IP')) text = term.sub(match_string, text) results.append({ 'label': '<strong>Server:</strong> ' + text, 'value': url_for('server_module.view', server_id=svr['id']) }) if 'sshkeys' in app.config['installed_blueprints']: ssh = SshKeyManager(client) for key in ssh.list_keys(): if term.match(key['label']) or term.match(key['fingerprint']): text = '%s (%s)' % (key['label'], key['fingerprint']) text = term.sub(match_string, text) results.append({ 'label': '<strong>SSH Key:</strong> ' + text, 'value': url_for('ssh_module.view', key_id=key['id']) }) return results
def on_put(self, req, resp, tenant_id, server_id): client = req.env['sl_client'] cci = CCIManager(client) body = json.loads(req.stream.read().decode()) if 'name' in lookup(body, 'server'): if lookup(body, 'server', 'name').strip() == '': return bad_request(resp, message='Server name is blank') cci.edit(server_id, hostname=lookup(body, 'server', 'name')) instance = cci.get_instance(server_id, mask=get_virtual_guest_mask()) results = get_server_details_dict(self.app, req, instance) resp.body = {'server': results}
def on_delete(self, req, resp, tenant_id, server_id): client = req.env['sl_client'] cci = CCIManager(client) try: cci.cancel_instance(server_id) except SoftLayerAPIError as e: if 'active transaction' in e.faultString: return bad_request( resp, message='Can not cancel an instance when there is already' ' an active transaction', code=409) raise resp.status = 204
def on_get(self, req, resp, tenant_id=None): client = req.env['sl_client'] cci = CCIManager(client) params = get_list_params(req) sl_instances = cci.list_instances(**params) if not isinstance(sl_instances, list): sl_instances = [sl_instances] results = [] for instance in sl_instances: results.append(get_server_details_dict(self.app, req, instance)) resp.status = 200 resp.body = {'servers': results}
def on_get(self, req, resp, tenant_id): client = req.env['sl_client'] cci = CCIManager(client) all_options = cci.get_create_options() results = [] # Load and sort all data centers for option in all_options['datacenters']: name = lookup(option, 'template', 'datacenter', 'name') results.append({ 'zoneState': { 'available': True }, 'hosts': None, 'zoneName': name }) results = sorted(results, key=lambda x: x['zoneName']) resp.body = {'availabilityZoneInfo': results}
def on_get(self, req, resp, tenant_id, target_id): client = req.env['sl_client'] cci = CCIManager(client) start_time = datetime.datetime.now() + datetime.timedelta(hours=-1) usage = { 'server_usages': [], 'start': start_time.isoformat(), 'stop': datetime.datetime.now().isoformat(), 'tenant_id': target_id, 'total_hours': 0.0, 'total_local_gb_usage': 0.0, 'total_memory_mb_usage': 0.0, 'total_vcpus_usage': 0.0, } params = { 'mask': get_virtual_guest_mask(), } for instance in cci.list_instances(**params): server_dict = { 'ended_at': None, 'flavor': 'custom', 'hours': 0.0, 'instance_id': instance['id'], 'local_gb': 1, 'memory_mb': instance['maxMemory'], 'name': instance['hostname'], 'started_at': instance.get('provisionDate'), 'state': instance['status']['keyName'].lower(), 'tenant_id': target_id, 'uptime': 3600, 'vcpus': instance['maxCpu'], } usage['total_vcpus_usage'] += instance['maxCpu'] usage['total_memory_mb_usage'] += instance['maxMemory'] usage['server_usages'].append(server_dict) resp.body = {'tenant_usage': usage}
def on_get(self, req, resp, tenant_id, server_id): client = req.env['sl_client'] cci = CCIManager(client) instance = cci.get_instance( server_id, mask='id, primaryIpAddress, primaryBackendIpAddress') addresses = {} if instance.get('primaryIpAddress'): addresses['public'] = [{ 'version': 4, 'addr': instance['primaryIpAddress'], }] if instance.get('primaryBackendIpAddress'): addresses['private'] = [{ 'version': 4, 'addr': instance['primaryBackendIpAddress'], }] resp.body = {'addresses': addresses}
def on_get(self, req, resp, tenant_id, server_id, network_label): network_label = network_label.lower() network_mask = None if network_label == 'public': network_mask = 'primaryIpAddress' elif network_label == 'private': network_mask = 'primaryBackendIpAddress' else: return not_found(resp, message='Network does not exist') client = req.env['sl_client'] cci = CCIManager(client) instance = cci.get_instance(server_id, mask='id, ' + network_mask) resp.body = { network_label: [ { 'version': 4, 'addr': instance[network_mask] }, ] }
def on_post(self, req, resp, tenant_id, instance_id): body = json.loads(req.stream.read().decode()) if len(body) == 0: return bad_request(resp, message="Malformed request body") vg_client = req.env['sl_client']['Virtual_Guest'] cci = CCIManager(req.env['sl_client']) try: instance_id = int(instance_id) except ValueError: return not_found(resp, "Invalid instance ID specified.") instance = cci.get_instance(instance_id) if 'pause' in body or 'suspend' in body: try: vg_client.pause(id=instance_id) except SoftLayerAPIError as e: if 'Unable to pause instance' in e.faultString: return duplicate(resp, e.faultString) raise resp.status = 202 return elif 'unpause' in body or 'resume' in body: vg_client.resume(id=instance_id) resp.status = 202 return elif 'reboot' in body: if body['reboot'].get('type') == 'SOFT': vg_client.rebootSoft(id=instance_id) elif body['reboot'].get('type') == 'HARD': vg_client.rebootHard(id=instance_id) else: vg_client.rebootDefault(id=instance_id) resp.status = 202 return elif 'os-stop' in body: vg_client.powerOff(id=instance_id) resp.status = 202 return elif 'os-start' in body: vg_client.powerOn(id=instance_id) resp.status = 202 return elif 'createImage' in body: image_name = body['createImage']['name'] disks = [] for disk in filter(lambda x: x['device'] == '0', instance['blockDevices']): disks.append(disk) try: vg_client.createArchiveTransaction( image_name, disks, "Auto-created by OpenStack compatibility layer", id=instance_id, ) # Workaround for not having an image guid until the image is # fully created. TODO: Fix this cci.wait_for_transaction(instance_id, 300) _filter = { 'privateBlockDeviceTemplateGroups': { 'name': { 'operation': image_name }, 'createDate': { 'operation': 'orderBy', 'options': [{ 'name': 'sort', 'value': ['DESC'] }], } } } acct = req.env['sl_client']['Account'] matching_image = acct.getPrivateBlockDeviceTemplateGroups( mask='id, globalIdentifier', filter=_filter, limit=1) image_guid = matching_image.get('globalIdentifier') url = self.app.get_endpoint_url('image', req, 'v2_image', image_guid=image_guid) resp.status = 202 resp.set_header('location', url) except SoftLayerAPIError as e: compute_fault(resp, e.faultString) return elif 'os-getConsoleOutput' in body: resp.status = 501 return return bad_request(resp, message="There is no such action: %s" % list(body.keys()), code=400)
def on_post(self, req, resp, tenant_id): client = req.env['sl_client'] body = json.loads(req.stream.read().decode()) flavor_id = int(body['server'].get('flavorRef')) if flavor_id not in FLAVORS: return bad_request(resp, 'Flavor could not be found') flavor = FLAVORS[flavor_id] ssh_keys = [] key_name = body['server'].get('key_name') if key_name: sshkey_mgr = SshKeyManager(client) keys = sshkey_mgr.list_keys(label=key_name) if len(keys) == 0: return bad_request(resp, 'KeyPair could not be found') ssh_keys.append(keys[0]['id']) private_network_only = False networks = lookup(body, 'server', 'networks') if networks: # Make sure they're valid networks if not all([ network['uuid'] in ['public', 'private'] in network for network in networks ]): return bad_request(resp, message='Invalid network') # Find out if it's private only if not any([ network['uuid'] == 'public' in network for network in networks ]): private_network_only = True user_data = {} if lookup(body, 'server', 'metadata'): user_data['metadata'] = lookup(body, 'server', 'metadata') if lookup(body, 'server', 'user_data'): user_data['user_data'] = lookup(body, 'server', 'user_data') if lookup(body, 'server', 'personality'): user_data['personality'] = lookup(body, 'server', 'personality') datacenter = None if lookup(body, 'server', 'availability_zone'): datacenter = lookup(body, 'server', 'availability_zone') cci = CCIManager(client) payload = { 'hostname': body['server']['name'], 'domain': 'jumpgate.com', # TODO - Don't hardcode this 'cpus': flavor['cpus'], 'memory': flavor['ram'], 'hourly': True, # TODO - How do we set this accurately? 'datacenter': datacenter, 'image_id': body['server']['imageRef'], 'ssh_keys': ssh_keys, 'private': private_network_only, 'userdata': json.dumps(user_data), } try: new_instance = cci.create_instance(**payload) except ValueError as e: return bad_request(resp, message=str(e)) resp.set_header('x-compute-request-id', 'create') resp.status = 202 resp.body = { 'server': { 'id': new_instance['id'], 'links': [{ 'href': self.app.get_endpoint_url('compute', req, 'v2_server', instance_id=new_instance['id']), 'rel': 'self' }], 'adminPass': '', } }
def get_vm_manager(): return CCIManager(get_client())
from django.core.management.base import BaseCommand, CommandError from slsync.models import Inst class Command(BaseCommand): #empty the staging table for import Inst.objects.all().delete() from SoftLayer import Client, CCIManager from SoftLayer.CLI.helpers import (NestedDict) import os sl_api_user = os.environ['SL_API_USER'] sl_api_key = os.environ['SL_API_KEY'] client = Client(username=sl_api_user, api_key=sl_api_key) cci = CCIManager(client) guests = cci.list_instances() for guest in guests: guest = NestedDict(guest) a = Inst(inst_id=guest['id'], pub_ip=guest['primaryIpAddress'], pri_ip=guest['primaryBackendIpAddress'], fulldomainname=guest['fullyQualifiedDomainName']) a.save()