-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgshellbuilder.go
1335 lines (1204 loc) · 34.1 KB
/
gshellbuilder.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gshellos
import (
"context"
"crypto/md5"
_ "embed" // go embed
"encoding/base64"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"math/rand"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"gopkg.in/yaml.v3"
as "github.com/godevsig/adaptiveservice"
"github.com/godevsig/glib/sys/log"
"github.com/godevsig/glib/sys/shell"
"github.com/traefik/yaegi/interp"
)
//go:embed bin/rev
var commitRev string
//go:embed bin/gittag
var version string
//go:embed bin/buildtag
var buildTags string
//go:embed bin/buildtime
var buildTime string
const (
defaultWorkDir = "/var/tmp/gshell"
godevsigPublisher = "godevsig"
)
var (
loglevel = "info"
providerID = "self"
pluginDir = "/usr/lib/gshell/plugins"
debugService func(lg *log.Logger)
)
func init() {
if len(commitRev) == 0 {
commitRev = "devel"
}
if len(version) == 0 {
version = commitRev[:5]
}
if len(buildTags) == 0 {
buildTags = "unknown"
}
if len(buildTime) == 0 {
buildTime = "unknown"
}
}
var getSelfID = getSelfIDFunc()
func getSelfIDFunc() func() string {
var selfID = "NA"
var once sync.Once
return func() string {
once.Do(func() {
c := as.NewClient(as.WithScope(as.ScopeProcess | as.ScopeOS)).SetDiscoverTimeout(0)
conn := <-c.Discover(as.BuiltinPublisher, as.SrvProviderInfo)
if conn != nil {
conn.SendRecv(&as.ReqProviderInfo{}, &selfID)
conn.Close()
}
})
return selfID
}
}
func trimName(name string, size int) string {
if len(name) > size {
name = name[:size-3] + "..."
}
return name
}
type subCmd struct {
*flag.FlagSet
action func() error
}
var cmds []subCmd
func newLogger(logStream *log.Stream, loggerName string) *log.Logger {
level := log.Linfo
switch loglevel {
case "debug":
level = log.Ldebug
logStream.SetFlag(log.Lfileline)
case "warn":
level = log.Lwarn
case "error":
level = log.Lerror
}
logStream.SetLoglevel("*", level)
return logStream.NewLogger(loggerName, log.Linfo)
}
func newCmd(name, usage string, helps ...string) string {
var b strings.Builder
fmt.Fprintf(&b, "%s %s", name, usage)
for _, line := range helps {
fmt.Fprintf(&b, "\n\t%s", line)
}
return b.String()
}
var updateInterval = "600"
func addDaemonCmd() {
cmd := flag.NewFlagSet(newCmd("daemon", "[options]", "Start local gshell daemon"), flag.ExitOnError)
workDir := cmd.String("wd", defaultWorkDir, "set working directory")
rootRegistry := cmd.Bool("root", false, "enable root registry service")
invisible := cmd.Bool("invisible", false, "make gshell daemon invisible in gshell service network")
registryAddr := cmd.String("registry", "", "root registry address in host:port format")
lanBroadcastPort := cmd.String("bcast", "", "broadcast port for LAN")
codeRepo := cmd.String("repo", "", "code repo local path or https address in format site/org/proj/branch")
updateURL := cmd.String("update", "", "url of artifacts to update gshell, require -root")
clean := cmd.Bool("clean", false, "clean status/log/code files from old runs before starting the new run")
daemonRunning := func() bool {
c := as.NewClient(as.WithScope(as.ScopeOS)).SetDiscoverTimeout(0)
conn := <-c.Discover(godevsigPublisher, "gshellDaemon")
if conn == nil {
return false
}
conn.Close()
return true
}
action := func() error {
if providerID != "self" {
return errors.New("command does not run on remote node")
}
if daemonRunning() {
return errors.New("detected a running gshell daemon on local node")
}
workDir := *workDir
if *clean {
killGrgByName("*")
os.RemoveAll(workDir)
os.RemoveAll(gshellTempDir)
}
if err := os.MkdirAll(gshellTempDir, 0755); err != nil {
return err
}
if err := os.MkdirAll(workDir+"/logs", 0755); err != nil {
return err
}
if err := os.MkdirAll(workDir+"/status", 0755); err != nil {
return err
}
logStream := log.NewStream("daemon")
if err := logStream.SetOutput("file:" + workDir + "/logs/daemon.log"); err != nil {
return err
}
lg := newLogger(logStream, "daemon")
lg.Infof("daemon version: %s", version)
if *clean {
lg.Infof("work dir and temp dir recreated")
}
cmdArgs := os.Args
scope := as.ScopeAll
if len(*registryAddr) == 0 {
scope &= ^as.ScopeWAN // not ScopeWAN
}
if len(*lanBroadcastPort) == 0 {
scope &= ^as.ScopeLAN // not ScopeLAN
}
updateURL := *updateURL
if len(updateURL) != 0 || *rootRegistry {
if scope&as.ScopeWAN != as.ScopeWAN {
return errors.New("root registry address not set")
}
}
codeRepo := *codeRepo
crs := &codeRepoSvc{}
if len(codeRepo) != 0 {
fi, err := os.Stat(codeRepo)
if err != nil || !fi.Mode().IsDir() {
crs.httpRepoInfo = strings.Split(codeRepo, "/")
if len(crs.httpRepoInfo) != 4 {
return errors.New("wrong repo format")
}
if httpOp == nil {
return errors.New("http feature not enabled, check build tags")
}
} else {
crs.localRepoPath, _ = filepath.Abs(codeRepo)
}
}
euid := os.Geteuid()
if err := syscall.Setreuid(euid, euid); err != nil {
return err
}
egid := os.Getegid()
if err := syscall.Setregid(egid, egid); err != nil {
return err
}
opts := []as.Option{
as.WithScope(scope),
as.WithLogger(lg),
}
if len(*registryAddr) != 0 {
opts = append(opts, as.WithRegistryAddr(*registryAddr))
}
s := as.NewServer(opts...).
SetPublisher(godevsigPublisher).
SetScaleFactors(4, 0, 0).
EnableServiceLister().
EnableMessageTracer()
defer s.Close()
if len(*lanBroadcastPort) != 0 {
s.SetBroadcastPort(*lanBroadcastPort)
}
if !*invisible && scope&as.ScopeNetwork != 0 {
s.EnableAutoReverseProxy()
}
if *rootRegistry {
s.EnableRootRegistry()
s.EnableIPObserver()
if len(updateURL) != 0 {
if httpOp == nil {
return errors.New("http feature not enabled, check build tags")
}
updateURL = strings.TrimSuffix(updateURL, "/")
updtr := &updater{url: updateURL, lg: lg}
if err := s.Publish("updater",
updaterKnownMsgs,
as.OnNewStreamFunc(func(ctx as.Context) { ctx.SetContext(updtr) }),
); err != nil {
return err
}
}
}
if len(crs.localRepoPath) != 0 || len(crs.httpRepoInfo) != 0 {
scope := scope
if len(crs.localRepoPath) != 0 {
scope &= ^as.ScopeWAN // not ScopeWAN
scope &= ^as.ScopeLAN // not ScopeLAN
}
if err := s.PublishIn(scope, "codeRepo",
codeRepoKnownMsgs,
as.OnNewStreamFunc(func(ctx as.Context) { ctx.SetContext(crs) }),
); err != nil {
return err
}
}
var updateChan chan struct{}
go func() {
if _, has := os.LookupEnv("GSHELL_NOUPDATE"); has {
lg.Infoln("no auto update")
return
}
i, _ := strconv.Atoi(updateInterval)
lg.Debugf("updater interval: %d", i)
exe, err := os.Executable()
if err != nil {
lg.Warnf("executable path error: %s", err)
return
}
lg.Debugf("executable path: %s", exe)
for {
time.Sleep(time.Duration(i) * time.Second)
c := as.NewClient(as.WithLogger(lg)).SetDiscoverTimeout(0)
conn := <-c.Discover(godevsigPublisher, "updater")
if conn == nil {
continue
}
var gshellbin *gshellBin
lg.Debugln("trying to update")
err := conn.SendRecv(tryUpdate{revInuse: commitRev, arch: runtime.GOARCH}, &gshellbin)
conn.Close()
lg.Debugln("updater returned with", err)
if err != nil {
if strings.Contains(err.Error(), ErrNoUpdate.Error()) {
lg.Debugln(ErrNoUpdate)
} else {
lg.Warnf("get gshell bin error: %v", err)
}
continue
}
if fmt.Sprintf("%x", md5.Sum(gshellbin.bin)) != gshellbin.md5 {
lg.Warnf("gshell new version md5 mismatch")
continue
}
newFile := workDir + "/gshell.updating"
if err := os.WriteFile(newFile, gshellbin.bin, 0755|fs.ModeSetuid|fs.ModeSetgid); err != nil {
lg.Warnf("create gshell new version failed")
continue
}
lg.Debugln(shell.Run("ls -lh " + newFile))
lg.Infof("updating gshell version...")
if err := os.Rename(newFile, exe); err != nil {
lg.Infof("failed to rename new gshell to %s: %s", exe, err)
output, _ := shell.Run("mv -f " + newFile + " " + exe)
if len(output) != 0 {
lg.Warnf("failed to mv new gshell to %s: %s", exe, output)
continue
}
}
if output, _ := shell.Run("chmod ugo+s " + exe); len(output) != 0 {
lg.Warnf("failed to set gshell bin permission : %s", output)
continue
}
updateChan = make(chan struct{})
s.CloseWait()
cmd := cmdArgs[0]
args := cmdArgs[1:]
if cmdArgs[0] == "gshell.tester" {
coverageOpt := "-test.coverprofile=.test/l2_gshelld" + genID(3) + ".cov"
args = append([]string{"-test.run", "^TestRunMain$", coverageOpt, "--"}, args...)
}
var newArgs []string
for _, s := range args {
if !strings.Contains(s, "-clean") {
newArgs = append(newArgs, s)
}
}
if err := exec.Command(cmd, newArgs...).Start(); err != nil {
lg.Errorf("start new gshell failed: %v", err)
} else {
lg.Infof("new version gshell started")
}
close(updateChan)
return
}
}()
gd := &daemon{
lg: lg,
workDir: workDir,
}
visibleScope := scope
if *invisible {
visibleScope = as.ScopeProcess | as.ScopeOS
}
if err := s.PublishIn(visibleScope, "gshellDaemon",
daemonKnownMsgs,
as.OnNewStreamFunc(gd.onNewStream),
); err != nil {
return err
}
if debugService != nil {
go debugService(lg)
}
go gd.grgRestarter()
err := s.Serve()
if updateChan != nil {
<-updateChan
}
return err
}
cmds = append(cmds, subCmd{cmd, action})
}
func addListCmd() {
cmd := flag.NewFlagSet(newCmd("list", "[options]", "List services in all scopes"), flag.ExitOnError)
verbose := cmd.Bool("v", false, "show verbose info")
publisher := cmd.String("p", "*", "publisher name, can be wildcard")
service := cmd.String("s", "*", "service name, can be wildcard")
action := func() error {
if providerID != "self" {
return errors.New("command does not run on remote node")
}
opts := []as.Option{
as.WithScope(as.ScopeProcess | as.ScopeOS),
as.WithLogger(newLogger(log.DefaultStream, "main")),
}
c := as.NewClient(opts...).SetDiscoverTimeout(0)
conn := <-c.Discover(as.BuiltinPublisher, as.SrvServiceLister)
if conn == nil {
return as.ErrServiceNotFound(as.BuiltinPublisher, as.SrvServiceLister)
}
defer conn.Close()
msg := as.ListService{TargetScope: as.ScopeAll, Publisher: *publisher, Service: *service}
var scopes [4][]*as.ServiceInfo
if err := conn.SendRecv(&msg, &scopes); err != nil {
return err
}
selfID := getSelfID()
if *verbose {
for _, services := range scopes {
for _, svc := range services {
if svc.ProviderID == selfID {
svc.ProviderID = "self"
}
fmt.Printf("PUBLISHER: %s\n", svc.Publisher)
fmt.Printf("SERVICE : %s\n", svc.Service)
fmt.Printf("PROVIDER : %s\n", svc.ProviderID)
addr := svc.Addr
if addr[len(addr)-1] == 'P' {
addr = addr[:len(addr)-1] + "(proxied)"
}
fmt.Printf("ADDRESS : %s\n\n", addr)
}
}
} else {
list := make(map[string]*as.Scope)
for i, services := range scopes {
for _, svc := range services {
if svc.ProviderID == selfID {
svc.ProviderID = "self"
}
k := svc.Publisher + "_" + svc.Service + "_" + svc.ProviderID
p, has := list[k]
if !has {
v := as.Scope(0)
p = &v
list[k] = p
}
*p = *p | 1<<i
}
}
names := make([]string, 0, len(list))
for name := range list {
names = append(names, name)
}
sort.Strings(names)
fmt.Println("PUBLISHER SERVICE PROVIDER WLOP(SCOPE)")
for _, svc := range names {
p := list[svc]
if p == nil {
panic("nil p")
}
ss := strings.Split(svc, "_")
fmt.Printf("%-24s %-24s %-12s %4b\n", trimName(ss[0], 24), trimName(ss[1], 24), ss[2], *p)
}
}
return nil
}
cmds = append(cmds, subCmd{cmd, action})
}
func addIDCmd() {
cmd := flag.NewFlagSet(newCmd("id", "", "Print self provider ID"), flag.ExitOnError)
action := func() error {
if providerID != "self" {
return errors.New("command does not run on remote node")
}
selfID := getSelfID()
fmt.Println(selfID)
return nil
}
cmds = append(cmds, subCmd{cmd, action})
}
func addExecCmd() {
cmd := flag.NewFlagSet(newCmd("exec", "<path[/file.go]> [args...]", "Run go file(s) in a local GRE"), flag.ExitOnError)
action := func() error {
if providerID != "self" {
return errors.New("command does not run on remote node")
}
args := cmd.Args()
if len(args) == 0 {
return errors.New("no path provided, see gshell exec --help")
}
if err := loadPlugins(pluginDir); err != nil {
fmt.Fprintf(os.Stderr, "load plugins error: %v", err)
}
filePath := args[0]
zip, err := zipPathToBuffer(filePath)
if err != nil {
return err
}
gsh, err := newShellWithCodeZip(zip)
if err != nil {
return err
}
defer gsh.close()
if err := gsh.init(interp.Options{Args: args}); err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
return gsh.start(ctx)
}
cmds = append(cmds, subCmd{cmd, action})
}
func addStartCmd() {
cmd := flag.NewFlagSet(newCmd("__start", "[options]", "Start named GRG"), flag.ExitOnError)
workDir := cmd.String("wd", defaultWorkDir, "set working directory")
grgNameVer := cmd.String("group", "", "GRG name")
getRealtimePriority := func(pid int) int {
statData, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
if err != nil {
return 0
}
fields := strings.Fields(string(statData))
if len(fields) < 40 {
return 0
}
priorityStr := fields[39]
priority, err := strconv.Atoi(priorityStr)
if err != nil {
return 0
}
return priority
}
action := func() error {
grgNameVer := *grgNameVer
if providerID != "self" {
return errors.New("command does not run on remote node")
}
if len(grgNameVer) == 0 {
return errors.New("no GRG name, see gshell __start --help")
}
workDir := *workDir
logStream := log.NewStream("grg")
logStream.SetOutput("file:" + workDir + "/logs/grg.log")
lg := newLogger(logStream, "grg-"+grgNameVer)
if err := loadPlugins(pluginDir); err != nil {
lg.Warnf("load plugins error: %v", err)
}
opts := []as.Option{
as.WithScope(as.ScopeOS),
as.WithLogger(lg),
}
var serverErr error
rtprio := getRealtimePriority(os.Getpid())
maxProcs := 0
if v, has := os.LookupEnv("GOMAXPROCS"); has {
if i, err := strconv.Atoi(v); err == nil {
maxProcs = i
}
}
grgStatDir := fmt.Sprintf("%s/status/grg-%s-%d-%d", workDir, grgNameVer, rtprio, maxProcs)
if err := os.MkdirAll(grgStatDir, 0755); err != nil {
return err
}
defer func() {
// remove the file only if no errors
if serverErr == nil {
os.RemoveAll(grgStatDir)
}
}()
grgLockFile := filepath.Join(grgStatDir, ".lock")
f, err := os.OpenFile(grgLockFile, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return err
}
defer f.Close()
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
return err
}
lg.Debugf("status %s locked", grgStatDir)
defer func() {
syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
lg.Debugf("status %s unlocked", grgStatDir)
}()
s := as.NewServer(opts...).SetPublisher(godevsigPublisher)
grg := &grg{
processInfo: processInfo{
name: grgNameVer,
rtPriority: rtprio,
maxProcs: maxProcs,
statDir: grgStatDir,
pid: os.Getpid(),
},
workDir: workDir,
server: s,
lg: lg,
gres: make(map[string]*greCtl),
}
if err := grg.loadGREs(); err != nil {
return err
}
if err := s.Publish("grg-"+grgNameVer,
grgKnownMsgs,
as.OnNewStreamFunc(grg.onNewStream),
); err != nil {
return err
}
if debugService != nil {
go debugService(lg)
}
serverErr = s.Serve()
return serverErr
}
cmds = append(cmds, subCmd{cmd, action})
}
func randStringRunes(n int) string {
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func connectDaemon(providerID string, lg *log.Logger) (conn as.Connection) {
if providerID == "self" || providerID == getSelfID() { // local
c := as.NewClient(as.WithLogger(lg), as.WithScope(as.ScopeOS)).SetDiscoverTimeout(3)
conn = <-c.Discover(godevsigPublisher, "gshellDaemon")
} else { // remote
c := as.NewClient(as.WithLogger(lg), as.WithScope(as.ScopeNetwork)).SetDiscoverTimeout(3)
conn = <-c.Discover(godevsigPublisher, "gshellDaemon", providerID)
}
return
}
func addRepoCmd() {
cmd := flag.NewFlagSet(newCmd("repo", "[ls [path]]", "List contens of the code repo seen on local/remote node"), flag.ExitOnError)
action := func() error {
args := cmd.Args()
lg := newLogger(log.DefaultStream, "main")
conn := connectDaemon(providerID, lg)
if conn == nil {
return as.ErrServiceNotFound(godevsigPublisher, "gshellDaemon")
}
defer conn.Close()
if len(args) == 0 {
addr := "NA"
conn.SendRecv(codeRepoAddrByNode{}, &addr)
fmt.Println(addr)
return nil
}
if args[0] == "ls" {
path := ""
if len(args) >= 2 {
path = args[1]
}
var entries []dirEntry
if err := conn.SendRecv(codeRepoListByNode{codeRepoList{path}}, &entries); err != nil {
return err
}
for _, e := range entries {
if e.isDir {
fmt.Printf("\x1b[34m%s\x1b[0m\n", e.name)
} else {
fmt.Println(e.name)
}
}
return nil
}
return fmt.Errorf("unknown command %s, see gshell repo --help", args[0])
}
cmds = append(cmds, subCmd{cmd, action})
}
func addRunCmd() {
cmd := flag.NewFlagSet(newCmd("run",
"[options] <path[/file.go]> [args...]",
"Try local code path[/file.go] first or fetch the code from `gshell repo`,",
"and run it in a new GRE in specified GRG on local/remote node",
"Use `gshell repo ls [path]` to see available code files"),
flag.ExitOnError)
grgName := cmd.String("group", "", `name of the GRG in below forms
name-version: exact target group name, usually specifying an existing GRG
name: target daemon version will be used if no version specified
random group name will be used if no name specified`)
maxprocs := cmd.Int("maxprocs", 0, "set GOMAXPROCS variable")
rtPriority := cmd.Int("rt", 0, `set the GRG to SCHED_RR min/max priority 1/99 on new GRG creation
silently ignore errors if real-time priority can not be set`)
interactive := cmd.Bool("i", false, "enter interactive mode")
autoRemove := cmd.Bool("rm", false, "auto-remove the GRE when it exits")
autoRestart := cmd.Uint("restart", 0, `auto-restart the GRE on failure for at most specified times
only applicable for non-interactive mode`)
autoImport := cmd.Bool("import", false, "auto-import dependent packages")
action := func() error {
grgName := *grgName
args := cmd.Args()
if len(args) == 0 {
return errors.New("no file provided, see gshell run --help")
}
if len(grgName) == 0 {
grgName = randStringRunes(6)
} else {
if strings.Contains(grgName, "*") {
return errors.New("wrong use of wildcard(*), see gshell run --help")
}
if strings.Count(grgName, "-") > 1 {
return errors.New("wrong group format, see gshell run --help")
}
}
maxprocs := *maxprocs
if maxprocs < 0 {
maxprocs = 0
}
rtPriority := *rtPriority
if rtPriority < 0 || rtPriority > 99 {
return errors.New("wrong SCHED_RR priority, see man chrt")
}
lg := newLogger(log.DefaultStream, "main")
if *interactive {
*autoRestart = 0
}
conn := connectDaemon(providerID, lg)
if conn == nil {
return as.ErrServiceNotFound(godevsigPublisher, "gshellDaemon")
}
defer conn.Close()
jobcmd := JobCmd{
Args: args,
AutoRemove: *autoRemove,
AutoRestartMax: *autoRestart,
}
// try to use local file/path if it exists
filePath := args[0]
if zip, err := zipPathToBuffer(filePath); err == nil {
jobcmd.CodeZip = zip
}
selfID := getSelfID()
cmd := cmdRun{
grgCmdRun: grgCmdRun{
JobCmd: jobcmd,
Interactive: *interactive,
AutoImport: *autoImport,
RequestedBy: selfID,
},
GRGName: grgName,
RtPriority: rtPriority,
Maxprocs: maxprocs,
}
if err := conn.Send(&cmd); err != nil {
return err
}
if !*interactive {
var greid string
if err := conn.Recv(&greid); err != nil {
return err
}
fmt.Println(greid)
return nil
}
ioconn := as.NewStreamIO(conn)
lg.Debugln("enter interactive io")
go io.Copy(ioconn, os.Stdin)
_, err := io.Copy(os.Stdout, ioconn)
lg.Debugln("exit interactive io")
return err
}
cmds = append(cmds, subCmd{cmd, action})
}
func addKillCmd() {
cmd := flag.NewFlagSet(newCmd("kill",
"[options] names ...",
"Terminate the named GRG(s) on local/remote node",
"name supports simple wildcard(*), but must be full GRG name when force kill"),
flag.ExitOnError)
force := cmd.Bool("f", false, "force terminate the GRG even if there are still running GREs in it")
action := func() error {
args := cmd.Args()
if len(args) == 0 {
return errors.New("no GRG specified, see gshell kill --help")
}
force := *force
if force {
str := strings.Join(args, " ")
if strings.Contains(str, "*") {
return errors.New("wildcard not supported when force kill, see gshell kill --help")
}
}
lg := newLogger(log.DefaultStream, "main")
conn := connectDaemon(providerID, lg)
if conn == nil {
return as.ErrServiceNotFound(godevsigPublisher, "gshellDaemon")
}
defer conn.Close()
cmd := cmdKill{
GRGNames: args,
Force: force,
}
var reply string
if err := conn.SendRecv(&cmd, &reply); err != nil {
return err
}
fmt.Println(reply)
return nil
}
cmds = append(cmds, subCmd{cmd, action})
}
func addJoblistCmd() {
cmd := flag.NewFlagSet(newCmd("joblist",
"[options] <save|load>",
"Save all current jobs to file or load them to run on local/remote node"),
flag.ExitOnError)
file := cmd.String("file", "default.joblist.yaml", "the file save to or load from")
tiny := cmd.Bool("tiny", false, "discard bytecode")
action := func() error {
args := cmd.Args()
if len(args) == 0 {
return errors.New("no subcommand provided, see gshell joblist --help")
}
action := args[0]
file, err := filepath.Abs(*file)
if err != nil {
return err
}
lg := newLogger(log.DefaultStream, "main")
conn := connectDaemon(providerID, lg)
if conn == nil {
return as.ErrServiceNotFound(godevsigPublisher, "gshellDaemon")
}
defer conn.Close()
tiny := *tiny
switch action {
case "save":
var jlist joblist
if err := conn.SendRecv(cmdJoblistSave{tiny}, &jlist); err != nil {
return err
}
// turn bytecode to string
for _, grg := range jlist.GRGs {
for _, job := range grg.Jobs {
if !tiny {
job.CodeZipBase64 = base64.StdEncoding.EncodeToString(job.CodeZip)
}
job.CodeZip = nil
job.Cmd = strings.Join(job.Args, " ")
job.Args = nil
}
}
f, err := os.Create(file)
if err != nil {
return err
}
defer f.Close()
enc := yaml.NewEncoder(f)
if err := enc.Encode(jlist); err != nil {
return err
}
fmt.Println(file, "saved")
case "load":
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
var jlist joblist
dec := yaml.NewDecoder(f)
if err := dec.Decode(&jlist); err != nil {
return err
}
grgMap := make(map[string]struct{})
// back to bytecode
for _, grg := range jlist.GRGs {
if len(grg.Name) == 0 {
return fmt.Errorf("empty grg name in joblist %s", file)
}
if _, has := grgMap[grg.Name]; has {
return fmt.Errorf("duplicated grg entry %s in joblist %s", grg.Name, file)
}
grgMap[grg.Name] = struct{}{}
for _, job := range grg.Jobs {
if len(job.CodeZipBase64) != 0 {
data, err := base64.StdEncoding.DecodeString(job.CodeZipBase64)
if err != nil {
return fmt.Errorf("parse joblist %s with error: %v", file, err)
}
job.CodeZipBase64 = ""
job.CodeZip = data
}
job.Args = strings.Fields(job.Cmd)
if len(job.Args) == 0 {
return fmt.Errorf("parse joblist %s error: empty job", file)
}
job.Cmd = ""
}
}
selfID := getSelfID()
if err := conn.SendRecv(&cmdJoblistLoad{jlist, selfID}, nil); err != nil {
return err
}
default:
return errors.New("wrong subcommand, see gshell joblist --help")
}
return nil
}
cmds = append(cmds, subCmd{cmd, action})
}
func addPsCmd() {
cmd := flag.NewFlagSet(newCmd("ps", "[options] [GRE IDs ...|names ...]", "Show jobs by GRE ID or name on local/remote node"), flag.ExitOnError)
grgName := cmd.String("group", "*", "in which GRG, wildcard(*) is supported")
action := func() error {
lg := newLogger(log.DefaultStream, "main")
conn := connectDaemon(providerID, lg)
if conn == nil {
return as.ErrServiceNotFound(godevsigPublisher, "gshellDaemon")
}
defer conn.Close()
msg := cmdQuery{GRGName: *grgName, IDPattern: cmd.Args()}
var ggis []*grgGREInfo
if err := conn.SendRecv(&msg, &ggis); err != nil {
return err
}
for _, ggi := range ggis {
grei := ggi.GREInfos
sort.Slice(grei, func(i int, j int) bool {
return grei[i].StartTime.After(grei[j].StartTime)
})
}
sort.Slice(ggis, func(i, j int) bool {
if len(ggis[i].GREInfos) == 0 {
return false
}
if len(ggis[j].GREInfos) == 0 {
return true
}
return ggis[i].GREInfos[0].StartTime.After(ggis[j].GREInfos[0].StartTime)
})
if len(msg.IDPattern) != 0 { // info
for _, ggi := range ggis {
for _, grei := range ggi.GREInfos {
fmt.Println("GRE ID :", grei.ID)
fmt.Println("IN GROUP :", ggi.Name)
fmt.Println("NAME :", grei.Name)
fmt.Println("ARGS :", grei.Args)
fmt.Println("REQUESTED BY :", grei.RequestedBy)