-
Notifications
You must be signed in to change notification settings - Fork 6
/
service.go
449 lines (403 loc) · 12.1 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
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
// Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
"text/template"
"time"
"v.io/v23/context"
"v.io/v23/conventions"
"v.io/v23/rpc"
"v.io/v23/security"
"v.io/v23/security/access"
"v.io/v23/verror"
"v.io/v23/vom"
"v.io/x/ref/services/allocator"
)
const pkgPath = "v.io/x/ref/services/allocator/allocatord"
var (
errLimitExceeded = verror.Register(pkgPath+".errLimitExceeded", verror.NoRetry, "{1:}{2:} limit ({3}) exceeded")
errGlobalLimitExceeded = verror.Register(pkgPath+".errGlobalLimitExceeded", verror.NoRetry, "{1:}{2:} global limit ({3}) exceeded")
)
type allocatorImpl struct {
baseBlessings security.Blessings
baseBlessingNames []string
}
// Create creates a new instance of the service.
// It returns a handle for the new instance.
func (i *allocatorImpl) Create(ctx *context.T, call rpc.ServerCall) (string, error) {
b, _ := security.RemoteBlessingNames(ctx, call.Security())
ctx.Infof("Create() called by %v", b)
email := emailFromBlessingNames(b)
if email == "" {
return "", verror.New(verror.ErrNoAccess, ctx, "unable to determine caller's email address")
}
return create(ctx, email, i.baseBlessings, i.baseBlessingNames)
}
// Destroy destroys the instance with the given handle.
func (i *allocatorImpl) Destroy(ctx *context.T, call rpc.ServerCall, kName string) error {
b, _ := security.RemoteBlessingNames(ctx, call.Security())
ctx.Infof("Destroy(%q) called by %v", kName, b)
email := emailFromBlessingNames(b)
if email == "" {
return verror.New(verror.ErrNoAccess, ctx, "unable to determine caller's email address")
}
return destroy(ctx, email, kName)
}
// List returns a list of all the instances owned by the caller.
func (i *allocatorImpl) List(ctx *context.T, call rpc.ServerCall) ([]allocator.Instance, error) {
b, _ := security.RemoteBlessingNames(ctx, call.Security())
ctx.Infof("List() called by %v", b)
email := emailFromBlessingNames(b)
if email == "" {
return nil, verror.New(verror.ErrNoAccess, ctx, "unable to determine caller's email address")
}
return serverInstances(ctx, email)
}
func create(ctx *context.T, email string, baseBlessings security.Blessings, baseBlessingNames []string) (string, error) {
// Enforce a limit on the number of instances. These tests are a little
// bit racy. It's possible that multiple calls to create() will run
// concurrently and that we'll end up with too many instances.
if n, err := serverInstances(ctx, email); err != nil {
return "", err
} else if len(n) >= maxInstancesPerUserFlag {
return "", verror.New(errLimitExceeded, ctx, maxInstancesPerUserFlag)
}
if n, err := serverInstances(ctx, ""); err != nil {
return "", err
} else if len(n) >= maxInstancesFlag {
return "", verror.New(errGlobalLimitExceeded, ctx, maxInstancesFlag)
}
kName, err := newKubeName()
if err != nil {
return "", err
}
mName := mountNameFromKubeName(ctx, kName)
cfg, cleanup, err := createDeploymentConfig(ctx, email, kName, mName, baseBlessingNames)
defer cleanup()
if err != nil {
return "", err
}
vomBlessings, err := vom.Encode(baseBlessings)
if err != nil {
return "", err
}
if err := createPersistentDisk(ctx, kName); err != nil {
return "", err
}
if _, err := vkube(
"start", "-f", cfg,
"--base-blessings", base64.URLEncoding.EncodeToString(vomBlessings),
"--wait",
kName,
); err != nil {
ctx.Errorf("Error: %v", err)
deletePersistentDisk(ctx, kName)
return "", verror.New(verror.ErrInternal, ctx, err)
}
return kName, nil
}
func scale(ctx *context.T, email, kName string, replicas int) error {
args := []string{"kubectl", "scale", "--timeout=1m", fmt.Sprintf("--replicas=%d", replicas), "deployment", kName}
if _, err := vkube(args...); err != nil {
ctx.Errorf("Error: %v", err)
return verror.New(verror.ErrInternal, ctx, err)
}
return nil
}
func suspendImpl(ctx *context.T, email, kName string) error {
return scale(ctx, email, kName, 0)
}
func suspend(ctx *context.T, email, kName string) error {
if err := isOwnerOfInstance(ctx, email, kName); err != nil {
return err
}
return suspendImpl(ctx, email, kName)
}
func resumeImpl(ctx *context.T, email, kName string) error {
return scale(ctx, email, kName, 1)
}
func resume(ctx *context.T, email, kName string) error {
if err := isOwnerOfInstance(ctx, email, kName); err != nil {
return err
}
return resumeImpl(ctx, email, kName)
}
func resetDisk(ctx *context.T, email, kName string) error {
instance, err := getInstance(ctx, email, kName)
if err != nil {
return err
}
if instance.Replicas > 0 {
if err := suspend(ctx, email, kName); err != nil {
return err
}
}
if err := deletePersistentDisk(ctx, kName); err != nil {
return err
}
if err := createPersistentDisk(ctx, kName); err != nil {
return err
}
if instance.Replicas > 0 {
return resume(ctx, email, kName)
}
return nil
}
func destroy(ctx *context.T, email, kName string) error {
if err := isOwnerOfInstance(ctx, email, kName); err != nil {
return err
}
cfg, cleanup, err := createDeploymentConfig(ctx, email, kName, "", nil)
defer cleanup()
if err != nil {
return err
}
if _, err := vkube("stop", "-f", cfg); err != nil {
ctx.Errorf("Error: %v", err)
return verror.New(verror.ErrInternal, ctx, err)
}
return deletePersistentDisk(ctx, kName)
}
func createDeploymentConfig(ctx *context.T, email, deploymentName, mountName string, baseBlessingNames []string) (string, func(), error) {
cleanup := func() {}
acl, err := accessList(ctx, email)
if err != nil {
return "", cleanup, err
}
blessingNames := make([]string, len(baseBlessingNames))
for i, b := range baseBlessingNames {
blessingNames[i] = b + security.ChainSeparator + deploymentName
}
creatorInfo, err := creatorInfo(ctx, email, mountName, blessingNames)
if err != nil {
return "", cleanup, err
}
t, err := template.ParseFiles(deploymentTemplateFlag)
if err != nil {
return "", cleanup, err
}
data := struct {
AccessList string
CreatorInfo string
MountName string
Name string
OwnerHash string
Version string
}{
AccessList: acl,
CreatorInfo: creatorInfo,
MountName: mountName,
Name: deploymentName,
OwnerHash: emailHash(email),
Version: serverVersionFlag,
}
f, err := ioutil.TempFile("", "allocator-deployment-")
if err != nil {
return "", cleanup, err
}
defer f.Close()
cleanup = func() { os.Remove(f.Name()) }
if err := t.Execute(f, data); err != nil {
return "", cleanup, err
}
return f.Name(), cleanup, nil
}
// accessList returns a double encoded JSON access list that can be used in a
// Deployment template that contains something like:
// "--v23.permissions.literal={\"Admin\": {{.AccessList}} }"
// The access list include the creator.
func accessList(ctx *context.T, email string) (string, error) {
var acl access.AccessList
if globalAdminsFlag != "" {
for _, admin := range strings.Split(globalAdminsFlag, ",") {
acl.In = append(acl.In, security.BlessingPattern(admin))
}
}
for _, blessing := range conventions.ParseBlessingNames(blessingNamesFromEmail(email)...) {
acl.In = append(acl.In, blessing.UserPattern())
}
j, err := json.Marshal(acl)
if err != nil {
ctx.Errorf("json.Marshal(%#v) failed: %v", acl, err)
return "", err
}
// JSON encode again, because the access list is in a JSON template.
str := string(j)
j, err = json.Marshal(str)
if err != nil {
ctx.Errorf("json.Marshal(%#v) failed: %v", str, err)
return "", err
}
// Remove the quotes.
return string(j[1 : len(j)-1]), nil
}
type creatorInfoData struct {
Email string `json:"email"`
BlessingNames []string `json:"blessingNames"`
MountName string `json:"mountName"`
}
// creatorInfo returns a double encoded JSON access list that can be used as
// annotation in a Deployment template, e.g.
// "annotations": {
// "v.io/allocator-creator-info": {{.CreatorInfo}}
// }
func creatorInfo(ctx *context.T, email, mountName string, blessingNames []string) (string, error) {
j, err := json.Marshal(creatorInfoData{email, blessingNames, mountName})
if err != nil {
ctx.Errorf("json.Marshal() failed: %v", err)
return "", err
}
// JSON encode again, because the annotation is in a JSON template.
str := string(j)
j, err = json.Marshal(str)
if err != nil {
ctx.Errorf("json.Marshal(%#v) failed: %v", str, err)
return "", err
}
return string(j), nil
}
func decodeCreatorInfo(s string) (data creatorInfoData, err error) {
err = json.Unmarshal([]byte(s), &data)
return
}
func emailHash(email string) string {
h := sha1.Sum([]byte(email))
return hex.EncodeToString(h[:])
}
func serverInstances(ctx *context.T, email string) ([]allocator.Instance, error) {
args := []string{"kubectl", "get", "deployments", "-o", "json"}
if email != "" {
args = append(args, "-l", "ownerHash="+emailHash(email))
}
var out []byte
var err error
for retry := 0; retry < 10; retry++ {
if out, err = vkube(args...); err == nil {
break
}
time.Sleep(time.Second)
}
if err != nil {
return nil, err
}
var list struct {
Items []struct {
Metadata struct {
Name string `json:"name"`
CreationTime time.Time `json:"creationTimestamp"`
Annotations map[string]string `json:"annotations"`
} `json:"metadata"`
Spec struct {
Replicas int32 `json:"replicas"`
Template struct {
Metadata struct {
Labels struct {
Version string `json:"version"`
} `json:"labels"`
} `json:"metadata"`
} `json:"template"`
} `json:"spec"`
} `json:"items"`
}
if err := json.Unmarshal(out, &list); err != nil {
return nil, err
}
instances := []allocator.Instance{}
for _, l := range list.Items {
if !strings.HasPrefix(l.Metadata.Name, serverNameFlag+"-") {
continue
}
cInfo, err := decodeCreatorInfo(l.Metadata.Annotations["v.io/allocator-creator-info"])
if err != nil {
ctx.Errorf("decodeCreatorInfo failed: %v", err)
continue
}
instances = append(instances, allocator.Instance{
Handle: l.Metadata.Name,
MountName: cInfo.MountName,
BlessingNames: cInfo.BlessingNames,
CreationTime: l.Metadata.CreationTime,
Replicas: l.Spec.Replicas,
Version: l.Spec.Template.Metadata.Labels.Version,
})
}
return instances, nil
}
func getInstance(ctx *context.T, email, kName string) (allocator.Instance, error) {
instances, err := serverInstances(ctx, email)
if err != nil {
return allocator.Instance{}, err
}
for _, i := range instances {
if i.Handle == kName {
return i, nil
}
}
return allocator.Instance{}, verror.New(verror.ErrNoExistOrNoAccess, nil)
}
func isOwnerOfInstance(ctx *context.T, email, kName string) error {
_, err := getInstance(ctx, email, kName)
return err
}
func createPersistentDisk(ctx *context.T, name string) error {
if out, err := gcloud("compute", "disks", "create", name, "--size", diskSizeFlag); err != nil {
ctx.Errorf("disk creation failed: %v: %s", err, string(out))
return err
}
return nil
}
func deletePersistentDisk(ctx *context.T, name string) error {
var (
start = time.Now()
out []byte
err error
)
for time.Since(start) < 5*time.Minute {
if out, err = gcloud("compute", "disks", "delete", name); err == nil {
return nil
}
time.Sleep(time.Second)
}
ctx.Errorf("disk deletion failed: %v: %s", err, string(out))
return err
}
func gcloud(args ...string) ([]byte, error) {
data, err := ioutil.ReadFile(vkubeCfgFlag)
if err != nil {
return nil, err
}
var config struct {
Project string `json:"project"`
Zone string `json:"zone"`
}
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
args = append(args, "--project", config.Project, "--zone", config.Zone)
return exec.Command(gcloudBinFlag, args...).CombinedOutput()
}
func vkube(args ...string) (out []byte, err error) {
args = append(
[]string{
"--config=" + vkubeCfgFlag,
"--kubectl=" + kubectlBinFlag,
"--no-headers",
},
args...,
)
out, err = exec.Command(vkubeBinFlag, args...).CombinedOutput()
if err != nil {
err = fmt.Errorf("vkube(%v) failed: %v\n%s\n", args, err, string(out))
}
return
}