forked from openvswitch/ovs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
raft.c
4349 lines (3889 loc) · 144 KB
/
raft.c
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 (c) 2017, 2018 Nicira, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <config.h>
#include "raft.h"
#include "raft-private.h"
#include <errno.h>
#include <unistd.h>
#include "hash.h"
#include "jsonrpc.h"
#include "lockfile.h"
#include "openvswitch/dynamic-string.h"
#include "openvswitch/hmap.h"
#include "openvswitch/json.h"
#include "openvswitch/list.h"
#include "openvswitch/poll-loop.h"
#include "openvswitch/vlog.h"
#include "ovsdb-error.h"
#include "ovsdb-parser.h"
#include "ovsdb/log.h"
#include "raft-rpc.h"
#include "random.h"
#include "socket-util.h"
#include "stream.h"
#include "timeval.h"
#include "unicode.h"
#include "unixctl.h"
#include "util.h"
#include "uuid.h"
VLOG_DEFINE_THIS_MODULE(raft);
/* Roles for a Raft server:
*
* - Followers: Servers in touch with the current leader.
*
* - Candidate: Servers unaware of a current leader and seeking election to
* leader.
*
* - Leader: Handles all client requests. At most one at a time.
*
* In normal operation there is exactly one leader and all of the other servers
* are followers. */
enum raft_role {
RAFT_FOLLOWER,
RAFT_CANDIDATE,
RAFT_LEADER
};
/* A connection between this Raft server and another one. */
struct raft_conn {
struct ovs_list list_node; /* In struct raft's 'conns' list. */
struct jsonrpc_session *js; /* JSON-RPC connection. */
struct uuid sid; /* This server's unique ID. */
char *nickname; /* Short name for use in log messages. */
bool incoming; /* True if incoming, false if outgoing. */
unsigned int js_seqno; /* Seqno for noticing (re)connections. */
};
static void raft_conn_close(struct raft_conn *);
/* A "command", that is, a request to append an entry to the log.
*
* The Raft specification only allows clients to issue commands to the leader.
* With this implementation, clients may issue a command on any server, which
* then relays the command to the leader if necessary.
*
* This structure is thus used in three cases:
*
* 1. We are the leader and the command was issued to us directly.
*
* 2. We are a follower and relayed the command to the leader.
*
* 3. We are the leader and a follower relayed the command to us.
*/
struct raft_command {
/* All cases. */
struct hmap_node hmap_node; /* In struct raft's 'commands' hmap. */
unsigned int n_refs; /* Reference count. */
enum raft_command_status status; /* Execution status. */
/* Case 1 only. */
uint64_t index; /* Index in log (0 if being relayed). */
/* Cases 2 and 3. */
struct uuid eid; /* Entry ID of result. */
/* Case 2 only. */
long long int timestamp; /* Issue or last ping time, for expiration. */
/* Case 3 only. */
struct uuid sid; /* The follower (otherwise UUID_ZERO). */
};
static void raft_command_complete(struct raft *, struct raft_command *,
enum raft_command_status);
static void raft_complete_all_commands(struct raft *,
enum raft_command_status);
/* Type of deferred action, see struct raft_waiter. */
enum raft_waiter_type {
RAFT_W_ENTRY,
RAFT_W_TERM,
RAFT_W_RPC,
};
/* An action deferred until a log write commits to disk. */
struct raft_waiter {
struct ovs_list list_node;
uint64_t commit_ticket;
enum raft_waiter_type type;
union {
/* RAFT_W_ENTRY.
*
* Waits for a RAFT_REC_ENTRY write to our local log to commit. Upon
* completion, updates 'log_synced' to indicate that the new log entry
* or entries are committed and, if we are leader, also updates our
* local 'match_index'. */
struct {
uint64_t index;
} entry;
/* RAFT_W_TERM.
*
* Waits for a RAFT_REC_TERM or RAFT_REC_VOTE record write to commit.
* Upon completion, updates 'synced_term' and 'synced_vote', which
* triggers sending RPCs deferred by the uncommitted 'term' and
* 'vote'. */
struct {
uint64_t term;
struct uuid vote;
} term;
/* RAFT_W_RPC.
*
* Sometimes, sending an RPC to a peer must be delayed until an entry,
* a term, or a vote mentioned in the RPC is synced to disk. This
* waiter keeps a copy of such an RPC until the previous waiters have
* committed. */
union raft_rpc *rpc;
};
};
static struct raft_waiter *raft_waiter_create(struct raft *,
enum raft_waiter_type,
bool start_commit);
static void raft_waiters_destroy(struct raft *);
/* The Raft state machine. */
struct raft {
struct hmap_node hmap_node; /* In 'all_rafts'. */
struct ovsdb_log *log;
/* Persistent derived state.
*
* This must be updated on stable storage before responding to RPCs. It can be
* derived from the header, snapshot, and log in 'log'. */
struct uuid cid; /* Cluster ID (immutable for the cluster). */
struct uuid sid; /* Server ID (immutable for the server). */
char *local_address; /* Local address (immutable for the server). */
char *local_nickname; /* Used for local server in log messages. */
char *name; /* Schema name (immutable for the cluster). */
/* Contains "struct raft_server"s and represents the server configuration
* most recently added to 'log'. */
struct hmap servers;
/* Persistent state on all servers.
*
* Must be updated on stable storage before responding to RPCs. */
/* Current term and the vote for that term. These might be on the way to
* disk now. */
uint64_t term; /* Initialized to 0 and only increases. */
struct uuid vote; /* All-zeros if no vote yet in 'term'. */
/* The term and vote that have been synced to disk. */
uint64_t synced_term;
struct uuid synced_vote;
/* The log.
*
* A log entry with index 1 never really exists; the initial snapshot for a
* Raft is considered to include this index. The first real log entry has
* index 2.
*
* A new Raft instance contains an empty log: log_start=2, log_end=2.
* Over time, the log grows: log_start=2, log_end=N.
* At some point, the server takes a snapshot: log_start=N, log_end=N.
* The log continues to grow: log_start=N, log_end=N+1...
*
* Must be updated on stable storage before responding to RPCs. */
struct raft_entry *entries; /* Log entry i is in log[i - log_start]. */
uint64_t log_start; /* Index of first entry in log. */
uint64_t log_end; /* Index of last entry in log, plus 1. */
uint64_t log_synced; /* Index of last synced entry. */
size_t allocated_log; /* Allocated entries in 'log'. */
/* Snapshot state (see Figure 5.1)
*
* This is the state of the cluster as of the last discarded log entry,
* that is, at log index 'log_start - 1' (called prevIndex in Figure 5.1).
* Only committed log entries can be included in a snapshot. */
struct raft_entry snap;
/* Volatile state.
*
* The snapshot is always committed, but the rest of the log might not be yet.
* 'last_applied' tracks what entries have been passed to the client. If the
* client hasn't yet read the latest snapshot, then even the snapshot isn't
* applied yet. Thus, the invariants are different for these members:
*
* log_start - 2 <= last_applied <= commit_index < log_end.
* log_start - 1 <= commit_index < log_end.
*/
enum raft_role role; /* Current role. */
uint64_t commit_index; /* Max log index known to be committed. */
uint64_t last_applied; /* Max log index applied to state machine. */
struct uuid leader_sid; /* Server ID of leader (zero, if unknown). */
/* Followers and candidates only. */
#define ELECTION_BASE_MSEC 1024
#define ELECTION_RANGE_MSEC 1024
long long int election_base; /* Time of last heartbeat from leader. */
long long int election_timeout; /* Time at which we start an election. */
/* Used for joining a cluster. */
bool joining; /* Attempting to join the cluster? */
struct sset remote_addresses; /* Addresses to try to find other servers. */
long long int join_timeout; /* Time to re-send add server request. */
/* Used for leaving a cluster. */
bool leaving; /* True if we are leaving the cluster. */
bool left; /* True if we have finished leaving. */
long long int leave_timeout; /* Time to re-send remove server request. */
/* Failure. */
bool failed; /* True if unrecoverable error has occurred. */
/* File synchronization. */
struct ovs_list waiters; /* Contains "struct raft_waiter"s. */
/* Network connections. */
struct pstream *listener; /* For connections from other Raft servers. */
long long int listen_backoff; /* For retrying creating 'listener'. */
struct ovs_list conns; /* Contains struct raft_conns. */
/* Leaders only. Reinitialized after becoming leader. */
struct hmap add_servers; /* Contains "struct raft_server"s to add. */
struct raft_server *remove_server; /* Server being removed. */
struct hmap commands; /* Contains "struct raft_command"s. */
#define PING_TIME_MSEC (ELECTION_BASE_MSEC / 3)
long long int ping_timeout; /* Time at which to send a heartbeat */
/* Candidates only. Reinitialized at start of election. */
int n_votes; /* Number of votes for me. */
};
/* All Raft structures. */
static struct hmap all_rafts = HMAP_INITIALIZER(&all_rafts);
static void raft_init(void);
static struct ovsdb_error *raft_read_header(struct raft *)
OVS_WARN_UNUSED_RESULT;
static void raft_send_execute_command_reply(struct raft *,
const struct uuid *sid,
const struct uuid *eid,
enum raft_command_status,
uint64_t commit_index);
static void raft_update_our_match_index(struct raft *, uint64_t min_index);
static void raft_send_remove_server_reply__(
struct raft *, const struct uuid *target_sid,
const struct uuid *requester_sid, struct unixctl_conn *requester_conn,
bool success, const char *comment);
static void raft_server_init_leader(struct raft *, struct raft_server *);
static bool raft_rpc_is_heartbeat(const union raft_rpc *);
static bool raft_is_rpc_synced(const struct raft *, const union raft_rpc *);
static void raft_handle_rpc(struct raft *, const union raft_rpc *);
static bool raft_send(struct raft *, const union raft_rpc *);
static bool raft_send__(struct raft *, const union raft_rpc *,
struct raft_conn *);
static void raft_send_append_request(struct raft *,
struct raft_server *, unsigned int n,
const char *comment);
static void raft_become_leader(struct raft *);
static void raft_become_follower(struct raft *);
static void raft_reset_timer(struct raft *);
static void raft_send_heartbeats(struct raft *);
static void raft_start_election(struct raft *, bool leadership_transfer);
static bool raft_truncate(struct raft *, uint64_t new_end);
static void raft_get_servers_from_log(struct raft *, enum vlog_level);
static bool raft_handle_write_error(struct raft *, struct ovsdb_error *);
static void raft_run_reconfigure(struct raft *);
static struct raft_server *
raft_find_server(const struct raft *raft, const struct uuid *sid)
{
return raft_server_find(&raft->servers, sid);
}
static char *
raft_make_address_passive(const char *address_)
{
if (!strncmp(address_, "unix:", 5)) {
return xasprintf("p%s", address_);
} else {
char *address = xstrdup(address_);
char *host, *port;
inet_parse_host_port_tokens(strchr(address, ':') + 1, &host, &port);
struct ds paddr = DS_EMPTY_INITIALIZER;
ds_put_format(&paddr, "p%.3s:%s:", address, port);
if (strchr(host, ':')) {
ds_put_format(&paddr, "[%s]", host);
} else {
ds_put_cstr(&paddr, host);
}
free(address);
return ds_steal_cstr(&paddr);
}
}
static struct raft *
raft_alloc(void)
{
raft_init();
struct raft *raft = xzalloc(sizeof *raft);
hmap_node_nullify(&raft->hmap_node);
hmap_init(&raft->servers);
raft->log_start = raft->log_end = 1;
raft->role = RAFT_FOLLOWER;
sset_init(&raft->remote_addresses);
raft->join_timeout = LLONG_MAX;
ovs_list_init(&raft->waiters);
raft->listen_backoff = LLONG_MIN;
ovs_list_init(&raft->conns);
hmap_init(&raft->add_servers);
hmap_init(&raft->commands);
raft->ping_timeout = time_msec() + PING_TIME_MSEC;
raft_reset_timer(raft);
return raft;
}
/* Creates an on-disk file that represents a new Raft cluster and initializes
* it to consist of a single server, the one on which this function is called.
*
* Creates the local copy of the cluster's log in 'file_name', which must not
* already exist. Gives it the name 'name', which should be the database
* schema name and which is used only to match up this database with the server
* added to the cluster later if the cluster ID is unavailable.
*
* The new server is located at 'local_address', which must take one of the
* forms "tcp:IP:PORT" or "ssl:IP:PORT", where IP is an IPv4 address or a
* square bracket enclosed IPv6 address and PORT is a TCP port number.
*
* This only creates the on-disk file. Use raft_open() to start operating the
* new server.
*
* Returns null if successful, otherwise an ovsdb_error describing the
* problem. */
struct ovsdb_error * OVS_WARN_UNUSED_RESULT
raft_create_cluster(const char *file_name, const char *name,
const char *local_address, const struct json *data)
{
/* Parse and verify validity of the local address. */
struct ovsdb_error *error = raft_address_validate(local_address);
if (error) {
return error;
}
/* Create log file. */
struct ovsdb_log *log;
error = ovsdb_log_open(file_name, RAFT_MAGIC, OVSDB_LOG_CREATE_EXCL,
-1, &log);
if (error) {
return error;
}
/* Write log file. */
struct raft_header h = {
.sid = uuid_random(),
.cid = uuid_random(),
.name = xstrdup(name),
.local_address = xstrdup(local_address),
.joining = false,
.remote_addresses = SSET_INITIALIZER(&h.remote_addresses),
.snap_index = 1,
.snap = {
.term = 1,
.data = json_nullable_clone(data),
.eid = uuid_random(),
.servers = json_object_create(),
},
};
shash_add_nocopy(json_object(h.snap.servers),
xasprintf(UUID_FMT, UUID_ARGS(&h.sid)),
json_string_create(local_address));
error = ovsdb_log_write_and_free(log, raft_header_to_json(&h));
raft_header_uninit(&h);
if (!error) {
error = ovsdb_log_commit_block(log);
}
ovsdb_log_close(log);
return error;
}
/* Creates a database file that represents a new server in an existing Raft
* cluster.
*
* Creates the local copy of the cluster's log in 'file_name', which must not
* already exist. Gives it the name 'name', which must be the same name
* passed in to raft_create_cluster() earlier.
*
* 'cid' is optional. If specified, the new server will join only the cluster
* with the given cluster ID.
*
* The new server is located at 'local_address', which must take one of the
* forms "tcp:IP:PORT" or "ssl:IP:PORT", where IP is an IPv4 address or a
* square bracket enclosed IPv6 address and PORT is a TCP port number.
*
* Joining the cluster requires contacting it. Thus, 'remote_addresses'
* specifies the addresses of existing servers in the cluster. One server out
* of the existing cluster is sufficient, as long as that server is reachable
* and not partitioned from the current cluster leader. If multiple servers
* from the cluster are specified, then it is sufficient for any of them to
* meet this criterion.
*
* This only creates the on-disk file and does no network access. Use
* raft_open() to start operating the new server. (Until this happens, the
* new server has not joined the cluster.)
*
* Returns null if successful, otherwise an ovsdb_error describing the
* problem. */
struct ovsdb_error * OVS_WARN_UNUSED_RESULT
raft_join_cluster(const char *file_name,
const char *name, const char *local_address,
const struct sset *remote_addresses,
const struct uuid *cid)
{
ovs_assert(!sset_is_empty(remote_addresses));
/* Parse and verify validity of the addresses. */
struct ovsdb_error *error = raft_address_validate(local_address);
if (error) {
return error;
}
const char *addr;
SSET_FOR_EACH (addr, remote_addresses) {
error = raft_address_validate(addr);
if (error) {
return error;
}
if (!strcmp(addr, local_address)) {
return ovsdb_error(NULL, "remote addresses cannot be the same "
"as the local address");
}
}
/* Verify validity of the cluster ID (if provided). */
if (cid && uuid_is_zero(cid)) {
return ovsdb_error(NULL, "all-zero UUID is not valid cluster ID");
}
/* Create log file. */
struct ovsdb_log *log;
error = ovsdb_log_open(file_name, RAFT_MAGIC, OVSDB_LOG_CREATE_EXCL,
-1, &log);
if (error) {
return error;
}
/* Write log file. */
struct raft_header h = {
.sid = uuid_random(),
.cid = cid ? *cid : UUID_ZERO,
.name = xstrdup(name),
.local_address = xstrdup(local_address),
.joining = true,
/* No snapshot yet. */
};
sset_clone(&h.remote_addresses, remote_addresses);
error = ovsdb_log_write_and_free(log, raft_header_to_json(&h));
raft_header_uninit(&h);
if (!error) {
error = ovsdb_log_commit_block(log);
}
ovsdb_log_close(log);
return error;
}
/* Reads the initial header record from 'log', which must be a Raft clustered
* database log, and populates '*md' with the information read from it. The
* caller must eventually destroy 'md' with raft_metadata_destroy().
*
* On success, returns NULL. On failure, returns an error that the caller must
* eventually destroy and zeros '*md'. */
struct ovsdb_error * OVS_WARN_UNUSED_RESULT
raft_read_metadata(struct ovsdb_log *log, struct raft_metadata *md)
{
struct raft *raft = raft_alloc();
raft->log = log;
struct ovsdb_error *error = raft_read_header(raft);
if (!error) {
md->sid = raft->sid;
md->name = xstrdup(raft->name);
md->local = xstrdup(raft->local_address);
md->cid = raft->cid;
} else {
memset(md, 0, sizeof *md);
}
raft->log = NULL;
raft_close(raft);
return error;
}
/* Frees the metadata in 'md'. */
void
raft_metadata_destroy(struct raft_metadata *md)
{
if (md) {
free(md->name);
free(md->local);
}
}
static const struct raft_entry *
raft_get_entry(const struct raft *raft, uint64_t index)
{
ovs_assert(index >= raft->log_start);
ovs_assert(index < raft->log_end);
return &raft->entries[index - raft->log_start];
}
static uint64_t
raft_get_term(const struct raft *raft, uint64_t index)
{
return (index == raft->log_start - 1
? raft->snap.term
: raft_get_entry(raft, index)->term);
}
static const struct json *
raft_servers_for_index(const struct raft *raft, uint64_t index)
{
ovs_assert(index >= raft->log_start - 1);
ovs_assert(index < raft->log_end);
const struct json *servers = raft->snap.servers;
for (uint64_t i = raft->log_start; i <= index; i++) {
const struct raft_entry *e = raft_get_entry(raft, i);
if (e->servers) {
servers = e->servers;
}
}
return servers;
}
static void
raft_set_servers(struct raft *raft, const struct hmap *new_servers,
enum vlog_level level)
{
struct raft_server *s, *next;
HMAP_FOR_EACH_SAFE (s, next, hmap_node, &raft->servers) {
if (!raft_server_find(new_servers, &s->sid)) {
ovs_assert(s != raft->remove_server);
hmap_remove(&raft->servers, &s->hmap_node);
VLOG(level, "server %s removed from configuration", s->nickname);
raft_server_destroy(s);
}
}
HMAP_FOR_EACH_SAFE (s, next, hmap_node, new_servers) {
if (!raft_find_server(raft, &s->sid)) {
VLOG(level, "server %s added to configuration", s->nickname);
struct raft_server *new
= raft_server_add(&raft->servers, &s->sid, s->address);
raft_server_init_leader(raft, new);
}
}
}
static uint64_t
raft_add_entry(struct raft *raft,
uint64_t term, struct json *data, const struct uuid *eid,
struct json *servers)
{
if (raft->log_end - raft->log_start >= raft->allocated_log) {
raft->entries = x2nrealloc(raft->entries, &raft->allocated_log,
sizeof *raft->entries);
}
uint64_t index = raft->log_end++;
struct raft_entry *entry = &raft->entries[index - raft->log_start];
entry->term = term;
entry->data = data;
entry->eid = eid ? *eid : UUID_ZERO;
entry->servers = servers;
return index;
}
/* Writes a RAFT_REC_ENTRY record for 'term', 'data', 'eid', 'servers' to
* 'raft''s log and returns an error indication. */
static struct ovsdb_error * OVS_WARN_UNUSED_RESULT
raft_write_entry(struct raft *raft, uint64_t term, struct json *data,
const struct uuid *eid, struct json *servers)
{
struct raft_record r = {
.type = RAFT_REC_ENTRY,
.term = term,
.entry = {
.index = raft_add_entry(raft, term, data, eid, servers),
.data = data,
.servers = servers,
.eid = eid ? *eid : UUID_ZERO,
},
};
return ovsdb_log_write_and_free(raft->log, raft_record_to_json(&r));
}
static struct ovsdb_error * OVS_WARN_UNUSED_RESULT
raft_write_state(struct ovsdb_log *log,
uint64_t term, const struct uuid *vote)
{
struct raft_record r = { .term = term };
if (vote && !uuid_is_zero(vote)) {
r.type = RAFT_REC_VOTE;
r.sid = *vote;
} else {
r.type = RAFT_REC_TERM;
}
return ovsdb_log_write_and_free(log, raft_record_to_json(&r));
}
static struct ovsdb_error * OVS_WARN_UNUSED_RESULT
raft_apply_record(struct raft *raft, unsigned long long int rec_idx,
const struct raft_record *r)
{
/* Apply "term", which is present in most kinds of records (and otherwise
* 0).
*
* A Raft leader can replicate entries from previous terms to the other
* servers in the cluster, retaining the original terms on those entries
* (see section 3.6.2 "Committing entries from previous terms" for more
* information), so it's OK for the term in a log record to precede the
* current term. */
if (r->term > raft->term) {
raft->term = raft->synced_term = r->term;
raft->vote = raft->synced_vote = UUID_ZERO;
}
switch (r->type) {
case RAFT_REC_ENTRY:
if (r->entry.index < raft->commit_index) {
return ovsdb_error(NULL, "record %llu attempts to truncate log "
"from %"PRIu64" to %"PRIu64" entries, but "
"commit index is already %"PRIu64,
rec_idx, raft->log_end, r->entry.index,
raft->commit_index);
} else if (r->entry.index > raft->log_end) {
return ovsdb_error(NULL, "record %llu with index %"PRIu64" skips "
"past expected index %"PRIu64,
rec_idx, r->entry.index, raft->log_end);
}
if (r->entry.index < raft->log_end) {
/* This can happen, but it is notable. */
VLOG_DBG("record %llu truncates log from %"PRIu64" to %"PRIu64
" entries", rec_idx, raft->log_end, r->entry.index);
raft_truncate(raft, r->entry.index);
}
uint64_t prev_term = (raft->log_end > raft->log_start
? raft->entries[raft->log_end
- raft->log_start - 1].term
: raft->snap.term);
if (r->term < prev_term) {
return ovsdb_error(NULL, "record %llu with index %"PRIu64" term "
"%"PRIu64" precedes previous entry's term "
"%"PRIu64,
rec_idx, r->entry.index, r->term, prev_term);
}
raft->log_synced = raft_add_entry(
raft, r->term,
json_nullable_clone(r->entry.data), &r->entry.eid,
json_nullable_clone(r->entry.servers));
return NULL;
case RAFT_REC_TERM:
return NULL;
case RAFT_REC_VOTE:
if (r->term < raft->term) {
return ovsdb_error(NULL, "record %llu votes for term %"PRIu64" "
"but current term is %"PRIu64,
rec_idx, r->term, raft->term);
} else if (!uuid_is_zero(&raft->vote)
&& !uuid_equals(&raft->vote, &r->sid)) {
return ovsdb_error(NULL, "record %llu votes for "SID_FMT" in term "
"%"PRIu64" but a previous record for the "
"same term voted for "SID_FMT, rec_idx,
SID_ARGS(&raft->vote), r->term,
SID_ARGS(&r->sid));
} else {
raft->vote = raft->synced_vote = r->sid;
return NULL;
}
break;
case RAFT_REC_NOTE:
if (!strcmp(r->note, "left")) {
return ovsdb_error(NULL, "record %llu indicates server has left "
"the cluster; it cannot be added back (use "
"\"ovsdb-tool join-cluster\" to add a new "
"server)", rec_idx);
}
return NULL;
case RAFT_REC_COMMIT_INDEX:
if (r->commit_index < raft->commit_index) {
return ovsdb_error(NULL, "record %llu regresses commit index "
"from %"PRIu64 " to %"PRIu64,
rec_idx, raft->commit_index, r->commit_index);
} else if (r->commit_index >= raft->log_end) {
return ovsdb_error(NULL, "record %llu advances commit index to "
"%"PRIu64 " but last log index is %"PRIu64,
rec_idx, r->commit_index, raft->log_end - 1);
} else {
raft->commit_index = r->commit_index;
return NULL;
}
break;
case RAFT_REC_LEADER:
/* XXX we could use this to take back leadership for quick restart */
return NULL;
default:
OVS_NOT_REACHED();
}
}
static struct ovsdb_error * OVS_WARN_UNUSED_RESULT
raft_read_header(struct raft *raft)
{
/* Read header record. */
struct json *json;
struct ovsdb_error *error = ovsdb_log_read(raft->log, &json);
if (error || !json) {
/* Report error or end-of-file. */
return error;
}
ovsdb_log_mark_base(raft->log);
struct raft_header h;
error = raft_header_from_json(&h, json);
json_destroy(json);
if (error) {
return error;
}
raft->sid = h.sid;
raft->cid = h.cid;
raft->name = xstrdup(h.name);
raft->local_address = xstrdup(h.local_address);
raft->local_nickname = raft_address_to_nickname(h.local_address, &h.sid);
raft->joining = h.joining;
if (h.joining) {
sset_clone(&raft->remote_addresses, &h.remote_addresses);
} else {
raft_entry_clone(&raft->snap, &h.snap);
raft->log_start = raft->log_end = h.snap_index + 1;
raft->commit_index = h.snap_index;
raft->last_applied = h.snap_index - 1;
}
raft_header_uninit(&h);
return NULL;
}
static struct ovsdb_error * OVS_WARN_UNUSED_RESULT
raft_read_log(struct raft *raft)
{
for (unsigned long long int i = 1; ; i++) {
struct json *json;
struct ovsdb_error *error = ovsdb_log_read(raft->log, &json);
if (!json) {
if (error) {
/* We assume that the error is due to a partial write while
* appending to the file before a crash, so log it and
* continue. */
char *error_string = ovsdb_error_to_string_free(error);
VLOG_WARN("%s", error_string);
free(error_string);
error = NULL;
}
break;
}
struct raft_record r;
error = raft_record_from_json(&r, json);
if (!error) {
error = raft_apply_record(raft, i, &r);
raft_record_uninit(&r);
}
if (error) {
return ovsdb_wrap_error(error, "error reading record %llu from "
"%s log", i, raft->name);
}
}
/* Set the most recent servers. */
raft_get_servers_from_log(raft, VLL_DBG);
return NULL;
}
static void
raft_reset_timer(struct raft *raft)
{
unsigned int duration = (ELECTION_BASE_MSEC
+ random_range(ELECTION_RANGE_MSEC));
raft->election_base = time_msec();
raft->election_timeout = raft->election_base + duration;
}
static void
raft_add_conn(struct raft *raft, struct jsonrpc_session *js,
const struct uuid *sid, bool incoming)
{
struct raft_conn *conn = xzalloc(sizeof *conn);
ovs_list_push_back(&raft->conns, &conn->list_node);
conn->js = js;
if (sid) {
conn->sid = *sid;
}
conn->nickname = raft_address_to_nickname(jsonrpc_session_get_name(js),
&conn->sid);
conn->incoming = incoming;
conn->js_seqno = jsonrpc_session_get_seqno(conn->js);
}
/* Starts the local server in an existing Raft cluster, using the local copy of
* the cluster's log in 'file_name'. Takes ownership of 'log', whether
* successful or not. */
struct ovsdb_error * OVS_WARN_UNUSED_RESULT
raft_open(struct ovsdb_log *log, struct raft **raftp)
{
struct raft *raft = raft_alloc();
raft->log = log;
struct ovsdb_error *error = raft_read_header(raft);
if (error) {
goto error;
}
if (!raft->joining) {
error = raft_read_log(raft);
if (error) {
goto error;
}
/* Find our own server. */
if (!raft_find_server(raft, &raft->sid)) {
error = ovsdb_error(NULL, "server does not belong to cluster");
goto error;
}
/* If there's only one server, start an election right away so that the
* cluster bootstraps quickly. */
if (hmap_count(&raft->servers) == 1) {
raft_start_election(raft, false);
}
} else {
raft->join_timeout = time_msec() + 1000;
}
*raftp = raft;
hmap_insert(&all_rafts, &raft->hmap_node, hash_string(raft->name, 0));
return NULL;
error:
raft_close(raft);
*raftp = NULL;
return error;
}
/* Returns the name of 'raft', which in OVSDB is the database schema name. */
const char *
raft_get_name(const struct raft *raft)
{
return raft->name;
}
/* Returns the cluster ID of 'raft'. If 'raft' has not yet completed joining
* its cluster, then 'cid' will be all-zeros (unless the administrator
* specified a cluster ID running "ovsdb-tool join-cluster").
*
* Each cluster has a unique cluster ID. */
const struct uuid *
raft_get_cid(const struct raft *raft)
{
return &raft->cid;
}
/* Returns the server ID of 'raft'. Each server has a unique server ID. */
const struct uuid *
raft_get_sid(const struct raft *raft)
{
return &raft->sid;
}
/* Returns true if 'raft' has completed joining its cluster, has not left or
* initiated leaving the cluster, does not have failed disk storage, and is
* apparently connected to the leader in a healthy way (or is itself the
* leader).*/
bool
raft_is_connected(const struct raft *raft)
{
return (raft->role != RAFT_CANDIDATE
&& !raft->joining
&& !raft->leaving
&& !raft->left
&& !raft->failed);
}
/* Returns true if 'raft' is the cluster leader. */
bool
raft_is_leader(const struct raft *raft)
{
return raft->role == RAFT_LEADER;
}
/* Returns true if 'raft' is the process of joining its cluster. */
bool
raft_is_joining(const struct raft *raft)
{
return raft->joining;
}
/* Only returns *connected* connections. */
static struct raft_conn *
raft_find_conn_by_sid(struct raft *raft, const struct uuid *sid)
{
if (!uuid_is_zero(sid)) {
struct raft_conn *conn;
LIST_FOR_EACH (conn, list_node, &raft->conns) {
if (uuid_equals(sid, &conn->sid)
&& jsonrpc_session_is_connected(conn->js)) {
return conn;
}
}
}
return NULL;
}
static struct raft_conn *
raft_find_conn_by_address(struct raft *raft, const char *address)
{