forked from cardigann/cardigann
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
126 lines (104 loc) · 2.31 KB
/
service.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
package main
import (
"encoding/json"
"fmt"
_ "log"
"os"
"github.com/Sirupsen/logrus"
"github.com/cardigann/cardigann/server"
"github.com/kardianos/service"
)
type programOpts struct {
UserService bool
}
type program struct {
exit chan struct{}
service service.Service
logger service.Logger
}
func newProgram(opts programOpts) (*program, error) {
svcConfig := &service.Config{
Name: "Cardigann",
DisplayName: "Cardigann Proxy",
Description: "Cardigann Torrent Indexer Proxy",
Option: service.KeyValue{
"RunAtLoad": true,
"UserService": opts.UserService,
},
Arguments: []string{
"service", "run",
},
}
prg := &program{}
s, err := service.New(prg, svcConfig)
if err != nil {
return nil, err
}
prg.service = s
return prg, nil
}
func (p *program) Start(s service.Service) error {
if service.Interactive() {
p.logger.Info("Running interactively")
}
p.exit = make(chan struct{})
go p.run()
return nil
}
func (p *program) run() error {
p.logger.Infof("Running service via %v.", service.Platform())
conf, err := newConfig()
if err != nil {
return err
}
s, err := server.New(conf, Version)
if err != nil {
return err
}
go s.Listen()
// block until exit
<-p.exit
return nil
}
func (p *program) Stop(s service.Service) error {
p.logger.Info("Shutting down cardigann")
p.exit <- struct{}{}
return nil
}
type serviceLogHook struct {
service.Logger
}
func (hook *serviceLogHook) Fire(entry *logrus.Entry) error {
line, err := entry.String()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
return err
}
switch entry.Level {
case logrus.PanicLevel:
hook.Logger.Error(line)
case logrus.FatalLevel:
hook.Logger.Error(line)
case logrus.ErrorLevel:
hook.Logger.Error(line)
case logrus.WarnLevel:
hook.Logger.Warning(line)
case logrus.InfoLevel:
hook.Logger.Info(line)
case logrus.DebugLevel:
hook.Logger.Info(line)
}
return nil
}
func (hook *serviceLogHook) Levels() []logrus.Level {
return logrus.AllLevels
}
type serviceLogFormatter struct {
}
func (f *serviceLogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
serialized, err := json.Marshal(entry.Data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return []byte(fmt.Sprintf("%s %s", entry.Message, serialized)), nil
}