/
main.go
206 lines (184 loc) · 4.77 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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/flags"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
const (
errExitCode = 1
defaultCheckInterval = 60 * time.Second
containerVersionKey = "com.cenkalti.container-manager.container-version"
)
// Version of client. Set during build.
// "0.0.0" is the development version.
var Version = "v0.0.0"
// Command line flags
var (
configPath = flag.String("config", "/etc/container-manager.yaml", "config path")
printVersion = flag.Bool("version", false, "print program version")
)
// Global state
var (
// Config file unmarshaled from YAML
cfg Config
// Contains container defintions from config after count adding "-<count>" postfix
definitions map[string]*Container
// Containers currently managed by the app
managers = make(map[string]*Manager)
// Docker daemon client
cli client.APIClient
// Protects config and other global state
mu sync.Mutex
// Error channel for passing HTTP server errors to main goroutine
httpErrC = make(chan error, 1)
)
func main() {
flag.Parse()
if *printVersion {
fmt.Println(Version)
return
}
dockerCLI, err := command.NewDockerCli()
if err != nil {
fmt.Fprintln(os.Stderr, "cannot create docker client:", err.Error())
os.Exit(errExitCode)
}
err = dockerCLI.Initialize(flags.NewClientOptions())
if err != nil {
fmt.Fprintln(os.Stderr, "cannot initialize docker client:", err.Error())
os.Exit(errExitCode)
}
cli = dockerCLI.Client()
err = readConfig()
if err != nil {
fmt.Fprintln(os.Stderr, "cannot read config:", err.Error())
os.Exit(errExitCode)
}
err = removeStaleContainers()
if err != nil {
fmt.Fprintln(os.Stderr, "cannot remove stale continers:", err.Error())
os.Exit(errExitCode)
}
reloadContainers()
http.HandleFunc("/health", handleHealth)
go runHTTPServer()
chanReload := make(chan os.Signal, 1)
signal.Notify(chanReload, syscall.SIGHUP)
for {
select {
case <-chanReload:
err := readConfig()
if err != nil {
fmt.Fprintln(os.Stderr, "cannot read config:", err.Error())
os.Exit(errExitCode)
}
reloadContainers()
case err = <-httpErrC:
fmt.Fprintln(os.Stderr, "cannot serve http:", err.Error())
os.Exit(errExitCode)
}
}
}
func runHTTPServer() {
if err := http.ListenAndServe(cfg.ListenAddr, nil); err != nil {
httpErrC <- err
}
}
func handleHealth(w http.ResponseWriter, r *http.Request) {
errors := make([]string, 0)
addError := func(s string) {
errors = append(errors, s)
}
defer func() {
w.Header().Set("content-type", "application/json")
if len(errors) > 0 {
w.WriteHeader(http.StatusInternalServerError)
}
_ = json.NewEncoder(w).Encode(map[string]interface{}{"errors": errors})
}()
containers, err := cli.ContainerList(r.Context(), types.ContainerListOptions{})
if err != nil {
addError(err.Error())
return
}
running := make(map[string]struct{}, len(containers))
for _, con := range containers {
for _, name := range con.Names {
running[name] = struct{}{}
}
}
mu.Lock()
for name, manager := range managers {
if manager.IsStuck() {
addError(name + ": manager is stuck")
}
if _, ok := running["/"+name]; !ok {
addError(name + ": container is not running")
} else {
if err = manager.errHealthCheck; err != nil {
addError(name + ": health check failed: " + err.Error())
}
}
}
mu.Unlock()
}
func reloadContainers() {
mu.Lock()
defer mu.Unlock()
for _, mgr := range managers {
mgr.Reload()
}
for name, con := range definitions {
if _, ok := managers[name]; !ok {
managers[name] = Manage(name, con)
}
}
}
// Some containers left from previous runs may still be running.
// If config is changed while container-manager is not running and some container definitions are removed from config, they remain in running state.
// This function find those containers and remove them.
func removeStaleContainers() error {
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true})
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
for _, con := range containers {
if _, ok := con.Labels[containerVersionKey]; !ok {
// Container didn't get started by container-manager
continue
}
if len(con.Names) == 0 {
// Container state is "removal in progress" and does not have any name.
continue
}
if inDefinitions(con.Names) {
// Container has a definition in config
continue
}
name := strings.TrimPrefix(con.Names[0], "/")
managers[name] = Manage(name, nil)
}
return nil
}
func inDefinitions(names []string) bool {
for _, name := range names {
if _, ok := definitions[strings.TrimPrefix(name, "/")]; ok {
return true
}
}
return false
}