-
Notifications
You must be signed in to change notification settings - Fork 43
/
service.go
95 lines (83 loc) · 2.04 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
package git
import (
"sync"
"github.com/abiosoft/caddy-git/gitos"
)
var (
// Services holds all git pulling services and provides the function to
// stop them.
Services = &services{}
)
// repoService is the service that runs in background and periodically
// pull from the repository.
type repoService struct {
repo *Repo
ticker gitos.Ticker // ticker to tick at intervals
halt chan struct{} // channel to notify service to halt and stop pulling.
}
// Start starts a new background service to pull periodically.
func Start(repo *Repo) {
if repo.Interval <= 0 {
// ignore, don't setup periodic pull.
Logger().Println("interval too small, periodic pull not enabled.")
return
}
service := &repoService{
repo,
gos.NewTicker(repo.Interval),
make(chan struct{}),
}
go func(s *repoService) {
for {
select {
case <-s.ticker.C():
err := repo.Pull()
if err != nil {
Logger().Println(err)
}
case <-s.halt:
s.ticker.Stop()
return
}
}
}(service)
// add to services to make it stoppable
Services.add(service)
}
// services stores all repoServices
type services struct {
services []*repoService
sync.Mutex
}
// add adds a new service to list of services.
func (s *services) add(r *repoService) {
s.Lock()
defer s.Unlock()
s.services = append(s.services, r)
}
// Stop stops at most `limit` running services pulling from git repo at
// repoURL. It waits until the service is terminated before returning.
// If limit is less than zero, it is ignored.
// TODO find better ways to identify repos
func (s *services) Stop(repoURL string, limit int) {
s.Lock()
defer s.Unlock()
// locate repos
for i, j := 0, 0; i < len(s.services) && ((limit >= 0 && j < limit) || limit < 0); i++ {
service := s.services[i]
if string(service.repo.URL) == repoURL {
// send halt signal
service.halt <- struct{}{}
s.services[i] = nil
j++
}
}
// remove them from repos list
services := s.services[:0]
for _, s := range s.services {
if s != nil {
services = append(services, s)
}
}
s.services = services
}