def update_eip_runtime(self): eip_instance = self.get_eip() eip_id = eip_instance.runtime_properties[common_constants.EXTERNAL_ID] eip_instance.runtime_properties = {} request_body = {'AllocationId.1': eip_id} eip_info = Helper().execute_request('eip', 'describe_addresses', request_body)['AddressesSet'][0] eip_instance.runtime_properties[ common_constants.EXTERNAL_ID] = eip_info['AllocationId'] eip_instance.runtime_properties[ common_constants.EIP_ADDRESS] = eip_info['PublicIp'] eip_instance.runtime_properties[ common_constants.EIP_STATUS] = eip_info['State'] eip_instance.runtime_properties[ ksyun_constants.KS_EIP_TYPE] = eip_info.get('InstanceType') instance_id = eip_info.get('InstanceId') if instance_id and eip_info.get('InstanceType') == 'Ipfwd': vm_info = self.describe_vm(eip_info['InstanceId']) if vm_info: eip_instance.runtime_properties[ common_constants. EIP_RELATED_INSTANCE_ID] = eip_info['InstanceId'] eip_instance.runtime_properties[ common_constants.EIP_RELATED_INSTANCE_NAME] = vm_info.get( 'InstanceName') eip_instance.update()
def describe_instance_cloud_volumes(self): instance_id = ctx.instance.runtime_properties['external_id'] cloud_volumes = Helper().execute_request('ebs', 'describe_instance_volumes', {"InstanceId": instance_id}) cloud_volumes = cloud_volumes.get('Attachments') or [] return cloud_volumes
def describe_instance_local_volumes(self): instance_id = ctx.instance.runtime_properties['external_id'] local_volumes = Helper().execute_request('kec', 'describe_local_volumes', {"InstanceId": instance_id}) local_volumes = local_volumes.get('LocalVolumeSet') or [] return local_volumes
def delete(self): instance_id = ctx.instance.runtime_properties['external_id'] self.disassociate_eip() Helper().execute_request('kec', 'terminate_instances', {"InstanceId.1": instance_id}) self.release_ip_in_delete_operation() time.sleep(os.environ.get("KSYUN_VM_DELETE_WAIT_TIME_SECOND") or 5)
def associate_eip(self): if not self.is_allocated_eip(): return eip_obj = self.get_eip() vm = ctx.instance eip_id = eip_obj.runtime_properties[common_constants.EXTERNAL_ID] instance_id = vm.runtime_properties[common_constants.EXTERNAL_ID] interface_id = vm.runtime_properties['network_interface_id'] ctx.logger.info( 'Start associate EIP:{} to Instance:{},interface_id:{}'.format( eip_id, instance_id, interface_id)) request_body = { 'AllocationId': eip_id, 'InstanceId': instance_id, 'InstanceType': 'Ipfwd', 'NetworkInterfaceId': interface_id } Helper().execute_request('eip', 'associate_address', request_body) eip_obj = self.wait_eip_for_target_state( eip_id, [ksyun_constants.KS_EIP_STATE_ASSOCIATE]) networks = vm.runtime_properties['networks'] networks['public_ip'] = { 'ip': eip_obj['PublicIp'], 'name': 'public_ip' } vm.runtime_properties['networks'] = networks vm.runtime_properties['ip'] = eip_obj['PublicIp'] ctx.instance.update() self.update_eip_runtime() ctx.logger.info('Associate EIP successfully...')
def _create(self): ctx.logger.info('Start to create subnet...') cidr = validate_parameter('cidr_block', self.resource_config) ip_range_from, ip_range_to = self.get_ip_range(cidr) params = { 'AvailabilityZone': validate_parameter('available_zone_id', self.resource_config), 'SubnetName': self.resource_config.get('subnet_name'), 'CidrBlock': validate_parameter('cidr_block', self.resource_config), 'SubnetType': validate_parameter('subnet_type', self.resource_config), 'DhcpIpFrom': ip_range_from, 'DhcpIpTo': ip_range_to, 'GatewayIp': validate_parameter('gateway', self.resource_config), 'VpcId': validate_parameter('resource_id', self.resource_config), 'Dns1': validate_parameter('dns1', self.resource_config), 'Dns2': self.resource_config.get('dns2'), } params = dict((k, v) for k, v in list(params.items()) if v) ctx.logger.info( 'Try to create subnet with parameters {}'.format(params)) res = Helper().execute_request('vpc', 'create_subnet', params) subnet_id = res['Subnet']['SubnetId'] self.write_runtime(subnet_id) ctx.logger.info("Create subnet {0} successfully".format(subnet_id))
def describe_volume(self, volume_id=None): params = {"VolumeId.1": volume_id} if volume_id else {} res = Helper().execute_request('ebs', 'describe_volumes', params) ctx.logger.info('describe volume, id: {},parmas:{}, ret:{}'.format(volume_id, params, res)) if volume_id and res['Volumes']: return res['Volumes'][0] return res['Volumes']
def _reboot(self, instance_id): vm_state = self.get_vm_state(instance_id) if vm_state == ksyun_constants.KS_INSTANCE_STATE_STOPPED: raise NonRecoverableError( "Can not reboot virtual machine which state is stopped, you can start it!" ) reboot_params = {'InstanceId.1': instance_id, 'ForceReboot': True} Helper().execute_request('kec', 'reboot_instances', reboot_params)
def get_system_volume_by_kec(self, instance_id): request_body = { 'InstanceId': instance_id, } volumes = Helper().execute_request('kec', 'describe_local_volumes', request_body).get('LocalVolumeSet', []) for volume in volumes: if volume.get("LocalVolumeCategory") == 'system': return volume
def get_system_volume_by_ebs(self, instance_id): request_body = { 'InstanceId': instance_id, } volumes = Helper().execute_request('ebs', 'describe_instance_volumes', request_body).get('Attachments', []) for volume in volumes: if volume['VolumeCategory'] == 'system': return volume
def delete(self): listener_id = ctx.instance.runtime_properties.get( constants.EXTERNAL_ID) if not listener_id: ctx.logger.info('The listener was not created successfully') return request_body = {'ListenerId': listener_id} result = Helper().execute_request('slb', 'delete_listeners', request_body) if result.get('Return'): ctx.instance.runtime_properties = {} ctx.instance.update() ctx.logger.info( 'Delete listeners: {0} successfully.'.format(listener_id)) else: raise NonRecoverableError( 'Delete listeners: {0} failed.'.format(listener_id))
def _create(self): params = self.prepare_params() display_params = copy.deepcopy(params) ctx.instance.runtime_properties[ common_constants.EXTERNAL_HOSTNAME] = params.get('HostName') display_params['InstancePassword'] = '******' ctx.logger.info("VM creating params is {0}".format(display_params)) return Helper().execute_request( 'kec', 'run_instances', params)['InstancesSet'][0]['InstanceId']
def delete(self): vpc_id = ctx.instance.runtime_properties.get('external_id') if vpc_id: ctx.logger.info("Start to delete VPC {0}...".format(vpc_id)) Helper().execute_request('vpc', 'delete_vpc', {'VpcId': vpc_id}) ctx.logger.info(" Delete VPC {0} successfully".format(vpc_id)) else: ctx.logger.info( "Can not find vpc in runtime properties, skip the step.")
def get_network(self, resource_id): query_params = {'SubnetId.1': resource_id} network = Helper().execute_request('vpc', 'describe_subnets', query_params).get('SubnetSet') if not network: raise NonRecoverableError( "Subnet {0} not exists".format(resource_id)) else: return network[0]
def get_security_group(self, resource_id): query_params = {'SecurityGroupId.1': resource_id} sg = Helper().execute_request('vpc', 'describe_security_groups', query_params).get('SecurityGroupSet') if not sg: raise NonRecoverableError( "Security Group {0} not exists".format(resource_id)) else: return sg[0]
def get_vpc(vpc_id): params = {"VpcId.1": vpc_id} res = Helper().execute_request('vpc', 'describe_vpcs', params) vpcs = res['VpcSet'] if vpcs: return vpcs[0] else: raise NonRecoverableError( "Can not find VPC {0} in the account.".format(vpc_id))
def describe_cloud_volume_snapshots(self): cloud_volumes = self.describe_instance_cloud_volumes() snapshots = [] for volume in cloud_volumes: params = {'VolumeId': volume['VolumeId']} volume_snapshots = Helper().execute_request( 'ebs', 'describe_snapshots', params).get('Snapshots') or [] snapshots.extend(volume_snapshots) return snapshots
def describe_local_volume_snapshots(self): local_volumes = self.describe_instance_local_volumes() snapshots = [] for volume in local_volumes: params = {'SourceLocalVolumeId': volume['LocalVolumeId']} volume_snapshots = Helper().execute_request( 'kec', 'describe_local_volume_snapshots', params).get('LocalVolumeSnapshotSet') or [] snapshots.extend(volume_snapshots) return snapshots
def update_listener_runtime(listener_id): request_body = {'ListenerId.1': listener_id} result = Helper().execute_request('slb', 'describe_listeners', request_body) listeners_obj = result.get('ListenerSet') if listeners_obj: external_slb_id = listeners_obj[0].pop('LoadBalancerId') listener_obj = listeners_obj[0] ctx.instance.runtime_properties['external_id'] = listener_obj.get( 'ListenerId') ctx.instance.runtime_properties[ 'external_name'] = listener_obj.get('ListenerName') ctx.instance.runtime_properties['status'] = listener_obj.get( 'ListenerState') ctx.instance.runtime_properties[ 'external_slb_id'] = external_slb_id ctx.instance.runtime_properties.update(listener_obj) ctx.instance.update() else: ctx.logger.info('Listeners does not exist!')
def delete(self): subnet_id = ctx.instance.runtime_properties.get('external_id') if subnet_id: ctx.logger.info("Start to delete subnet {0}...".format(subnet_id)) Helper().execute_request('vpc', 'delete_subnet', {'SubnetId': subnet_id}) ctx.logger.info( " Delete subnet {0} successfully".format(subnet_id)) else: ctx.logger.info( "Can not find subnet in runtime properties, skip the step.")
def delete(self): if not convert2bool(self.resource_config.get('allocate_eip', True)): return eip_id = ctx.instance.runtime_properties[common_constants.EXTERNAL_ID] request_body = { 'AllocationId': eip_id } ctx.logger.info('Start release eip with parameters:{}'.format(request_body)) Helper().execute_request('eip', 'release_address', request_body) ctx.logger.info('Finish release eip successfully...') ctx.instance.runtime_properties = {}
def resize(self, **kwargs): vm_id = ctx.instance.runtime_properties['external_id'] ins_type = kwargs.get("flavor", "") if not ins_type: ctx.logger.error( "The param `flavor` is required, received param is:{}".format( kwargs)) return params = dict(InstanceId=vm_id, InstanceType=ins_type) ret = Helper().execute_request("kec", "modify_instance_type", params) ctx.logger.error("resize vm:{}, params:{}, rest: {}".format( vm_id, params, ret)) self.wait_for_target_state( vm_id, (ksyun_constants.KS_INSTANCE_RESIZE_SUCCESS, ksyun_constants.KS_INSTANCE_MIGRATE_SUCCESS)) start_ret = Helper().execute_request('kec', 'start_instances', {"InstanceId.1": vm_id}) ctx.logger.error("reboot vm:{}, rest: {}".format(vm_id, start_ret)) self.wait_for_target_state(vm_id, ksyun_constants.KS_INSTANCE_STATE_ACTIVE) self.update_runtime_properties(vm_id)
def _create(self): ctx.logger.info('Start to create VPC...') params = { "VpcName": self.resource_config.get('vpc_name'), "CidrBlock": validate_parameter('cidr_block', self.resource_config), } ctx.logger.info('Try to create Vpc with parameters {}'.format(params)) res = Helper().execute_request('vpc', 'create_vpc', params) vpc_id = res['Vpc']['VpcId'] self.write_runtime(vpc_id) ctx.logger.info('Create Vpc {0} successfully'.format(vpc_id))
def _start(self, instance_id): vm_state = self.get_vm_state(instance_id) if vm_state == ksyun_constants.KS_INSTANCE_STATE_ACTIVE: ctx.logger.info("The virtual machine is active, No need to start!") return if vm_state != ksyun_constants.KS_INSTANCE_STATE_STOPPED: raise NonRecoverableError( "Only virtual machines that are in a stopped state can be started" ) else: Helper().execute_request('kec', 'start_instances', {"InstanceId.1": instance_id})
def create(self): slb_id = self.get_related_slb() if not slb_id: raise NonRecoverableError( 'Unable to obtain load balancer ID, single node deployment is not supported!' ) listener_params = self.prepare_params(slb_id) ctx.logger.info( 'Attempting to create listeners parameters: {0}'.format( listener_params)) result = Helper().execute_request('slb', 'create_listeners', listener_params) listener_id = result.get('ListenerId') if not listener_id: raise NonRecoverableError('Listener create failed!') self.update_listener_runtime(listener_id) ctx.logger.info( 'Create listeners: {0} successfully'.format(listener_id)) health_check_params = self.get_health_check_params(listener_id) ctx.logger.info( 'Attempting to create health check parameters: {0}'.format( health_check_params)) res = Helper().execute_request('slb', 'configure_health_check', health_check_params) health_check_id = res.get('HealthCheckId') if health_check_id: self.update_listener_runtime(listener_id) ctx.logger.info( 'Create listeners: {0} and health check: {1} successfully.'. format(listener_id, health_check_id)) else: raise NonRecoverableError('Create health check failed!')
def create_cloud_volume_snapshot(self, volume_id, name, desc): instance_id = ctx.instance.runtime_properties['external_id'] params = { 'VolumeId': volume_id, 'SnapshotName': name, 'SnapshotDesc': desc } self.wait_for_target_state(instance_id, (ksyun_constants.KS_INSTANCE_STATE_ACTIVE, ksyun_constants.KS_INSTANCE_STATE_STOPPED)) resp = Helper().execute_request('ebs', 'create_snapshot', params) self.wait_for_snapshot_available('cloud_volume', snapshot_id=resp['SnapshotId'])
def _stop(self, instance_id): vm_state = self.get_vm_state(instance_id) if not vm_state: ctx.logger.info( "The virtual machine isnot exist, No need to stop!") return "not exist" if vm_state == ksyun_constants.KS_INSTANCE_STATE_STOPPED: ctx.logger.info("The virtual machine is stopped, No need to stop!") return stop_params = { "InstanceId.1": instance_id, "ForceStop": True, "StoppedMode": "StopCharging" } Helper().execute_request('kec', 'stop_instances', stop_params)
def create(self): ''' There will be two situations: 1.EIP is to be created with no relationship 2.EIP is to be created with instance and should be associate with instance ''' if not convert2bool(self.resource_config.get('allocate_eip', True)): return if self.use_external_resource: self._create_external_eip() return resource_config = ctx.node.properties['resource_config'] ctx.logger.info('Allocate Eip...resource_config:{}'.format(resource_config)) request_body = { 'BandWidth': validate_parameter('band_width', resource_config), 'ChargeType': resource_config.get('charge_type', 'HourlyInstantSettlement'), } line_id = resource_config.get('line_id', None) if line_id: request_body['LineId'] = line_id ctx.logger.info('Allocate Eip...request_body:{}'.format(request_body)) eip_obj = Helper().execute_request('eip', 'allocate_address', request_body) ctx.logger.info('Allocate Eip successfully....Eip info:{}'.format(eip_obj)) self.update_eip_runtime(eip_obj.get('AllocationId'))
def wait_eip_for_target_state(self, eip_id, statuses, timeout=600, interval=15): request_body = {'AllocationId.1': eip_id} eip_info = Helper().execute_request('eip', 'describe_addresses', request_body)['AddressesSet'][0] while timeout: if eip_info['State'] in statuses: return eip_info ctx.logger.info( 'Wait Eip:{} to be status:{},current status:{}...'.format( eip_id, ','.join(statuses), eip_info['State'])) time.sleep(interval) timeout -= interval raise NonRecoverableError( "Waiting eip to target state failed! the current " "state is {0}, the target state:{1}".format( eip_info['State'], ','.join(statuses)))
def disassociate_eip(self): if not self.is_allocated_eip(): return eip_obj = self.get_eip() eip_id = eip_obj.runtime_properties[common_constants.EXTERNAL_ID] ctx.logger.info('Disassociate EIP id:{}'.format(eip_id)) request_body = {'AllocationId': eip_id} ctx.logger.info('Start to disassociate EIP:{}...'.format(eip_id)) Helper().execute_request('eip', 'disassociate_address', request_body) self.wait_eip_for_target_state( eip_id, [ksyun_constants.KS_EIP_STATE_DISASSOCIATE]) vm = ctx.instance networks = vm.runtime_properties['networks'] networks.pop('public_ip') vm.runtime_properties['networks'] = networks vm_info = self.describe_vm( vm.runtime_properties[common_constants.EXTERNAL_ID]) if vm_info: vm.runtime_properties['ip'] = vm_info['PrivateIpAddress'] vm.update() self.update_eip_runtime() ctx.logger.info('Disassociate EIP successfully...')