-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrequests_copy.go
931 lines (762 loc) · 29.6 KB
/
requests_copy.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
package ctrl
import (
"context"
"crypto/sha256"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/fxamacker/cbor/v2"
"github.com/google/uuid"
)
type copyInitialData struct {
UUID string
SrcMethod Method
SrcNode Node
DstMethod Method
DstNode Node
SrcFilePath string
DstDir string
DstFile string
SplitChunkSize int
MaxTotalCopyTime int
FileMode fs.FileMode
FolderPermission uint64
}
// methodCopySrc are handles the initial and first part of
// the message flow for a copy to destination request.
// It's main role is to start up a sub process for the destination
// in which all the actual file copying is done.
//
// Initialization, Source:
// - Use the REQCopySrc method to handle the initial request from the user.
// - Spawn a REQCopySrc_uid subscriber to receive sync messages from destination.
// - Send the uid, and full-file hash to the destination in a REQCopyDst message.
//
// Initialization, Destination:
// - Spawn a REQCopyDst-uid from the uid we got from source.
// --------------------------------------------------------------------------------------
//
// All below happens in the From-uid and To-uid methods until the copying is done.
//
// - dst->src, dst sends a REQCopySrc-uid message with status "ready" file receiving to src.
// - src receives the message and start reading the file:
// - src, creates hash of the complete file.
// - src, reads the file in chunks, and create a hash of each chunk.
// - src->dst, send chunk when read.
// - dst->src, wait for status "ready" indicating the chuck was transfered.
// - Loop and read new chunc.
// - src->dst, when last chunch is sent send status back that we are ready for the next message.
// - src->dst, if failure send status "error", abort file copying and clean up on both src and dst.
//
// - dst, read and store each chunch to tmp folder and verify hash.
// - dst->src, send status "ready" to src when chunch is stored.
// - loop and check for status "last", if last:
// - build original file from chuncs.
// - verify hash when file is built.
// - dst->src, send status "done".
//
// - We should also be be able to resend a chunk, or restart the copying from where we left of if it seems to hang.
//
// dataStructure{
// Data []bytes
// Status copyStatus
// id int
// }
//
// Create a new copy sync process to handle the actual file copying.
// We use the context already created based on the time out specified
// in the requestTimeout field of the message.
//
// -----------------------------------------------------
// Handle writing to a file. Will truncate any existing data if the file did already
// exist.
func methodCopySrc(proc process, message Message, node string) ([]byte, error) {
// If the toNode field is not the same as nodeName of the receiving node
// we should forward the message to that specified toNode. This will allow
// us to initiate a file copy from another node to this node.
if message.ToNode != proc.node {
proc.newMessagesCh <- message
return nil, fmt.Errorf("info: the copy message was forwarded to %v message, %v", message.ToNode, message)
}
var subProcessName string
proc.processes.wg.Add(1)
go func() {
defer proc.processes.wg.Done()
// Set default split chunk size, will be replaced with value from
// methodArgs[3] if defined.
splitChunkSize := 100000
// Set default max total copy time, will be replaced with value from
// methodArgs[4] if defined.
maxTotalCopyTime := message.MethodTimeout
// Default permission of destination folder if we need to create it.
// The value will be replaced
folderPermission := uint64(0755)
proc.errorKernel.logDebug("methodCopySrc: before switch: FolderPermission defined in message for socket: %04o", "folderPermission", folderPermission)
// Verify and check the methodArgs
if len(message.MethodArgs) < 3 {
er := fmt.Errorf("error: methodCopySrc: got <3 number methodArgs: want srcfilePath,dstNode,dstFilePath")
proc.errorKernel.errSend(proc, message, er, logWarning)
return
}
if len(message.MethodArgs) > 3 {
// Check if split chunk size was set, if not keep default.
var err error
splitChunkSize, err = strconv.Atoi(message.MethodArgs[3])
if err != nil {
er := fmt.Errorf("error: methodCopySrc: unble to convert splitChunkSize into int value: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
}
}
if len(message.MethodArgs) > 4 {
// Check if maxTotalCopyTime was set, if not keep default.
var err error
maxTotalCopyTime, err = strconv.Atoi(message.MethodArgs[4])
if err != nil {
er := fmt.Errorf("error: methodCopySrc: unble to convert maxTotalCopyTime into int value: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
}
}
if len(message.MethodArgs) > 5 && message.MethodArgs[5] != "" {
// Check if file permissions were set, if not use default.
var err error
folderPermission, err = strconv.ParseUint(message.MethodArgs[5], 8, 32)
if err != nil {
proc.errorKernel.logError("methodCopySrc: failed to parse uint", "error", err)
}
proc.errorKernel.logDebug("methodCopySrc: FolderPermission defined in message for socket", "socket", message.MethodArgs[5], "converted", folderPermission)
if err != nil {
er := fmt.Errorf("error: methodCopySrc: unable to convert folderPermission into int value: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
}
}
SrcFilePath := message.MethodArgs[0]
DstNode := message.MethodArgs[1]
DstFilePath := message.MethodArgs[2]
// Create a child context to use with the procFunc with timeout set to the max allowed total copy time
// specified in the message.
var ctx context.Context
var cancel context.CancelFunc
func() {
ctx, cancel = context.WithTimeout(proc.ctx, time.Second*time.Duration(maxTotalCopyTime))
}()
// Create a subject for one copy request
uid := uuid.New()
subProcessName = fmt.Sprintf("%v.%v", SUBCopySrc, uid.String())
dstDir := filepath.Dir(DstFilePath)
dstFile := filepath.Base(DstFilePath)
m := Method(subProcessName)
// Also choosing to create the naming for the dst method here so
// we can have all the information in the cia from the beginning
// at both ends.
dstSubProcessName := fmt.Sprintf("%v.%v", SUBCopyDst, uid.String())
dstM := Method(dstSubProcessName)
// Get the file permissions
fileInfo, err := os.Stat(SrcFilePath)
if err != nil {
// errCh <- fmt.Errorf("error: methodCopySrc: failed to open file: %v, %v", SrcFilePath, err)
proc.errorKernel.logDebug("error: copySrcSubProcFunc: failed to stat", "file", err)
return
}
fileMode := fileInfo.Mode()
cia := copyInitialData{
UUID: uid.String(),
SrcNode: proc.node,
SrcMethod: m,
DstNode: Node(DstNode),
DstMethod: dstM,
SrcFilePath: SrcFilePath,
DstDir: dstDir,
DstFile: dstFile,
SplitChunkSize: splitChunkSize,
MaxTotalCopyTime: maxTotalCopyTime,
FileMode: fileMode,
FolderPermission: folderPermission,
}
sub := newSubjectNoVerifyHandler(m, node)
// Create a new sub process that will do the actual file copying.
copySrcSubProc := newSubProcess(ctx, proc.server, sub)
// Give the sub process a procFunc so we do the actual copying within a procFunc,
// and not directly within the handler.
copySrcSubProc.procFunc = copySrcSubProcFunc(cia, cancel, message)
// assign a handler to the sub process
copySrcSubProc.handler = copySrcSubHandler()
// The process will be killed when the context expires.
go copySrcSubProc.start()
// Send a message over the the node where the destination file will be written,
// to also start up a sub process on the destination node.
// Marshal the data payload to send to the dst.
cb, err := cbor.Marshal(cia)
if err != nil {
er := fmt.Errorf("error: newSubjectAndMessage : %v, message: %v", err, message)
proc.errorKernel.errSend(proc, message, er, logWarning)
cancel()
}
msg := message
msg.ToNode = Node(DstNode)
//msg.Method = REQToFile
msg.Method = CopyDst
msg.Data = cb
msg.ACKTimeout = message.ACKTimeout
msg.Retries = message.Retries
msg.ReplyACKTimeout = message.ReplyACKTimeout
msg.ReplyRetries = message.ReplyRetries
// msg.Directory = dstDir
// msg.FileName = dstFile
proc.newMessagesCh <- msg
replyData := fmt.Sprintf("info: succesfully initiated copy source process: procName=%v, srcNode=%v, srcPath=%v, dstNode=%v, dstPath=%v, starting sub process=%v for the actual copying", copySrcSubProc.processName, node, SrcFilePath, DstNode, DstFilePath, subProcessName)
newReplyMessage(proc, message, []byte(replyData))
}()
ackMsg := []byte("confirmed from: " + node + ": " + fmt.Sprint(message.ID))
return ackMsg, nil
}
// newSubProcess is a wrapper around newProcess which sets the isSubProcess value to true.
func newSubProcess(ctx context.Context, server *server, subject Subject) process {
p := newProcess(ctx, server, subject)
p.isSubProcess = true
return p
}
// ----
// methodCopyDst are handles the initial and first part of
// the message flow for a copy to destination request.
// It's main role is to start up a sub process for the destination
// in which all the actual file copying is done.
func methodCopyDst(proc process, message Message, node string) ([]byte, error) {
var subProcessName string
proc.processes.wg.Add(1)
go func() {
defer proc.processes.wg.Done()
// Get the status message sent from source.
var cia copyInitialData
err := cbor.Unmarshal(message.Data, &cia)
if err != nil {
er := fmt.Errorf("error: methodCopyDst: failed to cbor Unmarshal data: %v, message=%v", err, message)
proc.errorKernel.errSend(proc, message, er, logWarning)
return
}
// Create a child context to use with the procFunc with timeout set to the max allowed total copy time
// specified in the message.
var ctx context.Context
var cancel context.CancelFunc
func() {
ctx, cancel = context.WithTimeout(proc.ctx, time.Second*time.Duration(cia.MaxTotalCopyTime))
}()
// Create a subject for one copy request
sub := newSubjectNoVerifyHandler(cia.DstMethod, node)
// Check if we already got a sub process registered and started with
// the processName. If true, return here and don't start up another
// process for that file.
//
// This check is put in here if a message for some reason are
// received more than once. The reason that this might happen can be
// that a message for the same copy request was received earlier, but
// was unable to start up within the timeout specified. The Sender of
// that request will then resend the message, but at the time that
// second message is received the subscriber process started for the
// previous message is then fully up and running, so we just discard
// that second message in those cases.
pn := processNameGet(sub.name())
// fmt.Printf("\n\n *** DEBUG: processNameGet: %v\n\n", pn)
proc.processes.active.mu.Lock()
_, ok := proc.processes.active.procNames[pn]
proc.processes.active.mu.Unlock()
if ok {
proc.errorKernel.logDebug("methodCopyDst: subprocesses already existed, will not start another subscriber for", "processName", pn)
// HERE!!!
// If the process name already existed we return here before any
// new information is registered in the process map and we avoid
// having to clean that up later.
return
}
// Create a new sub process that will do the actual file copying.
copyDstSubProc := newSubProcess(ctx, proc.server, sub)
// Give the sub process a procFunc so we do the actual copying within a procFunc,
// and not directly within the handler.
copyDstSubProc.procFunc = copyDstSubProcFunc(cia, message, cancel)
// assign a handler to the sub process
copyDstSubProc.handler = copyDstSubHandler()
// The process will be killed when the context expires.
go copyDstSubProc.start()
fp := filepath.Join(cia.DstDir, cia.DstFile)
replyData := fmt.Sprintf("info: succesfully initiated copy source process: procName=%v, srcNode=%v, dstPath=%v, starting sub process=%v for the actual copying", copyDstSubProc.processName, node, fp, subProcessName)
newReplyMessage(proc, message, []byte(replyData))
}()
ackMsg := []byte("confirmed from: " + node + ": " + fmt.Sprint(message.ID))
return ackMsg, nil
}
func copySrcSubHandler() func(process, Message, string) ([]byte, error) {
h := func(proc process, message Message, node string) ([]byte, error) {
// We should receive a ready message generated by the procFunc of Dst,
// and any messages received we directly route into the procFunc.
select {
case <-proc.ctx.Done():
proc.errorKernel.logDebug("copySrcHandler: process ended", "processName", proc.processName)
case proc.procFuncCh <- message:
proc.errorKernel.logDebug("copySrcHandler: passing message over to procFunc", "processName", proc.processName)
}
return nil, nil
}
return h
}
func copyDstSubHandler() func(process, Message, string) ([]byte, error) {
h := func(proc process, message Message, node string) ([]byte, error) {
select {
case <-proc.ctx.Done():
proc.errorKernel.logDebug("copyDstHandler: process ended", "processName", proc.processName)
case proc.procFuncCh <- message:
proc.errorKernel.logDebug("copyDstHandler: passing message over to procFunc", "processName", proc.processName)
}
return nil, nil
}
return h
}
type copyStatus int
const (
copyReady copyStatus = 1
copyData copyStatus = 2
copySrcDone copyStatus = 3
copyResendLast copyStatus = 4
copyDstDone copyStatus = 5
)
// copySubData is the structure being used between the src and dst while copying data.
type copySubData struct {
CopyStatus copyStatus
CopyData []byte
ChunkNumber int
Hash [32]byte
}
func copySrcSubProcFunc(cia copyInitialData, cancel context.CancelFunc, initialMessage Message) func(context.Context, process, chan Message) error {
pf := func(ctx context.Context, proc process, procFuncCh chan Message) error {
// Check if the realpath of the directory and filename specified in the
// message are of type unix socket, and if it is we do not add the extra
// suffix to the filename.
file := filepath.Join(initialMessage.Directory, initialMessage.FileName)
// Check the file is a unix socket, and if it is we write the
// data to the socket instead of writing it to a normal file.
// We don't care about the error.
fi, err := os.Stat(file)
if err != nil {
er := fmt.Errorf("DEBUG: ERROR while os.Stat(file): copySrcProcFunc, fileInfo: %v, err: %v", fi, err)
proc.errorKernel.errSend(proc, Message{}, er, logWarning)
}
// We want to be able to send the reply message when the copying is done,
// and also for any eventual errors within the subProcFunc. We want to
// write these to the same place as the the reply message for the initial
// request, but we append .sub and .error to be able to write them to
// individual files.
msgForSubReplies := initialMessage
msgForSubErrors := initialMessage
if fi != nil {
if fi.Mode().Type() != fs.ModeSocket {
msgForSubReplies.FileName = msgForSubReplies.FileName + ".copyreply"
msgForSubErrors.FileName = msgForSubErrors.FileName + ".copyerror"
}
} else {
msgForSubReplies.FileName = msgForSubReplies.FileName + ".copyreply"
msgForSubErrors.FileName = msgForSubErrors.FileName + ".copyerror"
}
var chunkNumber = 0
var lastReadChunk []byte
var resendRetries int
// Initiate the file copier.
fh, err := os.Open(cia.SrcFilePath)
if err != nil {
er := fmt.Errorf("error: copySrcSubProcFunc: failed to open file: %v", err)
proc.errorKernel.errSend(proc, Message{}, er, logWarning)
newReplyMessage(proc, msgForSubErrors, []byte(er.Error()))
return er
}
defer fh.Close()
// Do action based on copyStatus received.
for {
select {
case <-ctx.Done():
proc.errorKernel.logDebug("copySrcProcFunc: canceling procFunc", "processName", proc.processName)
return nil
// Pick up the message recived by the copySrcSubHandler.
case message := <-procFuncCh:
var csa copySubData
err := cbor.Unmarshal(message.Data, &csa)
if err != nil {
er := fmt.Errorf("error: copySrcSubHandler: cbor unmarshal of csa failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
newReplyMessage(proc, msgForSubErrors, []byte(er.Error()))
return er
}
switch csa.CopyStatus {
case copyReady:
err := func() error {
// We set the default status to copyData. If we get an io.EOF we change it to copyDone later.
status := copyData
b := make([]byte, cia.SplitChunkSize)
n, err := fh.Read(b)
if err != nil && err != io.EOF {
er := fmt.Errorf("error: copySrcSubHandler: failed to read chunk from file: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
newReplyMessage(proc, msgForSubErrors, []byte(er.Error()))
return er
}
if err == io.EOF {
status = copySrcDone
}
lastReadChunk = make([]byte, len(b[:n]))
copy(lastReadChunk, b[:n])
//lastReadChunk = b[:n]
// Create a hash of the bytes.
hash := sha256.Sum256(b[:n])
chunkNumber++
// Create message and send data to dst.
csa := copySubData{
CopyStatus: status,
CopyData: b[:n],
ChunkNumber: chunkNumber,
Hash: hash,
}
csaSerialized, err := cbor.Marshal(csa)
if err != nil {
er := fmt.Errorf("error: copySrcSubProcFunc: cbor marshal of csa failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
newReplyMessage(proc, msgForSubErrors, []byte(er.Error()))
return er
}
// We want to send a message back to src that we are ready to start.
msg := Message{
ToNode: cia.DstNode,
FromNode: cia.SrcNode,
Method: cia.DstMethod,
ReplyMethod: None,
Data: csaSerialized,
IsSubPublishedMsg: true,
ACKTimeout: initialMessage.ACKTimeout,
Retries: initialMessage.Retries,
ReplyACKTimeout: initialMessage.ReplyACKTimeout,
ReplyRetries: initialMessage.ReplyRetries,
}
proc.newMessagesCh <- msg
resendRetries = 0
// Testing with contect canceling here.
// proc.ctxCancel()
return nil
}()
if err != nil {
return err
}
case copyResendLast:
if resendRetries > message.Retries {
er := fmt.Errorf("error: %v: failed to resend the chunk for the %v time, giving up", cia.DstMethod, resendRetries)
proc.errorKernel.errSend(proc, message, er, logWarning)
newReplyMessage(proc, msgForSubErrors, []byte(er.Error()))
// NB: Should we call cancel here, or wait for the timeout ?
proc.ctxCancel()
}
b := lastReadChunk
status := copyData
// Create a hash of the bytes
hash := sha256.Sum256(b)
chunkNumber++
// Create message and send data to dst
csa := copySubData{
CopyStatus: status,
CopyData: b,
ChunkNumber: chunkNumber,
Hash: hash,
}
csaSerialized, err := cbor.Marshal(csa)
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: cbor marshal of csa failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
newReplyMessage(proc, msgForSubErrors, []byte(er.Error()))
return er
}
// We want to send a message back to src that we are ready to start.
msg := Message{
ToNode: cia.DstNode,
FromNode: cia.SrcNode,
Method: cia.DstMethod,
ReplyMethod: None,
Data: csaSerialized,
IsSubPublishedMsg: true,
ACKTimeout: initialMessage.ACKTimeout,
Retries: initialMessage.Retries,
ReplyACKTimeout: initialMessage.ReplyACKTimeout,
ReplyRetries: initialMessage.ReplyRetries,
}
proc.newMessagesCh <- msg
resendRetries++
case copyDstDone:
d := fmt.Sprintf("copyDstDone,%v,%v", cia.SrcFilePath, filepath.Join(cia.DstDir, cia.DstFile))
newReplyMessage(proc, msgForSubReplies, []byte(d))
cancel()
return nil
default:
er := fmt.Errorf("error: copySrcSubProcFunc: not valid copyStatus, exiting: %v", csa.CopyStatus)
proc.errorKernel.errSend(proc, message, er, logWarning)
newReplyMessage(proc, msgForSubErrors, []byte(er.Error()))
return er
}
}
}
//return nil
}
return pf
}
func copyDstSubProcFunc(cia copyInitialData, message Message, cancel context.CancelFunc) func(context.Context, process, chan Message) error {
pf := func(ctx context.Context, proc process, procFuncCh chan Message) error {
csa := copySubData{
CopyStatus: copyReady,
}
csaSerialized, err := cbor.Marshal(csa)
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: cbor marshal of csa failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
return er
}
// We want to send a message back to src that we are ready to start.
{
msg := Message{
ToNode: cia.SrcNode,
FromNode: cia.DstNode,
Method: cia.SrcMethod,
ReplyMethod: None,
Data: csaSerialized,
IsSubPublishedMsg: true,
ACKTimeout: message.ACKTimeout,
Retries: message.Retries,
ReplyACKTimeout: message.ReplyACKTimeout,
ReplyRetries: message.ReplyRetries,
}
proc.newMessagesCh <- msg
}
// Open a tmp folder for where to write the received chunks
tmpFolder := filepath.Join(proc.configuration.SocketFolder, cia.DstFile+"-"+cia.UUID)
err = os.Mkdir(tmpFolder, 0770)
if err != nil {
er := fmt.Errorf("copyDstProcSubFunc: create tmp folder for copying failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
return er
}
defer func() {
err = os.RemoveAll(tmpFolder)
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: remove temp dir failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
}
}()
for {
select {
case <-ctx.Done():
proc.errorKernel.logDebug("copyDstProcFunc: procFunc ended: %v", "processName", proc.processName)
return nil
case message := <-procFuncCh:
var csa copySubData
err := cbor.Unmarshal(message.Data, &csa)
if err != nil {
er := fmt.Errorf("error: copySrcSubHandler: cbor unmarshal of csa failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
return er
}
// Check if the hash matches. If it fails we set the status so we can
// trigger the resend of the last message in the switch below.
hash := sha256.Sum256(csa.CopyData)
if hash != csa.Hash {
proc.errorKernel.logDebug("copyDstSubProcFunc: hash of received message is not correct for", "DstMethod", cia.DstMethod)
csa.CopyStatus = copyResendLast
}
switch csa.CopyStatus {
case copyData:
err := func() error {
filePath := filepath.Join(tmpFolder, strconv.Itoa(csa.ChunkNumber)+"."+cia.UUID)
fh, err := os.OpenFile(filePath, os.O_TRUNC|os.O_RDWR|os.O_CREATE|os.O_SYNC, 0660)
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: open destination chunk file for writing failed: %v", err)
return er
}
defer fh.Close()
_, err = fh.Write(csa.CopyData)
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: writing to chunk file failed: %v", err)
return er
}
return nil
}()
if err != nil {
proc.errorKernel.errSend(proc, message, err, logWarning)
return err
}
// Prepare and send a ready message to src for the next chunk.
csa := copySubData{
CopyStatus: copyReady,
}
csaSer, err := cbor.Marshal(csa)
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: cbor marshal of csa failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
return er
}
msg := Message{
ToNode: cia.SrcNode,
FromNode: cia.DstNode,
Method: cia.SrcMethod,
ReplyMethod: None,
Data: csaSer,
IsSubPublishedMsg: true,
ACKTimeout: message.ACKTimeout,
Retries: message.Retries,
ReplyACKTimeout: message.ReplyACKTimeout,
ReplyRetries: message.ReplyRetries,
}
proc.newMessagesCh <- msg
case copyResendLast:
// The csa already contains copyStatus copyResendLast when reached here,
// so we can just serialize csa, and send a message back to sourcde for
// resend of the last message.
csaSer, err := cbor.Marshal(csa)
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: cbor marshal of csa failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
return er
}
msg := Message{
ToNode: cia.SrcNode,
FromNode: cia.DstNode,
Method: cia.SrcMethod,
ReplyMethod: None,
Data: csaSer,
IsSubPublishedMsg: true,
ACKTimeout: message.ACKTimeout,
Retries: message.Retries,
ReplyACKTimeout: message.ReplyACKTimeout,
ReplyRetries: message.ReplyRetries,
}
proc.newMessagesCh <- msg
case copySrcDone:
err := func() error {
// Open the main file that chunks files will be written into.
filePath := filepath.Join(cia.DstDir, cia.DstFile)
// HERE:
proc.errorKernel.logDebug("copyDstSubProcFunc: Before creating folder: cia.FolderPermission: %04o", "FolderPermission", cia.FolderPermission)
if _, err := os.Stat(cia.DstDir); os.IsNotExist(err) {
err := os.MkdirAll(cia.DstDir, fs.FileMode(cia.FolderPermission))
if err != nil {
return fmt.Errorf("copyDstSubProcFunc: failed to create destination directory for file copying %v: %v", cia.DstDir, err)
}
proc.errorKernel.logDebug("copyDstSubProcFunc: Created folder: with cia.FolderPermission: %04o", "folderPermission", cia.FolderPermission)
}
// Rename the file so we got a backup.
backupOriginalFileName := filePath + ".bck"
os.Rename(filePath, backupOriginalFileName)
mainfh, err := os.OpenFile(filePath, os.O_TRUNC|os.O_RDWR|os.O_CREATE|os.O_SYNC, cia.FileMode)
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: open final destination file failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
return er
}
defer mainfh.Close()
type fInfo struct {
name string
dir string
nr int
}
files := []fInfo{}
// Walk the tmp transfer directory and combine all the chunks into one file.
err = filepath.Walk(tmpFolder, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
fi := fInfo{}
fi.name = filepath.Base(path)
fi.dir = filepath.Dir(path)
sp := strings.Split(fi.name, ".")
nr, err := strconv.Atoi(sp[0])
if err != nil {
return err
}
fi.nr = nr
files = append(files, fi)
}
return nil
})
// Sort all the source nodes.
sort.SliceStable(files, func(i, j int) bool {
return files[i].nr < files[j].nr
})
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: creation of slice of chunk paths failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
return er
}
err = func() error {
for _, fInfo := range files {
fp := filepath.Join(fInfo.dir, fInfo.name)
fh, err := os.Open(fp)
if err != nil {
return err
}
defer fh.Close()
b := make([]byte, cia.SplitChunkSize)
n, err := fh.Read(b)
if err != nil {
return err
}
_, err = mainfh.Write(b[:n])
if err != nil {
return err
}
}
return nil
}()
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: write to final destination file failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
}
// Remove the backup file.
err = os.Remove(backupOriginalFileName)
if err != nil && !os.IsNotExist(err) {
er := fmt.Errorf("error: copyDstSubProcFunc: remove of backup of original file failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
}
proc.errorKernel.logDebug("copyDstSubProcFunc: copy: successfully wrote all split chunk files into", "file", filePath)
// Signal back to src that we are done, so it can cancel the process.
{
csa := copySubData{
CopyStatus: copyDstDone,
}
csaSerialized, err := cbor.Marshal(csa)
if err != nil {
er := fmt.Errorf("error: copyDstSubProcFunc: cbor marshal of csa failed: %v", err)
proc.errorKernel.errSend(proc, message, er, logWarning)
return er
}
// We want to send a message back to src that we are ready to start.
msg := Message{
ToNode: cia.SrcNode,
FromNode: cia.DstNode,
Method: cia.SrcMethod,
ReplyMethod: None,
Data: csaSerialized,
IsSubPublishedMsg: true,
ACKTimeout: message.ACKTimeout,
Retries: message.Retries,
ReplyACKTimeout: message.ReplyACKTimeout,
ReplyRetries: message.ReplyRetries,
}
proc.newMessagesCh <- msg
}
cancel()
return nil
}()
if err != nil {
return err
}
}
}
}
}
return pf
}