Esempio n. 1
0
def main():
    client = Client({
        "region": "cn-bj2",
        "project_id": "org-5wakzh",
        "public_key": "",
        "private_key": "",
        "base_url": "https://api.ucloud.cn",
    })

    try:
        resp = client.uhost().create_uhost_instance({
            "MachineType":
            "O",
            "ChargeType":
            "Dynamic",
            "SecurityGroupId":
            "firewall-4fntbzvk",
            "Zone":
            "cn-bj2-03",
            "ImageId":
            "uimage-i2pcb2i3",
            "Password":
            "",
            "LoginMode":
            "Password",
            "Name":
            "test-",
            "CPU":
            8,
            "Memory":
            8192,
            "MaxCount":
            1,
            "NetworkInterface": [{
                "EIP": {
                    "Bandwidth": 300,
                    "PayMode": "Traffic",
                    "OperatorName": "Bgp"
                }
            }],
            "Disks": [{
                "Type": "CLOUD_RSSD",
                "IsBoot": "True",
                "Size": 20
            }]
        })
    except exc.UCloudException as e:
        print(e)
    else:
        print(resp['IPs'][0])
Esempio n. 2
0
    def permission_auth(access_id, access_key, region, project_id, offset=1, limit=1):
        """
        请求一台机器做权限测试
        :param access_id:
        :param access_key:
        :param region:
        :param project_id:
        :param offset:
        :param limit:
        :return:
        """

        client = Client(
            {"region": region, "project_id": project_id, "public_key": access_id, "private_key": access_key})
        response = client.uhost().describe_uhost_instance({"Offset": offset, "Limit": limit})
        return response
Esempio n. 3
0
    def get_uhost_count(self):
        try:
            client = Client({
                "region": self.region,
                "project_id": self.project_id,
                "public_key": self.access_id,
                "private_key": self.access_key
            })
            response = client.uhost().describe_uhost_instance({})
            return response['TotalCount']

        except exc.UCloudException as uerr:
            ins_log.read_log('error', '请求Ucloud接口出错:{0}'.format(uerr))
            return False
        except Exception as err:
            ins_log.read_log('error', err)
            return False
Esempio n. 4
0
 def get_region_uhosts(self, offset=0, limit=50):
     try:
         client = Client({
             "region": self.region,
             "project_id": self.project_id,
             "public_key": self.access_id,
             "private_key": self.access_key
         })
         response = client.uhost().describe_uhost_instance({
             "Offset": offset,
             "Limit": limit
         })
         return response
     except exc.UCloudException as uerr:
         ins_log.read_log('error', '请求Ucloud接口出错:{0}'.format(uerr))
         return False
     except Exception as err:
         ins_log.read_log('error', err)
         return False
Esempio n. 5
0
def find_eip_uhost_id(eip, rzone):  #获得该项目的所有EIP,遍历找到输入的eip
    client = Client({
        "region": rzone,
        "project_id": project_id,
        "public_key": public_key,
        "private_key": private_key
    })
    try:
        resp = client.invoke("DescribeEIP")
    except exc.RetCodeException as e:
        resp = e
    eipSets = resp.get('EIPSet')
    for eipSet in eipSets:
        ip = eipSet.get('EIPAddr')[0].get('IP')
        if ip == eip:  #如果找到输入的IP,则记下eipid和uhostid
            eip_id = eipSet.get('EIPId')
            uhost_id = eipSet.get('Resource').get('ResourceID')
            id_array.append(eip)
            id_array.append(eip_id)
            id_array.append(uhost_id)
            #return  uhost_id

            d = {"UHostIds": [uhost_id]}  # 构造请求字典
            try:
                resp = client.uhost().describe_uhost_instance(d)
            except exc.UCloudException as e:
                print(e)
            else:
                for i in range(len(resp['UHostSet'][0]['DiskSet'])):
                    if i < 1:
                        # print('just only system disk')
                        pass
                    else:
                        disk_id = resp['UHostSet'][0]['DiskSet'][i]['DiskId']
                        id_array.append(disk_id)
                switch_arry = id_array.copy()
                # bind_all.extend(id_array)
                # switch_serial = bind_all.copy()
                # serialization.append(switch_serial)
                total_renew.append(switch_arry)
                #print(total_renew)
                id_array.clear()
Esempio n. 6
0
def main():
    client = Client({
        "region": "cn-bj2",
        "project_id": os.getenv("UCLOUD_PROJECT_ID"),
        "public_key": os.getenv("UCLOUD_PUBLIC_KEY"),
        "private_key": os.getenv("UCLOUD_PRIVATE_KEY"),
    })
    logger.info("finding image, random choice one")
    images = (client.uhost().describe_image({
        "ImageType": "Base",
        "OsType": "Linux"
    }).get("ImageSet", []))
    assert len(images) > 0
    logger.info("creating uhost instance ...")
    image = random.choice(images)
    resp = client.uhost().create_uhost_instance({
        "Name":
        "sdk-python-example",
        "Zone":
        image["Zone"],
        "ImageId":
        image["ImageId"],
        "LoginMode":
        "Password",
        "Password":
        utils.gen_password(20),
        "CPU":
        1,
        "Memory":
        1024,
        "Disks": [{
            "Size": image["ImageSize"],
            "Type": "LOCAL_NORMAL",
            "IsBoot": "True",
        }],
    })
    uhost_id = utils.first(resp["UHostIds"])
    logger.info("uhost instance is created")

    def refresh_state():
        uhost = utils.first(client.uhost().describe_uhost_instance({
            "UHostIds": [uhost_id]
        }).get("UHostSet", []))
        if uhost.get("State") in ["Running", "Stopped"]:
            return uhost["State"].lower()
        return "pending"

    logger.info("wait uhost state is running ...")
    try:
        wait.wait_for_state(
            pending=["pending"],
            target=["running"],
            timeout=300,
            refresh=refresh_state,
        )
    except wait.WaitTimeoutException as e:
        logger.error(e)
    logger.info("uhost instance is running")
    logger.info("stopping uhost for clean up resources ...")
    client.uhost().stop_uhost_instance({"UHostId": uhost_id})
    try:
        wait.wait_for_state(
            pending=["pending"],
            target=["stopped"],
            timeout=180,
            refresh=refresh_state,
        )
    except wait.WaitTimeoutException as e:
        logger.error(e)
    else:
        logger.info("uhost instance is stopped")
    logger.info("remove uhost instance from cloud")
    client.uhost().terminate_uhost_instance({"UHostId": uhost_id})
Esempio n. 7
0
def main():
    client = Client({
        "region": "cn-bj2",
        "project_id": os.getenv("UCLOUD_PROJECT_ID"),
        "public_key": os.getenv("UCLOUD_PUBLIC_KEY"),
        "private_key": os.getenv("UCLOUD_PRIVATE_KEY"),
    })

    logger.info("finding image, random choice one")
    images = client.uhost().describe_image({
        'ImageType': 'Base',
        'OsType': 'Linux'
    }).get('ImageSet', [])

    assert len(images) > 0

    logger.info("creating uhost instance ...")
    image = random.choice(images)

    resp = client.uhost().create_uhost_instance({
        'Name':
        'sdk-python-example',
        'Zone':
        image["Zone"],
        'ImageId':
        image["ImageId"],
        'LoginMode':
        "Password",
        'Password':
        utils.gen_password(20),
        'CPU':
        1,
        'Memory':
        1024,
        'Disks': [{
            'Size': image["ImageSize"],
            'Type': 'CLOUD_NORMAL',
            'IsBoot': 'True',
        }],
    })
    uhost_id = utils.first(resp["UHostIds"])
    logger.info("uhost instance is created")

    def refresh_state():
        uhost = utils.first(client.uhost().describe_uhost_instance({
            'UHostIds': [uhost_id]
        }).get('UHostSet', []))
        if uhost.get('State') in ['Running', 'Stopped']:
            return uhost['State'].lower()
        return 'pending'

    logger.info("wait uhost state is running ...")
    try:
        wait.wait_for_state(pending=['pending'],
                            target=['running'],
                            timeout=300,
                            refresh=refresh_state)
    except wait.WaitTimeoutException as e:
        logger.error(e)
    logger.info("uhost instance is running")

    logger.info("stopping uhost for clean up resources ...")
    client.uhost().stop_uhost_instance({'UHostId': uhost_id})

    try:
        wait.wait_for_state(pending=['pending'],
                            target=['stopped'],
                            timeout=180,
                            refresh=refresh_state)
    except wait.WaitTimeoutException as e:
        logger.error(e)
    else:
        logger.info("uhost instance is stopped")

    logger.info("remove uhost instance from cloud")
    client.uhost().terminate_uhost_instance({'UHostId': uhost_id})