Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add GetConfiguration using yaml w/ test #118

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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, "./") {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

strings package has HasPrefix function

you can use string.HasPrefix(rpath,"./") | string.HasPrefix(rpath,"../")

it can prevent path like ..../a/b/c or like /a/b/./c

abs, err := filepath.Abs(rpath)
if err != nil {
return rpath, err
}
return abs, nil
}

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

plz comment using english :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

strings package has HasPrefix function

detail explain is in upper comment

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops. not upper but lower


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
12 changes: 10 additions & 2 deletions cmd/swim.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import (
"os"
"time"

"github.com/DE-labtory/swim/cmd/common"
"github.com/DE-labtory/swim/conf"

"github.com/urfave/cli"
)

Expand Down Expand Up @@ -34,8 +37,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
}
68 changes: 68 additions & 0 deletions conf/configuration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package conf_test

import (
"io/ioutil"
"os"
"testing"

"github.com/DE-labtory/swim"

"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