def create_subnets(request, data, region, vpc): """ 创建子网 :param request: :param data: 前端按钮v,p :param region: 金山云区域 :param vpc: vpc_id :return: """ s = get_session() client_vpc = s.create_client("vpc", region, use_ssl=False, ks_access_key_id=ACCESS_KEY_ID, ks_secret_access_key=SECRET_ACCESS_KEY) cidrblock_re = '' cidrblock = [] subnetname_list = [] subnet_list = [] subnet_num = [] subnetname_new = [] subnet_new = '' # print(data, region, vpc) # for v in client_vpc.describe_subnets(**{"Dns2.1": ['InstanceId']})['SubnetSet']: # print('v---------->:', v) # 根据VPCID切子网段,用于拼接新的子网 for k in client_vpc.describe_vpcs()['VpcSet']: if k['VpcId'] == vpc: # print(k) cidrblock.append(k['CidrBlock']) cidrblock_re = ".".join(k['CidrBlock'].split(".")[0:2]) + "." # print('cidrblock_re:', type(cidrblock_re), cidrblock_re, cidrblock) # 根据VPCID取出的子网的名称和所有已有子网 for i in client_vpc.describe_subnets()['SubnetSet']: if i['VpcId'] == vpc: # print('****', i) # subnets[i['SubnetName']] = i['CidrBlock'] subnetname_list.append(i['SubnetName']) subnet_list.append(i['CidrBlock']) # print(subnetname_list, subnet_list) # 根据创建时根据当前最大名称排序+1(v)或者-1(p)的原则组成新的子网名称, for s_num in subnetname_list: if s_num.startswith(data): # print(s_num, re.findall(r'\d+', s_num)) # print(s_num, s_num.split('_')[0].split(data)[1]) for x in re.findall(r'\d+', re.split('_', s_num, 1)[0]): subnet_num.append(int(x)) # print(type(subnet_num[0]), subnet_num) # print('max_num:', subnet_num) # 创建子网 count = 0 while count < 5: count += 1 # print('count:', count) subnetname_new = data + str(max(subnet_num) + count) + '_' + 'subnet' # print(subnetname_new) if data == 'v': subnet_new = cidrblock_re + str(max(subnet_num)+count) + '.0/24' # print(subnet_new) if subnet_new in subnet_list: # print('aaa', subnet_new) continue else: # print('bbb', subnet_new) client_vpc.create_subnet(AvailabilityZoneName=region, SubnetName=subnetname_new, CidrBlock=subnet_new, SubnetType='Normal', DhcpIpFrom=cidrblock_re + str(max(subnet_num)+count) + '.2', DhcpIpTo=cidrblock_re + str(max(subnet_num)+count) + '.253', GatewayIp=cidrblock_re + str(max(subnet_num)+count) + '.1', Dns1='198.18.254.30', Dns2='198.18.254.31', VpcId=vpc) # print(cidrblock_re + str(max(subnet_num)+count) + '.2') break if data == 'p': subnet_new = cidrblock_re + str(254 - (max(subnet_num)+count)) + '.0/24' # print(subnet_new) if subnet_new in subnet_list: # print('aaa', subnet_new) continue else: # print('aaa', subnet_new) client_vpc.create_subnet(AvailabilityZoneName=region, SubnetName=subnetname_new, CidrBlock=subnet_new, SubnetType='Normal', DhcpIpFrom=cidrblock_re + str(254 - (max(subnet_num) + count)) + '.2', DhcpIpTo=cidrblock_re + str(254 - (max(subnet_num) + count)) + '.253', GatewayIp=cidrblock_re + str(254 - (max(subnet_num) + count)) + '.1', Dns1='198.18.254.30', Dns2='198.18.254.31', VpcId=vpc) # print(cidrblock_re + str(254 - (max(subnet_num) + count)) + '.2') break # return HttpResponse('dididi') return JsonResponse({'data': subnet_new})
# -*- encoding:utf-8 -*- from kscore.session import get_session import json #初始化 s = get_session() #注:参数不能改变 client = s.create_client("offline", "cn-beijing-6", use_ssl=False) #创建模板接口调用示例 : preset presetname = 'testpreset' description = 'just a demo' presetType = 'avop' #具体的格式请参考官网说明 param = { "preset": presetname, "description": description, "presettype": presetType, "param": { "f": "mp4", "AUDIO": { "acodec": "aac", "ar": "44100", "ab": "64k" }, "VIDEO": { "vr": 25, "vb": "500k", "vcodec": "h264", "width": 640,
def createSdkClinet(service, region): s = get_session() s.set_credentials(ak, sk) client = s.create_client(service, region, use_ssl=True) return client
# -*- encoding:utf-8 -*- from kscore.session import get_session if __name__ == "__main__": s = get_session() client = s.create_client("kog", use_ssl=True) projects = client.get_project_list() project = client.add_project(name='123123', comment='123123') project.update(name="bcd") client.edit_project(**project) client.delete_project(id=project['id']) assert projects == client.get_project_list()
when='D', interval=1, backupCount=100) except (IOError, OSError): print 'can not write log file to [%s]' % g_config['log_path'] return False formatter = logging.Formatter(format_str) handler_file.setFormatter(formatter) g_logger.addHandler(handler_file) return True if __name__ == '__main__': if not _load_config(): sys.exit(-1) if not _init_log(): sys.exit(-1) g_session = get_session() server = _threaded_httpserver((g_config['bind_ip'], g_config['bind_port']), _request_handler) g_logger.info('run server on %s:%s', g_config['bind_ip'], g_config['bind_port']) try: server.serve_forever() except KeyboardInterrupt: g_logger.info('receive keyboard interrupt, quit program')
def eip_key(self,module="eip",region="cn-beijing-6"): client = get_session().create_client(module,region,ks_access_key_id=self.ACCESS_KEY_ID, ks_secret_access_key=self.SECRET_ACCESS_KEY,use_ssl=False) return client
def monitor_key(self,module="monitor",region="cn-beijing-6",): client = get_session().create_client(module,region,ks_access_key_id=self.ACCESS_KEY_ID, ks_secret_access_key=self.SECRET_ACCESS_KEY,use_ssl=True) return client
def create_ecs(form_data): try: client = get_session().create_client("kec", form_data['region'], use_ssl=False, ks_access_key_id=settings.ACCESS_KEY_ID, ks_secret_access_key=settings.SECRET_ACCESS_KEY) results = [] for hostname in form_data['hostnames_I18B']: run_result = client.run_instances(ImageId='cb7a02d2-a6e2-4bc4-a3a0-5ee8b131a451', InstanceType='I1.8B', DataDiskGb=500, MaxCount=1, MinCount=1, InstancePassword='******', SubnetId=form_data['subnet'], SecurityGroupId='1f66de4c-a5c2-4e94-a416-58ec0b5a5a21', InstanceName=hostname, ChargeType='Daily' ) log.info("I18B: ", run_result) results.extend(run_result['InstancesSet']) for hostname in form_data['hostnames_I18A']: run_result = client.run_instances(ImageId='cb7a02d2-a6e2-4bc4-a3a0-5ee8b131a451', InstanceType='I1.8A', DataDiskGb=200, MaxCount=1, MinCount=1, InstancePassword='******', SubnetId=form_data['subnet'], SecurityGroupId='1f66de4c-a5c2-4e94-a416-58ec0b5a5a21', InstanceName=hostname, ChargeType='Daily' ) log.info("I18A: ", run_result) results.extend(run_result['InstancesSet']) for hostname in form_data['hostnames_I14B']: run_result = client.run_instances(ImageId='cb7a02d2-a6e2-4bc4-a3a0-5ee8b131a451', InstanceType='I1.4B', DataDiskGb=200, MaxCount=1, MinCount=1, InstancePassword='******', SubnetId=form_data['subnet'], SecurityGroupId='1f66de4c-a5c2-4e94-a416-58ec0b5a5a21', InstanceName=hostname, ChargeType='Daily' ) log.info("I14B: ", run_result) results.extend(run_result['InstancesSet']) for hostname in form_data['hostnames_I14C']: run_result = client.run_instances(ImageId='cb7a02d2-a6e2-4bc4-a3a0-5ee8b131a451', InstanceType='I1.4C', DataDiskGb=200, MaxCount=1, MinCount=1, InstancePassword='******', SubnetId=form_data['subnet'], SecurityGroupId='1f66de4c-a5c2-4e94-a416-58ec0b5a5a21', InstanceName=hostname, ChargeType='Daily' ) print("I14C: ", run_result) results.extend(run_result['InstancesSet']) log.info("ECS创建成功!") log.info(results) print(results) waiting_ecs(results, form_data) print(results) init_task = init_ecs.delay(results) return results, init_task.id except Exception as e: traceback.print_exc()
def waiting_ecs(ecs_list, form_data): """ 等待机器running,返回ID,内网IP等信息 :param ecs_list: [{InstanceId, InstanceName, PrivateId, PublicId}...] :param form_data: 表单数据 :return: [{InstanceId, InstanceName, PrivateId, PublicId}...] 直接修改ecs_list参数,不返回任何值 """ print("start ansible") client = get_session().create_client("kec", form_data['region'], use_ssl=False, ks_access_key_id=settings.ACCESS_KEY_ID, ks_secret_access_key=settings.SECRET_ACCESS_KEY) instances_args = {} for i in range(0, len(ecs_list)): instances_args['InstanceId.' + str(i + 1)] = ecs_list[i]['InstanceId'] print('\tadd arg: ', 'InstanceId.' + str(i + 1), ecs_list[i]['InstanceId']) print("args: ", instances_args) for i in range(0, 60): time.sleep(5) print("fetching instances") status = client.describe_instances(**instances_args) print(status) log.info("hhhhh::", status) try: # str_status = str(status) # 是否继续等待的标志,如果状态有不为active的将继续循环等待 loop_flag = False for _st in status['InstancesSet']: if 'InstanceState' in _st and 'Name' in _st['InstanceState'] \ and _st['InstanceState']['Name'] == 'active' and 'PrivateIpAddress' in _st: continue else: loop_flag = True break if loop_flag: continue # if str_status and 'scheduling' not in str_status and 'spawning' not in str_status: # 将内网IP地址写入ecs_list对应的实例信息中 for _instance_detail in status['InstancesSet']: for _instance_data in ecs_list: if _instance_data['InstanceId'] == _instance_detail['InstanceId']: _instance_data['PrivateIp'] = _instance_detail['PrivateIpAddress'] break break except Exception as e: traceback.print_exc() else: # 150 秒内 创建的机器仍有调度中的机器 print("Create ECS ERROR, has scheduling status.") print("bind EIP to kf_master starting...") for instance_detail in ecs_list: if 'kf_master' in instance_detail['InstanceName']: kf_master = client.describe_instances(**{"InstanceId.1": instance_detail['InstanceId']}) print("即将绑定EIP到kf_master,主机信息:", kf_master) if len(kf_master['InstancesSet']) == 0: print("不存在kf_master主机!") continue try: eip_client = get_session().create_client("eip", form_data['region'], use_ssl=False, ks_access_key_id=settings.ACCESS_KEY_ID, ks_secret_access_key=settings.SECRET_ACCESS_KEY) # 链路ID 对应于BGP, 使用eip_client.describe_addresses()查询 eip = eip_client.allocate_address(ChargeType="Daily", BandWidth=50, LineId='5fc2595f-1bfd-481b-bf64-2d08f116d800') # eip格式:{'PublicIp': '120.92.18.69', 'RequestId': '49363671-fa53-4c98-a286-eb3c5605f710', 'AllocationId': '0395cf2e-f26d-46c4-826d-c23002b59158'} print("创建EIP成功:", eip) print("正在绑定EIP:AllocationId=%s, InstanceType=%s, InstanceId=%s, NetworkInterfaceId=%s" % (eip['AllocationId'], 'Ipfwd', kf_master['InstancesSet'][0]['InstanceId'], kf_master['InstancesSet'][0]['NetworkInterfaceSet'][0]['NetworkInterfaceId'])) eip_result = eip_client.associate_address(AllocationId=eip['AllocationId'], InstanceType='Ipfwd', InstanceId=kf_master['InstancesSet'][0]['InstanceId'], NetworkInterfaceId= kf_master['InstancesSet'][0]['NetworkInterfaceSet'][0][ 'NetworkInterfaceId']) # eip_result格式:{'RequestId': 'bfc3c418-222d-4e0a-b16e-e276545a350a', 'Return': True} print("绑定EIP结果:", eip_result) if eip_result['Return']: print("绑定成功") instance_detail['PublicIp'] = eip['PublicIp'] else: print("绑定失败!") except Exception as e: traceback.print_exc() # print(client.allocate_address(ChargeType="Daily", BandWidth=50, LineId='5fc2595f-1bfd-481b-bf64-2d08f116d800')) # {'AllocationId': '478a2f0b-5dfb-404d-bba8-0120787e93ee', 'PublicIp': '120.92.93.112', 'RequestId': '7b750f99-08d9-47e8-97f4-87de4d9ffd64'} print("bind EIP to kf_master success")