Example #1
0
def update_ecs_status():
    resp = {}
    host_list = Host.objects.all()
    request = DescribeInstancesRequest()

    # Get all host from Host model
    yjh_clt = client.AcsClient(yjh_credentials.AK, yjh_credentials.SK,
                               'cn-shenzhen')
    tbus_clt = client.AcsClient(tbus_credentials.AK, tbus_credentials.SK,
                                'cn-shenzhen')
    for host in host_list:
        if host.org.code == 'YJH':
            clt = yjh_clt
        elif host.org.code == 'TBUS':
            clt = tbus_clt
        else:
            # skip BIZ org
            continue
        request.set_InstanceName(host.hostname)
        response = _send_request(request, clt)
        if response is not None:
            try:
                instance_detail = response.get('Instances').get('Instance')[0]
                status = instance_detail.get('Status')
                expire_time = instance_detail.get('ExpiredTime')
                resp[host.hostname] = [status, expire_time]
                host.status = status.lower()
                host.expiration_date = parser.parse(expire_time)
                host.save()
            except IndexError:
                raise IndexError(
                    'response is empty, please check host and org')
    return resp
Example #2
0
def getInstance(client, instance_name=None, instance_ids=None):
    request = DescribeInstancesRequest()
    request.set_accept_format('json')
    if instance_ids:
        request.set_InstanceIds(instance_ids)
    if instance_name:
        request.set_InstanceName(instance_name)

    response = client.do_action_with_exception(request)
    return response
Example #3
0
def get_instance_by_name(name):
    request_describe_instances = DescribeInstancesRequest()
    request_describe_instances.set_InstanceName(name)
    request_describe_instances.set_PageSize(100)

    response = sendrequest(request_describe_instances)
    if response is None:
        logger.error(
            f"Failed to get ECS by name({name}), please check above log")
        return None

    logger.info(
        f"Successfully get {response.get('TotalCount')} ECS(s) by name({name})."
    )

    #[{"ResourceGroupId":"","Memory":2048,"InstanceChargeType":"PostPaid","Cpu":2,"OSName":"CentOS  7.8 64位","InstanceNetworkType":"vpc","InnerIpAddress":{"IpAddress":[]},"ExpiredTime":"2099-12-31T15:59Z","ImageId":"centos_7_8_x64_20G_alibase_20200622.vhd","EipAddress":{"AllocationId":"","IpAddress":"","InternetChargeType":""},"HostName":"main","VlanId":"","Status":"Running","MetadataOptions":{"HttpTokens":"","HttpEndpoint":""},"InstanceId":"i-uf6ddw7sm2rjqzk6kt5a","StoppedMode":"Not-applicable","CpuOptions":{"ThreadsPerCore":2,"Numa":"ON","CoreCount":1},"StartTime":"2020-07-31T17:26Z","DeletionProtection":false,"SecurityGroupIds":{"SecurityGroupId":["sg-uf6isrfirr1cm5t11h81"]},"VpcAttributes":{"PrivateIpAddress":{"IpAddress":["192.168.7.1"]},"VpcId":"vpc-uf6o8756puxsi6yrtukv5","VSwitchId":"vsw-uf6eb8cjpyi92lzkx4il0","NatIpAddress":""},"InternetChargeType":"PayByBandwidth","InstanceName":"main","DeploymentSetId":"","InternetMaxBandwidthOut":1,"SerialNumber":"abe536e8-5d76-47ba-9f77-7ae1fc999660","OSType":"linux","CreationTime":"2020-07-13T05:45Z","AutoReleaseTime":"","Description":"","InstanceTypeFamily":"ecs.t6","DedicatedInstanceAttribute":{"Tenancy":"","Affinity":""},"PublicIpAddress":{"IpAddress":["106.14.188.212"]},"GPUSpec":"","NetworkInterfaces":{"NetworkInterface":[{"PrimaryIpAddress":"192.168.7.1","NetworkInterfaceId":"eni-uf6i39kqgewm4ud72b9g","MacAddress":"00:16:3e:10:9d:df"}]},"SpotPriceLimit":0.0,"DeviceAvailable":true,"SaleCycle":"","InstanceType":"ecs.t6-c1m1.large","OSNameEn":"CentOS  7.8 64 bit","SpotStrategy":"NoSpot","IoOptimized":true,"ZoneId":"cn-shanghai-g","ClusterId":"","EcsCapacityReservationAttr":{"CapacityReservationPreference":"","CapacityReservationId":""},"DedicatedHostAttribute":{"DedicatedHostId":"","DedicatedHostName":""},"GPUAmount":0,"OperationLocks":{"LockReason":[]},"InternetMaxBandwidthIn":80,"Recyclable":false,"RegionId":"cn-shanghai","CreditSpecification":"Standard"}]
    return response.get('Instances').get('Instance')
Example #4
0
    instance_amount = 1

    ordered_hours = 1  # generate auto release time according to ordered hours
    time_now_utc = datetime.datetime.utcnow()
    release_time = time_now_utc + datetime.timedelta(hours=ordered_hours)
    auto_release_time = release_time.strftime('%Y-%m-%dT%H:%M:%SZ')
    instance_name = 'geth-pbft-%s' % time_now_utc.strftime('%Y%m%dT%H%M%S')
    instances = AliyunRunInstances(aliyun_region_id[1], image_id,
                                   instance_type, instance_amount,
                                   auto_release_time, instance_name,
                                   is_dry_run)
    instances.run()

    print('waiting...')
    time.sleep(20)
    # ------------------------------------------------------------------
    # write IP addresses of instances to file
    client = AcsClient(ACCESS_KEY_ID, ACCESS_SECRET, 'cn-zhangjiakou')
    request = DescribeInstancesRequest()
    request.set_accept_format('json')
    request.set_PageSize(100)
    request.set_InstanceName("geth-pbft*")
    response = client.do_action_with_exception(request)

    r = json.loads(str(response, encoding='utf-8'))
    instances = (r['Instances']['Instance'])
    ips = [ins['PublicIpAddress']['IpAddress'][0] + '\n' for ins in instances]
    print(len(ips), ips)
    with open('../config/my_ip.txt', 'w') as ip_file:
        ip_file.writelines(ips)