-
Notifications
You must be signed in to change notification settings - Fork 311
/
syncthing.go
678 lines (580 loc) · 17.9 KB
/
syncthing.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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
// Copyright 2020 The Okteto Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package syncthing
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"text/template"
"time"
"github.com/okteto/okteto/pkg/config"
"github.com/okteto/okteto/pkg/errors"
"github.com/okteto/okteto/pkg/log"
"github.com/okteto/okteto/pkg/model"
"golang.org/x/crypto/bcrypt"
yaml "gopkg.in/yaml.v2"
ps "github.com/mitchellh/go-ps"
uuid "github.com/satori/go.uuid"
)
var (
configTemplate = template.Must(template.New("syncthingConfig").Parse(configXML))
)
const (
certFile = "cert.pem"
keyFile = "key.pem"
configFile = "config.xml"
logFile = "syncthing.log"
syncthingPidFile = "syncthing.pid"
// DefaultRemoteDeviceID remote syncthing ID
DefaultRemoteDeviceID = "ATOPHFJ-VPVLDFY-QVZDCF2-OQQ7IOW-OG4DIXF-OA7RWU3-ZYA4S22-SI4XVAU"
localDeviceID = "ABKAVQF-RUO4CYO-FSC2VIP-VRX4QDA-TQQRN2J-MRDXJUC-FXNWP6N-S6ZSAAR"
// DefaultFileWatcherDelay how much to wait before starting a sync after a file change
DefaultFileWatcherDelay = 5
// ClusterPort is the port used by syncthing in the cluster
ClusterPort = 22000
// GUIPort is the port used by syncthing in the cluster for the http endpoint
GUIPort = 8384
)
// Syncthing represents the local syncthing process.
type Syncthing struct {
APIKey string `yaml:"apikey"`
GUIPassword string `yaml:"password"`
GUIPasswordHash string `yaml:"-"`
binPath string `yaml:"-"`
Client *http.Client `yaml:"-"`
cmd *exec.Cmd `yaml:"-"`
Dev *model.Dev `yaml:"-"`
DevPath string `yaml:"-"`
FileWatcherDelay int `yaml:"-"`
ForceSendOnly bool `yaml:"-"`
GUIAddress string `yaml:"local"`
Home string `yaml:"-"`
LogPath string `yaml:"-"`
ListenAddress string `yaml:"-"`
RemoteAddress string `yaml:"-"`
RemoteDeviceID string `yaml:"-"`
RemoteGUIAddress string `yaml:"remote"`
RemoteGUIPort int `yaml:"-"`
RemotePort int `yaml:"-"`
Source string `yaml:"-"`
Type string `yaml:"-"`
IgnoreDelete bool `yaml:"-"`
pid int `yaml:"-"`
}
//Ignores represents the .stignore file
type Ignores struct {
Ignore []string `json:"ignore"`
}
// Status represents the status of a syncthing folder.
type Status struct {
State string `json:"state"`
PullErrors int64 `json:"pullErrors"`
}
// Completion represents the completion of a syncthing folder.
type Completion struct {
Completion float64 `json:"completion"`
GlobalBytes int64 `json:"globalBytes"`
NeedBytes int64 `json:"needBytes"`
NeedDeletes int64 `json:"needDeletes"`
}
// FolderErrors represents folder errors in syncthing.
type FolderErrors struct {
Data DataFolderErrors `json:"data"`
}
// DataFolderErrors represents data folder errors in syncthing.
type DataFolderErrors struct {
Errors []FolderError `json:"errors"`
}
// FolderError represents a folder error in syncthing.
type FolderError struct {
Error string `json:"error"`
Path string `json:"path"`
}
// New constructs a new Syncthing.
func New(dev *model.Dev) (*Syncthing, error) {
fullPath := getInstallPath()
remotePort, err := model.GetAvailablePort()
if err != nil {
return nil, err
}
remoteGUIPort, err := model.GetAvailablePort()
if err != nil {
return nil, err
}
guiPort, err := model.GetAvailablePort()
if err != nil {
return nil, err
}
listenPort, err := model.GetAvailablePort()
if err != nil {
return nil, err
}
pwd := uuid.NewV4().String()
hash, err := bcrypt.GenerateFromPassword([]byte(pwd), 0)
if err != nil {
log.Infof("couldn't hash the password %s", err)
hash = []byte("")
}
s := &Syncthing{
APIKey: "cnd",
GUIPassword: pwd,
GUIPasswordHash: string(hash),
binPath: fullPath,
Client: NewAPIClient(),
Dev: dev,
DevPath: dev.DevPath,
FileWatcherDelay: DefaultFileWatcherDelay,
GUIAddress: fmt.Sprintf("localhost:%d", guiPort),
Home: config.GetDeploymentHome(dev.Namespace, dev.Name),
LogPath: config.GetSyncthingLogFile(dev.Namespace, dev.Name),
ListenAddress: fmt.Sprintf("localhost:%d", listenPort),
RemoteAddress: fmt.Sprintf("tcp://localhost:%d", remotePort),
RemoteDeviceID: DefaultRemoteDeviceID,
RemoteGUIAddress: fmt.Sprintf("localhost:%d", remoteGUIPort),
RemoteGUIPort: remoteGUIPort,
RemotePort: remotePort,
Source: dev.DevDir,
Type: "sendonly",
IgnoreDelete: true,
}
if err := s.Save(dev); err != nil {
log.Infof("error saving syncthing object: %s", err)
}
log.Infof("local syncthing intialized: gui -> %d, sync -> %d", guiPort, listenPort)
log.Infof("remote syncthing intialized: gui -> %d, sync -> %d", remoteGUIPort, remotePort)
log.Infof("syncthing gui password: '%s'", pwd)
return s, nil
}
func (s *Syncthing) cleanupDaemon(pid int) error {
process, err := ps.FindProcess(pid)
if process == nil && err == nil {
return nil
}
if err != nil {
log.Infof("error when looking up the process: %s", err)
return err
}
if process.Executable() != getBinaryName() {
log.Debugf("found %s pid-%d ppid-%d", process.Executable(), process.Pid(), process.PPid())
return nil
}
err = terminate(pid)
if err == nil {
log.Infof("terminated syncthing with pid %d", pid)
}
return err
}
func (s *Syncthing) initConfig() error {
if err := os.MkdirAll(s.Home, 0700); err != nil {
return fmt.Errorf("failed to create %s: %s", s.Home, err)
}
if err := s.UpdateConfig(); err != nil {
return err
}
if err := ioutil.WriteFile(filepath.Join(s.Home, certFile), cert, 0700); err != nil {
return err
}
if err := ioutil.WriteFile(filepath.Join(s.Home, keyFile), key, 0700); err != nil {
return err
}
return nil
}
// UpdateConfig updates the syncthing config file
func (s *Syncthing) UpdateConfig() error {
buf := new(bytes.Buffer)
if err := configTemplate.Execute(buf, s); err != nil {
return err
}
if err := ioutil.WriteFile(filepath.Join(s.Home, configFile), buf.Bytes(), 0700); err != nil {
return err
}
return nil
}
// Run starts up a local syncthing process to serve files from.
func (s *Syncthing) Run(ctx context.Context) error {
if err := s.initConfig(); err != nil {
return err
}
pidPath := filepath.Join(s.Home, syncthingPidFile)
cmdArgs := []string{
"-home", s.Home,
"-no-browser",
"-verbose",
"-logfile", s.LogPath,
"-log-max-old-files=0",
}
s.cmd = exec.Command(s.binPath, cmdArgs...) //nolint: gas, gosec
s.cmd.Env = append(os.Environ(), "STNOUPGRADE=1")
if err := s.cmd.Start(); err != nil {
return err
}
if s.cmd.Process == nil {
return nil
}
if err := ioutil.WriteFile(
pidPath,
[]byte(strconv.Itoa(s.cmd.Process.Pid)),
0600); err != nil {
return err
}
s.pid = s.cmd.Process.Pid
log.Infof("local syncthing pid-%d running", s.pid)
return nil
}
//WaitForPing waits for synthing to be ready
func (s *Syncthing) WaitForPing(ctx context.Context, local bool) error {
ticker := time.NewTicker(100 * time.Millisecond)
log.Infof("waiting for syncthing local=%t to be ready...", local)
for i := 0; i < 300; i++ {
_, err := s.APICall(ctx, "rest/system/ping", "GET", 200, nil, local, nil)
if err == nil {
return nil
}
log.Debugf("error calling 'rest/system/ping' local=%t syncthing API: %s", local, err)
select {
case <-ticker.C:
continue
case <-ctx.Done():
log.Debugf("cancelling call to 'rest/system/ping' local=%t syncthing API", local)
return ctx.Err()
}
}
return fmt.Errorf("Syncthing local=%t not responding after 30s", local)
}
//SendStignoreFile sends .stignore from local to remote
func (s *Syncthing) SendStignoreFile(ctx context.Context, dev *model.Dev) {
log.Infof("sending '.stignore' file to the remote syncthing...")
params := getFolderParameter(dev)
ignores := &Ignores{}
body, err := s.APICall(ctx, "rest/db/ignores", "GET", 200, params, true, nil)
if err != nil {
log.Infof("error getting 'rest/db/ignores' syncthing API: %s", err)
return
}
err = json.Unmarshal(body, ignores)
if err != nil {
log.Infof("error unmarshaling 'rest/db/ignores': %s", err)
return
}
body, err = json.Marshal(ignores)
if err != nil {
log.Infof("error marshaling 'rest/db/ignores': %s", err)
}
_, err = s.APICall(ctx, "rest/db/ignores", "POST", 200, params, false, body)
if err != nil {
log.Infof("error posting 'rest/db/ignores' syncthing API: %s", err)
return
}
}
//ResetDatabase resets the syncthing database
func (s *Syncthing) ResetDatabase(ctx context.Context, dev *model.Dev, local bool) error {
log.Infof("reseting syncthing database local=%t...", local)
params := getFolderParameter(dev)
_, err := s.APICall(ctx, "rest/system/reset", "POST", 200, params, local, nil)
if err != nil {
log.Infof("error posting 'rest/system/reset' local=%t syncthing API: %s", local, err)
return err
}
return nil
}
//Overwrite overwrites local changes to the remote syncthing
func (s *Syncthing) Overwrite(ctx context.Context, dev *model.Dev) error {
log.Infof("overriding local changes to the remote syncthing...")
params := getFolderParameter(dev)
_, err := s.APICall(ctx, "rest/db/override", "POST", 200, params, true, nil)
if err != nil {
log.Infof("error posting 'rest/db/override' syncthing API: %s", err)
return err
}
return nil
}
//WaitForScanning waits for synthing to finish initial scanning
func (s *Syncthing) WaitForScanning(ctx context.Context, dev *model.Dev, local bool) error {
ticker := time.NewTicker(100 * time.Millisecond)
params := getFolderParameter(dev)
status := &Status{}
log.Infof("waiting for initial scan to complete local=%t...", local)
for i := 0; i < 3000; i++ {
select {
case <-ticker.C:
case <-ctx.Done():
log.Debug("cancelling call to 'rest/db/status'")
return ctx.Err()
}
body, err := s.APICall(ctx, "rest/db/status", "GET", 200, params, local, nil)
if err != nil {
log.Debugf("error calling 'rest/db/status' local=%t syncthing API: %s", local, err)
continue
}
err = json.Unmarshal(body, status)
if err != nil {
log.Debugf("error unmarshaling 'rest/db/status': %s", err)
continue
}
log.Infof("syncthing folder local=%t is '%s'", local, status.State)
if status.State != "scanning" && status.State != "scan-waiting" {
return nil
}
}
return fmt.Errorf("Syncthing not completed initial scan after 5min. Please, retry in a few minutes")
}
// WaitForCompletion waits for the remote to be totally synched
func (s *Syncthing) WaitForCompletion(ctx context.Context, dev *model.Dev, reporter chan float64) error {
defer close(reporter)
ticker := time.NewTicker(500 * time.Millisecond)
log.Infof("waiting for synchronization to complete...")
for {
select {
case <-ticker.C:
if err := s.Overwrite(ctx, dev); err != nil {
log.Infof("error calling 'rest/db/override' syncthing API: %s", err)
continue
}
completion, err := s.GetCompletion(ctx, dev, true)
if err != nil {
log.Debugf("error calling getting completion: %s", err)
continue
}
if completion.GlobalBytes == 0 {
return nil
}
progress := (float64(completion.GlobalBytes-completion.NeedBytes) / float64(completion.GlobalBytes)) * 100
log.Infof("syncthing folder is %.2f%%, needBytes %d, needDeletes %d",
progress,
completion.NeedBytes,
completion.NeedDeletes,
)
reporter <- progress
if completion.NeedBytes == 0 {
return nil
}
status, err := s.GetStatus(ctx, dev, false)
if err != nil {
log.Debugf("error getting status: %s", err)
continue
}
if status.PullErrors > 0 {
return s.GetFolderErrors(ctx, dev, false)
}
case <-ctx.Done():
log.Debug("cancelling call to 'rest/db/completion'")
return ctx.Err()
}
}
}
// GetStatus returns the syncthing status
func (s *Syncthing) GetStatus(ctx context.Context, dev *model.Dev, local bool) (*Status, error) {
params := getFolderParameter(dev)
status := &Status{}
body, err := s.APICall(ctx, "rest/db/status", "GET", 200, params, local, nil)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, status)
if err != nil {
return nil, err
}
return status, nil
}
// GetCompletion returns the syncthing completion
func (s *Syncthing) GetCompletion(ctx context.Context, dev *model.Dev, local bool) (*Completion, error) {
params := getFolderParameter(dev)
if local {
params["device"] = DefaultRemoteDeviceID
} else {
params["device"] = localDeviceID
}
completion := &Completion{}
body, err := s.APICall(ctx, "rest/db/completion", "GET", 200, params, local, nil)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, completion)
if err != nil {
return nil, err
}
return completion, nil
}
// GetCompletionProgress returns the syncthing completion progress
func (s *Syncthing) GetCompletionProgress(ctx context.Context, dev *model.Dev, local bool) (float64, error) {
completion, err := s.GetCompletion(ctx, dev, local)
if err != nil {
return 0, err
}
if completion.GlobalBytes == 0 {
return 100, nil
}
progress := (float64(completion.GlobalBytes-completion.NeedBytes) / float64(completion.GlobalBytes)) * 100
return progress, nil
}
// GetFolderErrors returns the last folder errors
func (s *Syncthing) GetFolderErrors(ctx context.Context, dev *model.Dev, local bool) error {
params := getFolderParameter(dev)
params["since"] = "0"
params["limit"] = "1"
params["timeout"] = "15"
params["events"] = "FolderErrors"
folderErrorsList := []FolderErrors{}
body, err := s.APICall(ctx, "rest/events", "GET", 200, params, local, nil)
if err != nil {
return err
}
err = json.Unmarshal(body, &folderErrorsList)
if err != nil {
return err
}
if len(folderErrorsList) == 0 {
return errors.ErrUnknownSyncError
}
folderErrors := folderErrorsList[len(folderErrorsList)-1]
if len(folderErrors.Data.Errors) == 0 {
return errors.ErrUnknownSyncError
}
return fmt.Errorf("%s: %s", folderErrors.Data.Errors[0].Path, folderErrors.Data.Errors[0].Error)
}
// Restart restarts the syncthing process
func (s *Syncthing) Restart(ctx context.Context) error {
log.Infof("restarting syncthing...")
_, err := s.APICall(ctx, "rest/system/restart", "POST", 200, nil, true, nil)
return err
}
// Stop halts the background process and cleans up.
func (s *Syncthing) Stop(force bool) error {
pidPath := filepath.Join(s.Home, syncthingPidFile)
pid, err := getPID(pidPath)
if os.IsNotExist(err) {
return nil
}
if !force {
if pid != s.pid {
log.Infof("syncthing pid-%d wasn't created by this command, skipping", pid)
return nil
}
}
if err := s.cleanupDaemon(pid); err != nil {
return err
}
if err := os.Remove(pidPath); err != nil {
if os.IsNotExist(err) {
return nil
}
log.Infof("failed to delete pidfile %s: %s", pidPath, err)
}
return nil
}
// Save saves the syncthing object in the dev home folder
func (s *Syncthing) Save(dev *model.Dev) error {
marshalled, err := yaml.Marshal(s)
if err != nil {
return err
}
syncthingInfoFile := config.GetSyncthingInfoFile(dev.Namespace, dev.Name)
if err := ioutil.WriteFile(syncthingInfoFile, marshalled, 0600); err != nil {
return err
}
return nil
}
// Load loads the syncthing object from the dev home folder
func Load(dev *model.Dev) (*Syncthing, error) {
syncthingInfoFile := config.GetSyncthingInfoFile(dev.Namespace, dev.Name)
b, err := ioutil.ReadFile(syncthingInfoFile)
if err != nil {
return nil, err
}
s := &Syncthing{
Client: NewAPIClient(),
}
if err := yaml.Unmarshal(b, s); err != nil {
return nil, err
}
return s, nil
}
// RemoveFolder deletes all the files created by the syncthing instance
func RemoveFolder(dev *model.Dev) error {
s, err := New(dev)
if err != nil {
return fmt.Errorf("failed to create syncthing instance")
}
if s.Home == "" {
log.Info("the home directory is not set when deleting")
return nil
}
if _, err := filepath.Rel(config.GetOktetoHome(), s.Home); err != nil || config.GetOktetoHome() == s.Home {
log.Errorf("%s is not inside %s, ignoring", s.Home, config.GetOktetoHome())
return nil
}
if err := os.RemoveAll(s.Home); err != nil {
log.Info(err)
return nil
}
parentDir := filepath.Dir(s.Home)
if parentDir != "." {
empty, err := isDirEmpty(parentDir)
if err != nil {
log.Info(err)
return nil
}
if empty {
log.Debugf("deleting %s since it's empty", parentDir)
if err := os.RemoveAll(parentDir); err != nil {
log.Infof("couldn't delete folder: %s", err)
return nil
}
}
}
return nil
}
func isDirEmpty(path string) (bool, error) {
f, err := os.Open(path)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdirnames(1) // Or f.Readdir(1)
if err == io.EOF {
return true, nil
}
return false, err // Either not empty or error, suits both cases
}
func getPID(pidPath string) (int, error) {
if _, err := os.Stat(pidPath); err != nil {
return 0, err
}
content, err := ioutil.ReadFile(pidPath) // nolint: gosec
if err != nil {
return 0, err
}
return strconv.Atoi(string(content))
}
func getInstallPath() string {
return filepath.Join(config.GetOktetoHome(), getBinaryName())
}
func getBinaryName() string {
if runtime.GOOS == "windows" {
return "syncthing.exe"
}
return "syncthing"
}
func getFolderParameter(dev *model.Dev) map[string]string {
folder := fmt.Sprintf("okteto-%s", dev.Name)
return map[string]string{"folder": folder, "device": DefaultRemoteDeviceID}
}