Exemplo n.º 1
0
    def set_info_by_vips(self):
        """ Return {'lb_id': 'vip', ...} """
        try:
            client = clb_client.ClbClient(self.get_credential, self.region)
            req = clb_model.DescribeLoadBalancersRequest()
            req.LoadBalancerVips = self.vips
            ret_str = client.DescribeLoadBalancers(
                req).to_json_string(indent=2)
            ret_obj = json.loads(ret_str)

            if ret_obj.get("TotalCount") < len(self.vips) == 1:
                self.region = "ap-hongkong"
                self.vpc = self.get_vpc()
                client = clb_client.ClbClient(self.get_credential, self.region)
                req = clb_model.DescribeLoadBalancersRequest()
                req.LoadBalancerVips = self.vips
                ret_str = client.DescribeLoadBalancers(
                    req).to_json_string(indent=2)
                ret_obj = json.loads(ret_str)

            result = {}
            [result.setdefault(lb.get("LoadBalancerVips")[0], lb.get(
                "LoadBalancerId")) for lb in ret_obj.get("LoadBalancerSet")]
            self.load_balance_info.update(result)

        except TencentCloudSDKException:
            print(traceback.format_exc())
            exit(1)
Exemplo n.º 2
0
 def add_rules(self, load_balance_id, listener_id, domain):
     try:
         client = clb_client.ClbClient(self.get_credential, self.region)
         req = clb_model.CreateRuleRequest()
         req.LoadBalancerId = load_balance_id
         req.ListenerId = listener_id
         req.Rules = [
             {
                 "Domain": domain,
                 "Url": "/",
                 "ForwardType": "HTTP",
                 "TargetType": "NODE"
             },
         ]
         # req.Rules = [{"Domain": domain, "Url": "/", "ForwardType": "HTTP", "TargetType": "NODE", "SessionExpireTime": 300}, ]
         ret_str = client.CreateRule(req).to_json_string()
         print("AddRule Success: AddRule args: %s %s %s" %
               (load_balance_id, listener_id, domain))
         return json.loads(ret_str).get("RequestId"), json.loads(
             ret_str).get("LocationIds")[0]
     except TencentCloudSDKException, error:
         print("Exception Occur: AddRule args: %s %s %s" %
               (load_balance_id, listener_id, domain))
         print(error)
         exit(1)
Exemplo n.º 3
0
    def init_client(self, region):
        self._region = region
        if True:
            try:
                cred = credential.Credential(
                    self._tencent_id, self._tencent_key)
                if self._region in self._regions:
                    endpoint = self._api+'.tencentcloudapi.com'
		    hp=http_profile.HttpProfile()
		    hp.endpoint = endpoint
		    cp = client_profile.ClientProfile()
		    cp.httpProfile = hp
		    self._client = clb_client.ClbClient(cred, region, cp)
                #    if region.find('ap-shenzhen-fsi'):
                #        endpoint = self._api+'.tencentcloudapi.com'
		#	hp=http_profile.HttpProfile()
		#	hp.endpoint = endpoint
		#	cp = client_profile.ClientProfile()
		#	cp.httpProfile = hp
		#	self._client = clb_client.ClbClient(cred, "ap-shenzhen-fsi", cp)
                #    else:
                #        print self._region
		#	self._client = clb_client.ClbClient(cred, self._region)
            except TencentCloudSDKException as err:
                print(err)
            except Exception as e:
                print str(e)
Exemplo n.º 4
0
 def bind_rs(self, load_balance_id, target_obj):
     try:
         client = clb_client.ClbClient(self.get_credential, self.region)
         req = clb_model.BatchRegisterTargetsRequest()
         req.LoadBalancerId = load_balance_id
         req.Targets = target_obj
         client.BatchRegisterTargets(req).to_json_string(indent=2)
         print("Bindrs success !")
     except TencentCloudSDKException:
         print(traceback.format_exc())
         exit(1)
Exemplo n.º 5
0
def get_clb(Region_Id):
    """
    查询 CLB 列表
    :param config_dict:
    :return: InstanceId
    """
    describe_request = clb_models.DescribeLoadBalancersRequest()
    try:
        clt = clb_client.ClbClient(cred, Region_Id)
        response = clt.DescribeLoadBalancers(describe_request)
        result_content = response.to_json_string()
        return json.loads(result_content)
    except TencentCloudSDKException as e:
        print(e)
Exemplo n.º 6
0
    def _delete_listener_exec(self, load_balance_id, listener_id):
        try:
            client = clb_client.ClbClient(self.get_credential, self.region)
            req = clb_model.DeleteListenerRequest()
            req.LoadBalancerId = load_balance_id
            req.ListenerId = listener_id
            ret_str = client.DeleteListener(req).to_json_string(indent=2)

            request_id = json.loads(ret_str).get("RequestId")
            print("Delete Listener Request: %s " % request_id)
            self.wait_request(request_id)
            print("[Delete Listener] Success! info: %s, %s" % (load_balance_id, listener_id))
        except TencentCloudSDKException:
            print(traceback.format_exc())
            exit(1)
Exemplo n.º 7
0
 def create_listener(self, load_balance_id, protocol, vport):
     try:
         client = clb_client.ClbClient(self.get_credential, self.region)
         req = clb_model.CreateListenerRequest()
         req.LoadBalancerId = load_balance_id
         req.Protocol = protocol
         req.Ports = [int(vport), ]
         ret_obj = json.loads(client.CreateListener(
             req).to_json_string(indent=2))
         print("CreateListener success: %s %s %s" %
               (load_balance_id, protocol, str(vport)))
         return ret_obj.get("RequestId"), ret_obj.get("ListenerIds")[0]
     except TencentCloudSDKException:
         print(traceback.format_exc())
         print("Exception occur: CreateListener args: %s %s %s" %
               (load_balance_id, protocol, str(vport)))
Exemplo n.º 8
0
    def cust_bind_rs(self, region, load_balance_id, listener_id, new_rs, rs_port):
        try:
            self.region = region
            self.vpc = self.get_vpc()
            client = clb_client.ClbClient(self.get_credential, self.region)
            req = clb_model.RegisterTargetsRequest()
            req.LoadBalancerId = load_balance_id
            req.ListenerId = listener_id
            req.Targets = [{"Port": int(rs_port), "EniIp": new_rs}]
            ret_str = client.RegisterTargets(req).to_json_string(indent=2)

            request_id = json.loads(ret_str).get("RequestId")
            print("Bind request: %s" % request_id)
            self.wait_request(request_id)
            print("[Bind rs] Success! Info: %s, %s, %s, %s, %s" % (region, load_balance_id, listener_id, new_rs, rs_port))
        except TencentCloudSDKException:
            print(traceback.format_exc())
            exit(1)
Exemplo n.º 9
0
    def query_listener(self, load_balance_id):
        """
        :param load_balance_id:
        :return:
            {
              "443": {
                "rules": {
                  "a.gwgo.qq.com": "loc-bb9y1k05"
                },
                "listener_id": "lbl-ansoslhl"
              }
            }
        """
        try:
            client = clb_client.ClbClient(self.get_credential, self.region)
            req = clb_model.DescribeListenersRequest()
            req.LoadBalancerId = load_balance_id
            ret_str = client.DescribeListeners(req).to_json_string(indent=2)
            ret_obj = json.loads(ret_str)
            listeners = ret_obj.get("Listeners")

            listener_obj = {}
            for listener in listeners:
                if listener.get("Protocol") == "HTTPS":
                    vport = listener.get("Port")
                    listener_id = listener.get("ListenerId")

                    rule_obj = {}
                    rules = listener.get("Rules")
                    if len(rules) > 0:
                        for rule in rules:
                            rule_obj.setdefault(rule.get("Domain"),
                                                rule.get("LocationId"))
                    listener_obj.setdefault(str(vport), {
                        "listener_id": listener_id,
                        "rules": rule_obj
                    })
            print("QueryListener Success: %s" % load_balance_id)
            print(json.dumps(listener_obj, indent=2, ensure_ascii=False))
            return listener_obj
        except TencentCloudSDKException, error:
            print("Exception Occur: QueryListener args: %s" % load_balance_id)
            print(error)
            exit(1)
Exemplo n.º 10
0
    def set_info_by_vips(self):
        """ Return {'lb_id': 'vip', ...} """
        try:
            client = clb_client.ClbClient(self.get_credential, self.region)
            req = clb_model.DescribeLoadBalancersRequest()
            req.LoadBalancerVips = self.vips
            ret_str = client.DescribeLoadBalancers(req).to_json_string(
                indent=2)
            ret_obj = json.loads(ret_str)

            result = {}
            [
                result.setdefault(
                    lb.get("LoadBalancerVips")[0], lb.get("LoadBalancerId"))
                for lb in ret_obj.get("LoadBalancerSet")
            ]
            self.load_balance_info.update(result)
        except TencentCloudSDKException, error:
            print(error)
            exit(1)
Exemplo n.º 11
0
    def wait_request(self, request_id):
        client = clb_client.ClbClient(self.get_credential, self.region)
        req = clb_model.DescribeTaskStatusRequest()
        req.TaskId = request_id

        count = 0
        while count <= 10:
            time.sleep(2)
            ret_str = client.DescribeTaskStatus(req).to_json_string()
            status = json.loads(ret_str).get("Status")
            if status == 0:
                print("Request %s exec done" % request_id)
                break
            elif status == 1:
                print("Request %s occur error, please check! ")
                break
            elif status == 2:
                count += 1
                print("Request %s is doing, and will retry %s times!" %
                      (request_id, str(count)))
Exemplo n.º 12
0
 def create_listener(self, load_balance_id, vport, cert_id):
     try:
         client = clb_client.ClbClient(self.get_credential, self.region)
         req = clb_model.CreateListenerRequest()
         req.LoadBalancerId = load_balance_id
         req.ListenerNames = ["https_" + str(vport)]
         req.Ports = [
             int(vport),
         ]
         req.Protocol = "HTTPS"
         req.Certificate = {"SSLMode": "UNIDIRECTIONAL", "CertId": cert_id}
         ret_str = client.CreateListener(req).to_json_string()
         print("CreateListener Success: CreateListener args: %s %s %s" %
               (load_balance_id, vport, cert_id))
         return json.loads(ret_str).get("ListenerIds")[0]
     except TencentCloudSDKException, error:
         print("Exception Occur: CreateListener args: %s %s %s" %
               (load_balance_id, vport, cert_id))
         print(error)
         exit(1)
Exemplo n.º 13
0
    def bind_host(self, load_balance_id, listener_id, rule_id, new_rs):
        try:
            re.sub(r",$", "", new_rs)
            new_rs_list = new_rs.split(",")

            client = clb_client.ClbClient(self.get_credential, self.region)
            req = clb_model.RegisterTargetsRequest()
            req.LoadBalancerId = load_balance_id
            req.ListenerId = listener_id
            req.LocationId = rule_id
            req.Targets = [{
                "EniIp": rs.split(":")[0],
                "Port": int(rs.split(":")[1])
            } for rs in new_rs_list]
            client.RegisterTargets(req).to_json_string(indent=2)
            print("BindHost Success: %s %s %s %s " %
                  (load_balance_id, listener_id, rule_id, new_rs))
        except TencentCloudSDKException, error:
            print("Exception Occur: BindHost args: %s %s %s %s" %
                  (load_balance_id, listener_id, rule_id, new_rs))
            print(error)
            exit(1)
Exemplo n.º 14
0
    def query_listener(self, load_balance_id):
        try:
            client = clb_client.ClbClient(self.get_credential, self.region)
            req = clb_model.DescribeListenersRequest()
            req.LoadBalancerId = load_balance_id
            ret_str = client.DescribeListeners(req).to_json_string(indent=2)
            ret_obj = json.loads(ret_str)
            listeners = ret_obj.get("Listeners")

            listener_obj = {}
            for listener in listeners:
                if listener.get("Protocol") in ["TCP", "UDP"]:
                    vport = listener.get("Port")
                    protocol = listener.get("Protocol")
                    listener_id = listener.get("ListenerId")
                    protocol_vport_key = protocol + str(vport)
                    listener_obj.setdefault(protocol_vport_key, listener_id)

            print("QueryListener Success: %s" % load_balance_id)
            return listener_obj
        except TencentCloudSDKException:
            print("Exception Occur: QueryListener args: %s" % load_balance_id)
            print(traceback.format_exc())
            exit(1)
Exemplo n.º 15
0
def _get_clb_client():
    cred = credential.Credential(TENCENTCLOUD_SECRET_ID,
                                 TENCENTCLOUD_SECRET_KEY)
    return clb_client.ClbClient(cred, REGION)