github.com/jpetazzo/etcd@v0.2.1-0.20140113055439-97f1363afac5/tests/functional/kill_leader_test.go (about)

     1  package test
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strconv"
     7  	"strings"
     8  	"testing"
     9  	"time"
    10  )
    11  
    12  // This test will kill the current leader and wait for the etcd cluster to elect a new leader for 200 times.
    13  // It will print out the election time and the average election time.
    14  func TestKillLeader(t *testing.T) {
    15  	procAttr := new(os.ProcAttr)
    16  	procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
    17  
    18  	clusterSize := 5
    19  	argGroup, etcds, err := CreateCluster(clusterSize, procAttr, false)
    20  	if err != nil {
    21  		t.Fatal("cannot create cluster")
    22  	}
    23  	defer DestroyCluster(etcds)
    24  
    25  	stop := make(chan bool)
    26  	leaderChan := make(chan string, 1)
    27  	all := make(chan bool, 1)
    28  
    29  	time.Sleep(time.Second)
    30  
    31  	go Monitor(clusterSize, 1, leaderChan, all, stop)
    32  
    33  	var totalTime time.Duration
    34  
    35  	leader := "http://127.0.0.1:7001"
    36  
    37  	for i := 0; i < clusterSize; i++ {
    38  		fmt.Println("leader is ", leader)
    39  		port, _ := strconv.Atoi(strings.Split(leader, ":")[2])
    40  		num := port - 7001
    41  		fmt.Println("kill server ", num)
    42  		etcds[num].Kill()
    43  		etcds[num].Release()
    44  
    45  		start := time.Now()
    46  		for {
    47  			newLeader := <-leaderChan
    48  			if newLeader != leader {
    49  				leader = newLeader
    50  				break
    51  			}
    52  		}
    53  		take := time.Now().Sub(start)
    54  
    55  		totalTime += take
    56  		avgTime := totalTime / (time.Duration)(i+1)
    57  		fmt.Println("Total time:", totalTime, "; Avg time:", avgTime)
    58  
    59  		etcds[num], err = os.StartProcess(EtcdBinPath, argGroup[num], procAttr)
    60  	}
    61  	stop <- true
    62  }