-
Notifications
You must be signed in to change notification settings - Fork 28
/
impl.go
419 lines (371 loc) · 12.3 KB
/
impl.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
// Copyright 2015 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.
// The following enables go generate to generate the doc.go file.
//go:generate go run v.io/x/lib/cmdline/gendoc .
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"regexp"
"sort"
"strings"
"time"
"v.io/x/lib/cmdline"
"v.io/x/lib/set"
v23 "v.io/v23"
"v.io/v23/context"
"v.io/v23/naming"
"v.io/v23/options"
"v.io/v23/security"
"v.io/v23/security/access"
"v.io/v23/verror"
"v.io/x/ref/lib/v23cmd"
_ "v.io/x/ref/runtime/factories/static"
)
func main() {
cmdline.HideGlobalFlagsExcept(regexp.MustCompile(`^v23\.namespace\.root$`))
cmdline.Main(cmdRoot)
}
var (
flagLongGlob bool
flagInsecureResolve bool
flagInsecureResolveToMT bool
flagDeleteSubtree bool
flagShallowResolve bool
flagErrorOnAnyError bool
)
func init() {
cmdGlob.Flags.BoolVar(&flagLongGlob, "l", false, "Long listing format.")
cmdGlob.Flags.BoolVar(&flagErrorOnAnyError, "fail-on-any-error", false, "exit on any error, by default glob will report errors but not return a non-zero exit code")
cmdResolve.Flags.BoolVar(&flagInsecureResolve, "insecure", false, "Insecure mode: May return results from untrusted servers and invoke Resolve on untrusted mounttables")
cmdResolve.Flags.BoolVar(&flagShallowResolve, "s", false, "True to perform a shallow resolution")
cmdResolveToMT.Flags.BoolVar(&flagInsecureResolveToMT, "insecure", false, "Insecure mode: May return results from untrusted servers and invoke Resolve on untrusted mounttables")
cmdDelete.Flags.BoolVar(&flagDeleteSubtree, "r", false, "Delete all children of the name in addition to the name itself.")
}
var cmdGlob = &cmdline.Command{
Runner: v23cmd.RunnerFunc(runGlob),
Name: "glob",
Short: "Returns all matching entries from the namespace",
Long: "Returns all matching entries from the namespace.",
ArgsName: "<pattern>",
ArgsLong: `
<pattern> is a glob pattern that is matched against all the names below the
specified mount name.
`,
}
func handleErrors(successes int, errors []*naming.GlobError) error {
if len(errors) == 0 {
return nil
}
if !flagErrorOnAnyError && successes > 0 {
for _, err := range errors {
fmt.Fprintf(os.Stderr, "%s: %v\n", err.Name, err.Error)
}
return nil
}
msg := ""
for _, err := range errors {
msg += fmt.Sprintf("%s: %v\n", err.Name, err.Error)
}
return fmt.Errorf("%v", strings.TrimSuffix(msg, "\n"))
}
func runGlob(ctx *context.T, env *cmdline.Env, args []string) error {
if expected, got := 1, len(args); expected != got {
return env.UsageErrorf("glob: incorrect number of arguments, expected %d, got %d", expected, got)
}
pattern := args[0]
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
ns := v23.GetNamespace(ctx)
c, err := ns.Glob(ctx, pattern)
if err != nil {
ctx.Infof("ns.Glob(%q) failed: %v", pattern, err)
return err
}
errors := []*naming.GlobError{}
successes := 0
if flagLongGlob {
// Show all the information we received.
for res := range c {
switch v := res.(type) {
case *naming.GlobReplyEntry:
fmt.Fprint(env.Stdout, v.Value.Name)
for _, s := range v.Value.Servers {
delta := time.Until(s.Deadline.Time)
fmt.Fprintf(env.Stdout, " %s (Expires in %d sec)", s.Server, int(delta.Seconds()))
}
fmt.Fprintln(env.Stdout)
successes++
case *naming.GlobReplyError:
errors = append(errors, &v.Value)
}
}
return handleErrors(successes, errors)
}
// Show a sorted list of unique names, and any errors.
resultSet := make(map[string]struct{})
for res := range c {
switch v := res.(type) {
case *naming.GlobReplyEntry:
if v.Value.Name != "" {
resultSet[v.Value.Name] = struct{}{}
}
successes++
case *naming.GlobReplyError:
errors = append(errors, &v.Value)
}
}
results := set.String.ToSlice(resultSet)
sort.Strings(results)
for _, result := range results {
fmt.Fprintln(env.Stdout, result)
}
return handleErrors(successes, errors)
}
var cmdMount = &cmdline.Command{
Runner: v23cmd.RunnerFunc(runMount),
Name: "mount",
Short: "Adds a server to the namespace",
Long: "Adds server <server> to the namespace with name <name>.",
ArgsName: "<name> <server> <ttl>",
ArgsLong: `
<name> is the name to add to the namespace.
<server> is the object address of the server to add.
<ttl> is the TTL of the new entry. It is a decimal number followed by a unit
suffix (s, m, h). A value of 0s represents an infinite duration.
`,
}
func runMount(ctx *context.T, env *cmdline.Env, args []string) error {
if expected, got := 3, len(args); expected != got {
return env.UsageErrorf("mount: incorrect number of arguments, expected %d, got %d", expected, got)
}
name := args[0]
server := args[1]
ttlArg := args[2]
ttl, err := time.ParseDuration(ttlArg)
if err != nil {
return fmt.Errorf("TTL parse error: %v", err)
}
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
ns := v23.GetNamespace(ctx)
if err = ns.Mount(ctx, name, server, ttl); err != nil {
ctx.Infof("ns.Mount(%q, %q, %s) failed: %v", name, server, ttl, err)
return err
}
fmt.Fprintln(env.Stdout, "Server mounted successfully.")
return nil
}
var cmdUnmount = &cmdline.Command{
Runner: v23cmd.RunnerFunc(runUnmount),
Name: "unmount",
Short: "Removes a server from the namespace",
Long: "Removes server <server> with name <name> from the namespace.",
ArgsName: "<name> <server>",
ArgsLong: `
<name> is the name to remove from the namespace.
<server> is the object address of the server to remove.
`,
}
func runUnmount(ctx *context.T, env *cmdline.Env, args []string) error {
if expected, got := 2, len(args); expected != got {
return env.UsageErrorf("unmount: incorrect number of arguments, expected %d, got %d", expected, got)
}
name := args[0]
server := args[1]
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
ns := v23.GetNamespace(ctx)
if err := ns.Unmount(ctx, name, server); err != nil {
ctx.Infof("ns.Unmount(%q, %q) failed: %v", name, server, err)
return err
}
fmt.Fprintln(env.Stdout, "Server unmounted successfully.")
return nil
}
var cmdResolve = &cmdline.Command{
Runner: v23cmd.RunnerFunc(runResolve),
Name: "resolve",
Short: "Translates a object name to its object address(es)",
Long: "Translates a object name to its object address(es).",
ArgsName: "<name>",
ArgsLong: "<name> is the name to resolve.",
}
func runResolve(ctx *context.T, env *cmdline.Env, args []string) error {
if expected, got := 1, len(args); expected != got {
return env.UsageErrorf("resolve: incorrect number of arguments, expected %d, got %d", expected, got)
}
name := args[0]
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
ns := v23.GetNamespace(ctx)
var opts []naming.NamespaceOpt
if flagInsecureResolve {
opts = append(opts, options.NameResolutionAuthorizer{
Authorizer: security.AllowEveryone(),
})
}
var err error
var me *naming.MountEntry
if flagShallowResolve {
me, err = ns.ShallowResolve(ctx, name, opts...)
} else {
me, err = ns.Resolve(ctx, name, opts...)
}
if err != nil {
ctx.Infof("ns.Resolve(%q) failed: %v", name, err)
return err
}
for _, n := range me.Names() {
fmt.Fprintln(env.Stdout, n)
}
return nil
}
var cmdResolveToMT = &cmdline.Command{
Runner: v23cmd.RunnerFunc(runResolveToMT),
Name: "resolvetomt",
Short: "Finds the address of the mounttable that holds an object name",
Long: "Finds the address of the mounttable that holds an object name.",
ArgsName: "<name>",
ArgsLong: "<name> is the name to resolve.",
}
func runResolveToMT(ctx *context.T, env *cmdline.Env, args []string) error {
if expected, got := 1, len(args); expected != got {
return env.UsageErrorf("resolvetomt: incorrect number of arguments, expected %d, got %d", expected, got)
}
name := args[0]
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
ns := v23.GetNamespace(ctx)
var opts []naming.NamespaceOpt
if flagInsecureResolveToMT {
opts = append(opts, options.NameResolutionAuthorizer{
Authorizer: security.AllowEveryone(),
})
}
e, err := ns.ResolveToMountTable(ctx, name, opts...)
if err != nil {
ctx.Infof("ns.ResolveToMountTable(%q) failed: %v", name, err)
return err
}
for _, s := range e.Servers {
fmt.Fprintln(env.Stdout, naming.JoinAddressName(s.Server, e.Name))
}
return nil
}
var cmdPermissions = &cmdline.Command{
Name: "permissions",
Short: "Manipulates permissions on an entry in the namespace",
Long: `
Commands to get and set the permissions on a name - controlling the blessing
names required to resolve the name.
The permissions are provided as an JSON-encoded version of the Permissions type
defined in v.io/v23/security/access/types.vdl.
`,
Children: []*cmdline.Command{cmdPermissionsGet, cmdPermissionsSet},
}
var cmdPermissionsSet = &cmdline.Command{
Runner: v23cmd.RunnerFunc(runPermissionsSet),
Name: "set",
Short: "Sets permissions on a mount name",
Long: `
Set replaces the permissions controlling usage of a mount name.
`,
ArgsName: "<name> <permissions>",
ArgsLong: `
<name> is the name on which permissions are to be set.
<permissions> is the path to a file containing a JSON-encoded Permissions
object (defined in v.io/v23/security/access/types.vdl), or "-" for STDIN.
`,
}
func runPermissionsSet(ctx *context.T, env *cmdline.Env, args []string) error {
if expected, got := 2, len(args); expected != got {
return env.UsageErrorf("set: incorrect number of arguments, expected %d, got %d", expected, got)
}
name := args[0]
var perms access.Permissions
file := os.Stdin
if args[1] != "-" {
var err error
if file, err = os.Open(args[1]); err != nil {
return err
}
defer file.Close()
}
if err := json.NewDecoder(file).Decode(&perms); err != nil {
return err
}
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
ns := v23.GetNamespace(ctx)
for {
_, etag, err := ns.GetPermissions(ctx, name)
if err != nil && !errors.Is(err, naming.ErrNoSuchName) {
return err
}
if err = ns.SetPermissions(ctx, name, perms, etag); errors.Is(err, verror.ErrBadVersion) {
ctx.Infof("SetPermissions(%q, %q) failed: %v, retrying...", name, etag, err)
continue
}
return err
}
}
var cmdPermissionsGet = &cmdline.Command{
Runner: v23cmd.RunnerFunc(runPermissionsGet),
Name: "get",
Short: "Gets permissions on a mount name",
ArgsName: "<name>",
ArgsLong: `
<name> is a name in the namespace.
`,
Long: `
Get retrieves the permissions on the usage of a name.
The output is a JSON-encoded Permissions object (defined in
v.io/v23/security/access/types.vdl).
`,
}
func runPermissionsGet(ctx *context.T, env *cmdline.Env, args []string) error {
if expected, got := 1, len(args); expected != got {
return env.UsageErrorf("get: incorrect number of arguments, expected %d, got %d", expected, got)
}
name := args[0]
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
perms, _, err := v23.GetNamespace(ctx).GetPermissions(ctx, name)
if err != nil {
return err
}
return json.NewEncoder(env.Stdout).Encode(perms)
}
var cmdDelete = &cmdline.Command{
Runner: v23cmd.RunnerFunc(runDelete),
Name: "delete",
Short: "Deletes a name from the namespace",
ArgsName: "<name>",
ArgsLong: "<name> is a name to delete.",
Long: "Deletes a name from the namespace.",
}
func runDelete(ctx *context.T, env *cmdline.Env, args []string) error {
if expected, got := 1, len(args); expected != got {
return env.UsageErrorf("delete: incorrect number of arguments, expected %d, got %d", expected, got)
}
name := args[0]
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
return v23.GetNamespace(ctx).Delete(ctx, name, flagDeleteSubtree)
}
var cmdRoot = &cmdline.Command{
Name: "namespace",
Short: "resolves and manages names in the Vanadium namespace",
Long: `
Command namespace resolves and manages names in the Vanadium namespace.
The namespace roots are set from the command line via --v23.namespace.root
command line option or from environment variables that have a name starting
with V23_NAMESPACE, e.g. V23_NAMESPACE, V23_NAMESPACE_2, V23_NAMESPACE_GOOGLE,
etc. The command line options override the environment.
`,
Children: []*cmdline.Command{cmdGlob, cmdMount, cmdUnmount, cmdResolve, cmdResolveToMT, cmdPermissions, cmdDelete},
}