-
Notifications
You must be signed in to change notification settings - Fork 0
/
root.go
174 lines (153 loc) · 4.59 KB
/
root.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
package cmd
import (
"context"
"fmt"
"net"
"net/http"
"net/netip"
"os"
"os/signal"
"strings"
"syscall"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/reflection"
"github.com/caldog20/zeronet/controller"
"github.com/caldog20/zeronet/controller/auth"
"github.com/caldog20/zeronet/controller/db"
"github.com/caldog20/zeronet/controller/middleware"
controllerv1 "github.com/caldog20/zeronet/proto/gen/controller/v1"
"github.com/caldog20/zeronet/third_party"
)
var (
storePath string
prefix string
autoCert bool
grpcPort uint16
httpPort uint16
discoveryPort uint16
debug bool
rootCmd = &cobra.Command{
Use: "controller",
Short: "ZeroNet Controller",
Long: "",
Run: func(cmd *cobra.Command, args []string) {
ctx, cancel := context.WithCancel(context.Background())
go func() {
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)
log.Printf("Received %v signal, shutting down services\n", <-sigchan)
cancel()
}()
// Current uses logrus default logger with some tweaks
log.SetFormatter(&log.TextFormatter{FullTimestamp: true})
if debug {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
// TODO Implement config stuff/multiple commands
log.Printf("initializing sqlite store using file: %s", storePath)
db, err := db.New(storePath, log.WithField("type", "gorm"))
if err != nil {
log.Fatal(err)
}
pfix, err := netip.ParsePrefix(prefix)
if err != nil {
log.Fatalf("error parsing prefix: %s", err)
}
ctrl := controller.NewController(db, pfix)
tokenValidator, err := auth.NewTokenValidator(ctx)
if err != nil {
log.Fatalf("error creating token validator: %s", err)
}
// GRPC Server
grpcServer := controller.NewGRPCServer(ctrl, tokenValidator)
server := grpc.NewServer(grpc.UnaryInterceptor(middleware.NewUnaryLogInterceptor()))
controllerv1.RegisterControllerServiceServer(server, grpcServer)
reflection.Register(server)
eg, egCtx := errgroup.WithContext(ctx)
eg.Go(func() error {
log.Printf("starting grpc server on port: %d", grpcPort)
conn, err := net.Listen("tcp", fmt.Sprintf(":%d", grpcPort))
if err != nil {
return err
}
return server.Serve(conn)
})
// HTTP Server
// httpServer := controller.NewHTTPServer(ctrl, tokenValidator)
// eg.Go(func() error {
// log.Printf("starting http server on port: %d", httpPort)
// return httpServer.Serve(fmt.Sprintf(":%d", httpPort))
// })
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
err = controllerv1.RegisterControllerServiceHandlerFromEndpoint(
egCtx,
mux,
"localhost:50000",
opts,
)
if err != nil {
log.Fatal(err)
}
gwServer := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api") {
mux.ServeHTTP(w, r)
return
}
getOpenAPIHandler().ServeHTTP(w, r)
}),
}
eg.Go(func() error {
if err := gwServer.ListenAndServe(); err != http.ErrServerClosed {
return err
}
return nil
})
// Cleanup
eg.Go(func() error {
<-egCtx.Done()
server.GracefulStop()
gwServer.Shutdown(context.Background())
// httpServer.Close(context.Background())
return err
})
// Wait for all errgroup routines to finish before exiting
if err = eg.Wait(); err != nil {
log.Fatal(err)
}
},
}
)
func getOpenAPIHandler() http.Handler {
return http.FileServer(http.FS(third_party.OpenAPI))
}
func init() {
rootCmd.PersistentFlags().
StringVar(&storePath, "storepath", "store.db", "file path for controller store persistence")
rootCmd.PersistentFlags().
StringVar(&prefix, "prefix", "100.70.0.0/24", "prefix to use for the overlay network")
rootCmd.PersistentFlags().
BoolVar(&autoCert, "autocert", false, "enable autocert for controller")
rootCmd.PersistentFlags().
Uint16Var(&grpcPort, "grpcport", 50000, "port to listen for grpc connections")
rootCmd.PersistentFlags().
BoolVar(&debug, "debug", false, "enable debug logging")
rootCmd.PersistentFlags().
Uint16Var(&httpPort, "httpport", 8080, "port to listen for http connections")
}
// TODO handle signals and contextual things here
func Execute() {
if err := rootCmd.Execute(); err != nil {
log.Println(err)
os.Exit(1)
}
}