This repository has been archived by the owner on Feb 14, 2023. It is now read-only.
/
instances.go
370 lines (334 loc) · 11.8 KB
/
instances.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
/*
Copyright 2016 The Kubernetes 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 cloudstack
import (
"context"
"errors"
"fmt"
"net"
"strings"
"time"
"github.com/xanzy/go-cloudstack/v2/cloudstack"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
cloudprovider "k8s.io/cloud-provider"
"k8s.io/klog"
)
type node struct {
projectID string
name string
environment string
vmID string
}
func (n node) toProviderID() string {
return strings.Join([]string{n.environment, n.projectID, n.vmID}, "/")
}
// NodeAddresses returns the addresses of the specified instance.
func (cs *CSCloud) NodeAddresses(ctx context.Context, name types.NodeName) ([]v1.NodeAddress, error) {
klog.V(4).Infof("NodeAddresses(%v)", name)
node, err := cs.getNodeByName(string(name))
if err != nil {
return nil, fmt.Errorf("error retrieving node by name %q: %v", string(name), err)
}
instance, err := cs.getInstanceForNode(node)
if err != nil {
if err == cloudprovider.InstanceNotFound {
return nil, err
}
return nil, fmt.Errorf("error retrieving node addresses: %v", err)
}
return cs.nodeAddresses(instance)
}
// NodeAddressesByProviderID returns the addresses of the specified instance.
func (cs *CSCloud) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error) {
klog.V(4).Infof("NodeAddressesByProviderID(%v)", providerID)
if providerID == "" {
return nil, fmt.Errorf("empty providerID")
}
instance, err := cs.instanceByProviderID(providerID)
if err != nil {
return nil, err
}
return cs.nodeAddresses(instance)
}
func (cs *CSCloud) nodeAddresses(instance *cloudstack.VirtualMachine) ([]v1.NodeAddress, error) {
if len(instance.Nic) == 0 {
return nil, errors.New("instance does not have an internal IP")
}
var addresses []v1.NodeAddress
var internalAddr string
internalIndex := cs.config.Global.InternalIPIndex
if internalIndex < 0 || internalIndex >= len(instance.Nic) {
klog.V(4).Infof("Unable to use index %v for internal IP, only %v NICs available, falling back to index 0", internalIndex, len(instance.Nic))
internalIndex = 0
}
internalAddr = instance.Nic[internalIndex].Ipaddress
addresses = append(addresses, v1.NodeAddress{Type: v1.NodeInternalIP, Address: internalAddr})
if instance.Hostname != "" {
addresses = append(addresses, v1.NodeAddress{Type: v1.NodeHostName, Address: instance.Hostname})
} else {
names := lookupAddrWithTimeout(internalAddr)
for _, name := range names {
// There's a chance for a PTR record to exist even when the A
// record does not exist or is invalid. This resolves the name
// returned in the PTR record to check if it reeeeaaallllly matches
// the internal IP.
ips := lookupHostWithTimeout(name)
for _, ip := range ips {
if ip == internalAddr {
addresses = append(addresses, v1.NodeAddress{Type: v1.NodeHostName, Address: name})
break
}
}
}
}
externalIndex := cs.config.Global.ExternalIPIndex
if externalIndex != internalIndex && externalIndex >= 0 && externalIndex < len(instance.Nic) {
addresses = append(addresses, v1.NodeAddress{Type: v1.NodeExternalIP, Address: instance.Nic[externalIndex].Ipaddress})
} else {
klog.V(4).Infof("Unable to use index %v for external IP, only %v NICs available and %v is internal IP, ignoring", externalIndex, len(instance.Nic), internalIndex)
}
if instance.Publicip != "" {
addresses = append(addresses, v1.NodeAddress{Type: v1.NodeExternalIP, Address: instance.Publicip})
} else {
// Since there is no sane way to determine the external IP if the host isn't
// using static NAT, we will just fire a log message and omit the external IP.
klog.V(4).Infof("Could not determine the public IP of host %v (%v)", instance.Name, instance.Id)
}
return addresses, nil
}
// InstanceID returns the cloud provider ID of the specified instance.
func (cs *CSCloud) InstanceID(ctx context.Context, name types.NodeName) (string, error) {
klog.V(4).Infof("InstanceID(%v)", name)
node, err := cs.getNodeByName(string(name))
if err != nil {
return "", fmt.Errorf("error retrieving node by name %q: %v", string(name), err)
}
instance, err := cs.getInstanceForNode(node)
if err != nil {
if err == cloudprovider.InstanceNotFound {
return "", err
}
return "", fmt.Errorf("error retrieving instance ID: %v", err)
}
node.vmID = instance.Id
return node.toProviderID(), nil
}
func parseProviderID(instanceID string) (node, error) {
id := strings.TrimPrefix(instanceID, ProviderName+"://")
parts := strings.Split(id, "/")
if len(parts) != 3 {
return node{}, fmt.Errorf("error parsing providerID: %q - %#v", instanceID, parts)
}
return node{
environment: parts[0],
projectID: parts[1],
vmID: parts[2],
}, nil
}
// InstanceType returns the type of the specified instance.
func (cs *CSCloud) InstanceType(ctx context.Context, name types.NodeName) (string, error) {
klog.V(4).Infof("InstanceType(%v)", name)
node, err := cs.getNodeByName(string(name))
if err != nil {
return "", fmt.Errorf("error retrieving node by name %q: %v", string(name), err)
}
instance, err := cs.getInstanceForNode(node)
if err != nil {
if err == cloudprovider.InstanceNotFound {
return "", err
}
return "", fmt.Errorf("error retrieving instance type: %v", err)
}
return instance.Serviceofferingid, nil
}
func (cs *CSCloud) instanceByProviderID(providerID string) (*cloudstack.VirtualMachine, error) {
nodeIDData, err := parseProviderID(providerID)
if err != nil {
return nil, err
}
client, err := cs.clientForEnvironment(nodeIDData.environment)
if err != nil {
return nil, err
}
instance, count, err := client.VirtualMachine.GetVirtualMachineByID(
nodeIDData.vmID,
cloudstack.WithProject(nodeIDData.projectID),
)
if count == 0 {
return nil, cloudprovider.InstanceNotFound
}
if err != nil {
err = fmt.Errorf("error retrieving instance: %v", err)
}
return instance, err
}
// InstanceTypeByProviderID returns the type of the specified instance.
func (cs *CSCloud) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error) {
klog.V(4).Infof("InstanceTypeByProviderID(%v)", providerID)
if providerID == "" {
return "", fmt.Errorf("empty providerID")
}
instance, err := cs.instanceByProviderID(providerID)
if err != nil {
return "", err
}
return instance.Serviceofferingname, nil
}
// AddSSHKeyToAllInstances is currently not implemented.
func (cs *CSCloud) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error {
klog.V(4).Infof("AddSSHKeyToAllInstances(%v, %v)", user, keyData)
return errors.New("AddSSHKeyToAllInstances not implemented")
}
// CurrentNodeName returns the name of the node we are currently running on.
func (cs *CSCloud) CurrentNodeName(ctx context.Context, hostname string) (types.NodeName, error) {
klog.V(4).Infof("CurrentNodeName(%v)", hostname)
return types.NodeName(hostname), nil
}
// InstanceExistsByProviderID returns if the instance still exists.
func (cs *CSCloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {
klog.V(4).Infof("InstanceExistsByProviderID(%v)", providerID)
if providerID == "" {
return false, fmt.Errorf("empty providerID")
}
_, err := cs.instanceByProviderID(providerID)
if err != nil {
if err == cloudprovider.InstanceNotFound {
err = nil
}
return false, err
}
return true, nil
}
// InstanceShutdownByProviderID returns true if the instance is shutdown in cloudprovider
func (cs *CSCloud) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error) {
klog.V(4).Infof("InstanceShutdownByProviderID(%v)", providerID)
if providerID == "" {
return false, fmt.Errorf("empty providerID")
}
instance, err := cs.instanceByProviderID(providerID)
if err != nil {
return false, err
}
// States from https://github.com/apache/cloudstack/blob/87c43501608a1df72a2f01ed17a522233e6617b0/api/src/main/java/com/cloud/vm/VirtualMachine.java#L45
switch instance.State {
case "Stopping", "Stopped", "Destroyed", "Expunging", "Shutdowned", "Error":
return true, nil
case "Unknown":
return false, errors.New("unknown vm state in cloudstack")
}
return false, nil
}
func (cs *CSCloud) getInstanceForNode(n *node) (*cloudstack.VirtualMachine, error) {
client, err := cs.clientForNode(n)
if err != nil {
return nil, err
}
instance, count, err := client.VirtualMachine.GetVirtualMachineByName(
n.name,
cloudstack.WithProject(n.projectID),
)
if err != nil {
klog.V(4).Infof("getInstanceForNode(%v): Could not find VM: %v", n, err)
if count == 0 {
return nil, cloudprovider.InstanceNotFound
}
return nil, fmt.Errorf("error instance for node %v: %v", n, err)
}
klog.V(4).Infof("getInstanceForNode(%v): Found instance %#v", n, instance)
return instance, nil
}
func (cs *CSCloud) getNodeByName(name string) (*node, error) {
kubeNode, err := cs.kubeClient.CoreV1().Nodes().Get(name, metav1.GetOptions{})
if err != nil {
return nil, err
}
n, err := cs.newNode(kubeNode)
if err != nil {
return nil, err
}
klog.V(4).Infof("getNodeByName(%v): found node: %#v", name, n)
return n, nil
}
func (cs *CSCloud) newNode(kubeNode *v1.Node) (*node, error) {
name := kubeNode.Name
if n, ok := getLabelOrAnnotation(kubeNode.ObjectMeta, cs.config.Global.NodeNameLabel); ok {
name = n
}
environment := cs.environmentForMeta(kubeNode.ObjectMeta)
projectID, err := cs.projectForMeta(kubeNode.ObjectMeta, environment)
if err != nil {
return nil, fmt.Errorf("error processing node %#v: %v", kubeNode, err)
}
n := &node{
projectID: projectID,
environment: environment,
name: name,
vmID: kubeNode.Spec.ProviderID,
}
return n, nil
}
func (cs *CSCloud) clientForNode(n *node) (*cloudstack.CloudStackClient, error) {
return cs.clientForEnvironment(n.environment)
}
func (cs *CSCloud) projectForMeta(meta metav1.ObjectMeta, environment string) (string, error) {
projectID, ok := getLabelOrAnnotation(meta, cs.config.Global.ProjectIDLabel)
if !ok {
if envConfig, ok := cs.config.Environment[environment]; ok {
projectID = envConfig.ProjectID
}
if projectID == "" {
return "", errors.New("no projectID found")
}
}
return projectID, nil
}
func (cs *CSCloud) environmentForMeta(meta metav1.ObjectMeta) string {
environment, _ := getLabelOrAnnotation(meta, cs.config.Global.EnvironmentLabel)
if environment == "" && len(cs.environments) == 1 {
for k := range cs.environments {
environment = k
}
}
return environment
}
func (cs *CSCloud) clientForEnvironment(environment string) (*cloudstack.CloudStackClient, error) {
client := cs.environments[environment].client
if client == nil {
return nil, fmt.Errorf("unable to retrieve client for environment %v, available environments: %#v", environment, cs.environments)
}
return client, nil
}
func getLabelOrAnnotation(obj metav1.ObjectMeta, name string) (string, bool) {
if name == "" {
return "", false
}
if n, ok := obj.Labels[name]; ok {
return n, true
}
n, ok := obj.Annotations[name]
return n, ok
}
func lookupAddrWithTimeout(addr string) []string {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
names, _ := net.DefaultResolver.LookupAddr(ctx, addr)
return names
}
func lookupHostWithTimeout(host string) []string {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
ips, _ := net.DefaultResolver.LookupHost(ctx, host)
return ips
}