caddy/middleware/git/service.go

85 lines
1.8 KiB
Go
Raw Normal View History

2015-05-26 11:44:47 +08:00
package git
import (
"sync"
2015-05-28 15:21:10 +08:00
"github.com/mholt/caddy/middleware/git/gitos"
2015-05-26 11:44:47 +08:00
)
// repoService is the service that runs in background and periodically
// pull from the repository.
type repoService struct {
2015-05-28 15:21:10 +08:00
repo *Repo
ticker gitos.Ticker // ticker to tick at intervals
halt chan struct{} // channel to notify service to halt and stop pulling.
2015-05-26 11:44:47 +08:00
}
// Start starts a new background service to pull periodically.
2015-05-26 11:44:47 +08:00
func Start(repo *Repo) {
service := &repoService{
2015-05-26 11:44:47 +08:00
repo,
2015-05-28 15:21:10 +08:00
gos.NewTicker(repo.Interval),
2015-05-26 11:44:47 +08:00
make(chan struct{}),
}
go func(s *repoService) {
2015-05-26 11:44:47 +08:00
for {
select {
2015-05-28 15:21:10 +08:00
case <-s.ticker.C():
err := repo.Pull()
if err != nil {
logger().Println(err)
}
case <-s.halt:
s.ticker.Stop()
return
2015-05-26 11:44:47 +08:00
}
}
}(service)
// add to services to make it stoppable
Services.add(service)
2015-05-26 11:44:47 +08:00
}
// services stores all repoServices
type services struct {
services []*repoService
2015-05-26 11:44:47 +08:00
sync.Mutex
}
// add adds a new service to list of services.
func (s *services) add(r *repoService) {
s.Lock()
defer s.Unlock()
2015-05-26 11:44:47 +08:00
s.services = append(s.services, r)
2015-05-26 11:44:47 +08:00
}
// 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.
2015-05-26 11:44:47 +08:00
// TODO find better ways to identify repos
func (s *services) Stop(repoURL string, limit int) {
s.Lock()
defer s.Unlock()
2015-05-26 11:44:47 +08:00
// locate repos
for i, j := 0, 0; i < len(s.services) && ((limit >= 0 && j < limit) || limit < 0); i++ {
service := s.services[i]
if service.repo.URL == repoURL {
2015-05-26 11:44:47 +08:00
// send halt signal
service.halt <- struct{}{}
s.services[i] = nil
2015-05-26 11:44:47 +08:00
j++
}
}
// remove them from repos list
services := s.services[:0]
for _, s := range s.services {
2015-05-26 11:44:47 +08:00
if s != nil {
services = append(services, s)
}
}
s.services = services
2015-05-26 11:44:47 +08:00
}