Ejemplo n.º 1
0
def getImages():
    request = DescribeImagesRequest()
    request.set_accept_format('json')
    response = client.do_action_with_exception(request)
    response = json.loads(str(response, encoding='utf-8'))

    return response
def __get_img_id(image_name, region):
    request = DescribeImagesRequest()
    request.set_accept_format('json')
    result = do_action(request, region)
    for k, v in result['Images'].iteritems():
        for i in v:
            if image_name == i['ImageName']:
                return i['ImageId']
    return None
Ejemplo n.º 3
0
 def refresh(self):
     request = DescribeImagesRequest()
     request.set_ImageId(self.image_id)
     items = _get_response(self._client, request, {}, 'Images.Image')
     if not items:
         raise ClientException(
             errors.ERROR_INVALID_SERVER_RESPONSE,
             "Failed to find image data from DescribeImages "
             "response. "
             "ImageId = {0}".format(self.image_id))
     self._assign_attributes(items[0])
Ejemplo n.º 4
0
    def get_image_id(self, img_name):
        request = DescribeImagesRequest()
        request.set_accept_format('json')
        request.set_ImageOwnerAlias("self")
        request.set_PageSize(20)
        response = self.client.do_action_with_exception(request)
        response = json.loads(response)
        totalcount = response["TotalCount"]

        iteration = totalcount // 20
        if iteration * 20 < totalcount:
            iteration += 1

        for ii in range(1, iteration + 1):
            count = 0
            flag = 0
            request.set_PageNumber(ii)
            while count < 10:
                try:
                    response = self.client.do_action_with_exception(request)
                    response = json.loads(response)
                    for img in response["Images"]["Image"]:
                        if img["ImageName"] == img_name:
                            return img["ImageId"]
                    flag = 1
                    break
                except:
                    count += 1
                    time.sleep(10)
        if not flag:
            dlog.info("get image failed, exit")
            sys.exit()
def describe_images(image_id, image_name):
    """Print description of an image with matching id or name."""
    request = DescribeImagesRequest()
    if image_id:
        request.set_ImageId(image_id)
    if image_name:
        request.set_ImageName(image_name)
    return request
Ejemplo n.º 6
0
 def describe_images(self, image_id, image_name):
     """ Send request to get details of images
         Filter by image id and name
         Return Alibaba response """
     request = DescribeImagesRequest()
     if image_id:
         request.set_ImageId(image_id)
     if image_name:
         request.set_ImageName(image_name)
     return self.__send_request(request)
Ejemplo n.º 7
0
 def get_image_id(self, img_name):
     request = DescribeImagesRequest()
     request.set_accept_format('json')
     request.set_ImageOwnerAlias("self")
     response = self.client.do_action_with_exception(request)
     response = json.loads(response)
     for img in response["Images"]["Image"]:
         if img["ImageName"] == img_name:
             return img["ImageId"]
Ejemplo n.º 8
0
 def get_image_id(self, img_name):
     request = DescribeImagesRequest()
     request.set_accept_format('json')
     request.set_ImageOwnerAlias("self")
     request.set_PageSize(100)
     count = 0
     flag = 0
     while count < 10:
         try:
             response = self.client.do_action_with_exception(request)
             response = json.loads(response)
             for img in response["Images"]["Image"]:
                 if img["ImageName"] == img_name:
                     return img["ImageId"]
             flag = 1
             break
         except:
             count += 1
             time.sleep(10)
     if not flag:
         dlog.info("get image failed, exit")
         sys.exit()
Ejemplo n.º 9
0
def get_img_from_region(region, status='Available'):
    client = AcsClient(__SK, __KEY, region)
    request = DescribeImagesRequest()
    request.set_accept_format('json')
    request.set_Status(status)
    result = json.loads(client.do_action_with_exception(request))
    images = dict()
    for k, v in result.iteritems():
        if k == 'Images':
            for i in v['Image']:
                if i['ImageOwnerAlias'] == 'self':
                    tmp = dict()
                    for key in IMAGE_RETURN_ATTR:
                        tmp[key] = i[key]
                    images[i['ImageName']] = tmp
                    continue
    return images
Ejemplo n.º 10
0
def make():
    security_group_dict = acdb.db.load(
        "security_group_dict")  # map[region_id]security_group_id
    region_instance_id_list = []

    # Check image id is avaliable
    for node_conf in conf.config["ecs"]["node"]:
        print("Get request", node_conf)
        client = AcsClient(
            conf.secret["aliyun"]["access_key"],
            conf.secret["aliyun"]["access_secret"],
            node_conf["region_id"],
        )
        req = DescribeImagesRequest()
        req.set_Status("Available")
        req.set_ImageOwnerAlias("system")
        req.set_InstanceType(node_conf["instance_type"])
        req.set_OSType("linux")
        req.set_PageSize(100)
        req.set_ActionType("CreateEcs")
        res = json.loads(client.do_action_with_exception(req))
        all_avaliable_image = [e["ImageId"] for e in res["Images"]["Image"]]
        assert node_conf["image"] in all_avaliable_image

    # Create ECS instance
    for node_conf in conf.config["ecs"]["node"]:
        client = AcsClient(
            conf.secret["aliyun"]["access_key"],
            conf.secret["aliyun"]["access_secret"],
            node_conf["region_id"],
        )
        req = CreateInstanceRequest()
        req.set_ImageId(node_conf["image"])
        req.set_SecurityGroupId(security_group_dict[node_conf["region_id"]])
        req.set_Password(conf.secret["aliyun"]["ecs_password"])
        req.set_InstanceChargeType("PostPaid")
        req.set_SystemDiskCategory("cloud_efficiency")
        req.set_SystemDiskSize(c_system_disk_size)
        req.set_InstanceType(node_conf["instance_type"])
        req.set_InternetMaxBandwidthOut(
            node_conf["internet_max_bandwidth_out"])
        req.set_KeyPairName(c_keypair_name)
        res = json.loads(client.do_action_with_exception(req))
        instance_id = res["InstanceId"]
        print("Create", node_conf["region_id"], instance_id)
        region_instance_id_list.append([node_conf["region_id"], instance_id])

    print("Wait")
    for _ in range(1 << 32):
        if sum([
                e["Status"] == "Stopped" for e in info(region_instance_id_list)
        ]) == len(region_instance_id_list):
            break

    for (region_id, instance_id) in region_instance_id_list:
        client = AcsClient(
            conf.secret["aliyun"]["access_key"],
            conf.secret["aliyun"]["access_secret"],
            region_id,
        )
        # Allocate public ip address
        req = AllocatePublicIpAddressRequest()
        req.set_accept_format("json")
        req.set_InstanceId(instance_id)
        client.do_action_with_exception(req)
        print("Allocate public ip address", region_id, instance_id)

        # Start ECS instance
        req = StartInstanceRequest()
        req.set_accept_format("json")
        req.set_InstanceId(instance_id)
        res = json.loads(client.do_action_with_exception(req))
        print("Start", region_id, instance_id)

    print("Wait")
    for _ in range(1 << 32):
        if sum([
                e["Status"] == "Running" for e in info(region_instance_id_list)
        ]) == len(region_instance_id_list):
            break

    # Get ECS info
    acdb.db.save("instance_list", info(region_instance_id_list))
    print(
        f"Instance info saved at {conf.config['db']['path']}/instance_list.json"
    )
Ejemplo n.º 11
0
def get_image_infos():
    imageclient = AcsClient(accessKeyId, accessSecret, regionId)
    request = DescribeImagesRequest()
    request.set_accept_format('json')
    request.set_PageSize(100)
    request.set_OSType("linux")
    request.set_Architecture("x86_64")
    # request.set_Usage("instance")
    request.set_ActionType("CreateEcs")
    response = imageclient.do_action_with_exception(request)
    res_image = json.loads(str(response, encoding='utf-8'))
    image_list = []
    for image in res_image['Images']['Image']:
        image_dict = {}
        image_dict['imageid'] = image['ImageId']
        image_dict['imageowner'] = image['ImageOwnerAlias']
        image_dict['name'] = image['ImageName']
        image_list.append(image_dict)
    # print(image_list)
    return image_list