forked from FactomProject/factomd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
processList.go
1397 lines (1191 loc) · 45.7 KB
/
processList.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
// Copyright 2017 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package state
import (
"bytes"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/FactomProject/factomd/events/eventmessages/generated/eventmessages"
"github.com/FactomProject/factomd/common/adminBlock"
"github.com/FactomProject/factomd/common/constants"
"github.com/FactomProject/factomd/common/directoryBlock"
"github.com/FactomProject/factomd/common/entryCreditBlock"
"github.com/FactomProject/factomd/common/interfaces"
"github.com/FactomProject/factomd/common/messages"
"github.com/FactomProject/factomd/common/primitives"
"github.com/FactomProject/factomd/util/atomic"
//"github.com/FactomProject/factomd/database/databaseOverlay"
log "github.com/sirupsen/logrus"
)
var _ = fmt.Print
var _ = log.Print
var plLogger = packageLogger.WithFields(log.Fields{"subpack": "process-list"})
type ProcessList struct {
DBHeight uint32 // The directory block height for these lists
// Temporary balances from updating transactions in real time.
FactoidBalancesT map[[32]byte]int64
FactoidBalancesTMutex sync.Mutex
ECBalancesT map[[32]byte]int64
ECBalancesTMutex sync.Mutex
State *State
VMs []*VM // Process list for each server (up to 32)
ServerMap [10][64]int // Map of FedServers to all Servers for each minute
System VM // System Faults and other system wide messages
diffSigTally int /* Tally of how many VMs have provided different
Directory Block Signatures than what we have
(discard DBlock if > 1/2 have sig differences) */
// messages processed in this list
OldMsgs map[[32]byte]interfaces.IMsg
oldmsgslock sync.Mutex
// Chains that are executed, but not processed. There is a small window of a pending chain that the ack
// will pass and the chainhead will fail. This covers that window. This is only used by WSAPI,
// do not use it anywhere internally.
PendingChainHeads *SafeMsgMap
OldAcks map[[32]byte]interfaces.IMsg
oldackslock sync.Mutex
// Entry Blocks added within 10 minutes (follower and leader)
NewEBlocks map[[32]byte]interfaces.IEntryBlock
neweblockslock sync.Mutex
NewEntriesMutex sync.RWMutex
NewEntries map[[32]byte]interfaces.IEntry
// State information about the directory block while it is under construction. We may
// have to start building the next block while still building the previous block.
AdminBlock interfaces.IAdminBlock
EntryCreditBlock interfaces.IEntryCreditBlock
DirectoryBlock interfaces.IDirectoryBlock
// Number of Servers acknowledged by Factom
Matryoshka []interfaces.IHash // Reverse Hash
AuditServers []interfaces.IServer // List of Audit Servers
FedServers []interfaces.IServer // List of Federated Servers
// The Fedlist and Audlist at the START of the block. Server faults
// can change the list, and we can calculate the deltas at the end
StartingAuditServers []interfaces.IServer // List of Audit Servers
StartingFedServers []interfaces.IServer // List of Federated Servers
// DB Sigs
DBSignatures []DBSig
DBSigAlreadySent bool
NextHeightToProcess [64]int
// Cut overhead
stringCnt int
}
var _ interfaces.IProcessList = (*ProcessList)(nil)
// Data needed to add to admin block
type DBSig struct {
ChainID interfaces.IHash
Signature interfaces.IFullSignature
VMIndex int
}
type VM struct {
List []interfaces.IMsg // Lists of acknowledged messages
ListAck []*messages.Ack // Acknowledgements
Height int // Height of first unprocessed message (count of messages processed)
EomMinuteIssued int // Last Minute Issued on this VM (from the leader, when we are the leader)
LeaderMinute int // Where the leader is in acknowledging messages
Synced bool // Is this VM synced yet?
heartBeat int64 // Just ping ever so often if we have heard nothing.
Signed bool // We have signed the previous block.
WhenFaulted int64 // WhenFaulted is a timestamp of when this VM was faulted
FaultFlag int // FaultFlag tracks what the VM was faulted for (0 = EOM missing, 1 = negotiation issue)
ProcessTime interfaces.Timestamp // Last time we made progress on this VM
VmIndex int // the index of this MV
HighestNil int // Debug highest nil reported
p *ProcessList // processList this VM part of
}
func (p *ProcessList) GetKeysNewEntries() (keys [][32]byte) {
if p == nil {
return
}
p.NewEntriesMutex.RLock()
defer p.NewEntriesMutex.RUnlock()
keys = make([][32]byte, len(p.NewEntries))
i := 0
for k := range p.NewEntries {
keys[i] = k
i++
}
return
}
func (p *ProcessList) GetNewEntry(key [32]byte) interfaces.IEntry {
if p == nil {
return nil
}
p.NewEntriesMutex.RLock()
defer p.NewEntriesMutex.RUnlock()
return p.NewEntries[key]
}
func (p *ProcessList) LenNewEntries() int {
if p == nil {
return 0
}
p.NewEntriesMutex.RLock()
defer p.NewEntriesMutex.RUnlock()
return len(p.NewEntries)
}
func (p *ProcessList) Complete() bool {
if p == nil {
return false
}
if p.DBHeight <= p.State.GetHighestSavedBlk() {
return true
}
for i := 0; i < len(p.FedServers); i++ {
vm := p.VMs[i]
if vm.LeaderMinute < 10 {
return false
}
if vm.Height < len(vm.List) {
return false
}
}
return true
}
// Returns the Virtual Server index for this hash for the given minute
func (p *ProcessList) VMIndexFor(hash []byte) int {
if p == nil || p.State.OneLeader {
return 0
}
v := uint64(0)
for _, b := range hash {
v += uint64(b)
}
r := int(v % uint64(len(p.FedServers)))
return r
}
func (p *ProcessList) GetVMStatsForFedServer(index int) (vmIndex int, listHeight int, listLength int, nextNil int) {
vmIndex = FedServerVM(p.ServerMap, len(p.FedServers), p.State.GetCurrentMinute(), index)
if vmIndex < 0 {
return vmIndex, -1, -1, -1
}
listHeight = p.VMs[vmIndex].Height
listLength = len(p.VMs[vmIndex].List)
nextNil = p.VMs[vmIndex].HighestNil
return vmIndex, listHeight, listLength, nextNil
}
func SortServers(servers []interfaces.IServer) []interfaces.IServer {
for i := 0; i < len(servers)-1; i++ {
done := true
for j := 0; j < len(servers)-1-i; j++ {
fs1 := servers[j].GetChainID().Bytes()
fs2 := servers[j+1].GetChainID().Bytes()
if bytes.Compare(fs1, fs2) > 0 {
tmp := servers[j]
servers[j] = servers[j+1]
servers[j+1] = tmp
done = false
}
}
if done {
return servers
}
}
return servers
}
// duplicate function in election but cannot import because of a dependency loop
func (p *ProcessList) Sort(serv []interfaces.IServer) bool {
changed := false
for i := 0; i < len(serv)-1; i++ {
allgood := true
for j := 0; j < len(serv)-1-i; j++ {
if bytes.Compare(serv[j].GetChainID().Bytes(), serv[j+1].GetChainID().Bytes()) > 0 {
s := serv[j]
serv[j] = serv[j+1]
serv[j+1] = s
allgood = false
changed = true
}
}
if allgood {
return changed
}
}
return changed
}
func (p *ProcessList) LogPrintLeaders(log string) {
s := p.State
s.LogPrintf(log, "%6s | %6s", "Fed", "Aud")
limit := len(p.FedServers)
if limit < len(p.AuditServers) {
limit = len(p.AuditServers)
}
for i := 0; i < limit; i++ {
f := ""
a := ""
if i < len(p.FedServers) {
f = fmt.Sprintf("%x", p.FedServers[i].GetChainID().Bytes()[3:6])
}
if i < len(p.AuditServers) {
a = fmt.Sprintf("%x", p.AuditServers[i].GetChainID().Bytes()[3:6])
}
s.LogPrintf(log, "%s | %s", f, a)
}
}
func (p *ProcessList) SortFedServers() {
s := p.State
if p.FedServers != nil {
s.LogPrintf("executeMsg", "Process Sort FedServers")
changed := p.Sort(p.FedServers)
if changed {
s.LogPrintf("election", "Sort changed p.Federated in ProcessList.SortFedServers")
p.LogPrintLeaders("process")
}
}
}
func (p *ProcessList) SortAuditServers() {
s := p.State
if p.AuditServers != nil {
s.LogPrintf("executeMsg", "Process Sort AuditServers")
changed := p.Sort(p.AuditServers)
if changed {
s.LogPrintf("election", "Sort changed p.Audit in ProcessList.SortAuditServers")
p.LogPrintLeaders("process")
}
}
}
func (p *ProcessList) SortDBSigs() {
// Sort by VMIndex
for i := 0; i < len(p.DBSignatures)-1; i++ {
done := true
for j := 0; j < len(p.DBSignatures)-1-i; j++ {
if p.DBSignatures[j].VMIndex > p.DBSignatures[j+1].VMIndex {
tmp := p.DBSignatures[j]
p.DBSignatures[j] = p.DBSignatures[j+1]
p.DBSignatures[j+1] = tmp
done = false
}
}
if done {
return
}
}
/* Sort by ChainID
for i := 0; i < len(p.DBSignatures)-1; i++ {
done := true
for j := 0; j < len(p.DBSignatures)-1-i; j++ {
fs1 := p.DBSignatures[j].ChainID.Bytes()
fs2 := p.DBSignatures[j+1].ChainID.Bytes()
if bytes.Compare(fs1, fs2) > 0 {
tmp := p.DBSignatures[j]
p.DBSignatures[j] = p.DBSignatures[j+1]
p.DBSignatures[j+1] = tmp
done = false
}
}
if done {
return
}
}*/
}
// Returns the Federated Server responsible for this hash in this minute
func (p *ProcessList) FedServerFor(minute int, hash []byte) interfaces.IServer {
vs := p.VMIndexFor(hash)
if vs < 0 {
return nil
}
fedIndex := p.ServerMap[minute][vs]
return p.FedServers[fedIndex]
}
func FedServerVM(serverMap [10][64]int, numberOfFedServers int, minute int, fedIndex int) int {
for i := 0; i < numberOfFedServers; i++ {
if serverMap[minute][i] == fedIndex {
return i
}
}
return -1
}
func (p *ProcessList) GetVirtualServers(minute int, identityChainID interfaces.IHash) (found bool, index int) {
//fmt.Fprintf(os.Stderr, "GetVirtualServers(%d,%x)", minute, identityChainID.Bytes()[3:6])
found, fedIndex := p.GetFedServerIndexHash(identityChainID)
if !found {
return false, -1
}
p.MakeMap()
if minute > 9 {
minute = 9 // in case we get called between blocks.
}
for i := 0; i < len(p.FedServers); i++ {
fedix := p.ServerMap[minute][i]
if fedix == fedIndex {
return true, i
}
}
return false, -1
}
// Returns true and the index of this server, or false and the insertion point for this server
func (p *ProcessList) GetFedServerIndexHash(identityChainID interfaces.IHash) (bool, int) {
if p == nil {
return false, 0
}
scid := identityChainID.Bytes()
for i, fs := range p.FedServers {
// Find and remove
// Check first byte first.
chainID := fs.GetChainID().Bytes()
if scid[20] == chainID[20] {
comp := bytes.Compare(scid, chainID)
if comp == 0 {
return true, i
}
}
}
return false, len(p.FedServers)
}
// Returns true and the index of this server, or false and the insertion point for this server
func (p *ProcessList) GetAuditServerIndexHash(identityChainID interfaces.IHash) (bool, int) {
if p == nil {
return false, 0
}
scid := identityChainID.Bytes()
for i, fs := range p.AuditServers {
// Find and remove
if bytes.Compare(scid, fs.GetChainID().Bytes()) == 0 {
return true, i
}
}
return false, len(p.AuditServers)
}
// This function will be replaced by a calculation from the Matryoshka hashes from the servers
// but for now, we are just going to make it a function of the dbheight.
// serverMap[minute][vmIndex] => Index of the Federated Server responsible for that minute
func MakeMap(numberFedServers int, dbheight uint32) (serverMap [10][64]int) {
if numberFedServers > 0 {
indx := int(dbheight*131) % numberFedServers
for i := 0; i < 10; i++ {
indx = (indx + 1) % numberFedServers
for j := 0; j < numberFedServers; j++ {
serverMap[i][j] = indx
indx = (indx + 1) % numberFedServers
}
}
}
return
}
func (p *ProcessList) MakeMap() {
//p.State.LogPrintf("executeMsg", "MakeMap(%d)", p.DBHeight)
p.ServerMap = MakeMap(len(p.FedServers), p.DBHeight)
//p.State.LogPrintf("executeMsg", "%s", p.PrintMap())
}
// This function will be replaced by a calculation from the Matryoshka hashes from the servers
// but for now, we are just going to make it a function of the dbheight.
func (p *ProcessList) PrintMap() string {
n := len(p.FedServers)
prt := fmt.Sprintf("===PrintMapStart=== %d\n", p.DBHeight)
prt = prt + fmt.Sprintf("dddd %s minute map: s.LeaderVMIndex %d pl.dbht %d s.dbht %d s.EOM %v\ndddd ",
p.State.FactomNodeName, p.State.LeaderVMIndex, p.DBHeight, p.State.LLeaderHeight, p.State.EOM)
for i := 0; i < n; i++ {
prt = fmt.Sprintf("%s%3d", prt, i)
}
prt = prt + "\ndddd "
for i := 0; i < 10; i++ {
prt = fmt.Sprintf("%s%3d ", prt, i)
for j := 0; j < len(p.FedServers); j++ {
prt = fmt.Sprintf("%s%2d ", prt, p.ServerMap[i][j])
}
prt = prt + "\ndddd "
}
prt = prt + fmt.Sprintf("\n===PrintMapEnd=== %d\n", p.DBHeight)
return prt
}
// Will set the starting fed/aud list for delta comparison at the end of the block
func (p *ProcessList) SetStartingAuthoritySet() {
copyServer := func(os interfaces.IServer) interfaces.IServer {
s := new(Server)
s.ChainID = os.GetChainID()
s.Name = os.GetName()
s.Online = os.IsOnline()
s.Replace = os.LeaderToReplace()
return s
}
p.StartingFedServers = []interfaces.IServer{}
p.StartingAuditServers = []interfaces.IServer{}
for _, f := range p.FedServers {
p.StartingFedServers = append(p.StartingFedServers, copyServer(f))
}
for _, a := range p.AuditServers {
p.StartingAuditServers = append(p.StartingAuditServers, copyServer(a))
}
}
// Add the given serverChain to this processlist as a Federated Server, and return
// the server index number of the added server
func (p *ProcessList) AddFedServer(identityChainID interfaces.IHash) int {
p.SortFedServers()
found, i := p.GetFedServerIndexHash(identityChainID)
if found {
//p.State.AddStatus(fmt.Sprintf("ProcessList.AddFedServer Server already there %x at height %d", identityChainID.Bytes()[2:6], p.DBHeight))
return i
}
if i < 0 {
return i
}
// If an audit server, it gets promoted
auditFound, _ := p.GetAuditServerIndexHash(identityChainID)
if auditFound {
//p.State.AddStatus(fmt.Sprintf("ProcessList.AddFedServer Server %x was an audit server at height %d", identityChainID.Bytes()[2:6], p.DBHeight))
p.RemoveAuditServerHash(identityChainID)
}
// Debugging a panic
if p.State == nil {
fmt.Println("-- Debug p.State", p.State)
}
if p.State.EFactory == nil {
fmt.Println("-- Debug p.State.EFactory", p.State.EFactory, p.State.FactomNodeName)
}
// Inform Elections of a new leader
InMsg := p.State.EFactory.NewAddLeaderInternal(
p.State.FactomNodeName,
p.DBHeight,
identityChainID,
)
p.State.electionsQueue.Enqueue(InMsg)
p.FedServers = append(p.FedServers, nil)
copy(p.FedServers[i+1:], p.FedServers[i:])
p.FedServers[i] = &Server{ChainID: identityChainID, Online: true}
//p.State.AddStatus(fmt.Sprintf("ProcessList.AddFedServer Server added at index %d %x at height %d", i, identityChainID.Bytes()[2:6], p.DBHeight))
p.MakeMap()
//p.State.AddStatus(fmt.Sprintf("PROCESSLIST.AddFedServer: Adding Server %x", identityChainID.Bytes()[3:8]))
return i
}
// Add the given serverChain to this processlist as an Audit Server, and return
// the server index number of the added server
func (p *ProcessList) AddAuditServer(identityChainID interfaces.IHash) int {
found, i := p.GetAuditServerIndexHash(identityChainID)
if found {
//p.State.AddStatus(fmt.Sprintf("ProcessList.AddAuditServer Server already there %x at height %d", identityChainID.Bytes()[2:6], p.DBHeight))
return i
}
// If a fed server, demote
fedFound, _ := p.GetFedServerIndexHash(identityChainID)
if fedFound {
//p.State.AddStatus(fmt.Sprintf("ProcessList.AddAuditServer Server %x was a fed server at height %d", identityChainID.Bytes()[2:6], p.DBHeight))
p.RemoveFedServerHash(identityChainID)
}
InMsg := p.State.EFactory.NewAddAuditInternal(
p.State.FactomNodeName,
p.DBHeight,
identityChainID,
)
p.State.electionsQueue.Enqueue(InMsg)
p.AuditServers = append(p.AuditServers, nil)
copy(p.AuditServers[i+1:], p.AuditServers[i:])
p.AuditServers[i] = &Server{ChainID: identityChainID, Online: true}
//p.State.AddStatus(fmt.Sprintf("PROCESSLIST.AddAuditServer Server added at index %d %x at height %d", i, identityChainID.Bytes()[2:6], p.DBHeight))
return i
}
// Remove the given serverChain from this processlist's Federated Servers
func (p *ProcessList) RemoveFedServerHash(identityChainID interfaces.IHash) {
found, i := p.GetFedServerIndexHash(identityChainID)
if !found {
p.RemoveAuditServerHash(identityChainID) // SOF-201
return
}
InMsg := p.State.EFactory.NewRemoveLeaderInternal(
p.State.FactomNodeName,
p.DBHeight,
identityChainID,
)
p.State.electionsQueue.Enqueue(InMsg)
p.FedServers = append(p.FedServers[:i], p.FedServers[i+1:]...)
p.MakeMap()
//p.State.AddStatus(fmt.Sprintf("PROCESSLIST.RemoveFedServer: Removing Server %x", identityChainID.Bytes()[3:8]))
}
// Remove the given serverChain from this processlist's Audit Servers
func (p *ProcessList) RemoveAuditServerHash(identityChainID interfaces.IHash) {
found, i := p.GetAuditServerIndexHash(identityChainID)
if !found {
return
}
InMsg := p.State.EFactory.NewRemoveAuditInternal(
p.State.FactomNodeName,
p.DBHeight,
identityChainID,
)
p.State.electionsQueue.Enqueue(InMsg)
p.AuditServers = append(p.AuditServers[:i], p.AuditServers[i+1:]...)
//p.State.AddStatus(fmt.Sprintf("PROCESSLIST.RemoveAuditServer: Removing Audit Server %x", identityChainID.Bytes()[3:8]))
}
func (p *ProcessList) CountFederatedServersAddedAndRemoved() (added int, removed int) {
startingFeds := p.StartingFedServers
var containsServerChainID func([]interfaces.IServer, interfaces.IHash) bool
containsServerChainID = func(haystack []interfaces.IServer, needle interfaces.IHash) bool {
for _, hay := range haystack {
if needle.IsSameAs(hay.GetChainID()) {
return true
}
}
return false
}
for _, adminEntry := range p.AdminBlock.GetABEntries() {
switch adminEntry.Type() {
case constants.TYPE_ADD_FED_SERVER:
// Double check the entry is a real add fed server message
ad, ok := adminEntry.(*adminBlock.AddFederatedServer)
if !ok {
continue
}
if containsServerChainID(startingFeds, ad.IdentityChainID) {
removed--
} else {
added++
}
case constants.TYPE_REMOVE_FED_SERVER:
// Double check the entry is a real remove fed server message
ad, ok := adminEntry.(*adminBlock.RemoveFederatedServer)
if !ok {
continue
}
// See if this was one of our starting leaders
if containsServerChainID(startingFeds, ad.IdentityChainID) {
removed++
}
case constants.TYPE_ADD_AUDIT_SERVER:
// This could be a demotion, so we need to reduce the fedcount
ad, ok := adminEntry.(*adminBlock.AddAuditServer)
if !ok {
continue
}
// See if this was one of our starting leaders
if containsServerChainID(startingFeds, ad.IdentityChainID) {
removed++
}
}
}
return added, removed
}
// Given a server index, return the last Ack
func (p *ProcessList) GetAckAt(vmIndex int, height int) *messages.Ack {
vm := p.VMs[vmIndex]
if height < 0 || height >= len(vm.ListAck) {
return nil
}
return vm.ListAck[height]
}
func (p *ProcessList) AddOldMsgs(m interfaces.IMsg) {
p.oldmsgslock.Lock()
defer p.oldmsgslock.Unlock()
p.OldMsgs[m.GetHash().Fixed()] = m
}
func (p *ProcessList) GetOldAck(key interfaces.IHash) interfaces.IMsg {
if p == nil {
return nil
}
p.oldackslock.Lock()
defer p.oldackslock.Unlock()
a, ok := p.OldAcks[key.Fixed()]
if !ok {
return nil
}
return a
}
func (p *ProcessList) AddNewEBlocks(key interfaces.IHash, value interfaces.IEntryBlock) {
p.neweblockslock.Lock()
defer p.neweblockslock.Unlock()
p.NewEBlocks[key.Fixed()] = value
}
func (p *ProcessList) GetNewEBlocks(key interfaces.IHash) interfaces.IEntryBlock {
p.neweblockslock.Lock()
defer p.neweblockslock.Unlock()
return p.NewEBlocks[key.Fixed()]
}
func (p *ProcessList) AddNewEntry(key interfaces.IHash, value interfaces.IEntry) {
p.NewEntriesMutex.Lock()
defer p.NewEntriesMutex.Unlock()
p.NewEntries[key.Fixed()] = value
}
func (p *ProcessList) ResetDiffSigTally() {
p.diffSigTally = 0
}
func (p *ProcessList) IncrementDiffSigTally() {
p.diffSigTally++
}
func (p *ProcessList) CheckDiffSigTally() bool {
// If the majority of VMs' signatures do not match our
// saved block, we discard that block from our database.
if p.diffSigTally > 0 && p.diffSigTally > (len(p.FedServers)/2) {
fmt.Println("**** dbstate diffSigTally", p.diffSigTally, "len/2", len(p.FedServers)/2)
// p.State.DB.Delete([]byte(databaseOverlay.DIRECTORYBLOCK), p.State.ProcessLists.Lists[0].DirectoryBlock.GetKeyMR().Bytes())
return false
}
return true
}
func (p *ProcessList) TrimVMList(h uint32, vmIndex int) {
height := int(h)
if len(p.VMs[vmIndex].List) > height {
if p.VMs[vmIndex].Height > height {
// We can not trim beyond the highest processed message.
p.State.LogPrintf("processList", "Attempt to trim higher than processed list=%d p=%d h=%d", len(p.VMs[vmIndex].List), p.VMs[vmIndex].Height, height)
return
}
p.State.LogPrintf("processList", "TrimVMList() %d/%d/%d, trimmed %d", p.DBHeight, vmIndex, height, len(p.VMs[vmIndex].List)-height)
p.VMs[vmIndex].List = p.VMs[vmIndex].List[:height]
if len(p.VMs[vmIndex].ListAck) > height { // Also trim ListAck
p.VMs[vmIndex].ListAck = p.VMs[vmIndex].ListAck[:height]
}
if p.State.DebugExec() {
if p.VMs[vmIndex].HighestNil > height {
p.VMs[vmIndex].HighestNil = height // Drag report limit back
}
}
} else {
p.State.LogPrintf("processList", "Attempt to trim higher than list list=%d p=%d h=%d", len(p.VMs[vmIndex].List), p.VMs[vmIndex].Height, height)
}
}
func (p *ProcessList) GetDBHeight() uint32 {
return p.DBHeight
}
type foo struct {
Syncing, DBSig, EOM, DBSigDone, EOMDone, EOMmax, EOMmin, DBSigMax, DBSigMin bool
}
var decodeMap map[foo]string = map[foo]string{
//grep "Unexpected state" FNode0*process.txt | awk ' {print substr($0,index($0,"0x"));}' | sort -u
//0x043 {true true false false false false true false false}
//0x04b {true true false true false false true false false}
//0x0cb {true true false true false false true true false}
//0x10d {true false true true false false false false true}
//0x11d {true false true true true false false false true}
//0x12d {true false true true false true false false true}
//0x13d {true false true true true true false false true}
//0x140 {false false false false false false true false true}
//0x148 {false false false true false false true false true}
//0x14d {true false true true false false true false true}
foo{true, true, false, false, false, false, true, false, false}: "Syncing DBSig", //0x043
foo{true, true, false, true, false, false, true, false, false}: "Syncing DBSig Done", //0x04b
foo{true, true, false, true, false, false, true, true, false}: "Syncing DBSig Stop", //0x0cb
foo{true, false, true, true, false, false, false, false, true}: "Syncing EOM", //0x10d
foo{true, false, true, true, true, false, false, false, true}: "Syncing EOM Done", //0x11d
foo{true, false, true, true, false, true, false, false, true}: "Syncing EOM Stop", //0x12d
foo{true, false, true, true, true, true, false, false, true}: "Syncing EOM Done", //0x13d
foo{false, false, false, false, false, false, true, false, true}: "Normal (Begining of time)", //0x140
foo{false, false, false, true, false, false, true, false, true}: "Normal", //0x148
foo{true, false, true, true, false, false, true, false, true}: "Syncing EOM Start", //0x14d
// old code used to also hit these states some of which are problematic as they allow both DBSIG and EOM concurrently
//foo{true, true, false, true, false, false, true, true, false}: "Stop Syncing DBSig", //0x0cb
//foo{true, false, false, false, false, false, false, false, false}: "Sync Only??", //0x100 ***
//foo{true, false, true, true, false, false, false, false, true}: "Syncing EOM ... ", //0x10d
//foo{true, true, false, false, false, false, true, false, true}: "Start Syncing DBSig", //0x143
//foo{true, false, true, false, false, false, true, false, true}: "Syncing EOM Start (DBSIG !Done)", //0x145 ***
//foo{true, false, true, true, true, false, true, false, true}: "Syncing EOM ... ", //0x15d
}
func (p *ProcessList) decodeState(Syncing bool, DBSig bool, EOM bool, DBSigDone bool, EOMDone bool, FedServers int, EOMProcessed int, DBSigProcessed int) string {
p.stringCnt++
if p.stringCnt%1000 == 0 {
return ""
}
if EOMProcessed > FedServers || EOMProcessed < 0 {
p.State.LogPrintf("process", "Unexpected EOMProcessed %v of %v", EOMProcessed, FedServers)
}
if DBSigProcessed > FedServers || DBSigProcessed < 0 {
p.State.LogPrintf("process", "Unexpected DBSigProcessed %v of %v", DBSigProcessed, FedServers)
}
var x foo = foo{Syncing, DBSig, EOM, DBSigDone, EOMDone,
EOMProcessed == FedServers, EOMProcessed == 0, DBSigProcessed == FedServers, DBSigProcessed == 0}
xx := 0
var z []bool = []bool{Syncing, DBSig, EOM, DBSigDone, EOMDone, EOMProcessed == FedServers, EOMProcessed == 0, DBSigProcessed == FedServers, DBSigProcessed == 0}
for i, b := range z {
if b {
xx = xx | (1 << uint(i))
}
}
s, ok := decodeMap[x]
if !ok {
p.State.LogPrintf("process", "Unexpected 0x%03x %v", xx, x)
s = "Unknown"
}
// divide ProcessListProcessCnt by a big number to make it not change the status string very often
return fmt.Sprintf("SyncingStatus: %d-:-%d 0x%03x %25s EOM/DBSIG %02d/%02d of %02d -- %d",
p.State.LeaderPL.DBHeight, p.State.CurrentMinute, xx, s, EOMProcessed, DBSigProcessed, FedServers, p.State.ProcessListProcessCnt/5000)
}
var extraDebug bool = false
func (p *ProcessList) processVM(vm *VM) (progress bool) {
i := vm.VmIndex
s := p.State
now := s.GetTimestamp()
if vm.Height == len(vm.List) {
// if we are syncing EOMs ...
if s.EOM || s.DBSig {
// means that we are missing an EOM or DBSig
vm.ReportMissing(vm.Height, 0) // ask for it now
}
// If we haven't heard anything from a VM in 2 seconds, ask for a message at the last-known height
if now.GetTimeMilli()-vm.ProcessTime.GetTimeMilli() > int64(s.FactomSecond()/time.Millisecond) {
vm.ReportMissing(vm.Height, int64(2*s.FactomSecond()/time.Millisecond)) // Ask for one past the end of the list
}
return false
}
if ValidationDebug {
s.LogPrintf("process", "start process for VM %d/%d/%d", vm.p.DBHeight, vm.VmIndex, vm.Height)
defer s.LogPrintf("process", "stop process for VM %d/%d/%d", vm.p.DBHeight, vm.VmIndex, vm.Height)
}
defer p.UpdateStatus(s) // update the status after each VM
progress = false // assume we will not process any messages
for j := vm.Height; j < len(vm.List); j++ {
s.ProcessListProcessCnt++
if vm.List[j] == nil {
vm.ReportMissing(j, 0)
return progress
}
if extraDebug {
s.LogMessage("process", fmt.Sprintf("Consider %v/%v/%v", p.DBHeight, i, j), vm.List[j])
}
ack := vm.ListAck[j]
msg := vm.List[j]
//todo: Need to re-validate the signatures of the message and ACK at this point to make sure they are current federated servers
var expectedSerialHash interfaces.IHash
var err error
if vm.Height == 0 {
expectedSerialHash = ack.SerialHash
} else {
prevAck := vm.ListAck[j-1]
expectedSerialHash, err = primitives.CreateHash(prevAck.MessageHash, ack.MessageHash)
if err != nil {
p.RemoveFromPL(vm, j, "Error making hash "+err.Error())
return progress
}
s.LogPrintf("serialhashs", "%d/%d/%d\t%x %x", ack.DBHeight, ack.VMIndex, ack.Height, ack.SerialHash.Fixed(), expectedSerialHash.Fixed())
// compare the SerialHash of this acknowledgement with the
// expected serialHash (generated above)
if !expectedSerialHash.IsSameAs(ack.SerialHash) {
s.LogMessage("process", "prev msg", prevAck)
s.LogMessage("process", "this msg", ack)
s.LogPrintf("process", "expected %x", expectedSerialHash.Bytes())
s.LogPrintf("process", "ack %x", ack.SerialHash.Bytes())
p.RemoveFromPL(vm, j, "ack hash mismatch")
return progress
}
}
// Try an process this message
now = p.State.GetTimestamp()
vm.ProcessTime = now
msgRepeatHashFixed := msg.GetRepeatHash().Fixed()
msgHashFixed := msg.GetMsgHash().Fixed()
if _, valid := s.Replay.Valid(constants.INTERNAL_REPLAY, msgRepeatHashFixed, msg.GetTimestamp(), now); !valid {
p.RemoveFromPL(vm, j, "INTERNAL_REPLAY")
return progress
}
valid := msg.Validate(p.State)
if valid == -1 {
p.RemoveFromPL(vm, j, "invalid msg")
return progress
}
if msg.Process(p.DBHeight, s) { // Try and Process this entry
p.State.LogMessage("processList", fmt.Sprintf("done %v/%v/%v", p.DBHeight, i, j), msg)
vm.heartBeat = 0
vm.Height = j + 1 // Don't process it again if the process worked.
s.LogMessage("process", fmt.Sprintf("done %v/%v/%v", p.DBHeight, i, j), msg)
//s.LogPrintf("process", "thisAck %x", thisAck.SerialHash.Bytes())
progress = true
// We have already tested and found m to be a new message. We now record its hashes so later, we
// can detect that it has been recorded. We don't care about the results of IsTSValidAndUpdateState at this point.
// block network replay too since we have already seen this message there is not need to see it again
s.Replay.IsTSValidAndUpdateState(constants.INTERNAL_REPLAY|constants.NETWORK_REPLAY, msgRepeatHashFixed, msg.GetTimestamp(), now)
s.Replay.IsTSValidAndUpdateState(constants.INTERNAL_REPLAY, msgHashFixed, msg.GetTimestamp(), now)
delete(s.Acks, msgHashFixed)
//delete(s.Holding, msgHashFixed)
// REVIEW: does this leave msg in dependent holding?
s.DeleteFromHolding(msgHashFixed, msg, "msg.Process done")
} else {
s.LogMessage("process", fmt.Sprintf("retry %v/%v/%v", p.DBHeight, i, j), msg)
return progress
}
}
return progress
} // processVM(){...}
func (p *ProcessList) RemoveFromPL(vm *VM, j int, reason string) {
p.State.LogMessage("process", fmt.Sprintf("nil out message %v/%v/%v, %s", p.DBHeight, vm.VmIndex, j, reason), vm.List[j]) //todo: revisit message
p.State.rejects <- MsgPair{vm.ListAck[j], vm.List[j]} // Notify MMR framework that we rejected this message
vm.List[j] = nil
if vm.HighestNil > j {
vm.HighestNil = j // Drag report limit back
}
vm.ReportMissing(j, 0)
}
func (p *ProcessList) UpdateStatus(s *State) {
x := p.decodeState(s.Syncing, s.DBSig, s.EOM, s.DBSigDone, s.EOMDone,
len(s.LeaderPL.FedServers), s.EOMProcessed, s.DBSigProcessed)
// Compute a syncing s string and report if it has changed
if x != "" && s.SyncingState[s.SyncingStateCurrent] != x {
s.LogPrintf("processStatus", x)
s.SyncingStateCurrent = (s.SyncingStateCurrent + 1) % len(s.SyncingState)
s.SyncingState[s.SyncingStateCurrent] = x
}
}
// Process messages and update our state.
func (p *ProcessList) Process(s *State) (progress bool) {
dbht := s.GetHighestSavedBlk()
if dbht >= p.DBHeight {
//s.AddStatus(fmt.Sprintf("ProcessList.Process: VM Height is %d and Saved height is %d", dbht, s.GetHighestSavedBlk()))
return false
}
// So here is the deal. After we have processed a block, we have to allow the DirectoryBlockSignatures a chance to save
// to disk. Then we can insist on having the entry blocks.
diff := (int(s.LLeaderHeight)*10 + int(s.CurrentMinute)) - int(s.EntryDBHeightComplete)*10
// Keep in mind, the process list is processing at a height one greater than the database. 1 is caught up. 2 is one behind.
// Until the first couple signatures are processed, we will be 2 behind.
//TODO: Why is this in the execution per message per VM when it's global to the processlist -- clay
if s.WaitForEntries {
s.LogPrintf("processList", "s.WaitForEntries %d-:-%d [%d] > %d + 2", p.DBHeight, s.CurrentMinute, s.EntryDBHeightComplete)
return progress // Don't process further in this list, go to the next.
}
// If the block is not yet being written to disk (22 minutes old...)
// dif >2 means the second pass sync is not complete so don't process yet.
// this prevent you from becoming a leader when you don't have complete identities
if diff > 22 {
s.LogPrintf("process", "Waiting on saving")
s.LogPrintf("EntrySync", "Waiting on saving EntryDBHeightComplete = %d", s.EntryDBHeightComplete)
// If we don't have the Entry Blocks (or we haven't processed the signatures) we can't do more.
// p.State.AddStatus(fmt.Sprintf("Can't do more: dbht: %d vm: %d vm-height: %d Entry Height: %d", p.DBHeight, i, j, s.EntryDBHeightComplete))
if extraDebug {
p.State.LogPrintf("process", "Waiting on saving blocks to progress complete %d processing %d-:-%d", s.EntryDBHeightComplete, s.LLeaderHeight, s.CurrentMinute)
}
return false
}
progress = false // assume we will not get any work done.
s.PLProcessHeight = p.DBHeight
// Loop thru the VM processing as much as we can
for i := 0; i < len(p.FedServers); i++ {
vm := p.VMs[i]
p := p.processVM(vm)
progress = p || progress
}
return progress
}
func (p *ProcessList) AddToProcessList(s *State, ack *messages.Ack, m interfaces.IMsg) {
//s.LogMessage("processList", "Message:", m) // also logged with the ack
s.LogMessage("processList", "Ack:", ack)
if p == nil {
s.LogPrintf("processList", "Drop no process list to add to")