-
Notifications
You must be signed in to change notification settings - Fork 405
/
init.go
175 lines (158 loc) · 4.61 KB
/
init.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
package server
import (
"bytes"
"context"
"io/ioutil"
"net"
"os"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/fnproject/fn/api/common"
"github.com/fnproject/fn/api/id"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
func init() {
// init logging stuff in init, in case any packages log stuff on startup
common.SetLogFormat(getEnv(EnvLogFormat, DefaultLogFormat))
common.SetLogLevel(getEnv(EnvLogLevel, DefaultLogLevel))
common.SetLogDest(getEnv(EnvLogDest, DefaultLogDest), getEnv(EnvLogPrefix, ""))
// gin is not nice by default, this can get set in logging initialization
gin.SetMode(gin.ReleaseMode)
// set machine id in init() before any packages are initialized that may use it
// (you may change this to seed the id another way but be wary of package initialization)
setMachineID()
}
func setMachineID() {
port := uint16(getEnvInt(EnvPort, DefaultPort))
addr := whoAmI().To4()
if addr == nil {
addr = net.ParseIP("127.0.0.1").To4()
logrus.Warn("could not find non-local ipv4 address to use, using '127.0.0.1' for ids, if this is a cluster beware of duplicate ids!")
}
id.SetMachineIdHost(addr, port)
}
// whoAmI searches for a non-local address on any network interface, returning
// the first one it finds. it could be expanded to search eth0 or en0 only but
// to date this has been unnecessary.
func whoAmI() net.IP {
ints, _ := net.Interfaces()
for _, i := range ints {
if i.Name == "docker0" || i.Name == "lo" {
// not perfect
continue
}
addrs, _ := i.Addrs()
for _, a := range addrs {
ip, _, err := net.ParseCIDR(a.String())
if a.Network() == "ip+net" && err == nil && ip.To4() != nil {
if !bytes.Equal(ip, net.ParseIP("127.0.0.1")) {
return ip
}
}
}
}
return nil
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
} else if value, ok := os.LookupEnv(key + "_FILE"); ok {
dat, err := ioutil.ReadFile(filepath.Clean(value))
if err == nil {
return string(dat)
}
}
return fallback
}
func getEnvInt(key string, fallback int) int {
if value, ok := os.LookupEnv(key); ok {
// linter liked this better than if/else
var err error
var i int
if i, err = strconv.Atoi(value); err != nil {
logrus.WithError(err).WithFields(logrus.Fields{"string": value, "environment_key": key}).Fatal("Failed to convert string to int")
}
return i
} else if value, ok := os.LookupEnv(key + "_FILE"); ok {
dat, err := ioutil.ReadFile(filepath.Clean(value))
if err == nil {
var err error
var i int
if i, err = strconv.Atoi(strings.TrimSpace(string(dat))); err != nil {
logrus.WithError(err).WithFields(logrus.Fields{"string": dat, "environment_key": key}).Fatal("Failed to convert string to int")
}
return i
}
}
return fallback
}
func getEnvDuration(key string, fallback time.Duration) time.Duration {
var err error
res := fallback
if tmp := os.Getenv(key); tmp != "" {
// if the returned value is not null it needs to be either an integral value in seconds or a parsable duration-format string
res, err = time.ParseDuration(tmp)
if err != nil {
// try to parse an int
s, perr := strconv.Atoi(tmp)
if perr != nil {
logrus.WithError(err).WithFields(logrus.Fields{"duration_string": tmp, "environment_key": key}).Fatal("Failed to parse duration from env")
} else {
res = time.Duration(s) * time.Second
}
}
}
return res
}
func contextWithSignal(ctx context.Context, signals ...os.Signal) (context.Context, context.CancelFunc) {
newCTX, halt := context.WithCancel(ctx)
c := make(chan os.Signal, 1)
signal.Notify(c, signals...)
go func() {
for {
select {
case <-c:
common.Logger(ctx).Info("Halting...")
halt()
return
case <-ctx.Done():
common.Logger(ctx).Info("Halting... Original server context canceled.")
halt()
return
}
}
}()
return newCTX, halt
}
// Installs a child process reaper if init process
func installChildReaper() {
// assume responsibilities of init process if running as init process for Linux
if runtime.GOOS != "linux" || os.Getpid() != 1 {
return
}
var sigs = make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGCHLD)
// we run this forever and leak a go routine. As init, we must
// reap our children until the very end, so this is OK.
go func() {
for {
<-sigs
for {
var status syscall.WaitStatus
var rusage syscall.Rusage
pid, err := syscall.Wait4(-1, &status, syscall.WNOHANG, &rusage)
// no children
if pid <= 0 {
break
}
logrus.Infof("Child terminated pid=%d err=%v status=%v usage=%v", pid, err, status, rusage)
}
}
}()
}