forked from appleboy/gorush
-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.go
511 lines (434 loc) · 13.1 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"syscall"
"time"
"github.com/appleboy/gorush/config"
"github.com/appleboy/gorush/core"
"github.com/appleboy/gorush/logx"
"github.com/appleboy/gorush/notify"
"github.com/appleboy/gorush/router"
"github.com/appleboy/gorush/rpc"
"github.com/appleboy/gorush/status"
"github.com/golang-queue/nats"
"github.com/golang-queue/nsq"
"github.com/golang-queue/queue"
"golang.org/x/sync/errgroup"
)
func withContextFunc(ctx context.Context, f func()) context.Context {
ctx, cancel := context.WithCancel(ctx)
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(c)
select {
case <-ctx.Done():
case <-c:
cancel()
f()
}
}()
return ctx
}
func main() {
opts := config.ConfYaml{}
var (
ping bool
showVersion bool
configFile string
topic string
message string
token string
title string
)
flag.BoolVar(&showVersion, "version", false, "Print version information.")
flag.BoolVar(&showVersion, "V", false, "Print version information.")
flag.StringVar(&configFile, "c", "", "Configuration file path.")
flag.StringVar(&configFile, "config", "", "Configuration file path.")
flag.StringVar(&opts.Core.PID.Path, "pid", "", "PID file path.")
flag.StringVar(&opts.Ios.KeyPath, "i", "", "iOS certificate key file path")
flag.StringVar(&opts.Ios.KeyPath, "key", "", "iOS certificate key file path")
flag.StringVar(&opts.Ios.KeyID, "key-id", "", "iOS Key ID for P8 token")
flag.StringVar(&opts.Ios.TeamID, "team-id", "", "iOS Team ID for P8 token")
flag.StringVar(&opts.Ios.Password, "P", "", "iOS certificate password for gorush")
flag.StringVar(&opts.Ios.Password, "password", "", "iOS certificate password for gorush")
flag.StringVar(&opts.Android.APIKey, "k", "", "Android api key configuration for gorush")
flag.StringVar(&opts.Android.APIKey, "apikey", "", "Android api key configuration for gorush")
flag.StringVar(&opts.Huawei.AppSecret, "hk", "", "Huawei api key configuration for gorush")
flag.StringVar(&opts.Huawei.AppSecret, "hmskey", "", "Huawei api key configuration for gorush")
flag.StringVar(&opts.Huawei.AppID, "hid", "", "HMS app id configuration for gorush")
flag.StringVar(&opts.Huawei.AppID, "hmsid", "", "HMS app id configuration for gorush")
flag.StringVar(&opts.Core.Address, "A", "", "address to bind")
flag.StringVar(&opts.Core.Address, "address", "", "address to bind")
flag.StringVar(&opts.Core.Port, "p", "", "port number for gorush")
flag.StringVar(&opts.Core.Port, "port", "", "port number for gorush")
flag.StringVar(&token, "t", "", "token string")
flag.StringVar(&token, "token", "", "token string")
flag.StringVar(&opts.Stat.Engine, "e", "", "store engine")
flag.StringVar(&opts.Stat.Engine, "engine", "", "store engine")
flag.StringVar(&opts.Stat.Redis.Addr, "redis-addr", "", "redis addr")
flag.StringVar(&message, "m", "", "notification message")
flag.StringVar(&message, "message", "", "notification message")
flag.StringVar(&title, "title", "", "notification title")
flag.BoolVar(&opts.Android.Enabled, "android", false, "send android notification")
flag.BoolVar(&opts.Huawei.Enabled, "huawei", false, "send huawei notification")
flag.BoolVar(&opts.Ios.Enabled, "ios", false, "send ios notification")
flag.BoolVar(&opts.Ios.Production, "production", false, "production mode in iOS")
flag.StringVar(&topic, "topic", "", "apns topic in iOS")
flag.StringVar(&opts.Core.HTTPProxy, "proxy", "", "http proxy url")
flag.BoolVar(&ping, "ping", false, "ping server")
flag.Usage = usage
flag.Parse()
router.SetVersion(Version)
// Show version and exit
if showVersion {
router.PrintGoRushVersion()
os.Exit(0)
}
// set default parameters.
cfg, err := config.LoadConf(configFile)
if err != nil {
log.Printf("Load yaml config file error: '%v'", err)
return
}
// Initialize push slots for concurrent iOS pushes
notify.MaxConcurrentIOSPushes = make(chan struct{}, cfg.Ios.MaxConcurrentPushes)
if opts.Ios.KeyPath != "" {
cfg.Ios.KeyPath = opts.Ios.KeyPath
}
if opts.Ios.KeyID != "" {
cfg.Ios.KeyID = opts.Ios.KeyID
}
if opts.Ios.TeamID != "" {
cfg.Ios.TeamID = opts.Ios.TeamID
}
if opts.Ios.Password != "" {
cfg.Ios.Password = opts.Ios.Password
}
if opts.Android.APIKey != "" {
cfg.Android.APIKey = opts.Android.APIKey
}
if opts.Huawei.AppSecret != "" {
cfg.Huawei.AppSecret = opts.Huawei.AppSecret
}
if opts.Huawei.AppID != "" {
cfg.Huawei.AppID = opts.Huawei.AppID
}
if opts.Stat.Engine != "" {
cfg.Stat.Engine = opts.Stat.Engine
}
if opts.Stat.Redis.Addr != "" {
cfg.Stat.Redis.Addr = opts.Stat.Redis.Addr
}
// overwrite server port and address
if opts.Core.Port != "" {
cfg.Core.Port = opts.Core.Port
}
if opts.Core.Address != "" {
cfg.Core.Address = opts.Core.Address
}
if err = logx.InitLog(
cfg.Log.AccessLevel,
cfg.Log.AccessLog,
cfg.Log.ErrorLevel,
cfg.Log.ErrorLog,
); err != nil {
log.Fatalf("can't load log module, error: %v", err)
}
if opts.Core.HTTPProxy != "" {
cfg.Core.HTTPProxy = opts.Core.HTTPProxy
}
if cfg.Core.HTTPProxy != "" {
err = notify.SetProxy(cfg.Core.HTTPProxy)
if err != nil {
logx.LogError.Fatalf("Set Proxy error: %v", err)
}
}
if ping {
if err := pinger(cfg); err != nil {
logx.LogError.Warnf("ping server error: %v", err)
}
return
}
// send android notification
if opts.Android.Enabled {
cfg.Android.Enabled = opts.Android.Enabled
req := ¬ify.PushNotification{
Platform: core.PlatFormAndroid,
Message: message,
Title: title,
}
// send message to single device
if token != "" {
req.Tokens = []string{token}
}
// send topic message
if topic != "" {
req.To = topic
}
err := notify.CheckMessage(req)
if err != nil {
logx.LogError.Fatal(err)
}
if err := status.InitAppStatus(cfg); err != nil {
return
}
if _, err := notify.PushToAndroid(req, cfg); err != nil {
return
}
return
}
// send huawei notification
if opts.Huawei.Enabled {
cfg.Huawei.Enabled = opts.Huawei.Enabled
req := ¬ify.PushNotification{
Platform: core.PlatFormHuawei,
Message: message,
Title: title,
}
// send message to single device
if token != "" {
req.Tokens = []string{token}
}
// send topic message
if topic != "" {
req.To = topic
}
err := notify.CheckMessage(req)
if err != nil {
logx.LogError.Fatal(err)
}
if err := status.InitAppStatus(cfg); err != nil {
return
}
if _, err := notify.PushToHuawei(req, cfg); err != nil {
return
}
return
}
// send ios notification
if opts.Ios.Enabled {
if opts.Ios.Production {
cfg.Ios.Production = opts.Ios.Production
}
cfg.Ios.Enabled = opts.Ios.Enabled
req := ¬ify.PushNotification{
Platform: core.PlatFormIos,
Message: message,
Title: title,
}
// send message to single device
if token != "" {
req.Tokens = []string{token}
}
// send topic message
if topic != "" {
req.Topic = topic
}
err := notify.CheckMessage(req)
if err != nil {
logx.LogError.Fatal(err)
}
if err := status.InitAppStatus(cfg); err != nil {
return
}
if err := notify.InitAPNSClient(cfg); err != nil {
return
}
if _, err := notify.PushToIOS(req, cfg); err != nil {
return
}
return
}
if err = notify.CheckPushConf(cfg); err != nil {
logx.LogError.Fatal(err)
}
if opts.Core.PID.Path != "" {
cfg.Core.PID.Path = opts.Core.PID.Path
cfg.Core.PID.Enabled = true
cfg.Core.PID.Override = true
}
if err = createPIDFile(cfg); err != nil {
logx.LogError.Fatal(err)
}
if err = status.InitAppStatus(cfg); err != nil {
logx.LogError.Fatal(err)
}
var w queue.Worker
switch core.Queue(cfg.Queue.Engine) {
case core.LocalQueue:
w = queue.NewConsumer(
queue.WithQueueSize(int(cfg.Core.QueueNum)),
queue.WithFn(notify.Run(cfg)),
queue.WithLogger(logx.QueueLogger()),
)
case core.NSQ:
w = nsq.NewWorker(
nsq.WithAddr(cfg.Queue.NSQ.Addr),
nsq.WithTopic(cfg.Queue.NSQ.Topic),
nsq.WithChannel(cfg.Queue.NSQ.Channel),
nsq.WithMaxInFlight(int(cfg.Core.WorkerNum)),
nsq.WithRunFunc(notify.Run(cfg)),
nsq.WithLogger(logx.QueueLogger()),
)
case core.NATS:
w = nats.NewWorker(
nats.WithAddr(cfg.Queue.NATS.Addr),
nats.WithSubj(cfg.Queue.NATS.Subj),
nats.WithQueue(cfg.Queue.NATS.Queue),
nats.WithRunFunc(notify.Run(cfg)),
nats.WithLogger(logx.QueueLogger()),
)
default:
logx.LogError.Fatalf("we don't support queue engine: %s", cfg.Queue.Engine)
}
q := queue.NewPool(
int(cfg.Core.WorkerNum),
queue.WithWorker(w),
queue.WithLogger(logx.QueueLogger()),
)
finished := make(chan struct{})
ctx := withContextFunc(context.Background(), func() {
logx.LogAccess.Info("close the queue system, current queue usage: ", q.Usage())
// stop queue system and wait job completed
q.Release()
close(finished)
// close the connection with storage
logx.LogAccess.Info("close the storage connection: ", cfg.Stat.Engine)
if err := status.StatStorage.Close(); err != nil {
logx.LogError.Fatal("can't close the storage connection: ", err.Error())
}
})
if cfg.Ios.Enabled {
if err = notify.InitAPNSClient(cfg); err != nil {
logx.LogError.Fatal(err)
}
}
if cfg.Android.Enabled {
if _, err = notify.InitFCMClient(cfg, cfg.Android.APIKey); err != nil {
logx.LogError.Fatal(err)
}
}
if cfg.Huawei.Enabled {
if _, err = notify.InitHMSClient(cfg, cfg.Huawei.AppSecret, cfg.Huawei.AppID); err != nil {
logx.LogError.Fatal(err)
}
}
var g errgroup.Group
// Run httpd server
g.Go(func() error {
return router.RunHTTPServer(ctx, cfg, q)
})
// Run gRPC internal server
g.Go(func() error {
return rpc.RunGRPCServer(ctx, cfg)
})
// check job completely
g.Go(func() error {
<-finished
return nil
})
if err = g.Wait(); err != nil {
logx.LogError.Fatal(err)
}
}
// Version control for notify.
var Version = "No Version Provided"
var usageStr = `
________ .__
/ _____/ ____ _______ __ __ ______| |__
/ \ ___ / _ \\_ __ \| | \/ ___/| | \
\ \_\ \( <_> )| | \/| | /\___ \ | Y \
\______ / \____/ |__| |____//____ >|___| /
\/ \/ \/
Usage: gorush [options]
Server Options:
-A, --address <address> Address to bind (default: any)
-p, --port <port> Use port for clients (default: 8088)
-c, --config <file> Configuration file path
-m, --message <message> Notification message
-t, --token <token> Notification token
-e, --engine <engine> Storage engine (memory, redis ...)
--title <title> Notification title
--proxy <proxy> Proxy URL
--pid <pid path> Process identifier path
--redis-addr <redis addr> Redis addr (default: localhost:6379)
--ping healthy check command for container
iOS Options:
-i, --key <file> certificate key file path
-P, --password <password> certificate key password
--ios enabled iOS (default: false)
--production iOS production mode (default: false)
Android Options:
-k, --apikey <api_key> Android API Key
--android enabled android (default: false)
Huawei Options:
-hk, --hmskey <hms_key> HMS App Secret
-hid, --hmsid <hms_id> HMS App ID
--huawei enabled huawei (default: false)
Common Options:
--topic <topic> iOS, Android or Huawei topic message
-h, --help Show this message
-V, --version Show version
`
// usage will print out the flag options for the server.
func usage() {
fmt.Printf("%s\n", usageStr)
os.Exit(0)
}
// handles pinging the endpoint and returns an error if the
// agent is in an unhealthy state.
func pinger(cfg *config.ConfYaml) error {
transport := &http.Transport{
Dial: (&net.Dialer{
Timeout: 5 * time.Second,
}).Dial,
TLSHandshakeTimeout: 5 * time.Second,
}
client := &http.Client{
Timeout: time.Second * 10,
Transport: transport,
}
resp, err := client.Get("http://localhost:" + cfg.Core.Port + cfg.API.HealthURI)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("server returned non-200 status code")
}
return nil
}
func createPIDFile(cfg *config.ConfYaml) error {
if !cfg.Core.PID.Enabled {
return nil
}
pidPath := cfg.Core.PID.Path
_, err := os.Stat(pidPath)
if os.IsNotExist(err) || cfg.Core.PID.Override {
currentPid := os.Getpid()
if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
return fmt.Errorf("can't create PID folder on %v", err)
}
file, err := os.Create(pidPath)
if err != nil {
return fmt.Errorf("can't create PID file: %v", err)
}
defer file.Close()
if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
return fmt.Errorf("can't write PID information on %s: %v", pidPath, err)
}
} else {
return fmt.Errorf("%s already exists", pidPath)
}
return nil
}