Exemplo n.º 1
0
    def __startInstance(self, instanceId=None):
        if instanceId is None:
            instance = self.__InstanceId
        else:
            instance = instanceId

        request = StartInstanceRequest.StartInstanceRequest()
        request.set_InstanceId(instance)

        request.set_accept_format(u'json')
        try:
            result = self.__client.do_action(request)
            result_data = json.loads(result)
        except Exception as e:
            print "exception arised "
            print e
            return 1

        if result_data.has_key(u"Code"):
            print 'start instance failed Code %s with instanceid %s' %(result_data[u'Code'], instance)
            print result_data[u'Message']
            return 1

        else:
            print 'start instance %s successful  ' %instance
            return 0
Exemplo n.º 2
0
    def do_start(self, region_id, instance_id):
        client = AcsClient(self.aliyun_token['id'], self.aliyun_token['secret'], region_id)

        # check status first
        describeInstanceAttributeRequest = DescribeInstanceAttributeRequest.DescribeInstanceAttributeRequest()
        describeInstanceAttributeRequest.set_InstanceId(instance_id)
        describeInstanceAttributeRequest.set_accept_format('json')

        resp = json_decode(client.do_action(describeInstanceAttributeRequest))

        result = {}
        # check if exist
        if 'Code' in resp.keys() and resp['Code'] == 'InvalidInstanceId.NotFound':
            result['text'] = 'start %s %s failed, %s' % (region_id, instance_id, resp['Code'])
        else:
            if resp['Status'] != 'Stopped':
                result['text'] = 'start %s %s failed' % (region_id, instance_id)
                result['attachments'] = [{"title": "%s" % resp['InstanceId'], "text": "%s" % resp['Status'], "color": "%s" % self.status_color(resp['Status'])}]
            else:
                startInstanceRequest = StartInstanceRequest.StartInstanceRequest()
                startInstanceRequest.set_InstanceId(instance_id)
                startInstanceRequest.set_accept_format('json')

                resp = json_decode(client.do_action(startInstanceRequest))
                result['text'] = 'starting instance %s %s' % (region_id, instance_id)

        return result
Exemplo n.º 3
0
 def is_valid_account(self) -> bool:
     request = StartInstanceRequest.StartInstanceRequest()
     request.set_DryRun(True)
     valid = self.handle_request(request)
     if valid:
         return True
     else:
         return False
Exemplo n.º 4
0
def startInstance(clt,instanceId):
    request = StartInstanceRequest.StartInstanceRequest()

    request.set_accept_format('json')
    request.set_InstanceId(instanceId)
    result = clt.do_action(request)
    print "startInstance=="+result
    return result;
Exemplo n.º 5
0
 def start_instance(self, instanceid):
     request = StartInstanceRequest.StartInstanceRequest()
     try:
         request.set_accept_format('json')
         request.add_query_param('InstanceId', instanceid)
         response = self.cli.do_action_with_exception(request)
         return response
     except Exception as ee:
         print("start instance error ", instanceid, ee)
Exemplo n.º 6
0
 def start_ecs(self, **kwargs):
     """
     :params: ECS实例ID
     """
     request = StartInstanceRequest.StartInstanceRequest()
     for k, v in kwargs.items():
         request.add_query_param(k, v)
     result = self.client.do_action(request)
     return result
Exemplo n.º 7
0
 def start_instance(client, instance_id):
     mylogger.info("trying to start instance...", )
     request = StartInstanceRequest.StartInstanceRequest()
     request.set_accept_format("JSON")
     request.set_InstanceId(instance_id)
     content = client.do_action_with_exception(request)
     response = json.loads(content)
     mylogger.info("success")
     return response.get('InstanceId')
Exemplo n.º 8
0
 def start_instance(self):
     request = StartInstanceRequest.StartInstanceRequest()
     request.set_accept_format('json')
     request.add_query_param('InstanceId', 'i-bjk23j1rlvfghlq79au')
     # 发起请求
     response = self.clentoper.do_action_with_exception(request)
     self.logger.info("public ecs vpn start successful!")
     self.logger.info(response)
     print(response)
Exemplo n.º 9
0
def start(instance_id):
    """
    启动实例
    :return:
    """
    request = StartInstanceRequest.StartInstanceRequest()
    request.set_InstanceId(instance_id)

    response = client.do_action_with_exception(request)
    print("启动实例: {}".format(response))
Exemplo n.º 10
0
def start_vm(vmid):
    client = create_acs_client()

    request = StartInstanceRequest.StartInstanceRequest()
    request.set_action_name('StartInstance')
    request.set_InstanceId(vmid)
    response = client.do_action_with_exception(request)
    r = json.loads(response.decode())
    log.debug(r)
    return r
Exemplo n.º 11
0
def boot_instance(instance_id,accesskey_id,accesskey_secret,region_id):
    print("Wait 30s for ECS booting...")
    print("the instance ID is "+instance_id)
    time.sleep(30)
    clt = client.AcsClient(accesskey_id, accesskey_secret, region_id)
    request=StartInstanceRequest.StartInstanceRequest()
    request.set_accept_format('json')
    request.set_InstanceId(instance_id)
    result = clt.do_action_with_exception(request)
    print result
    return
Exemplo n.º 12
0
 def start_instances(self, instance_id):
     try:
         request = StartInstanceRequest.StartInstanceRequest()
         request.set_InstanceId(instance_id)
         self._send_request(request)
         logging.info("Start %s command submit successfully.", instance_id)
         logging.info("ECS instance with id " + str(instance_id) + " started")
     except Exception as e:
         logging.error(
             "Failed to start node instance %s. Encountered following " "exception: %s." % (instance_id, e)
         )
         sys.exit(1)
Exemplo n.º 13
0
def boot(*, instance_id: str) -> Dict:
    """Let ecs instance of id start up.

    Params:
        instance_id: Id of ecs instance, must be poweroff.

    Returns: response info

    """
    request = StartInstanceRequest.StartInstanceRequest()
    request.set_InstanceId(instance_id)

    return alisdk.do_action_with_exception(request)
Exemplo n.º 14
0
 def start_instance(self, instance_id):
     """
     启动实例
     :param instance_id: 根据购买机器的实例ID启动
     :return:
     """
     try:
         request = StartInstanceRequest.StartInstanceRequest()
         request.set_accept_format('json')
         request.add_query_param('InstanceId', instance_id)
         response = self.conn.do_action(request)
         json.loads(str(response, encoding="utf8"))
     except Exception as e:
         # print(e)
         print('[Error]: 实例开启失败,也可登陆控制台查看状态,信息:{}'.format(e))
         exit(-3)
Exemplo n.º 15
0
 def startup_server(self,serverid):
     client = AcsClient(access_key_id, access_key_secret,region_id)
     request =StartInstanceRequest.StartInstanceRequest()
     request.set_InstanceId(serverid)
     response = client.do_action_with_exception(request)
     json_result = json.loads(response)
     i = 0
     
     while i < 600:
         serverstatus = self.get_server_status_by_serverid(serverid)
         if serverstatus['status'] == 'Running':
             break
         time.sleep(1)
         i = i + 1
     if  i == 600:
         raise Exception('startup timeout plesae check')
     return json_result['RequestId']
Exemplo n.º 16
0
def start_instance(config):
    click.echo(click.style("正在启动实例 ...", fg="green"))
    client = config.create_api_client()
    req = StartInstanceRequest.StartInstanceRequest()
    req.set_InstanceId(config.get('InstanceId'))
    result = do_action(client, req)
Exemplo n.º 17
0
def copyInstanceConfigCreateInstance(host=None, oldname=None, newname=None):
    conn = pymongo.MongoClient(host).aly.instance
    result = conn.find({
        'InstanceName': oldname
    }).sort('_id', pymongo.DESCENDING)
    if result.count() == 0:
        print '>> Not Find %s' % oldname
        sys.exit(1)
    params = {}
    params['RegionId'] = result[0]['RegionId']
    params['ZoneId'] = result[0]['ZoneId']
    params['ImageId'] = [
        x['ImageId'] for x in result[0]['images'] if x['Type'] == 'system'
    ][0]
    params['InstanceType'] = result[0]['InstanceType']
    params['SecurityGroupId'] = result[0]['SecurityGroupIds'][
        'SecurityGroupId'][0]
    params['InstanceName'] = newname
    params['Description'] = newname
    params['InternetChargeType'] = result[0]['InternetChargeType']
    params['InternetMaxBandwidthOut'] = result[0]['InternetMaxBandwidthOut']
    params['HostName'] = newname
    params['IoOptimized'] = result[0]['IoOptimized'] and 'optimized' or 'none'
    params['SystemDisk.Category'] = [
        x['Category'] for x in result[0]['images'] if x['Type'] == 'system'
    ][0]
    params['SystemDisk.Size'] = [
        x['Size'] for x in result[0]['images'] if x['Type'] == 'system'
    ][0]
    params['DataDisk.1.Category'] = 'cloud'
    params['DataDisk.1.Size'] = 100
    params['InstanceChargeType'] = result[0]['InstanceChargeType']
    params['Period'] = 1

    clt = client.AcsClient(access_key_id, access_key_secret,
                           params['RegionId'])
    request = CreateInstanceRequest.CreateInstanceRequest()
    request.set_accept_format('json')
    request.set_query_params(params)
    #c_r = json.loads(clt.do_action(request))
    c_r = json.loads(
        '{"InstanceId":"i-234hs2qwx","RequestId":"D3209274-D317-4041-8304-80D19F2ABB78"}'
    )
    if c_r.get('InstanceId', None) == None:
        print '>> Create Instance %s' % c_r['Message']
        sys.exit(1)
    if result[0]['PublicIpAddress']['IpAddress']:
        request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest(
        )
        request.set_accept_format('json')
        request.set_query_params({'InstanceId': c_r['InstanceId']})
        #p_r = json.loads(clt.do_action(request))
        p_r = json.loads(
            '{"RequestId": "080A06E3-75C5-4256-910B-23278063C38F", "IpAddress": "114.55.149.208"}'
        )
        if p_r.get('IpAddress', None) == None:
            print '>> Create Network %s' % c_r['Message']
            sys.exit(1)
    request = DescribeInstancesRequest.DescribeInstancesRequest()
    request.set_accept_format('json')
    request.set_query_params({'InstanceIds': '["%s"]' % c_r['InstanceId']})
    d_r = json.loads(clt.do_action(request))
    innerIpAddress = d_r['Instances']['Instance'][0]['InnerIpAddress'][
        'IpAddress'][0]
    request = StartInstanceRequest.StartInstanceRequest()
    request.set_accept_format('json')
    request.set_query_params({'InstanceId': c_r['InstanceId']})
    s_r = json.loads(clt.do_action(request))
    while 1:
        request = DescribeInstancesRequest.DescribeInstancesRequest()
        request.set_accept_format('json')
        request.set_query_params({'InstanceIds': '["%s"]' % c_r['InstanceId']})
        d_r = json.loads(clt.do_action(request))
        if d_r['Instances']['Instance'][0]['Status'] == 'Running': break
        time.sleep(10)
    print os.popen('echo /home/easemob/zhaoyufeng/autoinitserver.sh %s %s' %
                   (innerIpAddress, newname)).read()
Exemplo n.º 18
0
def start_instance(client, instance_id):
    req = StartInstanceRequest.StartInstanceRequest()
    req.set_InstanceId(instance_id)
    req.set_accept_format('json')

    return loads(client.do_action(req))
Exemplo n.º 19
0
 def StartInstance(self):
     request = StartInstanceRequest.StartInstanceRequest()
     request.set_InstanceId(self.instance_id)
     result = self.client.do_action_with_exception(request)
     return result
Exemplo n.º 20
0
 def start_instance(self, instance_id):
     request = StartInstanceRequest.StartInstanceRequest()
     request.set_InstanceId(instance_id)
     response = self.client.do_action_with_exception(request)
     return response.decode('utf-8')
Exemplo n.º 21
0
def buy_instance():
    clt = client.AcsClient('xxxxxx', 'xxxxxxxxxxxxx', 'cn-hangzhou')
    # 设置参数
    request = CreateInstanceRequest.CreateInstanceRequest()
    request.set_accept_format('json')
    request.add_query_param('RegionId', 'cn-hangzhou')
    request.add_query_param('SecurityGroupId', 'Gxxxxxxxxxxxxxxx')
    request.add_query_param('InternetMaxBandwidthIn', 1)
    request.add_query_param('InternetMaxBandwidthOut', 1)
    request.add_query_param('Password', 'cqmyg.123')
    # 自定义镜像
    #request.add_query_param('ImageId', 'm-xxxxxxxxxx')
    request.add_query_param('ImageId', 'm-xxxxxxxxxxxxxx')
    # 阿里云默认镜像
    # request.add_query_param('ImageId', 'ubuntu_16_0402_64_20G_alibase_20180409.vhd')
    request.add_query_param('InstanceType', 'ecs.sn1.medium')
    request.add_query_param('SystemDisk.Size', '100')
    request.add_query_param('InstanceName', 'tmp_validate_web_db')

    # 购买实例
    print("购买实例中...")
    response_buy = clt.do_action(request)
    print(response_buy)
    instance_id = json.loads(response_buy)["InstanceId"]

    # 分配公网IP
    time.sleep(3)
    print("分配公网ip中...")
    request_ip = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest(
    )
    request_ip.set_accept_format('json')
    request_ip.add_query_param('InstanceId', instance_id)
    response_ip = clt.do_action(request_ip)
    print("已分配IP", response_ip)

    # 启动实例
    print("启动实例中...")
    request_start = StartInstanceRequest.StartInstanceRequest()
    request_start.set_accept_format('json')
    #request_start.add_query_param('InstanceId', "i-bp15xf4ylewns1qav4q3")
    request_start.add_query_param('InstanceId', instance_id)
    response_start = clt.do_action(request_start)
    print(response_start)

    ## 设置自动释放时间
    time.sleep(70)
    request_release = CommonRequest()
    request_release.set_accept_format('json')
    request_release.set_domain('ecs.aliyuncs.com')
    request_release.set_method('POST')
    request_release.set_version('2014-05-26')
    request_release.set_action_name('ModifyInstanceAutoReleaseTime')
    request_release.add_query_param('InstanceId', instance_id)
    # 设置3个小时后自动释放服务器
    release_time_date = commands.getstatusoutput('date -u "+%Y-%m-%dT"')[1]
    tmp_hour = commands.getstatusoutput('date -u "+%H"')[1]
    release_time_hour = str(int(tmp_hour) + 4)
    # 如果小时小于10点,转为数字后会少个0
    if len(release_time_hour) == 1:
        release_time_hour = "0" + release_time_hour
    # 分钟要求是UTC时间并精确到分钟,时间比当前时间至少多2分钟,不然会接口调用失败
    tmp_minute = commands.getstatusoutput('date -u "+%M"')[1]
    release_time_minute = str(int(tmp_minute) + 3)
    # 如果遇到加了3分钟后大于59分的则直接设置分钟为3分钟,小时则加一小时
    if int(release_time_minute) > 59:
        release_time_minute = "03"
        release_time_hour = str(int(release_time_hour) + 1)
        if len(release_time_minute) == 1:
            release_time_minute = "0" + release_time_minute
        if len(release_time_hour) == 1:
            release_time_hour = "0" + release_time_hour
    if len(release_time_minute) == 1:
        release_time_minute = "0" + release_time_minute
    release_time = str(release_time_date) + str(release_time_hour) + ":" + str(
        release_time_minute) + ":00Z"
    print(release_time)
    # 发送请求
    request_release.add_query_param('AutoReleaseTime', release_time)
    response_release = clt.do_action_with_exception(request_release)
    print response_release
Exemplo n.º 22
0
#result = clt.do_action(request)
#print json.loads(result)
##  {u'InstanceId': u'i-62pepv5ke', u'RequestId': u'0CF4B16A-EEE3-4C6A-A6AC-352630688D58'}

print "##########AllocatePublicIpAddress###########"

request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest()
request.set_accept_format('json')
request.set_InstanceId('i-62wpk9e7e')

#print clt.do_action(request)
## {"RequestId":"3993EC47-222B-48EE-ABA1-246CEB40B2FC","IpAddress":"49.213.8.1"}

print "##########StartInstance###########"

request = StartInstanceRequest.StartInstanceRequest()
request.set_accept_format('json')
request.set_InstanceId('i-62wpk9e7e')

#print clt.do_action(request)

print "##########ModifyInstanceNetworkSpec###########"
request = ModifyInstanceNetworkSpecRequest.ModifyInstanceNetworkSpecRequest()
request.set_accept_format('json')
request.set_InstanceId('i-62wpk9e7e')
request.set_InternetMaxBandwidthOut(1)

#print clt.do_action(request)

print "##########StopInstance###########"
request = StopInstanceRequest.StopInstanceRequest()
Exemplo n.º 23
0
 def start_instance(self, instance_id):
     request = StartInstanceRequest.StartInstanceRequest()
     key_list = ["InstanceId"]
     self.vm_params["InstanceId"] = instance_id
     request = self._add_params(request, key_list, self.vm_params)
     return self._send_request(request)
Exemplo n.º 24
0
def start():
    request = StartInstanceRequest.StartInstanceRequest()
    request.set_InstanceId(settings.ACS_INSTANT_ID)
    resp = client.do_action_with_exception(request)

    print(resp)
Exemplo n.º 25
0
 def start_server(self, server_id, *args, **kwargs) -> bool:
     request = StartInstanceRequest.StartInstanceRequest()
     request.set_InstanceId(server_id)
     response = self.handle_request(request)
     return bool(response)
Exemplo n.º 26
0
 def start_instance(self):
     request = StartInstanceRequest.StartInstanceRequest()
     request.set_InstanceId(self.resource_id)
     self.execute(request, raise_on_falsy=True)
     return True
Exemplo n.º 27
0
def my_create_instance(clt,
                       imageid,
                       instancetype,
                       securitygroupid,
                       hostname,
                       etcname,
                       bandout,
                       vswitchid,
                       keyname='puppet-imou',
                       myopti='optimized'):

    createInstanceRequest = CreateInstanceRequest.CreateInstanceRequest()
    createInstanceRequest.set_accept_format('json')
    createInstanceRequest.set_ImageId(imageid)
    createInstanceRequest.set_InstanceType(instancetype)
    createInstanceRequest.set_SecurityGroupId(securitygroupid)
    createInstanceRequest.set_InstanceName(hostname)
    # PayByBandwidth  PayByTraffic,默认使用按带宽付费
    createInstanceRequest.set_InternetChargeType('PayByBandwidth')
    # 出网带宽,0-100(Mbps),带宽的设置主要是出网的带宽
    createInstanceRequest.set_InternetMaxBandwidthOut(bandout)
    createInstanceRequest.set_HostName(etcname)
    #createInstanceRequest.set_Password(passwd)
    createInstanceRequest.set_IoOptimized(myopti)  #I/O优化实例
    createInstanceRequest.set_KeyPairName("puppet-imou")  #密钥对

    if vswitchid != '':
        createInstanceRequest.set_VSwitchId(vswitchid)  #交换虚拟机
    # PrePaid(包年包月)   PostPaid(按量付费)
    createInstanceRequest.set_InstanceChargeType('PrePaid')
    # 买一个月
    createInstanceRequest.set_Period(1)
    # 设置ip
    # createInstanceRequest.set_PrivateIpAddress(ip)
    createInstanceResponse = clt.do_action_with_exception(
        createInstanceRequest)
    instanceId = json.loads(createInstanceResponse)['InstanceId']

    #print "instanceId is %s" % (instanceId)
    time.sleep(7)

    if int(bandout) > 0:
        allowPublicIpAddressRequest = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest(
        )
        allowPublicIpAddressRequest.set_accept_format('json')
        allowPublicIpAddressRequest.set_InstanceId(instanceId)
        allowPublicIpAddressResponse = clt.do_action_with_exception(
            allowPublicIpAddressRequest)
        #print(allowPublicIpAddressResponse)

    startInstanceRequest = StartInstanceRequest.StartInstanceRequest()  #添加外网IP

    print "start instances..."
    startInstanceRequest.set_accept_format('json')
    startInstanceRequest.set_InstanceId(instanceId)  #启动实例
    startInstanceResponse = clt.do_action_with_exception(startInstanceRequest)

    #print(startInstanceResponse)
    time.sleep(7)
    import_alito_dbandzabbix(clt, hostname)
    return instanceId