/
provider.go
309 lines (269 loc) · 8.75 KB
/
provider.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
/*
Copyright (c) 2024 Dell Inc., or its subsidiaries. All Rights Reserved.
Licensed under the Mozilla Public License Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://mozilla.org/MPL/2.0/
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package navigator
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"time"
client "github.com/dell/terraform-provider-apex/client/apexclient/client"
jmsClient "github.com/dell/terraform-provider-apex/client/jobsclient/client"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/provider"
"github.com/hashicorp/terraform-plugin-framework/provider/schema"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ provider.Provider = &myProvider{}
)
// New is a helper function to simplify provider server and testing implementation.
func New(version string) func() provider.Provider {
return func() provider.Provider {
return &myProvider{
version: version,
}
}
}
// myProviderModel maps provider schema data to a Go type.
type myProviderModel struct {
Host types.String `tfsdk:"host"`
Token types.String `tfsdk:"token"`
JMSEndpoint types.String `tfsdk:"jms_endpoint"`
}
// myProvider is the provider implementation.
type myProvider struct {
// version is set to the provider version on release, "dev" when the
// provider is built and ran locally, and "test" when running acceptance
// testing.
version string
}
// Clients is the implementation for the API client and JMS client.
type Clients struct {
APIClient *client.APIClient
JMSClient *jmsClient.APIClient
}
// Metadata returns the provider type name.
func (p *myProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "apex_navigator"
resp.Version = p.version
}
// Schema defines the provider-level schema for configuration data.
func (p *myProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"host": schema.StringAttribute{
Optional: true,
},
"token": schema.StringAttribute{
Optional: true,
},
"jms_endpoint": schema.StringAttribute{
Optional: true,
},
},
}
}
// Configure is the method responsible for configuring the provider.
func (p *myProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { //nolint:funlen
// Retrieve provider data from configuration
var config myProviderModel
diags := req.Config.Get(ctx, &config)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// If practitioner provided a configuration value for any of the
// attributes, it must be a known value.
if config.Host.IsUnknown() {
resp.Diagnostics.AddAttributeError(
path.Root("host"),
"Unknown Apex Navigator API Host",
"The provider cannot create the Apex Navigator API client as there is an unknown configuration value for the Apex Navigator API host. "+
"Either target apply the source of the value first, set the value statically in the configuration, or use the CIRRUS_HOST environment variable.",
)
}
if resp.Diagnostics.HasError() {
return
}
// Default values to environment variables, but override
// with Terraform configuration value if set.
jmsEndpoint := os.Getenv("JMS_ENDPOINT")
host := os.Getenv("APEX_NAVIGATOR_HOST")
if !config.Host.IsNull() {
host = config.Host.ValueString()
}
if !config.JMSEndpoint.IsNull() {
jmsEndpoint = config.JMSEndpoint.ValueString()
} else if jmsEndpoint == "" {
jmsEndpoint = config.Host.ValueString()
}
// If any of the expected configurations are missing, return
// errors with provider-specific guidance.
if host == "" {
resp.Diagnostics.AddAttributeError(
path.Root("host"),
"Missing Apex Navigator API Host",
"The provider cannot create the Apex Navigator API client as there is a missing or empty value for the Apex Navigator API host. "+
"Set the host value in the configuration or use the APEX_NAVIGATOR_HOST environment variable. "+
"If either is already set, ensure the value is not empty.",
)
}
if resp.Diagnostics.HasError() {
return
}
hostURL, err := url.Parse(host)
if err != nil {
resp.Diagnostics.AddError(
"Could not parse host URL: "+host,
"Could not parse host URL: "+host,
)
}
jmsURL, err := url.Parse(jmsEndpoint)
if err != nil {
resp.Diagnostics.AddError(
"Could not parse job host URL: "+jmsEndpoint,
"Could not parse job host URL: "+jmsEndpoint,
)
}
if hostURL.Scheme == "" {
resp.Diagnostics.AddError(
"Missing scheme in host URL",
"Missing scheme in host URL: "+host,
)
}
if resp.Diagnostics.HasError() {
return
}
token := ""
if !strings.Contains(host, "localhost") {
token = updateToken(resp)
}
//TODO: Change the token back to config.Token.ValueString() when the refresh token is implemented, change back the .tf config files also
cfg := &client.Configuration{
Host: hostURL.Host,
Scheme: hostURL.Scheme,
HTTPClient: &http.Client{
Transport: &customTransport{
originalTransport: http.DefaultTransport,
token: token,
},
Timeout: time.Second * 10000000,
},
Servers: client.ServerConfigurations{
{
URL: hostURL.Path,
Description: "No description provided",
},
},
}
apiClient := client.NewAPIClient(cfg)
jobCfg := &jmsClient.Configuration{
Host: jmsURL.Host,
Scheme: jmsURL.Scheme,
HTTPClient: &http.Client{
Transport: &customTransport{
originalTransport: http.DefaultTransport,
token: token,
},
},
Servers: jmsClient.ServerConfigurations{
{
URL: jmsURL.Path,
Description: "No description provided",
},
},
}
jobsClient := jmsClient.NewAPIClient(jobCfg)
// Make the cirrus client available during DataSource and Resource
// Make the Apex Navigator client available during DataSource and Resource
// type Configure methods.
resp.DataSourceData = apiClient
resp.ResourceData = Clients{APIClient: apiClient, JMSClient: jobsClient}
// Start a goroutine to update the token periodically
if !strings.Contains(host, "localhost") {
go func() {
for {
// Update the token value
token := updateToken(resp)
// Update the token field of the customTransport struct with the updated value
cfg.HTTPClient.Transport.(*customTransport).token = token
jobCfg.HTTPClient.Transport.(*customTransport).token = token
// Sleep for a certain duration before the next update
time.Sleep(10 * time.Second)
}
}()
}
}
func updateToken(resp *provider.ConfigureResponse) string {
// Update the token value
content, err := os.ReadFile("token_file.txt")
// add an error to log here
if err != nil {
resp.Diagnostics.AddAttributeError(
path.Root("host"),
"Could not read token_file.txt",
"Please update the token_file.txt with the correct unexpired token",
)
}
token := string(content)
return token
}
type customTransport struct {
originalTransport http.RoundTripper
token string
}
func (c *customTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.token))
resp, err := c.originalTransport.RoundTrip(r)
if err != nil {
return nil, err
}
return resp, nil
}
// DataSources defines the data sources implemented in the provider.
func (p *myProvider) DataSources(_ context.Context) []func() datasource.DataSource {
return []func() datasource.DataSource{
NewHostsDataSource,
NewVolumesDataSource,
NewStorageProductsDataSource,
NewPoolsDataSource,
NewClonesDataSource,
NewCloneInstancesDataSource,
NewStorageProductOptionsDataSource,
NewBlockStoragesDataSource,
NewBlockStorageInstanceDataSource,
NewMobilityGroupsDataSource,
NewMobilityGroupInstanceDataSource,
NewMobilityTargetsDataSource,
NewMobilityTargetInstanceDataSource,
}
}
// Resources defines the resources implemented in the provider.
func (p *myProvider) Resources(_ context.Context) []func() resource.Resource {
return []func() resource.Resource{
NewClonesResource,
NewBlockStorageResource,
NewMobilityGroupsResource,
NewMobilityTargetsResource,
NewMobilityGroupsCopyResource,
NewClonesMapResource,
NewClonesUnmapResource,
NewClonesRefreshResource,
}
}