-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
178 lines (155 loc) · 4.47 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
// Copyright 2020 The Cockroach Authors.
//
// 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 (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/bobvawter/iaido/pkg/config"
"github.com/bobvawter/iaido/pkg/diagnostics"
"github.com/bobvawter/iaido/pkg/frontend"
"github.com/pkg/errors"
"github.com/spf13/pflag"
"gopkg.in/yaml.v3"
)
func main() {
fs := pflag.NewFlagSet(os.Args[0], pflag.ContinueOnError)
boot := fs.StringSliceP("bootstrap", "b", nil,
"A list of bindings to bootstrap a configuration file with. "+
"The syntax for a binding is localPort:remoteHost:remotePort "+
"(e.g. 8080:example.com:80). This flag may be repeated multiple times.")
bootAddr := fs.String("bootstrapAddr", "", "the local network address to bind to")
help := fs.BoolP("help", "h", false, "display this message")
force := fs.BoolP("force", "f", false, "(bootstrap) overwrite any existing configuration file")
cfgPath := fs.StringP("config", "c", "iaido.yaml", "the configuration file to load")
cfgReloadPeriod := fs.Duration("reloadPeriod", time.Second, "how often to check the configuration file for changes")
checkOnly := fs.Bool("check", false, "if true, check and print the configuration file and exit")
version := fs.Bool("version", false, fmt.Sprintf("print the version %q and exit", frontend.BuildID()))
if err := fs.Parse(os.Args[1:]); err != nil {
println(err.Error())
*help = true
}
if *help {
println(fs.FlagUsagesWrapped(100))
os.Exit(1)
}
if *version {
println(frontend.BuildID())
os.Exit(0)
}
cfg := &config.Config{}
if *boot != nil {
if !*force {
if _, err := os.Stat(*cfgPath); err == nil {
log.Fatalf("configuration file %s already exists", *cfgPath)
} else if !errors.Is(err, os.ErrNotExist) {
log.Fatal(err)
}
}
if err := config.Bootstrap(cfg, *cfgPath, *bootAddr, *boot); err != nil {
log.Fatal(err)
}
*checkOnly = true
}
var mTime time.Time
loadConfig := func() (bool, error) {
info, err := os.Stat(*cfgPath)
if err != nil {
return false, errors.Wrapf(err, "unable to stat config file: %s", *cfgPath)
}
if info.ModTime() == mTime {
return false, nil
}
mTime = info.ModTime()
err = loadConfig(*cfgPath, cfg)
if err != nil {
return false, err
}
return true, nil
}
if _, err := loadConfig(); err != nil {
log.Fatal(err)
}
if *checkOnly {
bytes, err := yaml.Marshal(cfg)
if err != nil {
log.Fatal(err)
}
print(string(bytes))
os.Exit(0)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Set up a signal handler to gratefully, then forcefully terminate.
{
interrupted := make(chan os.Signal, 1)
signal.Notify(interrupted, syscall.SIGTERM, syscall.SIGINT)
go func() {
<-interrupted
log.Printf("signal received, draining for %s", cfg.GracePeriod)
cancel()
select {
case <-interrupted:
log.Print("second interrupt received")
case <-time.After(cfg.GracePeriod):
log.Print("grace period expired")
}
os.Exit(1)
}()
}
fe := &frontend.Frontend{}
if cfg.DiagAddr != "" {
go func() {
elts := map[string]interface{}{
"/configz": cfg,
"/statusz": fe,
"/healthz": "OK",
}
log.Print(diagnostics.ListenAndServe(cfg.DiagAddr, elts))
}()
}
hupped := make(chan os.Signal, 1)
signal.Notify(hupped, syscall.SIGHUP)
ticker := time.NewTicker(*cfgReloadPeriod)
defer ticker.Stop()
refreshLoop:
for {
if err := fe.Ensure(ctx, cfg); err != nil {
log.Printf("unable to refresh frontend: %v", err)
}
select {
case <-ctx.Done():
break refreshLoop
case <-ticker.C:
case <-hupped:
}
if _, err := loadConfig(); err != nil {
log.Printf("unable to reload configuration: %v", err)
}
}
fe.Wait()
log.Print("drained, goodbye!")
os.Exit(0)
}
func loadConfig(path string, cfg *config.Config) error {
cfgFile, err := os.Open(path)
if err != nil {
return errors.Wrapf(err, "could not open configuration file %s", path)
}
defer cfgFile.Close()
return config.DecodeConfig(cfgFile, cfg)
}