Skip to content

Commit

Permalink
feat: add GetConfiguration using yaml w/ test
Browse files Browse the repository at this point in the history
  • Loading branch information
zeroFruit committed Apr 3, 2019
1 parent 1b9b94c commit a6e85df
Show file tree
Hide file tree
Showing 15 changed files with 315 additions and 53 deletions.
6 changes: 3 additions & 3 deletions awareness.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ import (
type Awareness struct {
sync.RWMutex

// max is the upper threshold for the factor that increase the timeout value
// (the score will be constrained from 0 <= score < max)
// Max is the upper threshold for the factor that increase the timeout value
// (the score will be constrained from 0 <= score < Max)
max int

// score is the current awareness score. Lower values are healthier and
Expand All @@ -58,7 +58,7 @@ func (a *Awareness) GetHealthScore() int {
}

// ApplyDelta with given delta applies it to the score in thread-safe manner
// score must be bound from 0 to max value
// score must be bound from 0 to Max value
func (a *Awareness) ApplyDelta(delta int) {

a.RLock()
Expand Down
6 changes: 3 additions & 3 deletions awareness_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,17 @@ func TestNewAwareness(t *testing.T) {
max int
score int
}{
"max-3": {
"Max-3": {
input: 3,
max: 3,
score: 0,
},
"max-5": {
"Max-5": {
input: 5,
max: 5,
score: 0,
},
"max-10": {
"Max-10": {
input: 10,
max: 10,
score: 0,
Expand Down
2 changes: 1 addition & 1 deletion awareness_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func TestAwareness_ApplyDelta(t *testing.T) {
delta: -3,
score: 0,
},
"max score": {
"Max score": {
max: 5,
delta: 10,
score: 4,
Expand Down
58 changes: 58 additions & 0 deletions cmd/common/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package common

import (
"os/user"
"path"
"path/filepath"
"strings"
)

func RelativeToAbsolutePath(rpath string) (string, error) {
if rpath == "" {
return rpath, nil
}

absolutePath := ""

// case ./ ../
if strings.Contains(rpath, "./") {
abs, err := filepath.Abs(rpath)
if err != nil {
return rpath, err
}
return abs, nil
}

// case ~/
if strings.Contains(rpath, "~") {
i := strings.Index(rpath, "~") // 처음 나온 ~만 반환

if i > -1 {
pathRemain := rpath[i+1:]
usr, err := user.Current()
if err != nil {
return rpath, err
}
return path.Join(usr.HomeDir, pathRemain), nil

} else {
return rpath, nil
}
}

if string(rpath[0]) == "/" {
return rpath, nil
}

if string(rpath[0]) != "." && string(rpath[0]) != "/" {
currentPath, err := filepath.Abs(".")
if err != nil {
return rpath, err
}

return path.Join(currentPath, rpath), nil
}

return absolutePath, nil

}
86 changes: 86 additions & 0 deletions cmd/common/util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package common_test

import (
"io/ioutil"
"os"
"os/user"
"path"
"path/filepath"
"testing"

"github.com/DE-labtory/swim/cmd/common"
"github.com/stretchr/testify/assert"
)

func TestRelativeToAbsolutePath(t *testing.T) {

testfile1 := "./util.go"
testabsresult1, err := filepath.Abs(testfile1)
assert.NoError(t, err)
testabs1, err := common.RelativeToAbsolutePath(testfile1)

assert.NoError(t, err)
assert.Equal(t, testabs1, testabsresult1)

testfile2 := "../README.md"
testabsresult2, err := filepath.Abs(testfile2)
assert.NoError(t, err)

testabs2, err := common.RelativeToAbsolutePath(testfile2)

assert.NoError(t, err)
assert.Equal(t, testabs2, testabsresult2)

// 남의 홈패스에 뭐가있는지 알길이 없으니 하나 만들었다 지움
usr, err := user.Current()
assert.NoError(t, err)

testfile3 := usr.HomeDir + "/test.txt"

_, err = os.Stat(usr.HomeDir)
if os.IsNotExist(err) {
file, err := os.Create(testfile3)
assert.NoError(t, err)
defer file.Close()
}

err = ioutil.WriteFile(testfile3, []byte("test"), os.ModePerm)
assert.NoError(t, err)

testfile4 := "~/test.txt"

testabs3, err := common.RelativeToAbsolutePath(testfile4)
assert.NoError(t, err)
assert.Equal(t, testfile3, testabs3)

err = os.Remove(testfile3)
assert.NoError(t, err)
}

func TestRelativeToAbsolutePath_WhenGivenPathIsAbsolute(t *testing.T) {
sshPath := "/iAmRoot"

absPath, err := common.RelativeToAbsolutePath(sshPath)

assert.NoError(t, err)
assert.Equal(t, sshPath, absPath)
}

func TestRelativeToAbsolutePath_WhenGivenPathWithOnlyName(t *testing.T) {
sshPath := "test-dir"

absPath, err := common.RelativeToAbsolutePath(sshPath)
currentPath, _ := filepath.Abs(".")

assert.NoError(t, err)
assert.Equal(t, path.Join(currentPath, sshPath), absPath)
}

func TestRelativeToAbsolutePath_WhenGivenPathIsEmpty(t *testing.T) {
sshPath := ""

absPath, err := common.RelativeToAbsolutePath(sshPath)

assert.Equal(t, nil, err)
assert.Equal(t, "", absPath)
}
4 changes: 3 additions & 1 deletion cmd/subcommands.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cmd

import "github.com/urfave/cli"
import (
"github.com/urfave/cli"
)

var startCmd = cli.Command{
Name: "start",
Expand Down
11 changes: 9 additions & 2 deletions cmd/swim.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cmd

import (
"github.com/DE-labtory/swim/cmd/common"
"github.com/DE-labtory/swim/conf"
"log"
"os"
"time"
Expand Down Expand Up @@ -34,8 +36,13 @@ func main() {
app.Commands = append(app.Commands, Cmd()...)

app.Before = func(c *cli.Context) error {
// config
// debug
if configPath := c.String("config"); configPath != "" {
absPath, err := common.RelativeToAbsolutePath(configPath)
if err != nil {
return err
}
conf.SetConfigPath(absPath)
}
return nil
}
err := app.Run(os.Args)
Expand Down
44 changes: 44 additions & 0 deletions conf/configuration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package conf

import (
"fmt"
"os"
"sync"

"github.com/DE-labtory/swim"

"github.com/spf13/viper"
)

var confPath = os.Getenv("GOPATH") + "/src/github.com/DE-labtory/swim/conf/config.yaml"

type Configuration struct {
SWIMConfig swim.Config
SuspicionConfig swim.SuspicionConfig
MessageEndpointConfig swim.MessageEndpointConfig
Member swim.Member
}

// config is instance of SWIM configuration
var config = &Configuration{}

var once = sync.Once{}

func SetConfigPath(abspath string) {
confPath = abspath
}

func GetConfiguration() *Configuration {
once.Do(func() {
viper.SetConfigFile(confPath)
if err := viper.ReadInConfig(); err != nil {
panic(fmt.Sprintf("cannot read config from %s", confPath))
}
err := viper.Unmarshal(&config)
if err != nil {
panic("error in read config")
}
})

return config
}
67 changes: 67 additions & 0 deletions conf/configuration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package conf_test

import (
"github.com/DE-labtory/swim"
"io/ioutil"
"os"
"testing"

"github.com/DE-labtory/swim/conf"
"github.com/stretchr/testify/assert"
)

func TestGetConfiguration(t *testing.T) {
path := os.Getenv("GOPATH") + "/src/github.com/DE-labtory/swim/conf"
confFileName := "/config-test.yaml"
defer os.Remove(path + confFileName)

if _, err := os.Stat(path); os.IsNotExist(err) {
os.Mkdir(path, os.ModePerm)
}

// please leave this whitespace as space not tab
ConfJson := []byte(`
swimconfig:
maxlocalcount: 2
maxnsacounter: 8
t: 3000
acktimeout: 3000
k: 2
bindaddress: 127.0.0.1
bindport: 50000
suspicionconfig:
k: 2
min: 3000
max: 10000
messageendpointconfig:
encryptionenabled: false
sendtimeout: 5000
callbackcollectinterval: 7000
member:
id:
id: "hello_id"
`)

err := ioutil.WriteFile(path+confFileName, ConfJson, os.ModePerm)
assert.NoError(t, err)

conf.SetConfigPath(path + confFileName)
config := conf.GetConfiguration()
assert.Equal(t, config.SWIMConfig.MaxlocalCount, 2)
assert.Equal(t, config.SWIMConfig.MaxNsaCounter, 8)
assert.Equal(t, config.SWIMConfig.T, 3000)
assert.Equal(t, config.SWIMConfig.AckTimeOut, 3000)
assert.Equal(t, config.SWIMConfig.K, 2)
assert.Equal(t, config.SWIMConfig.BindAddress, "127.0.0.1")
assert.Equal(t, config.SWIMConfig.BindPort, 50000)

assert.Equal(t, config.SuspicionConfig.K, 2)
assert.Equal(t, config.SuspicionConfig.Min.Nanoseconds(), int64(3000))
assert.Equal(t, config.SuspicionConfig.Max.Nanoseconds(), int64(10000))

assert.Equal(t, config.MessageEndpointConfig.EncryptionEnabled, false)
assert.Equal(t, config.MessageEndpointConfig.SendTimeout.Nanoseconds(), int64(5000))
assert.Equal(t, config.MessageEndpointConfig.CallbackCollectInterval.Nanoseconds(), int64(7000))

assert.Equal(t, config.Member.ID, swim.MemberID{ID: "hello_id"})
}
20 changes: 10 additions & 10 deletions member_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,15 @@ func (s Status) toInt() int32 {
}

type SuspicionConfig struct {
// k is the maximum number of independent confirmation's we'd like to see
// this value is for making timer to drive @min value
k int
// K is the maximum number of independent confirmation's we'd like to see
// this value is for making timer to drive @Min value
K int

// min is the minimum timer value
min time.Duration
// Min is the minimum timer value
Min time.Duration

// max is the maximum timer value
max time.Duration
// Max is the maximum timer value
Max time.Duration
}

type MemberID struct {
Expand Down Expand Up @@ -147,7 +147,7 @@ func NewMemberMap(config *SuspicionConfig) *MemberMap {
}
}

// Select K random member (length of returning member can be lower than k).
// Select K random member (length of returning member can be lower than K).
func (m *MemberMap) SelectKRandomMemberID(k int) []Member {

m.lock.Lock()
Expand Down Expand Up @@ -235,7 +235,7 @@ func (m *MemberMap) suspectWhenDead() (bool, error) {
func (m *MemberMap) suspectWhenAlive(member *Member, confirmer string, incarnation uint32) (bool, error) {
config := m.suspicionConfig

suspicion, err := NewSuspicion(MemberID{confirmer}, config.k, config.min, config.max, getSuspicionCallback(m, member))
suspicion, err := NewSuspicion(MemberID{confirmer}, config.K, config.Min, config.Max, getSuspicionCallback(m, member))
if err != nil {
return false, ErrCreatingSuspicion
}
Expand All @@ -251,7 +251,7 @@ func (m *MemberMap) suspectWhenSuspect(member *Member, confirmer string, incarna
config := m.suspicionConfig

if member.Suspicion == nil {
suspicion, err := NewSuspicion(MemberID{confirmer}, config.k, config.min, config.max, getSuspicionCallback(m, member))
suspicion, err := NewSuspicion(MemberID{confirmer}, config.K, config.Min, config.Max, getSuspicionCallback(m, member))
if err != nil {
return false, ErrCreatingSuspicion
}
Expand Down
Loading

0 comments on commit a6e85df

Please sign in to comment.