blob: 9b9dec4e9265d88fddefd999350a321973f19b4c [file] [log] [blame]
khenaidooab1f7bd2019-11-14 14:00:27 -05001/*
2 * Copyright 2019-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package mocks
17
18import (
19 "go.etcd.io/etcd/embed"
20 "log"
21 "os"
22 "time"
23)
24
25const (
26 serverStartUpTimeout = 10 * time.Second // Maximum time allowed to wait for the Etcd server to be ready
27 localPersistentStorage = "voltha.embed.etcd"
28)
29
30//EtcdServer represents an embedded Etcd server. It is used for testing only.
31type EtcdServer struct {
32 server *embed.Etcd
33}
34
35//getDefaultCfg specifies the default config
36func getDefaultCfg() *embed.Config {
37 cfg := embed.NewConfig()
38 cfg.Dir = localPersistentStorage
39 cfg.Logger = "zap"
40 cfg.LogLevel = "error"
41 return cfg
42}
43
44//StartEtcdServer creates and starts an embedded Etcd server. A local directory to store data is created for the
45//embedded server lifetime (for the duration of a unit test. The server runs at localhost:2379.
46func StartEtcdServer(cfg *embed.Config) *EtcdServer {
47 // If the server is already running, just return
48 if cfg == nil {
49 cfg = getDefaultCfg()
50 }
51 // Remove the local directory as
52 // a safeguard for the case where a prior test failed
53 if err := os.RemoveAll(localPersistentStorage); err != nil {
54 log.Fatalf("Failure removing local directory %s", localPersistentStorage)
55 }
56 e, err := embed.StartEtcd(cfg)
57 if err != nil {
58 log.Fatal(err)
59 }
60 select {
61 case <-e.Server.ReadyNotify():
62 log.Printf("Embedded Etcd server is ready!")
63 case <-time.After(serverStartUpTimeout):
64 e.Server.HardStop() // trigger a shutdown
65 e.Close()
66 log.Fatal("Embedded Etcd server took too long to start!")
67 case err := <-e.Err():
68 e.Server.HardStop() // trigger a shutdown
69 e.Close()
70 log.Fatalf("Embedded Etcd server errored out - %s", err)
71 }
72 return &EtcdServer{server: e}
73}
74
75//Stop closes the embedded Etcd server and removes the local data directory as well
76func (es *EtcdServer) Stop() {
77 if es != nil {
78 es.server.Server.HardStop()
79 es.server.Close()
80 if err := os.RemoveAll(localPersistentStorage); err != nil {
81 log.Fatalf("Failure removing local directory %s", es.server.Config().Dir)
82 }
83 }
84}