-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathaction.go
More file actions
203 lines (177 loc) · 7.5 KB
/
Copy pathaction.go
File metadata and controls
203 lines (177 loc) · 7.5 KB
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
package runcommand
import (
"context"
"fmt"
"net/http"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-framework/action"
"github.com/hashicorp/terraform-plugin-framework/action/schema"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/services/runcommand/v2api"
"github.com/stackitcloud/stackit-sdk-go/services/runcommand/v2api/wait"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
runCommandUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/runcommand/utils"
providerUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ action.Action = &runCommandAction{}
_ action.ActionWithConfigure = &runCommandAction{}
)
type runCommandModel struct {
ProjectId types.String `tfsdk:"project_id"`
ServerId types.String `tfsdk:"server_id"`
Region types.String `tfsdk:"region"`
CommandTemplateName types.String `tfsdk:"command_template_name"`
Parameters types.Map `tfsdk:"parameters"`
}
// NewRunCommandAction is a helper function to simplify the provider implementation.
func NewRunCommandAction() action.Action {
return &runCommandAction{}
}
// runCommandAction is the action implementation.
type runCommandAction struct {
client *v2api.APIClient
providerData core.ProviderData
}
// Metadata returns the action type name.
func (a *runCommandAction) Metadata(_ context.Context, req action.MetadataRequest, resp *action.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_run_command"
}
// Configure adds the provider configured client to the action.
func (a *runCommandAction) Configure(ctx context.Context, req action.ConfigureRequest, resp *action.ConfigureResponse) {
var ok bool
a.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
a.client = runCommandUtils.ConfigureClient(ctx, &a.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Run command client configured")
}
// Schema defines the schema for the action.
func (a *runCommandAction) Schema(_ context.Context, _ action.SchemaRequest, resp *action.SchemaResponse) {
descriptions := map[string]string{
"main": "Executes a command on an IaaS server using the STACKIT Run Commands API. " + core.ResourceRegionFallbackDocstring,
"project_id": "STACKIT Project ID to which the server belongs.",
"server_id": "The ID of the server on which to execute the command.",
"region": "The region of the server. If not defined, the provider default_region is used.",
"command_template_name": "The name of the command template to execute (e.g. RunShellScript). Available templates can be listed with: `stackit server command template list`",
"parameters": "Optional parameters passed to the command template as key-value pairs.",
}
resp.Schema = schema.Schema{
Description: descriptions["main"],
Attributes: map[string]schema.Attribute{
"project_id": schema.StringAttribute{
Description: descriptions["project_id"],
Required: true,
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"server_id": schema.StringAttribute{
Description: descriptions["server_id"],
Required: true,
Validators: []validator.String{
validate.UUID(),
validate.NoSeparator(),
},
},
"region": schema.StringAttribute{
Description: descriptions["region"],
Optional: true,
},
"command_template_name": schema.StringAttribute{
Description: descriptions["command_template_name"],
Required: true,
},
"parameters": schema.MapAttribute{
Description: descriptions["parameters"],
Optional: true,
ElementType: types.StringType,
},
},
}
}
// Invoke executes the run command action.
func (a *runCommandAction) Invoke(ctx context.Context, req action.InvokeRequest, resp *action.InvokeResponse) {
var model runCommandModel
resp.Diagnostics.Append(req.Config.Get(ctx, &model)...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
serverId := model.ServerId.ValueString()
region := a.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "server_id", serverId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "command_template_name", model.CommandTemplateName.ValueString())
payload, err := toCreatePayload(ctx, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error invoking run command", fmt.Sprintf("Building API payload: %v", err))
return
}
resp.SendProgress(action.InvokeProgressEvent{
Message: fmt.Sprintf("Waiting for agent on server %s to be ready...", serverId),
})
// Retry on 404: the Run Command agent returns 404 until it is installed and ready on the server.
// There is no dedicated readiness endpoint, so we poll CreateCommand until it succeeds.
createResp, err := providerUtils.RetryRequest(ctx,
a.client.DefaultAPI.CreateCommand(ctx, projectId, serverId, region).CreateCommandPayload(*payload).Execute,
providerUtils.RetryConfig{
Attempts: 60,
Delay: 10 * time.Second,
RetryStatusCodes: []int{http.StatusNotFound},
},
)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error invoking run command", fmt.Sprintf("Waiting for agent / calling API: %v", err))
return
}
if createResp == nil || createResp.Id == nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error invoking run command", "API returned empty response or missing command ID")
return
}
commandId := createResp.GetId()
commandIdStr := strconv.Itoa(int(commandId))
ctx = tflog.SetField(ctx, "command_id", commandIdStr)
resp.SendProgress(action.InvokeProgressEvent{
Message: fmt.Sprintf("Command %q submitted (ID: %s). Waiting for completion...", model.CommandTemplateName.ValueString(), commandIdStr),
})
details, err := wait.RunCommandWaitHandler(ctx, a.client.DefaultAPI, projectId, serverId, region, commandIdStr).WaitWithContext(ctx)
if err != nil {
errDetail := fmt.Sprintf("Polling API: %v", err)
if details != nil {
errDetail = fmt.Sprintf("Command %s finished with status %q (exit code: %d).\nOutput:\n%s",
commandIdStr, details.GetStatus(), details.GetExitCode(), details.GetOutput())
}
core.LogAndAddError(ctx, &resp.Diagnostics, "Error waiting for run command", errDetail)
return
}
tflog.Info(ctx, fmt.Sprintf("Run command %s completed successfully", commandIdStr))
}
func toCreatePayload(ctx context.Context, model *runCommandModel) (*v2api.CreateCommandPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
payload := v2api.NewCreateCommandPayload(model.CommandTemplateName.ValueString())
if !model.Parameters.IsNull() && !model.Parameters.IsUnknown() {
params := map[string]string{}
diags := model.Parameters.ElementsAs(ctx, ¶ms, false)
if diags.HasError() {
return nil, fmt.Errorf("converting parameters: %v", diags.Errors())
}
payload.SetParameters(params)
}
return payload, nil
}