-
Notifications
You must be signed in to change notification settings - Fork 154
/
resource_huaweicloud_fgs_function.go
1393 lines (1284 loc) · 41.3 KB
/
resource_huaweicloud_fgs_function.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fgs
import (
"context"
"fmt"
"log"
"regexp"
"strconv"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/chnsz/golangsdk"
"github.com/chnsz/golangsdk/openstack/fgs/v2/aliases"
"github.com/chnsz/golangsdk/openstack/fgs/v2/function"
"github.com/chnsz/golangsdk/openstack/fgs/v2/versions"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/common"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
)
// @API FunctionGraph POST /v2/{project_id}/fgs/functions
// @API FunctionGraph GET /v2/{project_id}/fgs/functions/{function_urn}/config
// @API FunctionGraph GET /v2/{project_id}/fgs/functions/{function_urn}/versions
// @API FunctionGraph POST /v2/{project_id}/fgs/functions/{function_urn}/tags/create
// @API FunctionGraph DELETE /v2/{project_id}/fgs/functions/{function_urn}/tags/delete
// @API FunctionGraph PUT /v2/{project_id}/fgs/functions/{function_urn}/code
// @API FunctionGraph PUT /v2/{project_id}/fgs/functions/{function_urn}/config
// @API FunctionGraph PUT /v2/{project_id}/fgs/functions/{function_urn}/config-max-instance
// @API FunctionGraph GET /v2/{project_id}/fgs/functions/{function_urn}/aliases
// @API FunctionGraph POST /v2/{project_id}/fgs/functions/{function_urn}/aliases
// @API FunctionGraph DELETE /v2/{project_id}/fgs/functions/{function_urn}/aliases/{alias_name}
// @API FunctionGraph DELETE /v2/{project_id}/fgs/functions/{function_urn}
// @API FunctionGraph PUT /v2/{project_id}/fgs/functions/{function_urn}/reservedinstances
// @API FunctionGraph GET /v2/{project_id}/fgs/functions/reservedinstanceconfigs
func ResourceFgsFunctionV2() *schema.Resource {
return &schema.Resource{
CreateContext: resourceFgsFunctionCreate,
ReadContext: resourceFgsFunctionRead,
UpdateContext: resourceFgsFunctionUpdate,
DeleteContext: resourceFgsFunctionDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"memory_size": {
Type: schema.TypeInt,
Required: true,
},
"runtime": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"timeout": {
Type: schema.TypeInt,
Required: true,
},
"code_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"handler": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `schema: Required; The entry point of the function.`,
},
"functiongraph_version": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"v1", "v2",
}, false), // The current default value is v1, which may be adjusted in the future.
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"package": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"app"},
Deprecated: "use app instead",
},
"app": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"package"},
Description: "schema: Required",
},
"code_url": {
Type: schema.TypeString,
Optional: true,
},
"code_filename": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"user_data": {
Type: schema.TypeString,
Optional: true,
},
"encrypted_user_data": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"xrole": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"agency"},
Deprecated: "use agency instead",
},
"agency": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"xrole"},
},
"app_agency": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"func_code": {
Type: schema.TypeString,
Optional: true,
StateFunc: utils.DecodeHashAndHexEncode,
},
"depend_list": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"initializer_handler": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"initializer_timeout": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"enterprise_project_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
RequiredWith: []string{"network_id"},
},
"network_id": {
Type: schema.TypeString,
Optional: true,
RequiredWith: []string{"vpc_id"},
},
"dns_list": {
Type: schema.TypeString,
Optional: true,
Computed: true,
RequiredWith: []string{"vpc_id"},
},
"mount_user_id": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"mount_user_group_id": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"log_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
RequiredWith: []string{
"log_stream_id", "log_group_name", "log_stream_name"},
},
"log_stream_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
RequiredWith: []string{"log_group_id"},
},
"log_group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
RequiredWith: []string{"log_group_id"},
},
"log_stream_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
RequiredWith: []string{"log_group_id"},
},
"func_mounts": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"mount_type": {
Type: schema.TypeString,
Required: true,
},
"mount_resource": {
Type: schema.TypeString,
Required: true,
},
"mount_share_path": {
Type: schema.TypeString,
Required: true,
},
"local_mount_path": {
Type: schema.TypeString,
Required: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"custom_image": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"url": {
Type: schema.TypeString,
Required: true,
Description: "Specifies the URL of SWR image.",
},
"command": {
Type: schema.TypeString,
Optional: true,
Description: "Specifies the startup commands of the SWR image.",
},
"args": {
Type: schema.TypeString,
Optional: true,
Description: "Specifies the command line arguments used to start the SWR image.",
},
"working_dir": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Specifies the working directory of the SWR image.",
},
"user_id": {
Type: schema.TypeString,
Optional: true,
Description: "schema: Internal; Specifies the user ID for running the image.",
},
"user_group_id": {
Type: schema.TypeString,
Optional: true,
Description: "schema: Internal; Specifies the user group ID for running the image.",
},
},
},
ConflictsWith: []string{
"code_type",
},
},
"max_instance_num": {
// The original type of this parameter is int, but its zero value is meaningful.
// So, the following types of parameter passing are realized through the logic of terraform's implicit
// conversion of int:
// + -1: the number of instances is unlimited.
// + 0: this function is disabled.
// + (0, +1000]: Specific value (2023.06.26).
// + empty: keep the default (latest updated) value.
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(`^\-?\d+$`),
`invalid value of maximum instance number, want an integer number or integer string.`),
},
"versions": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "The version name.",
},
"aliases": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "The name of the version alias.",
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: "The description of the version alias.",
},
},
},
Description: "The aliases management for specified version.",
},
},
},
Description: "The versions management of the function.",
},
"tags": common.TagsSchema(),
"reserved_instances": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"qualifier_type": {
Type: schema.TypeString,
Required: true,
},
"qualifier_name": {
Type: schema.TypeString,
Required: true,
},
"count": {
Type: schema.TypeInt,
Required: true,
},
"idle_mode": {
Type: schema.TypeBool,
Optional: true,
},
"tactics_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: tracticsConfigsSchema(),
},
},
},
},
// The value in the api document is -1 to 1000, After confirmation, when the parameter set to -1 or 0,
// the actual number of concurrent requests is 1, so the value range is set to 1 to 1000, and the document
// will be modified later (2024.02.29).
"concurrency_num": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"gpu_memory": {
Type: schema.TypeInt,
Optional: true,
RequiredWith: []string{"gpu_type"},
},
"gpu_type": {
Type: schema.TypeString,
Optional: true,
RequiredWith: []string{"gpu_memory"},
},
// Currently, the "pre_stop_timeout" and "pre_stop_timeout" are not visible on the page,
// so they are temporarily used as internal parameters.
"pre_stop_handler": {
Type: schema.TypeString,
Optional: true,
Description: "schema: Internal; Specifies the pre-stop handler of a function.",
},
"pre_stop_timeout": {
Type: schema.TypeInt,
Optional: true,
Description: "schema: Internal; Specifies the maximum duration that the function can be initialized.",
},
"version": {
Type: schema.TypeString,
Computed: true,
},
"urn": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func tracticsConfigsSchema() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
"cron_configs": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"cron": {
Type: schema.TypeString,
Required: true,
},
"count": {
Type: schema.TypeInt,
Required: true,
},
"start_time": {
Type: schema.TypeInt,
Required: true,
},
"expired_time": {
Type: schema.TypeInt,
Required: true,
},
},
},
},
"metric_configs": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"type": {
Type: schema.TypeString,
Required: true,
},
"threshold": {
Type: schema.TypeInt,
Required: true,
},
"min": {
Type: schema.TypeInt,
Required: true,
},
},
},
},
},
}
}
func buildCustomImage(imageConfig []interface{}) *function.CustomImage {
if len(imageConfig) < 1 {
return nil
}
cfg := imageConfig[0].(map[string]interface{})
return &function.CustomImage{
Enabled: true,
Image: cfg["url"].(string),
Command: cfg["command"].(string),
Args: cfg["args"].(string),
WorkingDir: cfg["working_dir"].(string),
UserId: cfg["user_id"].(string),
UserGroupId: cfg["user_group_id"].(string),
}
}
func buildFgsFunctionParameters(d *schema.ResourceData, cfg *config.Config) (function.CreateOpts, error) {
// check app and package
app, appOk := d.GetOk("app")
pkg, pkgOk := d.GetOk("package")
if !appOk && !pkgOk {
return function.CreateOpts{}, fmt.Errorf("one of app or package must be configured")
}
packV := ""
if appOk {
packV = app.(string)
} else {
packV = pkg.(string)
}
// get value from agency or xrole (xrole is deplicated)
agencyV := ""
if v, ok := d.GetOk("agency"); ok {
agencyV = v.(string)
} else if v, ok := d.GetOk("xrole"); ok {
agencyV = v.(string)
}
result := function.CreateOpts{
FuncName: d.Get("name").(string),
Type: d.Get("functiongraph_version").(string),
Package: packV,
CodeType: d.Get("code_type").(string),
CodeUrl: d.Get("code_url").(string),
Description: d.Get("description").(string),
CodeFilename: d.Get("code_filename").(string),
Handler: d.Get("handler").(string),
MemorySize: d.Get("memory_size").(int),
Runtime: d.Get("runtime").(string),
Timeout: d.Get("timeout").(int),
UserData: d.Get("user_data").(string),
EncryptedUserData: d.Get("encrypted_user_data").(string),
Xrole: agencyV,
EnterpriseProjectID: cfg.GetEnterpriseProjectID(d),
CustomImage: buildCustomImage(d.Get("custom_image").([]interface{})),
GPUMemory: d.Get("gpu_memory").(int),
GPUType: d.Get("gpu_type").(string),
PreStopHandler: d.Get("pre_stop_handler").(string),
PreStopTimeout: d.Get("pre_stop_timeout").(int),
}
if v, ok := d.GetOk("func_code"); ok {
funcCode := function.FunctionCodeOpts{
File: utils.TryBase64EncodeString(v.(string)),
}
result.FuncCode = &funcCode
}
if v, ok := d.GetOk("log_group_id"); ok {
logConfig := function.FuncLogConfig{
GroupId: v.(string),
StreamId: d.Get("log_stream_id").(string),
GroupName: d.Get("log_group_name").(string),
StreamName: d.Get("log_stream_name").(string),
}
result.LogConfig = &logConfig
}
return result, nil
}
func resourceFgsFunctionCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
fgsClient, err := cfg.FgsV2Client(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating FunctionGraph v2 client: %s", err)
}
createOpts, err := buildFgsFunctionParameters(d, cfg)
if err != nil {
return diag.FromErr(err)
}
log.Printf("[DEBUG] Create Options: %#v", createOpts)
f, err := function.Create(fgsClient, createOpts).Extract()
if err != nil {
return diag.Errorf("error creating function: %s", err)
}
// The "func_urn" is the unique identifier of the function
// in terraform, we convert to id, not using FuncUrn
d.SetId(f.FuncUrn)
urn := resourceFgsFunctionUrn(d.Id())
// lintignore:R019
if d.HasChanges("vpc_id", "func_mounts", "app_agency", "initializer_handler", "initializer_timeout", "concurrency_num") {
err := resourceFgsFunctionMetadataUpdate(fgsClient, urn, d)
if err != nil {
return diag.FromErr(err)
}
}
if d.HasChange("depend_list") {
err := resourceFgsFunctionCodeUpdate(fgsClient, urn, d)
if err != nil {
return diag.FromErr(err)
}
}
if strNum, ok := d.GetOk("max_instance_num"); ok {
// The integer string of the maximum instance number has been already checked in the schema validation.
maxInstanceNum, _ := strconv.Atoi(strNum.(string))
_, err = function.UpdateMaxInstanceNumber(fgsClient, urn, maxInstanceNum)
if err != nil {
return diag.FromErr(err)
}
}
if tagList, ok := d.GetOk("tags"); ok {
opts := function.TagsActionOpts{
Tags: utils.ExpandResourceTags(tagList.(map[string]interface{})),
}
if err := function.CreateResourceTags(fgsClient, d.Id(), opts); err != nil {
return diag.Errorf("failed to add tags to FunctionGraph function (%s): %s", d.Id(), err)
}
}
if err = createFunctionVersions(fgsClient, urn, d.Get("versions").(*schema.Set)); err != nil {
return diag.Errorf("error creating function versions: %s", err)
}
if d.HasChanges("reserved_instances") {
if err = updateReservedInstanceConfig(fgsClient, d); err != nil {
return diag.FromErr(err)
}
}
return resourceFgsFunctionRead(ctx, d, meta)
}
func createFunctionVersions(client *golangsdk.ServiceClient, functionUrn string, versionSet *schema.Set) error {
for _, v := range versionSet.List() {
version := v.(map[string]interface{})
versionNum := version["name"].(string) // The version name, also name as the version number.
if versionNum != "latest" {
createOpts := versions.CreateOpts{
FunctionUrn: functionUrn,
Version: versionNum,
}
_, err := versions.Create(client, createOpts)
if err != nil {
return err
}
}
// In the future, the function will support manage multiple versions, and will add the corresponding logic to
// create versions based on the related API (Create) in this place.
aliasCfg := version["aliases"].([]interface{})
for _, val := range aliasCfg {
alias := val.(map[string]interface{})
opt := aliases.CreateOpts{
FunctionUrn: functionUrn,
Name: alias["name"].(string),
Version: versionNum,
Description: alias["description"].(string),
}
_, err := aliases.Create(client, opt)
if err != nil {
return err
}
}
}
return nil
}
func setFgsFunctionApp(d *schema.ResourceData, app string) error {
if _, ok := d.GetOk("app"); ok {
return d.Set("app", app)
}
return d.Set("package", app)
}
func setFgsFunctionAgency(d *schema.ResourceData, agency string) error {
if _, ok := d.GetOk("agency"); ok {
return d.Set("agency", agency)
}
return d.Set("xrole", agency)
}
func setFgsFunctionVpcAccess(d *schema.ResourceData, funcVpc function.FuncVpc) error {
mErr := multierror.Append(
d.Set("vpc_id", funcVpc.VpcId),
d.Set("network_id", funcVpc.SubnetId),
)
if err := mErr.ErrorOrNil(); err != nil {
return fmt.Errorf("error setting vault fields: %s", err)
}
return nil
}
func setFuncionMountConfig(d *schema.ResourceData, mountConfig function.MountConfig) error {
// set mount_config
if mountConfig.MountUser != (function.MountUser{}) {
funcMounts := make([]map[string]string, 0, len(mountConfig.FuncMounts))
for _, v := range mountConfig.FuncMounts {
funcMount := map[string]string{
"mount_type": v.MountType,
"mount_resource": v.MountResource,
"mount_share_path": v.MountSharePath,
"local_mount_path": v.LocalMountPath,
"status": v.Status,
}
funcMounts = append(funcMounts, funcMount)
}
mErr := multierror.Append(
d.Set("func_mounts", funcMounts),
d.Set("mount_user_id", mountConfig.MountUser.UserId),
d.Set("mount_user_group_id", mountConfig.MountUser.UserGroupId),
)
if err := mErr.ErrorOrNil(); err != nil {
return fmt.Errorf("error setting vault fields: %s", err)
}
}
return nil
}
func flattenFgsCustomImage(imageConfig function.CustomImage) []map[string]interface{} {
if (imageConfig != function.CustomImage{}) {
return []map[string]interface{}{
{
"url": imageConfig.Image,
"command": imageConfig.Command,
"args": imageConfig.Args,
"working_dir": imageConfig.WorkingDir,
"user_id": imageConfig.UserId,
"user_group_id": imageConfig.UserGroupId,
},
}
}
return nil
}
func queryFunctionVersions(client *golangsdk.ServiceClient, functionUrn string) ([]string, error) {
queryOpts := versions.ListOpts{
FunctionUrn: functionUrn,
}
versionList, err := versions.List(client, queryOpts)
if err != nil {
return nil, fmt.Errorf("error querying version list for the specified function URN: %s", err)
}
// The length of the function version list is at least 1 (when creating a function, a version named latest is
// created by default).
result := make([]string, len(versionList))
for i, version := range versionList {
result[i] = version.Version
}
return result, nil
}
func queryFunctionAliases(client *golangsdk.ServiceClient, functionUrn string) (map[string][]interface{}, error) {
aliasList, err := aliases.List(client, functionUrn)
if err != nil {
return nil, fmt.Errorf("error querying alias list for the specified function URN: %s", err)
}
// Multiple version aliases may exist in the future.
result := make(map[string][]interface{})
for _, v := range aliasList {
result[v.Version] = append(result[v.Version], map[string]interface{}{
"name": v.Name,
"description": v.Description,
})
}
return result, nil
}
func parseFunctionVersions(client *golangsdk.ServiceClient, functionUrn string) ([]map[string]interface{}, error) {
versionList, err := queryFunctionVersions(client, functionUrn)
if err != nil {
return nil, err
}
aliasesConfig, err := queryFunctionAliases(client, functionUrn)
if err != nil {
return nil, err
}
result := make([]map[string]interface{}, 0, len(versionList))
for _, versionNum := range versionList {
version := map[string]interface{}{
"name": versionNum, // The version name, also name as the version number.
}
if v, ok := aliasesConfig[versionNum]; ok {
version["aliases"] = v
} else if versionNum == "latest" {
// If no alias is set for the default version, the corresponding structure object is not saved.
continue
}
result = append(result, version)
}
return result, nil
}
func flattenTracticsConfigs(policyConfig function.TacticsConfigObj) []map[string]interface{} {
if len(policyConfig.CronConfigs) == 0 && len(policyConfig.MetricConfigs) == 0 {
return nil
}
cronConfigRst := make([]map[string]interface{}, len(policyConfig.CronConfigs))
for i, v := range policyConfig.CronConfigs {
cronConfigRst[i] = map[string]interface{}{
"name": v.Name,
"cron": v.Cron,
"count": v.Count,
"start_time": v.StartTime,
"expired_time": v.ExpiredTime,
}
}
metricConfigs := make([]map[string]interface{}, len(policyConfig.MetricConfigs))
for i, v := range policyConfig.MetricConfigs {
metricConfigs[i] = map[string]interface{}{
"name": v.Name,
"type": v.Type,
"threshold": v.Threshold,
"min": v.Min,
}
}
return []map[string]interface{}{
{
"cron_configs": cronConfigRst,
"metric_configs": metricConfigs,
},
}
}
func getReservedInstanceConfig(c *golangsdk.ServiceClient, d *schema.ResourceData) ([]map[string]interface{}, error) {
opts := function.ListReservedInstanceConfigOpts{
FunctionUrn: d.Id(),
}
reservedInstances, err := function.ListReservedInstanceConfigs(c, opts)
if err != nil {
return nil, fmt.Errorf("error getting list of the function reserved instance config: %s", err)
}
result := make([]map[string]interface{}, len(reservedInstances))
for i, v := range reservedInstances {
result[i] = map[string]interface{}{
"count": v.MinCount,
"idle_mode": v.IdleMode,
"qualifier_name": v.QualifierName,
"qualifier_type": v.QualifierType,
"tactics_config": flattenTracticsConfigs(v.TacticsConfig),
}
}
return result, nil
}
func getConcurrencyNum(concurrencyNum *int) int {
return *concurrencyNum
}
func resourceFgsFunctionRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
fgsClient, err := cfg.FgsV2Client(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating FunctionGraph client: %s", err)
}
functionUrn := resourceFgsFunctionUrn(d.Id())
f, err := function.GetMetadata(fgsClient, functionUrn).Extract()
if err != nil {
return common.CheckDeletedDiag(d, err, "FunctionGraph function")
}
versionConfig, err := parseFunctionVersions(fgsClient, functionUrn)
if err != nil {
// Not all regions support the version related API calls.
log.Printf("[ERROR] Unable to parsing the function versions: %s", err)
}
log.Printf("[DEBUG] Retrieved Function %s: %+v", functionUrn, f)
mErr := multierror.Append(
d.Set("name", f.FuncName),
d.Set("code_type", f.CodeType),
d.Set("code_url", f.CodeUrl),
d.Set("description", f.Description),
d.Set("code_filename", f.CodeFileName),
d.Set("handler", f.Handler),
d.Set("memory_size", f.MemorySize),
d.Set("runtime", f.Runtime),
d.Set("timeout", f.Timeout),
d.Set("user_data", f.UserData),
d.Set("encrypted_user_data", f.EncryptedUserData),
d.Set("version", f.Version),
d.Set("urn", functionUrn),
d.Set("app_agency", f.AppXrole),
d.Set("depend_list", f.DependVersionList),
d.Set("initializer_handler", f.InitializerHandler),
d.Set("initializer_timeout", f.InitializerTimeout),
d.Set("enterprise_project_id", f.EnterpriseProjectID),
d.Set("functiongraph_version", f.Type),
d.Set("custom_image", flattenFgsCustomImage(f.CustomImage)),
d.Set("max_instance_num", strconv.Itoa(*f.StrategyConfig.Concurrency)),
d.Set("dns_list", f.DomainNames),
d.Set("log_group_id", f.LogGroupId),
d.Set("log_stream_id", f.LogStreamId),
setFgsFunctionApp(d, f.Package),
setFgsFunctionAgency(d, f.Xrole),
setFgsFunctionVpcAccess(d, f.FuncVpc),
setFuncionMountConfig(d, f.MountConfig),
d.Set("concurrency_num", getConcurrencyNum(f.StrategyConfig.ConcurrencyNum)),
d.Set("versions", versionConfig),
d.Set("gpu_memory", f.GPUMemory),
d.Set("gpu_type", f.GPUType),
d.Set("pre_stop_handler", f.PreStopHandler),
d.Set("pre_stop_timeout", f.PreStopTimeout),
)
reservedInstances, err := getReservedInstanceConfig(fgsClient, d)
if err != nil {
return diag.Errorf("error retrieving function reserved instance: %s", err)
}
mErr = multierror.Append(mErr,
d.Set("reserved_instances", reservedInstances),
)
if err := mErr.ErrorOrNil(); err != nil {
return diag.Errorf("error setting function fields: %s", err)
}
return nil
}
func updateFunctionTags(client *golangsdk.ServiceClient, d *schema.ResourceData) error {
var (
oRaw, nRaw = d.GetChange("tags")
oMap = oRaw.(map[string]interface{})
nMap = nRaw.(map[string]interface{})
functionUrn = d.Id()
)
if len(oMap) > 0 {
opts := function.TagsActionOpts{
Tags: utils.ExpandResourceTags(oMap),
}
if err := function.DeleteResourceTags(client, functionUrn, opts); err != nil {
return fmt.Errorf("failed to delete tags from FunctionGraph function (%s): %s", functionUrn, err)
}
}
if len(nMap) > 0 {
opts := function.TagsActionOpts{
Tags: utils.ExpandResourceTags(nMap),
}
if err := function.CreateResourceTags(client, functionUrn, opts); err != nil {
return fmt.Errorf("failed to add tags to FunctionGraph function (%s): %s", functionUrn, err)
}
}
return nil
}
func deleteFunctionVersions(client *golangsdk.ServiceClient, functionUrn string, versionSet *schema.Set) error {
// In the future, the function will support manage multiple versions.
for _, v := range versionSet.List() {
version := v.(map[string]interface{})
versionNum := version["name"].(string) // The version name, also name as the version number.
if versionNum != "latest" {
// Deletes a function version, also deleting all aliases beneath it.
err := function.Delete(client, fmt.Sprintf("%s:%s", functionUrn, versionNum)).ExtractErr()
if err != nil {
return err
}
continue
}
// Since the latest version cannot be deleted, only the version alias under it can be deleted.
aliasCfg := version["aliases"].([]interface{})
for _, val := range aliasCfg {
alias := val.(map[string]interface{})
err := aliases.Delete(client, functionUrn, alias["name"].(string))
if err != nil {
return err
}
}
}
return nil
}
func updateFunctionVersions(client *golangsdk.ServiceClient, d *schema.ResourceData) error {
var (
functionUrn = resourceFgsFunctionUrn(d.Id())
oldSet, newSet = d.GetChange("versions")
decrease = oldSet.(*schema.Set).Difference(newSet.(*schema.Set))
increase = newSet.(*schema.Set).Difference(oldSet.(*schema.Set))
)
err := deleteFunctionVersions(client, functionUrn, decrease)
if err != nil {
return fmt.Errorf("error deleting function versions: %s", err)
}
err = createFunctionVersions(client, functionUrn, increase)
if err != nil {
return fmt.Errorf("error creating function versions: %s", err)
}
return nil
}
func buildCronConfigs(cronConfigs []interface{}) []function.CronConfigObj {
if len(cronConfigs) < 1 {
return nil