/
service.go
390 lines (336 loc) · 10.9 KB
/
service.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
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package description
import (
"encoding/base64"
"github.com/juju/utils/set"
"github.com/juju/errors"
"github.com/juju/names"
"github.com/juju/schema"
)
type services struct {
Version int `yaml:"version"`
Services_ []*service `yaml:"services"`
}
type service struct {
Name_ string `yaml:"name"`
Series_ string `yaml:"series"`
Subordinate_ bool `yaml:"subordinate,omitempty"`
CharmURL_ string `yaml:"charm-url"`
Channel_ string `yaml:"cs-channel"`
CharmModifiedVersion_ int `yaml:"charm-mod-version"`
// ForceCharm is true if an upgrade charm is forced.
// It means upgrade even if the charm is in an error state.
ForceCharm_ bool `yaml:"force-charm,omitempty"`
Exposed_ bool `yaml:"exposed,omitempty"`
MinUnits_ int `yaml:"min-units,omitempty"`
Status_ *status `yaml:"status"`
StatusHistory_ `yaml:"status-history"`
Settings_ map[string]interface{} `yaml:"settings"`
SettingsRefCount_ int `yaml:"settings-refcount"`
Leader_ string `yaml:"leader,omitempty"`
LeadershipSettings_ map[string]interface{} `yaml:"leadership-settings"`
MetricsCredentials_ string `yaml:"metrics-creds,omitempty"`
// unit count will be assumed by the number of units associated.
Units_ units `yaml:"units"`
Annotations_ `yaml:"annotations,omitempty"`
Constraints_ *constraints `yaml:"constraints,omitempty"`
// Storage Constraints
}
// ServiceArgs is an argument struct used to add a service to the Model.
type ServiceArgs struct {
Tag names.ServiceTag
Series string
Subordinate bool
CharmURL string
Channel string
CharmModifiedVersion int
ForceCharm bool
Exposed bool
MinUnits int
Settings map[string]interface{}
SettingsRefCount int
Leader string
LeadershipSettings map[string]interface{}
MetricsCredentials []byte
}
func newService(args ServiceArgs) *service {
creds := base64.StdEncoding.EncodeToString(args.MetricsCredentials)
svc := &service{
Name_: args.Tag.Id(),
Series_: args.Series,
Subordinate_: args.Subordinate,
CharmURL_: args.CharmURL,
Channel_: args.Channel,
CharmModifiedVersion_: args.CharmModifiedVersion,
ForceCharm_: args.ForceCharm,
Exposed_: args.Exposed,
MinUnits_: args.MinUnits,
Settings_: args.Settings,
SettingsRefCount_: args.SettingsRefCount,
Leader_: args.Leader,
LeadershipSettings_: args.LeadershipSettings,
MetricsCredentials_: creds,
StatusHistory_: newStatusHistory(),
}
svc.setUnits(nil)
return svc
}
// Tag implements Service.
func (s *service) Tag() names.ServiceTag {
return names.NewServiceTag(s.Name_)
}
// Name implements Service.
func (s *service) Name() string {
return s.Name_
}
// Series implements Service.
func (s *service) Series() string {
return s.Series_
}
// Subordinate implements Service.
func (s *service) Subordinate() bool {
return s.Subordinate_
}
// CharmURL implements Service.
func (s *service) CharmURL() string {
return s.CharmURL_
}
// Channel implements Service.
func (s *service) Channel() string {
return s.Channel_
}
// CharmModifiedVersion implements Service.
func (s *service) CharmModifiedVersion() int {
return s.CharmModifiedVersion_
}
// ForceCharm implements Service.
func (s *service) ForceCharm() bool {
return s.ForceCharm_
}
// Exposed implements Service.
func (s *service) Exposed() bool {
return s.Exposed_
}
// MinUnits implements Service.
func (s *service) MinUnits() int {
return s.MinUnits_
}
// Settings implements Service.
func (s *service) Settings() map[string]interface{} {
return s.Settings_
}
// SettingsRefCount implements Service.
func (s *service) SettingsRefCount() int {
return s.SettingsRefCount_
}
// Leader implements Service.
func (s *service) Leader() string {
return s.Leader_
}
// LeadershipSettings implements Service.
func (s *service) LeadershipSettings() map[string]interface{} {
return s.LeadershipSettings_
}
// MetricsCredentials implements Service.
func (s *service) MetricsCredentials() []byte {
// Here we are explicitly throwing away any decode error. We check that
// the creds can be decoded when we parse the incoming data, or we encode
// an incoming byte array, so in both cases, we know that the stored creds
// can be decoded.
creds, _ := base64.StdEncoding.DecodeString(s.MetricsCredentials_)
return creds
}
// Status implements Service.
func (s *service) Status() Status {
// To avoid typed nils check nil here.
if s.Status_ == nil {
return nil
}
return s.Status_
}
// SetStatus implements Service.
func (s *service) SetStatus(args StatusArgs) {
s.Status_ = newStatus(args)
}
// Units implements Service.
func (s *service) Units() []Unit {
result := make([]Unit, len(s.Units_.Units_))
for i, u := range s.Units_.Units_ {
result[i] = u
}
return result
}
func (s *service) unitNames() set.Strings {
result := set.NewStrings()
for _, u := range s.Units_.Units_ {
result.Add(u.Name())
}
return result
}
// AddUnit implements Service.
func (s *service) AddUnit(args UnitArgs) Unit {
u := newUnit(args)
s.Units_.Units_ = append(s.Units_.Units_, u)
return u
}
func (s *service) setUnits(unitList []*unit) {
s.Units_ = units{
Version: 1,
Units_: unitList,
}
}
// Constraints implements HasConstraints.
func (s *service) Constraints() Constraints {
if s.Constraints_ == nil {
return nil
}
return s.Constraints_
}
// SetConstraints implements HasConstraints.
func (s *service) SetConstraints(args ConstraintsArgs) {
s.Constraints_ = newConstraints(args)
}
// Validate implements Service.
func (s *service) Validate() error {
if s.Name_ == "" {
return errors.NotValidf("service missing name")
}
if s.Status_ == nil {
return errors.NotValidf("service %q missing status", s.Name_)
}
// If leader is set, it must match one of the units.
var leaderFound bool
// All of the services units should also be valid.
for _, u := range s.Units() {
if err := u.Validate(); err != nil {
return errors.Trace(err)
}
// We know that the unit has a name, because it validated correctly.
if u.Name() == s.Leader_ {
leaderFound = true
}
}
if s.Leader_ != "" && !leaderFound {
return errors.NotValidf("missing unit for leader %q", s.Leader_)
}
return nil
}
func importServices(source map[string]interface{}) ([]*service, error) {
checker := versionedChecker("services")
coerced, err := checker.Coerce(source, nil)
if err != nil {
return nil, errors.Annotatef(err, "services version schema check failed")
}
valid := coerced.(map[string]interface{})
version := int(valid["version"].(int64))
importFunc, ok := serviceDeserializationFuncs[version]
if !ok {
return nil, errors.NotValidf("version %d", version)
}
sourceList := valid["services"].([]interface{})
return importServiceList(sourceList, importFunc)
}
func importServiceList(sourceList []interface{}, importFunc serviceDeserializationFunc) ([]*service, error) {
result := make([]*service, 0, len(sourceList))
for i, value := range sourceList {
source, ok := value.(map[string]interface{})
if !ok {
return nil, errors.Errorf("unexpected value for service %d, %T", i, value)
}
service, err := importFunc(source)
if err != nil {
return nil, errors.Annotatef(err, "service %d", i)
}
result = append(result, service)
}
return result, nil
}
type serviceDeserializationFunc func(map[string]interface{}) (*service, error)
var serviceDeserializationFuncs = map[int]serviceDeserializationFunc{
1: importServiceV1,
}
func importServiceV1(source map[string]interface{}) (*service, error) {
fields := schema.Fields{
"name": schema.String(),
"series": schema.String(),
"subordinate": schema.Bool(),
"charm-url": schema.String(),
"cs-channel": schema.String(),
"charm-mod-version": schema.Int(),
"force-charm": schema.Bool(),
"exposed": schema.Bool(),
"min-units": schema.Int(),
"status": schema.StringMap(schema.Any()),
"settings": schema.StringMap(schema.Any()),
"settings-refcount": schema.Int(),
"leader": schema.String(),
"leadership-settings": schema.StringMap(schema.Any()),
"metrics-creds": schema.String(),
"units": schema.StringMap(schema.Any()),
}
defaults := schema.Defaults{
"subordinate": false,
"force-charm": false,
"exposed": false,
"min-units": int64(0),
"leader": "",
"metrics-creds": "",
}
addAnnotationSchema(fields, defaults)
addConstraintsSchema(fields, defaults)
addStatusHistorySchema(fields)
checker := schema.FieldMap(fields, defaults)
coerced, err := checker.Coerce(source, nil)
if err != nil {
return nil, errors.Annotatef(err, "service v1 schema check failed")
}
valid := coerced.(map[string]interface{})
// From here we know that the map returned from the schema coercion
// contains fields of the right type.
result := &service{
Name_: valid["name"].(string),
Series_: valid["series"].(string),
Subordinate_: valid["subordinate"].(bool),
CharmURL_: valid["charm-url"].(string),
Channel_: valid["cs-channel"].(string),
CharmModifiedVersion_: int(valid["charm-mod-version"].(int64)),
ForceCharm_: valid["force-charm"].(bool),
Exposed_: valid["exposed"].(bool),
MinUnits_: int(valid["min-units"].(int64)),
Settings_: valid["settings"].(map[string]interface{}),
SettingsRefCount_: int(valid["settings-refcount"].(int64)),
Leader_: valid["leader"].(string),
LeadershipSettings_: valid["leadership-settings"].(map[string]interface{}),
StatusHistory_: newStatusHistory(),
}
result.importAnnotations(valid)
if err := result.importStatusHistory(valid); err != nil {
return nil, errors.Trace(err)
}
if constraintsMap, ok := valid["constraints"]; ok {
constraints, err := importConstraints(constraintsMap.(map[string]interface{}))
if err != nil {
return nil, errors.Trace(err)
}
result.Constraints_ = constraints
}
encodedCreds := valid["metrics-creds"].(string)
// The model stores the creds encoded, but we want to make sure that
// we are storing something that can be decoded.
if _, err := base64.StdEncoding.DecodeString(encodedCreds); err != nil {
return nil, errors.Annotate(err, "metrics credentials not valid")
}
result.MetricsCredentials_ = encodedCreds
status, err := importStatus(valid["status"].(map[string]interface{}))
if err != nil {
return nil, errors.Trace(err)
}
result.Status_ = status
units, err := importUnits(valid["units"].(map[string]interface{}))
if err != nil {
return nil, errors.Trace(err)
}
result.setUnits(units)
return result, nil
}