aboutsummaryrefslogtreecommitdiffsponsor
path: root/internal/service/service.go
blob: c5235f2b15a5d61e65db4e66a8b8d05b5e4a7a74 (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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package service

import (
	"errors"
	"fmt"
	"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",
}

// Service data associated with each mirror.
type mirrorRecord struct {
	*Mirror
	LastRun time.Time
	NextRun time.Time
}

func (s *mirrorRecord) String() string {
	return fmt.Sprintf("%s: %s -> %s at %s", s.Method, s.From, s.To, s.NextRun.Format(time.Kitchen))
}

type Service struct {
	cfg *Config

	mirrorsLock sync.Mutex
	mirrors     []*mirrorRecord

	stopCh chan struct{}
}

func NewService(arg *Config) (*Service, error) {
	// Apply  defaults
	var cfg Config

	cfg.Append(&DefaultConfig)
	cfg.Append(arg)

	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) 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")
		}
	}

	record := &mirrorRecord{
		Mirror:  arg,
		NextRun: time.Now().Add(RandomDuration(*s.cfg.MinInterval, *s.cfg.MaxInterval).Duration),
	}
	s.mirrors = append(s.mirrors, record)

	return nil
}

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

	now := time.Now()
	for _, m := range s.mirrors {
		if m.NextRun.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()

	index := -1

	for i, m := range s.mirrors {
		if m.Equal(arg) {
			index = i
			break
		}
	}

	if index == -1 {
		return errors.New("not found")
	}

	s.mirrors[index] = s.mirrors[len(s.mirrors)-1]
	s.mirrors = s.mirrors[:len(s.mirrors)-1]

	return nil
}

// Reload reloads the service with the given configuration.
func (s *Service) Reload(arg *Config) {
	s.mirrorsLock.Lock()
	defer s.mirrorsLock.Unlock()

	var cfg Config

	cfg.Append(&DefaultConfig)
	cfg.Append(arg)

	s.cfg = &cfg

	mirrorsByDest := make(map[string]*mirrorRecord)
	for _, m := range s.mirrors {
		mirrorsByDest[m.To.String()] = m
	}

	mirrors := make([]*mirrorRecord, 0)

	for _, m := range cfg.Mirrors {
		oldM, ok := mirrorsByDest[m.To.String()]
		if !ok {
			mirrors = append(
				mirrors,
				&mirrorRecord{
					Mirror:  m,
					LastRun: time.Time{},
					NextRun: time.Now().Add(RandomDuration(*s.cfg.MinInterval, *s.cfg.MaxInterval).Duration),
				},
			)

			continue
		}

		delete(mirrorsByDest, m.To.String())

		lastRun := oldM.LastRun
		if lastRun.IsZero() {
			lastRun = time.Now()
		}

		untilNextRun := Duration{oldM.NextRun.Sub(lastRun)}
		untilNextRun = cfg.MinInterval.Max(&untilNextRun)
		untilNextRun = cfg.MaxInterval.Min(&untilNextRun)

		// Records match up.
		record := mirrorRecord{
			Mirror:  m,
			LastRun: oldM.LastRun,
			NextRun: time.Now().Add(untilNextRun.Duration),
		}
		mirrors = append(
			mirrors,
			&record,
		)
	}

	s.mirrors = mirrors
}

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 *mirrorRecord) bool {
			err := s.Mirror(m.Mirror)
			if err != nil {
				s.Log(err.Error())
			}

			m.LastRun = time.Now()
			m.NextRun = time.Now().Add(RandomDuration(*s.cfg.MinInterval, *s.cfg.MaxInterval).Duration)

			return true
		})
	}

	return nil
}

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