forked from getcfs/megacfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
468 lines (443 loc) · 11.6 KB
/
main.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
// Package main builds a 'cfs' executable that is the client application for
// CFS.
package main
import (
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
_ "net/http/pprof"
"os"
"os/exec"
"os/signal"
"os/user"
"strings"
"sync"
"syscall"
"github.com/getcfs/megacfs/formic"
"github.com/gholt/brimtext"
"github.com/gholt/cpcp"
"github.com/gholt/dudu"
"github.com/gholt/findfind"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
)
var logger *zap.Logger
type redirectGRPCLogger struct {
sugaredLogger *zap.SugaredLogger
}
func (logger *redirectGRPCLogger) Fatal(args ...interface{}) {
logger.sugaredLogger.Fatal(args)
}
func (logger *redirectGRPCLogger) Fatalf(format string, args ...interface{}) {
logger.sugaredLogger.Fatalf(format, args)
}
func (logger *redirectGRPCLogger) Fatalln(args ...interface{}) {
logger.sugaredLogger.Fatal(args)
}
func (logger *redirectGRPCLogger) Print(args ...interface{}) {
logger.sugaredLogger.Debug(args)
}
func (logger *redirectGRPCLogger) Printf(format string, args ...interface{}) {
logger.sugaredLogger.Debugf(format, args)
}
func (logger *redirectGRPCLogger) Println(args ...interface{}) {
logger.sugaredLogger.Debug(args)
}
var redirectGRPCLoggerV redirectGRPCLogger
func init() {
debug := brimtext.TrueString(os.Getenv("DEBUG"))
for i := 1; i < len(os.Args)-1; i++ {
if os.Args[i] == "-o" {
v := os.Args[i+1]
if v == "debug" || strings.HasPrefix(v, "debug,") || strings.Contains(v, ",debug,") || strings.HasSuffix(v, ",debug") {
debug = true
break
}
}
}
var baseLogger *zap.Logger
var err error
if debug {
baseLogger, err = zap.NewDevelopmentConfig().Build()
baseLogger.Debug("Logging in developer mode.")
} else {
baseLogger, err = zap.NewProduction()
}
if err != nil {
panic(err)
}
logger = baseLogger.With(zap.String("name", "cfs"))
redirectGRPCLoggerV.sugaredLogger = baseLogger.With(zap.String("name", "cfs")).Sugar()
grpclog.SetLogger(&redirectGRPCLoggerV)
}
// FORMIC PORT
const (
PORT = 12300
)
// NullWriter ...
type NullWriter int
func (NullWriter) Write([]byte) (int, error) { return 0, nil }
var cfsVersion string
var buildDate string
var commitVersion string
var goVersion string
func auth(authURL string, username string, password string) string {
var token string
logger.Debug("auth called", zap.String("authURL", authURL), zap.String("username", username))
if authURL == "dev" {
logger.Debug("auth short-circuited due to 'dev' mode")
return ""
}
if token = os.Getenv("OS_TOKEN"); token != "" {
logger.Debug("auth short-circuited due to OS_TOKEN set")
return token
}
body := fmt.Sprintf(`{"auth":{"identity":{"methods":["password"],"password":{"user":{
"domain":{"id":"default"},"name":"%s","password":"%s"}}}}}`, username, password)
rbody := strings.NewReader(body)
if !strings.HasSuffix(authURL, "/") {
authURL += "/"
}
req, err := http.NewRequest("POST", authURL+"v3/auth/tokens", rbody)
if err != nil {
logger.Debug("auth error from NewRequest POST", zap.Error(err))
os.Exit(1)
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
logger.Debug("auth error from DefaultClient.Do POST", zap.Error(err))
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != 201 {
logger.Debug("auth error from POST response status", zap.Int("status", resp.StatusCode))
os.Exit(1)
}
token = resp.Header.Get("X-Subject-Token")
if len(token) == 0 {
logger.Debug("auth succeeded but ended up with zero-length token")
} else {
logger.Debug("auth succeeded")
}
return token
}
func mount(config map[string]string) error {
f := flag.NewFlagSet("mount", flag.ContinueOnError)
usageError := false
f.Usage = func() {
usageError = true
}
usageErr := errors.New(strings.TrimSpace(`
Usage:
cfs mount [-o option,...] [serveraddr:]<fsid> <mountpoint>
Options:
-o debug enables debug output
-o ro mount the filesystem read only
-o allow_other allow access to other users
-o noumount skips the fusermount -uz retry on first error
-o pprof=<host:port> Go tool pprof support; listens on <host:port>
Examples:
cfs mount 11111111-1111-1111-1111-111111111111 /mnt/test
cfs mount -o debug,ro 127.0.0.1:11111111-1111-1111-1111-111111111111 /mnt/test
`))
var options string
f.StringVar(&options, "o", "", "")
f.Parse(flag.Args()[1:])
if usageError {
return usageErr
}
if f.NArg() != 2 {
return usageErr
}
addrFSID := f.Args()[0]
if !strings.Contains(addrFSID, ":") {
addrFSID = config["addr"] + ":" + addrFSID
}
parts := strings.Split(addrFSID, ":")
if len(parts) != 2 {
fmt.Println("Invalid filesystem:", addrFSID)
return usageErr
}
addr := fmt.Sprintf("%s:%d", strings.ToLower(parts[0]), PORT)
fsid := parts[1]
mountpoint := f.Args()[1]
// Verify mountpoint exists
_, err := os.Stat(mountpoint)
if os.IsNotExist(err) {
return fmt.Errorf("Mount point %s does not exist\n", mountpoint)
}
// parse mount options string
clargs := getArgs(options)
if hostPort, ok := clargs["pprof"]; ok {
if hostPort == "" {
hostPort = ":9100"
}
if strings.HasPrefix(hostPort, "*:") {
hostPort = hostPort[1:]
}
go http.ListenAndServe(hostPort, nil)
}
for iteration := 0; ; iteration++ {
switch iteration {
case 0:
case 1:
if _, noumount := clargs["noumount"]; noumount {
return err
}
logger.Debug("retrying after fusermount -uz", zap.Error(err))
exec.Command("fusermount", "-uz", mountpoint).Run()
default:
return err
}
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
waitGroup := &sync.WaitGroup{}
shutdownChan := make(chan struct{})
waitGroup.Add(1)
go func() {
for {
select {
case <-ch:
logger.Debug("exit signal received, attempting to unmount")
exec.Command("fusermount", "-u", mountpoint).Run()
waitGroup.Done()
return
case <-shutdownChan:
waitGroup.Done()
return
}
}
}()
_, allowOther := clargs["allow_other"]
_, readOnly := clargs["ro"]
if err = formic.NewFuseFormic(&formic.FuseFormicConfig{
Logger: logger,
Mountpoint: mountpoint,
Address: addr,
FSID: fsid,
AllowOther: allowOther,
ReadOnly: readOnly,
}).Serve(); err != nil {
continue
}
close(shutdownChan)
waitGroup.Wait()
break
}
return nil
}
func main() {
// try to read config file
configured := false
config := map[string]string{}
user, err := user.Current()
if err != nil {
fmt.Printf("Unable to identify curent user: %v\n", err)
os.Exit(1)
}
var configfile string
if user.HomeDir != "" {
configfile = user.HomeDir + "/.cfs.json"
} else {
configfile = ".cfs.json"
}
f, err := ioutil.ReadFile(configfile)
if err == nil {
json.Unmarshal(f, &config)
configured = true
}
ip, _ := config["addr"]
authURL, _ := config["authURL"]
username, _ := config["username"]
password, _ := config["password"]
addr := fmt.Sprintf("%s:%d", ip, PORT)
flag.Usage = func() {
fmt.Println("Usage:")
fmt.Println(" cfs <command> [options] <args>")
fmt.Println("Commands:")
fmt.Println(" configure create configuration file")
fmt.Println(" list list all filesystems")
fmt.Println(" create create a new filesytem")
fmt.Println(" show show filesystem details")
fmt.Println(" update update filesystem name")
fmt.Println(" delete delete an existing filesystem")
fmt.Println(" grant grant access to a filesystem")
fmt.Println(" revoke revoke access to a filesystem")
fmt.Println(" mount mount an existing filesystem")
fmt.Println(" version show client version")
fmt.Println(" check check a file for errors")
fmt.Println(" cp parallel cp command; cfs cp --help")
fmt.Println(" du parallel du command; cfs du --help")
fmt.Println(" find parallel find command; cfs find --help")
fmt.Println(" help show usage for cfs")
fmt.Println("Examples:")
fmt.Println(" cfs configure")
fmt.Println(" cfs create <name>")
fmt.Println(" cfs grant <client addr> <fsid>")
fmt.Println(" cfs mount <server addr>:<fsid> <mountpoint>")
os.Exit(1)
}
flag.Parse()
if flag.NArg() == 0 {
flag.Usage()
}
command := flag.Args()[0]
switch command {
default:
fmt.Println("Invalid Command")
flag.Usage()
case "help":
flag.Usage()
case "version":
fmt.Println("version:", cfsVersion)
fmt.Println("commit:", commitVersion)
fmt.Println("build date:", buildDate)
fmt.Println("go version:", goVersion)
os.Exit(0)
case "configure":
err := configure(configfile)
if err != nil {
fmt.Printf("Error writing config file: %v\n", err)
os.Exit(1)
}
case "list":
if !configured {
fmt.Println("You must run \"cfs configure\" first.")
os.Exit(1)
}
err := list(addr, authURL, username, password)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
case "show":
if !configured {
fmt.Println("You must run \"cfs configure\" first.")
os.Exit(1)
}
err := show(addr, authURL, username, password)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
case "create":
if !configured {
fmt.Println("You must run \"cfs configure\" first.")
os.Exit(1)
}
err := create(addr, authURL, username, password)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
case "delete":
if !configured {
fmt.Println("You must run \"cfs configure\" first.")
os.Exit(1)
}
err := del(addr, authURL, username, password)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
case "update":
if !configured {
fmt.Println("You must run \"cfs configure\" first.")
os.Exit(1)
}
err := update(addr, authURL, username, password)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
case "grant":
if !configured {
fmt.Println("You must run \"cfs configure\" first.")
os.Exit(1)
}
err := grant(addr, authURL, username, password)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
case "revoke":
if !configured {
fmt.Println("You must run \"cfs configure\" first.")
os.Exit(1)
}
err := revoke(addr, authURL, username, password)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
case "check":
if !configured {
fmt.Println("You must run \"cfs configure\" first.")
os.Exit(1)
}
err := check(addr)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
case "mount":
err := mount(config)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
case "cp":
if err := cpcp.CPCP(flag.Args()[1:]); err != nil {
fmt.Println(err)
os.Exit(1)
}
case "du":
if err := dudu.DUDU(flag.Args()[1:]); err != nil {
fmt.Println(err)
os.Exit(1)
}
case "find":
if err := findfind.FindFind(flag.Args()[1:]); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
}
func getArgs(args string) map[string]string {
clargs := make(map[string]string)
optList := strings.Split(args, ",")
for _, item := range optList {
if strings.Contains(item, "=") {
value := strings.Split(item, "=")
if value[0] == "" || value[1] == "" {
logger.Fatal("Invalid option", zap.String("left side", value[0]), zap.String("right side", value[1]))
os.Exit(1)
} else {
clargs[value[0]] = value[1]
}
} else {
clargs[item] = ""
}
}
return clargs
}
// setupWS ...
func setupWS(svr string) *grpc.ClientConn {
var opts []grpc.DialOption
creds := credentials.NewTLS(&tls.Config{
InsecureSkipVerify: true,
})
opts = append(opts, grpc.WithTransportCredentials(creds))
conn, err := grpc.Dial(svr, opts...)
if err != nil {
logger.Fatal("failed to dial", zap.Error(err))
}
return conn
}