-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
220 lines (184 loc) · 5.16 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
package main
import (
_ "github.com/anacrolix/envpprof"
"io/ioutil"
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"syscall"
"time"
"github.com/anacrolix/sync"
"github.com/anacrolix/tagflag"
"github.com/op/go-logging"
"github.com/projectx13/projectx/api"
"github.com/projectx13/projectx/bittorrent"
"github.com/projectx13/projectx/config"
"github.com/projectx13/projectx/database"
"github.com/projectx13/projectx/library"
"github.com/projectx13/projectx/lockfile"
"github.com/projectx13/projectx/scrape"
"github.com/projectx13/projectx/trakt"
"github.com/projectx13/projectx/util"
"github.com/projectx13/projectx/xbmc"
)
var log = logging.MustGetLogger("main")
func init() {
// TODO: does this really work in this manner, without setting it before program starts?
os.Setenv("GODEBUG", os.Getenv("GODEBUG")+",madvdontneed=1")
sync.Enable()
}
func ensureSingleInstance(conf *config.Configuration) (lock *lockfile.LockFile, err error) {
file := filepath.Join(conf.Info.Path, ".lockfile")
lock, err = lockfile.New(file)
if err != nil {
log.Critical("Unable to initialize lockfile:", err)
return
}
var pid int
var p *os.Process
pid, err = lock.Lock()
if err != nil {
log.Warningf("Unable to acquire lock %q: %v, killing...", lock.File, err)
p, err = os.FindProcess(pid)
if err != nil {
log.Warning("Unable to find other process:", err)
return
}
if err = p.Kill(); err != nil {
log.Critical("Unable to kill other process:", err)
return
}
if err = os.Remove(lock.File); err != nil {
log.Critical("Unable to remove lockfile")
return
}
_, err = lock.Lock()
}
return
}
func main() {
now := time.Now()
tagflag.Parse(&config.Args)
// Make sure we are properly multithreaded.
runtime.GOMAXPROCS(runtime.NumCPU())
logging.SetFormatter(logging.MustStringFormatter(
`%{color}%{level:.4s} %{module:-12s} ▶ %{shortfunc:-15s} %{color:reset}%{message}`,
))
logging.SetBackend(logging.NewLogBackend(ioutil.Discard, "", 0), logging.NewLogBackend(os.Stdout, "", 0))
log.Infof("Starting projectx daemon")
log.Infof("Version: %s LibTorrent: %s Go: %s, Threads: %d", util.GetVersion(), util.GetTorrentVersion(), runtime.Version(), runtime.GOMAXPROCS(0))
conf := config.Reload()
xbmc.KodiVersion = conf.Platform.Kodi
log.Infof("Addon: %s v%s", conf.Info.ID, conf.Info.Version)
lock, err := ensureSingleInstance(conf)
defer lock.Unlock()
if err != nil {
log.Warningf("Unable to acquire lock %q: %v, exiting...", lock.File, err)
os.Exit(1)
}
db, err := database.InitStormDB(conf)
if err != nil {
log.Error(err)
return
}
cacheDb, errCache := database.InitCacheDB(conf)
if errCache != nil {
log.Error(errCache)
return
}
s := bittorrent.NewService()
var shutdown = func(fromSignal bool) {
if s == nil || s.Closer.IsSet() {
return
}
s.Closer.Set()
log.Info("Shutting down...")
library.CloseLibrary()
s.Close(true)
db.Close()
cacheDb.Close()
log.Info("Goodbye")
// If we don't give an exit code - python treat as well done and not
// restarting the daemon. So when we come here from Signal -
// we should properly exit with non-0 exitcode.
if !fromSignal {
os.Exit(0)
} else {
os.Exit(1)
}
}
var watchParentProcess = func() {
for {
if os.Getppid() == 1 {
log.Warning("Parent shut down, shutting down too...")
go shutdown(false)
break
}
time.Sleep(1 * time.Second)
}
}
go watchParentProcess()
http.Handle("/", api.Routes(s))
http.Handle("/info", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.ClientInfo(w)
}))
http.Handle("/debug/all", bittorrent.DebugAll(s))
http.Handle("/debug/bundle", bittorrent.DebugBundle(s))
http.Handle("/files/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
handler := http.StripPrefix("/files/", http.FileServer(bittorrent.NewTorrentFS(s)))
handler.ServeHTTP(w, r)
}))
http.Handle("/reload", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.Reconfigure()
}))
http.Handle("/notification", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Notification(w, r, s)
}))
http.Handle("/shutdown", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
shutdown(false)
}))
if config.Get().GreetingEnabled {
xbmc.Notify("projectx", "LOCALIZE[30208]", config.AddonIcon())
}
sigc := make(chan os.Signal, 2)
signal.Notify(sigc,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
signal.Ignore(syscall.SIGPIPE, syscall.SIGILL)
defer close(sigc)
go func() {
closer := s.Closer.C()
for {
select {
case <-closer:
return
case <-sigc:
shutdown(true)
}
}
}()
go func() {
if checkRepository() {
log.Info("Updating Kodi add-on repositories... ")
xbmc.UpdateAddonRepos()
}
xbmc.DialogProgressBGCleanup()
xbmc.ResetRPC()
}()
go library.Init()
go trakt.TokenRefreshHandler()
go db.MaintenanceRefreshHandler()
go cacheDb.MaintenanceRefreshHandler()
go scrape.Start()
log.Infof("Prepared in %s", time.Since(now))
log.Infof("Starting HTTP server")
if err = http.ListenAndServe(":"+strconv.Itoa(config.Args.LocalPort), nil); err != nil {
panic(err)
}
}