forked from infinilabs/crawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
237 lines (192 loc) · 5.71 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
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
/*
Copyright 2016 Medcl (m AT medcl.net)
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 (
"expvar"
_ "expvar"
"flag"
"fmt"
log "github.com/cihub/seelog"
"github.com/infinitbyte/gopa/core/daemon"
"github.com/infinitbyte/gopa/core/env"
"github.com/infinitbyte/gopa/core/global"
"github.com/infinitbyte/gopa/core/logger"
"github.com/infinitbyte/gopa/core/module"
"github.com/infinitbyte/gopa/core/stats"
"github.com/infinitbyte/gopa/core/util"
"github.com/infinitbyte/gopa/modules"
"net/http"
"os"
"os/signal"
"runtime"
"runtime/pprof"
"syscall"
"time"
)
var (
environment *env.Env
startTime time.Time
finalQuitSignal chan bool
)
func onStart() {
fmt.Println(env.GetWelcomeMessage())
startTime = time.Now()
}
func onShutdown() {
if environment.IsDebug {
fmt.Println(string(*stats.StatsAll()))
}
//force flush all logs
log.Flush()
fmt.Println(" | | ")
fmt.Println(" _` | _ \\ _ \\ _` | _ \\ | | -_) ")
fmt.Println(" \\__, | \\___/ \\___/ \\__,_| _.__/ \\_, | \\___| ")
fmt.Println(" ____/ ___/ ")
fmt.Println("[gopa] "+env.VERSION+", uptime:", time.Since(startTime))
fmt.Println(" ")
}
// report expvar and all metrics
func metricsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
first := true
report := func(key string, value interface{}) {
if !first {
fmt.Fprintf(w, ",\n")
}
first = false
if str, ok := value.(string); ok {
fmt.Fprintf(w, "%q: %q", key, str)
} else {
fmt.Fprintf(w, "%q: %v", key, value)
}
}
fmt.Fprintf(w, "{\n")
expvar.Do(func(kv expvar.KeyValue) {
report(kv.Key, kv.Value)
})
fmt.Fprintf(w, "\n}\n")
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
onStart()
var logLevel = flag.String("log", "info", "the log level,options:trace,debug,info,warn,error, default: info")
var configFile = flag.String("config", "gopa.yml", "the location of config file, default: gopa.yml")
var isDaemon = flag.Bool("daemon", false, "run in background as daemon")
var pidfile = flag.String("pidfile", "", "pidfile path (only for daemon)")
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file")
var memprofile = flag.String("memprofile", "", "write memory profile to this file")
var httpprof = flag.String("pprof", "", "enable and setup pprof/expvar service, eg: localhost:6060 , the endpoint will be: http://localhost:6060/debug/pprof/ and http://localhost:6060/debug/vars")
var isDebug = flag.Bool("debug", false, "enable debug")
var logDir = flag.String("log_path", "log", "the log path, default: log")
flag.Parse()
logger.SetLogging(env.EmptyEnv(), *logLevel, *logDir)
environment = env.Environment(*configFile)
environment.IsDebug = *isDebug
//put env into global registrar
global.RegisterEnv(environment)
logger.SetLogging(environment, *logLevel, *logDir)
//check instance lock
util.CheckInstanceLock(environment.SystemConfig.GetWorkingDir())
//set path to persist id
util.RestorePersistID(environment.SystemConfig.GetWorkingDir())
//cleanup
defer func() {
util.ClearInstanceLock()
if r := recover(); r != nil {
if e, ok := r.(runtime.Error); ok {
log.Error("main: ", e)
}
log.Error("main: ", r)
}
util.SnapshotPersistID()
log.Flush()
logger.Flush()
//print goodbye message
onShutdown()
}()
//profile options
if *httpprof != "" {
go func() {
log.Infof("pprof listen at: http://%s/debug/pprof/", *httpprof)
mux := http.NewServeMux()
// register pprof handler
mux.HandleFunc("/debug/pprof/", func(w http.ResponseWriter, r *http.Request) {
http.DefaultServeMux.ServeHTTP(w, r)
})
// register metrics handler
mux.HandleFunc("/debug/vars", metricsHandler)
endpoint := http.ListenAndServe(*httpprof, mux)
log.Debug("stop pprof server: %v", endpoint)
}()
}
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
panic(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
if *memprofile != "" {
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
panic(err)
}
pprof.WriteHeapProfile(f)
f.Close()
}
}
//daemon
if *isDaemon {
if runtime.GOOS == "darwin" || runtime.GOOS == "linux" {
runtime.LockOSThread()
context := new(daemon.Context)
if *pidfile != "" {
context.PidFileName = *pidfile
context.PidFilePerm = 0644
}
child, _ := context.Reborn()
if child != nil {
return
}
defer context.Release()
runtime.UnlockOSThread()
} else {
fmt.Println("daemon only available in linux and darwin")
}
}
//modules
module.New()
modules.Register()
module.Start()
finalQuitSignal = make(chan bool)
//handle exit event
sigc := make(chan os.Signal, 1)
signal.Notify(sigc,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT,
os.Interrupt)
go func() {
s := <-sigc
if s == os.Interrupt || s.(os.Signal) == syscall.SIGINT || s.(os.Signal) == syscall.SIGTERM ||
s.(os.Signal) == syscall.SIGKILL || s.(os.Signal) == syscall.SIGQUIT {
fmt.Printf("\n[gopa] got signal:%s ,start shutting down\n", s.String())
//wait workers to exit
module.Stop()
finalQuitSignal <- true
}
}()
<-finalQuitSignal
}