def create(self, callback=None): """Creates a snapshot :returns: :class:`Snapshot` :raises: :class:`SnapshotException` """ if self.snapshot_id is not None: raise SnapshotException('Cannot snapshot a snapshot: %s' % self.snapshot_id) payload = {'addSnapshot': [{}]} payload['addSnapshot'][0]['volume'] = camel_keys(self.volume) payload['addSnapshot'][0]['name'] = self.name payload['addSnapshot'][0]['description'] = self.description payload['addSnapshot'][0]['budget'] = self.budget optional_attrs = ['label'] for oa in optional_attrs: try: if getattr(self, oa) is not None: payload['addSnapshot'][0].update( camel_keys({oa: getattr(self, oa)})) except AttributeError: # We did say optional.... pass self.post(self.PATH, data=json.dumps(payload)) if self.last_error is None: if callback is not None: callback(self) else: return self else: raise SnapshotException(self.last_error)
def create(self, callback=None): """Creates a snapshot :returns: :class:`Snapshot` :raises: :class:`SnapshotException` """ if self.snapshot_id is not None: raise SnapshotException( 'Cannot snapshot a snapshot: %s' % self.snapshot_id) payload = {'addSnapshot': [{}]} payload['addSnapshot'][0]['volume'] = camel_keys(self.volume) payload['addSnapshot'][0]['name'] = self.name payload['addSnapshot'][0]['description'] = self.description payload['addSnapshot'][0]['budget'] = self.budget optional_attrs = ['label'] for oa in optional_attrs: try: if getattr(self, oa) is not None: payload['addSnapshot'][0].update( camel_keys({oa: getattr(self, oa)})) except AttributeError: # We did say optional.... pass self.post(self.PATH, data=json.dumps(payload)) if self.last_error is None: if callback is not None: callback(self) else: return self else: raise SnapshotException(self.last_error)
def launch(self, callback=None): """Launches a server with the configured parameters >>> def cb(j): print(j) >>> s = Server() >>> s.provider_product_id = 'm1.large' >>> s.machine_image = 12345 >>> s.description = 'my first launch' >>> s.name = 'server-1-test' >>> s.data_center = 54321 >>> s.keypair = 'my-aws-keypair' >>> s.launch(callback=cb) :param callback: Optional callback to send the results of the API call :type callback: func. :returns: int -- The job id of the launch request :raises: :class:`ServerLaunchException`, :class:`mixcoatl.decorators.validations.ValidationException` """ optional_attrs = ['vlan', 'firewalls', 'keypair', 'label', 'cmAccount', 'environment', 'cm_scripts', 'p_scripts', 'volumeConfiguration'] if self.server_id is not None: raise ServerLaunchException('Cannot launch an already running server: %s' % self.server_id) payload = {'launch': [{ 'productId': self.provider_product_id, 'budget': self.budget, 'machineImage': camel_keys(self.machine_image), 'description': self.description, 'name': self.name, 'dataCenter': camel_keys(self.data_center) }]} for oa in optional_attrs: try: if getattr(self, oa) is not None: if oa == 'cm_scripts': payload['launch'][0].update({'scripts':getattr(self, oa)}) elif oa == 'p_scripts': payload['launch'][0].update({'personalities':getattr(self, oa)}) elif oa == 'volumeConfiguration': payload['launch'][0].update({'volumeConfiguration':{u'raidlevel':'RAID0', u'volumeCount':1, u'volumeSize':2, u'fileSystem':'ext3', u'mountPoint':'/mnt/data'}}) elif oa == 'vlan': payload['launch'][0].update({'vlan':camel_keys(getattr(self, oa))}) else: payload['launch'][0].update({oa:getattr(self, oa)}) except AttributeError: pass self.post(data=json.dumps(payload)) if self.last_error is None: if callback is not None: callback(self.current_job) else: return self.current_job else: raise ServerLaunchException(self.last_error)
def attach(self, server_id, device_id=None, callback=None): """Attach a volume to a server :param server_id: Server to attach the volume :type server_id: int. :param callback: Optional callback to send the results :returns: :class:`Volume` :raises: :class:`VolumeException` """ payload = {'attach': [{'server': {'server_id': server_id}}]} if device_id is not None: payload['attach'][0]['device_id'] = device_id self.put(self.PATH + '/' + str(self.volume_id), data=json.dumps(camel_keys(payload))) if self.last_error is None: if callback is None: return self else: callback(self) else: raise VolumeException(self.last_error)
def create(self, callback=None): """Creates a new launch configuration :param callback: Optional callback to send the resulting :class:`Job` :raises: :class:`TierCreationException` """ #lc.name = name #lc.region = region #lc.primary_product = primary_product_id #lc.secondary_product = secondary_product_id #lc.primary_machine_image = primary_machine_image #lc.secondary_machine_image = secondary_machine_image #lc.server_name_template = server_name_template #lc.tier = tier #lc.firewall = firewall #lc.region = region parms = [{'tier':{'tierId':self.tier}, 'primaryMachineImage':{'machineImageId':self.primary_machine_image}, 'primaryProduct':{'productId':self.primary_product_id}, 'firewalls':[{'firewallId':self.firewalls}], 'region':{'regionId':self.region}}] payload = {'addLaunchConfiguration':camel_keys(parms)} response=self.post(data=json.dumps(payload)) if self.last_error is None: self.load() print response return response else: raise LaunchConfigurationCreationException(self.last_error)
def create(self): """Creates a new user.""" billing_code_list = [] for billing_code in self.billing_codes: billing_code_list.append({"billingCodeId": billing_code}) parms = [{'givenName':self.given_name, 'familyName': self.family_name, 'email': self.email, 'groups': [{'groupId':self.groups}], 'account': {'accountId':self.account}, 'billingCodes': billing_code_list}] if self.password is not None: parms[0].update({'password': self.password}) payload = {'addUser':camel_keys(parms)} response=self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise UserCreationException(self.last_error)
def update(self): """Updates a snapshot with changed values :returns: :class:`Snapshot` :raises: :class:`SnapshotException` """ if self.pending_changes is None: pass else: payload = {'describeSnapshot': [{}]} for x in ['name', 'description', 'label']: if x in self.pending_changes: new_val = self.pending_changes[x]['new'] payload['describeSnapshot'][0][camel_keys(x)] = new_val self.pending_changes.pop(x, None) if len(payload['describeSnapshot'][0]) == 0: pass else: self.put(self.PATH + '/' + str(self.snapshot_id), data=json.dumps(payload)) if self.last_error is None: self.load() return self else: raise SnapshotException(self.last_error)
def create(self, callback=None): """Creates a new tier :param callback: Optional callback to send the resulting :class:`Job` :raises: :class:`TierCreationException` """ parms = [{'budget': self.budget, 'deployment': {'deploymentId': self.deployment}, 'description': self.description, 'name': self.name, 'minimumServers': self.minimum_servers, 'maximumServers': self.maximum_servers, 'breachIncrement': self.breach_increment, 'breachPeriodInMinutes': self.breach_period_in_minutes, 'cooldownPeriodInMinutes': self.cooldown_period_in_minutes, 'lowerCpuThreshold': self.lower_cpu_threshold, 'upperCpuThreshold': self.upper_cpu_threshold, 'lowerRamThreshold': self.lower_ram_threshold, 'upperRamThreshold': self.upper_ram_threshold}] payload = {'addTier':camel_keys(parms)} response=self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise TierCreationException(self.last_error)
def load(self, **kwargs): """(Re)load the current object's attributes from an API call""" from mixcoatl.utils import uncamel_keys reserved_words = ['type'] p = self.PATH + "/" + str(getattr(self, self.__class__.PRIMARY_KEY)) if 'params' in kwargs: params = kwargs['params'] else: params = camel_keys(self.params) s = self.get(p, params=params) if self.last_error is None: scope = uncamel_keys(s[self.__class__.COLLECTION_NAME][0]) for k in scope.keys(): if k in reserved_words: the_key = 'e_' + k else: the_key = k nk = '_%s__%s' % (self.__class__.__name__, the_key) if the_key not in self.__props(): self.add_property(k) if 'DCM_DEBUG' in os.environ: print "Missing key found when loading class %s with primary key %s: %s" % \ ( self.__class__.__name__, str(getattr(self, self.__class__.PRIMARY_KEY)), k) setattr(self, nk, scope[k]) self.loaded = True else: return self.last_error
def attach(self, server_id, device_id=None, callback=None): """Attach a volume to a server :param server_id: Server to attach the volume :type server_id: int. :param callback: Optional callback to send the results :returns: :class:`Volume` :raises: :class:`VolumeException` """ payload = {'attach':[{ 'server':{'server_id': server_id}}]} if device_id is not None: payload['attach'][0]['device_id'] = device_id self.put(self.PATH+'/'+str(self.volume_id), data=json.dumps(camel_keys(payload))) if self.last_error is None: if callback is None: return self else: callback(self) else: raise VolumeException(self.last_error)
def create(self): """Creates a new user.""" billing_code_list = [] for billing_code in self.billing_codes: billing_code_list.append({"billingCodeId": billing_code}) parms = [{ 'givenName': self.given_name, 'familyName': self.family_name, 'email': self.email, 'groups': [{ 'groupId': self.groups }], 'account': { 'accountId': self.account }, 'billingCodes': billing_code_list }] if self.password is not None: parms[0].update({'password': self.password}) payload = {'addUser': camel_keys(parms)} response = self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise UserCreationException(self.last_error)
def create(self, callback=None): """Creates a new tier :param callback: Optional callback to send the resulting :class:`Job` :raises: :class:`TierCreationException` """ parms = [{ 'budget': self.budget, 'deployment': { 'deploymentId': self.deployment }, 'description': self.description, 'name': self.name, 'minimumServers': self.minimum_servers, 'maximumServers': self.maximum_servers, 'breachIncrement': self.breach_increment, 'breachPeriodInMinutes': self.breach_period_in_minutes, 'cooldownPeriodInMinutes': self.cooldown_period_in_minutes, 'lowerCpuThreshold': self.lower_cpu_threshold, 'upperCpuThreshold': self.upper_cpu_threshold, 'lowerRamThreshold': self.lower_ram_threshold, 'upperRamThreshold': self.upper_ram_threshold }] payload = {'addTier': camel_keys(parms)} response = self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise TierCreationException(self.last_error)
def load(self, **kwargs): """(Re)load the current object's attributes from an API call""" from mixcoatl.utils import uncamel_keys reserved_words = ['type'] p = self.PATH if 'params' in kwargs: params = kwargs['params'] else: params = camel_keys(self.params) s = self.get(p, params=params) if self.last_error is None: scope = uncamel_keys(s) for k in scope.keys(): if k in reserved_words: the_key = 'e_' + k else: the_key = k nk = '_%s__%s' % (self.__class__.__name__, the_key) # nk = '__%s' % the_key if the_key not in self._Resource__props(): self.add_property(k) setattr(self, nk, scope[k]) self.loaded = True else: return self.last_error
def create(self, callback=None): """Creates a new volume :param callback: Optional callback to send the resulting :class:`Job` :type callback: func. :returns: :class:`Job` :raises: :class:`VolumeCreationException` """ optional_attrs = ['label'] if self.volume_id is not None: raise VolumeCreationException( 'Cannot create an already created volume: %s' % self.volume_id) parms = {'name': self.name, 'description': self.description, 'data_center': self.data_center, 'size_in_gb': self.size_in_gb, 'budget': self.budget} for oa in optional_attrs: try: if getattr(self, oa) is not None: parms[0].update({oa: getattr(self, oa)}) except AttributeError: pass payload = {'addVolume': [camel_keys(parms)]} self.post(data=json.dumps(payload)) if self.last_error is None: j = Job(self.current_job, endpoint=self.endpoint) j.load() if callback is not None: callback(j) else: return j else: raise VolumeCreationException(self.last_error)
def update(self): """Updates a snapshot with changed values :returns: :class:`Snapshot` :raises: :class:`SnapshotException` """ if self.pending_changes is None: pass else: payload = {'describeSnapshot': [{}]} for x in ['name', 'description', 'label']: if x in self.pending_changes: new_val = self.pending_changes[x]['new'] payload['describeSnapshot'][0][camel_keys(x)] = new_val self.pending_changes.pop(x, None) if len(payload['describeSnapshot'][0]) == 0: pass else: self.put( self.PATH + '/' + str(self.snapshot_id), data=json.dumps(payload)) if self.last_error is None: self.load() return self else: raise SnapshotException(self.last_error)
def load(self, **kwargs): """(Re)load the current object's attributes from an API call""" from mixcoatl.utils import uncamel_keys reserved_words = ["type"] p = self.PATH if "params" in kwargs: params = kwargs["params"] else: params = camel_keys(self.params) s = self.get(p, params=params) if self.last_error is None: scope = uncamel_keys(s) for k in scope.keys(): if k in reserved_words: the_key = "e_" + k else: the_key = k nk = "_%s__%s" % (self.__class__.__name__, the_key) # nk = '__%s' % the_key if the_key not in self._Resource__props(): self.add_property(k) setattr(self, nk, scope[k]) self.loaded = True else: return self.last_error
def grant(self, acls): """Updates Roles ACL list.""" p = '%s/%s' % (self.PATH, str(self.role_id)) payload = {'grant': [{'acl': camel_keys(acls.values()[0])}]} return self.put(p, data=json.dumps(payload)) if self.last_error is None: self.load() else: raise setACLException(self.last_error)
def create(self, callback=None): """Creates a new group :param callback: Optional callback to send the resulting :class:`Job` :raises: :class:`GroupCreationException` """ parms = {'group': {'name': self.name, 'description': self.description}} payload = {'addGroup': camel_keys(parms)} response = self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise GroupCreationException(self.last_error)
def create(self): """Creates a new role. Status is hard-coded to ACTIVE for now. """ parms = [{'status': "ACTIVE", 'name': self.name, 'description': self.description}] payload = {'addRole': camel_keys(parms)} response = self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise RoleCreationException(self.last_error)
def grant(self,role_id,resource_type, action, qualifier): """Adds a new ACL to a role.""" parms = [{'acl': [{'resourceType' : resource_type, 'action' : action, 'qualifier' : qualifier}]}] p = '%s/%s' % (self.PATH, str(self.role_id)) payload = {'grant':camel_keys(parms)} return self.put(p, data=json.dumps(payload)) if self.last_error is None: self.load() else: raise setACLException(self.last_error)
def create(self, **kwargs): """Create a new network :param callback: Optional callback to call with resulting :class:`Network` :type callback: func. :returns: :class:`Job` :raises: :class:`NetworkException` """ optional_attrs = [ 'owning_groups', 'ntp_servers', 'dns_servers', 'label' ] payload = { 'add_network': [{ 'budget': self.budget, 'name': self.name, 'network_address': self.network_address, 'description': self.description, 'region': self.region }] } if 'label' in kwargs: payload['add_network'][0]['label'] = kwargs['label'] callback = kwargs.get('callback', None) for oa in optional_attrs: try: if getattr(self, oa) is not None: payload['add_network'][0].update({oa: getattr(self, oa)}) except AttributeError: pass self.post(self.PATH, data=json.dumps(camel_keys(payload))) if self.last_error is None: j = Job(self.current_job, endpoint=self.endpoint) j.load() if callback is not None: callback(j) else: return j else: raise NetworkException(self.last_error)
def _change_metadata(self): """Changes metadata""" new_vals = {} for x in ["name", "description", "label"]: if x in self.pending_changes: new_val = self.pending_changes[x]["new"] new_vals[camel_keys(x)] = new_val self.pending_changes.pop(x, None) if len(new_vals) == 0: pass else: payload = {"describeVolume": [new_vals]} self.put(self.PATH + "/" + str(self.volume_id), data=json.dumps(payload)) if self.last_error is None: self.load() return True else: raise VolumeException(self.last_error)
def create(self): """Creates a new CM service.""" parms = [{"budget": self.budget, "serviceEndpoint": self.endpoint, "description": self.description, "name": self.name, "label": "red", "cmSystem": {"cmSystemID": self.cm_system_id}}] payload = {"addService": camel_keys(parms)} print json.dumps(payload) response = self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise CMCreationException(self.last_error)
def create(self, callback=None): """Creates a new launch configuration :param callback: Optional callback to send the resulting :class:`Job` :raises: :class:`TierCreationException` """ #lc.name = name #lc.region = region #lc.primary_product = primary_product_id #lc.secondary_product = secondary_product_id #lc.primary_machine_image = primary_machine_image #lc.secondary_machine_image = secondary_machine_image #lc.server_name_template = server_name_template #lc.tier = tier #lc.firewall = firewall #lc.region = region parms = [{ 'tier': { 'tierId': self.tier }, 'primaryMachineImage': { 'machineImageId': self.primary_machine_image }, 'primaryProduct': { 'productId': self.primary_product_id }, 'firewalls': [{ 'firewallId': self.firewalls }], 'region': { 'regionId': self.region } }] payload = {'addLaunchConfiguration': camel_keys(parms)} response = self.post(data=json.dumps(payload)) if self.last_error is None: self.load() print response return response else: raise LaunchConfigurationCreationException(self.last_error)
def create(self, **kwargs): """Create a new firewall rule .. warning:: Does not currently support adding ICMP rules :param reason: Reason for the new rule :type reason: str. :returns: `bool` :raises: :class:`FirewallRuleException` """ if 'reason' not in kwargs: reason = 'Added by mixcoatl' else: reason = kwargs['reason'] payload = { 'add_rule': [{ 'firewall_id': self.firewall['firewall_id'], 'source': self.source, 'source_type': self.source_type, 'destination': self.destination, 'destination_type': self.destination_type, 'direction': self.direction, 'permission': self.permission, 'protocol': self.protocol, 'reason': reason }] } if self.firewall_rule_id is not None: raise FirewallRuleException('Cannot modify existing firewall rule') self.post(self.PATH, data=json.dumps(camel_keys(payload))) if self.last_error is None: return True else: if self.last_request.status_code == 418: return True else: raise FirewallRuleException(self.last_error)
def create(self, **kwargs): """Create a new firewall rule .. warning:: Does not currently support adding ICMP rules :param reason: Reason for the new rule :type reason: str. :returns: `bool` :raises: :class:`FirewallRuleException` """ if 'reason' not in kwargs: reason = 'Added by mixcoatl' else: reason = kwargs['reason'] payload = {'add_rule':[{ 'firewall_id': self.firewall['firewall_id'], 'direction': self.direction, 'start_port': self.start_port, 'end_port': self.end_port, 'protocol': self.protocol, 'reason': reason, 'source_type': self.source_type, 'source': self.source, 'permission': self.permission, 'destination': self.destination, 'cidr' : self.network_address}]} if self.firewall_rule_id is not None: raise FirewallRuleException('Cannot modify existing firewall rule') self.post(self.PATH, data=json.dumps(camel_keys(payload))) if self.last_error is None: return True else: if self.last_request.status_code == 418: return True else: raise FirewallRuleException(self.last_error)
def _change_metadata(self): """Changes metadata""" new_vals = {} for x in ['name', 'description', 'label']: if x in self.pending_changes: new_val = self.pending_changes[x]['new'] new_vals[camel_keys(x)] = new_val self.pending_changes.pop(x, None) if len(new_vals) == 0: pass else: payload = {'describeVolume': [new_vals]} self.put(self.PATH + '/' + str(self.volume_id), data=json.dumps(payload)) if self.last_error is None: self.load() return True else: raise VolumeException(self.last_error)
def grant(self, role_id, resource_type, action, qualifier): """Adds a new ACL to a role.""" parms = [{ 'acl': [{ 'resourceType': resource_type, 'action': action, 'qualifier': qualifier }] }] p = '%s/%s' % (self.PATH, str(self.role_id)) payload = {'grant': camel_keys(parms)} return self.put(p, data=json.dumps(payload)) if self.last_error is None: self.load() else: raise setACLException(self.last_error)
def create(self): """Creates a new user.""" parms = [{'givenName':self.given_name, 'familyName': self.family_name, 'account': self.account, 'email': self.email, 'groups': [{'groupId':self.groups}], 'account': {'accountId':self.account}, 'billingCodes':[{'billingCodeId':self.billing_codes}]}] payload = {'addUser':camel_keys(parms)} #print payload response=self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise UserCreationException(self.last_error)
def create(self, **kwargs): """Create a new network :param callback: Optional callback to call with resulting :class:`Network` :type callback: func. :returns: :class:`Job` :raises: :class:`NetworkException` """ optional_attrs = [ 'owning_groups', 'ntp_servers', 'dns_servers', 'label'] payload = {'add_network': [{ 'budget': self.budget, 'name': self.name, 'network_address': self.network_address, 'description': self.description, 'region': self.region}]} if 'label' in kwargs: payload['add_network'][0]['label'] = kwargs['label'] callback = kwargs.get('callback', None) for oa in optional_attrs: try: if getattr(self, oa) is not None: payload['add_network'][0].update({oa: getattr(self, oa)}) except AttributeError: pass self.post(self.PATH, data=json.dumps(camel_keys(payload))) if self.last_error is None: j = Job(self.current_job) j.load() if callback is not None: callback(j) else: return j else: raise NetworkException(self.last_error)
def create(self, callback=None): """Creates a new deployment :param callback: Optional callback to send the resulting :class:`Job` :raises: :class:`DeploymentCreationException` """ parms = [{'budget': self.budget, 'regionId': self.region, 'description': self.description, 'name': self.name}] payload = {'addDeployment':camel_keys(parms)} response=self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise DeploymentCreationException(self.last_error)
def create(self, **kwargs): """Create a new firewall :param label: Optional label to assign the firewall :type label: str. :param callback: Optional callback to call with resulting :class:`Firewall` :type callback: func. :returns: :class:`Firewall` :raises: :class:`FirewallException` """ payload = { 'add_firewall': [{ 'budget': self.budget, 'region': self.region, 'name': self.name, 'description': self.description }] } if 'label' in kwargs: payload['add_firewall'][0]['label'] = kwargs['label'] callback = kwargs.get('callback', None) self.post(self.PATH, data=json.dumps(camel_keys(payload))) if self.last_error is None: if callback is None: return self else: if Job.wait_for(self.current_job) is True: j = Job(self.current_job, endpoint=self.endpoint) self.__firewall_id = j.message self.load() return self else: raise FirewallException(j.last_error) else: raise FirewallException(self.last_error)
def create(self, callback=None): """Creates a new deployment :param callback: Optional callback to send the resulting :class:`Job` :raises: :class:`DeploymentCreationException` """ parms = [{ 'budget': self.budget, 'regionId': self.region, 'description': self.description, 'name': self.name }] payload = {'addDeployment': camel_keys(parms)} response = self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise DeploymentCreationException(self.last_error)
def create(self): """Creates a new CM service.""" parms = [{ "budget": self.budget, "serviceEndpoint": self.endpoint, "description": self.description, "name": self.name, "label": "red", "cmSystem": { "cmSystemID": self.cm_system_id } }] payload = {"addService": camel_keys(parms)} print json.dumps(payload) response = self.post(data=json.dumps(payload)) if self.last_error is None: self.load() return response else: raise CMCreationException(self.last_error)
def create(self, **kwargs): """Create a new firewall :param label: Optional label to assign the firewall :type label: str. :param callback: Optional callback to call with resulting :class:`Firewall` :type callback: func. :returns: :class:`Firewall` :raises: :class:`FirewallException` """ payload = {'add_firewall': [{ 'budget': self.budget, 'region': self.region, 'name': self.name, 'description': self.description }]} if 'label' in kwargs: payload['add_firewall'][0]['label'] = kwargs['label'] callback = kwargs.get('callback', None) self.post(self.PATH, data=json.dumps(camel_keys(payload))) if self.last_error is None: if callback is None: return self else: if Job.wait_for(self.current_job) is True: j = Job(self.current_job, endpoint=self.endpoint) self.__firewall_id = j.message self.load() return self else: raise FirewallException(j.last_error) else: raise FirewallException(self.last_error)
def load(self): """(Re)load the current object's attributes from an API call""" from mixcoatl.utils import uncamel_keys reserved_words = ['type'] p = self.PATH+"/"+str(getattr(self, self.__class__.PRIMARY_KEY)) #self.request_details = 'extended' s = self.get(p, params=camel_keys(self.params)) if self.last_error is None: scope = uncamel_keys(s[self.__class__.COLLECTION_NAME][0]) for k in scope.keys(): if k in reserved_words: the_key = 'e_'+k else: the_key = k nk = '_%s__%s' % (self.__class__.__name__, the_key) if the_key not in self.__props(): raise AttributeError('Key found without accessor: %s' % k) else: setattr(self, nk, scope[k]) self.loaded = True else: return self.last_error
def launch(self, callback=None): """Launches a server with the configured parameters >>> def cb(j): print(j) >>> s = Server() >>> s.provider_product_id = 'm1.large' >>> s.machine_image = 12345 >>> s.description = 'my first launch' >>> s.name = 'server-1-test' >>> s.data_center = 54321 >>> s.keypair = 'my-aws-keypair' >>> s.launch(callback=cb) :param callback: Optional callback to send the results of the API call :type callback: func. :returns: int -- The job id of the launch request :raises: :class:`ServerLaunchException`, :class:`mixcoatl.decorators.validations.ValidationException` """ optional_attrs = [ 'userData', 'vlan', 'firewalls', 'keypair', 'label', 'cmAccount', 'environment', 'cm_scripts', 'p_scripts', 'volumeConfiguration' ] if self.server_id is not None: raise ServerLaunchException( 'Cannot launch an already running server: %s' % self.server_id) payload = { 'launch': [{ 'product': { "productId": self.provider_product_id }, 'budget': self.budget, 'machineImage': camel_keys(self.machine_image), 'description': self.description, 'name': self.name, 'dataCenter': camel_keys(self.data_center) }] } for oa in optional_attrs: try: if getattr(self, oa) is not None: if oa == 'cm_scripts': payload['launch'][0].update( {'scripts': getattr(self, oa)}) elif oa == 'p_scripts': payload['launch'][0].update( {'personalities': getattr(self, oa)}) elif oa == 'volumeConfiguration': payload['launch'][0].update( {'volumeConfiguration': getattr(self, oa)}) elif oa == 'vlan': payload['launch'][0].update( {'vlan': camel_keys(getattr(self, oa))}) else: payload['launch'][0].update({oa: getattr(self, oa)}) except AttributeError: pass self.post(data=json.dumps(payload)) if self.last_error is None: if callback is not None: callback(self.current_job) else: return self.current_job else: raise ServerLaunchException(self.last_error)