forked from uber/arachne
/
util.go
201 lines (173 loc) · 6.73 KB
/
util.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
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package util
import (
"bufio"
"io/ioutil"
"os"
"os/signal"
"path"
"strconv"
"syscall"
"time"
"fmt"
"github.com/fatih/color"
"github.com/uber-go/zap"
"github.com/uber/arachne/metrics"
)
const bannerText = `
____________________________________________________________/\\\______________________________________
___________________________________________________________\/\\\______________________________________
___________________________________________________________\/\\\______________________________________
__/\\\\\\\\\_____/\\/\\\\\\\___/\\\\\\\\\________/\\\\\\\\_\/\\\__________/\\/\\\\\\_______/\\\\\\\\__
_\////////\\\___\/\\\/////\\\_\////////\\\_____/\\\//////__\/\\\\\\\\\\__\/\\\////\\\____/\\\/////\\\_
___/\\\\\\\\\\__\/\\\___\///____/\\\\\\\\\\___/\\\_________\/\\\/////\\\_\/\\\__\//\\\__/\\\\\\\\\\\__
__/\\\/////\\\__\/\\\__________/\\\/////\\\__\//\\\________\/\\\___\/\\\_\/\\\___\/\\\_\//\\///////___
_\//\\\\\\\\/\\_\/\\\_________\//\\\\\\\\/\\__\///\\\\\\\\_\/\\\___\/\\\_\/\\\___\/\\\__\//\\\\\\\\\\_
__\////////\//__\///___________\////////\//_____\////////__\///____\///__\///____\///____\//////////__
`
// KillChannels includes all channels to tell goroutines to terminate.
type KillChannels struct {
Receiver chan struct{}
Echo chan struct{}
Collector chan struct{}
DNSRefresh chan struct{}
}
// PrintBanner prints the binary's banner.
func PrintBanner() {
color.Set(color.FgHiYellow, color.Bold)
defer color.Unset()
f := bufio.NewWriter(os.Stdout)
defer f.Flush()
f.Write([]byte(bannerText))
}
// UnixSignals handles the UNIX signals received.
func UnixSignals(sigC chan struct{}, logger zap.Logger) {
// Set up channel on which to send signal notifications.
// We must use a buffered channel or risk missing the signal
// if we're not ready to receive when the signal is sent.
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGTERM,
syscall.SIGUSR1, syscall.SIGUSR2, syscall.SIGHUP, os.Interrupt)
go func() {
sigType := <-sigc
switch sigType {
//TODO Handle following cases
case os.Interrupt:
//handle SIGINT
case syscall.SIGHUP:
logger.Info("got Hangup/SIGHUP - portable number 1")
case syscall.SIGINT:
logger.Info("got Terminal interrupt signal/SIGINT - portable number 2")
case syscall.SIGQUIT:
logger.Fatal("got Terminal quit signal/SIGQUIT - portable number 3 - will core dump")
case syscall.SIGABRT:
logger.Fatal("got Process abort signal/SIGABRT - portable number 6 - will core dump")
case syscall.SIGKILL:
logger.Info("got Kill signal/SIGKILL - portable number 9")
case syscall.SIGALRM:
logger.Fatal("got Alarm clock signal/SIGALRM - portable number 14")
case syscall.SIGTERM:
logger.Info("got Termination signal/SIGTERM - portable number 15")
case syscall.SIGUSR1:
logger.Info("got User-defined signal 1/SIGUSR1")
case syscall.SIGUSR2:
logger.Info("got User-defined signal 2/SIGUSR2")
default:
logger.Fatal("unhandled Unix signal", zap.Object("sig_type", sigType))
}
sigC <- struct{}{}
return
}()
}
// CheckPID checks if another Arachne process is already running.
func CheckPID(fname string, logger zap.Logger) error {
if _, err := os.Stat(fname); os.IsNotExist(err) {
return savePID(fname, os.Getpid(), logger)
}
content, err := ioutil.ReadFile(fname)
if err != nil {
logger.Error("unable to read PID file", zap.String("file", fname), zap.Error(err))
return err
}
readPID, err := strconv.Atoi(string(content))
if err != nil {
logger.Error("invalid content inside PID file", zap.String("file", fname), zap.Error(err))
return savePID(fname, os.Getpid(), logger)
}
// Sending the signal 0 to a given PID just checks if any process with the given PID is running
// and you have the permission to send a signal to it.
if err = syscall.Kill(readPID, 0); err == nil {
logger.Error("Arachne already running and different from self PID",
zap.Int("other_PID", readPID),
zap.Int("self_PID", os.Getpid()))
return fmt.Errorf("Arachne already running and different from self PID")
}
return savePID(fname, os.Getpid(), logger)
}
func savePID(fname string, pid int, logger zap.Logger) error {
if err := os.MkdirAll(path.Dir(fname), 0777); err != nil {
logger.Error("failed to create PID directory", zap.String("path", path.Dir(fname)), zap.Error(err))
return err
}
if err := ioutil.WriteFile(fname, []byte(strconv.Itoa(pid)), 0644); err != nil {
logger.Error("failed to create PID file", zap.String("file", fname), zap.Error(err))
return err
}
logger.Debug("Created PID file", zap.Nest("PIDfile", zap.String("name", fname), zap.Int("PID", pid)))
return nil
}
// RemovePID removes the PID file.
func RemovePID(fname string, logger zap.Logger) {
if err := os.Remove(fname); err != nil {
logger.Error("failed to remove PID file", zap.String("name", fname), zap.Error(err))
} else {
logger.Debug("PID file removed", zap.String("name", fname))
}
}
// CleanUpRefresh removes state of past refresh.
func CleanUpRefresh(killC *KillChannels, receiverOnlyMode bool, senderOnlyMode bool) {
// Close all the channels
if !receiverOnlyMode {
close(killC.Echo)
}
if !senderOnlyMode {
close(killC.Receiver)
time.Sleep(500 * time.Millisecond)
}
if !receiverOnlyMode && !senderOnlyMode {
close(killC.Collector)
time.Sleep(50 * time.Millisecond)
}
close(killC.DNSRefresh)
}
// CleanUpAll conducts a clean exit.
func CleanUpAll(
killC *KillChannels,
receiverOnlyMode bool,
senderOnlyMode bool,
PIDPath string,
sr metrics.Reporter,
logger zap.Logger,
) {
CleanUpRefresh(killC, receiverOnlyMode, senderOnlyMode)
sr.Close()
RemovePID(PIDPath, logger)
}