github.com/letsencrypt/trillian@v1.1.2-0.20180615153820-ae375a99d36a/docs/storage/commit_log/simelection/election.go (about)

     1  // Copyright 2017 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package simelection simulates a master election.
    16  package simelection
    17  
    18  import "sync"
    19  
    20  // Election is a (flawed) simulated mastership election, which can
    21  // be made to report multiple masters at the same time.
    22  type Election struct {
    23  	mu      sync.RWMutex
    24  	masters []string
    25  }
    26  
    27  // IsMaster indicates whether the given name is master.
    28  func (e *Election) IsMaster(who string) bool {
    29  	e.mu.RLock()
    30  	defer e.mu.RUnlock()
    31  	for _, m := range e.masters {
    32  		if m == who {
    33  			return true
    34  		}
    35  	}
    36  	return false
    37  }
    38  
    39  // Masters returns the current set of masters.  There should be only one, but
    40  // bugs happen...
    41  func (e *Election) Masters() []string {
    42  	e.mu.RLock()
    43  	defer e.mu.RUnlock()
    44  	return e.masters
    45  }
    46  
    47  // SetMaster sets a single master.
    48  func (e *Election) SetMaster(who string) {
    49  	e.mu.Lock()
    50  	defer e.mu.Unlock()
    51  	e.masters = []string{who}
    52  }
    53  
    54  // SetMasters sets multiple masters.
    55  func (e *Election) SetMasters(who []string) {
    56  	e.mu.Lock()
    57  	defer e.mu.Unlock()
    58  	e.masters = who
    59  }