aboutsummaryrefslogtreecommitdiffsponsor
path: root/internal/service/service.go
blob: 637a1cf19bee8475c4c41bfd5b691e526e1e4827 (plain)
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
package service

import (
	"errors"
	"fmt"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"git.server.ky/slackcoder/mirror/internal"
	"git.server.ky/slackcoder/mirror/internal/github"
)

// These commands are required by the service to operate.
var requiredCommands = []string{
	"git",
	"rsync",
}

type Service struct {
	cfg *Config

	mirrorsLock sync.Mutex
	mirrors     []*Mirror
	schedule    []time.Time

	stopCh chan struct{}
}

func NewService(cfg *Config) (*Service, error) {
	// Apply  defaults
	cfg.Merge(&DefaultConfig)

	for _, cmd := range requiredCommands {
		if err := internal.RequireCommand(cmd); err != nil {
			return nil, err
		}
	}

	srv := &Service{
		cfg:     cfg,
		mirrors: nil,
		stopCh:  make(chan struct{}),
	}

	for _, m := range cfg.Mirrors {
		err := srv.AddMirror(m)
		if err != nil {
			return nil, err
		}
	}

	return srv, nil
}

func (s *Service) scheduleNextRun(arg *Mirror) {
	// Be polite.
	period := s.cfg.MaxInterval.Duration - s.cfg.MinInterval.Duration
	at := time.Now().Add(s.cfg.MinInterval.Duration + time.Duration(rand.Intn(int(period))))

	for i, m := range s.mirrors {
		if m.Equal(arg) {
			s.schedule[i] = at
		}
	}
}

func (s *Service) AddMirror(arg *Mirror) error {
	defer s.mirrorsLock.Unlock()
	s.mirrorsLock.Lock()

	for _, m := range s.mirrors {
		if m.Equal(arg) {
			return errors.New("must be unique")
		}
	}

	s.schedule = append(s.schedule, time.Time{})
	s.mirrors = append(s.mirrors, arg)
	s.scheduleNextRun(arg)

	return nil
}

func (s *Service) scheduled(yield func(*Mirror) bool) {
	defer s.mirrorsLock.Unlock()
	s.mirrorsLock.Lock()

	now := time.Now()
	for i, m := range s.mirrors {
		if s.schedule[i].After(now) {
			continue
		}

		if !yield(m) {
			break
		}
	}
}

func (s *Service) Mirror(arg *Mirror) error {
	if arg.From.Path == "" || arg.To.Path == "" || arg.Method == "" {
		return fmt.Errorf("badly formatted mirror '%s'", arg.String())
	}

	var err error

	switch arg.Method {
	case "git":
		err = MirrorGit(arg.To, arg.From, arg.Description)
	case "github-assets":
		client := github.NewClient()
		err = client.MirrorAssets(arg.To, arg.From)
	case "rsync":
		err = Rsync(arg.To, arg.From)
	default:
		err = fmt.Errorf("unknown method '%s'", arg.Method)
	}

	if err != nil {
		return fmt.Errorf("could not clone from '%s': %w", arg.From, err)
	}

	return nil
}

func (s *Service) RemoveMirror(arg *Mirror) error {
	defer s.mirrorsLock.Unlock()
	s.mirrorsLock.Lock()

	for i, m := range s.mirrors {
		if m.Equal(arg) {
			s.mirrors[i] = s.mirrors[len(s.mirrors)-1]
			s.mirrors = s.mirrors[:len(s.mirrors)-1]

			s.schedule[i] = s.schedule[len(s.schedule)-1]
			s.schedule = s.schedule[:len(s.schedule)-1]

			return nil
		}
	}

	return errors.New("not found")
}

func (s *Service) Log(str string) {
	escaped := []rune(strconv.Quote(strings.TrimSpace(str)))
	escaped = escaped[1 : len(escaped)-1]

	fmt.Fprintf(os.Stderr, "%s: %s\n", time.Now().Format(time.RFC822Z), string(escaped))
}

func (s *Service) Run() error {
	wakeup := time.NewTicker(time.Second)

mainLoop:
	for {
		select {
		case <-wakeup.C:
		case <-s.stopCh:
			break mainLoop
		}

		s.scheduled(func(m *Mirror) bool {
			err := s.Mirror(m)
			if err != nil {
				s.Log(err.Error())
			}

			s.scheduleNextRun(m)

			return true
		})
	}

	return nil
}

func (s *Service) Stop() {
	select {
	case <-s.stopCh:
	default:
		close(s.stopCh)
	}
}