Example #1
0
def _power_cvm_off():
    _describe_instances()

    client = _get_cvm_client()
    instance_ids = list(TOTAL_CVM_INSTANCES.keys())
    if len(instance_ids) == 0:
        return

    iter = len(instance_ids) / ITEM_UNIT
    left = len(instance_ids) % ITEM_UNIT

    count = 0
    while (count <= iter):
        req = models.StopInstancesRequest()
        req.ForceStop = True
        req.StoppedMode = "STOP_CHARGING"  # 关机不收费
        if count < iter:
            req.InstanceIds = instance_ids[count * ITEM_UNIT:(count + 1) *
                                           ITEM_UNIT]
        elif left:
            req.InstanceIds = instance_ids[-left:]
        else:
            break

        resp = client.StopInstances(req)
        if not _succeed(resp):
            logging.warning("Fail to StopInstances, need retry manually")
        count = count + 1
        time.sleep(0.1)
Example #2
0
def stop(name, force=False, call=None):
    """
    Stop a Tencent Cloud running instance
    Note: use `force=True` to make force stop

    CLI Examples:

    .. code-block:: bash

        salt-cloud -a stop myinstance
        salt-cloud -a stop myinstance force=True
    """
    if call != "action":
        raise SaltCloudSystemExit("The stop action must be called with -a or --action.")

    node = _get_node(name)

    client = get_provider_client("cvm_client")
    req = cvm_models.StopInstancesRequest()
    req.InstanceIds = [node.InstanceId]
    if force:
        req.ForceStop = "TRUE"
    resp = client.StopInstances(req)

    return resp
Example #3
0
 def stop_instance(self):
     """
     停止cvm
     :return:
     """
     request = models.StopInstancesRequest()
     request.InstanceIds = self.instance_list
     # 发起请求
     response = self.clentoper.StopInstances(request)
     self.logger.info("public ecs vpn reboot successful!")
     self.logger.info(response.to_json_string())
     print(response.to_json_string())
Example #4
0
    def turn_(self, InstanceIds=None, cluster=None, state: str = 'on'):
        if not InstanceIds:
            InstanceIds = tell_cluster_config(cluster).get('instance_ids')

        if not InstanceIds:
            warn('instance_ids not defined in cluster info, cannot proceed',
                 exit=1)

        for id_ in InstanceIds:
            ids = [id_]
            if state.lower() == 'off':
                req = cvm_models.StopInstancesRequest()
                req.InstanceIds = ids
                req.ForceStop = True
                req.StoppedMode = 'STOP_CHARGING'
                try:
                    self.cvm_client.StopInstances(req)
                except TencentCloudSDKException as e:
                    if e.code == 'UnauthorizedOperation':
                        error(f'weird error: {e.code}', exit=True)
                    if e.code != 'InvalidInstanceState.Stopped':
                        debug(f'retry due to {e.code}')
                        raise
            elif state.lower() == 'on':
                req = cvm_models.StartInstancesRequest()
                req.InstanceIds = ids
                try:
                    self.cvm_client.StartInstances(req)
                except TencentCloudSDKException as e:
                    if e.code not in {
                            'InvalidInstanceState.Running',
                            'UnsupportedOperation.InstanceStateRunning',
                    }:
                        debug(f'retry due to {e.code}')
                        raise
            else:
                error(f'weird state {state}, choose from {self.VM_STATES}',
                      exit=True)
Example #5
0
    def shutdown_server(self, server_id, *args, **kwargs) -> bool:
        regions_list = self.get_available_regions_list()

        for region in regions_list:
            region_code = region["region_code"]

            client = cvm_client.CvmClient(self.isp, region_code)
            req = tc_models.StopInstancesRequest()
            req_config = json.dumps(
                dict(
                    InstanceIds=[server_id],
                    ForceStop=True,
                ))
            req.from_json_string(req_config)
            try:
                client.StopInstances(req)
            except Exception as e:
                logging.warning(e)
                result = False
            else:
                result = True
                break
        return result
try:
    # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
    cred = credential.Credential("AKIDylMjqkOq7Azay9Nq8D5kCSVM1Sfft4Sd",
                                 "K8lBONAk7IEzXt30kGXcS5UfbJm0zkG4")

    httpProfile = HttpProfile()
    httpProfile.endpoint = "cvm.api3.test.403a.tcecqpoc.fsphere.cn"
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile

    # 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的。
    client = cvm_client.CvmClient(cred, "shanghai", clientProfile)

    # 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。
    req = models.StopInstancesRequest()

    # 这里还支持以标准json格式的string来赋值请求参数的方式。下面的代码跟上面的参数赋值是等效的。
    params = '{"InstanceIds":["ins-i4ekkudx","ins-gwggvy39"]}'

    req.from_json_string(params)

    # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的。
    # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
    resp = client.StopInstances(req)

    # 输出json格式的字符串回包
    print(resp.to_json_string())

    # 也可以取出单个值。
    # 你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义。
Example #7
0
def stopInstance(InstanceId):
    req = models.StopInstancesRequest()
    req.InstanceIds = [InstanceId]
    resp = client.StopInstances(req)
    return resp