This repository has been archived by the owner on Jan 5, 2023. It is now read-only.
forked from coreos/fleet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
units.go
390 lines (344 loc) · 10.5 KB
/
units.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 2014 CoreOS, Inc.
//
// 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 api
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"path"
"strings"
"github.com/coreos/fleet/client"
"github.com/coreos/fleet/job"
"github.com/coreos/fleet/log"
"github.com/coreos/fleet/pkg"
"github.com/coreos/fleet/schema"
"github.com/coreos/fleet/unit"
gsunit "github.com/coreos/go-systemd/unit"
)
func wireUpUnitsResource(mux *http.ServeMux, prefix string, tokenLimit int, cAPI client.API) {
base := path.Join(prefix, "units")
ur := unitsResource{cAPI, base, uint16(tokenLimit)}
mux.Handle(base, &ur)
mux.Handle(base+"/", &ur)
}
type unitsResource struct {
cAPI client.API
basePath string
tokenLimit uint16
}
func (ur *unitsResource) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if isCollectionPath(ur.basePath, req.URL.Path) {
switch req.Method {
case "GET":
ur.list(rw, req)
default:
sendError(rw, http.StatusMethodNotAllowed, errors.New("only GET supported against this resource"))
}
} else if item, ok := isItemPath(ur.basePath, req.URL.Path); ok {
switch req.Method {
case "GET":
ur.get(rw, req, item)
case "DELETE":
ur.destroy(rw, req, item)
case "PUT":
ur.set(rw, req, item)
default:
sendError(rw, http.StatusMethodNotAllowed, errors.New("only GET, PUT and DELETE supported against this resource"))
}
} else {
sendError(rw, http.StatusNotFound, nil)
}
}
func (ur *unitsResource) set(rw http.ResponseWriter, req *http.Request, item string) {
if err := validateContentType(req); err != nil {
sendError(rw, http.StatusUnsupportedMediaType, err)
return
}
var su schema.Unit
dec := json.NewDecoder(req.Body)
err := dec.Decode(&su)
if err != nil {
sendError(rw, http.StatusBadRequest, fmt.Errorf("unable to decode body: %v", err))
return
}
if su.Name == "" {
su.Name = item
}
if item != su.Name {
sendError(rw, http.StatusBadRequest, fmt.Errorf("name in URL %q differs from unit name in request body %q", item, su.Name))
return
}
if err := ValidateName(su.Name); err != nil {
sendError(rw, http.StatusBadRequest, err)
return
}
eu, err := ur.cAPI.Unit(su.Name)
if err != nil {
log.Errorf("Failed fetching Unit(%s) from Registry: %v", su.Name, err)
sendError(rw, http.StatusInternalServerError, nil)
return
}
newUnit := false
if eu == nil {
if len(su.Options) == 0 {
err := errors.New("unit does not exist and options field empty")
sendError(rw, http.StatusConflict, err)
return
} else if err := ValidateOptions(su.Options); err != nil {
sendError(rw, http.StatusBadRequest, err)
return
} else {
// New valid unit
newUnit = true
}
} else if eu.Name == su.Name && len(su.Options) > 0 {
// There is already a unit with the same name that
// was submitted before. Check their hashes, if they do
// not match then this is probably a new version which
// needs its own new unit entry.
// In the other case if su.Options == 0 then probably we
// don't want to update the Unit options nor its content
// but only set the target job state of the
// corresponding unit, in this case just ignore.
a := schema.MapSchemaUnitOptionsToUnitFile(su.Options)
b := schema.MapSchemaUnitOptionsToUnitFile(eu.Options)
newUnit = !unit.MatchUnitFiles(a, b)
}
if newUnit {
ur.create(rw, su.Name, &su)
return
}
if len(su.DesiredState) == 0 {
err := errors.New("must provide DesiredState to update existing unit")
sendError(rw, http.StatusConflict, err)
return
}
un := unit.NewUnitNameInfo(su.Name)
if un.IsTemplate() && job.JobState(su.DesiredState) != job.JobStateInactive {
err := fmt.Errorf("cannot activate template %q", su.Name)
sendError(rw, http.StatusBadRequest, err)
return
}
ur.update(rw, su.Name, su.DesiredState)
}
const (
// These constants taken from systemd
unitNameMax = 256
digits = "0123456789"
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alphanumerical = digits + lowercase + uppercase
validChars = alphanumerical + `:-_.\@`
)
var validUnitTypes = pkg.NewUnsafeSet(
"service",
"socket",
"busname",
"target",
"snapshot",
"device",
"mount",
"automount",
"swap",
"timer",
"path",
"slice",
"scope",
)
// ValidateName ensures that a given unit name is valid; if not, an error is
// returned describing the first issue encountered.
// systemd reference: `unit_name_is_valid` in `unit-name.c`
func ValidateName(name string) error {
length := len(name)
if length == 0 {
return errors.New("unit name cannot be empty")
}
if length > unitNameMax {
return fmt.Errorf("unit name exceeds maximum length (%d)", unitNameMax)
}
dot := strings.LastIndex(name, ".")
if dot == -1 {
return errors.New(`unit name must contain "."`)
}
if dot == length-1 {
return errors.New(`unit name cannot end in "."`)
}
if suffix := name[dot+1:]; !validUnitTypes.Contains(suffix) {
return fmt.Errorf("invalid unit type: %q", suffix)
}
for _, char := range name[:dot] {
if !strings.ContainsRune(validChars, char) {
return fmt.Errorf("invalid character %q in unit name", char)
}
}
if strings.HasPrefix(name, "@") {
return errors.New(`unit name cannot start in "@"`)
}
return nil
}
// ValidateOptions ensures that a set of UnitOptions is valid; if not, an error
// is returned detailing the issue encountered. If there are several problems
// with a set of options, only the first is returned.
func ValidateOptions(opts []*schema.UnitOption) error {
uf := schema.MapSchemaUnitOptionsToUnitFile(opts)
// Sanity check using go-systemd's deserializer, which will do things
// like check for excessive line lengths
_, err := gsunit.Deserialize(gsunit.Serialize(uf.Options))
if err != nil {
return err
}
j := &job.Job{
Unit: *uf,
}
conflicts := pkg.NewUnsafeSet(j.Conflicts()...)
replaces := pkg.NewUnsafeSet(j.Replaces()...)
peers := pkg.NewUnsafeSet(j.Peers()...)
for _, peer := range peers.Values() {
for _, conflict := range conflicts.Values() {
matched, _ := path.Match(conflict, peer)
if matched {
return fmt.Errorf("unresolvable requirements: peer %q matches conflict %q", peer, conflict)
}
}
for _, replace := range replaces.Values() {
matched, _ := path.Match(replace, peer)
if matched {
return fmt.Errorf("unresolvable requirements: peer %q matches replace %q", peer, replace)
}
}
}
hasPeers := peers.Length() != 0
hasConflicts := conflicts.Length() != 0
hasReplaces := replaces.Length() != 0
_, hasReqTarget := j.RequiredTarget()
u := &job.Unit{
Unit: *uf,
}
isGlobal := u.IsGlobal()
switch {
case hasReqTarget && hasPeers:
return errors.New("MachineID cannot be used with Peers")
case hasReqTarget && hasConflicts:
return errors.New("MachineID cannot be used with Conflicts")
case hasReqTarget && isGlobal:
return errors.New("MachineID cannot be used with Global")
case hasReqTarget && hasReplaces:
return errors.New("MachineID cannot be used with Replaces")
case isGlobal && hasPeers:
return errors.New("Global cannot be used with Peers")
case isGlobal && hasConflicts:
return errors.New("Global cannot be used with Conflicts")
case isGlobal && hasReplaces:
return errors.New("Global cannot be used with Replaces")
case hasConflicts && hasReplaces:
return errors.New("Conflicts cannot be used with Replaces")
}
return nil
}
func (ur *unitsResource) create(rw http.ResponseWriter, name string, u *schema.Unit) {
if err := ur.cAPI.CreateUnit(u); err != nil {
log.Errorf("Failed creating Unit(%s) in Registry: %v", u.Name, err)
sendError(rw, http.StatusInternalServerError, nil)
return
}
rw.WriteHeader(http.StatusCreated)
}
func (ur *unitsResource) update(rw http.ResponseWriter, item, ds string) {
if err := ur.cAPI.SetUnitTargetState(item, ds); err != nil {
log.Errorf("Failed setting target state of Unit(%s): %v", item, err)
sendError(rw, http.StatusInternalServerError, nil)
return
}
rw.WriteHeader(http.StatusNoContent)
}
func (ur *unitsResource) destroy(rw http.ResponseWriter, req *http.Request, item string) {
u, err := ur.cAPI.Unit(item)
if err != nil {
log.Errorf("Failed fetching Unit(%s): %v", item, err)
sendError(rw, http.StatusInternalServerError, nil)
return
}
if u == nil {
sendError(rw, http.StatusNotFound, errors.New("unit does not exist"))
return
}
err = ur.cAPI.DestroyUnit(item)
if err != nil {
log.Errorf("Failed destroying Unit(%s): %v", item, err)
sendError(rw, http.StatusInternalServerError, nil)
return
}
rw.WriteHeader(http.StatusNoContent)
}
func (ur *unitsResource) get(rw http.ResponseWriter, req *http.Request, item string) {
u, err := ur.cAPI.Unit(item)
if err != nil {
log.Errorf("Failed fetching Unit(%s) from Registry: %v", item, err)
sendError(rw, http.StatusInternalServerError, nil)
return
}
if u == nil {
sendError(rw, http.StatusNotFound, errors.New("unit does not exist"))
return
}
sendResponse(rw, http.StatusOK, *u)
}
func (ur *unitsResource) list(rw http.ResponseWriter, req *http.Request) {
token, err := findNextPageToken(req.URL, ur.tokenLimit)
if err != nil {
sendError(rw, http.StatusBadRequest, err)
return
}
if token == nil {
def := DefaultPageToken(ur.tokenLimit)
token = &def
}
page, err := getUnitPage(ur.cAPI, *token)
if err != nil {
log.Errorf("Failed fetching page of Units: %v", err)
sendError(rw, http.StatusInternalServerError, nil)
return
}
sendResponse(rw, http.StatusOK, page)
}
func getUnitPage(cAPI client.API, tok PageToken) (*schema.UnitPage, error) {
units, err := cAPI.Units()
if err != nil {
return nil, err
}
items, next := extractUnitPageData(units, tok)
page := schema.UnitPage{
Units: items,
}
if next != nil {
page.NextPageToken = next.Encode()
}
return &page, nil
}
func extractUnitPageData(all []*schema.Unit, tok PageToken) (items []*schema.Unit, next *PageToken) {
total := len(all)
startIndex := int((tok.Page - 1) * tok.Limit)
stopIndex := int(tok.Page * tok.Limit)
if startIndex < total {
if stopIndex > total {
stopIndex = total
} else {
n := tok.Next()
next = &n
}
items = all[startIndex:stopIndex]
}
return
}