-
Notifications
You must be signed in to change notification settings - Fork 33
/
main.go
269 lines (238 loc) · 7.8 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
// Copyright 2020 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/apigee/registry/pkg/log"
"github.com/apigee/registry/pkg/log/interceptor"
"github.com/apigee/registry/server/registry"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/pflag"
"google.golang.org/grpc"
"gopkg.in/yaml.v3"
)
// version is replaced by tag when binaries are generated by GoReleaser
var version = "dev"
const prometheusPath = "/metrics"
// ServerConfig is the top-level configuration structure.
type ServerConfig struct {
// Server port. If unset or zero, an open port will be assigned.
Port int `yaml:"port"`
Database DatabaseConfig `yaml:"database"`
Logging LoggingConfig `yaml:"logging"`
Pubsub PubsubConfig `yaml:"pubsub"`
Monitoring MonitoringConfig `yaml:"monitoring"`
}
// DatabaseConfig holds database configuration.
type DatabaseConfig struct {
// Driver for the database connection.
// Values: [ sqlite3, postgres, cloudsqlpostgres ]
Driver string `yaml:"driver"`
// Config for the database connection. The format is a data source name (DSN).
// PostgreSQL Reference: See "Connection Strings" at https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
// SQLite Reference: See "URI filename examples" at https://www.sqlite.org/c3ref/open.html
Config string `yaml:"config"`
}
// LoggingConfig holds logging configuration.
type LoggingConfig struct {
// Level of logging to print to standard output.
// Values: [ debug, info, warn, error, fatal ]
Level string `yaml:"level"`
// Format of log entries.
// Options: [ json, text ]
Format string `yaml:"format"`
}
// PubsubConfig holds pubsub (notification) configuration.
type PubsubConfig struct {
// Enable Pub/Sub for event notification publishing.
// Values: [ true, false ]
Enable bool `yaml:"enable"`
// Project ID of the Google Cloud project to use for Pub/Sub.
// Reference: https://cloud.google.com/resource-manager/docs/creating-managing-projects
Project string `yaml:"project"`
}
type MonitoringConfig struct {
// Enable Monitoring
// Values: [ true, false ], default: false
// Prometheus stats available at /metrics.
Enable bool `yaml:"enable"`
// Listener address if enabled.
// If unset or zero, an open port will be assigned.
// Example: ":9090" or ""
Address string `yaml:"address"`
}
// default configuration
var config = ServerConfig{
Port: 8080,
Database: DatabaseConfig{
Driver: "sqlite3",
Config: "file:/tmp/registry.db",
},
Logging: LoggingConfig{
Level: "info",
Format: "text",
},
Pubsub: PubsubConfig{
Enable: false,
Project: "",
},
Monitoring: MonitoringConfig{
Enable: false,
Address: ":9090",
},
}
func main() {
var configPath string
var printVersion, noMigrate bool
pflag.StringVarP(&configPath, "configuration", "c", "", "The server configuration file to load.")
pflag.BoolVarP(&printVersion, "version", "v", false, "Emit version and exit")
pflag.BoolVar(&noMigrate, "no-migrate", false, "Disable database auto-migrate")
pflag.Parse()
if printVersion {
fmt.Printf("registry-server version %s\n", version)
os.Exit(0)
}
// Use a default logger configuration until we load the server config.
bootLogger := log.NewLogger()
if configPath != "" {
bootLogger.Infof("Loading configuration from %s", configPath)
raw, err := os.ReadFile(configPath)
if err != nil {
bootLogger.WithError(err).Fatal("Failed to open config file")
}
// Expand environment variables before unmarshalling.
expanded := []byte(os.ExpandEnv(string(raw)))
err = yaml.Unmarshal(expanded, &config)
if err != nil {
bootLogger.WithError(err).Fatalf("Failed to read config file")
}
}
if err := validateConfig(); err != nil {
bootLogger.WithError(err).Fatalf("Invalid configuration")
}
// Use logging options from the server config.
var (
logOpts = loggerOptions(config.Logging)
logger = log.NewLogger(logOpts...)
logInterceptor = interceptor.CallLogger(logOpts...)
)
registryServer, err := registry.New(registry.Config{
Database: config.Database.Driver,
DBConfig: config.Database.Config,
LogLevel: config.Logging.Level,
LogFormat: config.Logging.Format,
Notify: config.Pubsub.Enable,
ProjectID: config.Pubsub.Project,
NoMigrate: noMigrate,
})
if err != nil {
logger.WithError(err).Fatalf("Failed to create registry server")
}
var serverOptions []grpc.ServerOption
if config.Monitoring.Enable {
serverOptions = []grpc.ServerOption{
grpc.ChainUnaryInterceptor(grpc_prometheus.UnaryServerInterceptor, logInterceptor),
grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
}
} else {
serverOptions = []grpc.ServerOption{
grpc.UnaryInterceptor(logInterceptor),
}
}
listener, server, err := registryServer.ServeGRPC(
&net.TCPAddr{Port: config.Port},
serverOptions...,
)
if err != nil {
logger.WithError(err).Fatalf("Failed to create TCP listener")
}
logger.Infof("Listening on %s", listener.Addr())
if config.Monitoring.Enable {
grpc_prometheus.EnableHandlingTimeHistogram()
metricsListener, err := net.Listen("tcp", config.Monitoring.Address)
if err != nil {
logger.WithError(err).Fatalf("Failed to create TCP listener")
}
mux := http.NewServeMux()
mux.Handle(prometheusPath, promhttp.Handler())
httpServer := &http.Server{
Addr: listener.Addr().String(),
Handler: mux,
}
logger.Infof("Monitoring on %s", metricsListener.Addr().String())
go func() {
if err := httpServer.Serve(metricsListener); err != nil {
logger.WithError(err).Fatalf("Failed to start http server")
}
}()
}
// Wait for an interruption signal.
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGTERM)
<-done
server.GracefulStop()
registryServer.Close()
}
func validateConfig() error {
if config.Port < 0 {
return fmt.Errorf("invalid port %q: must be non-negative", config.Port)
}
switch driver := config.Database.Driver; driver {
case "sqlite3", "postgres", "cloudsqlpostgres":
default:
return fmt.Errorf("invalid database.driver %q: must be one of [sqlite3, postgres, cloudsqlpostgres]", driver)
}
switch level := config.Logging.Level; level {
case "fatal", "error", "warn", "info", "debug":
default:
return fmt.Errorf("invalid logging.level %q: must be one of [fatal, error, warn, info, debug]", level)
}
switch format := config.Logging.Format; format {
case "json", "text":
default:
return fmt.Errorf("invalid logging format %q: must be one of [json, text]", format)
}
if project := config.Pubsub.Project; config.Pubsub.Enable && project == "" {
return fmt.Errorf("invalid pubsub.project %q: pubsub cannot be enabled without GCP project ID", project)
}
return nil
}
func loggerOptions(conf LoggingConfig) []log.Option {
opts := make([]log.Option, 0, 2)
switch conf.Level {
case "debug":
opts = append(opts, log.DebugLevel)
case "info":
opts = append(opts, log.InfoLevel)
case "warn":
opts = append(opts, log.WarnLevel)
case "error":
opts = append(opts, log.ErrorLevel)
case "fatal":
opts = append(opts, log.FatalLevel)
}
switch conf.Format {
case "json":
opts = append(opts, log.JSONFormat(os.Stderr))
case "text":
opts = append(opts, log.TextFormat(os.Stderr))
}
return opts
}