-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
297 lines (250 loc) · 7.32 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package main
import (
"bytes"
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"wphpfpm/conf"
"wphpfpm/phpfpm"
"wphpfpm/server"
"github.com/chai2010/winsvc"
log "github.com/sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
"gopkg.in/natefinch/lumberjack.v2"
)
var (
serviceName = "wphpfpm"
serviceDesc = "PHP FastCGI Manager for windows"
app = kingpin.New(serviceName, serviceDesc)
commandInstall *kingpin.CmdClause
commandUninstall *kingpin.CmdClause
commandStart *kingpin.CmdClause
commandStop *kingpin.CmdClause
commandRun *kingpin.CmdClause
flagConfigFile *string
servers []*server.Server
)
func main() {
if !winsvc.IsAnInteractiveSession() {
// run as service
flag := kingpin.Flag("conf", "Config file path , required by install or run.")
flagConfigFile = flag.Required().String()
kingpin.Parse()
checkConfigFileExist(*flagConfigFile)
fmt.Println(serviceName, "Run service")
if err := winsvc.RunAsService(serviceName, startService, stopService, false); err != nil {
log.Fatalf(serviceName+" run: %v\n", err)
}
} else {
// command line mode
initCommandFlag()
switch kingpin.Parse() {
case commandInstall.FullCommand():
checkConfigFileExist(*flagConfigFile)
installService()
case commandUninstall.FullCommand():
if err := winsvc.RemoveService(serviceName); err != nil {
fmt.Println("Uninstall service: ", err)
os.Exit(1)
}
fmt.Println("Uninstall service: success")
case commandRun.FullCommand():
checkConfigFileExist(*flagConfigFile)
startService()
case commandStart.FullCommand():
if err := winsvc.StartService(serviceName); err != nil {
fmt.Println("Start service:", err)
os.Exit(1)
}
fmt.Println("Start service: success")
case commandStop.FullCommand():
if err := winsvc.StopService(serviceName); err != nil {
fmt.Println("Stop service:", err)
os.Exit(1)
}
fmt.Println("Stop service: success")
return
}
}
}
func initCommandFlag() {
commandInstall = kingpin.Command("install", "Install as service")
commandUninstall = kingpin.Command("uninstall", "Uninstall service")
commandStart = kingpin.Command("start", "Start service.")
commandStop = kingpin.Command("stop", "Stop service.")
commandRun = kingpin.Command("run", "Run in console mode")
flag := kingpin.Flag("conf", "Config file path , required by install or run.")
if len(os.Args) > 1 && (os.Args[1] == "install" || os.Args[1] == "run") {
flagConfigFile = flag.Required().String()
} else {
flagConfigFile = flag.String()
}
}
// 安裝服務
func installService() {
var serviceExec string
var err error
if serviceExec, err = winsvc.GetAppPath(); err != nil {
fmt.Println(err)
os.Exit(1)
}
if err := os.Chdir(filepath.Dir(serviceExec)); err != nil {
fmt.Println(err)
os.Exit(1)
}
abs, err := filepath.Abs(*flagConfigFile)
serviceExecFull := "\"" + serviceExec + "\"" + " --conf=" + abs
args := []string{"--conf", abs}
fmt.Printf("Service install name : %s , binpath : %s\n", serviceName, serviceExecFull)
if err := winsvc.InstallService(serviceExec, serviceName, serviceDesc, args...); err != nil {
fmt.Printf("Install service error : %s\n", err.Error())
os.Exit(1)
}
fmt.Println("Install service successfully.")
}
// 啟動服務
func startService() {
config, err := conf.LoadFile(*flagConfigFile)
if err != nil {
fmt.Printf("Config load error : %s\n", err.Error())
os.Exit(1)
}
fmt.Printf("Start in console mode , press CTRL+C to exit ...\r\n")
initLogger(config)
err = phpfpm.Start(config)
if err != nil {
log.Fatalf("Can not start service : %s\n", err.Error())
}
var events server.Event
events.OnConnect = func(c *server.Conn) (action server.Action) {
p := phpfpm.GetIdleProcess(c.Server().Tag.(int))
if p == nil {
if log.IsLevelEnabled(log.ErrorLevel) {
log.Error("Can not get php-cgi process")
}
action = server.Close
return
}
serr, terr := p.Proxy(c) // blocked
if log.IsLevelEnabled(log.DebugLevel) {
log.Debugf("php-cgi(%s) proxy error , serr : %s , terr : %s", p.ExecWithPippedName(), serr, terr)
}
phpfpm.PutIdleProcess(p)
return
}
conf := phpfpm.Conf()
var wg sync.WaitGroup
wg.Add(len(conf.Instances))
servers = make([]*server.Server, len(conf.Instances))
for i := 0; i < len(conf.Instances); i++ {
instance := conf.Instances[i]
servers[i] = &server.Server{MaxConnections: instance.MaxProcesses, BindAddress: instance.Bind, Tag: i}
log.Infof("Start server #%d on %s", i, servers[i].BindAddress)
go func(s *server.Server) {
err := s.Serve(events)
if err != nil {
log.Errorf("Service serve error : %s", err.Error())
}
wg.Done()
}(servers[i])
}
log.Info("Service running ...")
// 這段處理 CTRL + C
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
log.Infof("Service got signal: %s", sig.String())
stopService()
return
}
}()
wg.Wait()
phpfpm.Stop()
log.Info("Service Stopped.")
}
// 停止服務
func stopService() {
for i := 0; i < len(servers); i++ {
servers[i].Shutdown()
}
}
func checkConfigFileExist(filepath string) {
exist := conf.FileExist(filepath)
if !exist {
fmt.Printf("Could not load config file : %s", filepath)
os.Exit(1)
}
}
func initLogger(config *conf.Conf) {
formatter := &MyTextFormatter{timeFormat: "2006-01-02 15:04:05 -0700"}
log.SetFormatter(formatter)
// Set logger
if len(config.Logger.Filename) > 0 {
logDir := filepath.Dir(config.Logger.Filename)
exeDir, err := filepath.Abs(filepath.Dir(os.Args[0])) // 執行檔的路徑
if err != nil {
log.Fatal(err)
}
if logDir == "." || logDir == "" {
// 如果 Filename 沒指定路徑,修正為 exe 的路徑
config.Logger.Filename = exeDir + "\\" + config.Logger.Filename
}
logger := &lumberjack.Logger{
Filename: config.Logger.Filename,
MaxSize: config.Logger.MaxSize,
MaxBackups: config.Logger.MaxBackups,
MaxAge: config.Logger.MaxAge,
Compress: config.Logger.Compress,
}
log.SetOutput(logger)
fmt.Printf("Logger ouput set to file %s .\n", config.Logger.Filename)
} else {
fmt.Printf("Logger ouput set to console.\n")
}
if config.LogLevel == "" {
config.LogLevel = "ERROR"
}
logLevel, err := log.ParseLevel(config.LogLevel)
if err != nil {
log.Fatalf("LogLevel %s can not parse.", config.LogLevel)
}
log.SetLevel(logLevel)
log.Infof("Set LogLevel to %s.", strings.ToUpper(logLevel.String()))
// Repair config
for i := 0; i < len(config.Instances); i++ {
if config.Instances[i].MaxRequestsPerProcess < 1 {
// Repair MaxRequestsPerProcess
log.Warnf("Instance #%d MaxRequestsPerProcess is less 1 , set to 500", i)
config.Instances[i].MaxRequestsPerProcess = 500
}
if config.Instances[i].MaxProcesses < 1 {
//Repair MaxProcesses
log.Warnf("Instance #%d MaxProcesses is less 1 , set to 4", i)
config.Instances[i].MaxProcesses = 4
}
}
}
// MyTextFormatter logrus custom formatter
type MyTextFormatter struct {
timeFormat string
}
// Format logrus custom format
func (f *MyTextFormatter) Format(entry *log.Entry) ([]byte, error) {
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
b.WriteString(entry.Time.Format(f.timeFormat))
b.WriteString(" [")
b.WriteString(entry.Level.String())
b.WriteString("]: ")
b.WriteString(entry.Message)
b.WriteByte('\n')
return b.Bytes(), nil
}