/
manager.go
470 lines (421 loc) · 13 KB
/
manager.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
// Copyright 2014 The Serviced 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 isvcs
import (
"github.com/Sirupsen/logrus"
"github.com/control-center/serviced/commons"
"github.com/control-center/serviced/commons/docker"
"github.com/control-center/serviced/domain"
"errors"
"fmt"
"os"
"path"
"sort"
"sync"
)
// managerOp is a type of manager operation (stop, start, notify)
type managerOp int
// constants for the manager operations
const (
managerOpStart managerOp = iota // Start the subservices
managerOpStop // stop the subservices
managerOpNotify // notify config in subservices
managerOpExit // exit the loop of the manager
managerOpRegisterContainer // register a given container
managerOpInit // make sure manager is ready to run containers
)
const HEALTH_STATUS_INDEX_ALL = -1 // The index to return all health statuses.
var (
ErrManagerUnknownOp = errors.New("manager: unknown operation")
ErrManagerUnknownArg = errors.New("manager: unknown arg type")
ErrImageNotExists = errors.New("manager: image does not exist")
ErrNotifyFailed = errors.New("manager: notification failure")
)
type StartError int
func (err StartError) Error() string {
return fmt.Sprintf("manager: could not start %d isvcs", int(err))
}
type StopError int
func (err StopError) Error() string {
return fmt.Sprintf("manager: could not stop %d isvcs", int(err))
}
// A managerRequest describes an operation for the manager loop() to perform and a response channel
type managerRequest struct {
op managerOp // the operation to perform
val interface{}
response chan error // the response channel
}
// A manager of docker services run in ephemeral containers
type Manager struct {
imagesDir string // local directory where images could be loaded from
volumesDir string // local directory where volumes are stored
requests chan managerRequest // the main loops request channel
services map[string]*IService
startGroups map[int][]string // map by group number of a list of service names
dockerLogDriver string // which log driver to use with containers
dockerLogConfig map[string]string // options for the log driver
}
// Returns a new Manager struct and starts the Manager's main loop()
func NewManager(imagesDir, volumesDir string, dockerLogDriver string, dockerLogConfig map[string]string) *Manager {
loadvolumes()
manager := &Manager{
imagesDir: imagesDir,
volumesDir: volumesDir,
requests: make(chan managerRequest),
services: make(map[string]*IService),
startGroups: make(map[int][]string),
dockerLogDriver: dockerLogDriver,
dockerLogConfig: dockerLogConfig,
}
go manager.loop()
return manager
}
// checks to see if the given repo:tag exists in docker
func (m *Manager) imageExists(repo, tag string) (bool, error) {
if _, err := docker.FindImage(commons.JoinRepoTag(repo, tag), false); docker.IsImageNotFound(err) {
return false, nil
} else if err != nil {
return false, err
}
return true, nil
}
// SetVolumesDir sets the volumes dir for *Manager
func (m *Manager) SetVolumesDir(dir string) {
m.volumesDir = dir
}
func (m *Manager) SetConfigurationOption(name, key string, value interface{}) error {
svc, found := m.services[name]
if !found {
return errors.New("could not find isvc")
}
log.WithFields(logrus.Fields{
"isvc": name,
"key": key,
"value": value,
}).Debug("Setting configuration option")
svc.Configuration[key] = value
return nil
}
// Returns a list of iservice names in sorted order
func (m *Manager) GetServiceNames() []string {
names := make([]string, 0, len(m.services))
for name := range m.services {
names = append(names, name)
}
sort.Strings(names)
return names
}
func (m *Manager) GetHealthStatus(name string, instIndex int) (IServiceHealthResult, error) {
result := IServiceHealthResult{
ServiceName: name,
ContainerName: "",
ContainerID: "",
HealthStatuses: make([]domain.HealthCheckStatus, 0),
}
svc, found := m.services[name]
if !found {
log.WithFields(logrus.Fields{
"isvc": name,
}).Warn("Internal service not found")
return IServiceHealthResult{}, fmt.Errorf("could not find isvc %q", name)
}
if ctr, err := docker.FindContainer(svc.name()); err == nil {
result.ContainerID = ctr.ID
}
svc.lock.RLock()
defer svc.lock.RUnlock()
result.ContainerName = svc.name()
if instIndex == HEALTH_STATUS_INDEX_ALL {
for _, statusMap := range svc.healthStatuses {
for _, value := range statusMap {
result.HealthStatuses = append(result.HealthStatuses, *value)
}
}
} else if instIndex < len(svc.healthStatuses) {
for _, value := range svc.healthStatuses[instIndex] {
result.HealthStatuses = append(result.HealthStatuses, *value)
}
} else {
log.WithFields(logrus.Fields{
"isvc": name,
"instIndex": instIndex,
}).Error("Instance index out of range")
return IServiceHealthResult{}, fmt.Errorf("Instance index out of range %d", instIndex)
}
return result, nil
}
// checks for the existence of all the container images
func (m *Manager) allImagesExist() error {
for _, c := range m.services {
if exists, err := m.imageExists(c.Repo, c.Tag); err != nil {
return err
} else {
if !exists {
return ErrImageNotExists
}
}
}
return nil
}
// loadImages() loads all the images defined in the registered services
func (m *Manager) loadImages() error {
loadedImages := make(map[string]bool)
for _, c := range m.services {
exists, err := m.imageExists(c.Repo, c.Tag)
if err != nil {
return err
}
if exists {
log.WithFields(logrus.Fields{
"isvc": c.Name,
"repo": c.Repo,
"tag": c.Tag,
}).Debug("Found image for internal service")
continue
}
localTar := path.Join(m.imagesDir, c.Repo, c.Tag+".tar.gz")
imageRepoTag := c.Repo + ":" + c.Tag
log := log.WithFields(logrus.Fields{
"image": imageRepoTag,
})
if _, exists := loadedImages[imageRepoTag]; exists {
continue
}
if _, err := os.Stat(localTar); err == nil {
if err := docker.ImportImage(imageRepoTag, localTar); err != nil {
return err
}
loadedImages[imageRepoTag] = true
log.WithFields(logrus.Fields{
"tarball": localTar,
}).Debug("Loaded image from local tarball")
} else {
log.Debug("Pulling image")
if err := docker.PullImage(imageRepoTag); err != nil {
return fmt.Errorf("Failed to pull image %s: %s", imageRepoTag, err)
}
loadedImages[imageRepoTag] = true
log.Info("Pulled image")
}
}
return nil
}
type containerStartResponse struct {
name string
err error
}
// loop() maitainers the Manager's state
func (m *Manager) loop() {
var once sync.Once
for {
select {
case request := <-m.requests:
switch request.op {
case managerOpNotify:
var failed bool
for _, svc := range m.services {
if svc.Notify != nil && svc.IsRunning() {
if err := svc.Notify(svc, request.val); err != nil {
log.WithFields(logrus.Fields{
"isvc": svc.Name,
}).WithError(err).Error("Unable to notify internal service")
failed = true
}
}
}
if failed {
request.response <- ErrNotifyFailed
} else {
request.response <- nil
}
case managerOpExit:
request.response <- nil
return // this will exit the loop()
case managerOpStart:
var err error
once.Do(func() {
if err = m.loadImages(); err != nil {
return
} else if err = m.allImagesExist(); err != nil {
return
}
})
if err != nil {
request.response <- err
continue
}
// Start each group of services in group-number order
unstartedServices := 0
for _, group := range m.orderedStartGroups() {
unstartedServices += m.startServiceGroup(group)
}
if unstartedServices > 0 {
request.response <- StartError(unstartedServices)
} else {
request.response <- nil
}
case managerOpStop:
// track the number of services that haven't stopped
var noStop = make([]int, len(m.services))
// stop services in parallel
var wg sync.WaitGroup
index := 0
for name, svc := range m.services {
if svc.IsRunning() {
wg.Add(1)
go func(svc *IService, i int) {
defer wg.Done()
if err := svc.Stop(); err != nil {
log.WithFields(logrus.Fields{
"isvc": svc.Name,
}).WithError(err).Error("Unable to stop internal service")
noStop[i] = 1
return
}
}(m.services[name], index)
}
index++
}
wg.Wait()
count := 0
for _, i := range noStop {
count += i
}
if count > 0 {
request.response <- StopError(count)
} else {
request.response <- nil
}
case managerOpRegisterContainer:
svc, ok := request.val.(*IService)
if !ok {
request.response <- ErrManagerUnknownArg
} else {
m.services[svc.Name] = svc
m.addServiceToStartGroup(svc)
request.response <- nil
}
case managerOpInit:
request.response <- nil
default:
request.response <- ErrManagerUnknownOp
}
}
}
}
func (m *Manager) addServiceToStartGroup(svc *IService) {
startGroup := int(svc.StartGroup)
if m.startGroups[startGroup] == nil {
m.startGroups[startGroup] = make([]string, 0)
}
m.startGroups[startGroup] = append(m.startGroups[startGroup], svc.Name)
}
// Returns a list of start groups in numeric order (lowest to highest)
func (m *Manager) orderedStartGroups() []int {
result := make([]int, len(m.startGroups))
i := 0
for key, _ := range m.startGroups {
result[i] = int(key)
i++
}
sort.Ints(result)
return result
}
// Start all of the services in the specified start group and wait for all of
// them to finish. Returns the number of services which failed to start.
func (m *Manager) startServiceGroup(group int) int {
log.WithFields(logrus.Fields{
"group": group,
"services": m.startGroups[group],
})
log.Debug("Starting internal services in group")
// track the number of services that haven't started
var noStart = make([]int, len(m.startGroups[group]))
// start all of the services for this group in parallel
var wg sync.WaitGroup
index := 0
for _, name := range m.startGroups[group] {
svc := m.services[name]
if !svc.IsRunning() {
wg.Add(1)
go func(svc *IService, i int) {
defer wg.Done()
if err := svc.Start(); err != nil {
log.WithFields(logrus.Fields{
"isvc": svc.Name,
}).WithError(err).Error("Unable to start internal service")
noStart[i] = 1
return
}
}(m.services[name], index)
}
index++
}
wg.Wait()
unstartedServices := 0
for _, i := range noStart {
unstartedServices += i
}
return unstartedServices
}
// makeRequest sends a manager operation request to the *Manager's loop()
func (m *Manager) makeRequest(op managerOp) error {
request := managerRequest{
op: op,
response: make(chan error),
}
m.requests <- request
return <-request.response
}
// Register() registers a container to be managed by the *Manager
func (m *Manager) Register(svc *IService) error {
svc.dockerLogDriver = m.dockerLogDriver
svc.dockerLogConfig = m.dockerLogConfig
request := managerRequest{
op: managerOpRegisterContainer,
val: svc,
response: make(chan error),
}
m.requests <- request
return <-request.response
}
// Stop() stops all the containers currently registered to the *Manager
func (m *Manager) Stop() error {
log.Debug("Internal services manager sending stop request")
defer log.Debug("Internal services manager received stop response")
return m.makeRequest(managerOpStop)
}
// Start() starts all the containers managed by the *Manager
func (m *Manager) Start() error {
log.Debug("Internal services manager sending start request")
defer log.Debug("Internal services manager received start response")
return m.makeRequest(managerOpStart)
}
// Notify() sends a notify() message to all the containers with the given data val
func (m *Manager) Notify(val interface{}) error {
log.Debug("Internal services manager sending notify request")
defer log.Debug("Internal services manager received notify response")
request := managerRequest{
op: managerOpNotify,
val: val,
response: make(chan error),
}
m.requests <- request
return <-request.response
}
// TearDown() causes the *Manager's loop() to exit
func (m *Manager) TearDown() error {
log.Debug("Internal services manager sending exit request")
defer log.Debug("Internal services manager received exit response")
return m.makeRequest(managerOpExit)
}