changeset 31:014a4e91df0f

Move tryBecomeMaster logic to Submit() so we can try submitting without starting an election
author Lewin Bormann <lbo@spheniscida.de>
date Fri, 14 Oct 2016 20:58:32 +0200
parents 218d4830661a
children e9b41018f5e4
files consensus.go consensus_impl.go example_http/example.go
diffstat 3 files changed, 25 insertions(+), 12 deletions(-) [+]
line wrap: on
line diff
--- a/consensus.go	Fri Oct 14 20:29:57 2016 +0200
+++ b/consensus.go	Fri Oct 14 20:58:32 2016 +0200
@@ -79,8 +79,16 @@
 	}
 }
 
+// Sends a no-op to the master and returns nil if the master is up and active.
+func (p *Participant) PingMaster() error {
+	return p.Submit([]Change{})
+}
+
 // Submit one change to the state machine
 func (p *Participant) SubmitOne(c Change) error {
+	if p.IsMaster() {
+		return nil
+	}
 	return p.Submit([]Change{c})
 }
 
@@ -99,7 +107,16 @@
 	if p.participantState == state_MASTER {
 		return p.submitAsMaster(c)
 	} else if p.participantState == state_PARTICIPANT_CLEAN || p.participantState == state_PARTICIPANT_PENDING {
-		return p.submitToRemoteMaster(c)
+		err := p.submitToRemoteMaster(c)
+		if err != nil {
+			err = p.tryBecomeMaster()
+
+			if err != nil {
+				return err
+			}
+
+			return p.submitAsMaster(c)
+		}
 	} else if p.participantState == state_CANDIDATE || p.participantState == state_PENDING_MASTER || p.participantState == state_UNJOINED {
 		return NewError(ERR_STATE, "Currently in candidate or unconfirmed-master state; try again later", nil)
 	}
--- a/consensus_impl.go	Fri Oct 14 20:29:57 2016 +0200
+++ b/consensus_impl.go	Fri Oct 14 20:58:32 2016 +0200
@@ -96,17 +96,7 @@
 	// Send to remote master
 	err = masterConn.SubmitRequest(c)
 
-	if err == nil {
-		return nil
-	}
-
-	err = p.tryBecomeMaster()
-
-	if err != nil {
-		return err // We tried everything
-	} else {
-		return p.submitAsMaster(c)
-	}
+	return err
 }
 
 func (p *Participant) tryBecomeMaster() error {
--- a/example_http/example.go	Fri Oct 14 20:29:57 2016 +0200
+++ b/example_http/example.go	Fri Oct 14 20:58:32 2016 +0200
@@ -108,6 +108,12 @@
 	for {
 		time.Sleep(time.Duration(*interval) * time.Second)
 
+		if err := participant.PingMaster(); err != nil {
+			fmt.Println("Master down:", err)
+		} else {
+			fmt.Println("Master is up")
+		}
+
 		err := participant.SubmitOne(Change{t: change_ADD, key: fmt.Sprintf("k%d", i), val: fmt.Sprintf("val%d", i)})
 
 		if err != nil {