diff options
Diffstat (limited to 'internal/quorum/quorum.go')
| -rw-r--r-- | internal/quorum/quorum.go | 61 |
1 files changed, 9 insertions, 52 deletions
diff --git a/internal/quorum/quorum.go b/internal/quorum/quorum.go index 71954f4..d730fed 100644 --- a/internal/quorum/quorum.go +++ b/internal/quorum/quorum.go @@ -2,9 +2,7 @@ package quorum import ( "context" - "fmt" "log" - "os" "sort" "strconv" "strings" @@ -32,8 +30,9 @@ func New(conf config.Config) Quorum { } } -func (quo Quorum) Start(ctx context.Context) <-chan vote.Vote { - ch := make(chan vote.Vote) +func (quo Quorum) Start(ctx context.Context) (<-chan vote.Vote, <-chan string) { + voteCh := make(chan vote.Vote) + scoreCh := make(chan string) interval := time.Second * time.Duration(quo.conf.LoopIntervalS) if vote.Expiry <= interval { @@ -42,7 +41,8 @@ func (quo Quorum) Start(ctx context.Context) <-chan vote.Vote { } go func() { - defer close(ch) + defer close(voteCh) + defer close(scoreCh) var ( myVote vote.Vote @@ -54,25 +54,21 @@ func (quo Quorum) Start(ctx context.Context) <-chan vote.Vote { case <-time.After(interval): myVote, _ = quo.makeMyVote() log.Println("quorum: made my vote:", myVote) - ch <- myVote + voteCh <- myVote case v := <-quo.voteCh: quo.vote(v) if myVote, changed = quo.makeMyVote(); changed { log.Println("quorum: changed my vote:", myVote) - ch <- myVote + voteCh <- myVote + scoreCh <- quo.strs() } case <-ctx.Done(): return } - - if err := quo.persist(changed); err != nil { - log.Println("quorum:", err) - notifyError(quo.conf, err) - } } }() - return ch + return voteCh, scoreCh } func (quo Quorum) Vote(v vote.Vote) { @@ -149,24 +145,6 @@ func (quo *Quorum) strs() string { return sb.String() } -func (quo *Quorum) persist(changed bool) error { - scoresStr := quo.strs() - - if changed { - if err := notify(quo.conf, "GORUM: Quorum changed", scoresStr); err != nil { - return err - } - } - - if _, err := os.Stat(quo.conf.StateDir); os.IsNotExist(err) { - if err := os.MkdirAll(quo.conf.StateDir, 0755); err != nil { - return err - } - } - - return writeFileViaTmp(fmt.Sprintf("%s/%s", quo.conf.StateDir, quo.conf.ScoreFile), scoresStr) -} - func (quo *Quorum) makeMyVote() (vote.Vote, bool) { newVote, err := quo.expireOldVotes() if err != nil { @@ -201,24 +179,3 @@ func (quo Quorum) expireOldVotes() (vote.Vote, error) { return vote.New(quo.conf, live...) } - -// Create tmp file first, and then, once written, rename it. -func writeFileViaTmp(filePath, content string) error { - tmpFilePath := fmt.Sprintf("%s.tmp", filePath) - - fd, err := os.Create(tmpFilePath) - if err != nil { - return err - } - defer fd.Close() - - if _, err := fd.WriteString(content); err != nil { - return err - } - - if err := fd.Sync(); err != nil { - return err - } - - return os.Rename(tmpFilePath, filePath) -} |
