/
machine_scope.go
246 lines (198 loc) · 8.52 KB
/
machine_scope.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
/*
Copyright 2021 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 machine
import (
"context"
"encoding/base64"
"fmt"
"net"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
corev1 "k8s.io/api/core/v1"
"k8s.io/klog"
machinev1 "github.com/openshift/api/machine/v1"
machinev1beta1 "github.com/openshift/api/machine/v1beta1"
alibabav1 "github.com/openshift/cluster-api-provider-alibaba/pkg/apis/alibabacloudprovider/v1"
alibabacloudClient "github.com/openshift/cluster-api-provider-alibaba/pkg/client"
machineapierros "github.com/openshift/machine-api-operator/pkg/controller/machine"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
// MachineScope defines a scope defined around a machine and its cluster.
type machineScope struct {
context.Context
// client for interacting with alibabacloud
alibabacloudClient alibabacloudClient.Client
// api server controller runtime client
client runtimeclient.Client
// machine resource
machine *machinev1beta1.Machine
machineToBePatched runtimeclient.Patch
providerSpec *machinev1.AlibabaCloudMachineProviderConfig
providerStatus *machinev1.AlibabaCloudMachineProviderStatus
}
// machineScopeParams defines the input parameters used to create a new MachineScope.
type machineScopeParams struct {
context.Context
alibabacloudClientBuilder alibabacloudClient.AlibabaCloudClientBuilderFunc
// api server controller runtime client
client runtimeclient.Client
// machine resource
machine *machinev1beta1.Machine
// api server controller runtime client for the openshift-config-managed namespace
configManagedClient runtimeclient.Client
}
// newMachineScope init machineScope instance
func newMachineScope(params machineScopeParams) (*machineScope, error) {
providerSpec, err := alibabav1.ProviderSpecFromRawExtension(params.machine.Spec.ProviderSpec.Value)
if err != nil {
return nil, machineapierros.InvalidMachineConfiguration("failed to get machine config: %v", err)
}
providerStatus, err := alibabav1.ProviderStatusFromRawExtension(params.machine.Status.ProviderStatus)
if err != nil {
return nil, machineapierros.InvalidMachineConfiguration("failed to get machine provider status: %v", err.Error())
}
credentialsSecretName := ""
if providerSpec.CredentialsSecret != nil {
credentialsSecretName = providerSpec.CredentialsSecret.Name
}
aliClient, err := params.alibabacloudClientBuilder(params.client, credentialsSecretName, params.machine.Namespace, providerSpec.RegionID, params.configManagedClient)
if err != nil {
return nil, machineapierros.InvalidMachineConfiguration("failed to create alibabacloud client: %v", err)
}
return &machineScope{
Context: params.Context,
alibabacloudClient: aliClient,
client: params.client,
machine: params.machine,
machineToBePatched: runtimeclient.MergeFrom(params.machine.DeepCopy()),
providerSpec: providerSpec,
providerStatus: providerStatus,
}, nil
}
// Patch patches the machine spec and machine status after reconciling.
func (s *machineScope) patchMachine() error {
klog.V(3).Infof("%v: patching machine", s.machine.GetName())
providerStatus, err := alibabav1.RawExtensionFromProviderStatus(s.providerStatus)
if err != nil {
return machineapierros.InvalidMachineConfiguration("failed to get machine provider status: %v", err)
}
s.machine.Status.ProviderStatus = providerStatus
statusCopy := *s.machine.Status.DeepCopy()
// patch machine
if err := s.client.Patch(context.Background(), s.machine, s.machineToBePatched); err != nil {
klog.Errorf("Failed to patch machine %q: %v", s.machine.GetName(), err)
return err
}
s.machine.Status = statusCopy
// patch status
if err := s.client.Status().Patch(context.Background(), s.machine, s.machineToBePatched); err != nil {
klog.Errorf("Failed to patch machine status %q: %v", s.machine.GetName(), err)
return err
}
return nil
}
// getUserData fetches the user-data from the secret referenced in the Machine's
// provider spec, if one is set.
func (s *machineScope) getUserData() (string, error) {
if s.providerSpec == nil || s.providerSpec.UserDataSecret == nil {
return "", nil
}
userDataSecret := &corev1.Secret{}
objKey := runtimeclient.ObjectKey{
Namespace: s.machine.Namespace,
Name: s.providerSpec.UserDataSecret.Name,
}
if err := s.client.Get(s.Context, objKey, userDataSecret); err != nil {
return "", fmt.Errorf("error getting user data secret %s in namespace %s: %w", s.providerSpec.UserDataSecret.Name, s.providerSpec.GetNamespace(), err)
}
userData, exists := userDataSecret.Data[userDataSecretKey]
if !exists {
return "", fmt.Errorf("secret %v/%v does not have userData field set. thus, no user data applied when creating an instance", s.providerSpec.GetNamespace(), s.providerSpec.UserDataSecret.Name)
}
return base64.StdEncoding.EncodeToString(userData), nil
}
func (s *machineScope) setProviderStatus(instance *ecs.Instance, condition metav1.Condition) error {
klog.Infof("%s: Updating status", s.machine.Name)
// assign value to providerStatus
if instance == nil {
s.providerStatus.InstanceID = nil
s.providerStatus.InstanceState = nil
} else {
s.providerStatus.InstanceID = &instance.InstanceId
s.providerStatus.InstanceState = &instance.Status
}
networkAddresses, err := s.getNetworkAddress(instance)
if err != nil {
klog.Errorf("%s : Error get Network Address :%v", s.machine.Name, err)
return nil
}
s.machine.Status.Addresses = networkAddresses
s.providerStatus.Conditions = setMachineProviderCondition(condition, s.providerStatus.Conditions)
return nil
}
func (s *machineScope) getNetworkAddress(instance *ecs.Instance) ([]corev1.NodeAddress, error) {
klog.Infof("%s : Setting network address", s.machine.Name)
networkAddresses := make([]corev1.NodeAddress, 0)
addresses, err := extractNodeAddressesFromInstance(instance)
if err != nil {
klog.Errorf("%s: Error extracting instance IP addresses: %v", s.machine.Name, err)
return nil, err
}
networkAddresses = append(networkAddresses, addresses...)
networkAddresses = append(networkAddresses, corev1.NodeAddress{
Type: corev1.NodeInternalDNS,
Address: s.machine.GetName(),
})
klog.Infof("%s: finished calculating alibabacloud status", s.machine.Name)
return networkAddresses, nil
}
// extractNodeAddressesFromInstance maps the instance information from ECS to an array of NodeAddresses
func extractNodeAddressesFromInstance(instance *ecs.Instance) ([]corev1.NodeAddress, error) {
if instance == nil {
return nil, fmt.Errorf("the ecs instance is nil")
}
addresses := make([]corev1.NodeAddress, 0)
// handle internal network interfaces
for _, networkInterface := range instance.NetworkInterfaces.NetworkInterface {
// https://github.com/openshift-kni/origin/commit/7db21c1e26a344e25ae1b825d4f21e7bef5c3650
for _, ipv6Address := range networkInterface.Ipv6Sets.Ipv6Set {
if addr := ipv6Address.Ipv6Address; addr != "" {
ip := net.ParseIP(addr)
if ip == nil {
return nil, fmt.Errorf("ECS instance had invalid IPv6 address: %s (%q)", instance.InstanceId, addr)
}
addresses = append(addresses, corev1.NodeAddress{Type: corev1.NodeInternalIP, Address: ip.String()})
}
}
for _, internalIP := range networkInterface.PrivateIpSets.PrivateIpSet {
if ipAddress := internalIP.PrivateIpAddress; ipAddress != "" {
ip := net.ParseIP(ipAddress)
if ip == nil {
return nil, fmt.Errorf("ECS instance had invalid private address: %s (%q)", instance.InstanceId, ipAddress)
}
addresses = append(addresses, corev1.NodeAddress{Type: corev1.NodeInternalIP, Address: ip.String()})
}
}
}
//// TODO: Other IP addresses (multiple ips)?
for _, publicIPAddress := range instance.PublicIpAddress.IpAddress {
if publicIPAddress != "" {
ip := net.ParseIP(publicIPAddress)
if ip == nil {
return nil, fmt.Errorf("ECS instance had invalid public address: %s (%s)", instance.InstanceId, publicIPAddress)
}
addresses = append(addresses, corev1.NodeAddress{Type: corev1.NodeExternalIP, Address: ip.String()})
}
}
return addresses, nil
}