forked from kubicorn/kubicorn
/
instancegroup.go
346 lines (306 loc) · 10.9 KB
/
instancegroup.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 © 2017 The Kubicorn 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 resources
import (
"fmt"
"time"
"strings"
"github.com/kris-nova/kubicorn/apis/cluster"
"github.com/kris-nova/kubicorn/bootstrap"
"github.com/kris-nova/kubicorn/cloud"
"github.com/kris-nova/kubicorn/cutil/compare"
"github.com/kris-nova/kubicorn/cutil/defaults"
"github.com/kris-nova/kubicorn/cutil/logger"
"github.com/kris-nova/kubicorn/cutil/script"
"google.golang.org/api/compute/v1"
)
var _ cloud.Resource = &InstanceGroup{}
// InstanceGroup is a representation of the server to be created on the cloud provider.
type InstanceGroup struct {
Shared
Location string
Size string
Image string
Count int
SSHFingerprint string
BootstrapScripts []string
ServerPool *cluster.ServerPool
}
const (
// MasterIPAttempts specifies how many times are allowed to be taken to get the master node IP.
MasterIPAttempts = 40
// MasterIPSleepSecondsPerAttempt specifies how much time should pass after a failed attempt to get the master IP.
MasterIPSleepSecondsPerAttempt = 3
)
// Actual is used to build a cluster based on instances on the cloud provider.
func (r *InstanceGroup) Actual(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {
logger.Debug("instanceGroup.Actual")
if r.CachedActual != nil {
logger.Debug("Using cached instance [actual]")
return immutable, r.CachedActual, nil
}
newResource := &InstanceGroup{
Shared: Shared{
Name: r.Name,
CloudID: r.ServerPool.Identifier,
},
}
project, err := Sdk.Service.Projects.Get(immutable.CloudId).Do()
if err != nil && project != nil {
instances, err := Sdk.Service.Instances.List(immutable.CloudId, immutable.Location).Do()
if err != nil {
return nil, nil, err
}
count := len(instances.Items)
if count > 0 {
newResource.Count = count
instance := instances.Items[0]
newResource.Name = instance.Name
newResource.CloudID = string(instance.Id)
newResource.Size = instance.Kind
newResource.Image = r.Image
newResource.Location = instance.Zone
}
}
newResource.BootstrapScripts = r.ServerPool.BootstrapScripts
newResource.SSHFingerprint = immutable.SSH.PublicKeyFingerprint
newResource.Name = r.Name
r.CachedActual = newResource
return immutable, newResource, nil
}
// Expected is used to build a cluster expected to be on the cloud provider.
func (r *InstanceGroup) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {
logger.Debug("instanceGroup.Expected")
if r.CachedExpected != nil {
logger.Debug("Using instance subnet [expected]")
return immutable, r.CachedExpected, nil
}
expected := &InstanceGroup{
Shared: Shared{
Name: r.Name,
CloudID: r.ServerPool.Identifier,
},
Size: r.ServerPool.Size,
Location: immutable.Location,
Image: r.ServerPool.Image,
Count: r.ServerPool.MaxCount,
SSHFingerprint: immutable.SSH.PublicKeyFingerprint,
BootstrapScripts: r.ServerPool.BootstrapScripts,
}
r.CachedExpected = expected
return immutable, expected, nil
}
// Apply is used to create the expected resources on the cloud provider.
func (r *InstanceGroup) Apply(actual, expected cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {
logger.Debug("instanceGroup.Apply")
applyResource := expected.(*InstanceGroup)
isEqual, err := compare.IsEqual(actual.(*InstanceGroup), expected.(*InstanceGroup))
if err != nil {
return nil, nil, err
}
if isEqual {
return immutable, applyResource, nil
}
scripts, err := script.BuildBootstrapScript(r.ServerPool.BootstrapScripts, immutable)
if err != nil {
return nil, nil, err
}
masterIPPrivate := ""
masterIPPublic := ""
if r.ServerPool.Type == cluster.ServerPoolTypeNode {
found := false
for i := 0; i < MasterIPAttempts; i++ {
masterTag := ""
for _, serverPool := range immutable.ServerPools {
if serverPool.Type == cluster.ServerPoolTypeMaster {
masterTag = serverPool.Name
}
}
if masterTag == "" {
return nil, nil, fmt.Errorf("Unable to find master tag")
}
instanceGroupManager, err := Sdk.Service.InstanceGroupManagers.ListManagedInstances(immutable.CloudId, expected.(*InstanceGroup).Location, strings.ToLower(masterTag)).Do()
if err != nil {
return nil, nil, err
}
if err != nil || len(instanceGroupManager.ManagedInstances) == 0 {
logger.Debug("Hanging for master IP.. (%v)", err)
time.Sleep(time.Duration(MasterIPSleepSecondsPerAttempt) * time.Second)
continue
}
parts := strings.Split(instanceGroupManager.ManagedInstances[0].Instance, "/")
instance, err := Sdk.Service.Instances.Get(immutable.CloudId, expected.(*InstanceGroup).Location, parts[len(parts)-1]).Do()
if err != nil {
logger.Debug("Hanging for master IP.. (%v)", err)
time.Sleep(time.Duration(MasterIPSleepSecondsPerAttempt) * time.Second)
continue
}
for _, networkInterface := range instance.NetworkInterfaces {
if networkInterface.Name == "nic0" {
masterIPPrivate = networkInterface.NetworkIP
for _, accessConfigs := range networkInterface.AccessConfigs {
masterIPPublic = accessConfigs.NatIP
}
}
}
if masterIPPublic == "" {
logger.Debug("Hanging for master IP..")
time.Sleep(time.Duration(MasterIPSleepSecondsPerAttempt) * time.Second)
continue
}
found = true
immutable.Values.ItemMap["INJECTEDMASTER"] = fmt.Sprintf("%s:%s", masterIPPrivate, immutable.KubernetesAPI.Port)
break
}
if !found {
return nil, nil, fmt.Errorf("Unable to find Master IP after defined wait")
}
}
immutable.Values.ItemMap["INJECTEDPORT"] = immutable.KubernetesAPI.Port
scripts, err = bootstrap.Inject(scripts, immutable.Values.ItemMap)
finalScripts := string(scripts)
if err != nil {
return nil, nil, err
}
tags := []string{}
if immutable.KubernetesAPI.Port == "443" {
tags = append(tags, "https-server")
}
if immutable.KubernetesAPI.Port == "80" {
tags = append(tags, "http-server")
}
prefix := "https://www.googleapis.com/compute/v1/projects/" + immutable.CloudId
imageURL := "https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/images/" + expected.(*InstanceGroup).Image
templateInstance, err := Sdk.Service.InstanceTemplates.Get(immutable.CloudId, strings.ToLower(expected.(*InstanceGroup).Name)).Do()
if err != nil {
sshPublicKeyValue := fmt.Sprintf("%s:%s", immutable.SSH.User, string(immutable.SSH.PublicKeyData))
templateInstance = &compute.InstanceTemplate{
Name: strings.ToLower(expected.(*InstanceGroup).Name),
Properties: &compute.InstanceProperties{
MachineType: expected.(*InstanceGroup).Size,
Disks: []*compute.AttachedDisk{
{
AutoDelete: true,
Boot: true,
Type: "PERSISTENT",
InitializeParams: &compute.AttachedDiskInitializeParams{
SourceImage: imageURL,
},
},
},
NetworkInterfaces: []*compute.NetworkInterface{
{
AccessConfigs: []*compute.AccessConfig{
{
Type: "ONE_TO_ONE_NAT",
Name: "External NAT",
},
},
Network: prefix + "/global/networks/default",
},
},
ServiceAccounts: []*compute.ServiceAccount{
{
Email: "default",
Scopes: []string{
compute.DevstorageFullControlScope,
compute.ComputeScope,
},
},
},
Metadata: &compute.Metadata{
Kind: "compute#metadata",
Items: []*compute.MetadataItems{
{
Key: "ssh-keys",
Value: &sshPublicKeyValue,
},
{
Key: "startup-script",
Value: &finalScripts,
},
},
},
Tags: &compute.Tags{
Items: tags,
},
},
}
_, err = Sdk.Service.InstanceTemplates.Insert(immutable.CloudId, templateInstance).Do()
if err != nil {
return nil, nil, err
}
}
_, err = Sdk.Service.InstanceGroupManagers.Get(immutable.CloudId, expected.(*InstanceGroup).Location, strings.ToLower(expected.(*InstanceGroup).Name)).Do()
if err != nil {
instanceGroupManager := &compute.InstanceGroupManager{
Name: templateInstance.Name,
BaseInstanceName: templateInstance.Name,
InstanceTemplate: prefix + "/global/instanceTemplates/" + templateInstance.Name,
TargetSize: int64(expected.(*InstanceGroup).Count),
}
for i := 0; i < MasterIPAttempts; i++ {
logger.Debug("Creating instance group manager")
_, err = Sdk.Service.InstanceGroupManagers.Insert(immutable.CloudId, expected.(*InstanceGroup).Location, instanceGroupManager).Do()
if err == nil {
break
}
logger.Debug("Waiting for instance template to be ready.")
time.Sleep(time.Duration(MasterIPSleepSecondsPerAttempt) * time.Second)
}
logger.Info("Created instance group manager [%s]", templateInstance.Name)
}
newResource := &InstanceGroup{
Shared: Shared{
Name: r.ServerPool.Name,
//CloudID: id,
},
Image: expected.(*InstanceGroup).Image,
Size: expected.(*InstanceGroup).Size,
Location: expected.(*InstanceGroup).Location,
Count: expected.(*InstanceGroup).Count,
BootstrapScripts: expected.(*InstanceGroup).BootstrapScripts,
}
immutable.KubernetesAPI.Endpoint = masterIPPublic
renderedCluster, err := r.immutableRender(newResource, immutable)
if err != nil {
return nil, nil, err
}
return renderedCluster, newResource, nil
}
// Delete is used to delete the instances on the cloud provider
func (r *InstanceGroup) Delete(actual cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {
logger.Debug("instanceGroup.Delete")
deleteResource := actual.(*InstanceGroup)
if deleteResource.Name == "" {
return nil, nil, fmt.Errorf("Unable to delete instance resource without Name [%s]", deleteResource.Name)
}
_, err := Sdk.Service.InstanceGroupManagers.Delete(immutable.CloudId, immutable.Location, strings.ToLower(r.ServerPool.Name)).Do()
if err != nil {
return nil, nil, err
}
logger.Info("Deleted InstanceGroup manager [%s]", r.ServerPool.Name)
// Kubernetes API
immutable.KubernetesAPI.Endpoint = ""
renderedCluster, err := r.immutableRender(actual, immutable)
if err != nil {
return nil, nil, err
}
return renderedCluster, actual, nil
}
func (r *InstanceGroup) immutableRender(newResource cloud.Resource, inaccurateCluster *cluster.Cluster) (*cluster.Cluster, error) {
logger.Debug("instanceGroup.Render")
newCluster := defaults.NewClusterDefaults(inaccurateCluster)
return newCluster, nil
}