-
Notifications
You must be signed in to change notification settings - Fork 29
/
statemachines.go
3074 lines (2819 loc) · 91.1 KB
/
statemachines.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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os/exec"
"strconv"
"strings"
"sync"
"time"
"github.com/coreos/etcd/client"
"github.com/nu7hatch/gouuid"
"golang.org/x/net/context"
)
func newFilesystemMachine(filesystemId string, s *InMemoryState) *fsMachine {
// initialize the fsMachine with a filesystem struct that has bare minimum
// information (just the filesystem id) required to get started
return &fsMachine{
filesystem: &filesystem{
id: filesystemId,
},
// stored here as well to avoid excessive locking on filesystem struct,
// which gets clobbered, just to read its id
filesystemId: filesystemId,
requests: make(chan *Event),
innerRequests: make(chan *Event),
innerResponses: make(chan *Event),
responses: map[string]chan *Event{},
responsesLock: &sync.Mutex{},
snapshotsModified: make(chan bool),
state: s,
snapshotsLock: &sync.Mutex{},
newSnapsOnServers: NewObserver(),
currentState: "discovering",
status: "",
lastTransitionTimestamp: time.Now().UnixNano(),
transitionObserver: NewObserver(),
lastTransferRequest: TransferRequest{},
// In the case where we're receiving a push (pushPeerState), it's the
// POST handler on our http server which handles the receiving of the
// snapshot. We need to coordinate with it so that we know when to
// reload the list of snapshots, update etcd and coordinate our own
// state changes, which we do via the POST handler sending on this
// channel.
externalSnapshotsChanged: make(chan bool),
dirtyDelta: 0,
sizeBytes: 0,
}
}
func activateClone(state *InMemoryState, topLevelFilesystemId, originFilesystemId, originSnapshotId, newCloneFilesystemId, newBranchName string) (string, error) {
// RegisterClone(name string, topLevelFilesystemId string, clone Clone)
err := state.registry.RegisterClone(
newBranchName, topLevelFilesystemId,
Clone{
newCloneFilesystemId,
Origin{
originFilesystemId, originSnapshotId,
},
},
)
if err != nil {
return "failed-clone-registration", err
}
// spin off a state machine
state.initFilesystemMachine(newCloneFilesystemId)
kapi, err := getEtcdKeysApi()
if err != nil {
return "failed-get-etcd", err
}
// claim the clone as mine, so that it can be mounted here
_, err = kapi.Set(
context.Background(),
fmt.Sprintf(
"%s/filesystems/masters/%s", ETCD_PREFIX, newCloneFilesystemId,
),
state.myNodeId,
// only modify current master if this is a new filesystem id
&client.SetOptions{PrevExist: client.PrevNoExist},
)
if err != nil {
return "failed-make-cloner-master", err
}
return "", nil
}
func (f *fsMachine) run() {
// TODO cancel this when we eventually support deletion
log.Printf("[run:%s] INIT", f.filesystemId)
go runWhileFilesystemLives(
f.markFilesystemAsLive,
"markFilesystemAsLive",
f.filesystemId,
time.Duration(f.state.config.FilesystemMetadataTimeout/2)*time.Second,
time.Duration(f.state.config.FilesystemMetadataTimeout/2)*time.Second,
)
// The success backoff time for updateEtcdAboutSnapshots is 0s
// because it blocks on a channel anyway; inserting a success
// backoff just means it'll be rate-limited as it'll sleep before
// processing each snapshot!
go runWhileFilesystemLives(
f.updateEtcdAboutSnapshots,
"updateEtcdAboutSnapshots",
f.filesystemId,
1*time.Second,
0*time.Second,
)
go runWhileFilesystemLives(
f.pollDirty,
"pollDirty",
f.filesystemId,
1*time.Second,
1*time.Second,
)
go func() {
for state := discoveringState; state != nil; {
state = state(f)
}
f.transitionedTo("gone", "")
terminateRunnersWhileFilesystemLived(f.filesystemId)
// Senders close channels, receivers check for closedness.
close(f.innerResponses)
// Remove ourself from the filesystems map
f.state.filesystemsLock.Lock()
defer f.state.filesystemsLock.Unlock()
delete(*(f.state.filesystems), f.filesystemId)
log.Printf("[run:%s] terminated", f.filesystemId)
}()
// proxy requests and responses, enforcing an ordering, to avoid accepting
// a new request before a response comes back, ie to serialize requests &
// responses per-statemachine (without blocking the entire etcd event loop,
// which asynchronously writes to the requests chan)
log.Printf("[run:%s] reading from external requests", f.filesystemId)
for req := range f.requests {
log.Printf("[run:%s] got req: %s", f.filesystemId, req)
log.Printf("[run:%s] writing to internal requests", f.filesystemId)
f.innerRequests <- req
log.Printf("[run:%s] reading from internal responses", f.filesystemId)
resp, more := <-f.innerResponses
if !more {
log.Printf("[run:%s] statemachine is finished", f.filesystemId)
resp = &Event{"filesystem-gone", &EventArgs{}}
}
log.Printf("[run:%s] got resp: %s", f.filesystemId, resp)
log.Printf("[run:%s] writing to external responses", f.filesystemId)
f.responsesLock.Lock()
respChan, ok := f.responses[(*req.Args)["RequestId"].(string)]
f.responsesLock.Unlock()
if ok {
respChan <- resp
} else {
log.Printf(
"[run:%s] unable to find response chan '%s'! dropping resp %s :/",
f.filesystemId,
(*req.Args)["RequestId"].(string),
resp,
)
}
log.Printf("[run:%s] reading from external requests", f.filesystemId)
}
}
func (f *fsMachine) pollDirty() error {
kapi, err := getEtcdKeysApi()
if err != nil {
return err
}
if f.filesystem.mounted {
dirtyDelta, sizeBytes, err := getDirtyDelta(
f.filesystemId, f.latestSnapshot(),
)
if err != nil {
return err
}
if f.dirtyDelta != dirtyDelta || f.sizeBytes != sizeBytes {
f.dirtyDelta = dirtyDelta
f.sizeBytes = sizeBytes
serialized, err := json.Marshal(dirtyInfo{
Server: f.state.myNodeId,
DirtyBytes: dirtyDelta,
SizeBytes: sizeBytes,
})
if err != nil {
return err
}
_, err = kapi.Set(
context.Background(),
fmt.Sprintf(
"%s/filesystems/dirty/%s", ETCD_PREFIX, f.filesystemId,
),
string(serialized),
nil,
)
if err != nil {
return err
}
}
}
return nil
}
// return the latest snapshot id, or "" if none exists
func (f *fsMachine) latestSnapshot() string {
f.snapshotsLock.Lock()
defer f.snapshotsLock.Unlock()
if len(f.filesystem.snapshots) > 0 {
return f.filesystem.snapshots[len(f.filesystem.snapshots)-1].Id
}
return ""
}
func (f *fsMachine) getResponseChan(reqId string, e *Event) (chan *Event, error) {
f.responsesLock.Lock()
respChan, ok := f.responses[reqId]
f.responsesLock.Unlock()
if !ok {
return nil, fmt.Errorf("No such request id response channel %s", reqId)
}
return respChan, nil
}
func (f *fsMachine) markFilesystemAsLive() error {
return f.state.markFilesystemAsLiveInEtcd(f.filesystemId)
}
func (f *fsMachine) updateEtcdAboutSnapshots() error {
// attempt to connect to etcd
kapi, err := getEtcdKeysApi()
if err != nil {
return err
}
// as soon as we're connected, eagerly: if we know about some
// snapshots, **or the absence of them**, set this in etcd.
serialized, err := func() ([]byte, error) {
f.snapshotsLock.Lock()
defer f.snapshotsLock.Unlock()
return json.Marshal(f.filesystem.snapshots)
}()
// since we want atomic rewrites, we can just save the entire
// snapshot data in a single key, as a json list. this is easier to
// begin with! although we'll bump into the 1MB request limit in
// etcd eventually.
_, err = kapi.Set(
context.Background(),
fmt.Sprintf(
"%s/servers/snapshots/%s/%s", ETCD_PREFIX,
f.state.myNodeId, f.filesystemId,
),
string(serialized),
nil,
)
if err != nil {
return err
}
// ISSUE: We don't always hear the echo in time, see
// issue https://github.com/dotmesh-io/dotmesh/issues/54
log.Printf(
"[updateEtcdAboutSnapshots] successfully set new snaps for %s on %s,"+
" will we hear an echo?",
f.filesystemId, f.state.myNodeId,
)
// wait until the state machine notifies us that it's changed the
// snapshots
_ = <-f.snapshotsModified
log.Printf("[updateEtcdAboutSnapshots] going 'round the loop")
return nil
}
func (f *fsMachine) getCurrentState() string {
// abusing snapshotsLock here, maybe we should have a separate lock over
// these fields
f.snapshotsLock.Lock()
defer f.snapshotsLock.Unlock()
return f.currentState
}
func (f *fsMachine) transitionedTo(state string, status string) {
// abusing snapshotsLock here, maybe we should have a separate lock over
// these fields
f.snapshotsLock.Lock()
defer f.snapshotsLock.Unlock()
now := time.Now().UnixNano()
log.Printf(
"<transition> %s to %s %s (from %s %s, %.2fs ago)",
f.filesystemId, state, status, f.currentState, f.status,
float64(now-f.lastTransitionTimestamp)/float64(time.Second),
)
f.currentState = state
f.status = status
f.lastTransitionTimestamp = now
f.transitionObserver.Publish("transitions", state)
// update etcd
kapi, err := getEtcdKeysApi()
if err != nil {
log.Printf("error connecting to etcd while trying to update states: %s", err)
return
}
update := map[string]string{
"state": state, "status": status,
}
serialized, err := json.Marshal(update)
if err != nil {
log.Printf("cannot serialize %s: %s", update, err)
return
}
_, err = kapi.Set(
context.Background(),
// .../:server/:filesystem = {"state": "inactive", "status": "pulling..."}
fmt.Sprintf(
"%s/servers/states/%s/%s",
ETCD_PREFIX, f.state.myNodeId, f.filesystemId,
),
string(serialized),
nil,
)
if err != nil {
log.Printf("error updating etcd: %s", update, err)
return
}
}
// state functions
// invariant: whenever a state function receives on the events channel, it
// should respond with a response event, even in an error case.
func handoffState(f *fsMachine) stateFn {
f.transitionedTo("handoff", "starting...")
// I am a master, trying to move this filesystem to a slave.
// I got put into this state in response to a "move" event on f.requests,
// so it's my responsibility to put something onto f.responses, because
// there'll be someone out there listening for my response...
// I assume that previous states stopped any containers that were running
// on this filesystem, so the filesystem is quiescent.
// TODO stop any containers being able to get started here.
target := (*f.handoffRequest.Args)["target"].(string)
log.Printf("Found target node %s", target)
// subscribe for snapshot updates before we start sending, in case of races...
newSnapsChan := make(chan interface{})
f.newSnapsOnServers.Subscribe(target, newSnapsChan)
defer f.newSnapsOnServers.Unsubscribe(target, newSnapsChan)
// unmount the filesystem immediately, so that the filesystem doesn't get
// dirtied by being unmounted
event, _ := f.unmount()
if event.Name != "unmounted" {
log.Printf("unexpected response to unmount attempt: %s", event)
f.innerResponses <- event
return backoffState
}
// XXX if we error out of handoffState, we'll end up in an infinite loop if
// we don't re-mount the filesystem. see comment in backoffState for
// possible fix.
// take a snapshot and wait for it to arrive on the target
response, _ := f.snapshot(&Event{
Name: "snapshot",
Args: &EventArgs{"metadata": metadata{
"author": "system",
"message": fmt.Sprintf(
"Automatic snapshot during migration from %s to %s.",
f.state.myNodeId, target,
)},
},
})
f.transitionedTo("handoff", fmt.Sprintf("got snapshot response %s", response))
if response.Name != "snapshotted" {
// error - bail
f.innerResponses <- response
return backoffState
}
slaveUpToDate := false
waitingForSlaveSnapshot:
for !slaveUpToDate {
// ok, so snapshot succeeded. wait for it to be replicated to the
// target node (it should be, naturally because currently we replicate
// everything everywhere)
f.transitionedTo("handoff", fmt.Sprintf("calling snapshotsFor %s", target))
slaveSnapshots, err := f.state.snapshotsFor(target, f.filesystemId)
f.transitionedTo(
"handoff",
fmt.Sprintf("done calling snapshotsFor %s: %s", target, err),
)
if err != nil {
// Let's assume that no record of snapshots on a node means no
// filesystem there. If we're wrong and there /is/ a filesystem
// there with no snapshots, we won't be able to receive into it.
// But this shouldn't happen because you can only create a
// filesystem if you can write atomically to etcd, claiming its
// name for yourself.
log.Printf(
"Unable to find target snaps for %s on %s, assuming there are none and proceeding...",
f.filesystemId, target,
)
}
f.transitionedTo(
"handoff",
fmt.Sprintf("finding own snaps for move to %s", target),
)
// information about our new snapshot probably hasn't roundtripped
// through etcd yet, so use our definitive knowledge about our local
// state...
f.snapshotsLock.Lock()
snaps := f.filesystem.snapshots
f.snapshotsLock.Unlock()
f.transitionedTo(
"handoff",
fmt.Sprintf("done finding own snaps for move to %s", target),
)
apply, err := canApply(snaps, pointers(slaveSnapshots))
f.transitionedTo(
"handoff",
fmt.Sprintf("canApply returned %s, %s", apply, err),
)
if err != nil {
switch err.(type) {
case *ToSnapsUpToDate:
log.Printf("Found ToSnapsUpToDate, setting slaveUpToDate for %s", f.filesystemId)
slaveUpToDate = true
break waitingForSlaveSnapshot
}
} else {
err = fmt.Errorf(
"ff update of %s for %s to %s was possible, can't move yet, retrying...",
f.filesystemId, f.state.myNodeId, target,
)
}
if !slaveUpToDate {
log.Printf(
"Not proceeding with migration yet for %s from %s to %s because %s, waiting for new snaps...",
f.filesystemId, f.state.myNodeId, target, err,
)
}
// TODO timeout, or liveness check on replication
log.Printf("About to read from newSnapsChan(%s) we created earlier", target)
// say no to everything right now, but don't clog up requests
gotSnaps := false
for !gotSnaps {
select {
case e := <-f.innerRequests:
// What if a deletion message comes in here?
// In that case, the deletion will happen later, when we
// go into discovery again and perform the check for the
// filesystem being deleted.
log.Printf("rejecting all %s", e)
f.innerResponses <- &Event{"busy-handoff", &EventArgs{}}
case _ = <-newSnapsChan:
// TODO check that the latest snap is the one we expected
gotSnaps = true
log.Printf("Got new snaps of %s on %s", f.filesystemId, target)
// carry on
}
}
}
// cool, fs is quiesced and latest snap is on target. switch!
kapi, err := getEtcdKeysApi()
if err != nil {
f.innerResponses <- &Event{Name: "failed-to-connect-to-etcd"}
}
_, err = kapi.Set(
context.Background(),
fmt.Sprintf(
"%s/filesystems/masters/%s", ETCD_PREFIX, f.filesystemId,
),
target,
// only modify current master if I am indeed still the master
&client.SetOptions{PrevValue: f.state.myNodeId},
)
if err != nil {
f.innerResponses <- &Event{
Name: "failed-to-set-master-in-etcd",
Args: &EventArgs{
"err": err,
"target": f.filesystemId,
"node": f.state.myNodeId,
},
}
return backoffState
}
f.innerResponses <- &Event{Name: "moved"}
return inactiveState
}
func (f *fsMachine) unmount() (responseEvent *Event, nextState stateFn) {
out, err := exec.Command("umount", mnt(f.filesystemId)).CombinedOutput()
if err != nil {
log.Printf("%v while trying to unmount %s", err, fq(f.filesystemId))
return &Event{
Name: "failed-unmount",
Args: &EventArgs{"err": err, "combined-output": string(out)},
}, backoffState
}
f.filesystem.mounted = false
return &Event{Name: "unmounted"}, inactiveState
}
func (f *fsMachine) snapshot(e *Event) (responseEvent *Event, nextState stateFn) {
var meta metadata
if val, ok := (*e.Args)["metadata"]; ok {
meta = castToMetadata(val)
} else {
meta = metadata{}
}
meta["timestamp"] = fmt.Sprintf("%d", time.Now().UnixNano())
metadataEncoded, err := encodeMetadata(meta)
if err != nil {
return &Event{
Name: "failed-metadata-encode", Args: &EventArgs{"err": err},
}, backoffState
}
id, err := uuid.NewV4()
if err != nil {
return &Event{
Name: "failed-uuid", Args: &EventArgs{"err": err},
}, backoffState
}
snapshotId := id.String()
args := []string{"snapshot"}
args = append(args, metadataEncoded...)
args = append(args, fq(f.filesystemId)+"@"+snapshotId)
out, err := exec.Command(ZFS, args...).CombinedOutput()
log.Printf("[snapshot] Attempting: zfs %s", args)
if err != nil {
log.Printf("[snapshot] %v while trying to snapshot %s (%s)", err, fq(f.filesystemId), args)
return &Event{
Name: "failed-snapshot",
Args: &EventArgs{"err": err, "combined-output": string(out)},
}, backoffState
}
list, err := exec.Command(ZFS, "list", fq(f.filesystemId)+"@"+snapshotId).CombinedOutput()
if err != nil {
log.Printf("[snapshot] %v while trying to list snapshot %s (%s)", err, fq(f.filesystemId), args)
return &Event{
Name: "failed-snapshot",
Args: &EventArgs{"err": err, "combined-output": string(out)},
}, backoffState
}
log.Printf("[snapshot] listed snapshot: '%q'", strconv.Quote(string(list)))
f.snapshotsLock.Lock()
log.Printf("[snapshot] Succeeded snapshotting (out: '%s'), saving: %s", out, &snapshot{Id: snapshotId, Metadata: &meta})
f.filesystem.snapshots = append(f.filesystem.snapshots,
&snapshot{Id: snapshotId, Metadata: &meta})
f.snapshotsLock.Unlock()
f.snapshotsModified <- true
return &Event{Name: "snapshotted"}, activeState
}
// find the user-facing name of a given filesystem id. if we're a branch
// (clone), return the name of our parent filesystem.
func (f *fsMachine) name() (VolumeName, error) {
tlf, _, err := f.state.registry.LookupFilesystemById(f.filesystemId)
return tlf.MasterBranch.Name, err
}
func (f *fsMachine) containersRunning() ([]DockerContainer, error) {
f.state.containersLock.Lock()
defer f.state.containersLock.Unlock()
name, err := f.name()
if err != nil {
return []DockerContainer{}, err
}
return f.state.containers.Related(name.String())
}
func (f *fsMachine) stopContainers() error {
f.state.containersLock.Lock()
defer f.state.containersLock.Unlock()
name, err := f.name()
if err != nil {
return err
}
return f.state.containers.Stop(name.StringWithoutAdmin())
}
func (f *fsMachine) startContainers() error {
f.state.containersLock.Lock()
defer f.state.containersLock.Unlock()
name, err := f.name()
if err != nil {
return err
}
return f.state.containers.Start(name.StringWithoutAdmin())
}
func activeState(f *fsMachine) stateFn {
f.transitionedTo("active", "waiting")
log.Printf("entering active state for %s", f.filesystemId)
select {
case e := <-f.innerRequests:
if e.Name == "delete" {
err := f.state.deleteFilesystem(f.filesystemId)
if err != nil {
f.innerResponses <- &Event{
Name: "cant-delete",
Args: &EventArgs{"err": err},
}
} else {
f.innerResponses <- &Event{
Name: "deleted",
}
}
return nil
} else if e.Name == "transfer" {
// TODO dedupe
transferRequest, err := transferRequestify((*e.Args)["Transfer"])
if err != nil {
f.innerResponses <- &Event{
Name: "cant-cast-transfer-request",
Args: &EventArgs{"err": err},
}
return backoffState
}
f.lastTransferRequest = transferRequest
transferRequestId, ok := (*e.Args)["RequestId"].(string)
if !ok {
f.innerResponses <- &Event{
Name: "cant-cast-transfer-requestid",
Args: &EventArgs{"err": err},
}
return backoffState
}
f.lastTransferRequestId = transferRequestId
log.Printf("GOT TRANSFER REQUEST %+v", f.lastTransferRequest)
if f.lastTransferRequest.Direction == "push" {
return pushInitiatorState
} else if f.lastTransferRequest.Direction == "pull" {
return pullInitiatorState
}
} else if e.Name == "peer-transfer" {
// TODO dedupe
transferRequest, err := transferRequestify((*e.Args)["Transfer"])
if err != nil {
f.innerResponses <- &Event{
Name: "cant-cast-transfer-request",
Args: &EventArgs{"err": err},
}
return backoffState
}
f.lastTransferRequest = transferRequest
transferRequestId, ok := (*e.Args)["RequestId"].(string)
if !ok {
f.innerResponses <- &Event{
Name: "cant-cast-transfer-requestid",
Args: &EventArgs{"err": err},
}
return backoffState
}
f.lastTransferRequestId = transferRequestId
log.Printf("GOT PEER TRANSFER REQUEST %+v", f.lastTransferRequest)
if f.lastTransferRequest.Direction == "push" {
return pushPeerState
} else if f.lastTransferRequest.Direction == "pull" {
return pullPeerState
}
} else if e.Name == "move" {
// move straight into a state which doesn't allow us to take
// snapshots or do rollbacks
// refuse to move if we have any containers running
containers, err := f.containersRunning()
if err != nil {
log.Printf("Can't move filesystem while we can't list whether containers are using it")
f.innerResponses <- &Event{
Name: "error-listing-containers-during-move",
Args: &EventArgs{"err": err},
}
return backoffState
}
if len(containers) > 0 {
log.Printf("Can't move filesystem while containers are using it")
f.innerResponses <- &Event{
Name: "cannot-move-while-containers-running",
Args: &EventArgs{"containers": containers},
}
return backoffState
}
f.handoffRequest = e
return handoffState
} else if e.Name == "snapshot" {
response, state := f.snapshot(e)
f.innerResponses <- response
return state
} else if e.Name == "rollback" {
// roll back to given snapshot
rollbackTo := (*e.Args)["rollbackTo"].(string)
// TODO also roll back slaves (i.e., support doing this in unmounted state)
sliceIndex := -1
for i, snapshot := range f.filesystem.snapshots {
if snapshot.Id == rollbackTo {
// the first *deleted* snapshot will be the one *after*
// rollbackTo
sliceIndex = i + 1
}
}
// XXX This is broken for pinned branches right now
err := f.stopContainers()
defer func() {
err := f.startContainers()
if err != nil {
log.Printf(
"[activeState] unable to start containers in deferred func: %s",
err,
)
}
}()
if err != nil {
log.Printf(
"%v while trying to stop containers during rollback %s",
err, fq(f.filesystemId),
)
f.innerResponses <- &Event{
Name: "failed-stop-containers-during-rollback",
Args: &EventArgs{"err": err},
}
return backoffState
}
out, err := exec.Command(ZFS, "rollback",
"-r", fq(f.filesystemId)+"@"+rollbackTo).CombinedOutput()
if err != nil {
log.Printf("%v while trying to rollback %s", err, fq(f.filesystemId))
f.innerResponses <- &Event{
Name: "failed-rollback",
Args: &EventArgs{"err": err, "combined-output": string(out)},
}
return backoffState
}
if sliceIndex > 0 {
log.Printf("found index %d", sliceIndex)
log.Printf("snapshots before %s", f.filesystem.snapshots)
f.snapshotsLock.Lock()
f.filesystem.snapshots = f.filesystem.snapshots[:sliceIndex]
f.snapshotsLock.Unlock()
f.snapshotsModified <- true
log.Printf("snapshots after %s", f.filesystem.snapshots)
} else {
f.innerResponses <- &Event{
Name: "no-such-snapshot",
}
}
err = f.startContainers()
if err != nil {
log.Printf(
"%v while trying to start containers during rollback %s",
err, fq(f.filesystemId),
)
f.innerResponses <- &Event{
Name: "failed-start-containers-during-rollback",
Args: &EventArgs{"err": err},
}
return backoffState
}
f.innerResponses <- &Event{
Name: "rolled-back",
}
return activeState
} else if e.Name == "clone" {
// clone a new filesystem from the given snapshot, then spin off a
// new fsMachine for it.
/*
"topLevelFilesystemId": topLevelFilesystemId,
"originFilesystemId": originFilesystemId,
"originSnapshotId": args.SourceSnapshotId,
"newBranchName": args.NewBranchName,
*/
topLevelFilesystemId := (*e.Args)["topLevelFilesystemId"].(string)
originFilesystemId := (*e.Args)["originFilesystemId"].(string)
originSnapshotId := (*e.Args)["originSnapshotId"].(string)
newBranchName := (*e.Args)["newBranchName"].(string)
uuid, err := uuid.NewV4()
if err != nil {
f.innerResponses <- &Event{
Name: "failed-uuid", Args: &EventArgs{"err": err},
}
return backoffState
}
newCloneFilesystemId := uuid.String()
out, err := exec.Command(
ZFS, "clone",
fq(f.filesystemId)+"@"+originSnapshotId,
fq(newCloneFilesystemId),
).CombinedOutput()
if err != nil {
log.Printf("%v while trying to clone %s", err, fq(f.filesystemId))
f.innerResponses <- &Event{
Name: "failed-clone",
Args: &EventArgs{"err": err, "combined-output": string(out)},
}
return backoffState
}
errorName, err := activateClone(f.state,
topLevelFilesystemId, originFilesystemId, originSnapshotId,
newCloneFilesystemId, newBranchName)
if err != nil {
f.innerResponses <- &Event{
Name: errorName, Args: &EventArgs{"err": err},
}
return backoffState
}
f.innerResponses <- &Event{
Name: "cloned",
Args: &EventArgs{},
}
return activeState
} else if e.Name == "mount" {
f.innerResponses <- &Event{
Name: "mounted",
Args: &EventArgs{},
}
return activeState
} else if e.Name == "unmount" {
// fail if any containers running
containers, err := f.containersRunning()
if err != nil {
log.Printf("Can't unmount filesystem when we are unable to list containers using it")
f.innerResponses <- &Event{
Name: "error-listing-containers-during-unmount",
Args: &EventArgs{"err": err},
}
return backoffState
}
if len(containers) > 0 {
log.Printf("Can't unmount filesystem while containers are using it")
f.innerResponses <- &Event{
Name: "cannot-unmount-while-running-containers",
Args: &EventArgs{"containers": containers},
}
return backoffState
}
response, state := f.unmount()
f.innerResponses <- response
return state
} else {
f.innerResponses <- &Event{
Name: "unhandled",
Args: &EventArgs{"current-state": f.currentState, "event": e},
}
log.Printf("unhandled event %s while in activeState", e)
}
}
// something unknown happened, go and check the state of the system after a
// short timeout to avoid busylooping
return backoffState
}
// probably the wrong way to do it
func pointers(snapshots []snapshot) []*snapshot {
newList := []*snapshot{}
for _, snap := range snapshots {
s := &snapshot{}
*s = snap
newList = append(newList, s)
}
return newList
}
func (f *fsMachine) mount() (responseEvent *Event, nextState stateFn) {
out, err := exec.Command(
"mkdir", "-p", mnt(f.filesystemId)).CombinedOutput()
if err != nil {
log.Printf("%v while trying to mkdir mountpoint %s", err, fq(f.filesystemId))
return &Event{
Name: "failed-mkdir-mountpoint",
Args: &EventArgs{"err": err, "combined-output": string(out)},
}, backoffState
}
out, err = exec.Command("mount.zfs", "-o", "noatime",
fq(f.filesystemId), mnt(f.filesystemId)).CombinedOutput()
if err != nil {
log.Printf("%v while trying to mount %s", err, fq(f.filesystemId))
return &Event{
Name: "failed-mount",
Args: &EventArgs{"err": err, "combined-output": string(out)},
}, backoffState
}
// trust that zero exit codes from mkdir && mount.zfs means
// that it worked and that the filesystem now exists and is
// mounted
f.snapshotsLock.Lock()
f.filesystem.exists = true // needed in create case
f.filesystem.mounted = true
f.snapshotsLock.Unlock()
return &Event{Name: "mounted", Args: &EventArgs{}}, activeState
}
func inactiveState(f *fsMachine) stateFn {
f.transitionedTo("inactive", "waiting")
log.Printf("entering inactive state for %s", f.filesystemId)
handleEvent := func(e *Event) (bool, stateFn) {
if e.Name == "delete" {
err := f.state.deleteFilesystem(f.filesystemId)
if err != nil {
f.innerResponses <- &Event{
Name: "cant-delete",
Args: &EventArgs{"err": err},
}
} else {
f.innerResponses <- &Event{
Name: "deleted",
}
}
return true, nil
} else if e.Name == "mount" {
f.transitionedTo("inactive", "mounting")
event, nextState := f.mount()
f.innerResponses <- event
return true, nextState
} else {
f.innerResponses <- &Event{
Name: "unhandled",
Args: &EventArgs{"current-state": f.currentState, "event": e},
}
log.Printf("unhandled event %s while in inactiveState", e)
}
return false, nil
}
// ensure that if there's an event on the channel which a receive was
// cancelled in order to process, that we process that immediately before
// going back into receive. do this with an asynchronous read before
// checking going back into receive...
// TODO test this behaviour
select {
case e := <-f.innerRequests:
doTransition, nextState := handleEvent(e)
if doTransition {
return nextState
}
default:
// carry on
}
if f.attemptReceive() {
return receivingState
}
newSnapsOnMaster := make(chan interface{})
f.state.newSnapsOnMaster.Subscribe(f.filesystemId, newSnapsOnMaster)
defer f.state.newSnapsOnMaster.Unsubscribe(f.filesystemId, newSnapsOnMaster)
select {
case _ = <-newSnapsOnMaster:
return receivingState
case e := <-f.innerRequests:
doTransition, nextState := handleEvent(e)
if doTransition {
return nextState
}
}
return backoffState
}
func (f *fsMachine) plausibleSnapRange() (*snapshotRange, error) {
// get all snapshots for the given filesystem on the current master, and
// then start a pull if we need to
snapshots, err := f.state.snapshotsForCurrentMaster(f.filesystemId)
if err != nil {
return nil, err
}
f.snapshotsLock.Lock()
snapRange, err := canApply(pointers(snapshots), f.filesystem.snapshots)
f.snapshotsLock.Unlock()