-
Notifications
You must be signed in to change notification settings - Fork 124
/
provider.go
346 lines (284 loc) · 10.6 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
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
/*
Copyright 2020 The Machine Controller Authors.
Licensed under the Apache 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://www.apache.org/licenses/LICENSE-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 anexia
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
anx "github.com/anexia-it/go-anxcloud/pkg"
anxclient "github.com/anexia-it/go-anxcloud/pkg/client"
anxvm "github.com/anexia-it/go-anxcloud/pkg/vsphere/provisioning/vm"
"github.com/kubermatic/machine-controller/pkg/apis/cluster/common"
"github.com/kubermatic/machine-controller/pkg/apis/cluster/v1alpha1"
"github.com/kubermatic/machine-controller/pkg/cloudprovider/common/ssh"
cloudprovidererrors "github.com/kubermatic/machine-controller/pkg/cloudprovider/errors"
"github.com/kubermatic/machine-controller/pkg/cloudprovider/instance"
anxtypes "github.com/kubermatic/machine-controller/pkg/cloudprovider/provider/anexia/types"
cloudprovidertypes "github.com/kubermatic/machine-controller/pkg/cloudprovider/types"
"github.com/kubermatic/machine-controller/pkg/providerconfig"
providerconfigtypes "github.com/kubermatic/machine-controller/pkg/providerconfig/types"
"k8s.io/apimachinery/pkg/runtime"
k8stypes "k8s.io/apimachinery/pkg/types"
)
type Config struct {
Token string
VlanID string
LocationID string
TemplateID string
CPUs int
Memory int
DiskSize int
}
type provider struct {
configVarResolver *providerconfig.ConfigVarResolver
}
func (p *provider) getConfig(s v1alpha1.ProviderSpec) (*Config, *providerconfigtypes.Config, error) {
if s.Value == nil {
return nil, nil, fmt.Errorf("machine.spec.providerSpec.value is nil")
}
pConfig := providerconfigtypes.Config{}
err := json.Unmarshal(s.Value.Raw, &pConfig)
if err != nil {
return nil, nil, err
}
rawConfig := anxtypes.RawConfig{}
if err = json.Unmarshal(pConfig.CloudProviderSpec.Raw, &rawConfig); err != nil {
return nil, nil, err
}
c := Config{}
c.Token, err = p.configVarResolver.GetConfigVarStringValueOrEnv(rawConfig.Token, anxtypes.AnxTokenEnv)
if err != nil {
return nil, nil, fmt.Errorf("failed to get 'token': %v", err)
}
c.CPUs = rawConfig.CPUs
c.Memory = rawConfig.Memory
c.DiskSize = rawConfig.DiskSize
c.LocationID, err = p.configVarResolver.GetConfigVarStringValue(rawConfig.LocationID)
if err != nil {
return nil, nil, fmt.Errorf("failed to get 'locationID': %v", err)
}
c.TemplateID, err = p.configVarResolver.GetConfigVarStringValue(rawConfig.TemplateID)
if err != nil {
return nil, nil, fmt.Errorf("failed to get 'templateID': %v", err)
}
c.VlanID, err = p.configVarResolver.GetConfigVarStringValue(rawConfig.VlanID)
if err != nil {
return nil, nil, fmt.Errorf("failed to get 'vlanID': %v", err)
}
return &c, &pConfig, nil
}
// New returns an Anexia provider
func New(configVarResolver *providerconfig.ConfigVarResolver) cloudprovidertypes.Provider {
return &provider{configVarResolver: configVarResolver}
}
// AddDefaults adds omitted optional values to the given MachineSpec
func (p *provider) AddDefaults(spec v1alpha1.MachineSpec) (v1alpha1.MachineSpec, error) {
return spec, nil
}
// Validate returns success or failure based according to its ProviderSpec
func (p *provider) Validate(machinespec v1alpha1.MachineSpec) error {
config, _, err := p.getConfig(machinespec.ProviderSpec)
if err != nil {
return fmt.Errorf("failed to parse config: %w", err)
}
if config.Token == "" {
return errors.New("token is missing")
}
if config.CPUs == 0 {
return errors.New("cpu count is missing")
}
if config.DiskSize == 0 {
return errors.New("disk size is missing")
}
if config.Memory == 0 {
return errors.New("memory size is missing")
}
if config.LocationID == "" {
return errors.New("location id is missing")
}
if config.TemplateID == "" {
return errors.New("template id is missing")
}
if config.VlanID == "" {
return errors.New("vlan id is missing")
}
return nil
}
func (p *provider) Get(machine *v1alpha1.Machine, _ *cloudprovidertypes.ProviderData) (instance.Instance, error) {
config, _, err := p.getConfig(machine.Spec.ProviderSpec)
if err != nil {
return nil, newError(common.InvalidConfigurationMachineError, "failed to parse MachineSpec: %v", err)
}
apiClient := getClient(config.Token)
status, err := getStatus(machine.Status.ProviderStatus)
if err != nil {
return nil, newError(common.InvalidConfigurationMachineError, "failed to get machine status: %v", err)
}
if status.InstanceID == "" {
return nil, cloudprovidererrors.ErrInstanceNotFound
}
ctx, cancel := context.WithTimeout(context.Background(), anxtypes.GetRequestTimeout)
defer cancel()
info, err := apiClient.VSphere().Info().Get(ctx, status.InstanceID)
if err != nil {
return nil, fmt.Errorf("failed get machine info: %w", err)
}
return &anexiaInstance{
info: &info,
}, nil
}
func (p *provider) GetCloudConfig(spec v1alpha1.MachineSpec) (string, string, error) {
return "", "", nil
}
// Create creates a cloud instance according to the given machine
func (p *provider) Create(machine *v1alpha1.Machine, providerData *cloudprovidertypes.ProviderData, userdata string) (instance.Instance, error) {
config, _, err := p.getConfig(machine.Spec.ProviderSpec)
if err != nil {
return nil, newError(common.InvalidConfigurationMachineError, "failed to parse MachineSpec: %v", err)
}
apiClient := getClient(config.Token)
ctx, cancel := context.WithTimeout(context.Background(), anxtypes.CreateRequestTimeout)
defer cancel()
status, err := getStatus(machine.Status.ProviderStatus)
if err != nil {
return nil, newError(common.InvalidConfigurationMachineError, "failed to get machine status: %v", err)
}
if status.ProvisioningID == "" {
ips, err := apiClient.VSphere().Provisioning().IPs().GetFree(ctx, config.LocationID, config.VlanID)
if err != nil {
return nil, newError(common.InvalidConfigurationMachineError, "failed to get ip pool: %v", err)
}
if len(ips) < 1 {
return nil, newError(common.InsufficientResourcesMachineError, "no ip address is available for this machine")
}
ipID := ips[0].Identifier
networkInterfaces := []anxvm.Network{{
NICType: anxtypes.VmxNet3NIC,
IPs: []string{ipID},
VLAN: config.VlanID,
}}
vm := apiClient.VSphere().Provisioning().VM().NewDefinition(
config.LocationID,
"templates",
config.TemplateID,
machine.ObjectMeta.Name,
config.CPUs,
config.Memory,
config.DiskSize,
networkInterfaces,
)
vm.Script = base64.StdEncoding.EncodeToString(
[]byte(fmt.Sprintf("anexia: true\n\n%s", userdata)),
)
sshKey, err := ssh.NewKey()
if err != nil {
return nil, newError(common.CreateMachineError, "failed to generate ssh key: %v", err)
}
vm.SSH = sshKey.PublicKey
provisionResponse, err := apiClient.VSphere().Provisioning().VM().Provision(ctx, vm)
if err != nil {
return nil, newError(common.CreateMachineError, "instance provisioning failed: %v", err)
}
status.ProvisioningID = provisionResponse.Identifier
status.IPAllocationID = ipID
if err := updateStatus(machine, status, providerData.Update); err != nil {
return nil, newError(common.UpdateMachineError, "machine status update failed: %v", err)
}
}
instanceID, err := apiClient.VSphere().Provisioning().Progress().AwaitCompletion(ctx, status.ProvisioningID)
if err != nil {
return nil, newError(common.CreateMachineError, "instance provisioning failed: %v", err)
}
status.InstanceID = instanceID
if err := updateStatus(machine, status, providerData.Update); err != nil {
return nil, newError(common.UpdateMachineError, "machine status update failed: %v", err)
}
return p.Get(machine, providerData)
}
func (p *provider) Cleanup(machine *v1alpha1.Machine, _ *cloudprovidertypes.ProviderData) (bool, error) {
config, _, err := p.getConfig(machine.Spec.ProviderSpec)
if err != nil {
return false, newError(common.InvalidConfigurationMachineError, "failed to parse MachineSpec: %v", err)
}
apiClient := getClient(config.Token)
status, err := getStatus(machine.Status.ProviderStatus)
if err != nil {
return false, newError(common.InvalidConfigurationMachineError, "failed to get machine status: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), anxtypes.DeleteRequestTimeout)
defer cancel()
err = apiClient.VSphere().Provisioning().VM().Deprovision(ctx, status.InstanceID, false)
if err != nil {
var respErr *anxclient.ResponseError
// Only error if the error was not "not found"
if !(errors.As(err, &respErr) && respErr.ErrorData.Code == http.StatusNotFound) {
return false, newError(common.DeleteMachineError, "failed to delete machine: %v", err)
}
}
err = apiClient.IPAM().Address().Delete(ctx, status.IPAllocationID)
if err != nil {
var respErr *anxclient.ResponseError
// Only error if the error was not "not found"
if !(errors.As(err, &respErr) && respErr.ErrorData.Code == http.StatusNotFound) {
return false, newError(common.DeleteMachineError, "failed to delete machine ip allocation: %v", err)
}
}
return true, nil
}
func (p *provider) MigrateUID(_ *v1alpha1.Machine, _ k8stypes.UID) error {
return nil
}
func (p *provider) MachineMetricsLabels(machine *v1alpha1.Machine) (map[string]string, error) {
return map[string]string{}, nil
}
func (p *provider) SetMetricsForMachines(machine v1alpha1.MachineList) error {
return nil
}
func getClient(token string) anx.API {
client := anxclient.NewTokenClient(token, nil)
return anx.NewAPI(client)
}
func getStatus(rawStatus *runtime.RawExtension) (*anxtypes.ProviderStatus, error) {
var status anxtypes.ProviderStatus
if rawStatus != nil && rawStatus.Raw != nil {
if err := json.Unmarshal(rawStatus.Raw, &status); err != nil {
return nil, err
}
}
return &status, nil
}
// newError creates a terminal error matching to the provider interface.
func newError(reason common.MachineStatusError, msg string, args ...interface{}) error {
return cloudprovidererrors.TerminalError{
Reason: reason,
Message: fmt.Sprintf(msg, args...),
}
}
func updateStatus(machine *v1alpha1.Machine, status *anxtypes.ProviderStatus, updater cloudprovidertypes.MachineUpdater) error {
rawStatus, err := json.Marshal(status)
if err != nil {
return err
}
err = updater(machine, func(machine *v1alpha1.Machine) {
machine.Status.ProviderStatus = &runtime.RawExtension{
Raw: rawStatus,
}
})
if err != nil {
return err
}
return nil
}