本文整理汇总了Python中SoftLayer.CCIManager类的典型用法代码示例。如果您正苦于以下问题:Python CCIManager类的具体用法?Python CCIManager怎么用?Python CCIManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CCIManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute
def execute(self, args):
cci = CCIManager(self.client)
cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')
if args['--really'] or no_going_back(cci_id):
cci.cancel_instance(cci_id)
else:
CLIAbort('Aborted')
示例2: on_get
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}
示例3: on_get
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}
示例4: on_delete
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
示例5: _update_with_like_args
def _update_with_like_args(self, args):
""" Update arguments with options taken from a currently running CCI.
:param CCIManager args: A CCIManager
:param dict args: CLI arguments
"""
if args['--like']:
cci = CCIManager(self.client)
cci_id = resolve_id(cci.resolve_ids, args.pop('--like'), 'CCI')
like_details = cci.get_instance(cci_id)
like_args = {
'--hostname': like_details['hostname'],
'--domain': like_details['domain'],
'--cpu': like_details['maxCpu'],
'--memory': like_details['maxMemory'],
'--hourly': like_details['hourlyBillingFlag'],
'--monthly': not like_details['hourlyBillingFlag'],
'--datacenter': like_details['datacenter']['name'],
'--network': like_details['networkComponents'][0]['maxSpeed'],
'--user-data': like_details['userData'] or None,
'--postinstall': like_details.get('postInstallScriptUri'),
'--dedicated': like_details['dedicatedAccountHostOnlyFlag'],
'--private': like_details['privateNetworkOnlyFlag'],
}
# Handle mutually exclusive options
like_image = lookup(like_details,
'blockDeviceTemplateGroup',
'globalIdentifier')
like_os = lookup(like_details,
'operatingSystem',
'softwareLicense',
'softwareDescription',
'referenceCode')
if like_image and not args.get('--os'):
like_args['--image'] = like_image
elif like_os and not args.get('--image'):
like_args['--os'] = like_os
if args.get('--hourly'):
like_args['--monthly'] = False
if args.get('--monthly'):
like_args['--hourly'] = False
# Merge like CCI options with the options passed in
for key, value in like_args.items():
if args.get(key) in [None, False]:
args[key] = value
示例6: on_put
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}
示例7: global_search
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
示例8: on_put
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}
示例9: on_get
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}
示例10: __init__
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)
示例11: on_get
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]},
]
}
示例12: on_get
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}
示例13: execute
def execute(self, args):
cci = CCIManager(self.client)
tags = None
if args.get('--tags'):
tags = [tag.strip() for tag in args.get('--tags').split(',')]
guests = cci.list_instances(
hourly=args.get('--hourly'),
monthly=args.get('--monthly'),
hostname=args.get('--hostname'),
domain=args.get('--domain'),
cpus=args.get('--cpu'),
memory=args.get('--memory'),
datacenter=args.get('--datacenter'),
nic_speed=args.get('--network'),
tags=tags)
t = Table([
'id', 'datacenter', 'host',
'cores', 'memory', 'primary_ip',
'backend_ip', 'active_transaction',
])
t.sortby = args.get('--sortby') or 'host'
for guest in guests:
guest = NestedDict(guest)
t.add_row([
guest['id'],
guest['datacenter']['name'] or blank(),
guest['fullyQualifiedDomainName'],
guest['maxCpu'],
mb_to_gb(guest['maxMemory']),
guest['primaryIpAddress'] or blank(),
guest['primaryBackendIpAddress'] or blank(),
active_txn(guest),
])
return t
示例14: CCITests
class CCITests(unittest.TestCase):
"""
Small class to verify the rename of CCIManager to VSManager didn't
break any existing code.
"""
def setUp(self):
self.client = FixtureClient()
self.cci = CCIManager(self.client)
def test_list_instances(self):
mcall = call(mask=ANY, filter={})
service = self.client['Account']
list_expected_ids = [100, 104]
hourly_expected_ids = [104]
monthly_expected_ids = [100]
results = self.cci.list_instances(hourly=True, monthly=True)
service.getVirtualGuests.assert_has_calls(mcall)
for result in results:
self.assertIn(result['id'], list_expected_ids)
result = self.cci.list_instances(hourly=False, monthly=False)
service.getVirtualGuests.assert_has_calls(mcall)
for result in results:
self.assertIn(result['id'], list_expected_ids)
results = self.cci.list_instances(hourly=False, monthly=True)
service.getMonthlyVirtualGuests.assert_has_calls(mcall)
for result in results:
self.assertIn(result['id'], monthly_expected_ids)
results = self.cci.list_instances(hourly=True, monthly=False)
service.getHourlyVirtualGuests.assert_has_calls(mcall)
for result in results:
self.assertIn(result['id'], hourly_expected_ids)
示例15: SoftLayer
class SoftLayer(object):
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)
@classmethod
def get_config(cls):
provider_conf = client_conf.get_client_settings()
if 'SL_SSH_KEY' in os.environ:
provider_conf['ssh_key'] = os.environ['SL_SSH_KEY']
if not ('auth' in provider_conf and 'endpoint_url' in provider_conf):
raise ConfigError("Missing digital ocean api credentials")
return provider_conf
def get_ssh_keys(self):
keys = map(SSHKey, self.ssh.list_keys())
if 'ssh_key' in self.config:
keys = [k for k in keys if k.name == self.config['ssh_key']]
log.debug(
"Using SoftLayer ssh keys: %s" % ", ".join(k.name for k in keys))
return keys
def get_instances(self):
return map(Instance, self.instances.list_instances())
def get_instance(self, instance_id):
return Instance(self.instances.get_instance(instance_id))
def launch_instance(self, params):
return Instance(self.instances.create_instance(**params))
def terminate_instance(self, instance_id):
self.instances.cancel_instance(instance_id)
def wait_on(self, instance):
# Wait up to 5 minutes, in 30 sec increments
result = self._wait_on_instance(instance, 30, 10)
if not result:
raise ProviderError("Could not provision instance before timeout")
return result
def _wait_on_instance(self, instance, limit, delay=10):
# Redo cci.wait to give user feedback in verbose mode.
for count, new_instance in enumerate(itertools.repeat(instance.id)):
instance = self.get_instance(new_instance)
if not instance.get('activeTransaction', {}).get('id') and \
instance.get('provisionDate'):
return True
if count >= limit:
return False
if count and count % 3 == 0:
log.debug("Waiting for instance:%s ip:%s waited:%ds" % (
instance.name, instance.ip_address, count*delay))
time.sleep(delay)