From 981e82187b4aa758e9493425f7e3362e4d7941d2 Mon Sep 17 00:00:00 2001 From: chenhanzhang Date: Wed, 25 Dec 2024 11:25:46 +0800 Subject: [PATCH] New Resource: alicloud_schedulerx_app_group; New Resource: alicloud_schedulerx_job; resource/alicloud_schedulerx_namespace: add new attribute namespace_uid. --- alicloud/connectivity/client.go | 27 +- alicloud/provider.go | 4 +- .../resource_alicloud_schedulerx_app_group.go | 322 ++++++ ...urce_alicloud_schedulerx_app_group_test.go | 113 ++ alicloud/resource_alicloud_schedulerx_job.go | 1014 +++++++++++++++++ .../resource_alicloud_schedulerx_job_test.go | 395 +++++++ .../resource_alicloud_schedulerx_namespace.go | 134 +-- ...urce_alicloud_schedulerx_namespace_test.go | 72 +- alicloud/service_alicloud_schedulerx_v2.go | 259 +++++ .../docs/r/schedulerx_app_group.html.markdown | 98 ++ website/docs/r/schedulerx_job.html.markdown | 223 ++++ .../docs/r/schedulerx_namespace.html.markdown | 53 +- 12 files changed, 2601 insertions(+), 113 deletions(-) create mode 100644 alicloud/resource_alicloud_schedulerx_app_group.go create mode 100644 alicloud/resource_alicloud_schedulerx_app_group_test.go create mode 100644 alicloud/resource_alicloud_schedulerx_job.go create mode 100644 alicloud/resource_alicloud_schedulerx_job_test.go create mode 100644 alicloud/service_alicloud_schedulerx_v2.go create mode 100644 website/docs/r/schedulerx_app_group.html.markdown create mode 100644 website/docs/r/schedulerx_job.html.markdown diff --git a/alicloud/connectivity/client.go b/alicloud/connectivity/client.go index 18f87a8d5d7f..a9c93dbbac41 100644 --- a/alicloud/connectivity/client.go +++ b/alicloud/connectivity/client.go @@ -2,7 +2,6 @@ package connectivity import ( "fmt" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "log" "net/http" "net/url" @@ -13,6 +12,8 @@ import ( "sync" "time" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + util "github.com/alibabacloud-go/tea-utils/service" ossclient "github.com/alibabacloud-go/alibabacloud-gateway-oss/client" @@ -5957,3 +5958,27 @@ func (client *AliyunClient) NewPaiClient() (*roa.Client, error) { } return conn, nil } +func (client *AliyunClient) NewSchedulerxClient() (*rpc.Client, error) { + productCode := "edasschedulerx" + endpoint := "" + if v, ok := client.config.Endpoints.Load(productCode); !ok || v.(string) == "" { + if err := client.loadEndpoint(productCode); err != nil { + endpoint = fmt.Sprintf("schedulerx.%s.aliyuncs.com", client.config.RegionId) + client.config.Endpoints.Store(productCode, endpoint) + log.Printf("[ERROR] loading %s endpoint got an error: %#v. Using the endpoint %s instead.", productCode, err, endpoint) + } + } + if v, ok := client.config.Endpoints.Load(productCode); ok && v.(string) != "" { + endpoint = v.(string) + } + if endpoint == "" { + return nil, fmt.Errorf("[ERROR] missing the product %s endpoint.", productCode) + } + sdkConfig := client.teaSdkConfig + sdkConfig.SetEndpoint(endpoint) + conn, err := rpc.NewClient(&sdkConfig) + if err != nil { + return nil, fmt.Errorf("unable to initialize the %s client: %#v", productCode, err) + } + return conn, nil +} diff --git a/alicloud/provider.go b/alicloud/provider.go index 1328d94f994d..cb383a36fb86 100644 --- a/alicloud/provider.go +++ b/alicloud/provider.go @@ -879,6 +879,8 @@ func Provider() terraform.ResourceProvider { "alicloud_cms_site_monitors": dataSourceAliCloudCloudMonitorServiceSiteMonitors(), }, ResourcesMap: map[string]*schema.Resource{ + "alicloud_schedulerx_app_group": resourceAliCloudSchedulerxAppGroup(), + "alicloud_schedulerx_job": resourceAliCloudSchedulerxJob(), "alicloud_express_connect_router_grant_association": resourceAliCloudExpressConnectRouterGrantAssociation(), "alicloud_live_caster": resourceAliCloudLiveCaster(), "alicloud_vpc_ipam_ipam_pool_allocation": resourceAliCloudVpcIpamIpamPoolAllocation(), @@ -1671,7 +1673,7 @@ func Provider() terraform.ResourceProvider { "alicloud_cms_sls_group": resourceAlicloudCmsSlsGroup(), "alicloud_config_aggregate_delivery": resourceAliCloudConfigAggregateDelivery(), "alicloud_edas_namespace": resourceAlicloudEdasNamespace(), - "alicloud_schedulerx_namespace": resourceAlicloudSchedulerxNamespace(), + "alicloud_schedulerx_namespace": resourceAliCloudSchedulerxNamespace(), "alicloud_ehpc_cluster": resourceAlicloudEhpcCluster(), "alicloud_cen_traffic_marking_policy": resourceAliCloudCenTrafficMarkingPolicy(), "alicloud_ecs_instance_set": resourceAlicloudEcsInstanceSet(), diff --git a/alicloud/resource_alicloud_schedulerx_app_group.go b/alicloud/resource_alicloud_schedulerx_app_group.go new file mode 100644 index 000000000000..bf767365d463 --- /dev/null +++ b/alicloud/resource_alicloud_schedulerx_app_group.go @@ -0,0 +1,322 @@ +// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you! +package alicloud + +import ( + "fmt" + "log" + "strconv" + "strings" + "time" + + util "github.com/alibabacloud-go/tea-utils/service" + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func resourceAliCloudSchedulerxAppGroup() *schema.Resource { + return &schema.Resource{ + Create: resourceAliCloudSchedulerxAppGroupCreate, + Read: resourceAliCloudSchedulerxAppGroupRead, + Update: resourceAliCloudSchedulerxAppGroupUpdate, + Delete: resourceAliCloudSchedulerxAppGroupDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(5 * time.Minute), + Update: schema.DefaultTimeout(5 * time.Minute), + Delete: schema.DefaultTimeout(5 * time.Minute), + }, + Schema: map[string]*schema.Schema{ + "app_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "app_type": { + Type: schema.TypeInt, + Optional: true, + }, + "app_version": { + Type: schema.TypeString, + Optional: true, + }, + "delete_jobs": { + Type: schema.TypeBool, + Optional: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "enable_log": { + Type: schema.TypeBool, + Optional: true, + }, + "group_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "max_concurrency": { + Type: schema.TypeInt, + Optional: true, + }, + "max_jobs": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + }, + "monitor_config_json": { + Type: schema.TypeString, + Optional: true, + }, + "monitor_contacts_json": { + Type: schema.TypeString, + Optional: true, + }, + "namespace": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "namespace_name": { + Type: schema.TypeString, + Required: true, + }, + "namespace_source": { + Type: schema.TypeString, + Optional: true, + }, + "schedule_busy_workers": { + Type: schema.TypeBool, + Optional: true, + }, + }, + } +} + +func resourceAliCloudSchedulerxAppGroupCreate(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*connectivity.AliyunClient) + + action := "CreateAppGroup" + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) + conn, err := client.NewSchedulerxClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query["Namespace"] = d.Get("namespace") + query["GroupId"] = d.Get("group_id") + query["RegionId"] = client.RegionId + + if v, ok := d.GetOk("description"); ok { + query["Description"] = StringPointer(v.(string)) + } + + if v, ok := d.GetOk("monitor_config_json"); ok { + query["MonitorConfigJson"] = StringPointer(v.(string)) + } + + if v, ok := d.GetOk("max_jobs"); ok { + query["MaxJobs"] = StringPointer(strconv.Itoa(v.(int))) + } + + if v, ok := d.GetOk("app_type"); ok { + query["AppType"] = StringPointer(strconv.Itoa(v.(int))) + } + + if v, ok := d.GetOk("schedule_busy_workers"); ok { + query["ScheduleBusyWorkers"] = StringPointer(strconv.FormatBool(v.(bool))) + } + + if v, ok := d.GetOk("namespace_source"); ok { + query["NamespaceSource"] = StringPointer(v.(string)) + } + + if v, ok := d.GetOk("namespace_name"); ok { + query["NamespaceName"] = StringPointer(v.(string)) + } + + if v, ok := d.GetOk("enable_log"); ok { + query["EnableLog"] = StringPointer(strconv.FormatBool(v.(bool))) + } + + if v, ok := d.GetOk("app_name"); ok { + query["AppName"] = StringPointer(v.(string)) + } + + if v, ok := d.GetOk("app_version"); ok { + query["AppVersion"] = StringPointer(v.(string)) + } + + if v, ok := d.GetOk("monitor_contacts_json"); ok { + query["MonitorContactsJson"] = StringPointer(v.(string)) + } + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, "alicloud_schedulerx_app_group", action, AlibabaCloudSdkGoERROR) + } + + d.SetId(fmt.Sprintf("%v:%v", query["Namespace"], query["GroupId"])) + + return resourceAliCloudSchedulerxAppGroupRead(d, meta) +} + +func resourceAliCloudSchedulerxAppGroupRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + schedulerxServiceV2 := SchedulerxServiceV2{client} + + objectRaw, err := schedulerxServiceV2.DescribeSchedulerxAppGroup(d.Id()) + if err != nil { + if !d.IsNewResource() && NotFoundError(err) { + log.Printf("[DEBUG] Resource alicloud_schedulerx_app_group DescribeSchedulerxAppGroup Failed!!! %s", err) + d.SetId("") + return nil + } + return WrapError(err) + } + + if objectRaw["AppName"] != nil { + d.Set("app_name", objectRaw["AppName"]) + } + if objectRaw["AppVersion"] != nil { + d.Set("app_version", objectRaw["AppVersion"]) + } + if objectRaw["Description"] != nil { + d.Set("description", objectRaw["Description"]) + } + if objectRaw["MaxJobs"] != nil { + d.Set("max_jobs", objectRaw["MaxJobs"]) + } + if objectRaw["GroupId"] != nil { + d.Set("group_id", objectRaw["GroupId"]) + } + + parts := strings.Split(d.Id(), ":") + d.Set("namespace", parts[0]) + + return nil +} + +func resourceAliCloudSchedulerxAppGroupUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + update := false + + parts := strings.Split(d.Id(), ":") + action := "UpdateAppGroup" + conn, err := client.NewSchedulerxClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["Namespace"] = parts[0] + request["GroupId"] = parts[1] + request["RegionId"] = client.RegionId + if d.HasChange("description") { + update = true + request["Description"] = d.Get("description") + } + + if d.HasChange("app_version") { + update = true + request["AppVersion"] = d.Get("app_version") + } + + if v, ok := d.GetOkExists("max_concurrency"); ok { + request["MaxConcurrency"] = v + } + if update { + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + } + + return resourceAliCloudSchedulerxAppGroupRead(d, meta) +} + +func resourceAliCloudSchedulerxAppGroupDelete(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*connectivity.AliyunClient) + parts := strings.Split(d.Id(), ":") + action := "DeleteAppGroup" + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) + conn, err := client.NewSchedulerxClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + request["Namespace"] = parts[0] + request["GroupId"] = parts[1] + request["RegionId"] = client.RegionId + + if v, ok := d.GetOkExists("delete_jobs"); ok { + request["DeleteJobs"] = v + } + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + + if err != nil { + if NotFoundError(err) { + return nil + } + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + + return nil +} diff --git a/alicloud/resource_alicloud_schedulerx_app_group_test.go b/alicloud/resource_alicloud_schedulerx_app_group_test.go new file mode 100644 index 000000000000..04b84bd07812 --- /dev/null +++ b/alicloud/resource_alicloud_schedulerx_app_group_test.go @@ -0,0 +1,113 @@ +package alicloud + +import ( + "fmt" + "testing" + + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +// Test Schedulerx AppGroup. >>> Resource test cases, automatically generated. +// Case 预发环境_20241220_杭州reigon 9654 +func TestAccAliCloudSchedulerxAppGroup_basic9654(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_schedulerx_app_group.default" + ra := resourceAttrInit(resourceId, AlicloudSchedulerxAppGroupMap9654) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &SchedulerxServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeSchedulerxAppGroup") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%sschedulerxappgroup%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudSchedulerxAppGroupBasicDependence9654) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "namespace": "${alicloud_schedulerx_namespace.CreateNameSpace.namespace_uid}", + "group_id": "test-appgroup-pop-autotest", + "description": "appgroup 资源用例自动生成", + "monitor_contacts_json": "[{\\\"userName\\\":\\\"张三\\\",\\\"userPhone\\\":\\\"89756******\\\"},{\\\"userName\\\":\\\"李四\\\",\\\"ding\\\":\\\"http://www.example.com\\\"}]", + "enable_log": "false", + "app_name": "test-appgroup-pop-autotest", + "app_version": "1", + "namespace_name": "default", + "monitor_config_json": "{\\\"sendChannel\\\":\\\"sms,ding\\\"}", + "app_type": "1", + "max_jobs": "100", + "namespace_source": "schedulerx", + "schedule_busy_workers": "false", + "delete_jobs": "false", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "namespace": CHECKSET, + "group_id": "test-appgroup-pop-autotest", + "description": "appgroup 资源用例自动生成", + "monitor_contacts_json": "[{\"userName\":\"张三\",\"userPhone\":\"89756******\"},{\"userName\":\"李四\",\"ding\":\"http://www.example.com\"}]", + "enable_log": "false", + "app_name": "test-appgroup-pop-autotest", + "app_version": "1", + "namespace_name": "default", + "monitor_config_json": "{\"sendChannel\":\"sms,ding\"}", + "app_type": "1", + "max_jobs": "100", + "namespace_source": "schedulerx", + "schedule_busy_workers": "false", + "delete_jobs": "false", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "description": "appgroup 资源用例自动生成_update", + "app_version": "2", + "max_concurrency": "500", + "delete_jobs": "true", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "description": "appgroup 资源用例自动生成_update", + "app_version": "2", + "max_concurrency": "500", + "delete_jobs": "true", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"app_type", "enable_log", "max_concurrency", "monitor_config_json", "monitor_contacts_json", "namespace_name", "namespace_source", "schedule_busy_workers", "delete_jobs"}, + }, + }, + }) +} + +var AlicloudSchedulerxAppGroupMap9654 = map[string]string{} + +func AlicloudSchedulerxAppGroupBasicDependence9654(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +resource "alicloud_schedulerx_namespace" "CreateNameSpace" { + namespace_name = var.name + description = "由appgroup 资源测试用例前置步骤创建" +} + + +`, name) +} + +// Test Schedulerx AppGroup. <<< Resource test cases, automatically generated. diff --git a/alicloud/resource_alicloud_schedulerx_job.go b/alicloud/resource_alicloud_schedulerx_job.go new file mode 100644 index 000000000000..1e7650c423e2 --- /dev/null +++ b/alicloud/resource_alicloud_schedulerx_job.go @@ -0,0 +1,1014 @@ +// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you! +package alicloud + +import ( + "fmt" + "log" + "strings" + "time" + + "github.com/PaesslerAG/jsonpath" + util "github.com/alibabacloud-go/tea-utils/service" + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func resourceAliCloudSchedulerxJob() *schema.Resource { + return &schema.Resource{ + Create: resourceAliCloudSchedulerxJobCreate, + Read: resourceAliCloudSchedulerxJobRead, + Update: resourceAliCloudSchedulerxJobUpdate, + Delete: resourceAliCloudSchedulerxJobDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(5 * time.Minute), + Update: schema.DefaultTimeout(5 * time.Minute), + Delete: schema.DefaultTimeout(5 * time.Minute), + }, + Schema: map[string]*schema.Schema{ + "attempt_interval": { + Type: schema.TypeInt, + Optional: true, + }, + "class_name": { + Type: schema.TypeString, + Optional: true, + }, + "content": { + Type: schema.TypeString, + Optional: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + }, + "execute_mode": { + Type: schema.TypeString, + Required: true, + }, + "fail_times": { + Type: schema.TypeInt, + Optional: true, + }, + "group_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "job_id": { + Type: schema.TypeInt, + Computed: true, + }, + "job_monitor_info": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "contact_info": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "user_name": { + Type: schema.TypeString, + Optional: true, + }, + "user_phone": { + Type: schema.TypeString, + Optional: true, + }, + "user_mail": { + Type: schema.TypeString, + Optional: true, + }, + "ding": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "monitor_config": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "timeout_enable": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "timeout": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + "miss_worker_enable": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "fail_enable": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + "send_channel": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "timeout_kill_enable": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "job_name": { + Type: schema.TypeString, + Required: true, + }, + "job_type": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "map_task_xattrs": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "task_attempt_interval": { + Type: schema.TypeInt, + Optional: true, + }, + "queue_size": { + Type: schema.TypeInt, + Optional: true, + }, + "dispatcher_size": { + Type: schema.TypeInt, + Optional: true, + }, + "page_size": { + Type: schema.TypeInt, + Optional: true, + }, + "task_max_attempt": { + Type: schema.TypeInt, + Optional: true, + }, + "consumer_size": { + Type: schema.TypeInt, + Optional: true, + }, + }, + }, + }, + "max_attempt": { + Type: schema.TypeInt, + Optional: true, + }, + "max_concurrency": { + Type: schema.TypeString, + Optional: true, + }, + "namespace": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "namespace_source": { + Type: schema.TypeString, + Optional: true, + }, + "parameters": { + Type: schema.TypeString, + Optional: true, + }, + "status": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: StringInSlice([]string{"Enable", "Disable"}, false), + }, + "success_notice_enable": { + Type: schema.TypeBool, + Optional: true, + }, + "task_dispatch_mode": { + Type: schema.TypeString, + Optional: true, + }, + "template": { + Type: schema.TypeString, + Optional: true, + }, + "time_config": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "calendar": { + Type: schema.TypeString, + Optional: true, + }, + "time_expression": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "data_offset": { + Type: schema.TypeInt, + Optional: true, + }, + "time_type": { + Type: schema.TypeInt, + Required: true, + }, + }, + }, + }, + "timezone": { + Type: schema.TypeString, + Optional: true, + }, + "x_attrs": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + } +} + +func resourceAliCloudSchedulerxJobCreate(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*connectivity.AliyunClient) + + action := "CreateJob" + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) + conn, err := client.NewSchedulerxClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + request["Namespace"] = d.Get("namespace") + request["GroupId"] = d.Get("group_id") + request["RegionId"] = client.RegionId + + if v, ok := d.GetOk("job_monitor_info"); ok { + jsonPathResult, err := jsonpath.Get("$[0].monitor_config[0].miss_worker_enable", v) + if err == nil && jsonPathResult != "" { + request["MissWorkerEnable"] = jsonPathResult + } + } + jsonPathResult1, err := jsonpath.Get("$[0].time_expression", d.Get("time_config")) + if err == nil { + request["TimeExpression"] = jsonPathResult1 + } + + if v, ok := d.GetOk("x_attrs"); ok { + request["XAttrs"] = v + } + if v, ok := d.GetOk("content"); ok { + request["Content"] = v + } + if v, ok := d.GetOk("max_concurrency"); ok { + request["MaxConcurrency"] = v + } + if v, ok := d.GetOk("class_name"); ok { + request["ClassName"] = v + } + if v, ok := d.GetOk("job_monitor_info"); ok { + localData, err := jsonpath.Get("$[0].contact_info", v) + if err != nil { + return WrapError(err) + } + contactInfoMapsArray := make([]interface{}, 0) + for _, dataLoop := range localData.([]interface{}) { + dataLoopTmp := dataLoop.(map[string]interface{}) + dataLoopMap := make(map[string]interface{}) + dataLoopMap["Ding"] = dataLoopTmp["ding"] + dataLoopMap["UserName"] = dataLoopTmp["user_name"] + dataLoopMap["UserPhone"] = dataLoopTmp["user_phone"] + dataLoopMap["UserMail"] = dataLoopTmp["user_mail"] + contactInfoMapsArray = append(contactInfoMapsArray, dataLoopMap) + } + request["ContactInfo"] = contactInfoMapsArray + } + + request["ExecuteMode"] = d.Get("execute_mode") + jsonPathResult7, err := jsonpath.Get("$[0].data_offset", d.Get("time_config")) + if err == nil { + request["DataOffset"] = jsonPathResult7 + } + + if v, ok := d.GetOk("timezone"); ok { + request["Timezone"] = v + } + if v, ok := d.GetOk("job_monitor_info"); ok { + jsonPathResult9, err := jsonpath.Get("$[0].monitor_config[0].timeout_enable", v) + if err == nil && jsonPathResult9 != "" { + request["TimeoutEnable"] = jsonPathResult9 + } + } + if v, ok := d.GetOkExists("success_notice_enable"); ok { + request["SuccessNoticeEnable"] = v + } + if v, ok := d.GetOk("map_task_xattrs"); ok { + jsonPathResult11, err := jsonpath.Get("$[0].dispatcher_size", v) + if err == nil && jsonPathResult11 != "" { + request["DispatcherSize"] = jsonPathResult11 + } + } + if v, ok := d.GetOk("job_monitor_info"); ok { + jsonPathResult12, err := jsonpath.Get("$[0].monitor_config[0].timeout_kill_enable", v) + if err == nil && jsonPathResult12 != "" { + request["TimeoutKillEnable"] = jsonPathResult12 + } + } + if v, ok := d.GetOk("map_task_xattrs"); ok { + jsonPathResult13, err := jsonpath.Get("$[0].page_size", v) + if err == nil && jsonPathResult13 != "" { + request["PageSize"] = jsonPathResult13 + } + } + if v, ok := d.GetOk("description"); ok { + request["Description"] = v + } + if v, ok := d.GetOk("status"); ok { + request["Status"] = convertSchedulerxJobStatusRequest(v.(string)) + } + if v, ok := d.GetOk("parameters"); ok { + request["Parameters"] = v + } + request["Name"] = d.Get("job_name") + if v, ok := d.GetOkExists("attempt_interval"); ok { + request["AttemptInterval"] = v + } + if v, ok := d.GetOk("namespace_source"); ok { + request["NamespaceSource"] = v + } + jsonPathResult20, err := jsonpath.Get("$[0].calendar", d.Get("time_config")) + if err == nil { + request["Calendar"] = jsonPathResult20 + } + + if v, ok := d.GetOkExists("max_attempt"); ok { + request["MaxAttempt"] = v + } + if v, ok := d.GetOk("map_task_xattrs"); ok { + jsonPathResult22, err := jsonpath.Get("$[0].task_max_attempt", v) + if err == nil && jsonPathResult22 != "" { + request["TaskMaxAttempt"] = jsonPathResult22 + } + } + if v, ok := d.GetOk("map_task_xattrs"); ok { + jsonPathResult23, err := jsonpath.Get("$[0].task_attempt_interval", v) + if err == nil && jsonPathResult23 != "" { + request["TaskAttemptInterval"] = jsonPathResult23 + } + } + if v, ok := d.GetOk("map_task_xattrs"); ok { + jsonPathResult24, err := jsonpath.Get("$[0].consumer_size", v) + if err == nil && jsonPathResult24 != "" { + request["ConsumerSize"] = jsonPathResult24 + } + } + if v, ok := d.GetOkExists("fail_times"); ok { + request["FailTimes"] = v + } + jsonPathResult26, err := jsonpath.Get("$[0].time_type", d.Get("time_config")) + if err == nil { + request["TimeType"] = jsonPathResult26 + } + + if v, ok := d.GetOk("job_monitor_info"); ok { + jsonPathResult27, err := jsonpath.Get("$[0].monitor_config[0].timeout", v) + if err == nil && jsonPathResult27 != "" { + request["Timeout"] = jsonPathResult27 + } + } + request["JobType"] = d.Get("job_type") + if v, ok := d.GetOk("job_monitor_info"); ok { + jsonPathResult29, err := jsonpath.Get("$[0].monitor_config[0].fail_enable", v) + if err == nil && jsonPathResult29 != "" { + request["FailEnable"] = jsonPathResult29 + } + } + if v, ok := d.GetOk("job_monitor_info"); ok { + jsonPathResult30, err := jsonpath.Get("$[0].monitor_config[0].send_channel", v) + if err == nil && jsonPathResult30 != "" { + request["SendChannel"] = jsonPathResult30 + } + } + if v, ok := d.GetOk("map_task_xattrs"); ok { + jsonPathResult31, err := jsonpath.Get("$[0].queue_size", v) + if err == nil && jsonPathResult31 != "" { + request["QueueSize"] = jsonPathResult31 + } + } + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, "alicloud_schedulerx_job", action, AlibabaCloudSdkGoERROR) + } + + DataJobIdVar, _ := jsonpath.Get("$.Data.JobId", response) + d.SetId(fmt.Sprintf("%v:%v:%v", request["Namespace"], request["GroupId"], DataJobIdVar)) + + return resourceAliCloudSchedulerxJobRead(d, meta) +} + +func resourceAliCloudSchedulerxJobRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + schedulerxServiceV2 := SchedulerxServiceV2{client} + + objectRaw, err := schedulerxServiceV2.DescribeSchedulerxJob(d.Id()) + if err != nil { + if !d.IsNewResource() && NotFoundError(err) { + log.Printf("[DEBUG] Resource alicloud_schedulerx_job DescribeSchedulerxJob Failed!!! %s", err) + d.SetId("") + return nil + } + return WrapError(err) + } + + if objectRaw["AttemptInterval"] != nil { + d.Set("attempt_interval", objectRaw["AttemptInterval"]) + } + if objectRaw["ClassName"] != nil { + d.Set("class_name", objectRaw["ClassName"]) + } + if objectRaw["Content"] != nil { + d.Set("content", objectRaw["Content"]) + } + if objectRaw["Description"] != nil { + d.Set("description", objectRaw["Description"]) + } + if objectRaw["ExecuteMode"] != nil { + d.Set("execute_mode", objectRaw["ExecuteMode"]) + } + if objectRaw["Name"] != nil { + d.Set("job_name", objectRaw["Name"]) + } + if objectRaw["JobType"] != nil { + d.Set("job_type", objectRaw["JobType"]) + } + if objectRaw["MaxAttempt"] != nil { + d.Set("max_attempt", objectRaw["MaxAttempt"]) + } + if objectRaw["MaxConcurrency"] != nil { + d.Set("max_concurrency", objectRaw["MaxConcurrency"]) + } + if objectRaw["Parameters"] != nil { + d.Set("parameters", objectRaw["Parameters"]) + } + if objectRaw["Status"] != nil { + d.Set("status", convertSchedulerxJobDataJobConfigInfoStatusResponse(objectRaw["Status"])) + } + if objectRaw["XAttrs"] != nil { + d.Set("x_attrs", objectRaw["XAttrs"]) + } + if objectRaw["JobId"] != nil { + d.Set("job_id", objectRaw["JobId"]) + } + + jobMonitorInfoMaps := make([]map[string]interface{}, 0) + jobMonitorInfoMap := make(map[string]interface{}) + jobMonitorInfo1Raw := make(map[string]interface{}) + if objectRaw["JobMonitorInfo"] != nil { + jobMonitorInfo1Raw = objectRaw["JobMonitorInfo"].(map[string]interface{}) + } + if len(jobMonitorInfo1Raw) > 0 { + + contactInfo1Raw := jobMonitorInfo1Raw["ContactInfo"] + contactInfoMaps := make([]map[string]interface{}, 0) + if contactInfo1Raw != nil { + for _, contactInfoChild1Raw := range contactInfo1Raw.([]interface{}) { + contactInfoMap := make(map[string]interface{}) + contactInfoChild1Raw := contactInfoChild1Raw.(map[string]interface{}) + contactInfoMap["ding"] = contactInfoChild1Raw["Ding"] + contactInfoMap["user_mail"] = contactInfoChild1Raw["UserMail"] + contactInfoMap["user_name"] = contactInfoChild1Raw["UserName"] + contactInfoMap["user_phone"] = contactInfoChild1Raw["UserPhone"] + + contactInfoMaps = append(contactInfoMaps, contactInfoMap) + } + } + jobMonitorInfoMap["contact_info"] = contactInfoMaps + monitorConfigMaps := make([]map[string]interface{}, 0) + monitorConfigMap := make(map[string]interface{}) + monitorConfig1Raw := make(map[string]interface{}) + if jobMonitorInfo1Raw["MonitorConfig"] != nil { + monitorConfig1Raw = jobMonitorInfo1Raw["MonitorConfig"].(map[string]interface{}) + } + if len(monitorConfig1Raw) > 0 { + monitorConfigMap["fail_enable"] = monitorConfig1Raw["FailEnable"] + monitorConfigMap["miss_worker_enable"] = monitorConfig1Raw["MissWorkerEnable"] + monitorConfigMap["send_channel"] = monitorConfig1Raw["SendChannel"] + monitorConfigMap["timeout"] = monitorConfig1Raw["Timeout"] + monitorConfigMap["timeout_enable"] = monitorConfig1Raw["TimeoutEnable"] + monitorConfigMap["timeout_kill_enable"] = monitorConfig1Raw["TimeoutKillEnable"] + + monitorConfigMaps = append(monitorConfigMaps, monitorConfigMap) + } + jobMonitorInfoMap["monitor_config"] = monitorConfigMaps + jobMonitorInfoMaps = append(jobMonitorInfoMaps, jobMonitorInfoMap) + } + if objectRaw["JobMonitorInfo"] != nil { + if err := d.Set("job_monitor_info", jobMonitorInfoMaps); err != nil { + return err + } + } + mapTaskXattrsMaps := make([]map[string]interface{}, 0) + mapTaskXattrsMap := make(map[string]interface{}) + mapTaskXAttrs1Raw := make(map[string]interface{}) + if objectRaw["MapTaskXAttrs"] != nil { + mapTaskXAttrs1Raw = objectRaw["MapTaskXAttrs"].(map[string]interface{}) + } + if len(mapTaskXAttrs1Raw) > 0 { + mapTaskXattrsMap["consumer_size"] = mapTaskXAttrs1Raw["ConsumerSize"] + mapTaskXattrsMap["dispatcher_size"] = mapTaskXAttrs1Raw["DispatcherSize"] + mapTaskXattrsMap["page_size"] = mapTaskXAttrs1Raw["PageSize"] + mapTaskXattrsMap["queue_size"] = mapTaskXAttrs1Raw["QueueSize"] + mapTaskXattrsMap["task_attempt_interval"] = mapTaskXAttrs1Raw["TaskAttemptInterval"] + mapTaskXattrsMap["task_max_attempt"] = mapTaskXAttrs1Raw["TaskMaxAttempt"] + + mapTaskXattrsMaps = append(mapTaskXattrsMaps, mapTaskXattrsMap) + } + if objectRaw["MapTaskXAttrs"] != nil { + if err := d.Set("map_task_xattrs", mapTaskXattrsMaps); err != nil { + return err + } + } + timeConfigMaps := make([]map[string]interface{}, 0) + timeConfigMap := make(map[string]interface{}) + timeConfig1Raw := make(map[string]interface{}) + if objectRaw["TimeConfig"] != nil { + timeConfig1Raw = objectRaw["TimeConfig"].(map[string]interface{}) + } + if len(timeConfig1Raw) > 0 { + timeConfigMap["calendar"] = timeConfig1Raw["Calendar"] + timeConfigMap["data_offset"] = timeConfig1Raw["DataOffset"] + timeConfigMap["time_expression"] = timeConfig1Raw["TimeExpression"] + timeConfigMap["time_type"] = timeConfig1Raw["TimeType"] + + timeConfigMaps = append(timeConfigMaps, timeConfigMap) + } + if objectRaw["TimeConfig"] != nil { + if err := d.Set("time_config", timeConfigMaps); err != nil { + return err + } + } + + parts := strings.Split(d.Id(), ":") + d.Set("namespace", parts[0]) + d.Set("group_id", parts[1]) + + return nil +} + +func resourceAliCloudSchedulerxJobUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + update := false + + if d.HasChange("status") { + schedulerxServiceV2 := SchedulerxServiceV2{client} + object, err := schedulerxServiceV2.DescribeSchedulerxJob(d.Id()) + if err != nil { + return WrapError(err) + } + + target := d.Get("status").(string) + if convertSchedulerxJobDataJobConfigInfoStatusResponse(object["Status"]).(string) != target { + if target == "Enable" { + parts := strings.Split(d.Id(), ":") + action := "EnableJob" + conn, err := client.NewSchedulerxClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + query["Namespace"] = parts[0] + query["JobId"] = parts[2] + query["GroupId"] = parts[1] + query["RegionId"] = client.RegionId + if v, ok := d.GetOk("namespace_source"); ok { + query["NamespaceSource"] = StringPointer(v.(string)) + } + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + + } + if target == "Disable" { + parts := strings.Split(d.Id(), ":") + action := "DisableJob" + conn, err := client.NewSchedulerxClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + query["Namespace"] = parts[0] + query["GroupId"] = parts[1] + query["JobId"] = parts[2] + query["RegionId"] = client.RegionId + if v, ok := d.GetOk("namespace_source"); ok { + query["NamespaceSource"] = StringPointer(v.(string)) + } + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + + } + } + } + + parts := strings.Split(d.Id(), ":") + action := "UpdateJob" + conn, err := client.NewSchedulerxClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["Namespace"] = parts[0] + request["GroupId"] = parts[1] + request["JobId"] = parts[2] + request["RegionId"] = client.RegionId + if v, ok := d.GetOk("task_dispatch_mode"); ok { + request["TaskDispatchMode"] = v + } + if d.HasChange("job_monitor_info.0.monitor_config.0.miss_worker_enable") { + update = true + jsonPathResult1, err := jsonpath.Get("$[0].monitor_config[0].miss_worker_enable", d.Get("job_monitor_info")) + if err == nil { + request["MissWorkerEnable"] = jsonPathResult1 + } + } + + if d.HasChange("time_config.0.time_expression") { + update = true + } + jsonPathResult2, err := jsonpath.Get("$[0].time_expression", d.Get("time_config")) + if err == nil { + request["TimeExpression"] = jsonPathResult2 + } + + if d.HasChange("x_attrs") { + update = true + request["XAttrs"] = d.Get("x_attrs") + } + + if d.HasChange("content") { + update = true + request["Content"] = d.Get("content") + } + + if d.HasChange("max_concurrency") { + update = true + request["MaxConcurrency"] = d.Get("max_concurrency") + } + + if d.HasChange("class_name") { + update = true + request["ClassName"] = d.Get("class_name") + } + + if d.HasChange("job_monitor_info") { + update = true + if v, ok := d.GetOk("job_monitor_info"); ok || d.HasChange("job_monitor_info") { + localData, err := jsonpath.Get("$[0].contact_info", v) + if err != nil { + return WrapError(err) + } + contactInfoMapsArray := make([]interface{}, 0) + for _, dataLoop := range localData.([]interface{}) { + dataLoopTmp := dataLoop.(map[string]interface{}) + dataLoopMap := make(map[string]interface{}) + dataLoopMap["Ding"] = dataLoopTmp["ding"] + dataLoopMap["UserName"] = dataLoopTmp["user_name"] + dataLoopMap["UserPhone"] = dataLoopTmp["user_phone"] + dataLoopMap["UserMail"] = dataLoopTmp["user_mail"] + contactInfoMapsArray = append(contactInfoMapsArray, dataLoopMap) + } + request["ContactInfo"] = contactInfoMapsArray + } + } + + if v, ok := d.GetOk("template"); ok { + request["Template"] = v + } + if d.HasChange("execute_mode") { + update = true + } + request["ExecuteMode"] = d.Get("execute_mode") + if d.HasChange("time_config.0.data_offset") { + update = true + } + jsonPathResult9, err := jsonpath.Get("$[0].data_offset", d.Get("time_config")) + if err == nil { + request["DataOffset"] = jsonPathResult9 + } + + if d.HasChange("job_monitor_info.0.monitor_config.0.timeout_enable") { + update = true + jsonPathResult10, err := jsonpath.Get("$[0].monitor_config[0].timeout_enable", d.Get("job_monitor_info")) + if err == nil { + request["TimeoutEnable"] = jsonPathResult10 + } + } + + if v, ok := d.GetOk("timezone"); ok { + request["Timezone"] = v + } + if v, ok := d.GetOkExists("success_notice_enable"); ok { + request["SuccessNoticeEnable"] = v + } + if d.HasChange("map_task_xattrs.0.dispatcher_size") { + update = true + jsonPathResult13, err := jsonpath.Get("$[0].dispatcher_size", d.Get("map_task_xattrs")) + if err == nil { + request["DispatcherSize"] = jsonPathResult13 + } + } + + if d.HasChange("job_monitor_info.0.monitor_config.0.timeout_kill_enable") { + update = true + jsonPathResult14, err := jsonpath.Get("$[0].monitor_config[0].timeout_kill_enable", d.Get("job_monitor_info")) + if err == nil { + request["TimeoutKillEnable"] = jsonPathResult14 + } + } + + if d.HasChange("map_task_xattrs.0.page_size") { + update = true + jsonPathResult15, err := jsonpath.Get("$[0].page_size", d.Get("map_task_xattrs")) + if err == nil { + request["PageSize"] = jsonPathResult15 + } + } + + if d.HasChange("description") { + update = true + request["Description"] = d.Get("description") + } + + if d.HasChange("parameters") { + update = true + request["Parameters"] = d.Get("parameters") + } + + if d.HasChange("job_name") { + update = true + } + request["Name"] = d.Get("job_name") + if d.HasChange("attempt_interval") { + update = true + request["AttemptInterval"] = d.Get("attempt_interval") + } + + if v, ok := d.GetOk("namespace_source"); ok { + request["NamespaceSource"] = v + } + if d.HasChange("time_config.0.calendar") { + update = true + } + jsonPathResult21, err := jsonpath.Get("$[0].calendar", d.Get("time_config")) + if err == nil { + request["Calendar"] = jsonPathResult21 + } + + if d.HasChange("max_attempt") { + update = true + request["MaxAttempt"] = d.Get("max_attempt") + } + + if d.HasChange("map_task_xattrs.0.task_max_attempt") { + update = true + jsonPathResult23, err := jsonpath.Get("$[0].task_max_attempt", d.Get("map_task_xattrs")) + if err == nil { + request["TaskMaxAttempt"] = jsonPathResult23 + } + } + + if d.HasChange("map_task_xattrs.0.task_attempt_interval") { + update = true + jsonPathResult24, err := jsonpath.Get("$[0].task_attempt_interval", d.Get("map_task_xattrs")) + if err == nil { + request["TaskAttemptInterval"] = jsonPathResult24 + } + } + + if v, ok := d.GetOkExists("fail_times"); ok { + request["FailTimes"] = v + } + if d.HasChange("map_task_xattrs.0.consumer_size") { + update = true + jsonPathResult26, err := jsonpath.Get("$[0].consumer_size", d.Get("map_task_xattrs")) + if err == nil { + request["ConsumerSize"] = jsonPathResult26 + } + } + + if d.HasChange("time_config.0.time_type") { + update = true + } + jsonPathResult27, err := jsonpath.Get("$[0].time_type", d.Get("time_config")) + if err == nil { + request["TimeType"] = jsonPathResult27 + } + + if d.HasChange("job_monitor_info.0.monitor_config.0.timeout") { + update = true + jsonPathResult28, err := jsonpath.Get("$[0].monitor_config[0].timeout", d.Get("job_monitor_info")) + if err == nil { + request["Timeout"] = jsonPathResult28 + } + } + + if d.HasChange("job_monitor_info.0.monitor_config.0.fail_enable") { + update = true + jsonPathResult29, err := jsonpath.Get("$[0].monitor_config[0].fail_enable", d.Get("job_monitor_info")) + if err == nil { + request["FailEnable"] = jsonPathResult29 + } + } + + if d.HasChange("job_monitor_info.0.monitor_config.0.send_channel") { + update = true + jsonPathResult30, err := jsonpath.Get("$[0].monitor_config[0].send_channel", d.Get("job_monitor_info")) + if err == nil { + request["SendChannel"] = jsonPathResult30 + } + } + + if d.HasChange("map_task_xattrs.0.queue_size") { + update = true + jsonPathResult31, err := jsonpath.Get("$[0].queue_size", d.Get("map_task_xattrs")) + if err == nil { + request["QueueSize"] = jsonPathResult31 + } + } + + if update { + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + } + + return resourceAliCloudSchedulerxJobRead(d, meta) +} + +func resourceAliCloudSchedulerxJobDelete(d *schema.ResourceData, meta interface{}) error { + + client := meta.(*connectivity.AliyunClient) + parts := strings.Split(d.Id(), ":") + action := "DeleteJob" + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) + conn, err := client.NewSchedulerxClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query["Namespace"] = parts[0] + query["GroupId"] = parts[1] + query["JobId"] = parts[2] + query["RegionId"] = client.RegionId + + if v, ok := d.GetOk("namespace_source"); ok { + query["NamespaceSource"] = StringPointer(v.(string)) + } + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + + if err != nil { + if NotFoundError(err) { + return nil + } + return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) + } + + return nil +} + +func convertSchedulerxJobDataJobConfigInfoStatusResponse(source interface{}) interface{} { + source = fmt.Sprint(source) + switch source { + case "1": + return "Enable" + case "0": + return "Disable" + } + return source +} +func convertSchedulerxJobStatusRequest(source interface{}) interface{} { + source = fmt.Sprint(source) + switch source { + case "Enable": + return "1" + case "Disable": + return "0" + } + return source +} diff --git a/alicloud/resource_alicloud_schedulerx_job_test.go b/alicloud/resource_alicloud_schedulerx_job_test.go new file mode 100644 index 000000000000..faaea9c0a3f1 --- /dev/null +++ b/alicloud/resource_alicloud_schedulerx_job_test.go @@ -0,0 +1,395 @@ +package alicloud + +import ( + "fmt" + "testing" + + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +// Test Schedulerx Job. >>> Resource test cases, automatically generated. +// Case 预发环境_20241220_杭州region_组合用例B 9597 +func TestAccAliCloudSchedulerxJob_basic9597(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_schedulerx_job.default" + ra := resourceAttrInit(resourceId, AlicloudSchedulerxJobMap9597) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &SchedulerxServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeSchedulerxJob") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%sschedulerxjob%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudSchedulerxJobBasicDependence9597) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "status": "Enable", + "max_attempt": "0", + "description": "Job资源用例自动生成的的任务", + "success_notice_enable": "false", + "job_name": name, + "max_concurrency": "1", + "time_config": []map[string]interface{}{ + { + "time_type": "-1", + "calendar": "workday", + }, + }, + "namespace": "${alicloud_schedulerx_namespace.CreateNameSpace.namespace_uid}", + "group_id": "${alicloud_schedulerx_app_group.CreateAppGroup.group_id}", + "job_type": "shell", + "job_monitor_info": []map[string]interface{}{ + { + "monitor_config": []map[string]interface{}{ + { + "timeout": "7200", + "send_channel": "webhook", + }, + }, + "contact_info": []map[string]interface{}{ + { + "user_name": "tangtao-1", + }, + { + "user_name": "tangtao-2", + }, + { + "user_name": "tangtao-3", + }, + }, + }, + }, + "content": "echo 'hello'", + "namespace_source": "schedulerx", + "attempt_interval": "30", + "execute_mode": "standalone", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "status": "Enable", + "max_attempt": "0", + "description": "Job资源用例自动生成的的任务", + "success_notice_enable": "false", + "job_name": name, + "max_concurrency": "1", + "namespace": CHECKSET, + "group_id": CHECKSET, + "job_type": "shell", + "content": "echo 'hello'", + "namespace_source": "schedulerx", + "attempt_interval": "30", + "execute_mode": "standalone", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "content": "echo 'helllo schedulerx'", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "content": "echo 'helllo schedulerx'", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"fail_times", "namespace_source", "success_notice_enable", "task_dispatch_mode", "template", "timezone"}, + }, + }, + }) +} + +var AlicloudSchedulerxJobMap9597 = map[string]string{ + "job_id": CHECKSET, +} + +func AlicloudSchedulerxJobBasicDependence9597(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +resource "alicloud_schedulerx_namespace" "CreateNameSpace" { + namespace_name = var.name + description = "namespace 资源用例自动创建的命名空间" +} + +resource "alicloud_schedulerx_app_group" "CreateAppGroup" { + namespace = alicloud_schedulerx_namespace.CreateNameSpace.namespace_uid + group_id = "test-appgroup-pop-autotest" + description = "appgroup 资源用例生成" + monitor_contacts_json = "[{\"userName\":\"张三\",\"userPhone\":\"89756******\"},{\"userName\":\"李四\",\"ding\":\"http://www.example.com\"}]" + app_name = "test-appgroup-pop-autotest" + app_version = "1" + namespace_name = alicloud_schedulerx_namespace.CreateNameSpace.namespace_name + monitor_config_json = "{\"sendChannel\":\"sms,ding\"}" + app_type = "2" + max_jobs = "100" + namespace_source = "schedulerx" +} + + +`, name) +} + +// Case 预发环境_20241220_杭州region_组合用例A 9548 +func TestAccAliCloudSchedulerxJob_basic9548(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_schedulerx_job.default" + ra := resourceAttrInit(resourceId, AlicloudSchedulerxJobMap9548) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &SchedulerxServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeSchedulerxJob") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%sschedulerxjob%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudSchedulerxJobBasicDependence9548) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "timezone": "GTM+7", + "status": "Enable", + "max_attempt": "0", + "description": "job资源用例自动生成的任务", + "parameters": "hello word", + "job_name": name, + "max_concurrency": "1", + "time_config": []map[string]interface{}{ + { + "data_offset": "1", + "time_expression": "100000", + "time_type": "3", + "calendar": "workday", + }, + }, + "map_task_xattrs": []map[string]interface{}{ + { + "task_max_attempt": "1", + "task_attempt_interval": "1", + "consumer_size": "5", + "queue_size": "10000", + "dispatcher_size": "5", + "page_size": "100", + }, + }, + "namespace": "${alicloud_schedulerx_namespace.CreateNameSpace.namespace_uid}", + "group_id": "${alicloud_schedulerx_app_group.CreateAppGroup.group_id}", + "job_type": "java", + "job_monitor_info": []map[string]interface{}{ + { + "contact_info": []map[string]interface{}{ + { + "user_phone": "18838204961", + "user_name": "tangtao-1", + "ding": "https://alidocs.dingtalk.com", + "user_mail": "12345678@qq.com", + }, + { + "user_phone": "18838204961", + "user_name": "tangtao-2", + "ding": "https://alidocs.dingtalk.com1", + "user_mail": "123456789@qq.com", + }, + }, + "monitor_config": []map[string]interface{}{ + { + "timeout": "7200", + "send_channel": "sms", + "timeout_kill_enable": "true", + "timeout_enable": "true", + "fail_enable": "true", + "miss_worker_enable": "true", + }, + }, + }, + }, + "class_name": "com.aliyun.schedulerx.example.processor.SimpleJob", + "namespace_source": "schedulerx", + "attempt_interval": "30", + "fail_times": "1", + "execute_mode": "batch", + "x_attrs": "{\\\"consumerSize\\\":5,\\\"dispatcherSize\\\":5,\\\"taskMaxAttempt\\\":1,\\\"taskAttemptInterval\\\":1,\\\"taskDispatchMode\\\":\\\"push\\\",\\\"failover\\\":true,\\\"execOnMaster\\\":true,\\\"produceInterval\\\":3,\\\"pageSize\\\":100,\\\"queueSize\\\":10000,\\\"globalConsumerSize\\\":1000}", + "success_notice_enable": "false", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "timezone": "GTM+7", + "status": "Enable", + "max_attempt": "0", + "description": "job资源用例自动生成的任务", + "parameters": "hello word", + "job_name": name, + "max_concurrency": "1", + "namespace": CHECKSET, + "group_id": CHECKSET, + "job_type": "java", + "class_name": "com.aliyun.schedulerx.example.processor.SimpleJob", + "namespace_source": "schedulerx", + "attempt_interval": "30", + "fail_times": "1", + "execute_mode": "batch", + "x_attrs": "{\"consumerSize\":5,\"dispatcherSize\":5,\"taskMaxAttempt\":1,\"taskAttemptInterval\":1,\"taskDispatchMode\":\"push\",\"failover\":true,\"execOnMaster\":true,\"produceInterval\":3,\"pageSize\":100,\"queueSize\":10000,\"globalConsumerSize\":1000}", + "success_notice_enable": "false", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "timezone": "GTM+8", + "max_attempt": "2", + "description": "hahaha", + "parameters": "hello word ,schedlerx", + "job_name": name + "_update", + "max_concurrency": "2", + "time_config": []map[string]interface{}{ + { + "time_type": "1", + "data_offset": "2", + "time_expression": "0 0 18 1 */1 ?", + "calendar": "finance", + }, + }, + "map_task_xattrs": []map[string]interface{}{ + { + "task_max_attempt": "2", + "task_attempt_interval": "2", + "consumer_size": "10", + "queue_size": "5000", + "dispatcher_size": "10", + "page_size": "200", + }, + }, + "job_monitor_info": []map[string]interface{}{ + { + "monitor_config": []map[string]interface{}{ + { + "timeout_kill_enable": "false", + "timeout_enable": "false", + "fail_enable": "false", + "miss_worker_enable": "false", + "timeout": "1000", + "send_channel": "ding", + }, + }, + "contact_info": []map[string]interface{}{ + { + "user_name": "tangtao-update", + "user_mail": "iamispangpang@163.com", + "user_phone": "12588888888", + "ding": "https://alidocs.dingtalk.com/i/nodes/dQPGYqjpJYZnRbNYCLggRQjP8akx1Z5N?utm_scene=team_space", + }, + { + "user_phone": "18888888888", + "user_name": "tangtao-3", + "user_mail": "12345678@qq.com", + "ding": "https://alidocs.dingtalk.com", + }, + { + "user_phone": "18888888666", + "user_name": "tangtao-4", + "ding": "1233", + "user_mail": "22345678@qq.com", + }, + }, + }, + }, + "class_name": "hello word", + "attempt_interval": "100", + "fail_times": "3", + "execute_mode": "grid", + "x_attrs": "{\\\"consumerSize\\\":10,\\\"dispatcherSize\\\":10,\\\"taskMaxAttempt\\\":2,\\\"taskAttemptInterval\\\":2,\\\"taskDispatchMode\\\":\\\"push\\\",\\\"failover\\\":true,\\\"execOnMaster\\\":true,\\\"produceInterval\\\":3,\\\"pageSize\\\":200,\\\"queueSize\\\":5000,\\\"globalConsumerSize\\\":1000}", + "success_notice_enable": "true", + "task_dispatch_mode": "push", + "template": "apiVersion: v1 kind: Pod metadata: name: schedulerx-python-{JOB_ID}11 namespace: {NAMESPACE} spec: containers: - name: python-job image: python imagePullPolicy: IfNotPresent volumeMounts: - name: script-python mountPath: script/python command: [\\\"python\\\",\\\"script/python/python-{JOB_ID}.py\\\"] volumes: - name: script-python configMap: name: schedulerx-configmap items: - key: schedulerx-python-{JOB_ID} path: python-{JOB_ID}.py restartPolicy: Never", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "timezone": "GTM+8", + "max_attempt": "2", + "description": "hahaha", + "parameters": "hello word ,schedlerx", + "job_name": name + "_update", + "max_concurrency": "2", + "class_name": "hello word", + "attempt_interval": "100", + "fail_times": "3", + "execute_mode": "grid", + "x_attrs": "{\"consumerSize\":10,\"dispatcherSize\":10,\"taskMaxAttempt\":2,\"taskAttemptInterval\":2,\"taskDispatchMode\":\"push\",\"failover\":true,\"execOnMaster\":true,\"produceInterval\":3,\"pageSize\":200,\"queueSize\":5000,\"globalConsumerSize\":1000}", + "success_notice_enable": "true", + "task_dispatch_mode": "push", + "template": "apiVersion: v1 kind: Pod metadata: name: schedulerx-python-{JOB_ID}11 namespace: {NAMESPACE} spec: containers: - name: python-job image: python imagePullPolicy: IfNotPresent volumeMounts: - name: script-python mountPath: script/python command: [\"python\",\"script/python/python-{JOB_ID}.py\"] volumes: - name: script-python configMap: name: schedulerx-configmap items: - key: schedulerx-python-{JOB_ID} path: python-{JOB_ID}.py restartPolicy: Never", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "status": "Disable", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "status": "Disable", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"fail_times", "namespace_source", "success_notice_enable", "task_dispatch_mode", "template", "timezone"}, + }, + }, + }) +} + +var AlicloudSchedulerxJobMap9548 = map[string]string{ + "job_id": CHECKSET, +} + +func AlicloudSchedulerxJobBasicDependence9548(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + +resource "alicloud_schedulerx_namespace" "CreateNameSpace" { + namespace_name = var.name + description = "pop资源用例自动生成" +} + +resource "alicloud_schedulerx_app_group" "CreateAppGroup" { + description = "appgroup 资源用例生成" + namespace = alicloud_schedulerx_namespace.CreateNameSpace.namespace_uid + group_id = "test-appgroup-pop-autotest" + app_name = "test-appgroup-pop-autotest" + app_version = "2" + namespace_name = alicloud_schedulerx_namespace.CreateNameSpace.namespace_name + app_type = "2" + max_jobs = "1000" +} + + +`, name) +} + +// Test Schedulerx Job. <<< Resource test cases, automatically generated. diff --git a/alicloud/resource_alicloud_schedulerx_namespace.go b/alicloud/resource_alicloud_schedulerx_namespace.go index 87ed4bfa65bb..48739454e3d6 100644 --- a/alicloud/resource_alicloud_schedulerx_namespace.go +++ b/alicloud/resource_alicloud_schedulerx_namespace.go @@ -1,3 +1,4 @@ +// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you! package alicloud import ( @@ -12,54 +13,66 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) -func resourceAlicloudSchedulerxNamespace() *schema.Resource { +func resourceAliCloudSchedulerxNamespace() *schema.Resource { return &schema.Resource{ - Create: resourceAlicloudSchedulerxNamespaceCreate, - Read: resourceAlicloudSchedulerxNamespaceRead, - Update: resourceAlicloudSchedulerxNamespaceUpdate, - Delete: resourceAlicloudSchedulerxNamespaceDelete, + Create: resourceAliCloudSchedulerxNamespaceCreate, + Read: resourceAliCloudSchedulerxNamespaceRead, + Delete: resourceAliCloudSchedulerxNamespaceDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(1 * time.Minute), - Update: schema.DefaultTimeout(1 * time.Minute), + Create: schema.DefaultTimeout(5 * time.Minute), + Delete: schema.DefaultTimeout(5 * time.Minute), }, Schema: map[string]*schema.Schema{ "description": { - Optional: true, Type: schema.TypeString, + Optional: true, + ForceNew: true, }, "namespace_name": { + Type: schema.TypeString, Required: true, + ForceNew: true, + }, + "namespace_uid": { Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, }, }, } } -func resourceAlicloudSchedulerxNamespaceCreate(d *schema.ResourceData, meta interface{}) error { +func resourceAliCloudSchedulerxNamespaceCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) - request := map[string]interface{}{ - "RegionId": client.RegionId, - } - conn, err := client.NewEdasschedulerxClient() + + action := "CreateNamespace" + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) + conn, err := client.NewSchedulerxClient() if err != nil { return WrapError(err) } + request = make(map[string]interface{}) + if v, ok := d.GetOk("namespace_uid"); ok { + request["Uid"] = v + } + request["RegionId"] = client.RegionId + request["Name"] = d.Get("namespace_name") if v, ok := d.GetOk("description"); ok { request["Description"] = v } - if v, ok := d.GetOk("namespace_name"); ok { - request["Name"] = v - } - - var response map[string]interface{} - action := "CreateNamespace" - wait := incrementalWait(3*time.Second, 3*time.Second) + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { - resp, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-04-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{}) + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) if err != nil { if NeedRetry(err) { wait() @@ -67,89 +80,50 @@ func resourceAlicloudSchedulerxNamespaceCreate(d *schema.ResourceData, meta inte } return resource.NonRetryableError(err) } - response = resp - addDebug(action, response, request) return nil }) + addDebug(action, response, request) + if err != nil { return WrapErrorf(err, DefaultErrorMsg, "alicloud_schedulerx_namespace", action, AlibabaCloudSdkGoERROR) } - if v, err := jsonpath.Get("$.Data.NamespaceUid", response); err != nil || v == nil { - return WrapErrorf(err, IdMsg, "alicloud_schedulerx_namespace") - } else { - d.SetId(fmt.Sprint(v)) - } + id, _ := jsonpath.Get("$.Data.NamespaceUid", response) + d.SetId(fmt.Sprint(id)) - return resourceAlicloudSchedulerxNamespaceRead(d, meta) + return resourceAliCloudSchedulerxNamespaceRead(d, meta) } -func resourceAlicloudSchedulerxNamespaceRead(d *schema.ResourceData, meta interface{}) error { +func resourceAliCloudSchedulerxNamespaceRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) - schedulerx2Service := Schedulerx2Service{client} + schedulerxServiceV2 := SchedulerxServiceV2{client} - object, err := schedulerx2Service.DescribeSchedulerxNamespace(d.Id()) + objectRaw, err := schedulerxServiceV2.DescribeSchedulerxNamespace(d.Id()) if err != nil { - if NotFoundError(err) { - log.Printf("[DEBUG] Resource alicloud_schedulerx_namespace schedulerx2Service.DescribeSchedulerxNamespace Failed!!! %s", err) + if !d.IsNewResource() && NotFoundError(err) { + log.Printf("[DEBUG] Resource alicloud_schedulerx_namespace DescribeSchedulerxNamespace Failed!!! %s", err) d.SetId("") return nil } return WrapError(err) } - d.Set("description", object["Description"]) - d.Set("namespace_name", object["Name"]) - return nil -} - -func resourceAlicloudSchedulerxNamespaceUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*connectivity.AliyunClient) - conn, err := client.NewEdasschedulerxClient() - if err != nil { - return WrapError(err) + if objectRaw["Description"] != nil { + d.Set("description", objectRaw["Description"]) } - update := false - request := map[string]interface{}{ - "Uid": d.Id(), - "RegionId": client.RegionId, + if objectRaw["Name"] != nil { + d.Set("namespace_name", objectRaw["Name"]) } - - if d.HasChange("description") { - update = true - if v, ok := d.GetOk("description"); ok { - request["Description"] = v - } + if objectRaw["UId"] != nil { + d.Set("namespace_uid", objectRaw["UId"]) } - if d.HasChange("namespace_name") { - update = true - } - request["Name"] = d.Get("namespace_name") - if update { - action := "CreateNamespace" - wait := incrementalWait(3*time.Second, 3*time.Second) - err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError { - resp, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-04-30"), StringPointer("AK"), nil, request, &util.RuntimeOptions{}) - if err != nil { - if NeedRetry(err) { - wait() - return resource.RetryableError(err) - } - return resource.NonRetryableError(err) - } - addDebug(action, resp, request) - return nil - }) - if err != nil { - return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) - } - } + d.Set("namespace_uid", d.Id()) - return resourceAlicloudSchedulerxNamespaceRead(d, meta) + return nil } -func resourceAlicloudSchedulerxNamespaceDelete(d *schema.ResourceData, meta interface{}) error { - log.Printf("[WARN] Cannot destroy resourceAlicloudSchedulerxNamespace. Terraform will remove this resource from the state file, however resources may remain.") +func resourceAliCloudSchedulerxNamespaceDelete(d *schema.ResourceData, meta interface{}) error { + log.Printf("[WARN] Cannot destroy resource AliCloud Resource Namespace. Terraform will remove this resource from the state file, however resources may remain.") return nil } diff --git a/alicloud/resource_alicloud_schedulerx_namespace_test.go b/alicloud/resource_alicloud_schedulerx_namespace_test.go index 756d4c1a0525..3c038f9424e9 100644 --- a/alicloud/resource_alicloud_schedulerx_namespace_test.go +++ b/alicloud/resource_alicloud_schedulerx_namespace_test.go @@ -19,7 +19,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) -func TestAccAlicloudSchedulerxNamespace_basic0(t *testing.T) { +func TestAccAliCloudSchedulerxNamespace_basic0(t *testing.T) { var v map[string]interface{} resourceId := "alicloud_schedulerx_namespace.default" ra := resourceAttrInit(resourceId, AlicloudSchedulerxNamespaceMap0) @@ -174,7 +174,7 @@ func TestUnitAccAlicloudSchedulerxNamespace(t *testing.T) { StatusCode: tea.Int(400), } }) - err = resourceAlicloudSchedulerxNamespaceCreate(dInit, rawClient) + err = resourceAliCloudSchedulerxNamespaceCreate(dInit, rawClient) patches.Reset() assert.NotNil(t, err) ReadMockResponseDiff := map[string]interface{}{} @@ -197,7 +197,7 @@ func TestUnitAccAlicloudSchedulerxNamespace(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudSchedulerxNamespaceCreate(dInit, rawClient) + err := resourceAliCloudSchedulerxNamespaceCreate(dInit, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -224,7 +224,7 @@ func TestUnitAccAlicloudSchedulerxNamespace(t *testing.T) { StatusCode: tea.Int(400), } }) - err = resourceAlicloudSchedulerxNamespaceUpdate(dExisted, rawClient) + err = resourceAliCloudSchedulerxNamespaceCreate(dExisted, rawClient) patches.Reset() assert.NotNil(t, err) attributesDiff := map[string]interface{}{ @@ -265,7 +265,7 @@ func TestUnitAccAlicloudSchedulerxNamespace(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudSchedulerxNamespaceUpdate(dExisted, rawClient) + err := resourceAliCloudSchedulerxNamespaceCreate(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -309,7 +309,7 @@ func TestUnitAccAlicloudSchedulerxNamespace(t *testing.T) { } return ReadMockResponse, nil }) - err := resourceAlicloudSchedulerxNamespaceRead(dExisted, rawClient) + err := resourceAliCloudSchedulerxNamespaceCreate(dExisted, rawClient) patches.Reset() switch errorCode { case "NonRetryableError": @@ -320,3 +320,63 @@ func TestUnitAccAlicloudSchedulerxNamespace(t *testing.T) { } } + +// Test Schedulerx Namespace. >>> Resource test cases, automatically generated. +// Case 预发环境_20241220_杭州region 9449 +func TestAccAliCloudSchedulerxNamespace_basic9449(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_schedulerx_namespace.default" + ra := resourceAttrInit(resourceId, AlicloudSchedulerxNamespaceMap9449) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &SchedulerxServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeSchedulerxNamespace") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(10000, 99999) + name := fmt.Sprintf("tf-testacc%sschedulerxnamespace%d", defaultRegionToTest, rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudSchedulerxNamespaceBasicDependence9449) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "namespace_name": name, + "description": "namespace 资源用例自动创建的命名空间", + "namespace_uid": fmt.Sprint(rand), + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "namespace_name": name, + "description": "namespace 资源用例自动创建的命名空间", + "namespace_uid": CHECKSET, + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{}, + }, + }, + }) +} + +var AlicloudSchedulerxNamespaceMap9449 = map[string]string{} + +func AlicloudSchedulerxNamespaceBasicDependence9449(name string) string { + return fmt.Sprintf(` +variable "name" { + default = "%s" +} + + +`, name) +} + +// Test Schedulerx Namespace. <<< Resource test cases, automatically generated. diff --git a/alicloud/service_alicloud_schedulerx_v2.go b/alicloud/service_alicloud_schedulerx_v2.go new file mode 100644 index 000000000000..f05ffdc2655b --- /dev/null +++ b/alicloud/service_alicloud_schedulerx_v2.go @@ -0,0 +1,259 @@ +package alicloud + +import ( + "fmt" + "strings" + "time" + + "github.com/PaesslerAG/jsonpath" + util "github.com/alibabacloud-go/tea-utils/service" + "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +type SchedulerxServiceV2 struct { + client *connectivity.AliyunClient +} + +// DescribeSchedulerxJob <<< Encapsulated get interface for Schedulerx Job. + +func (s *SchedulerxServiceV2) DescribeSchedulerxJob(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + parts := strings.Split(id, ":") + if len(parts) != 3 { + err = WrapError(fmt.Errorf("invalid Resource Id %s. Expected parts' length %d, got %d", id, 3, len(parts))) + } + action := "GetJobInfo" + conn, err := client.NewSchedulerxClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + query["GroupId"] = parts[1] + query["JobId"] = parts[2] + query["Namespace"] = parts[0] + query["RegionId"] = client.RegionId + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("GET"), StringPointer("2019-04-30"), StringPointer("AK"), query, nil, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + v, err := jsonpath.Get("$.Data.JobConfigInfo", response) + if err != nil { + return object, WrapErrorf(Error(GetNotFoundMessage("Job", id)), NotFoundMsg, response) + } + + return v.(map[string]interface{}), nil +} + +func (s *SchedulerxServiceV2) SchedulerxJobStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeSchedulerxJob(id) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + if strings.HasPrefix(field, "#") { + v, _ := jsonpath.Get(strings.TrimPrefix(field, "#"), object) + if v != nil { + currentStatus = "#CHECKSET" + } + } + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +// DescribeSchedulerxJob >>> Encapsulated. + +// DescribeSchedulerxNamespace <<< Encapsulated get interface for Schedulerx Namespace. + +func (s *SchedulerxServiceV2) DescribeSchedulerxNamespace(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + action := "ListNamespaces" + conn, err := client.NewSchedulerxClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["Namespace"] = id + request["RegionId"] = client.RegionId + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + v, err := jsonpath.Get("$.Data.Namespaces[*]", response) + if err != nil { + return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.Data.Namespaces[*]", response) + } + + if len(v.([]interface{})) == 0 { + return object, WrapErrorf(Error(GetNotFoundMessage("Namespace", id)), NotFoundMsg, response) + } + + return v.([]interface{})[0].(map[string]interface{}), nil +} + +func (s *SchedulerxServiceV2) SchedulerxNamespaceStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeSchedulerxNamespace(id) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + if strings.HasPrefix(field, "#") { + v, _ := jsonpath.Get(strings.TrimPrefix(field, "#"), object) + if v != nil { + currentStatus = "#CHECKSET" + } + } + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +// DescribeSchedulerxNamespace >>> Encapsulated. + +// DescribeSchedulerxAppGroup <<< Encapsulated get interface for Schedulerx AppGroup. + +func (s *SchedulerxServiceV2) DescribeSchedulerxAppGroup(id string) (object map[string]interface{}, err error) { + client := s.client + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + parts := strings.Split(id, ":") + if len(parts) != 2 { + err = WrapError(fmt.Errorf("invalid Resource Id %s. Expected parts' length %d, got %d", id, 2, len(parts))) + } + action := "GetAppGroup" + conn, err := client.NewSchedulerxClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["GroupId"] = parts[1] + request["Namespace"] = parts[0] + request["RegionId"] = client.RegionId + + runtime := util.RuntimeOptions{} + runtime.SetAutoretry(true) + wait := incrementalWait(3*time.Second, 5*time.Second) + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-04-30"), StringPointer("AK"), query, request, &runtime) + + if err != nil { + if NeedRetry(err) { + wait() + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + addDebug(action, response, request) + if err != nil { + return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR) + } + + v, err := jsonpath.Get("$.Data", response) + if err != nil { + return object, WrapErrorf(Error(GetNotFoundMessage("AppGroup", id)), NotFoundMsg, response) + } + + return v.(map[string]interface{}), nil +} + +func (s *SchedulerxServiceV2) SchedulerxAppGroupStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + object, err := s.DescribeSchedulerxAppGroup(id) + if err != nil { + if NotFoundError(err) { + return object, "", nil + } + return nil, "", WrapError(err) + } + + v, err := jsonpath.Get(field, object) + currentStatus := fmt.Sprint(v) + + if strings.HasPrefix(field, "#") { + v, _ := jsonpath.Get(strings.TrimPrefix(field, "#"), object) + if v != nil { + currentStatus = "#CHECKSET" + } + } + + for _, failState := range failStates { + if currentStatus == failState { + return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus)) + } + } + return object, currentStatus, nil + } +} + +// DescribeSchedulerxAppGroup >>> Encapsulated. diff --git a/website/docs/r/schedulerx_app_group.html.markdown b/website/docs/r/schedulerx_app_group.html.markdown new file mode 100644 index 000000000000..0c7df9b8da6d --- /dev/null +++ b/website/docs/r/schedulerx_app_group.html.markdown @@ -0,0 +1,98 @@ +--- +subcategory: "Schedulerx" +layout: "alicloud" +page_title: "Alicloud: alicloud_schedulerx_app_group" +description: |- + Provides a Alicloud Schedulerx App Group resource. +--- + +# alicloud_schedulerx_app_group + +Provides a Schedulerx App Group resource. + + + +For information about Schedulerx App Group and how to use it, see [What is App Group](https://www.alibabacloud.com/help/en/). + +-> **NOTE:** Available since v1.240.0. + +## Example Usage + +Basic Usage + +```terraform +variable "name" { + default = "terraform-example" +} + +provider "alicloud" { + region = "cn-hangzhou" +} + +resource "alicloud_schedulerx_namespace" "CreateNameSpace" { + namespace_name = var.name + description = var.name +} + +resource "alicloud_schedulerx_app_group" "default" { + max_jobs = "100" + monitor_contacts_json = jsonencode([{ "userName" : "name1", "userPhone" : "89756******" }, { "userName" : "name2", "ding" : "http://www.example.com" }]) + delete_jobs = "false" + app_type = "1" + namespace_source = "schedulerx" + group_id = "example-appgroup-pop-autoexample" + namespace_name = "default" + description = var.name + monitor_config_json = jsonencode({ "sendChannel" : "sms,ding" }) + app_version = "1" + app_name = "example-appgroup-pop-autoexample" + namespace = alicloud_schedulerx_namespace.CreateNameSpace.namespace_uid + enable_log = "false" + schedule_busy_workers = "false" +} +``` + +## Argument Reference + +The following arguments are supported: +* `app_name` - (Required, ForceNew) Application Name +* `app_type` - (Optional, Int) Application type. + - 1, general application. + - 2, k8s application. +* `app_version` - (Optional) Application Version, 1: Basic Edition, 2: Professional Edition +* `delete_jobs` - (Optional) Whether to delete the task in the application Group. The values are as follows: + - `true`: Delete. + - `false`: Do not delete. +* `description` - (Optional) Application Description +* `enable_log` - (Optional) Whether to enable the log. + - true: On + - false: Close +* `group_id` - (Required, ForceNew) Application ID +* `max_concurrency` - (Optional, Int) The maximum number of instances running at the same time. The default value is 1, that is, the last trigger is not completed, and the next trigger will not be performed even at the running time. +* `max_jobs` - (Optional, ForceNew, Int) Application Grouping Configurable Maximum Number of Tasks +* `monitor_config_json` - (Optional) Alarm configuration JSON field. For more information about this field, see **Request Parameters * *. +* `monitor_contacts_json` - (Optional) Alarm contact JSON format. +* `namespace` - (Required, ForceNew) The namespace ID, which is obtained on the namespace page of the console. +* `namespace_name` - (Required) The namespace name. +* `namespace_source` - (Optional) Not supported for the time being, no need to fill in. +* `schedule_busy_workers` - (Optional) Whether to schedule a busy machine. + +## Attributes Reference + +The following attributes are exported: +* `id` - The ID of the resource supplied above.The value is formulated as `:`. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration-0-11/resources.html#timeouts) for certain actions: +* `create` - (Defaults to 5 mins) Used when create the App Group. +* `delete` - (Defaults to 5 mins) Used when delete the App Group. +* `update` - (Defaults to 5 mins) Used when update the App Group. + +## Import + +Schedulerx App Group can be imported using the id, e.g. + +```shell +$ terraform import alicloud_schedulerx_app_group.example : +``` \ No newline at end of file diff --git a/website/docs/r/schedulerx_job.html.markdown b/website/docs/r/schedulerx_job.html.markdown new file mode 100644 index 000000000000..2e9af4f53d8b --- /dev/null +++ b/website/docs/r/schedulerx_job.html.markdown @@ -0,0 +1,223 @@ +--- +subcategory: "Schedulerx" +layout: "alicloud" +page_title: "Alicloud: alicloud_schedulerx_job" +description: |- + Provides a Alicloud Schedulerx Job resource. +--- + +# alicloud_schedulerx_job + +Provides a Schedulerx Job resource. + + + +For information about Schedulerx Job and how to use it, see [What is Job](https://www.alibabacloud.com/help/en/). + +-> **NOTE:** Available since v1.240.0. + +## Example Usage + +Basic Usage + +```terraform +variable "name" { + default = "terraform-example" +} + +provider "alicloud" { + region = "cn-hangzhou" +} + +resource "alicloud_schedulerx_namespace" "CreateNameSpace" { + namespace_name = var.name + description = var.name +} + +resource "alicloud_schedulerx_app_group" "default" { + max_jobs = "100" + monitor_contacts_json = jsonencode([{ "userName" : "name1", "userPhone" : "89756******" }, { "userName" : "name2", "ding" : "http://www.example.com" }]) + delete_jobs = "false" + app_type = "1" + namespace_source = "schedulerx" + group_id = "example-appgroup-pop-autoexample" + namespace_name = "default" + description = var.name + monitor_config_json = jsonencode({ "sendChannel" : "sms,ding" }) + app_version = "1" + app_name = "example-appgroup-pop-autoexample" + namespace = alicloud_schedulerx_namespace.CreateNameSpace.namespace_uid + enable_log = "false" + schedule_busy_workers = "false" +} + +resource "alicloud_schedulerx_job" "default" { + timezone = "GTM+7" + status = "Enable" + max_attempt = "0" + description = var.name + parameters = "hello word" + job_name = var.name + max_concurrency = "1" + time_config { + data_offset = "1" + time_expression = "100000" + time_type = "3" + calendar = "workday" + } + map_task_xattrs { + task_max_attempt = "1" + task_attempt_interval = "1" + consumer_size = "5" + queue_size = "10000" + dispatcher_size = "5" + page_size = "100" + } + namespace = alicloud_schedulerx_namespace.CreateNameSpace.namespace_uid + group_id = alicloud_schedulerx_app_group.default.group_id + job_type = "java" + job_monitor_info { + contact_info { + user_phone = "12345678910" + user_name = "tangtao-1" + ding = "https://alidocs.dingtalk.com" + user_mail = "12345678@xx.com" + } + contact_info { + user_phone = "12345678910" + user_name = "tangtao-2" + ding = "https://alidocs.dingtalk.com1" + user_mail = "123456789@xx.com" + } + monitor_config { + timeout = "7200" + send_channel = "sms" + timeout_kill_enable = true + timeout_enable = true + fail_enable = true + miss_worker_enable = true + } + } + class_name = "com.aliyun.schedulerx.example.processor.SimpleJob" + namespace_source = "schedulerx" + attempt_interval = "30" + fail_times = "1" + execute_mode = "batch" +} +``` + +## Argument Reference + +The following arguments are supported: +* `attempt_interval` - (Optional, Int) Error retry interval, unit s, default value 30. +* `class_name` - (Optional) Full path of the task interface class. + + This field is available only when your task is of the Java task type. +* `content` - (Optional) The script code of the python, shell, and go task types. +* `description` - (Optional) Task description. +* `execute_mode` - (Required) Task execution mode, the possible results are as follows: + - `standalone`: stand-alone operation + - `broadcast`: broadcast running + - `parallel`: parallel computing + - `grid`: Memory grid + - `batch`: Grid Computing + - `shard`: shard running +* `fail_times` - (Optional, Int) Number of consecutive failed alarms +* `group_id` - (Required, ForceNew) The application ID, which is obtained from the **application management** page of the console. +* `job_monitor_info` - (Optional, List) Task monitoring information See [`job_monitor_info`](#job_monitor_info) below. +* `job_name` - (Required) JobName +* `job_type` - (Required, ForceNew) Job Type +* `map_task_xattrs` - (Optional, List) Advanced configuration, limited to parallel computing, memory grid, and grid computing. See [`map_task_xattrs`](#map_task_xattrs) below. +* `max_attempt` - (Optional, Int) The maximum number of error retries, which is set based on business requirements. The default value is 0. +* `max_concurrency` - (Optional) The maximum number of instances running at the same time. The default value is 1, that is, the last trigger is not completed, and the next trigger will not be performed even at the running time. +* `namespace` - (Required, ForceNew) Namespace, which is obtained on the `Namespace` page of the console. +* `namespace_source` - (Optional) Special third parties are required. +* `parameters` - (Optional) User-defined parameters, which can be obtained at runtime. +* `status` - (Optional, Computed) Task status. The values are as follows: + - `1`: Enabled and can be triggered normally. + - `0`: Disabled and will not be triggered. +* `success_notice_enable` - (Optional) Success Notification Switch +* `task_dispatch_mode` - (Optional) Advanced configuration of parallel grid tasks, push model or pull model +* `template` - (Optional) K8s task type custom task template +* `time_config` - (Required, List) Time configuration information See [`time_config`](#time_config) below. +* `timezone` - (Optional) Time Zone +* `x_attrs` - (Optional, Computed) Task Extension Field + +### `job_monitor_info` + +The job_monitor_info supports the following: +* `contact_info` - (Optional, List) Contact information. See [`contact_info`](#job_monitor_info-contact_info) below. +* `monitor_config` - (Optional, Computed, List) Alarm switch and threshold configuration. See [`monitor_config`](#job_monitor_info-monitor_config) below. + +### `job_monitor_info-contact_info` + +The job_monitor_info-contact_info supports the following: +* `ding` - (Optional) DingTalk swarm robot webhook address +* `user_mail` - (Optional) User Email Address +* `user_name` - (Optional) The user name +* `user_phone` - (Optional) The user's mobile phone number + +### `job_monitor_info-monitor_config` + +The job_monitor_info-monitor_config supports the following: +* `fail_enable` - (Optional, Computed) Enable failure alarm +* `miss_worker_enable` - (Optional, Computed) Whether no available Machine alarm is on +* `send_channel` - (Optional, Computed) Alarm sending form + - sms: sms alarm + - phone: phone alarm + - mail: mail alarm + - webhook:webhook alarm +* `timeout` - (Optional, Computed, Int) Timeout threshold, unit s, default 7200. +* `timeout_enable` - (Optional, Computed) Time-out alarm switch. The values are as follows: + - `true`: On + - `false`: closed +* `timeout_kill_enable` - (Optional, Computed) The trigger switch is terminated by timeout and is turned off by default. + - `true`: On + - `false`: closed + +### `map_task_xattrs` + +The map_task_xattrs supports the following: +* `consumer_size` - (Optional, Int) The number of threads to execute a single trigger. The default value is 5. +* `dispatcher_size` - (Optional, Int) The number of subtask distribution threads. The default value is 5. +* `page_size` - (Optional, Int) The number of sub-tasks pulled by a parallel task at a time. The default value is 100. +* `queue_size` - (Optional, Int) The upper limit of the sub-task queue cache. The default value is 10000. +* `task_attempt_interval` - (Optional, Int) Subtask failure retry interval. +* `task_max_attempt` - (Optional, Int) The number of failed sub-task retries. + +### `time_config` + +The time_config supports the following: +* `calendar` - (Optional) The cron type can optionally fill in a custom calendar. +* `data_offset` - (Optional, Int) Cron type can choose time offset, unit s. +* `time_expression` - (Optional, Computed) Time expressions. Currently, the following types of time expressions are supported: + - `api`: No time expression. + - `fix_rate`: the specific fixed frequency value. For example, 30 indicates that the frequency is triggered every 30 seconds. + - `cron`: a standard cron expression. + - `second_delay`: The number of seconds to be delayed (1s to 60s). +* `time_type` - (Required, Int) Time configuration type. Currently, the following time types are supported: + - `1`:cron + - `3`:fix_rate + - `4`:second_delay + - `100`:api + +## Attributes Reference + +The following attributes are exported: +* `id` - The ID of the resource supplied above.The value is formulated as `::`. +* `job_id` - JobId + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration-0-11/resources.html#timeouts) for certain actions: +* `create` - (Defaults to 5 mins) Used when create the Job. +* `delete` - (Defaults to 5 mins) Used when delete the Job. +* `update` - (Defaults to 5 mins) Used when update the Job. + +## Import + +Schedulerx Job can be imported using the id, e.g. + +```shell +$ terraform import alicloud_schedulerx_job.example :: +``` \ No newline at end of file diff --git a/website/docs/r/schedulerx_namespace.html.markdown b/website/docs/r/schedulerx_namespace.html.markdown index a83885996501..0653dee58029 100644 --- a/website/docs/r/schedulerx_namespace.html.markdown +++ b/website/docs/r/schedulerx_namespace.html.markdown @@ -2,57 +2,60 @@ subcategory: "Schedulerx" layout: "alicloud" page_title: "Alicloud: alicloud_schedulerx_namespace" -sidebar_current: "docs-alicloud-resource-schedulerx-namespace" -description: |- - Provides a Alicloud Schedulerx Namespace resource. +description: |- + Provides a Alicloud Schedulerx Namespace resource. --- -# alicloud\_schedulerx\_namespace +# alicloud_schedulerx_namespace Provides a Schedulerx Namespace resource. -For information about Schedulerx Namespace and how to use it, see [What is Namespace](https://help.aliyun.com/document_detail/206088.html). --> **NOTE:** Available in v1.173.0+. + +For information about Schedulerx Namespace and how to use it, see [What is Namespace](https://www.alibabacloud.com/help/en/schedulerx/schedulerx-serverless/developer-reference/api-schedulerx2-2019-04-30-listnamespaces). + +-> **NOTE:** Available since v1.173.0. ## Example Usage Basic Usage - - ```terraform -resource "alicloud_schedulerx_namespace" "example" { - namespace_name = "example_value" +variable "name" { + default = "terraform-example" } +provider "alicloud" { + region = "cn-hangzhou" +} + + +resource "alicloud_schedulerx_namespace" "default" { + namespace_name = var.name + description = var.name +} ``` +### Deleting `alicloud_schedulerx_namespace` or removing it from your configuration + +Terraform cannot destroy resource `alicloud_schedulerx_namespace`. Terraform will remove this resource from the state file, however resources may remain. + ## Argument Reference The following arguments are supported: - -* `description` - (Optional) The description of the resource. -* `namespace_name` - (Required) The name of the resource. +* `description` - (Optional, ForceNew) Namespace description. +* `namespace_name` - (Required, ForceNew) Namespace name. +* `namespace_uid` - (Optional, ForceNew, Computed, Available since v1.240.0) Namespace uid. ## Attributes Reference The following attributes are exported: +* `id` - The ID of the resource supplied above. -* `id` - The resource ID in terraform of Namespace. Its value is same as `namespace_id`. - -### Timeouts +## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration-0-11/resources.html#timeouts) for certain actions: - -* `create` - (Defaults to 1 mins) Used when create the resource. -* `update` - (Defaults to 1 mins) Used when update the resource. - - +* `create` - (Defaults to 5 mins) Used when create the Namespace. ## Import