-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathglu.go
377 lines (311 loc) · 9.81 KB
/
glu.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
package glu
import (
"context"
"fmt"
"io/fs"
"iter"
"log/slog"
"maps"
"net/http"
"net/url"
"os"
"os/signal"
"slices"
"syscall"
"time"
"github.com/get-glu/glu/pkg/cli"
"github.com/get-glu/glu/pkg/config"
"github.com/get-glu/glu/pkg/containers"
"github.com/get-glu/glu/pkg/core"
otlpruntime "go.opentelemetry.io/contrib/instrumentation/runtime"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
"go.opentelemetry.io/otel/exporters/prometheus"
metricsdk "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
"golang.org/x/sync/errgroup"
)
// Metadata is an alias for the core Metadata structure (see core.Metadata)
type Metadata = core.Metadata
// Resource is an alias for the core Resource interface (see core.Resource)
type Resource = core.Resource
// Pipeline is an alias for the core Pipeline interface (see core.Pipeline)
type Pipeline = core.Pipeline
// NewPipeline delegates to core.NewPipeline
func NewPipeline(meta Metadata) *Pipeline {
return core.NewPipeline(meta)
}
// Phase is an alias for the core Phase interface (see core.Phase)
type Phase = core.Phase
// Descriptor is an alias for the core Descriptor interface (see core.Descriptor)
type Descriptor = core.Descriptor
// Edge is an alias for the core Edge interface (see core.Edge)
type Edge = core.Edge
// Name is a utility for quickly creating an instance of Metadata
// with a name (required) and optional labels / annotations
func Name(name string, opts ...containers.Option[Metadata]) Metadata {
meta := Metadata{Name: name}
containers.ApplyAll(&meta, opts...)
return meta
}
// Label returns a functional option for Metadata which sets
// a single label k/v pair on the provided Metadata
func Label(k, v string) containers.Option[Metadata] {
return func(m *core.Metadata) {
if m.Labels == nil {
m.Labels = map[string]string{}
}
m.Labels[k] = v
}
}
// Annotation returns a functional option for Metadata which sets
// a single annotation k/v pair on the provided Metadata
func Annotation(k, v string) containers.Option[Metadata] {
return func(m *core.Metadata) {
if m.Annotations == nil {
m.Annotations = map[string]string{}
}
m.Annotations[k] = v
}
}
type shutdownFunc func(context.Context) error
// System is the primary entrypoint for build a set of Glu pipelines.
// It supports functions for adding new pipelines, registering triggers
// running the API server and handly command-line inputs.
type System struct {
ctx context.Context
meta Metadata
conf *Config
pipelines map[string]*core.Pipeline
err error
ui fs.FS
server *Server
shutdownFuncs []shutdownFunc
}
// WithUI configures the provided fs.FS implementation to be served as the filesystem
// mounted on the root path in the API
//
// glu.NewSystem(ctx, glu.Name("mysystem"), glu.WithUI(ui.FS()))
// see: github.com/get-glu/glu/tree/main/ui sub-module for the pre-built default UI.
func WithUI(ui fs.FS) containers.Option[System] {
return func(s *System) {
s.ui = ui
}
}
// NewSystem constructs and configures a new system with the provided metadata.
func NewSystem(ctx context.Context, meta Metadata, opts ...containers.Option[System]) *System {
r := &System{
ctx: ctx,
meta: meta,
pipelines: map[string]*core.Pipeline{},
}
containers.ApplyAll(r, opts...)
r.server = newServer(r, r.ui)
return r
}
// Context returns the systems root context.
func (s *System) Context() context.Context {
return s.ctx
}
// GetPipeline returns a pipeline by name.
func (s *System) GetPipeline(name string) (*core.Pipeline, error) {
pipeline, ok := s.pipelines[name]
if !ok {
return nil, fmt.Errorf("pipeline %q: %w", name, core.ErrNotFound)
}
return pipeline, nil
}
// Pipelines returns an iterator across all name and pipeline pairs
// previously registered on the system.
func (s *System) Pipelines() iter.Seq2[string, *core.Pipeline] {
return maps.All(s.pipelines)
}
// AddPipeline invokes a pipeline builder function provided by the caller.
// The function is provided with the systems configuration and (if successful)
// the system registers the resulting pipeline.
func (s *System) AddPipeline(pipeline *core.Pipeline) *System {
s.pipelines[pipeline.Metadata().Name] = pipeline
return s
}
func (s *System) Configuration() (_ *Config, err error) {
if s.conf != nil {
return s.conf, nil
}
conf, err := config.ReadFromFS(os.DirFS("."))
if err != nil {
return nil, err
}
var level slog.Level
if err := level.UnmarshalText([]byte(conf.Log.Level)); err != nil {
return nil, err
}
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: level,
})))
s.conf = newConfigSource(s.ctx, conf)
return s.conf, nil
}
// Run invokes or serves the entire system.
// Given command-line arguments are provided then the system is run as a CLI.
// Otherwise, the system runs in server mode, which means that:
// - The API is hosted on the configured port
// - Triggers are setup (schedules etc.)
func (s *System) Run() error {
if s.err != nil {
return s.err
}
ctx, cancel := signal.NotifyContext(s.ctx, os.Interrupt, syscall.SIGTERM)
defer cancel()
if len(os.Args) > 1 {
return cli.Run(ctx, s, os.Args...)
}
sConf, err := s.Configuration()
if err != nil {
return err
}
var (
conf = sConf.conf
srv = http.Server{
Addr: fmt.Sprintf("%s:%d", conf.Server.Host, conf.Server.Port),
Handler: s.server,
}
)
s.shutdownFuncs = append(s.shutdownFuncs, srv.Shutdown)
if conf.Metrics.Enabled {
metricsExp, metricsShutdownFunc, err := getMetricsExporter(ctx, conf.Metrics)
if err != nil {
return err
}
s.shutdownFuncs = append(s.shutdownFuncs, metricsShutdownFunc)
metricsResource, err := resource.New(
ctx,
resource.WithSchemaURL(semconv.SchemaURL),
resource.WithAttributes(
semconv.ServiceName("glu"),
),
resource.WithFromEnv(),
resource.WithTelemetrySDK(),
resource.WithHost(),
resource.WithProcessRuntimeVersion(),
resource.WithProcessRuntimeName(),
)
if err != nil {
return fmt.Errorf("creating metrics resource: %w", err)
}
meterProvider := metricsdk.NewMeterProvider(
metricsdk.WithResource(metricsResource),
metricsdk.WithReader(metricsExp),
)
otel.SetMeterProvider(meterProvider)
s.shutdownFuncs = append(s.shutdownFuncs, meterProvider.Shutdown)
// We only want to start the runtime metrics by open telemetry if the user have chosen
// to use OTLP because the Prometheus endpoint already exposes those metrics.
if conf.Metrics.Exporter == config.MetricsExporterOTLP {
err = otlpruntime.Start(otlpruntime.WithMeterProvider(meterProvider))
if err != nil {
return fmt.Errorf("starting runtime metric exporter: %w", err)
}
}
}
var group errgroup.Group
group.Go(func() error {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// call in reverse order to emulate pop semantics of a stack
for _, fn := range slices.Backward(s.shutdownFuncs) {
if err := fn(shutdownCtx); err != nil {
slog.Error("shutting down", "error", err)
}
}
return nil
})
var serveFunc = srv.ListenAndServe
if conf.Server.Protocol == config.ProtocolHTTPS {
serveFunc = func() error {
return srv.ListenAndServeTLS(conf.Server.CertFile, conf.Server.KeyFile)
}
}
group.Go(func() error {
slog.Info("starting server", "addr", fmt.Sprintf("%s:%d", conf.Server.Host, conf.Server.Port))
if err := serveFunc(); err != nil && err != http.ErrServerClosed {
return err
}
slog.Debug("shutting down")
return nil
})
group.Go(func() error {
return s.runTriggers(ctx)
})
return group.Wait()
}
// Pipelines is a type which can list a set of configured name/Pipeline pairs.
type Pipelines interface {
Pipelines() iter.Seq2[string, *core.Pipeline]
}
func (s *System) runTriggers(ctx context.Context) error {
group, ctx := errgroup.WithContext(ctx)
for _, pipeline := range s.pipelines {
for edge := range pipeline.Edges() {
tedge, ok := edge.(core.TriggerableEdge)
if !ok {
slog.Debug("skipping non-triggerable edge", "kind", edge.Kind())
continue
}
group.Go(func() error {
return tedge.RunTriggers(ctx)
})
}
}
return group.Wait()
}
func getMetricsExporter(ctx context.Context, cfg config.Metrics) (metricsdk.Reader, shutdownFunc, error) {
var (
metricExp metricsdk.Reader
metricShutdownFunc shutdownFunc = func(context.Context) error { return nil }
err error
)
switch cfg.Exporter {
case config.MetricsExporterPrometheus:
// exporter registers itself on the prom client DefaultRegistrar
metricExp, err = prometheus.New()
if err != nil {
return nil, nil, err
}
case config.MetricsExporterOTLP:
u, err := url.Parse(cfg.OTLP.Endpoint)
if err != nil {
return nil, nil, fmt.Errorf("parsing otlp endpoint: %w", err)
}
var exporter metricsdk.Exporter
switch u.Scheme {
case "https":
exporter, err = otlpmetrichttp.New(ctx,
otlpmetrichttp.WithEndpoint(u.Host+u.Path),
otlpmetrichttp.WithHeaders(cfg.OTLP.Headers),
)
if err != nil {
return nil, nil, fmt.Errorf("creating otlp metrics exporter: %w", err)
}
case "http":
exporter, err = otlpmetrichttp.New(ctx,
otlpmetrichttp.WithEndpoint(u.Host+u.Path),
otlpmetrichttp.WithHeaders(cfg.OTLP.Headers),
otlpmetrichttp.WithInsecure(),
)
if err != nil {
return nil, nil, fmt.Errorf("creating otlp metrics exporter: %w", err)
}
default:
return nil, nil, fmt.Errorf("unsupported metrics exporter scheme: %s", u.Scheme)
}
metricExp = metricsdk.NewPeriodicReader(exporter)
metricShutdownFunc = func(ctx context.Context) error {
return exporter.Shutdown(ctx)
}
default:
return nil, nil, fmt.Errorf("unsupported metrics exporter: %s", cfg.Exporter)
}
return metricExp, metricShutdownFunc, err
}