Exemple #1
0
class mrs(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="description of the avaliable clusters",
             examples=[{
                 "List Clusters": "otc mrs describe_clusters"
             }, {
                 "Show Cluster Details":
                 "otc mrs describe_clusters mycluster"
             }],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='description of the avaliable clusters'),
                 arg('-cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='description of the avaliable clusters')
             ])
    def describe_clusters():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/bigdata/api/v1/clusters?pageSize=10&currentPage=1&clusterState=existing"

        if OtcConfig.CLUSTER_ID is None:
            ret = utils_http.get(url)
            print(url)
            print(ret)
            mrs.otcOutputHandler().print_output(ret,
                                                mainkey="clusters",
                                                listkey={"id", "name"})
        else:
            ret = utils_http.get(url + '/' + OtcConfig.INSTANCE_ID)
            maindata = json.loads(ret)
            if "itemNotFound" in maindata:
                raise RuntimeError("Not found!")
            mrs.otcOutputHandler().print_output(ret, mainkey="server")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="create hadoop cluster",
        args=[arg('--cluster-name', dest='CLUSTER', help='create cluster')])
    def create_cluster():
        pass
class s3(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

    @staticmethod
    def parse_bucket_uri(s3path):
        val = str(s3path).replace('s3://', '').split('/', 1)
        s3bucket = val[0]
        if len(val) > 1:
            s3dir = val[1]
        else:
            s3dir = ""
        return s3bucket, s3dir

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Create bucket",
             examples=[{
                 "List Buckets": "otc s3 ls"
             }, {
                 "List Bucket files": "otc s3 ls mybucket"
             }],
             args=[
                 arg('',
                     dest='SUBCOM_P1',
                     help='[optional Source/Target OBS directory]',
                     metavar="Source/Target DIR")
             ])
    def ls():
        if OtcConfig.SUBCOM_P1 is None:
            buckets = utils_s3.ls_buckets()
            s3.otcOutputHandler().print_output(
                buckets, mainkey="", listkey={"Name", "CreationDate"})
        else:
            s3bucket, s3dir = s3.parse_bucket_uri(OtcConfig.SUBCOM_P1)
            buckets = utils_s3.ls_bucket(Bucket=s3bucket, Prefix=s3dir)
            s3.otcOutputHandler().print_output(
                buckets, mainkey="", listkey={"Key", "Size", "LastModified"})

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Create bucket",
             args=[
                 arg('',
                     dest='SUBCOM_P1',
                     help='[optional Source/Target OBS directory]',
                     metavar="Source/Target DIR")
             ])
    def mb():
        s3bucket = s3.parse_bucket_uri(OtcConfig.SUBCOM_P1)[0]
        utils_s3.create_bucket(Bucket=s3bucket)

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete bucket",
             args=[
                 arg('',
                     dest='SUBCOM_P1',
                     help='[optional Source/Target OBS directory]',
                     metavar="Source/Target DIR")
             ])
    def rb():
        s3bucket = s3.parse_bucket_uri(OtcConfig.SUBCOM_P1)[0]
        utils_s3.delete_bucket(Bucket=s3bucket)

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Remove object",
             args=[
                 arg('',
                     dest='SUBCOM_P1',
                     help='[optional Source/Target OBS directory]',
                     metavar="Source/Target DIR")
             ])
    def rm():
        s3bucket, s3dir = s3.parse_bucket_uri(OtcConfig.SUBCOM_P1)
        utils_s3.delete_object(Bucket=s3bucket, Prefix=s3dir)

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Get Bucket versions",
             args=[
                 arg('',
                     dest='SUBCOM_P1',
                     help='[optional Source/Target OBS directory]',
                     metavar="Source/Target DIR")
             ])
    def get_bucket_versioning():
        s3bucket, s3dir = s3.parse_bucket_uri(
            OtcConfig.SUBCOM_P1)  # @UnusedVariable
        ver = utils_s3.get_bucket_versioning(Bucket=s3bucket, Prefix=s3dir)
        #print(ver) #debug
        s3.otcOutputHandler().print_output(
            ver, mainkey="", listkey={"Key", "Size", "LastModified"})

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="List Bucket file versions",
             args=[
                 arg('',
                     dest='SUBCOM_P1',
                     help='[optional Source/Target OBS directory]',
                     metavar="Source/Target DIR")
             ])
    def list_object_versions():
        s3bucket, s3dir = s3.parse_bucket_uri(
            OtcConfig.SUBCOM_P1)  # @UnusedVariable
        ver = utils_s3.list_object_versions(Bucket=s3bucket, Prefix=s3dir)
        s3.otcOutputHandler().print_output(
            ver, mainkey="", listkey={"Key", "Size", "LastModified"})

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Download / Upload file / directory to bucket",
        examples=[{
            "Download from bucket to local":
            "otc s3 cp s3://bucketname/filename.txt /localdir/filename.txt"
        }, {
            "Upload file / directory to bucket":
            "otc s3 cp /localdir/filename.txt s3://bucketname/filename.txt"
        }],
        args=[
            arg('--recursive',
                dest='S3RECURSIVE',
                help='S3 recursive operation'),
            arg('--encrypted',
                dest='S3ENCRYPTED',
                help='S3 enrypting operation'),
            arg('',
                dest='SUBCOM_P1',
                help='[optional Source/Target OBS directory]',
                metavar="Source/Target DIR"),
            arg('',
                dest='SUBCOM_P2',
                help='[optional Source/Target OBS directory]',
                metavar="Source/Target DIR")
        ])
    def cp():
        if (OtcConfig.SUBCOM_P1 is None or OtcConfig.SUBCOM_P2 is None):
            raise RuntimeError(
                "S3 Copy error. Please add s3 params correctly.")
        elif (str(OtcConfig.SUBCOM_P1).startswith("s3://")
              and OtcConfig.S3RECURSIVE):
            # directory download
            s3bucket, s3dir = s3.parse_bucket_uri(OtcConfig.SUBCOM_P1)
            utils_s3.download_file(Bucket=s3bucket,
                                   Prefix=s3dir,
                                   File=OtcConfig.SUBCOM_P2)
        elif (str(OtcConfig.SUBCOM_P2).startswith("s3://")
              and OtcConfig.S3RECURSIVE):
            # directory upload
            s3bucket, s3dir = s3.parse_bucket_uri(OtcConfig.SUBCOM_P2)
            utils_s3.upload_dir(Local=OtcConfig.SUBCOM_P1,
                                Bucket=s3bucket,
                                Prefix=s3dir,
                                Encryption=OtcConfig.S3ENCRYPTED)
        elif (str(OtcConfig.SUBCOM_P1).startswith("s3://")):
            # file download
            s3bucket, s3dir = s3.parse_bucket_uri(OtcConfig.SUBCOM_P1)
            utils_s3.download_file(Bucket=s3bucket,
                                   Prefix=s3dir,
                                   File=OtcConfig.SUBCOM_P2)
        elif (str(OtcConfig.SUBCOM_P2).startswith("s3://")):
            # file upload
            s3bucket, s3dir = s3.parse_bucket_uri(OtcConfig.SUBCOM_P2)
            utils_s3.upload_file(File=OtcConfig.SUBCOM_P1,
                                 Bucket=s3bucket,
                                 Prefix=s3dir,
                                 Encryption=OtcConfig.S3ENCRYPTED)
Exemple #3
0
class ces(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe alarms",
             args=[arg('--alarm-name', dest='ALARM_NAME', help='Alarm name')])
    def describe_alarms():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/V1.0/" + OtcConfig.PROJECT_ID + "/alarms"
        if not (OtcConfig.ALARM_NAME is None):
            ces.convertALARMNameToId()
            url = "https://" + OtcConfig.DEFAULT_HOST + "/V1.0/" + OtcConfig.PROJECT_ID + "/alarms?start=" + OtcConfig.ALARM_ID

        ret = utils_http.get(url)
        print(json.dumps(json.loads(ret), indent=4, sort_keys=True))
        #elb.otcOutputHandler().print_output(ret, mainkey="")
        #listkey={"id", "name", "status", "vip_address","update_time","bandwidth","type"}
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__, desc="List metric", args=[])
    def list_metrics():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/V1.0/" + OtcConfig.PROJECT_ID + "/metrics"
        ret = utils_http.get(url)
        print(json.dumps(json.loads(ret), indent=4, sort_keys=True))
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__, desc="List favourite metric", args=[])
    def list_favorite_metrics():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/V1.0/" + OtcConfig.PROJECT_ID + "/favorite-metrics"
        ret = utils_http.get(url)
        print(json.dumps(json.loads(ret), indent=4, sort_keys=True))
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__, desc="List metric", args=[])
    def list_metric_data():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/V1.0/" + OtcConfig.PROJECT_ID + "/metric-data?namespace=SYS.ECS&metric_name=cpu_util&dim.0=instance_id,092cebda-839b-42f5-8819-8b440a48cac2&from=1442347449274&to=1442390649274&period=1200&filter=min"
        ret = utils_http.get(url)
        print(json.dumps(json.loads(ret), indent=4, sort_keys=True))
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__, desc="Describ metric", args=[])
    def describe_metric():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/V1.0/" + OtcConfig.PROJECT_ID + "/metrics?namespace=SYS.ECS&metric_name=cpu_util&dim.0=instance_id,fc1a4d7f-44ea-4035-9e55-e29743252617&limit=10&order=desc"
        ret = utils_http.get(url)
        print(json.dumps(json.loads(ret), indent=4, sort_keys=True))
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__, desc="Describ quotas", args=[])
    def describe_quotas():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/V1.0/" + OtcConfig.PROJECT_ID + "/quotas"
        ret = utils_http.get(url)
        print(json.dumps(json.loads(ret), indent=4, sort_keys=True))
        return ret

#     @staticmethod
#     def delete_alarms():
#         if not (OtcConfig.ALARM_NAME is None):
#             ces.convertALARMNameToId()
#         if not (OtcConfig.VPCNAME is None):
#             ecs.convertVPCNameToId()
#         url = "https://" + OtcConfig.DEFAULT_HOST+ "/v1.0/" + OtcConfig.PROJECT_ID + "/alarms" + "?start=" + OtcConfig.ALARM_ID
#
#         ret = utils_http.delete(url)
#         print(ret)
#         return ret
#
#

    @staticmethod
    def convertALARMNameToId():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/alarms"
        JSON = utils_http.get(url)
        parsed = json.loads(JSON)
        alarms = parsed["alarms"]
        ret = None
        for alarm in alarms:
            if alarm.get(
                    "name"
            ) == OtcConfig.ALARM_NAME:  # and ( loadbalancer.get("vpc_id") == OtcConfig.VPCID or OtcConfig.VPCID is None ) :
                OtcConfig.ALARM_ID = alarm["id"]
                ret = OtcConfig.ALARM_ID
        return ret
Exemple #4
0
class mrs(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="description of the avaliable clusters",
             examples=[{
                 "List Clusters": "otc mrs describe_clusters"
             }, {
                 "Show Cluster Details":
                 "otc mrs describe_clusters mycluster"
             }],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='description of the avaliable clusters'),
                 arg('--cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='description of the avaliable clusters')
             ])
    def describe_clusters():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/cluster_infos"
        url = url.replace("iam", "mrs")
        if OtcConfig.CLUSTER_ID is None:
            print(url)
            ret = utils_http.get(url)
            mrs.otcOutputHandler().print_output(ret, mainkey="")
        else:
            ret = utils_http.get(url + '/' + OtcConfig.CLUSTER_ID)
            maindata = json.loads(ret)
            if "itemNotFound" in maindata:
                raise RuntimeError("Not found!")
            mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    def convertCLUSTERNameToId():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/    "

        url = url.replace("iam", "mrs")
        JSON = utils_http.get(url)
        parsed = json.loads(JSON)

        servers = parsed["clusters"]

        ret = None
        for server in servers:
            if server.get("clusterName") == OtcConfig.CLUSTER:
                ret = server["clusterId"]
        if ret:
            OtcConfig.CLUSTER_ID = ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="description of the avaliable hosts in specified cluster",
             examples=[{
                 "List Clusters": "otc mrs describe_clusterhosts"
             }, {
                 "Show Cluster Details":
                 "otc mrs describe_clusterhosts mycluster"
             }],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='description of the avaliable clusters'),
                 arg('--cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='description of the avaliable clusters')
             ])
    def describe_clusterhosts():
        if not (OtcConfig.CLUSTER is None):
            getplugin("mrs").convertCLUSTERNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/clusters/" + OtcConfig.CLUSTER_ID + "/hosts"
        url = url.replace("iam", "mrs")

        ret = utils_http.get(url)

        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="add new node(s) to cluster",
             examples=[{
                 "add node(s)":
                 "otc mrs add-node MYCLUSTER_ID NUM OF NODE"
             }],
             args=[
                 arg('--cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='id of the cluster')
             ])
    def add_nodes():
        REQ_ADD_NODE = utils_templates.create_request("add_node")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/cluster_infos/" + OtcConfig.CLUSTER_ID
        ret = utils_http.post(url, REQ_ADD_NODE)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="add new node(s) to cluster",
             examples=[{
                 "add node(s)":
                 "otc mrs add-node MYCLUSTER_ID NUM OF NODE"
             }],
             args=[
                 arg('--cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='id of the cluster')
             ])
    def add_as():
        if not (OtcConfig.CLUSTER is None):
            getplugin("mrs").convertCLUSTERNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/autoscaling-policy/" + OtcConfig.CLUSTER_ID
        url = url.replace("iam", "mrs")

        REQ_ADD_NODE = utils_templates.create_request("add_as")

        ret = utils_http.post(url, REQ_ADD_NODE)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="create hadoop cluster",
        args=[arg('--cluster-name', dest='CLUSTER', help='create cluster')])
    def create_cluster():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/run-job-flow"
        #vpc_id
        if not (OtcConfig.VPCNAME is None):
            getplugin("ecs").convertVPCNameToId()

        #network_id
        if not OtcConfig.SUBNETNAME is None:
            getplugin("ecs").convertSUBNETNameToId()

        REQ_CREATE_CLUSTER = utils_templates.create_request(
            "create_cluster_with_job")

        ret = utils_http.post(url, REQ_CREATE_CLUSTER)
        print(REQ_CREATE_CLUSTER)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="description of the cluster",
             examples=[{
                 "List jobs": "otc mrs describe-cluster MYCLUSTER-ID"
             }],
             args=[
                 arg('-cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='id of the cluster')
             ])
    def describe_cluster():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/cluster_infos/" + OtcConfig.CLUSTER_ID
        ret = utils_http.get(url)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="delete specific cluster",
             examples=[{
                 "List jobs":
                 "otc mrs delete-cluster --cluster-id MYCLUSTER-ID"
             }],
             args=[
                 arg('-cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='id of the cluster')
             ])
    def delete_cluster():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/clusters/" + OtcConfig.CLUSTER_ID
        ret = utils_http.delete(url)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="add job to cluster",
             examples=[{
                 "add job": "otc mrs add-job !!!!!!!!!"
             }],
             args=[
                 arg('-cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='id of the cluster')
             ])
    def add_job():
        REQ_ADD_JOB = utils_templates.create_request("add_job")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/jobs/submit-job"
        ret = utils_http.post(url, REQ_ADD_JOB)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="description of the avaliable jobs",
             examples=[{
                 "List jobs": "otc mrs describe-jobs"
             }, {
                 "Show Cluster Details": "otc mrs jobs of the cluster"
             }])
    def describe_jobs():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/job-exes"

        ret = utils_http.get(url)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="description of the job detail",
        examples=[{
            "List jobs":
            "otc mrs describe-job-detail -jobexecid JOB-EXEC-ID"
        }],
        args=[arg('--job-exec-id', dest='JOB_EXEC_ID', help='id of the job')])
    def describe_job_details():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/job-exes/" + OtcConfig.JOB_EXEC_ID
        ret = utils_http.get(url)
        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="delete the job ",
        examples=[{
            "List jobs": "otc mrs delete-job -jobexecid JOB-EXEC-ID"
        }],
        args=[arg('-job-exec-id', dest='JOB_EXEC_ID', help='id of the job')])
    def delete_job():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/job-executions/" + OtcConfig.JOB_EXEC_ID
        ret = utils_http.delete(url)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret
Exemple #5
0
class autoscaling(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

    @staticmethod
    def convertASNameToId():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group"
        JSON = utils_http.get(url)
        parsed = json.loads(JSON)
        autoscalings = parsed["scaling_groups"]
        ret = None
        for s in autoscalings:
            if s.get("scaling_group_name") == OtcConfig.SCALINGGROUP_NAME:
                ret = s["scaling_group_id"]
        OtcConfig.SCALINGGROUP_ID = ret


    @staticmethod
    def convertASPolicyNameToId():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_policy/" + OtcConfig.SCALINGGROUP_ID + "/list?scaling_policy_name="  + OtcConfig.SCALING_POLICY_NAME
        JSON = utils_http.get(url)
        parsed = json.loads(JSON)
        as_policy = parsed["scaling_policies"]
        ret = None
        for s in as_policy:
            if s.get("scaling_policy_name") == OtcConfig.SCALING_POLICY_NAME:
                ret = s["scaling_policy_id"]
        OtcConfig.SCALING_POLICY_ID = ret


    @staticmethod
    def convertASConfigurationNameToId():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_configuration"
        JSON = utils_http.get(url)
        parsed = json.loads(JSON)
        autoscaleConfs = parsed["scaling_configurations"]
        ret = None
        for s in autoscaleConfs:
            if s.get("scaling_configuration_name") == OtcConfig.SCALING_CONFIGURATION_NAME:
                ret = s["scaling_configuration_id"]

        OtcConfig.SCALING_CONFIGURATION_ID = ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete auto scaling group",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--auto-scaling-group-id',    dest='SCALINGGROUP_ID',     help='Id of Auto Scaling group')
                          ])
    def delete_auto_scaling_group():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group/" + OtcConfig.SCALINGGROUP_ID
        ret = utils_http.delete(url)
        print(ret)
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe auto scaling groups",
             examples=[],
             args = [ ])
    def describe_auto_scaling_groups():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group"
        ret = utils_http.get(url)
        #print(ret)
        autoscaling.otcOutputHandler().print_output(ret, mainkey="scaling_groups",listkey={"scaling_group_name","scaling_configuration_name","create_time","instance_terminate_policy","is_scaling", "scaling_group_status"})
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe auto scaling group details",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--auto-scaling-group-id',    dest='SCALINGGROUP_ID',     help='Id of Auto Scaling group')
                          ])
    def describe_auto_scaling_groups_details():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group/" + OtcConfig.SCALINGGROUP_ID
        ret = utils_http.get(url)
        autoscaling.otcOutputHandler().print_output(ret,
                                                    mainkey="scaling_group"#,listkey={"instance_terminate_policy","is_scaling"}
                                                    )
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe auto scaling configuration details",
             examples=[],
             args=[])
    def describe_auto_scaling_configuration():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_configuration"
        ret = utils_http.get(url)
        autoscaling.otcOutputHandler().print_output(ret, mainkey="scaling_configurations" #, subkey="instance_config"
        , listkey={"scaling_configuration_name","scaling_configuration_id","create_time"#, "instance_config"
                }
                )
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe auto scaling configuration details",
             examples=[],
             args = [
                    arg(    '--scaling-configuration-id',     dest='SCALING_CONFIGURATION_ID',     help='scaling-configuration-id'),
                    arg(    '--scaling-configuration-name',     dest='SCALING_CONFIGURATION_NAME',     help='scaling-configuration-name')
                          ])
    def describe_auto_scaling_configuration_details():
        if not (OtcConfig.SCALING_CONFIGURATION_NAME is None):
            autoscaling.convertASConfigurationNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_configuration/" + OtcConfig.SCALING_CONFIGURATION_ID
        ret = utils_http.get(url)
        #print(ret)
        autoscaling.otcOutputHandler().print_output(ret, mainkey="scaling_configuration" #, subkey="instance_config"
        )
        #autoscaling.otcOutputHandler().print_output(ret, mainkey="scaling_configuration", listkey={"scaling_configuration_name",
        #                                                                                            "scaling_configuration_id",
        #                                                                                             "create_time", "instance_config"})
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe auto scaling instances",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--auto-scaling-group-id',    dest='SCALINGGROUP_ID',     help='Id of Auto Scaling group')
                          ])
    def describe_auto_scaling_instances():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group_instance/" + OtcConfig.SCALINGGROUP_ID + "/list"
        ret = utils_http.get(url)
        autoscaling.otcOutputHandler().print_output(ret, mainkey="scaling_group_instances",listkey={"instance_name","instance_id", "scaling_group_name", "life_cycle_state"} )
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe policies",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--auto-scaling-group-id',    dest='SCALINGGROUP_ID',     help='Id of Auto Scaling group')
                          ])
    def describe_policies():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_policy/" + OtcConfig.SCALINGGROUP_ID + "/list"
        ret = utils_http.get(url)
        #print(ret)
        autoscaling.otcOutputHandler().print_output(ret, mainkey="scaling_policies",
                                                                 listkey={"cool_down_time", "scaling_policy_action",
                                                                  "policy_status", "scaling_policy_type", "scheduled_policy", "scaling_policy_name", "scaling_policy_id"})
        return ret


    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe activitylog",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--auto-scaling-group-id',    dest='SCALINGGROUP_ID',     help='Id of Auto Scaling group')
                          ])
    def describe_activitylog():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_activity_log/" + OtcConfig.SCALINGGROUP_ID
        ret = utils_http.get(url)

        autoscaling.otcOutputHandler().print_output(ret, mainkey="scaling_activity_log", listkey={"id", "status", "description", "instance_value", "desire_value", "scaling_configuration_name", "scaling_value", "start_time", "end_time", "instance_added_list", "instance_deleted_list", "instance_removed_list"})
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe quotas",
             examples=[],
             args = [ ])
    def describe_quotas():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/quotas"
        ret = utils_http.get(url)
        parsed = json.loads(ret)
        autoscaling.otcOutputHandler().print_output(parsed["quotas"]["resources"], mainkey="", listkey={"type", "used", "quota", "max"})
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe quotas of group",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--auto-scaling-group-id',    dest='SCALINGGROUP_ID',     help='Id of Auto Scaling group')
                          ])
    def describe_quotas_of_group():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/quotas/" + OtcConfig.SCALINGGROUP_ID
        ret = utils_http.get(url)
        parsed = json.loads(ret)
        autoscaling.otcOutputHandler().print_output(parsed["quotas"]["resources"], mainkey="", listkey={"type", "used", "quota", "max"})
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe policy details",
             examples=[],
             args = [
                    arg(    '--scaling-policy-name',     dest='SCALING_POLICY_NAME',     help='Specifies the AS policy name. The name can contain letters,digits,underscores(_), and hyphens (-) and cannot exceed 64 characters'),
                    arg(     '--scaling-policy-id',     dest='SCALING_POLICY_ID',     help='scaling-policy-id')
                          ])
    def describe_policy_details():
        if not (OtcConfig.SCALING_POLICY_NAME is None):
            autoscaling.convertASPolicyNameToId()

        print(OtcConfig.SCALING_POLICY_ID)
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_policy/" + OtcConfig.SCALING_POLICY_ID
        ret = utils_http.get(url)
        #autoscaling.otcOutputHandler().print_output(ret, mainkey="scaling_policy",                                                     listkey={"scaling_policy_id", "scaling_group_id"})
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        return ret


    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Create auto scaling policy",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--scaling-policy-name',     dest='SCALING_POLICY_NAME',     help='Specifies the AS policy name. The name can contain letters,digits,underscores(_), and hyphens (-) and cannot exceed 64 characters'),
                    arg(     '--scaling-policy-id' ,    dest='SCALING_POLICY_ID'  ,   help='scaling-policy-id'),
                    arg(    '--recurrence-value',     dest='RECURRENCE_VALUE',     help='recurrence-value'),
                    arg(    '--start-time',     dest='START_TIME',     help='start-time'),
                    arg(    '--launch-time',     dest='LAUNCH_TIME',     help='launch-time'),
                    arg(    '--end-time',     dest='END_TIME',     help='end-time'),
                    arg(    '--recurrence-type',     dest='RECURRENCE_TYPE',     help='recurrence-type'),

                    arg(    '--scaling-policy-type',     dest='SCALING_POLICY_TYPE',     help='Specifies the AS policy type: ALARM/SCHEDULED/RECURRENCE'),
                    arg(    '--operation-as-policy',     dest='OPERATION_AS_POLICY',     help='Specifies the operation to be performed. The default operation is ADD.ADD: adds instances to the AS group.REMOVE: removes instances from the AS group.SET: sets the number of the instances in the AS group'),
                    arg('--count',    dest='NUMCOUNT',     help='Number of VM will be created'),
                    arg(    '--cool-down-time',     dest='COOL_DOWN_TIME',     help='cool-down-time')
])
    def create_auto_scaling_policy():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()
        REQ_CREATE_SCP=utils_templates.create_request("create_as_policy")
        url = "https://" + OtcConfig.DEFAULT_HOST+ "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_policy"
        ret = utils_http.post(url, REQ_CREATE_SCP)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        return ret


    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Modify auto scaling policy",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--scaling-policy-name',     dest='SCALING_POLICY_NAME',     help='Specifies the AS policy name. The name can contain letters,digits,underscores(_), and hyphens (-) and cannot exceed 64 characters'),
                    arg(     '--scaling-policy-id' ,    dest='SCALING_POLICY_ID' ,    help='scaling-policy-id'),
                    arg(    '--recurrence-value',     dest='RECURRENCE_VALUE',     help='recurrence-value'),
                    arg(    '--start-time',     dest='START_TIME',     help='start-time'),
                    arg(    '--launch-time',     dest='LAUNCH_TIME',     help='launch-time'),
                    arg(    '--end-time',     dest='END_TIME',     help='end-time'),
                    arg(    '--recurrence-type',     dest='RECURRENCE_TYPE',     help='recurrence-type'),

                    arg(    '--scaling-policy-type',     dest='SCALING_POLICY_TYPE',     help='Specifies the AS policy type: ALARM/SCHEDULED/RECURRENCE'),
                    arg(    '--operation-as-policy',     dest='OPERATION_AS_POLICY',     help='Specifies the operation to be performed. The default operation is ADD.ADD: adds instances to the AS group.REMOVE: removes instances from the AS group.SET: sets the number of the instances in the AS group'),
                    arg('--count',    dest='NUMCOUNT',     help='Number of VM will be created'),
                    arg(    '--cool-down-time',     dest='COOL_DOWN_TIME',     help='cool-down-time')
                    ])
    def modify_auto_scaling_policy():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()
        if not (OtcConfig.SCALING_POLICY_NAME is None):
            autoscaling.convertASPolicyNameToId()

        REQ_CREATE_SCP=utils_templates.create_request("modify_as_policy")
        #print(REQ_CREATE_SCP)

        url = "https://" + OtcConfig.DEFAULT_HOST+ "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_policy/" + OtcConfig.SCALING_POLICY_ID
        #print(url)
        ret = utils_http.put(url, REQ_CREATE_SCP)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        return ret



    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Create auto scaling group",
             examples=[],
             args = [

                    arg(    '--scaling-policy-name',     dest='SCALING_POLICY_NAME',     help='Specifies the AS policy name. The name can contain letters,digits,underscores(_), and hyphens (-) and cannot exceed 64 characters'),
                    arg(     '--scaling-policy-id' ,    dest='SCALING_POLICY_ID'  ,   help='scaling-policy-id'),
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--scaling-configuration-id',     dest='SCALING_CONFIGURATION_ID',     help='scaling-configuration-id'),
                    arg(    '--scaling-configuration-name',     dest='SCALING_CONFIGURATION_NAME',     help='scaling-configuration-name'),
                    arg('--count',    dest='NUMCOUNT',     help='Number of VM will be created'),
                                         arg(    '--cool-down-time',     dest='COOL_DOWN_TIME',     help='cool-down-time'),
                    arg(    '--min-instance-number',     dest='MIN_INSTANCE_NUMBER',     help='min-instance-number'),
                    arg(    '--max-instance-number',     dest='MAX_INSTANCE_NUMBER',     help='max-instance-number'),
                    arg(    '--listener-id',     dest='LISTENER_ID',     help='Listener Id of the VM'),
                    arg(    '--health-periodic-audit-method',     dest='HEALTH_PERIODIC_AUDIT_METHOD',     help='health-periodic-audit-method'),
                    arg(    '--health-periodic-audit-time',     dest='HEALTH_PERIODIC_AUDIT_TIME',     help='health-periodic-audit-time'),
                    arg(    '--instance-terminate-policy',     dest='INSTANCE_TERMINATE_POLICY',     help='instance-terminate-policy'),
                    arg(    '--vpc-id',    dest='VPCID',     help='Id of the VPC will use during VM creation'),
                    arg(    '--vpc-name',    dest='VPCNAME',     help='Name of the VPC reference will use during VM creation'),
                    arg(  '--subnet-name',    dest='SUBNETNAME',     help='Name of the subnet reference will use during VM creation'),
                    arg(  '--subnet-id',    dest='SUBNETID',     help='Id of the subnet will use during VM creation'),
                    arg(    '--notifications',     dest='NOTIFICATIONS',     help='notifications'),
                    arg(    '--group-names',    dest='SECUGROUPNAME',     help='Name of the security group'),
                    arg(    '--security-group-ids',    dest='SECUGROUP',     help='Id of the security group')
                    ])
    def create_auto_scaling_group():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()

        #vpc_id
        if not (OtcConfig.VPCNAME is None):
            getplugin("ecs").convertVPCNameToId()
        #scaling_configuration_id
        if not (OtcConfig.SCALING_CONFIGURATION_NAME is None):
            autoscaling.convertASConfigurationNameToId()

        #lb_listener_id
        if not (OtcConfig.LISTENER_NAME is None):
            autoscaling.convertLISTENERNameToId()
        #network_id
        if not OtcConfig.SUBNETNAME is None:
            getplugin("ecs").convertSUBNETNameToId()
        #security_group_id
        if not OtcConfig.SECUGROUPNAME is None:
            getplugin("ecs").convertSECUGROUPNameToId()
        print(OtcConfig.SUBNETID)
        print(OtcConfig.SUBNETID)
        REQ_CREATE_SCG=utils_templates.create_request("create_as_group")
        url = "https://" + OtcConfig.DEFAULT_HOST+ "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group"
        ret = utils_http.post(url, REQ_CREATE_SCG)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        #print(REQ_CREATE_SCG)
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Create auto scaling group",
             examples=[],
             args = [

                    arg(    '--scaling-policy-name',     dest='SCALING_POLICY_NAME',     help='Specifies the AS policy name. The name can contain letters,digits,underscores(_), and hyphens (-) and cannot exceed 64 characters'),
                    arg(     '--scaling-policy-id',     dest='SCALING_POLICY_ID',     help='scaling-policy-id'),
					arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--scaling-configuration-id',     dest='SCALING_CONFIGURATION_ID',     help='scaling-configuration-id'),
                    arg(    '--scaling-configuration-name',     dest='SCALING_CONFIGURATION_NAME',     help='scaling-configuration-name'),
                    arg('--count',    dest='NUMCOUNT',     help='Number of VM will be created'),
                    arg(    '--cool-down-time',     dest='COOL_DOWN_TIME',     help='cool-down-time'),                    arg(    '--min-instance-number',     dest='MIN_INSTANCE_NUMBER',     help='min-instance-number'),
                    arg(    '--max-instance-number',     dest='MAX_INSTANCE_NUMBER',     help='max-instance-number'),
                    arg(    '--listener-id',     dest='LISTENER_ID',     help='Listener Id of the VM'),
                    arg(    '--health-periodic-audit-method',     dest='HEALTH_PERIODIC_AUDIT_METHOD',     help='health-periodic-audit-method'),
                    arg(    '--health-periodic-audit-time',     dest='HEALTH_PERIODIC_AUDIT_TIME',     help='health-periodic-audit-time'),
                    arg(    '--instance-terminate-policy',     dest='INSTANCE_TERMINATE_POLICY',     help='instance-terminate-policy'),
                    arg(    '--vpc-id',    dest='VPCID',     help='Id of the VPC will use during VM creation'),
                    arg(    '--vpc-name',    dest='VPCNAME',     help='Name of the VPC reference will use during VM creation'),
                    arg(  '--subnet-name',    dest='SUBNETNAME',     help='Name of the subnet reference will use during VM creation'),
                    arg(  '--subnet-id',    dest='SUBNETID',     help='Id of the subnet will use during VM creation'),
                    arg(    '--notifications',     dest='NOTIFICATIONS',     help='notifications'),
                    arg(    '--group-names',    dest='SECUGROUPNAME',     help='Name of the security group'),
                    arg(    '--security-group-ids',    dest='SECUGROUP',     help='Id of the security group')
                    ])
    def modify_auto_scaling_group():
        if (OtcConfig.SCALINGGROUP_ID is None) and not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()
        #print(SCALINGGROUP_NAME)
        #vpc_id
        if not (OtcConfig.VPCNAME is None):
            getplugin("ecs").convertVPCNameToId()
        #scaling_configuration_id
        if not (OtcConfig.SCALING_CONFIGURATION_NAME is None):
            autoscaling.convertASConfigurationNameToId()

        #lb_listener_id
        if not (OtcConfig.LISTENER_NAME is None):
            autoscaling.convertLISTENERNameToId()
        #network_id
        if not OtcConfig.SUBNETNAME is None:
            getplugin("ecs").convertSUBNETNameToId()
        #security_group_id
        if not OtcConfig.SECUGROUPNAME is None:
            getplugin("ecs").convertSECUGROUPNameToId()
        #print(OtcConfig.SECUGROUPNAME)
        #print(OtcConfig.SECUGROUP)
        REQ_CREATE_SCG=utils_templates.create_request("modify_as_group")
        url = "https://" + OtcConfig.DEFAULT_HOST+ "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group/"+ OtcConfig.SCALINGGROUP_ID
        ret = utils_http.put(url, REQ_CREATE_SCG)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        #print(REQ_CREATE_SCG)
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Enable auto scaling policy",
             examples=[],
             args = [

                    arg(    '--scaling-policy-name',     dest='SCALING_POLICY_NAME',     help='Specifies the AS policy name. The name can contain letters,digits,underscores(_), and hyphens (-) and cannot exceed 64 characters'),
                    arg(     '--scaling-policy-id' ,    dest='SCALING_POLICY_ID'   ,  help='scaling-policy-id')
                    ])
    def enable_auto_scaling_policy():
        if not (OtcConfig.SCALING_POLICY_NAME is None):
            autoscaling.convertASPolicyNameToId()
        OtcConfig.AS_POLICY_ACTION="resume"
        REQ_ACTION_SCP=utils_templates.create_request("execute_enable_disable_as_policy")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_policy/" + OtcConfig.SCALING_POLICY_ID  + "/action"
        ret = utils_http.post(url, REQ_ACTION_SCP)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        return ret


    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Disable auto scaling policy",
             examples=[],
             args = [

                    arg(    '--scaling-policy-name',     dest='SCALING_POLICY_NAME',     help='Specifies the AS policy name. The name can contain letters,digits,underscores(_), and hyphens (-) and cannot exceed 64 characters'),
                    arg(     '--scaling-policy-id' ,    dest='SCALING_POLICY_ID' ,    help='scaling-policy-id')
                    ])
    def disable_auto_scaling_policy():
        if not (OtcConfig.SCALING_POLICY_NAME is None):
            autoscaling.convertASPolicyNameToId()
        print(OtcConfig.SCALING_POLICY_ID)
        OtcConfig.AS_POLICY_ACTION="pause"
        REQ_ACTION_SCP=utils_templates.create_request("execute_enable_disable_as_policy")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_policy/" + OtcConfig.SCALING_POLICY_ID  + "/action"
        ret = utils_http.post(url, REQ_ACTION_SCP)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Execute auto scaling policy",
             examples=[],
             args = [

                    arg(    '--scaling-policy-name',     dest='SCALING_POLICY_NAME',     help='Specifies the AS policy name. The name can contain letters,digits,underscores(_), and hyphens (-) and cannot exceed 64 characters'),
                    arg(     '--scaling-policy-id',     dest='SCALING_POLICY_ID' ,    help='scaling-policy-id')
                    ])
    def execute_auto_scaling_policy():
        if not (OtcConfig.SCALING_POLICY_NAME is None):
            autoscaling.convertASPolicyNameToId()
        OtcConfig.AS_POLICY_ACTION="execute"
        REQ_ACTION_SCP=utils_templates.create_request("execute_enable_disable_as_policy")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_policy/" + OtcConfig.SCALING_POLICY_ID  + "/action"
        ret = utils_http.post(url, REQ_ACTION_SCP)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        return ret


    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Enable auto scaling group",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--auto-scaling-group-id',    dest='SCALINGGROUP_ID',     help='Id of Auto Scaling group')
                          ])
    def enable_auto_scaling_group():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()

        OtcConfig.ACTION_DISABLE_ENABLE_AS_GROUP="resume"
        REQ_ACTION_SCG=utils_templates.create_request("disable_enable_as_group")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group/" + OtcConfig.SCALINGGROUP_ID + "/action"
        ret = utils_http.post(url, REQ_ACTION_SCG)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Disable auto scaling group",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--auto-scaling-group-id',    dest='SCALINGGROUP_ID',     help='Id of Auto Scaling group')
                          ])
    def disable_auto_scaling_group():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()
        OtcConfig.ACTION_DISABLE_ENABLE_AS_GROUP="pause"
        REQ_ACTION_SCG=utils_templates.create_request("disable_enable_as_group")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group/" + OtcConfig.SCALINGGROUP_ID + "/action"
        ret = utils_http.post(url, REQ_ACTION_SCG)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
            desc="Deletes auto scaling instance from group",
            examples=[],
            args = [
                     arg(    '--instance-name',     dest='INSTANCE_NAME',     help='Instance name of the VM'),
               ])
    def delete_auto_scaling_instance_from_group():
        if not OtcConfig.INSTANCE_NAME is None:
            getplugin("ecs").convertINSTANCENameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group_instance/" + OtcConfig.INSTANCE_ID
        ret = utils_http.delete(url)
        print(ret)
        return ret


    @staticmethod

    @otcfunc(plugin_name=__name__,
             desc="Batch delete auto scaling configuration",
             examples=[],
             args = [
                    arg(    '--scaling-configuration-id',     dest='SCALING_CONFIGURATION_ID',     help='scaling-configuration-id'),
                    arg(    '--scaling-configuration-name',     dest='SCALING_CONFIGURATION_NAME',     help='scaling-configuration-name')
                    ])
    def batch_delete_auto_scaling_configuration():
        if (OtcConfig.SCALING_CONFIGURATION_ID is None) and not (OtcConfig.SCALING_CONFIGURATION_NAME is None):
            autoscaling.convertASConfigurationNameToId()

        REQ_DELETE_BATCH_SC=utils_templates.create_request("batch_delete_AS_config")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_configurations"
        ret = utils_http.post(url, REQ_DELETE_BATCH_SC)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        #print(REQ_DELETE_BATCH_SC)
        return ret


    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Batch delete auto scaling instances",
             examples=[],
             args = [
                    arg(    '--auto-scaling-group-name',    dest='SCALINGGROUP_NAME',     help='Name of Auto Scaling group'),
                    arg(    '--auto-scaling-group-id',    dest='SCALINGGROUP_ID',     help='Id of Auto Scaling group'),
                    arg(    '--instance-name',     dest='INSTANCE_NAME',     help='Instance name of the VM'),
                    arg(    '--instance-action-add-remove-batch',     dest='INSTANCE_ACTION_ADD_REMOVE_BATCH',     help='instance-action-add-remove-batch'),
                    arg(    '--instance-ids',     dest='INSTANCE_ID',     help='Instance Id of the VM'),
                    arg(    '--instance-delete',     dest='INSTANCE_DELETE',     help='instance-delete'),
               ])
    def batch_add_delete_auto_scaling_instances():
        if not (OtcConfig.SCALINGGROUP_NAME is None):
            autoscaling.convertASNameToId()

        if (OtcConfig.INSTANCE_ID is None) and not OtcConfig.INSTANCE_NAME is None:
            getplugin("ecs").convertINSTANCENameToId()

        REQ_BATCH_INST=utils_templates.create_request("batch_remove_add_instance")

        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_group_instance/"+ OtcConfig.SCALINGGROUP_ID +"/action"
        ret = utils_http.post(url, REQ_BATCH_INST)
        #print(REQ_BATCH_INST)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        return ret


    @staticmethod
    def create_launch_configuration():
        raise RuntimeError("NOT IMPLEMENTED!")

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete policies",
             examples=[],
             args = [

                    arg(    '--scaling-policy-name',     dest='SCALING_POLICY_NAME',     help='Specifies the AS policy name. The name can contain letters,digits,underscores(_), and hyphens (-) and cannot exceed 64 characters'),
                    arg(     '--scaling-policy-id',     dest='SCALING_POLICY_ID' ,    help='scaling-policy-id')
                    ])
    def delete_policies():
        if not (OtcConfig.SCALING_POLICY_NAME is None):
            autoscaling.convertASPolicyNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_policy/" + OtcConfig.SCALING_POLICY_ID
        ret = utils_http.delete(url)
        print(ret)
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete auto scaling configuration",
             examples=[],
             args = [
                    arg(    '--scaling-configuration-id',     dest='SCALING_CONFIGURATION_ID',     help='scaling-configuration-id'),
                    arg(    '--scaling-configuration-name',     dest='SCALING_CONFIGURATION_NAME',     help='scaling-configuration-name')
                    ])
    def delete_auto_scaling_configuration():
        if not (OtcConfig.SCALING_CONFIGURATION_NAME is None):
            autoscaling.convertASConfigurationNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_configuration/"+ OtcConfig.SCALING_CONFIGURATION_ID
        ret = utils_http.delete(url)
        print(ret)
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete auto scaling configuration",
             examples=[],
             args = [
                    arg(    '--scaling-configuration-id',     dest='SCALING_CONFIGURATION_ID',     help='scaling-configuration-id'),
                    arg(    '--scaling-configuration-name',     dest='SCALING_CONFIGURATION_NAME',     help='scaling-configuration-name'),
                    arg(    '--image-name',    dest='IMAGENAME',     help='Name of the image reference will used during VM creation'),
                    arg(    '--image-id',    dest='IMAGE_ID',     help='Id of the image reference will use during VM creation'),
                    arg(    '--instance-type',    dest='INSTANCE_TYPE_NAME',     help='Flavor type of the VM'),
                    arg(    '--size',    dest='VOLUME_SIZE',     help='Size of the EVS disk'),
                    arg(    '--volume-type',    dest='VOLUME_TYPE',     help='Volume type of the EVS disk [SSD SAS SATA]'),
                    arg(    '--disk-type',     dest='DISK_TYPE',     help='disk-type'),
                    arg(    '--key-name',     dest='KEYNAME',     help='SSH key name| S3 Object key')
                    ])
    def create_auto_scaling_configuration():
        if not OtcConfig.INSTANCE_TYPE_NAME is None:
            getplugin("ecs").convertFlavorNameToId()
        if not OtcConfig.IMAGENAME is None:
            getplugin("ecs").convertIMAGENameToId()
        REQ_CREATE_SC=utils_templates.create_request("create_as_configuration")
        #print(REQ_CREATE_SC)
        url = "https://" + OtcConfig.DEFAULT_HOST+ "/autoscaling-api/v1/" + OtcConfig.PROJECT_ID + "/scaling_configuration"
        ret = utils_http.post(url, REQ_CREATE_SC)
        autoscaling.otcOutputHandler().print_output(ret,mainkey="")
        return ret

    @staticmethod
    def delete_launch_configuration():
        raise RuntimeError("NOT IMPLEMENTED!")
Exemple #6
0
class rds(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="create rds cluster",
        examples=[{
            'otc rds create_cluster --subnet-id  1111111-1111-1111-1111-a96f27f31111 --vpc-name MYVPC --group-names MYSECGROUP --cluster-name TEST --admin-pass Test1234+'
        }],
        args=[
            arg('--cluster-name', dest='CLUSTER', help='create cluster'),
            arg('--disk-size', dest='DISK_SIZE', help='disk size')
        ])
    def create_cluster():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/rds/v1/" + OtcConfig.PROJECT_ID + "/instances"
        url = string.replace(url, 'iam', 'rds')
        #vpc_id
        if not (OtcConfig.VPCNAME is None):
            getplugin("ecs").convertVPCNameToId()

        #network_id
        if not OtcConfig.SUBNETNAME is None:
            getplugin("ecs").convertSUBNETNameToId()

        if (not (OtcConfig.SECUGROUPNAME is None)):
            getplugin("ecs").convertSECUGROUPNameToId()

        if not OtcConfig.SUBNETNAME is None:
            ecs.convertSUBNETNameToId()

        if (OtcConfig.DBTYPE is None):
            OtcConfig.DBTYPE = "MySQL"

        if (OtcConfig.DBVERSION is None):
            OtcConfig.DBVERSION = "5.7.20"

        if (OtcConfig.DISK_SIZE is None):
            OtcConfig.DISK_SIZE = 100

        if (OtcConfig.DISK_TYPE is None):
            OtcConfig.DISK_TYPE = "COMMON"

        REQ_CREATE_CLUSTER = utils_templates.create_request("create_cluster")

        ret = utils_http.post(url, REQ_CREATE_CLUSTER)
        print REQ_CREATE_CLUSTER
        print(url)
        print(ret)
        rds.otcOutputHandler().print_output(ret, mainkey="")

    @staticmethod
    def add():
        # TODO: NOT implemented
        ret = utils_templates.create_request("as_modify")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Description of all DB instances",
             examples=[{
                 "List DB instances": "otc rds describe_db_instances"
             }],
             args=[])
    def describe_db_instances():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/rds/v1/" + OtcConfig.PROJECT_ID + "/instances"
        url = string.replace(url, 'iam', 'rds')
        ret = utils_http.get(url)
        rds.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Description of all Datastores",
        examples=[{
            "List DB instances":
            "otc rds describe-datastore --db-type [MySQL|PostgreSQL|SQLServer]"
        }],
        args=[])
    def describe_datastore():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/rds/v1/" + OtcConfig.PROJECT_ID + "/datastores/" + OtcConfig.DBTYPE + "/versions"
        url = string.replace(url, 'iam', 'rds')
        ret = utils_http.get(url)
        rds.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Description of all flavors for a Datastores",
        examples=[{
            "List DB instances":
            "otc rds describe-flavors --db-type [MySQL|PostgreSQL|SQLServer]"
        }],
        args=[])
    def describe_flavors():
        if (OtcConfig.REGION is None):
            OtcConfig.REGION = "eu-de"
        if (OtcConfig.DATASTORE_ID is None):
            OtcConfig.DATASTORE_ID = "4f71c5b5-8939-424e-8825-8e3816e4303d"
        url = "https://" + OtcConfig.DEFAULT_HOST + "/rds/v1/" + OtcConfig.PROJECT_ID + "/flavors?dbId=" + OtcConfig.DATASTORE_ID + "&region=" + OtcConfig.REGION
        url = string.replace(url, 'iam', 'rds')

        ret = utils_http.get(url)
        rds.otcOutputHandler().print_output(ret, mainkey="")
        return ret
Exemple #7
0
class dcs(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

    # url = "https://" + OtcConfig.DEFAULT_HOST+ "/v2/" + OtcConfig.PROJECT_ID + "/os-availability-zone/detail"

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="List instances",
        examples=
        [{'List instances":"otc dcs list_instances'},
         {
             'Information about all DCS instances (JSON): otc dcs list_instances --output json '
         }],
        args=[])
    def list_instances():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/instances"
        url = url.replace('iam', 'dcs')
        ret = utils_http.get(url)
        #print (url)
        #print (ret)
        dcs.otcOutputHandler().print_output(
            ret,
            mainkey="instances",
            listkey={
                "instance_id", "name", "capacity", "ip", "port", "used_memory",
                "max_memory", "resource_spec_code", "engine_version", "status",
                "created_at"
            })

        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Describe instance",
        examples=
        [{'Describe instances":"otc dcs describe_instances'},
         {
             'Detailed information about a specific DCS instance (JSON): otc dcs describe_instances --instance-ids 097da903-ab95-44f3-bb5d-5fc08dfb6cc3 --output json '
         }],
        args=[
            arg('--instance-ids',
                dest='INSTANCE_ID',
                help='Instance ID of the VM')
        ])
    def describe_instance():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/instances"
        url = url.replace('iam', 'dcs')
        ret = utils_http.get(url + '/' + OtcConfig.INSTANCE_ID)
        print(url + '/' + OtcConfig.INSTANCE_ID)
        #print (ret)
        dcs.otcOutputHandler().print_output(ret, mainkey="")

        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Create instance",
        examples=
        [{'Create instances":"otc dcs create_instance'},
         {
             'Create a DCS instance (JSON): otc dcs create_instance --instance-name Test-MS --instance-type OTC_DCS_MS:2 --description Test --admin-pass Test1234 --vpc-name vpc-adc-docker  --group-names DCS --subnet-name subnet-az1-110 '
         }],
        args=[
            arg('--instance-name',
                dest='INSTANCE_NAME',
                help='Name of the DCS instance'),
            arg('--instance-type',
                dest='INSTANCE_TYPE_NAME',
                help='DCS Instance Type:Memory Size'),
            arg('--description',
                dest='DESCRIPTION',
                help='DCS Instance Description'),
            arg('--admin-pass',
                dest='ADMINPASS',
                help='DCS Instance Admin Password'),
            arg('--vpc-name', dest='VPCNAME', help='VPC name'),
            arg('--group-names',
                dest='SECUGROUPNAME',
                help='Security Group name'),
            arg('--subnet-name', dest='SUBNETNAME', help='Subnet name')
        ])
    def create_instance():
        if not OtcConfig.VPCNAME is None:
            getplugin("ecs").convertVPCNameToId()
        if not OtcConfig.SUBNETNAME is None:
            getplugin("ecs").convertSUBNETNameToId()
        if not OtcConfig.SECUGROUPNAME is None:
            getplugin("ecs").convertSECUGROUPNameToId()
        if not OtcConfig.AZ is None:
            dcs.convertAZnameToId()
        if OtcConfig.INSTANCE_TYPE_NAME is None:
            OtcConfig.INSTANCE_TYPE_NAME = "OTC_DCS_SINGLE:1"
        if OtcConfig.INSTANCE_NAME is None:
            OtcConfig.INSTANCE_NAME = "dcs"

        (OtcConfig.INSTANCE_DCS_TYPE, OtcConfig.INSTANCE_DCS_SIZE) = str(
            OtcConfig.INSTANCE_TYPE_NAME).split(':')
        REQ_CREATE_DCS = utils_templates.create_request("create_instance")
        #print (REQ_CREATE_DCS)

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/instances"
        url = url.replace('iam', 'dcs')
        #print (url)
        ret = utils_http.post(url, REQ_CREATE_DCS)

        print(ret)

        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Delete instance",
        examples=
        [{'Delete instances":"otc dcs delete_instances'},
         {
             'Delete a specific DCS instance: otc dcs delete_instance --instance-ids 097da903-ab95-44f3-bb5d-5fc08dfb6cc3 '
         }],
        args=[
            arg('--instance-ids',
                dest='INSTANCE_ID',
                help='Instance ID of the DCS instance')
        ])
    def delete_instance():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/instances"
        url = url.replace('iam', 'dcs')
        ret = utils_http.delete(url + '/' + OtcConfig.INSTANCE_ID)
        #print (url)
        #print (ret)
        dcs.otcOutputHandler().print_output(ret, mainkey="")

        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Stop instance",
        examples=
        [{'Stop instance":"otc dcs stop_instance'},
         {
             'Stop a specific DCS instance: otc dcs stop_instance --instance-ids 097da903-ab95-44f3-bb5d-5fc08dfb6cc3 '
         }],
        args=[
            arg('--instance-ids',
                dest='INSTANCE_ID',
                help='Instance ID of the DCS instance')
        ])
    def stop_instance():
        OtcConfig.DCS_ACTION = "stop"
        REQ_UPDATE_DCS = utils_templates.create_request("update_instance")
        #print (REQ_UPDATE_DCS)

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/instances/status"
        url = url.replace('iam', 'dcs')
        #print (url)
        ret = utils_http.put(url, REQ_UPDATE_DCS)

        #print (ret)

        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Start instance",
        examples=
        [{'Start instance":"otc dcs start_instance'},
         {
             'Start a specific DCS instance: otc dcs start_instance --instance-ids 097da903-ab95-44f3-bb5d-5fc08dfb6cc3 '
         }],
        args=[
            arg('--instance-ids',
                dest='INSTANCE_ID',
                help='Instance ID of the DCS instance')
        ])
    def start_instance():
        OtcConfig.DCS_ACTION = "start"
        REQ_UPDATE_DCS = utils_templates.create_request("update_instance")
        #print (REQ_UPDATE_DCS)

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/instances/status"
        url = url.replace('iam', 'dcs')
        #print (url)
        ret = utils_http.put(url, REQ_UPDATE_DCS)

        print(ret)

        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Restart instance",
        examples=
        [{'Restart instance":"otc dcs restart_instance'},
         {
             'Restart a specific DCS instance: otc dcs restart_instance --instance-ids 097da903-ab95-44f3-bb5d-5fc08dfb6cc3 '
         }],
        args=[
            arg('--instance-ids',
                dest='INSTANCE_ID',
                help='Instance ID of the DCS instance')
        ])
    def restart_instance():
        OtcConfig.DCS_ACTION = "restart"
        REQ_UPDATE_DCS = utils_templates.create_request("update_instance")
        #print (REQ_UPDATE_DCS)

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/instances/status"
        url = url.replace('iam', 'dcs')
        #print (url)
        ret = utils_http.put(url, REQ_UPDATE_DCS)

        #print (ret)

        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="List Backups",
        examples=
        [{'List backups":"otc dcs list_backups'},
         {
             'List the backups for a specific DCS instance: otc dcs list_backups --instance-ids 097da903-ab95-44f3-bb5d-5fc08dfb6cc3 '
         }],
        args=[
            arg('--instance-ids',
                dest='INSTANCE_ID',
                help='Instance ID of the DCS instance')
        ])
    def list_backups():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/instances/" + OtcConfig.INSTANCE_ID + '/backups?start=1&limit=10&beginTime=&endTime='
        url = url.replace('iam', 'dcs')
        #print (url)
        ret = utils_http.get(url)

        #print (ret)

        dcs.otcOutputHandler().print_output(ret,
                                            mainkey="backup_record_response",
                                            listkey={
                                                "status", "remark", "period",
                                                "progress", "size",
                                                "backup_id", "created_at",
                                                "updated_at", "backup_type",
                                                "backup_name", "error_code"
                                            })

        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe quotas",
             examples=[{'Describe DCS quotas":"otc dcs describe-quotas'}],
             args=[])
    def describe_quotas():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/quota"
        url = url.replace('iam', 'dcs')
        #print (url)
        ret = utils_http.get(url)

        #print (ret)
        dcs.otcOutputHandler().print_output(ret, mainkey="")

        return ret

    @staticmethod
    def convertAZnameToId():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + "availableZones"
        url = url.replace('iam', 'dcs')
        JSON = utils_http.get(url)
        parsed = json.loads(JSON)
        azs = parsed["available_zones"]
        ret = None
        for az in azs:
            if az.get("name") == OtcConfig.AZ:
                ret = az["id"]
        OtcConfig.AZID = ret

        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="List availability zones",
             examples=[{'Describe DCS quotas":"otc dcs describe-quotas'}],
             args=[])
    def describe_azs():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + "availableZones"
        url = url.replace('iam', 'dcs')
        #print (url)
        ret = utils_http.get(url)

        #print (ret)

        dcs.otcOutputHandler().print_output(ret, mainkey="")

        return ret
Exemple #8
0
class elb(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

    @staticmethod
    def attach_load_balancers():
        pass

    @staticmethod
    def create_launch_configuration():
        raise RuntimeError("NOT IMPLEMENTED!")

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete loadbalancers",
             args=[
                 arg('--load-balancer-name',
                     dest='LOADBALANCER_NAME',
                     help='Loadbalancer name of the VM'),
                 arg('--load-balancer-id',
                     dest='LOADBALANCER_ID',
                     help='Loadbalancer Id of the VM')
             ])
    def delete_load_balancers():
        if not (OtcConfig.LOADBALANCER_NAME is None):
            elb.convertELBNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/loadbalancers" + "/" + OtcConfig.LOADBALANCER_ID

        ret = utils_http.delete(url)
        print(ret)
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe listeners",
             args=[
                 arg('--load-balancer-name',
                     dest='LOADBALANCER_NAME',
                     help='Loadbalancer name of the VM'),
                 arg('--load-balancer-id',
                     dest='LOADBALANCER_ID',
                     help='Loadbalancer Id of the VM')
             ])
    def describe_listeners():
        if not (OtcConfig.LOADBALANCER_NAME is None):
            elb.convertELBNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/listeners" + "?loadbalancer_id=" + OtcConfig.LOADBALANCER_ID
        ret = utils_http.get(url)
        #mod =  ret.replace("[","").replace("]","")
        print(json.dumps(json.loads(ret), indent=4, sort_keys=True))
        #elb.otcOutputHandler().print_output(ret,mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe listeners",
             args=[
                 arg('--load-balancer-name',
                     dest='LOADBALANCER_NAME',
                     help='Loadbalancer name of the VM'),
                 arg('--load-balancer-id',
                     dest='LOADBALANCER_ID',
                     help='Loadbalancer Id of the VM')
             ])
    def describe_members():
        if not (OtcConfig.LISTENER_NAME is None):
            elb.convertLISTENERNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/listeners/" + OtcConfig.LISTENER_ID + "/members"

        ret = utils_http.get(url)
        mod = "{ \"members\": " + ret + " }"

        elb.otcOutputHandler().print_output(mod,
                                            mainkey="members",
                                            listkey={
                                                "server_address", "server_id",
                                                "server_name", "update_time",
                                                "create_time", "id", "name",
                                                "status", "health_status",
                                                "address"
                                            })
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe health check",
             args=[
                 arg('--healthcheck-id',
                     dest='HEALTHCHECK_ID',
                     help='healthcheck-id'),
                 arg('--load-balancer-name',
                     dest='LOADBALANCER_NAME',
                     help='Loadbalancer name of the VM'),
                 arg('--load-balancer-id',
                     dest='LOADBALANCER_ID',
                     help='Loadbalancer Id of the VM')
             ])
    def describe_health_check():
        if not (OtcConfig.LOADBALANCER_NAME is None):
            elb.convertELBNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/healthcheck/" + OtcConfig.HEALTHCHECK_ID

        ret = utils_http.get(url)

        elb.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe health check",
             args=[
                 arg('--load-balancer-name',
                     dest='LOADBALANCER_NAME',
                     help='Loadbalancer name of the VM'),
                 arg('--load-balancer-id',
                     dest='LOADBALANCER_ID',
                     help='Loadbalancer Id of the VM')
             ])
    def describe_load_balancers():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/loadbalancers"
        if not (OtcConfig.LOADBALANCER_NAME is None):
            elb.convertELBNameToId()

        if OtcConfig.LOADBALANCER_ID:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/loadbalancers" + "/" + OtcConfig.LOADBALANCER_ID
            ret = utils_http.get(url)
            elb.otcOutputHandler().print_output(ret, mainkey="")
        else:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/loadbalancers"
            ret = utils_http.get(url)
            elb.otcOutputHandler().print_output(
                ret,
                mainkey="loadbalancers",
                listkey={
                    "vip_address", "update_time", "create_time", "id", "name",
                    "status", "bandwidth", "admin_state_up", "type",
                    "description"
                })

        return ret

    @staticmethod
    def convertELBNameToId():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/loadbalancers"
        JSON = utils_http.get(url)
        parsed = json.loads(JSON)
        loadbalancers = parsed["loadbalancers"]
        ret = None
        for loadbalancer in loadbalancers:
            if loadbalancer.get(
                    "name"
            ) == OtcConfig.LOADBALANCER_NAME:  # and ( loadbalancer.get("vpc_id") == OtcConfig.VPCID or OtcConfig.VPCID is None ) :
                OtcConfig.LOADBALANCER_ID = loadbalancer["id"]
                ret = OtcConfig.LOADBALANCER_ID
        return ret

    @staticmethod
    def convertLISTENERNameToId():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/listeners"
        JSON = utils_http.get(url)

        parsed = json.loads(JSON)
        listeners = parsed
        ret = None
        for listener in listeners:
            if listener.get(
                    "name"
            ) == OtcConfig.LISTENER_NAME:  # and ( loadbalancer.get("vpc_id") == OtcConfig.VPCID or OtcConfig.VPCID is None ) :
                OtcConfig.LISTENER_ID = listener["id"]
                ret = OtcConfig.LISTENER_ID
        return ret

    @staticmethod
    def convertLISTENERIdToHealthCheckId():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/listeners/" + OtcConfig.LISTENER_ID

        JSON = utils_http.get(url)
        parsed = json.loads(JSON)
        OtcConfig.HEALTHCHECK_ID = parsed["healthcheck_id"]
        ret = OtcConfig.HEALTHCHECK_ID
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Create load balancers",
        args=[
            arg('--vpc-name',
                dest='VPCNAME',
                help='Name of the VPC reference will use during VM creation'),
            arg('--vpc-id',
                dest='VPCID',
                help='Id of the VPC will use during VM creation'),
            arg('--description',
                dest='DESCRIPTION',
                help='Description definition ( eg: backups)'),
            arg('--bandwidth', dest='BANDWIDTH', help='bandwidth'),
            arg('--healthcheck-id',
                dest='HEALTHCHECK_ID',
                help='healthcheck-id'),
            arg('--load-balancer-name',
                dest='LOADBALANCER_NAME',
                help='Loadbalancer name of the VM')
        ])
    def create_load_balancers():
        if not (OtcConfig.LOADBALANCER_NAME is None):
            elb.convertELBNameToId()
        if not (OtcConfig.VPCNAME is None):
            getplugin("ecs").convertVPCNameToId()
        REQ_CREATE_ELB = utils_templates.create_request("create_loadbalancer")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/loadbalancers"
        ret = utils_http.post(url, REQ_CREATE_ELB)

        maindata = json.loads(ret)
        if "code" in maindata:
            print("Can not create:" + maindata["message"])
            os._exit(1)
        print("created")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Create listener",
        args=[
            arg('--listener-name',
                dest='LISTENER_NAME',
                help='Listener name of the VM'),
            arg('--listener-description',
                dest='LISTENER_DESCRIPTION',
                help='listener-description'),
            arg('--listener-port', dest='LISTENER_PORT', help='listener-port'),
            arg('--backend-port', dest='BACKEND_PORT', help='backend-port'),
            arg('--lb-algorithm', dest='LB_ALGORITHM', help='lb-algorithm'),
            arg('--protocol',
                dest='PROTOCOL',
                help='Protocol of the specific security group rule'),
            arg('--portmin',
                dest='PORTMIN',
                help='Lower por of the specific security group rule'),
            arg('--listener-description',
                dest='LISTENER_DESCRIPTION',
                help='listener-description'),
            arg('--session-sticky',
                dest='SESSION_STICKY',
                help=
                'Specifies whether to enable the session persistence function.The value is true or false. The session persistence function is enabled when the value is true, and is disabled when the value is false.'
                ),
            arg('--sticky-session-type',
                dest='STICKY_SESSION_TYPE',
                help=
                'Specifies the cookie processing method. The value is insert.insert indicates that the cookie is inserted by the load balancer. This parameter is valid when protocol is set to HTTP, and session_sticky to true. The default value is insert. This parameter is invalid when protocol is set to TCP. That means the parameter is empty.'
                ),
            arg('--cookie-timeout',
                dest='COOKIE_TIMEOUT',
                help=
                'Specifies the cookie timeout period (s).The value ranges from 1 to 86,400. This parameter is valid when protocol is set to HTTP, session_sticky to true, and sticky_session_type to insert. This parameter is invalid when protocol is set to TCP.'
                )
        ])
    def create_listener():

        if not (OtcConfig.LOADBALANCER_NAME is None):
            elb.convertELBNameToId()
        if not (OtcConfig.VPCNAME is None):
            getplugin("ecs").convertVPCNameToId()

        REQ_CREATE_LISTENER = utils_templates.create_request("create_listener")
        print(REQ_CREATE_LISTENER)
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/listeners"
        ret = utils_http.post(url, REQ_CREATE_LISTENER)
        maindata = json.loads(ret)
        if "code" in maindata:
            print("Can not create:" + maindata["message"])
            os._exit(1)
        elb.otcOutputHandler().print_output(ret, mainkey="")
        print(ret)
        #ecs.otcOutputHandler().print_output(ret, mainkey="loadbalancer")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe quotas",
             examples=[],
             args=[])
    def describe_quotas():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/quotas"
        ret = utils_http.get(url)
        print(ret)
        elb.otcOutputHandler().print_output(ret, mainkey="")
        return ret

#     @staticmethod
#     def describe_members():
#         if not (OtcConfig.LISTENER_NAME is None):
#             elb.convertLISTENERNameToId()
#
#         url = "https://" + OtcConfig.DEFAULT_HOST+ "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/listeners/" + OtcConfig.LISTENER_ID + "/members"
#
#         ret = utils_http.get(url)
#         mod =  "{ \"members\": " + ret + " }"
#
#
#         elb.otcOutputHandler().print_output(mod, mainkey="members", listkey={"server_address","server_id","server_name","update_time","create_time","id","name","status","health_status","address" } )
#         return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Create backend member",
        examples=[],
        args=[
            arg('--instance-name',
                dest='INSTANCE_NAME',
                help='Instance name of the VM'),
            arg('--listener-name',
                dest='LISTENER_NAME',
                help='Listener name of the VM'),
            arg('--address',
                dest='ADDRESS',
                help='Specifies the private IP address of the backend member')
        ])
    def create_backend_member():
        if not (OtcConfig.LISTENER_NAME is None):
            elb.convertLISTENERNameToId()
        if not OtcConfig.INSTANCE_NAME is None:
            getplugin("ecs").convertINSTANCENameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/listeners/" + OtcConfig.LISTENER_ID + "/members"
        REQ_CREATE_BACKEND_MEMBER = utils_templates.create_request(
            "add_backend_member")
        ret = utils_http.post(url, REQ_CREATE_BACKEND_MEMBER)
        print(ret)
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete backend member",
             examples=[],
             args=[
                 arg('--instance-name',
                     dest='INSTANCE_NAME',
                     help='Instance name of the VM'),
                 arg('--listener-name',
                     dest='LISTENER_NAME',
                     help='Listener name of the VM')
             ])
    def delete_backend_member():
        if not (OtcConfig.LISTENER_NAME is None):
            elb.convertLISTENERNameToId()
        if not OtcConfig.INSTANCE_NAME is None:
            getplugin("ecs").convertINSTANCENameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/listeners/" + OtcConfig.LISTENER_ID + "/members/action"

        REQ_DELETE_BACKEND_MEMBER = utils_templates.create_request(
            "delete_backend_member")

        ret = utils_http.post(url, REQ_DELETE_BACKEND_MEMBER)

        print(ret)
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Create health check",
        examples=[],
        args=[
            arg('--listener-name',
                dest='LISTENER_NAME',
                help='Listener name of the VM'),
            arg('--healthcheck-connect-port',
                dest='HEALTHCHECK_CONNECT_PORT',
                help='Specifies the port for health check'),
            arg('--healthcheck-interval',
                dest='HEALTHCHECK_INTERVAL',
                help=
                'Specifies the maximum interval for health check.The value ranges from 1 to 5(s)'
                ),
            arg('--healthcheck-protocol',
                dest='HEALTHCHECK_PROTOCOL',
                help=
                'Specifies the health check protocol.The value can be HTTP or TCP (case-insensitive)'
                ),
            arg('--healthcheck-timeout',
                dest='HEALTHCHECK_TIMEOUT',
                help=
                'Specifies the maximum timeout duration for health check. The value ranges from 1 to 50 (s)'
                ),
            arg('--healthcheck-uri',
                dest='HEALTHCHECK_URI',
                help=
                'Specifies the URI for health check. The value is a string of 1 to 80 characters that contain only letters'
                ),
            arg('--healthy-threahold',
                dest='HEALTHY_THREAHOLD',
                help=
                'Specifies the number of consecutive successful health checks for the health check result changing from fail to success. The value ranges from 1 to 10.'
                ),
            arg('--unhealthy-threshold',
                dest='UNHEALTHY_THRESHOLD',
                help=
                'Specifies the number of consecutive successful health checks for the health check result changing from success to fail. The value ranges from 1 to 10.'
                )
        ])
    def create_health_check():
        if not (OtcConfig.LISTENER_NAME is None):
            elb.convertLISTENERNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/healthcheck"

        REQ_CREATE_HEALTH_CHECK = utils_templates.create_request(
            "creating_health_check_task")

        ret = utils_http.post(url, REQ_CREATE_HEALTH_CHECK)
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Create health check",
        examples=[],
        args=[
            arg('--listener-name',
                dest='LISTENER_NAME',
                help='Listener name of the VM'),
            arg('--healthcheck-connect-port',
                dest='HEALTHCHECK_CONNECT_PORT',
                help='Specifies the port for health check'),
            arg('--healthcheck-interval',
                dest='HEALTHCHECK_INTERVAL',
                help=
                'Specifies the maximum interval for health check.The value ranges from 1 to 5(s)'
                ),
            arg('--healthcheck-protocol',
                dest='HEALTHCHECK_PROTOCOL',
                help=
                'Specifies the health check protocol.The value can be HTTP or TCP (case-insensitive)'
                ),
            arg('--healthcheck-timeout',
                dest='HEALTHCHECK_TIMEOUT',
                help=
                'Specifies the maximum timeout duration for health check. The value ranges from 1 to 50 (s)'
                ),
            arg('--healthcheck-uri',
                dest='HEALTHCHECK_URI',
                help=
                'Specifies the URI for health check. The value is a string of 1 to 80 characters that contain only letters'
                ),
            arg('--healthy-threahold',
                dest='HEALTHY_THREAHOLD',
                help=
                'Specifies the number of consecutive successful health checks for the health check result changing from fail to success. The value ranges from 1 to 10.'
                ),
            arg('--unhealthy-threshold',
                dest='UNHEALTHY_THRESHOLD',
                help=
                'Specifies the number of consecutive successful health checks for the health check result changing from success to fail. The value ranges from 1 to 10.'
                )
        ])
    def modify_health_check():
        if not (OtcConfig.LOADBALANCER_NAME is None):
            elb.convertELBNameToId()
        if not (OtcConfig.HEALTHCHECK_ID is None):
            elb.convertLISTENERIdToHealthCheckId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/healthcheck/" + OtcConfig.HEALTHCHECK_ID

        REQ_MODIFY_HEALTH_CHECK = utils_templates.create_request(
            "modify_information_health_check_task")

        ret = utils_http.put(url, REQ_MODIFY_HEALTH_CHECK)
        print(ret)
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Modify load balancers",
        args=[
            arg('--vpc-name',
                dest='VPCNAME',
                help='Name of the VPC reference will use during VM creation'),
            arg('--vpc-id',
                dest='VPCID',
                help='Id of the VPC will use during VM creation'),
            arg('--bandwidth', dest='BANDWIDTH', help='bandwidth'),
            arg('--listener-description',
                dest='LISTENER_DESCRIPTION',
                help='listener-description'),
            arg('--load-balancer-name',
                dest='LOADBALANCER_NAME',
                help='Loadbalancer name of the VM')
        ])
    def modify_load_balancers():
        if not (OtcConfig.LOADBALANCER_NAME is None):
            elb.convertELBNameToId()
        if not (OtcConfig.VPCNAME is None):
            getplugin("ecs").convertVPCNameToId()

        REQ_MODIFY_ELB = utils_templates.create_request("modify_load_balancer")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/loadbalancers/" + OtcConfig.LOADBALANCER_ID
        print(REQ_MODIFY_ELB)
        ret = utils_http.put(url, REQ_MODIFY_ELB)
        print(ret)
        maindata = json.loads(ret)
        if "code" in maindata:
            print("Can not modify:" + maindata["message"])
            os._exit(1)
        print("created")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Modify listener",
             args=[
                 arg('--listener-name',
                     dest='LISTENER_NAME',
                     help='Listener name of the VM'),
                 arg('--listener-description',
                     dest='LISTENER_DESCRIPTION',
                     help='listener-description'),
                 arg('--listener-port',
                     dest='LISTENER_PORT',
                     help='listener-port'),
                 arg('--backend-port',
                     dest='BACKEND_PORT',
                     help='backend-port'),
                 arg('--lb-algorithm',
                     dest='LB_ALGORITHM',
                     help='lb-algorithm')
             ])
    def modify_listeners():
        #if not (OtcConfig.LOADBALANCER_NAME is None):
        #    elb.convertELBNameToId()
        #if not (OtcConfig.VPCNAME is None):
        #    getplugin("ecs").convertVPCNameToId()
        if not (OtcConfig.LISTENER_NAME is None):
            elb.convertLISTENERNameToId()

        #REQ_CREATE_LISTENER = "{ \"name\":\"listener1\", \"description\":\"\", \"loadbalancer_id\":\"0b07acf06d243925bc24a0ac7445267a\", \"protocol\":\"HTTP\", \"port\":88, \"backend_protocol\":\"HTTP\", \"backend_port\":80, \"lb_algorithm\":\"roundrobin\", \"session_sticky\":true, \"sticky_session_type\":\"insert\", \"cookie_timeout\":100 }"
        REQ_MODIFY_LISTENER = utils_templates.create_request(
            "modify_information_listener")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/listeners/" + OtcConfig.LISTENER_ID
        ret = utils_http.put(url, REQ_MODIFY_LISTENER)
        print(ret)
        maindata = json.loads(ret)
        if "code" in maindata:
            print("Can not create:" + maindata["message"])
            os._exit(1)

        print(ret)
        #ecs.otcOutputHandler().print_output(ret, mainkey="loadbalancer")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete listener",
             args=[
                 arg('--listener-name',
                     dest='LISTENER_NAME',
                     help='Listener name of the VM')
             ])
    def delete_listener():
        if not (OtcConfig.LISTENER_NAME is None):
            elb.convertLISTENERNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/listeners/" + OtcConfig.LISTENER_ID
        ret = utils_http.delete(url)

        print(ret)
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete health check",
             args=[
                 arg('--healthcheck-id',
                     dest='HEALTHCHECK_ID',
                     help='healthcheck-id'),
                 arg('--load-balancer-name',
                     dest='LOADBALANCER_NAME',
                     help='Loadbalancer name of the VM'),
                 arg('--load-balancer-id',
                     dest='LOADBALANCER_ID',
                     help='Loadbalancer Id of the VM')
             ])
    def delete_health_check():
        if not (OtcConfig.LOADBALANCER_NAME is None):
            elb.convertELBNameToId()
        if not (OtcConfig.HEALTHCHECK_ID is None):
            elb.convertLISTENERIdToHealthCheckId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.0/" + OtcConfig.PROJECT_ID + "/elbaas/healthcheck/" + OtcConfig.HEALTHCHECK_ID
        ret = utils_http.delete(url)

        print(ret)
        return ret
Exemple #9
0
class cce(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

#ret = utils_templates.create_request("template_name")
#return ret

    @staticmethod
    def convertClusterNameToId():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/clusters"
        JSON = utils_http.get(url)
        parsed = json.loads(JSON)
        clusters = parsed
        ret = None
        for cluster in clusters:
            if cluster.get("metadata").get("name") == OtcConfig.CLUSTER:
                ret = cluster.get("metadata").get("uuid")
        OtcConfig.CLUSTER_ID = ret

    @staticmethod
    @otcfunc(plugin_name=__name__, desc="List clusters", examples=[], args=[])
    def list_clusters():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/clusters"
        ret = utils_http.get(url)
        #print (ret)
        cce.otcOutputHandler().print_output(
            json.loads(ret),
            subkey="metadata",
            listkey={"name", "uuid", "createAt"})
        #cce.otcOutputHandler().print_output(json.loads(ret),mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe clusters",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster')
             ])
    def describe_clusters():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        if OtcConfig.CLUSTER_ID:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/clusters/" + OtcConfig.CLUSTER_ID
            ret = utils_http.get(url)
            cce.otcOutputHandler().print_output(ret, mainkey="")
        else:
            return cce.list_clusters()

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="List container intaces",
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--instance-name',
                     dest='INSTANCE_NAME',
                     help='Instance name of the VM')
             ])
    def list_container_instances():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        if OtcConfig.INSTANCE_NAME:
            cce.convertINSTANCENameToId()

        if OtcConfig.INSTANCE_ID:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/clusters/" + OtcConfig.CLUSTER_ID + "/hosts"
            ret = utils_http.get(url)
            cce.otcOutputHandler().print_output(ret, mainkey="")
        else:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/clusters/" + OtcConfig.CLUSTER_ID + "/hosts/" + OtcConfig.INSTANCE_ID
            ret = utils_http.get(url)
            cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="List services",
        examples=[{
            'Registers image":"otc ims register_image --image-url testuser:c.qcow2'
        }],
        args=[
            arg('--cluster-name', dest='CLUSTER', help='Name of the cluster')
        ])
    def list_services():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/services"
        ret = utils_http.get(url)

        print(ret)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Create services",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--service-name',
                     dest='SERVICE_NAME',
                     help='CCE Service name'),
                 arg('--portmin',
                     dest='PORTMIN',
                     help='Lower por of the specific security group rule'),
                 arg('--portmax',
                     dest='PORTMAX',
                     help='Upper  port of the specific security group rule')
             ])
    def create_service():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/services"
        req = utils_templates.create_request("cce_create_service")
        ret = utils_http.post(url, req)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Modify services",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--service-name',
                     dest='SERVICE_NAME',
                     help='CCE Service name'),
                 arg('--portmin',
                     dest='PORTMIN',
                     help='Lower por of the specific security group rule'),
                 arg('--portmax',
                     dest='PORTMAX',
                     help='Upper  port of the specific security group rule')
             ])
    def modify_service():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/services/" + OtcConfig.SERVICE_NAME
        req = utils_templates.create_request("cce_create_service")
        ret = utils_http.put(url, req)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete services",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster')
             ])
    def delete_service():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/services/" + OtcConfig.SERVICE_NAME
        ret = utils_http.delete(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Create namespace",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE', help='CES/CCE Namespace')
             ])
    def create_namespace():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces"
        req = utils_templates.create_request("create_namespace")
        #print req
        #print OtcConfig.NAMESPACE
        ret = utils_http.post(url, req)
        #print (ret)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Rename namespace",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('',
                     dest='SUBCOM_P1',
                     help='[optional Source/Target OBS directory]',
                     metavar="Source/Target DIR")
             ])
    def rename_namespace():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces"
        req = utils_templates.create_request("cce_rename_namespace")
        ret = utils_http.post(url, req)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe namespace",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
             ])
    def describe_namespaces():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        if OtcConfig.NAMESPACE:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE
        else:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces"
        ret = utils_http.get(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete namespace",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
             ])
    def delete_namespace():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE
        ret = utils_http.delete(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe pods",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
             ])
    def describe_pods():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        if OtcConfig.NAMESPACE:
            if OtcConfig.POD:
                url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/pods/" + OtcConfig.POD
            else:
                url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/pods"
        else:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/pods"
        ret = utils_http.get(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Create pod",
        examples=[],
        args=[
            arg('--cluster-name', dest='CLUSTER', help='Name of the cluster'),
            arg('--namespace', dest='NAMESPACE', help='CES/CCE Namespace'),
            arg('--pod', dest='POD', help='CCE POD'),
            arg('--container-name',
                dest='CONTAINER_NAME',
                help='CCE POD container name'),
            arg('--image-name',
                dest='IMAGENAME',
                help='Name of the image reference will used during VM creation'
                )
        ])
    def create_pod():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/pods"
        req = utils_templates.create_request("cce_create_pod")
        print(req)
        ret = utils_http.post(url, req)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete pod",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('--pod', dest='POD', help='CCE POD')
             ])
    def delete_pod():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/pods/" + OtcConfig.POD

        ret = utils_http.delete(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Create pod template",
        examples=[],
        args=[
            arg('--cluster-name', dest='CLUSTER', help='Name of the cluster'),
            arg('--namespace', dest='NAMESPACE', help='CES/CCE Namespace'),
            arg('--pod', dest='POD', help='CCE POD'),
            arg('--container-name',
                dest='CONTAINER_NAME',
                help='CCE POD container name'),
            arg('--image-name',
                dest='IMAGENAME',
                help='Name of the image reference will used during VM creation'
                ),
            arg('--portmin',
                dest='PORTMIN',
                help='Lower por of the specific security group rule')
        ])
    def create_pod_template():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/podtemplates"
        req = utils_templates.create_request("cce_create_pod_template")
        print(req)
        ret = utils_http.post(url, req)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe pod templates",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
             ])
    def describe_pod_templates():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        if OtcConfig.POD:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/podtemplates/" + OtcConfig.POD
        else:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/podtemplates"

        ret = utils_http.get(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Delete pod templates",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('--pod', dest='POD', help='CCE POD')
             ])
    def delete_pod_templates():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        if OtcConfig.POD:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/podtemplates/" + OtcConfig.POD

        ret = utils_http.delete(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe endpoints",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('--endpoint-name',
                     dest='ENDPOINT_NAME',
                     help='CCE endpoint name')
             ])
    def describe_endpoints():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        if OtcConfig.NAMESPACE:
            if OtcConfig.ENDPOINT_NAME:
                url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/endpoints/" + OtcConfig.ENDPOINT_NAME
            else:
                url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/endpoints"
        else:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/endpoints"

        ret = utils_http.get(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Create endpoints",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('--endpoint-name',
                     dest='ENDPOINT_NAME',
                     help='CCE endpoint name'),
                 arg('--public-ip',
                     dest='PUBLICIP',
                     help='Public IP for association'),
                 arg('--portmin',
                     dest='PORTMIN',
                     help='Lower por of the specific security group rule')
             ])
    def create_endpoint():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/endpoints"
        req = utils_templates.create_request("cce_create_endpoint")
        print(req)
        ret = utils_http.post(url, req)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe endpoints",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('--endpoint-name',
                     dest='ENDPOINT_NAME',
                     help='CCE endpoint name')
             ])
    def delete_endpoint():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/endpoints/" + OtcConfig.ENDPOINT_NAME

        ret = utils_http.delete(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe secrets",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('--secret-name',
                     dest='SECRET_NAME',
                     help='CCE secret name')
             ])
    def describe_secrets():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        if OtcConfig.SECRET_NAME:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/secrets/" + OtcConfig.SECRET_NAME
        else:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/secrets"

        ret = utils_http.get(url)
        print(ret)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe secrets",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('--secret-name',
                     dest='SECRET_NAME',
                     help='CCE secret name'),
                 arg('--key-name',
                     dest='KEYNAME',
                     help='SSH key name| S3 Object key'),
                 arg('--admin-pass',
                     dest='ADMINPASS',
                     help='Admin password of the started VM')
             ])
    def create_secret():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/secrets"
        req = utils_templates.create_request("cce_create_secret")
        #print req
        ret = utils_http.post(url, req)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe secrets",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('--secret-name',
                     dest='SECRET_NAME',
                     help='CCE secret name')
             ])
    def delete_secret():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/secrets/" + OtcConfig.SECRET_NAME

        ret = utils_http.delete(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe secrets",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('--rc-name',
                     dest='RC_NAME',
                     help='CCE replication controller name')
             ])
    def describe_rc():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        if OtcConfig.NAMESPACE:
            if OtcConfig.RC_NAME:
                url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/replicationcontrollers/" + OtcConfig.RC_NAME
            else:
                url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/replicationcontrollers"
        else:
            url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/replicationcontrollers"

        ret = utils_http.get(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Describe secrets",
        examples=[],
        args=[
            arg('--cluster-name', dest='CLUSTER', help='Name of the cluster'),
            arg('--namespace', dest='NAMESPACE', help='CES/CCE Namespace'),
            arg('--rc-name',
                dest='RC_NAME',
                help='CCE replication controller name'),
            arg('--secret-name', dest='SECRET_NAME', help='CCE secret name'),
            arg('--container-name',
                dest='CONTAINER_NAME',
                help='CCE POD container name'),
            arg('--image-name',
                dest='IMAGENAME',
                help='Name of the image reference will used during VM creation'
                ),
            arg('--portmin',
                dest='PORTMIN',
                help='Lower por of the specific security group rule'),
            arg('--image-ref', dest='IMAGE_REF', help='image-ref')
        ])
    def create_rc():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/replicationcontrollers"
        req = utils_templates.create_request("cce_create_rc")
        #print req
        ret = utils_http.post(url, req)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Describe secrets",
        examples=[],
        args=[
            arg('--cluster-name', dest='CLUSTER', help='Name of the cluster'),
            arg('--namespace', dest='NAMESPACE', help='CES/CCE Namespace'),
            arg('--rc-name',
                dest='RC_NAME',
                help='CCE replication controller name'),
            arg('--secret-name', dest='SECRET_NAME', help='CCE secret name'),
            arg('--container-name',
                dest='CONTAINER_NAME',
                help='CCE POD container name'),
            arg('--image-name',
                dest='IMAGENAME',
                help='Name of the image reference will used during VM creation'
                ),
            arg('--portmin',
                dest='PORTMIN',
                help='Lower por of the specific security group rule'),
            arg('--image-ref', dest='IMAGE_REF', help='image-ref')
        ])
    def modify_rc():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()

        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/replicationcontrollers/" + OtcConfig.RC_NAME
        req = utils_templates.create_request("cce_create_rc")
        #print req
        ret = utils_http.put(url, req)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="Describe secrets",
             examples=[],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='Name of the cluster'),
                 arg('--namespace', dest='NAMESPACE',
                     help='CES/CCE Namespace'),
                 arg('--rc-name',
                     dest='RC_NAME',
                     help='CCE replication controller name')
             ])
    def delete_rc():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/replicationcontrollers/" + OtcConfig.RC_NAME

        ret = utils_http.delete(url)
        cce.otcOutputHandler().print_output(ret, mainkey="")
        return ret
Exemple #10
0
class ims(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

    @staticmethod
    def update_image_metadata():
        if not (OtcConfig.IMAGENAME is None):
            getplugin("ecs").convertIMAGENameToId()
        ims.create_image_metadata()

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Creates image metadata",
        examples=[{
            'Creates image metadata":"otc ims create_image_metadata  --image-name testimagenzs --os-version "Ubuntu 14.04 server 64bit" --container-format bare --disk-format raw --min-disk 1 --min-ram 1024 --tags "test,image" --visibility private --protected false'
        }],
        args=[
            arg('--os-version',
                dest='OS_VERSION',
                metavar='__os_version',
                default='Other Linux(64 bit)',
                help=
                'Specifies the image OS version, if this  is not specified, the value will be set to Other Linux(64 bit)'
                ),
            arg('--container-format',
                dest='CONTAINTER_FORMAT',
                metavar='container_format',
                default=None,
                help='Container format used during image creation'),
            arg('--disk_format',
                dest='DISK_FORMAT',
                metavar='<disk_format>',
                default=None,
                help='Disk format used during image creation'),
            arg('--min_disk',
                dest='MIN_DISK',
                metavar='<min_disk>',
                default=None,
                help='Min disk used during image creation'),
            arg('--min_ram',
                dest='MIN_RAM',
                metavar='<min_ram>',
                default=None,
                help='Min ram used during image creation'),
            arg('--image-name',
                dest='IMAGENAME',
                metavar='<image-name>',
                default=None,
                help='description of the avaliable clusters'),
            arg('--tags',
                dest='TAG_LIST',
                metavar='<tags>',
                default=None,
                help='Tags of the image will used during Image creation'),
            arg('--visibility',
                dest='IMAGE_VISIBILITY',
                metavar='<visibility>',
                default=None,
                help='Image visibility used during image creation'),
            arg('--protected   ',
                dest='PROTECTED',
                metavar='<protected>',
                default=None,
                help='Protected status of  image used during VM creation')
        ])
    def create_image_metadata():

        # image id filled until now
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v2/images"
        REQ_CREATE_META_IMAGE = "{    \"__os_version\": \"" + OtcConfig.OS_VERSION + "\",\"container_format\": \"" + OtcConfig.CONTAINTER_FORMAT + "\",\"disk_format\": \"" + OtcConfig.DISK_FORMAT + "\",    \"min_disk\": " + OtcConfig.MIN_DISK + ",\"min_ram\": " + OtcConfig.MIN_RAM + ",\"name\": \"" + OtcConfig.IMAGENAME + "\",\"tags\": [\"" + OtcConfig.TAG_LIST + "\",\"image\"],\"visibility\": \"" + OtcConfig.IMAGE_VISIBILITY + "\",\"protected\": " + OtcConfig.PROTECTED + "}"
        ret = utils_http.post(url, REQ_CREATE_META_IMAGE)
        ims.otcOutputHandler().print_output(ret, mainkey="")

        OtcConfig.IMAGE_ID = json.loads(ret)["id"]

        if OtcConfig.IMAGE_ID is None:
            raise RuntimeError("Image not created! " + ret)

        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Registers image",
        examples=[{
            'Registers image":"otc ims register_image --image-url testuser:c.qcow2'
        }],
        args=[
            arg('--image-url',
                dest='IMAGE_URL',
                metavar='image_url',
                default=None,
                help='Url of the image used during Image creation'),
            arg('--image-id',
                dest='IMAGE_ID',
                metavar='image_id',
                default=None,
                help='Id of the image reference will use during VM creation'),
            arg('--image-name',
                dest='IMAGENAME',
                metavar='<image-name>',
                default=None,
                help='description of the avaliable clusters')
        ])
    def register_image():
        if not (OtcConfig.IMAGENAME is None):
            getplugin("ecs").convertIMAGENameToId()

        if OtcConfig.IMAGE_ID is None:
            # error handling
            raise RuntimeError("Please define image id!")

        # image id filled until now
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v2/images/" + OtcConfig.IMAGE_ID + "/file"
        REQ_REG_IMAGE = "{\"image_url\":\"" + OtcConfig.IMAGE_URL + "\" }"
        ret = utils_http.put(url, REQ_REG_IMAGE)
        if len(ret) != 0:
            print("Image registration error!" + ret)
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Gets image data",
        examples=[{
            'Gets image data":"otc ims get_image --image-url testuser:c.qcow2'
        }],
        args=[
            arg('--image-url',
                dest='IMAGE_URL',
                metavar='image_url',
                default=None,
                help='Url of the image used during Image creation'),
            arg('--image-id',
                dest='IMAGE_ID',
                metavar='image_id',
                default=None,
                help='Id of the image reference will use during VM creation'),
            arg('--image-name',
                dest='IMAGENAME',
                metavar='<image-name>',
                default=None,
                help='description of the avaliable clusters')
        ])
    def get_image():
        if not (OtcConfig.IMAGENAME is None):
            getplugin("ecs").convertIMAGENameToId()

        if OtcConfig.IMAGE_ID is None:
            # error handling
            raise RuntimeError("Please define image id!")

        # image id filled until now
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v2/images/" + OtcConfig.IMAGE_ID + "/file"
        REQ_REG_IMAGE = "{\"image_url\":\"" + OtcConfig.IMAGE_URL + "\" }"
        ret = utils_http.post(url, REQ_REG_IMAGE)
        if len(ret) != 0:
            print("Image registration error!" + ret)
        return ret

    @staticmethod
    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="Creates image",
        examples=[{
            'Creates image":"otc ims create_image --image-url testuser:c.qcow2 --image-name testimagenzs --os-version "Ubuntu 14.04 server 64bit" --container-format bare --disk-format raw --min-disk 1 --min-ram 1024 --tags "test,image" --visibility private --protected false'
        }],
        args=[
            arg('--os-version',
                dest='OS_VERSION',
                metavar='__os_version',
                default='Other Linux(64 bit)',
                help=
                'Specifies the image OS version, if this  is not specified, the value will be set to Other Linux(64 bit)'
                ),
            arg('--container-format',
                dest='CONTAINTER_FORMAT',
                metavar='container_format',
                default=None,
                help='Container format used during image creation'),
            arg('--disk_format',
                dest='DISK_FORMAT',
                metavar='<disk_format>',
                default=None,
                help='Disk format used during image creation'),
            arg('--min_disk',
                dest='MIN_DISK',
                metavar='<min_disk>',
                default=None,
                help='Min disk used during image creation'),
            arg('--min_ram',
                dest='MIN_RAM',
                metavar='<min_ram>',
                default=None,
                help='Min ram used during image creation'),
            arg('--image-name',
                dest='IMAGENAME',
                metavar='<image-name>',
                default=None,
                help='description of the avaliable clusters'),
            arg('--tags',
                dest='TAG_LIST',
                metavar='<tags>',
                default=None,
                help='Tags of the image will used during Image creation'),
            arg('--visibility',
                dest='IMAGE_VISIBILITY',
                metavar='<visibility>',
                default=None,
                help='Image visibility used during image creation'),
            arg('--protected   ',
                dest='PROTECTED',
                metavar='<protected>',
                default=None,
                help='Protected status of  image used during VM creation'),
            arg('--image-url',
                dest='IMAGE_URL',
                metavar='image_url',
                default=None,
                help='Url of the image used during Image creation')
        ])
    def create_image():
        ims.create_image_metadata()
        ret = ims.register_image()
        return ret
Exemple #11
0
class mrs(otcpluginbase):
    ar = {}

    @staticmethod
    def otcOutputHandler():
        return getplugin(OtcConfig.OUTPUT_FORMAT)

    def otctype(self):
        return "func"

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="description of the avaliable clusters",
             examples=[{
                 "List Clusters": "otc mrs describe_clusters"
             }, {
                 "Show Cluster Details":
                 "otc mrs describe_clusters mycluster"
             }],
             args=[
                 arg('--cluster-name',
                     dest='CLUSTER',
                     help='description of the avaliable clusters'),
                 arg('-cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='description of the avaliable clusters')
             ])
    def describe_clusters():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/bigdata/api/v1/clusters?pageSize=10&currentPage=1&clusterState=existing"

        if OtcConfig.CLUSTER_ID is None:
            ret = utils_http.get(url)
            print(url)
            print(ret)
            mrs.otcOutputHandler().print_output(ret,
                                                mainkey="clusters",
                                                listkey={"id", "name"})
        else:
            ret = utils_http.get(url + '/' + OtcConfig.INSTANCE_ID)
            maindata = json.loads(ret)
            if "itemNotFound" in maindata:
                raise RuntimeError("Not found!")
            mrs.otcOutputHandler().print_output(ret, mainkey="server")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="add new node(s) to cluster",
             examples=[{
                 "add node(s)":
                 "otc mrs add-node MYCLUSTER_ID NUM OF NODE"
             }],
             args=[
                 arg('-cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='id of the cluster')
             ])
    def add_nodes():
        REQ_ADD_NODE = utils_templates.create_request("add_node")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/cluster_infos/" + OtcConfig.CLUSTER_ID
        ret = utils_http.post(url, REQ_ADD_NODE)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="create hadoop cluster",
        args=[arg('--cluster-name', dest='CLUSTER', help='create cluster')])
    def create_cluster():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/run-job-flow"
        #vpc_id
        if not (OtcConfig.VPCNAME is None):
            getplugin("ecs").convertVPCNameToId()

        #network_id
        if not OtcConfig.SUBNETNAME is None:
            getplugin("ecs").convertSUBNETNameToId()

        REQ_CREATE_CLUSTER = utils_templates.create_request(
            "create_cluster_with_job")

        ret = utils_http.post(url, REQ_CREATE_CLUSTER)
        print REQ_CREATE_CLUSTER
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="description of the cluster",
             examples=[{
                 "List jobs": "otc mrs describe-cluster MYCLUSTER-ID"
             }],
             args=[
                 arg('-cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='id of the cluster')
             ])
    def describe_cluster():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/cluster_infos/" + OtcConfig.CLUSTER_ID
        ret = utils_http.get(url)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="delete specific cluster",
             examples=[{
                 "List jobs":
                 "otc mrs delete-cluster --cluster-id MYCLUSTER-ID"
             }],
             args=[
                 arg('-cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='id of the cluster')
             ])
    def delete_cluster():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/clusters/" + OtcConfig.CLUSTER_ID
        ret = utils_http.delete(url)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="add job to cluster",
             examples=[{
                 "add job": "otc mrs add-job !!!!!!!!!"
             }],
             args=[
                 arg('-cluster-id',
                     dest='CLUSTER_ID',
                     metavar='<cluster_id>',
                     default=None,
                     help='id of the cluster')
             ])
    def add_job():
        REQ_ADD_JOB = utils_templates.create_request("add_job")
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/jobs/submit-job"
        ret = utils_http.post(url, REQ_ADD_JOB)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")

    @staticmethod
    @otcfunc(plugin_name=__name__,
             desc="description of the avaliable jobs",
             examples=[{
                 "List jobs": "otc mrs describe-jobs"
             }, {
                 "Show Cluster Details": "otc mrs jobs of the cluster"
             }])
    def describe_jobs():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/job-exes"

        ret = utils_http.get(url)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="description of the job detail",
        examples=[{
            "List jobs":
            "otc mrs describe-job-detail -jobexecid JOB-EXEC-ID"
        }],
        args=[arg('-job-exec-id', dest='JOB_EXEC_ID', help='id of the job')])
    def describe_job_details():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/job-exes/" + OtcConfig.JOB_EXEC_ID
        ret = utils_http.get(url)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret

    @staticmethod
    @otcfunc(
        plugin_name=__name__,
        desc="delete the job ",
        examples=[{
            "List jobs": "otc mrs delete-job -jobexecid JOB-EXEC-ID"
        }],
        args=[arg('-job-exec-id', dest='JOB_EXEC_ID', help='id of the job')])
    def delete_job():
        url = "https://" + OtcConfig.DEFAULT_HOST + "/v1.1/" + OtcConfig.PROJECT_ID + "/job-executions/" + OtcConfig.JOB_EXEC_ID
        ret = utils_http.delete(url)
        print(url)
        print(ret)
        mrs.otcOutputHandler().print_output(ret, mainkey="")
        return ret