This repository has been archived by the owner on Dec 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logserver.go
212 lines (177 loc) · 5.71 KB
/
logserver.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
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"git.sgu.ru/ultramarine/logserver/auth"
"git.sgu.ru/ultramarine/logserver/cmd"
"git.sgu.ru/ultramarine/logserver/conf"
"git.sgu.ru/ultramarine/logserver/pb"
"git.sgu.ru/ultramarine/logserver/server"
_ "github.com/ClickHouse/clickhouse-go"
"github.com/gorilla/mux"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/jmoiron/sqlx"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
confName = kingpin.Flag("conf", "Path to config file.").Short('c').Default("logserver.conf").String()
installWEBDependencies = kingpin.Flag("install-spa-dependencies", "Install WEB app dependencies.").Short('i').Bool()
buildSPA = kingpin.Flag("build-spa", "Build WEB app.").Short('b').Bool()
tlsEnabled = kingpin.Flag("tls", "If used TLS cookies will have Secure flag").Short('s').Bool()
)
func init() {
kingpin.Parse()
if *installWEBDependencies {
log.Info("Running 'npm install'...")
if err := cmd.InstallWEBDependenciesCmd.Run(); err != nil {
log.Fatalf("Failed to install web app dependencies: %s", err)
}
log.Info("Dependencies of web app installed")
}
if *buildSPA {
log.Info("Building web app...")
if err := cmd.BuildWEBAppCmd.Run(); err != nil {
log.Fatalf("Failed to build web app: %s", err)
}
log.Info("Web app builded successfully")
}
if _, err := os.Stat("ui/node_modules"); os.IsNotExist(err) {
log.Fatal("Dependencies of web app are not installed.\nRun program with '-i' flag or run 'npm install' in 'ui' folder")
}
if _, err := os.Stat("ui/build"); os.IsNotExist(err) {
log.Fatal("Web app are not built.\nRun program with '-b' flag or run 'npm run build' in 'ui' folder")
}
}
func main() {
if err := conf.Load(*confName); err != nil {
log.Fatalf("Failed to load configuration: %s", err)
}
auth.InitKeysAndCookies(*tlsEnabled)
ctx := context.Background()
db, err := sqlx.ConnectContext(ctx, "clickhouse", fmt.Sprintf("%s?username=%s&password=%s&database=%s", conf.Config.DBHost, conf.Config.DBUser, conf.Config.DBPass, conf.Config.DBName))
if err != nil {
log.Fatalf("Failed to connect to database: %v", err)
}
defer db.Close()
log.Info("Connected to ClickHouse database")
var (
logger = log.New()
srv = server.LogServer{DB: db}
errChan = make(chan error, 1000)
)
go func() {
listener, err := net.Listen("tcp", ":"+conf.Config.GRPCPort)
if err != nil {
errChan <- err
return
}
creds, err := credentials.NewServerTLSFromFile(conf.Config.CertPath, conf.Config.KeyPath)
if err != nil {
errChan <- err
return
}
entry := log.NewEntry(logger)
opts := []grpc_logrus.Option{
grpc_logrus.WithLevels(grpc_logrus.DefaultCodeToLevel),
}
grpc_logrus.ReplaceGrpcLogger(entry)
gRPCServer := grpc.NewServer(
grpc.Creds(creds),
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_auth.UnaryServerInterceptor(auth.LDAPAuthFunc),
grpc_logrus.UnaryServerInterceptor(entry, opts...),
),
)
pb.RegisterLogServiceServer(gRPCServer, srv)
log.Infof("Started LogServer on %s port", conf.Config.GRPCPort)
errChan <- gRPCServer.Serve(listener)
}()
go func() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
b, err := ioutil.ReadFile(conf.Config.ClientCertPath)
if err != nil {
errChan <- err
return
}
cp := x509.NewCertPool()
if !cp.AppendCertsFromPEM(b) {
errChan <- errors.New("Failed to append certificates")
return
}
tlsConfig := &tls.Config{
InsecureSkipVerify: false,
RootCAs: cp,
}
gwmux := runtime.NewServeMux()
opts := []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
grpc.WithUnaryInterceptor(grpc_logrus.UnaryClientInterceptor(log.NewEntry(logger))),
}
err = pb.RegisterLogServiceHandlerFromEndpoint(ctx, gwmux, fmt.Sprintf("localhost:%s", conf.Config.GRPCPort), opts)
if err != nil {
errChan <- err
return
}
spa := spaHandler{staticPath: "ui/build", indexPath: "index.html"}
router := mux.NewRouter()
router.PathPrefix("/api").Handler(gwmux)
router.HandleFunc("/auth", auth.Handler)
router.HandleFunc("/logout", auth.LogoutHandler)
router.PathPrefix("/").Handler(spa)
router.Use(auth.TwoCookieAuthMiddleware)
srv := &http.Server{
Handler: router,
Addr: ":" + conf.Config.GatewayPort,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
errChan <- srv.ListenAndServe()
}()
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
errChan <- fmt.Errorf("%v", <-c)
}()
log.Info(<-errChan)
}
type spaHandler struct {
staticPath string
indexPath string
}
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path, err := filepath.Abs(r.URL.Path)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
path = filepath.Join(h.staticPath, path)
if _, err = os.Stat(path); os.IsNotExist(err) {
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}