[VOL-2735]Durations in voltha-lib-go should be specified as type time.Duration not int
Change-Id: I782e44fe1dc041b9eb54fd837950d2176e18fe42
diff --git a/pkg/config/configmanager.go b/pkg/config/configmanager.go
index 0dafc7a..c0915af 100644
--- a/pkg/config/configmanager.go
+++ b/pkg/config/configmanager.go
@@ -22,6 +22,7 @@
"github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore"
"github.com/opencord/voltha-lib-go/v3/pkg/log"
"strings"
+ "time"
)
const (
@@ -92,7 +93,7 @@
kvStoreEventChan chan *kvstore.Event
}
-func NewConfigManager(kvClient kvstore.Client, kvStoreType, kvStoreHost string, kvStorePort, kvStoreTimeout int) *ConfigManager {
+func NewConfigManager(kvClient kvstore.Client, kvStoreType, kvStoreHost string, kvStorePort int, kvStoreTimeout time.Duration) *ConfigManager {
return &ConfigManager{
KvStoreConfigPrefix: defaultkvStoreConfigPath,
diff --git a/pkg/db/backend.go b/pkg/db/backend.go
index 4d29195..20bacad 100644
--- a/pkg/db/backend.go
+++ b/pkg/db/backend.go
@@ -40,7 +40,7 @@
StoreType string
Host string
Port int
- Timeout int
+ Timeout time.Duration
PathPrefix string
alive bool // Is this backend connection alive?
liveness chan bool // channel to post alive state
@@ -49,7 +49,7 @@
}
// NewBackend creates a new instance of a Backend structure
-func NewBackend(storeType string, host string, port int, timeout int, pathPrefix string) *Backend {
+func NewBackend(storeType string, host string, port int, timeout time.Duration, pathPrefix string) *Backend {
var err error
b := &Backend{
@@ -75,7 +75,7 @@
return b
}
-func (b *Backend) newClient(address string, timeout int) (kvstore.Client, error) {
+func (b *Backend) newClient(address string, timeout time.Duration) (kvstore.Client, error) {
switch b.StoreType {
case "consul":
return kvstore.NewConsulClient(address, timeout)
diff --git a/pkg/db/backend_test.go b/pkg/db/backend_test.go
index 865d239..f96ed19 100644
--- a/pkg/db/backend_test.go
+++ b/pkg/db/backend_test.go
@@ -31,7 +31,7 @@
const (
embedEtcdServerHost = "localhost"
- defaultTimeout = 1
+ defaultTimeout = 1 * time.Second
defaultPathPrefix = "Prefix"
)
@@ -119,7 +119,7 @@
// Liveness Check against Embedded Etcd Server should return alive state
func TestPerformLivenessCheck_EmbeddedEtcdServer(t *testing.T) {
backend := provisionBackendWithEmbeddedEtcdServer(t)
- ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
alive := backend.PerformLivenessCheck(ctx)
assert.True(t, alive)
@@ -128,7 +128,7 @@
// Liveness Check against Dummy Etcd Server should return not-alive state
func TestPerformLivenessCheck_DummyEtcdServer(t *testing.T) {
backend := provisionBackendWithDummyEtcdServer(t)
- ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
alive := backend.PerformLivenessCheck(ctx)
assert.False(t, alive)
@@ -148,7 +148,7 @@
// Enabling Liveness Channel after First Liveness Check
func TestEnableLivenessChannel_EmbeddedEtcdServer_AfterLivenessCheck(t *testing.T) {
backend := provisionBackendWithEmbeddedEtcdServer(t)
- ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
backend.PerformLivenessCheck(ctx)
diff --git a/pkg/db/kvstore/client.go b/pkg/db/kvstore/client.go
index b9cb1ee..158e626 100644
--- a/pkg/db/kvstore/client.go
+++ b/pkg/db/kvstore/client.go
@@ -15,11 +15,14 @@
*/
package kvstore
-import "context"
+import (
+ "context"
+ "time"
+)
const (
// Default timeout in seconds when making a kvstore request
- defaultKVGetTimeout = 5
+ defaultKVGetTimeout = 5 * time.Second
// Maximum channel buffer between publisher/subscriber goroutines
maxClientChannelBufferSize = 10
)
@@ -77,12 +80,12 @@
Get(ctx context.Context, key string) (*KVPair, error)
Put(ctx context.Context, key string, value interface{}) error
Delete(ctx context.Context, key string) error
- Reserve(ctx context.Context, key string, value interface{}, ttl int64) (interface{}, error)
+ Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error)
ReleaseReservation(ctx context.Context, key string) error
ReleaseAllReservations(ctx context.Context) error
RenewReservation(ctx context.Context, key string) error
Watch(ctx context.Context, key string, withPrefix bool) chan *Event
- AcquireLock(ctx context.Context, lockName string, timeout int) error
+ AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error
ReleaseLock(lockName string) error
IsConnectionUp(ctx context.Context) bool // timeout in second
CloseWatch(key string, ch chan *Event)
diff --git a/pkg/db/kvstore/consulclient.go b/pkg/db/kvstore/consulclient.go
index bdf2d10..d2544dd 100644
--- a/pkg/db/kvstore/consulclient.go
+++ b/pkg/db/kvstore/consulclient.go
@@ -44,13 +44,11 @@
}
// NewConsulClient returns a new client for the Consul KV store
-func NewConsulClient(addr string, timeout int) (*ConsulClient, error) {
-
- duration := GetDuration(timeout)
+func NewConsulClient(addr string, timeout time.Duration) (*ConsulClient, error) {
config := consulapi.DefaultConfig()
config.Address = addr
- config.WaitTime = duration
+ config.WaitTime = timeout
consul, err := consulapi.NewClient(config)
if err != nil {
logger.Error(err)
@@ -76,7 +74,9 @@
deadline, _ := ctx.Deadline()
kv := c.consul.KV()
var queryOptions consulapi.QueryOptions
- queryOptions.WaitTime = GetDuration(deadline.Second())
+ // Substract current time from deadline to get the waitTime duration
+ queryOptions.WaitTime = time.Until(deadline)
+
// For now we ignore meta data
kvps, _, err := kv.List(key, &queryOptions)
if err != nil {
@@ -97,7 +97,9 @@
deadline, _ := ctx.Deadline()
kv := c.consul.KV()
var queryOptions consulapi.QueryOptions
- queryOptions.WaitTime = GetDuration(deadline.Second())
+ // Substract current time from deadline to get the waitTime duration
+ queryOptions.WaitTime = time.Until(deadline)
+
// For now we ignore meta data
kvp, _, err := kv.Get(key, &queryOptions)
if err != nil {
@@ -166,11 +168,11 @@
c.session = nil
}
-func (c *ConsulClient) createSession(ttl int64, retries int) (*consulapi.Session, string, error) {
+func (c *ConsulClient) createSession(ttl time.Duration, retries int) (*consulapi.Session, string, error) {
session := c.consul.Session()
entry := &consulapi.SessionEntry{
Behavior: consulapi.SessionBehaviorDelete,
- TTL: "10s", // strconv.FormatInt(ttl, 10) + "s", // disable ttl
+ TTL: ttl.String(),
}
for {
@@ -218,7 +220,7 @@
// defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself.
// If the key is acquired then the value returned will be the value passed in. If the key is already acquired
// then the value assigned to that key will be returned.
-func (c *ConsulClient) Reserve(ctx context.Context, key string, value interface{}, ttl int64) (interface{}, error) {
+func (c *ConsulClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
// Validate that we can create a byte array from the value as consul API expects a byte array
var val []byte
@@ -432,10 +434,9 @@
logger.Debugw("start-watching-channel", log.Fields{"key": key, "channel": ch})
defer c.CloseWatch(key, ch)
- duration := GetDuration(defaultKVGetTimeout)
kv := c.consul.KV()
var queryOptions consulapi.QueryOptions
- queryOptions.WaitTime = duration
+ queryOptions.WaitTime = defaultKVGetTimeout
// Get the existing value, if any
previousKVPair, meta, err := kv.Get(key, &queryOptions)
@@ -503,7 +504,7 @@
}
}
-func (c *ConsulClient) AcquireLock(ctx context.Context, lockName string, timeout int) error {
+func (c *ConsulClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
return nil
}
diff --git a/pkg/db/kvstore/etcdclient.go b/pkg/db/kvstore/etcdclient.go
index 90158bc..8d4a462 100644
--- a/pkg/db/kvstore/etcdclient.go
+++ b/pkg/db/kvstore/etcdclient.go
@@ -20,6 +20,7 @@
"errors"
"fmt"
"sync"
+ "time"
"github.com/opencord/voltha-lib-go/v3/pkg/log"
v3Client "go.etcd.io/etcd/clientv3"
@@ -39,13 +40,12 @@
}
// NewEtcdClient returns a new client for the Etcd KV store
-func NewEtcdClient(addr string, timeout int, level log.LogLevel) (*EtcdClient, error) {
- duration := GetDuration(timeout)
+func NewEtcdClient(addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) {
logconfig := log.ConstructZapConfig(log.JSON, level, log.Fields{})
c, err := v3Client.New(v3Client.Config{
Endpoints: []string{addr},
- DialTimeout: duration,
+ DialTimeout: timeout,
LogConfig: &logconfig,
})
if err != nil {
@@ -162,7 +162,7 @@
// defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself.
// If the key is acquired then the value returned will be the value passed in. If the key is already acquired
// then the value assigned to that key will be returned.
-func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl int64) (interface{}, error) {
+func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
// Validate that we can convert value to a string as etcd API expects a string
var val string
var er error
@@ -170,7 +170,7 @@
return nil, fmt.Errorf("unexpected-type%T", value)
}
- resp, err := c.ectdAPI.Grant(ctx, ttl)
+ resp, err := c.ectdAPI.Grant(ctx, int64(ttl.Seconds()))
if err != nil {
logger.Error(err)
return nil, err
@@ -457,7 +457,7 @@
return lock, session
}
-func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout int) error {
+func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx))
mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName)
if err := mu.Lock(context.Background()); err != nil {
diff --git a/pkg/db/kvstore/kvutils.go b/pkg/db/kvstore/kvutils.go
index cf9a95c..64e7d30 100644
--- a/pkg/db/kvstore/kvutils.go
+++ b/pkg/db/kvstore/kvutils.go
@@ -15,19 +15,7 @@
*/
package kvstore
-import (
- "fmt"
- "time"
-)
-
-// GetDuration converts a timeout value from int to duration. If the timeout value is
-// either not set of -ve then we default KV timeout (configurable) is used.
-func GetDuration(timeout int) time.Duration {
- if timeout <= 0 {
- return defaultKVGetTimeout * time.Second
- }
- return time.Duration(timeout) * time.Second
-}
+import "fmt"
// ToString converts an interface value to a string. The interface should either be of
// a string type or []byte. Otherwise, an error is returned.
diff --git a/pkg/db/kvstore/kvutils_test.go b/pkg/db/kvstore/kvutils_test.go
index 86c4369..98c96c9 100644
--- a/pkg/db/kvstore/kvutils_test.go
+++ b/pkg/db/kvstore/kvutils_test.go
@@ -18,30 +18,8 @@
import (
"github.com/stretchr/testify/assert"
"testing"
- "time"
)
-func TestDurationWithNegativeTimeout(t *testing.T) {
- actualResult := GetDuration(-1)
- var expectedResult = defaultKVGetTimeout * time.Second
-
- assert.Equal(t, expectedResult, actualResult)
-}
-
-func TestDurationWithZeroTimeout(t *testing.T) {
- actualResult := GetDuration(0)
- var expectedResult = defaultKVGetTimeout * time.Second
-
- assert.Equal(t, expectedResult, actualResult)
-}
-
-func TestDurationWithTimeout(t *testing.T) {
- actualResult := GetDuration(10)
- var expectedResult = time.Duration(10) * time.Second
-
- assert.Equal(t, expectedResult, actualResult)
-}
-
func TestToStringWithString(t *testing.T) {
actualResult, _ := ToString("myString")
var expectedResult = "myString"
diff --git a/pkg/kafka/endpoint_manager_test.go b/pkg/kafka/endpoint_manager_test.go
index 20b330a..de7d028 100644
--- a/pkg/kafka/endpoint_manager_test.go
+++ b/pkg/kafka/endpoint_manager_test.go
@@ -62,7 +62,7 @@
configName := "voltha-lib.kafka.ep.test"
storageDir := "voltha-lib.kafka.ep.etcd"
logLevel := "error"
- timeout := time.Duration(5 * time.Second)
+ timeout := 5 * time.Second
kvClientPort, err := freeport.GetFreePort()
if err != nil {
@@ -77,7 +77,7 @@
return status.Error(codes.Internal, "Embedded server failed to start")
}
- ep.backend = db.NewBackend("etcd", "127.0.0.1", kvClientPort, int(timeout.Milliseconds()), "service/voltha")
+ ep.backend = db.NewBackend("etcd", "127.0.0.1", kvClientPort, timeout, "service/voltha")
return nil
}
diff --git a/pkg/mocks/etcd/etcd_server_test.go b/pkg/mocks/etcd/etcd_server_test.go
index 6178568..43c7a42 100644
--- a/pkg/mocks/etcd/etcd_server_test.go
+++ b/pkg/mocks/etcd/etcd_server_test.go
@@ -25,6 +25,7 @@
"github.com/stretchr/testify/assert"
"os"
"testing"
+ "time"
)
var etcdServer *EtcdServer
@@ -44,7 +45,7 @@
logger.Fatal("Embedded server failed to start")
}
clientAddr := fmt.Sprintf("localhost:%d", clientPort)
- client, err = kvstore.NewEtcdClient(clientAddr, 10, log.WarnLevel)
+ client, err = kvstore.NewEtcdClient(clientAddr, 10*time.Second, log.WarnLevel)
if err != nil || client == nil {
etcdServer.Stop()
logger.Fatal("Failed to create an Etcd client")
diff --git a/pkg/ponresourcemanager/ponresourcemanager.go b/pkg/ponresourcemanager/ponresourcemanager.go
index 2d388a5..4cccb84 100755
--- a/pkg/ponresourcemanager/ponresourcemanager.go
+++ b/pkg/ponresourcemanager/ponresourcemanager.go
@@ -23,6 +23,7 @@
"errors"
"fmt"
"strconv"
+ "time"
bitmap "github.com/boljen/go-bitmap"
"github.com/opencord/voltha-lib-go/v3/pkg/db"
@@ -124,7 +125,7 @@
POOL = "pool"
NUM_OF_PON_INTF = 16
- KVSTORE_RETRY_TIMEOUT = 5
+ KVSTORE_RETRY_TIMEOUT = 5 * time.Second
//Path on the KV store for storing reserved gem ports
//Format: reserved_gemport_ids
RESERVED_GEMPORT_IDS_PATH = "reserved_gemport_ids"
@@ -155,7 +156,7 @@
Globalorlocal string
}
-func newKVClient(storeType string, address string, timeout int) (kvstore.Client, error) {
+func newKVClient(storeType string, address string, timeout time.Duration) (kvstore.Client, error) {
logger.Infow("kv-store-type", log.Fields{"store": storeType})
switch storeType {
case "consul":
diff --git a/pkg/ponresourcemanager/ponresourcemanager_test.go b/pkg/ponresourcemanager/ponresourcemanager_test.go
index 11c0072..c2a651e 100644
--- a/pkg/ponresourcemanager/ponresourcemanager_test.go
+++ b/pkg/ponresourcemanager/ponresourcemanager_test.go
@@ -26,6 +26,7 @@
"github.com/stretchr/testify/assert"
"strings"
"testing"
+ "time"
)
const (
@@ -88,7 +89,7 @@
}
// Reserve mock function implementation for KVClient
-func (kvclient *MockResKVClient) Reserve(ctx context.Context, key string, value interface{}, ttl int64) (interface{}, error) {
+func (kvclient *MockResKVClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
return nil, errors.New("key didn't find")
}
@@ -113,7 +114,7 @@
}
// AcquireLock mock function implementation for KVClient
-func (kvclient *MockResKVClient) AcquireLock(ctx context.Context, lockName string, timeout int) error {
+func (kvclient *MockResKVClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
return nil
}
diff --git a/pkg/techprofile/config.go b/pkg/techprofile/config.go
index 4af2bd5..8a304be 100644
--- a/pkg/techprofile/config.go
+++ b/pkg/techprofile/config.go
@@ -17,6 +17,7 @@
import (
"github.com/opencord/voltha-lib-go/v3/pkg/db"
+ "time"
)
// tech profile default constants
@@ -28,7 +29,7 @@
defaultGemportsCount = 1
defaultPbits = "0b11111111"
- defaultKVStoreTimeout = 5 //in seconds
+ defaultKVStoreTimeout = 5 * time.Second //in seconds
// Tech profile path prefix in kv store
defaultKVPathPrefix = "service/voltha/technology_profiles"
@@ -78,7 +79,7 @@
KVStoreHost string
KVStorePort int
KVStoreType string
- KVStoreTimeout int
+ KVStoreTimeout time.Duration
KVBackend *db.Backend
TPKVPathPrefix string
TPFileKVPath string
diff --git a/pkg/techprofile/tech_profile.go b/pkg/techprofile/tech_profile.go
index 316bd57..cbbe835 100644
--- a/pkg/techprofile/tech_profile.go
+++ b/pkg/techprofile/tech_profile.go
@@ -23,6 +23,7 @@
"fmt"
"regexp"
"strconv"
+ "time"
"github.com/opencord/voltha-lib-go/v3/pkg/db"
@@ -268,7 +269,7 @@
*/
}
-func newKVClient(storeType string, address string, timeout int) (kvstore.Client, error) {
+func newKVClient(storeType string, address string, timeout time.Duration) (kvstore.Client, error) {
logger.Infow("kv-store", log.Fields{"storeType": storeType, "address": address})
switch storeType {