-
Notifications
You must be signed in to change notification settings - Fork 170
/
stack.go
445 lines (372 loc) · 12.2 KB
/
stack.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package dockerclient
import (
"errors"
"fmt"
"sort"
"strconv"
"strings"
"github.com/Dataman-Cloud/crane/src/dockerclient/model"
rauth "github.com/Dataman-Cloud/crane/src/plugins/registryauth"
"github.com/Dataman-Cloud/crane/src/utils/cranerror"
docker "github.com/Dataman-Cloud/go-dockerclient"
log "github.com/Sirupsen/logrus"
"github.com/docker/engine-api/types"
"github.com/docker/engine-api/types/filters"
"github.com/docker/engine-api/types/swarm"
)
type Stacks []Stack
func (s Stacks) Len() int {
return len(s)
}
func (s Stacks) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s Stacks) Less(i, j int) bool {
return s[i].Services[0].CreatedAt.Unix() < s[j].Services[0].CreatedAt.Unix()
}
type Stack struct {
// Name is the name of the stack
Namespace string `json:"Namespace"`
// Services is the number of the services
ServiceCount int `json:"ServiceCount"`
Services []ServiceStatus
}
// deploy a new stack
func (client *CraneDockerClient) DeployStack(bundle *model.Bundle) error {
if bundle.Namespace == "" || !isValidName.MatchString(bundle.Namespace) {
return cranerror.NewError(CodeInvalidStackName, "invalid name, only [a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]")
}
newNetworkMap, err := client.PretreatmentStack(*bundle)
if err != nil {
return err
}
return client.deployServices(bundle.Stack.Services, bundle.Namespace, newNetworkMap)
}
// before deploy stack we must verify all service spec params and check port conflict
// also we need check networks used by all of the servcie if the network is not existed
// created the network by the default param(network driver --overlay)
func (client *CraneDockerClient) PretreatmentStack(bundle model.Bundle) (map[string]bool, error) {
// create network map and convert to slice for distinct network
networkMap := make(map[string]bool)
// all the publish port in the stack
publishedPortMap := make(map[string]bool)
for _, serviceSpec := range bundle.Stack.Services {
if err := ValidateCraneServiceSpec(&serviceSpec); err != nil {
return nil, err
}
for _, network := range serviceSpec.Networks {
networkMap[network] = true
}
if serviceSpec.EndpointSpec != nil {
for _, pc := range serviceSpec.EndpointSpec.Ports {
if pc.PublishedPort > 0 {
portConflictStr := PortConflictToString(pc)
// have two service publish the same port
if _, ok := publishedPortMap[portConflictStr]; ok {
portConflictErr := &cranerror.ServicePortConflictError{
Name: serviceSpec.Name,
Namespace: bundle.Namespace,
PublishedPort: portConflictStr,
}
return nil, &cranerror.CraneError{Code: CodeGetServicePortConflictError, Err: portConflictErr}
}
publishedPortMap[portConflictStr] = true
}
}
}
}
// check stack need publish port is conflicted with exist services
if len(publishedPortMap) > 0 {
existingServices, err := client.ListServiceSpec(types.ServiceListOptions{})
if err != nil {
return nil, err
}
if err := checkPortConflicts(publishedPortMap, "", existingServices); err != nil {
return nil, err
}
}
// check if all network used by stack was exist, if not create it
newNetworkMap, err := client.updateNetworks(networkMap, bundle.Namespace)
if err != nil {
return nil, err
}
return newNetworkMap, nil
}
// list all stack
func (client *CraneDockerClient) ListStack() (Stacks, error) {
filter := filters.NewArgs()
filter.Add("label", labelNamespace)
services, err := client.ListServiceSpec(types.ServiceListOptions{Filter: filter})
if err != nil {
return nil, err
}
stackMap := make(map[string]*Stack, 0)
for _, service := range services {
labels := service.Spec.Labels
name, ok := labels[labelNamespace]
if !ok {
log.Warnf("Cannot get label %s for service %s", labelNamespace, service.ID)
continue
}
stack, ok := stackMap[name]
if !ok {
stackMap[name] = &Stack{
Namespace: name,
ServiceCount: 1,
}
} else {
stack.ServiceCount++
}
}
var stacks Stacks
for _, stack := range stackMap {
stackServices, err := client.ListStackService(stack.Namespace, types.ServiceListOptions{})
if err == nil {
stack.Services = stackServices
}
stacks = append(stacks, *stack)
}
sort.Sort(sort.Reverse(stacks))
return stacks, nil
}
// ListStackServices return list of service staus and core config in stack
func (client *CraneDockerClient) ListStackService(namespace string, opts types.ServiceListOptions) ([]ServiceStatus, error) {
services, err := client.FilterServiceByStack(namespace, opts)
if err != nil {
return nil, err
}
return client.GetServicesStatus(services)
}
// Inspect stack get stack info
func (client *CraneDockerClient) InspectStack(namespace string) (*model.Bundle, error) {
services, err := client.FilterServiceByStack(namespace, types.ServiceListOptions{})
if err != nil {
return nil, err
}
stackServices := make(map[string]model.CraneServiceSpec)
for _, swarmService := range services {
stackServices[swarmService.Spec.Name] = client.ToCraneServiceSpec(swarmService.Spec)
}
return &model.Bundle{
Namespace: namespace,
Stack: model.BundleService{
//TODO stack version is missing
Services: stackServices,
},
}, nil
}
// remove all service and network in the stack
func (client *CraneDockerClient) RemoveStack(namespace string) error {
services, err := client.FilterServiceByStack(namespace, types.ServiceListOptions{})
if err != nil {
return err
}
for _, service := range services {
log.Info("begin to remove service ", service.Spec.Name)
if err := client.RemoveService(service.ID); err != nil {
return err
}
}
networks, err := client.filterStackNetwork(namespace)
if err != nil {
return err
}
for _, network := range networks {
log.Info("begin to remove network ", network.Name)
if err := client.RemoveNetwork(network.ID); err != nil {
return err
}
}
if len(services) == 0 && len(networks) == 0 {
return cranerror.NewError(CodeStackUnavailable, fmt.Sprintf("stack or network can't be empty %s ", namespace))
}
return nil
}
// filter service by stack name
func (client *CraneDockerClient) FilterServiceByStack(namespace string, opts types.ServiceListOptions) ([]swarm.Service, error) {
if opts.Filter.Len() == 0 {
opts.Filter = filters.NewArgs()
}
opts.Filter.Add("label", labelNamespace)
services, err := client.ListServiceSpec(opts)
if err != nil {
return nil, err
}
var stackServices []swarm.Service
for _, service := range services {
labels := service.Spec.Labels
name, ok := labels[labelNamespace]
if !ok {
log.Warnf("Cannot get label %s for service %s", labelNamespace, service.ID)
continue
}
if name != namespace {
continue
}
stackServices = append(stackServices, service)
}
return stackServices, nil
}
func (client *CraneDockerClient) GetStackGroup(bundle *model.Bundle) (uint64, error) {
for _, service := range bundle.Stack.Services {
for k, _ := range service.Labels {
if strings.HasPrefix(k, "com.crane.permissions") {
groupId, err := strconv.ParseUint(strings.Split(k, ".")[3], 10, 64)
if err == nil {
return groupId, nil
}
}
}
}
return 0, errors.New("can't found stack groupid")
}
func (client *CraneDockerClient) updateNetworks(networks map[string]bool, namespace string) (map[string]bool, error) {
existingNetworks, err := client.ListNetworks(docker.NetworkFilterOpts{})
if err != nil {
return nil, err
}
existingNetworkMap := make(map[string]docker.Network)
for _, network := range existingNetworks {
existingNetworkMap[network.Name] = network
}
createOpts := &docker.CreateNetworkOptions{
Labels: client.getStackLabels(namespace, nil),
Driver: defaultNetworkDriver,
// docker TODO: remove when engine-api uses omitempty for IPAM
IPAM: docker.IPAMOptions{Driver: "default"},
}
newNetworkMap := make(map[string]bool)
for internalName := range networks {
if _, exists := existingNetworkMap[internalName]; exists {
newNetworkMap[internalName] = false
continue
}
name := fmt.Sprintf("%s_%s", namespace, internalName)
log.Infof("Creating network %s\n", name)
createOpts.Name = name
if _, err := client.CreateNetwork(*createOpts); err != nil {
return newNetworkMap, err
}
newNetworkMap[internalName] = true
}
return newNetworkMap, nil
}
func convertNetworks(newNetworkMap map[string]bool, networks []string, namespace string, name string) []swarm.NetworkAttachmentConfig {
nets := []swarm.NetworkAttachmentConfig{}
for _, serviceNetwork := range networks {
if isNew, ok := newNetworkMap[serviceNetwork]; ok && isNew {
nets = append(nets, swarm.NetworkAttachmentConfig{
Target: namespace + "_" + serviceNetwork,
Aliases: []string{name},
})
} else {
nets = append(nets, swarm.NetworkAttachmentConfig{
Target: serviceNetwork,
Aliases: []string{name},
})
}
}
return nets
}
func (client *CraneDockerClient) deployServices(services map[string]model.CraneServiceSpec, namespace string, newNetworkMap map[string]bool) error {
existingServices, err := client.filterStackServices(namespace)
if err != nil {
return err
}
existingServiceMap := make(map[string]swarm.Service)
for _, service := range existingServices {
existingServiceMap[service.Spec.Name] = service
}
for internalName, service := range services {
name := fmt.Sprintf("%s_%s", namespace, internalName)
serviceSpec := swarm.ServiceSpec{
Annotations: swarm.Annotations{
Name: name,
Labels: client.getStackLabels(namespace, service.Labels),
},
Mode: service.Mode,
TaskTemplate: service.TaskTemplate,
EndpointSpec: service.EndpointSpec,
Networks: convertNetworks(newNetworkMap, service.Networks, namespace, internalName),
UpdateConfig: service.UpdateConfig,
}
createOpts := types.ServiceCreateOptions{}
updateOpts := types.ServiceUpdateOptions{}
if service.RegistryAuth != "" {
authInfo, err := rauth.Get(service.RegistryAuth)
if err != nil {
return err
}
encodedRegistryAuth, err := EncodeRegistryAuth(authInfo)
if err != nil {
return err
}
createOpts.EncodedRegistryAuth = encodedRegistryAuth
updateOpts.EncodedRegistryAuth = encodedRegistryAuth
if serviceSpec.Labels == nil {
serviceSpec.Labels = make(map[string]string)
}
serviceSpec.Annotations.Labels[LabelRegistryAuth] = service.RegistryAuth
} else {
// is safe to delete and not exist field
delete(serviceSpec.Annotations.Labels, LabelRegistryAuth)
}
//TODO change service WorkingDir and User
//cspec := &serviceSpec.TaskTemplate.ContainerSpec
//if service.WorkingDir != nil {
// cspec.Dir = *service.WorkingDir
//}
//if service.User != nil {
// cspec.User = *service.User
//}
if service, exists := existingServiceMap[name]; exists {
log.Infof("Updating service %s (id %s)", name, service.ID)
if err := client.UpdateService(service.ID, service.Version, serviceSpec, updateOpts); err != nil {
return err
}
} else {
log.Infof("Creating service %s", name)
if _, err := client.CreateService(serviceSpec, createOpts); err != nil {
return err
}
}
}
return nil
}
// get stack labels
func (client *CraneDockerClient) getStackLabels(namespace string, labels map[string]string) map[string]string {
if labels == nil {
labels = make(map[string]string)
}
labels[labelNamespace] = namespace
return labels
}
// split joint stack filter
func (client *CraneDockerClient) getStackFilter(namespace string) filters.Args {
filter := filters.NewArgs()
filter.Add("label", labelNamespace+"="+namespace)
return filter
}
// get service by default stack labels
func (client *CraneDockerClient) filterStackServices(namespace string) ([]swarm.Service, error) {
return client.ListServiceSpec(types.ServiceListOptions{Filter: client.getStackFilter(namespace)})
}
// get network by default filter
func (client *CraneDockerClient) filterStackNetwork(namespace string) ([]docker.Network, error) {
filter := docker.NetworkFilterOpts{"label": map[string]bool{labelNamespace: true}}
networks, err := client.ListNetworks(filter)
if err != nil {
return nil, err
}
var stackNetwork []docker.Network
for _, network := range networks {
if network.Labels == nil {
continue
}
if name, ok := network.Labels[labelNamespace]; !ok || name != namespace {
continue
}
stackNetwork = append(stackNetwork, network)
}
return stackNetwork, nil
}