-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
servergroup.go
213 lines (183 loc) · 6.14 KB
/
servergroup.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
/*
Copyright 2017 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 openstacktasks
import (
"fmt"
"strings"
"sync"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/servergroups"
"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
"k8s.io/klog/v2"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/openstack"
)
// +kops:fitask
type ServerGroup struct {
ID *string
Name *string
ClusterName *string
IGName *string
Policies []string
MaxSize *int32
Lifecycle fi.Lifecycle
mutex sync.Mutex
// members caches a list of member instance names.
// When we create new instances, we can add them to this list also.
members []string
// gotMemberList records if we have returned the member list to another task.
// If we attempt to add a member after doing so, it indicates a missing dependency.
gotMemberList bool
}
var _ fi.CompareWithID = &ServerGroup{}
func (s *ServerGroup) CompareWithID() *string {
return s.ID
}
func (s *ServerGroup) Find(context *fi.CloudupContext) (*ServerGroup, error) {
if s == nil || s.Name == nil {
return nil, nil
}
cloud := context.T.Cloud.(openstack.OpenstackCloud)
// TODO: move to cloud, add vfs backoff
page, err := servergroups.List(cloud.ComputeClient(), servergroups.ListOpts{}).AllPages()
if err != nil {
return nil, fmt.Errorf("Failed to list server groups: %v", err)
}
serverGroups, err := servergroups.ExtractServerGroups(page)
if err != nil {
return nil, fmt.Errorf("Failed to extract server groups: %v", err)
}
var actual *ServerGroup
for _, serverGroup := range serverGroups {
if serverGroup.Name == *s.Name {
if actual != nil {
return nil, fmt.Errorf("Found multiple server groups with name %s", fi.ValueOf(s.Name))
}
actual = &ServerGroup{
Name: fi.PtrTo(serverGroup.Name),
ClusterName: s.ClusterName,
IGName: s.IGName,
ID: fi.PtrTo(serverGroup.ID),
Lifecycle: s.Lifecycle,
Policies: serverGroup.Policies,
MaxSize: fi.PtrTo(int32(len(serverGroup.Members))),
members: serverGroup.Members,
}
}
}
if actual == nil {
return nil, nil
}
// ignore if IG is scaled up, this is handled in instancetasks
if fi.ValueOf(actual.MaxSize) < fi.ValueOf(s.MaxSize) {
s.MaxSize = actual.MaxSize
}
s.ID = actual.ID
s.members = actual.members
return actual, nil
}
func (s *ServerGroup) Run(context *fi.CloudupContext) error {
return fi.CloudupDefaultDeltaRunMethod(s, context)
}
func (_ *ServerGroup) CheckChanges(a, e, changes *ServerGroup) error {
if a == nil {
if e.Name == nil {
return fi.RequiredField("Name")
}
} else {
if changes.ID != nil {
return fi.CannotChangeField("ID")
}
if changes.Name != nil {
return fi.CannotChangeField("Name")
}
}
return nil
}
func (_ *ServerGroup) RenderOpenstack(t *openstack.OpenstackAPITarget, a, e, changes *ServerGroup) error {
if a == nil {
klog.V(2).Infof("Creating ServerGroup with Name:%q", fi.ValueOf(e.Name))
opt := servergroups.CreateOpts{
Name: fi.ValueOf(e.Name),
Policies: e.Policies,
}
g, err := t.Cloud.CreateServerGroup(opt)
if err != nil {
return fmt.Errorf("error creating ServerGroup: %v", err)
}
e.ID = fi.PtrTo(g.ID)
return nil
} else if changes.MaxSize != nil && fi.ValueOf(a.MaxSize) > fi.ValueOf(changes.MaxSize) {
currentLastIndex := fi.ValueOf(a.MaxSize)
for currentLastIndex > fi.ValueOf(changes.MaxSize) {
iName := strings.ToLower(fmt.Sprintf("%s-%d.%s", fi.ValueOf(a.IGName), currentLastIndex, fi.ValueOf(a.ClusterName)))
instanceName := strings.Replace(iName, ".", "-", -1)
opts := servers.ListOpts{
Name: fmt.Sprintf("^%s", fi.ValueOf(a.IGName)),
}
allInstances, err := t.Cloud.ListInstances(opts)
if err != nil {
return fmt.Errorf("error fetching instance list: %v", err)
}
instances := []servers.Server{}
for _, server := range allInstances {
val, ok := server.Metadata["k8s"]
if !ok || val != fi.ValueOf(a.ClusterName) {
continue
}
metadataName := ""
val, ok = server.Metadata[openstack.TagKopsName]
if ok {
metadataName = val
}
// name or metadata tag should match to instance name
// this is needed for backwards compatibility
if server.Name == instanceName || metadataName == instanceName {
instances = append(instances, server)
}
}
if len(instances) == 1 {
klog.V(2).Infof("Openstack task ServerGroup scaling down instance %s", instanceName)
err := t.Cloud.DeleteInstanceWithID(instances[0].ID)
if err != nil {
return fmt.Errorf("Could not delete instance %s: %v", instanceName, err)
}
} else {
return fmt.Errorf("found %d instances with name: %s", len(instances), instanceName)
}
currentLastIndex -= 1
}
}
klog.V(2).Infof("Openstack task ServerGroup::RenderOpenstack did nothing")
return nil
}
// AddNewMember is called when we created an instance in this server group.
// It adds it to the internal cached list of members.
// If we have already called GetMembers, this function will panic;
// this can be avoided by use of GetDependencies() (typically by depending on Instance tasks)
func (s *ServerGroup) AddNewMember(memberID string) {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.gotMemberList {
klog.Fatalf("attempt to add member %q after member list already returned", memberID)
}
s.members = append(s.members, memberID)
}
// GetMembers returns the ids of servers in this group.
// It also activates the "flag" preventning further calls to AddNewMember,
// guaranteeing that no new members will be added.
func (s *ServerGroup) GetMembers() []string {
s.mutex.Lock()
defer s.mutex.Unlock()
s.gotMemberList = true
return s.members
}