def setUp(self): access_key = 'ak' secret_key = 'sk' self.credential = Credential(access_key, secret_key) # 指定使用http方式访问vpc专用域名,超时为20s config = Config('vm.internal.cn-north-1.jdcloud-api.com', SCHEME_HTTP, 20) logger = Logger( 3 ) # FATAL = 0 ERROR = 1 WARN = 2 INFO = 3;如果不想输出日志,可将日志级别设置为0(FATAL);不设置logger,则默认为INFO self.client = VmClient(self.credential, config, logger)
def __init__(self, access_key, secret_key, regionId, az, instanceType, imageId,\ name, password, maxCount=1, chargeSpec=None, description=None): self.regionId = regionId self.az = az # E.G. 'g.s1.micro' self.instanceType = instanceType self.imageId = imageId # instance name prefix self.name = name self.password = password self.maxCount = maxCount # Default None: postpaid_by_duration:按配置后付费 self.chargeSpec = chargeSpec self.description = description # InstanceDiskAttachmentSpec[] self.dataDiskSpec = [] self.elasticIpSpec = None self.credential = Credential(access_key, secret_key) self.client = VmClient(self.credential) print 'Client created...'
import sys # ak & sk access_key = 'ak' secret_key = 'sk' # 区域resion id region_id = 'cn-north-1' # 弹性网卡ID ENI = 'port-ejuyeng7qs' # 本实例ID thisVmId = 'i-3ltkvzycml' # 对方实例ID thatVmId = 'i-yupwhaqzet' myCredential = Credential(access_key, secret_key) myClient = VmClient(myCredential) # 日志输出至/etc/keepalived/keepalived.log logger = logging.getLogger("KeepAlived") formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s') # 输出到文件pgy.log file_handler = logging.FileHandler("keepalived.log") file_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.setLevel(logging.INFO) def attach_eni(instanceId, networkInterfaceId): logger.info('Trying to attach elastic NI to ' + instanceId) try: parameters = AttachNetworkInterfaceParameters(instanceId=instanceId, regionId=region_id, \
def getVmClient(accessKey, secretKey): credential = Credential(accessKey, secretKey) logger = Logger(2) config = Config(timeout=1000) client = VmClient(credential, logger=logger, config=config) return client
def setUp(self): access_key = 'ak' secret_key = 'sk' self.credential = Credential(access_key, secret_key) self.client = VmClient(self.credential)
class VmTest(unittest.TestCase): def setUp(self): access_key = 'ak' secret_key = 'sk' self.credential = Credential(access_key, secret_key) self.client = VmClient(self.credential) # def testDescribeInstanceTypes(self): # parameters = DescribeInstanceTypesParameters('cn-north-1') # request = DescribeInstanceTypesRequest(parameters) # # resp = self.client.send(request) # self.assertTrue(resp.error is None) # # def testDescribeInstances(self): # param = DescribeInstancesParameters('cn-north-1') # request = DescribeInstancesRequest(param) # # resp = self.client.send(request) # self.assertTrue(resp.error is None) # # def testDescribeInstancesPaging(self): # param = DescribeInstancesParameters('cn-north-1') # param.setPageNumber(2) # param.setPageSize(10) # request = DescribeInstancesRequest(param) # # resp = self.client.send(request) # self.assertEqual(10, len(resp.result['instances'])) # # def testDescribeInstancesFilter(self): # f = Filter('instanceId', ['i-6e67ykot7m'], 'eq') # param = DescribeInstancesParameters('cn-north-1') # param.setFilters([f]) # request = DescribeInstancesRequest(param) # # resp = self.client.send(request) # self.assertEqual(1, len(resp.result['instances'])) # # def testDescribeInstance(self): # param = DescribeInstanceParameters('cn-north-1', 'i-6e67ykot7m') # request = DescribeInstanceRequest(param) # # resp = self.client.send(request) # self.assertTrue(resp.error is None) def testCreateAndDeleteInstance(self): # create instance networkInterface = NetworkInterfaceSpec(az='cn-north-1a', subnetId='subnet-crpgl13lsv') network = InstanceNetworkInterfaceAttachmentSpec( networkInterface=networkInterface) sysDisk = InstanceDiskAttachmentSpec('local') instanceSpec = InstanceSpec( az='cn-north-1a', instanceType='g.s1.micro', name='python-sdk-test', imageId='7f7cc799-04dd-44a9-89f1-486de8bfed08', primaryNetworkInterface=network, systemDisk=sysDisk, dataDisks=None, keyNames=None, description='python-sdk-vm') param = CreateInstancesParameters('cn-north-1') param.setInstanceSpec(instanceSpec) param.setMaxCount(1) request = CreateInstancesRequest(param) create_resp = self.client.send(request) print create_resp print "=========================" self.assertTrue(create_resp.error is None) instance_id = create_resp.result['instanceIds'][0] # stop instance def _stop_instance(): param = StopInstanceParameters('cn-north-1', instance_id) request = StopInstanceRequest(param) #stop_resp = self.client.send(request) #return stop_resp.error is None print "not stop instance dueto need attach vol" return request result = self._try(10, 5, _stop_instance) self.assertTrue(result) # delete instance, may need try many times def _delete_instance(): param = DeleteInstanceParameters('cn-north-1', instance_id) request = DeleteInstanceRequest(param) #delete_resp = self.client.send(request) #return delete_resp.error is None print "~~~~~~~~~~~~~~~~~~" print instance_id print "~~~~~~~~~~~~~~~~~~" return instance_id result = self._try(10, 5, _delete_instance) self.assertTrue(result) def _try(self, count, wait, func): try_count = count result = False while try_count > 0: print 'try_count=', try_count time.sleep(wait) result = func() if result: break try_count -= 1 return result
class VmTest(unittest.TestCase): def setUp(self): access_key = 'ak' secret_key = 'sk' self.credential = Credential(access_key, secret_key) self.client = VmClient(self.credential) def testDescribeInstanceTypes(self): parameters = DescribeInstanceTypesParameters('cn-north-1') request = DescribeInstanceTypesRequest(parameters) resp = self.client.send(request) self.assertTrue(resp.error is None) def testDescribeInstances(self): param = DescribeInstancesParameters('cn-north-1') request = DescribeInstancesRequest(param) resp = self.client.send(request) self.assertTrue(resp.error is None) def testDescribeInstancesPaging(self): param = DescribeInstancesParameters('cn-north-1') param.setPageNumber(2) param.setPageSize(10) request = DescribeInstancesRequest(param) resp = self.client.send(request) self.assertEqual(10, len(resp.result['instances'])) def testDescribeInstancesFilter(self): f = Filter('instanceId', ['i-d4c1a56z3p'], 'eq') param = DescribeInstancesParameters('cn-north-1') param.setFilters([f]) request = DescribeInstancesRequest(param) resp = self.client.send(request) self.assertEqual(1, len(resp.result['instances'])) def testDescribeInstance(self): param = DescribeInstanceParameters('cn-north-1', 'i-d4c1a56z3p') request = DescribeInstanceRequest(param) resp = self.client.send(request) self.assertTrue(resp.error is None) def testCreateAndDeleteInstance(self): # create instance networkInterface = NetworkInterfaceSpec(az='cn-north-1a', subnetId='subnet-3dm13k30gh') network = InstanceNetworkInterfaceAttachmentSpec(networkInterface=networkInterface) sysDisk = InstanceDiskAttachmentSpec('local') instanceSpec = InstanceSpec(az='cn-north-1a', instanceType='g.s1.micro', name='python-sdk-test', imageId='98d44a0f-88c1-451a-8971-f1f769073b6c', primaryNetworkInterface=network, systemDisk=sysDisk, dataDisks=None, keyNames=None, description='python-sdk-vm') param = CreateInstancesParameters('cn-north-1') param.setInstanceSpec(instanceSpec) param.setMaxCount(1) request = CreateInstancesRequest(param) create_resp = self.client.send(request) self.assertTrue(create_resp.error is None) instance_id = create_resp.result['instanceIds'][0] # stop instance def _stop_instance(): param = StopInstanceParameters('cn-north-1', instance_id) request = StopInstanceRequest(param) stop_resp = self.client.send(request) return stop_resp.error is None result = self._try(10, 5, _stop_instance) self.assertTrue(result) # delete instance, may need try many times def _delete_instance(): param = DeleteInstanceParameters('cn-north-1', instance_id) request = DeleteInstanceRequest(param) delete_resp = self.client.send(request) return delete_resp.error is None result = self._try(10, 5, _delete_instance) self.assertTrue(result) def _try(self, count, wait, func): try_count = count result = False while try_count > 0: print 'try_count=', try_count time.sleep(wait) result = func() if result: break try_count -= 1 return result
class NewInstances(object): def __init__(self, access_key, secret_key, regionId, az, instanceType, imageId,\ name, password, maxCount=1, chargeSpec=None, description=None): self.regionId = regionId self.az = az # E.G. 'g.s1.micro' self.instanceType = instanceType self.imageId = imageId # instance name prefix self.name = name self.password = password self.maxCount = maxCount # Default None: postpaid_by_duration:按配置后付费 self.chargeSpec = chargeSpec self.description = description # InstanceDiskAttachmentSpec[] self.dataDiskSpec = [] self.elasticIpSpec = None self.credential = Credential(access_key, secret_key) self.client = VmClient(self.credential) print 'Client created...' def setNetworkSpec(self, subnetId, primaryIpAddress=None, securityGroups=None): # Necessary: subnetID Optional: primaryIpAddress/securityGroups new_networkinterface = NetworkInterfaceSpec(subnetId=subnetId, az=self.az, primaryIpAddress=primaryIpAddress,\ securityGroups=securityGroups) self.networkSpec = InstanceNetworkInterfaceAttachmentSpec( networkInterface=new_networkinterface) print 'NetworkSpec created...' print 'SubnetID: ' + self.networkSpec.networkInterface.subnetId def setChargeSpec(self, chargeMode=None, chargeUnit=None, chargeDuration=None): # chargeMode: prepaid_by_duration:预付费,postpaid_by_usage:按用量后付费,postpaid_by_duration:按配置后付费,默认为postpaid_by_duration self.chargeSpec = ChargeSpec(chargeMode, chargeUnit, chargeDuration) print 'ChargeSpec created...' print 'ChargeMode: ' + self.chargeSpec.chargeMode def setSystemDisk(self): # System disk: diskCategory='local' self.systemDiskSpec = InstanceDiskAttachmentSpec(diskCategory='local') print 'SystemDiskSpec created...' print 'SystemDisk: ' + self.systemDiskSpec.diskCategory def setDataDisk(self, name, diskSizeGB, diskType, snapshotId=None): # Data disk: diskCategory='cloud' new_diskspec = DiskSpec(az=self.az, name=name, diskType=diskType, diskSizeGB=diskSizeGB, snapshotId=snapshotId) new_instanceDiskAttachmentSpec = InstanceDiskAttachmentSpec( diskCategory='cloud', cloudDiskSpec=new_diskspec) self.dataDiskSpec.append(new_instanceDiskAttachmentSpec) print 'DataDiskSpec created...' print 'DataDisk: ' + new_instanceDiskAttachmentSpec.diskCategory def setElasticIp(self, bandwidthMbps, provider): # bandwidthMbps(Integer), provider: 'bgp' or 'no_bgp' self.elasticIpSpec = ElasticIpSpec(bandwidthMbps, provider, self.chargeSpec) print 'ElasticIPSpec created...' print 'BandWidth: ', self.elasticIpSpec.bandwidthMbps, ' provider: ', self.elasticIpSpec.provider def createInstances(self): # Create instances and get the response # Return list: str[] print 'Creating instances...' instanceSpec = InstanceSpec(az=self.az, instanceType=self.instanceType, imageId=self.imageId,\ name=self.name, keyNames=None, primaryNetworkInterface=self.networkSpec,\ systemDisk=self.systemDiskSpec, dataDisks=self.dataDiskSpec, description=self.description,\ password=self.password, elasticIp=self.elasticIpSpec, charge=self.chargeSpec) # Create Instance Parameters newParam = CreateInstancesParameters(self.regionId) newParam.setInstanceSpec(instanceSpec) newParam.setMaxCount(self.maxCount) # Create Request newRequest = CreateInstancesRequest(newParam) # Client send request resp = self.client.send(newRequest) if resp.error is not None: print resp.error.code, resp.error.message my_resp = [] #from unicode to utf8 for i in resp.result['instanceIds']: my_resp.append(i.encode("utf-8")) return my_resp