Removed all references to the ro-core.
Also removed unused afrouter tests.
Also removed cli/ folder.
Completes VOL-2295
Change-Id: Id8afcbf80a55b6d3d254896222c427834e0795d7
diff --git a/.gitignore b/.gitignore
index 5a1a698..8ae7909 100644
--- a/.gitignore
+++ b/.gitignore
@@ -56,6 +56,3 @@
# test output
tests/results
sca-report
-
-# etcd mocks
-ro_core/core/voltha.lib.mocks.etcd
diff --git a/Makefile b/Makefile
index 78783a5..f79717a 100644
--- a/Makefile
+++ b/Makefile
@@ -30,7 +30,6 @@
DOCKER_REPOSITORY ?=
DOCKER_TAG ?= ${VERSION}$(shell [[ ${DOCKER_LABEL_VCS_DIRTY} == "true" ]] && echo "-dirty" || true)
RWCORE_IMAGENAME := ${DOCKER_REGISTRY}${DOCKER_REPOSITORY}voltha-rw-core
-ROCORE_IMAGENAME := ${DOCKER_REGISTRY}${DOCKER_REPOSITORY}voltha-ro-core
TYPE ?= minimal
## Docker labels. Only set ref and commit date if committed
@@ -58,7 +57,7 @@
DOCKER_BUILD_ARGS_LOCAL ?= ${DOCKER_BUILD_ARGS} \
--build-arg LOCAL_PROTOS=${LOCAL_PROTOS}
-.PHONY: rw_core ro_core local-protos
+.PHONY: rw_core local-protos
# This should to be the first and default target in this Makefile
help:
@@ -68,7 +67,6 @@
@echo "build : Build the docker images."
@echo " - If this is the first time you are building, choose 'make build' option."
@echo "rw_core : Build the rw_core docker image"
- @echo "ro_core : Build the ro_core docker image"
@echo "clean : Remove files created by the build and tests"
@echo "distclean : Remove sca directory and clean"
@echo "docker-push : Push the docker images to an external repository"
@@ -99,22 +97,17 @@
build: docker-build
-docker-build: rw_core ro_core
+docker-build: rw_core
rw_core: local-protos local-lib-go
docker build $(DOCKER_BUILD_ARGS) -t ${RWCORE_IMAGENAME}:${DOCKER_TAG} -t ${RWCORE_IMAGENAME}:latest -f docker/Dockerfile.rw_core .
-ro_core: local-protos local-lib-go
- docker build $(DOCKER_BUILD_ARGS) -t ${ROCORE_IMAGENAME}:${DOCKER_TAG} -t ${ROCORE_IMAGENAME}:latest -f docker/Dockerfile.ro_core .
-
docker-push:
docker push ${RWCORE_IMAGENAME}:${DOCKER_TAG}
- docker push ${ROCORE_IMAGENAME}:${DOCKER_TAG}
docker-kind-load:
@if [ "`kind get clusters | grep voltha-$(TYPE)`" = '' ]; then echo "no voltha-$(TYPE) cluster found" && exit 1; fi
kind load docker-image ${RWCORE_IMAGENAME}:${DOCKER_TAG} --name=voltha-$(TYPE) --nodes $(shell kubectl get nodes --template='{{range .items}}{{.metadata.name}},{{end}}' | rev | cut -c 2- | rev)
- kind load docker-image ${ROCORE_IMAGENAME}:${DOCKER_TAG} --name=voltha-$(TYPE) --nodes $(shell kubectl get nodes --template='{{range .items}}{{.metadata.name}},{{end}}' | rev | cut -c 2- | rev)
## lint and unit tests
@@ -200,7 +193,7 @@
sca: golangci_lint_tool_install
rm -rf ./sca-report
@mkdir -p ./sca-report
- $(GOLANGCI_LINT_TOOL) run --deadline=2m -E golint --out-format junit-xml ./cli/... ./rw_core/... ./ro_core/... ./tests/... ./common/... ./db/... 2>&1 | tee ./sca-report/sca-report.xml
+ $(GOLANGCI_LINT_TOOL) run --deadline=4m -E golint --out-format junit-xml ./rw_core/... ./tests/... ./common/... ./db/... 2>&1 | tee ./sca-report/sca-report.xml
test: go_junit_install gocover_cobertura_install local-lib-go
@mkdir -p ./tests/results
diff --git a/cli/main.go b/cli/main.go
deleted file mode 100644
index f87bd6c..0000000
--- a/cli/main.go
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package main
-
-import (
- "flag"
- "fmt"
- "log"
- "os/exec"
-
- "github.com/opencord/voltha-go/cli/menu/mainmenu"
- l "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "google.golang.org/grpc"
-)
-
-func main() {
-
- // disable input buffering
- err := exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
- if err != nil {
- l.Errorw("unable-to-configure-terminal-session-parameters-cbreak-and-min", l.Fields{"error": err})
- }
- // do not display entered characters on the screen
- err = exec.Command("stty", "-F", "/dev/tty", "-echo").Run()
- if err != nil {
- l.Errorw("unable-to-configure-terminal-session-parameter-echo", l.Fields{"error": err})
- }
- printHeader()
-
- volthaAddress := flag.String("voltha_address", "localhost:6161", "IP/Hostname:Port for Voltha Core")
- h := flag.Bool("h", false, "Print help")
- help := flag.Bool("help", false, "Print help")
- flag.Parse()
- if *h || *help {
- fmt.Println("cli -h(elp) print this message")
- fmt.Println("cli -voltha_address=$VOLTHA_ADDRESS:PORT default localhost:6161")
- return
- }
- conn, err := grpc.Dial(*volthaAddress, grpc.WithInsecure())
- if err != nil {
- log.Fatalf("did not connect: %s", err)
- }
- defer conn.Close()
- fmt.Println("Connecting to " + *volthaAddress)
-
- mainmenu.MainLoop(conn)
-}
-func printHeader() {
- header :=
- ` _ _ _ ___ _ ___
-__ _____| | |_| |_ __ _ / __| | |_ _|
-\ V / _ \ | _| ' \/ _' | | (__| |__ | |
- \_/\___/_|\__|_||_\__,_| \___|____|___|
-`
- fmt.Println(header)
-}
diff --git a/cli/menu/devicemenu/deviceMenu.go b/cli/menu/devicemenu/deviceMenu.go
deleted file mode 100644
index a392e95..0000000
--- a/cli/menu/devicemenu/deviceMenu.go
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import (
- "fmt"
-
- "github.com/bclicn/color"
- "github.com/opencord/voltha-go/cli/util"
- "google.golang.org/grpc"
-)
-
-/*
-Conn - the grpc connection to use for making calls to voltha core
-*/
-var (
- Conn *grpc.ClientConn
- DeviceID *string
- InputPrompt *string
- Commands *[]string
-)
-
-/*
-MainLoop - the loop which processes commands at the main level
-*/
-func MainLoop(conn *grpc.ClientConn, deviceID string) {
-
- DeviceID = &deviceID
- inputPrompt := fmt.Sprint("(" + color.LightRed("device "+deviceID) + ") ")
- InputPrompt = &inputPrompt
- funcTable := make(map[string]func(bool))
- // inputPromptSize := len(inputPrompt)
- Conn = conn
- funcTable["quit"] = util.Exit
- funcTable["exit"] = nil
- funcTable["edit"] = doEdit
- funcTable["history"] = doHistory
- funcTable["img_dnld_request"] = doImgDnldRequest
- funcTable["perf_config"] = doPerfConfig
- funcTable["save"] = doSave
- funcTable["eof"] = doEOF
- funcTable["images"] = doImages
- funcTable["img_dnld_status"] = doImgDnldStatus
- funcTable["ports"] = doPorts
- funcTable["set"] = doSet
- funcTable["img_activate"] = doImgActivate
- funcTable["img_revert"] = doImgRevert
- funcTable["py"] = doPy
- funcTable["shell"] = doShell
- funcTable["flows"] = doFlows
- funcTable["img_dnld_canel"] = doImgDnldCancel
- funcTable["list"] = doList
- funcTable["shortcuts"] = doShortCuts
- funcTable["help"] = doHelp
- funcTable["img_dnld_list"] = doImgDnldList
- funcTable["pause"] = doPause
- funcTable["run"] = doRun
- funcTable["show"] = doShow
-
- commands := make([]string, len(funcTable))
- i := 0
- for key := range funcTable {
- commands[i] = key
- i++
- }
- Commands = &commands
-
- util.ProcessTable(funcTable, inputPrompt)
-
-}
diff --git a/cli/menu/devicemenu/edit.go b/cli/menu/devicemenu/edit.go
deleted file mode 100644
index 137ec10..0000000
--- a/cli/menu/devicemenu/edit.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doEdit(enterPressed bool) {
- fmt.Println("doEdit")
-}
diff --git a/cli/menu/devicemenu/eof.go b/cli/menu/devicemenu/eof.go
deleted file mode 100644
index 2c73b26..0000000
--- a/cli/menu/devicemenu/eof.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doEOF(enterPressed bool) {
- fmt.Println("doEOF")
-}
diff --git a/cli/menu/devicemenu/flows.go b/cli/menu/devicemenu/flows.go
deleted file mode 100644
index b9c3add..0000000
--- a/cli/menu/devicemenu/flows.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doFlows(enterPressed bool) {
- fmt.Println("doFlows")
-}
diff --git a/cli/menu/devicemenu/help.go b/cli/menu/devicemenu/help.go
deleted file mode 100644
index 69475c0..0000000
--- a/cli/menu/devicemenu/help.go
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import (
- "fmt"
- "os"
- "strings"
-
- "github.com/opencord/voltha-go/cli/util"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
-)
-
-func doHelp(enterPressed bool) {
- input := ""
- var b = make([]byte, 1)
- inputPrompt := *InputPrompt + "help "
- for {
- _, err := os.Stdin.Read(b)
- if err != nil {
- log.Errorw("unable-to-read-from-stdin-file", log.Fields{"error": err})
- }
- char := string(b)
- if char == "\t" || char == "\n" || char == "?" {
- if enterPressed {
- baseHelp()
- return
- }
-
- fmt.Println("")
- ret, prompt := util.Test(input, *Commands)
- if len(ret) == 1 {
- input = ret[0]
- if input == "quit" {
- util.Exit(true)
- } else if input == "exit" {
- return
- }
-
- MainLoop(Conn, input)
- return
- } else if len(ret) == 0 {
- input = ""
- fmt.Print("Invalid Input \n" + inputPrompt)
- } else {
-
- fmt.Println(ret)
- input = prompt
- fmt.Print(prompt + inputPrompt)
- }
- } else if b[0] == 127 || char == "\b" {
-
- sz := len(input)
- if sz > 0 {
- fmt.Print("\b \b")
- input = input[:sz-1]
- }
- if !(strings.HasPrefix(input, "device")) {
- return
- }
- } else {
- fmt.Print(char)
- input += char
- }
- }
-}
-func baseHelp() {
- message := `
-Documented commands (type help <topic>):
-========================================
-edit help img_dnld_cancel img_revert ports set
-eof history img_dnld_list list py shell
-exit images img_dnld_request pause run shortcuts
-flows img_activate img_dnld_status perf_config save show
-
-Miscellaneous help topics:
-==========================
-load
-
-Undocumented commands:
-======================
-quit
-
-`
- fmt.Println(message)
-}
diff --git a/cli/menu/devicemenu/history.go b/cli/menu/devicemenu/history.go
deleted file mode 100644
index 009fb16..0000000
--- a/cli/menu/devicemenu/history.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doHistory(enterPressed bool) {
- fmt.Println("doHistory")
-}
diff --git a/cli/menu/devicemenu/images.go b/cli/menu/devicemenu/images.go
deleted file mode 100644
index b859af2..0000000
--- a/cli/menu/devicemenu/images.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doImages(enterPressed bool) {
- fmt.Println("doImages")
-}
diff --git a/cli/menu/devicemenu/img_activate.go b/cli/menu/devicemenu/img_activate.go
deleted file mode 100644
index d900401..0000000
--- a/cli/menu/devicemenu/img_activate.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doImgActivate(enterPressed bool) {
- fmt.Println("doImgActivate")
-}
diff --git a/cli/menu/devicemenu/img_dnld_cancel.go b/cli/menu/devicemenu/img_dnld_cancel.go
deleted file mode 100644
index 7dbffd8..0000000
--- a/cli/menu/devicemenu/img_dnld_cancel.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doImgDnldCancel(enterPressed bool) {
- fmt.Println("doImgDnldCancel")
-}
diff --git a/cli/menu/devicemenu/img_dnld_list.go b/cli/menu/devicemenu/img_dnld_list.go
deleted file mode 100644
index 06b0e48..0000000
--- a/cli/menu/devicemenu/img_dnld_list.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doImgDnldList(enterPressed bool) {
- fmt.Println("doImgDnldList")
-}
diff --git a/cli/menu/devicemenu/img_dnld_request.go b/cli/menu/devicemenu/img_dnld_request.go
deleted file mode 100644
index c2cb739..0000000
--- a/cli/menu/devicemenu/img_dnld_request.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doImgDnldRequest(enterPressed bool) {
- fmt.Println("doImgDnldRequest")
-}
diff --git a/cli/menu/devicemenu/img_dnld_status.go b/cli/menu/devicemenu/img_dnld_status.go
deleted file mode 100644
index c338524..0000000
--- a/cli/menu/devicemenu/img_dnld_status.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doImgDnldStatus(enterPressed bool) {
- fmt.Println("doImgDnldStatus")
-}
diff --git a/cli/menu/devicemenu/img_revert.go b/cli/menu/devicemenu/img_revert.go
deleted file mode 100644
index 4d0aaa5..0000000
--- a/cli/menu/devicemenu/img_revert.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doImgRevert(enterPressed bool) {
- fmt.Println("doImgRevert")
-}
diff --git a/cli/menu/devicemenu/list.go b/cli/menu/devicemenu/list.go
deleted file mode 100644
index 31804e5..0000000
--- a/cli/menu/devicemenu/list.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doList(enterPressed bool) {
- fmt.Println("doList")
-}
diff --git a/cli/menu/devicemenu/pause.go b/cli/menu/devicemenu/pause.go
deleted file mode 100644
index 3c77bfb..0000000
--- a/cli/menu/devicemenu/pause.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doPause(enterPressed bool) {
- fmt.Println("doPause")
-}
diff --git a/cli/menu/devicemenu/perf_config.go b/cli/menu/devicemenu/perf_config.go
deleted file mode 100644
index 178a17e..0000000
--- a/cli/menu/devicemenu/perf_config.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doPerfConfig(enterPressed bool) {
- fmt.Println("doPrefConfig")
-}
diff --git a/cli/menu/devicemenu/ports.go b/cli/menu/devicemenu/ports.go
deleted file mode 100644
index 2d9f276..0000000
--- a/cli/menu/devicemenu/ports.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doPorts(enterPressed bool) {
- fmt.Println("doPorts")
-}
diff --git a/cli/menu/devicemenu/py.go b/cli/menu/devicemenu/py.go
deleted file mode 100644
index 8667ed3..0000000
--- a/cli/menu/devicemenu/py.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doPy(enterPressed bool) {
- fmt.Println("doPy")
-}
diff --git a/cli/menu/devicemenu/run.go b/cli/menu/devicemenu/run.go
deleted file mode 100644
index b8b780b..0000000
--- a/cli/menu/devicemenu/run.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doRun(enterPressed bool) {
- fmt.Println("doRun")
-}
diff --git a/cli/menu/devicemenu/save.go b/cli/menu/devicemenu/save.go
deleted file mode 100644
index dd531da..0000000
--- a/cli/menu/devicemenu/save.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doSave(enterPressed bool) {
- fmt.Println("doSave")
-}
diff --git a/cli/menu/devicemenu/set.go b/cli/menu/devicemenu/set.go
deleted file mode 100644
index c44e164..0000000
--- a/cli/menu/devicemenu/set.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doSet(enterPressed bool) {
- fmt.Println("doSet")
-}
diff --git a/cli/menu/devicemenu/shell.go b/cli/menu/devicemenu/shell.go
deleted file mode 100644
index ddfd8f8..0000000
--- a/cli/menu/devicemenu/shell.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doShell(enterPressed bool) {
- fmt.Println("doShell")
-}
diff --git a/cli/menu/devicemenu/shortcuts.go b/cli/menu/devicemenu/shortcuts.go
deleted file mode 100644
index 0e3d120..0000000
--- a/cli/menu/devicemenu/shortcuts.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import "fmt"
-
-func doShortCuts(enterPressed bool) {
- fmt.Println("doShortCuts")
-}
diff --git a/cli/menu/devicemenu/show.go b/cli/menu/devicemenu/show.go
deleted file mode 100644
index 4113532..0000000
--- a/cli/menu/devicemenu/show.go
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package devicemenu
-
-import (
- "context"
- "fmt"
- "strconv"
-
- "github.com/opencord/voltha-go/cli/util"
- "github.com/opencord/voltha-protos/v3/go/common"
- "github.com/opencord/voltha-protos/v3/go/voltha"
-)
-
-func doShow(enterPressed bool) {
- client := voltha.NewVolthaServiceClient(Conn)
- fmt.Println(*DeviceID)
- device, err := client.GetDevice(context.Background(), &common.ID{Id: *DeviceID})
- if err != nil {
- fmt.Println(err)
- }
- fields := []string{"field", "value"}
- var rows []map[string]string
-
- id := make(map[string]string)
- id["field"] = "id"
- id["value"] = device.Id
- rows = append(rows, id)
-
- Type := make(map[string]string)
- Type["field"] = "type"
- Type["value"] = device.Type
- rows = append(rows, Type)
-
- parentID := make(map[string]string)
- parentID["field"] = "parent_id"
- parentID["value"] = device.ParentId
- rows = append(rows, parentID)
-
- vlan := make(map[string]string)
- vlan["field"] = "vlan"
- vlan["value"] = strconv.FormatUint(uint64(device.Vlan), 10)
- rows = append(rows, vlan)
-
- adminState := make(map[string]string)
- adminState["field"] = "admin_state"
- adminState["value"] = strconv.FormatUint(uint64(device.AdminState), 10)
- rows = append(rows, adminState)
-
- proxyAddress := device.GetProxyAddress()
- proxyDeviceID := make(map[string]string)
- proxyDeviceID["field"] = "proxy_address.device_id"
- proxyDeviceID["value"] = proxyAddress.DeviceId
- rows = append(rows, proxyDeviceID)
-
- proxyDeviceType := make(map[string]string)
- proxyDeviceType["field"] = "proxy_address.device_type"
- proxyDeviceType["value"] = proxyAddress.DeviceType
- rows = append(rows, proxyDeviceType)
-
- proxyChannelID := make(map[string]string)
- proxyChannelID["field"] = "proxy_address.channel_id"
- proxyChannelID["value"] = strconv.FormatUint(uint64(proxyAddress.ChannelId), 10)
- rows = append(rows, proxyChannelID)
-
- parentPortNumber := make(map[string]string)
- parentPortNumber["field"] = "parent_port_no"
- parentPortNumber["value"] = strconv.FormatUint(uint64(device.GetParentPortNo()), 10)
- rows = append(rows, parentPortNumber)
-
- output, _ := util.BuildTable(fields, rows)
-
- fmt.Println(output)
-}
diff --git a/cli/menu/mainmenu/Makefile b/cli/menu/mainmenu/Makefile
deleted file mode 100644
index fd522a5..0000000
--- a/cli/menu/mainmenu/Makefile
+++ /dev/null
@@ -1,13 +0,0 @@
-VOLTHA_PROTO_PATH := protos/voltha_protos
-VOLTHA_PROTO_FILES := $(wildcard protos/voltha_protos/*.proto)
-VOLTHA_PROTO_GO_FILES := $(foreach f,$(VOLTHA_PROTO_FILES),$(subst .proto,.pb.go,$(f)))
-VOLTHA_PROTO_DESC_FILES := $(foreach f,$(VOLTHA_PROTO_FILES),$(subst .proto,.desc,$(f)))
-
-voltha-api: $(VOLTHA_PROTO_GO_FILES)
-
-%.pb.go: %.proto
- @protoc -I ${VOLTHA_PROTO_PATH} \
- --go_out=plugins=grpc:${VOLTHA_PROTO_PATH} \
- -I${GOPATH}/src \
- -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
- $<
diff --git a/cli/menu/mainmenu/alarmFilters.go b/cli/menu/mainmenu/alarmFilters.go
deleted file mode 100644
index 4473a87..0000000
--- a/cli/menu/mainmenu/alarmFilters.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doAlarmFilters(enterPressed bool) {
- fmt.Print("input: alarm_filters>")
-}
diff --git a/cli/menu/mainmenu/arriveOnus.go b/cli/menu/mainmenu/arriveOnus.go
deleted file mode 100644
index 06b699d..0000000
--- a/cli/menu/mainmenu/arriveOnus.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doArriveOnus(enterPressed bool) {
- fmt.Print("input: arrive_onus>")
-}
diff --git a/cli/menu/mainmenu/cmdEnvironment.go b/cli/menu/mainmenu/cmdEnvironment.go
deleted file mode 100644
index d3a54fe..0000000
--- a/cli/menu/mainmenu/cmdEnvironment.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doCmdEnvironment(enterPressed bool) {
- fmt.Println("input: doCmdEnvironment> ")
-}
diff --git a/cli/menu/mainmenu/delete.go b/cli/menu/mainmenu/delete.go
deleted file mode 100644
index c8d4226..0000000
--- a/cli/menu/mainmenu/delete.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doDelete(enterPressed bool) {
- fmt.Println("input: delete > ")
-}
diff --git a/cli/menu/mainmenu/deleteAllFlows.go b/cli/menu/mainmenu/deleteAllFlows.go
deleted file mode 100644
index bf13cfb..0000000
--- a/cli/menu/mainmenu/deleteAllFlows.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doDeleteAllFlows(enterPressed bool) {
- fmt.Print("input: delete_all_flows>")
-}
diff --git a/cli/menu/mainmenu/device.go b/cli/menu/mainmenu/device.go
deleted file mode 100644
index 783c064..0000000
--- a/cli/menu/mainmenu/device.go
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import (
- "context"
- "fmt"
- "os"
- "strings"
-
- "github.com/golang/protobuf/ptypes/empty"
- "github.com/opencord/voltha-go/cli/menu/devicemenu"
- "github.com/opencord/voltha-go/cli/util"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-protos/v3/go/voltha"
-)
-
-func doDevice(enterPressed bool) {
- fmt.Print(" ")
- client := voltha.NewVolthaServiceClient(Conn)
- devices, err := client.ListDevices(context.Background(), &empty.Empty{})
- items := devices.GetItems()
- if err != nil {
- fmt.Println(err)
- }
- deviceIDs := []string{"exit", "quit"}
- for i := 0; i < len(items); i++ {
- deviceIDs = append(deviceIDs, items[i].Id)
- }
- var b = make([]byte, 1)
- input := ""
-
- for {
- _, err := os.Stdin.Read(b)
- if err != nil {
- log.Errorw("unable-to-read-from-stdin-file", log.Fields{"error": err})
- }
- char := string(b)
- if char == "\t" || char == "\n" || char == "?" {
- fmt.Println("")
- ret, prompt := util.Test(input, deviceIDs)
- if len(ret) == 1 {
- input = ret[0]
- if input == "quit" {
- util.Exit(true)
- } else if input == "exit" {
- return
- }
-
- devicemenu.MainLoop(Conn, input)
- return
- } else if len(ret) == 0 {
- input = ""
- fmt.Print("Invalid Input \ninput:")
- } else {
-
- fmt.Println(ret)
- input = prompt
- fmt.Print("input: " + prompt)
- }
- } else if b[0] == 127 || char == "\b" {
-
- sz := len(input)
- if sz > 0 {
- fmt.Print("\b \b")
- input = input[:sz-1]
- }
- if !(strings.HasPrefix(input, "device")) {
- return
- }
- } else {
- fmt.Print(char)
- input += char
- }
- }
-
-}
diff --git a/cli/menu/mainmenu/devices.go b/cli/menu/mainmenu/devices.go
deleted file mode 100644
index ec373a0..0000000
--- a/cli/menu/mainmenu/devices.go
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import (
- "context"
- "fmt"
- "strconv"
-
- "github.com/golang/protobuf/ptypes/empty"
- "github.com/opencord/voltha-go/cli/util"
- "github.com/opencord/voltha-protos/v3/go/voltha"
-)
-
-/*
- reason | proxy_address.device_id | proxy_address.onu_id | proxy_address.onu_session_id |
-*/
-func doDevices(enterPressed bool) {
-
- client := voltha.NewVolthaServiceClient(Conn)
- devices, err := client.ListDevices(context.Background(), &empty.Empty{})
- if err != nil {
- fmt.Println(err)
- }
- var rows []map[string]string
- items := devices.GetItems()
- var fields = []string{"id", "type", "root", "parent_id", "serial_number", "admin_state", "oper_status", "connect_status", "parent_port_no", "host_and_port", "reason",
- "proxy_address.device_id", "proxy_address.onu_id", "proxy_address.onu_session_id"}
-
- for i := 0; i < len(items); i++ {
- //fmt.Println(items[i])
- device := items[i]
- row := make(map[string]string)
- row["id"] = device.Id
- row["type"] = device.Type
- row["root"] = strconv.FormatBool(device.Root)
- row["parent_id"] = device.ParentId
- row["serial_number"] = device.SerialNumber
- row["admin_state"] = device.AdminState.String()
- row["oper_status"] = device.OperStatus.String()
- row["connect_status"] = device.ConnectStatus.String()
- row["parent_port_no"] = strconv.FormatUint(uint64(device.GetParentPortNo()), 10)
- row["host_and_port"] = device.GetHostAndPort()
- row["reason"] = device.Reason
- proxyAddress := device.GetProxyAddress()
- if proxyAddress != nil {
- row["proxy_address.device_id"] = proxyAddress.DeviceId
- row["proxy_address.onu_id"] = strconv.FormatUint(uint64(proxyAddress.OnuId), 10)
- row["proxy_address.onu_session_id"] = strconv.FormatUint(uint64(proxyAddress.OnuSessionId), 10)
- } else {
- row["proxy_address.device_id"] = ""
- row["proxy_address.onu_id"] = ""
- row["proxy_address.onu_session_id"] = ""
- }
-
- rows = append(rows, row)
- }
- output, err := util.BuildTable(fields, rows)
- if err != nil {
- fmt.Println(err)
- }
- fmt.Print(output)
-
-}
diff --git a/cli/menu/mainmenu/disable.go b/cli/menu/mainmenu/disable.go
deleted file mode 100644
index f0bfb0f..0000000
--- a/cli/menu/mainmenu/disable.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doDisable(enterPressed bool) {
- fmt.Print("input: disable>")
-}
diff --git a/cli/menu/mainmenu/enable.go b/cli/menu/mainmenu/enable.go
deleted file mode 100644
index 691407d..0000000
--- a/cli/menu/mainmenu/enable.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doEnable(enterPressed bool) {
- fmt.Print("input: enable>")
-}
diff --git a/cli/menu/mainmenu/health.go b/cli/menu/mainmenu/health.go
deleted file mode 100644
index b6ca362..0000000
--- a/cli/menu/mainmenu/health.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doHealth(enterPressed bool) {
- fmt.Print("input: health>")
-}
diff --git a/cli/menu/mainmenu/injectEapolStart.go b/cli/menu/mainmenu/injectEapolStart.go
deleted file mode 100644
index c71e958..0000000
--- a/cli/menu/mainmenu/injectEapolStart.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doInjectEapolStart(enterPressed bool) {
- fmt.Print("input: inject_eapol_start>")
-}
diff --git a/cli/menu/mainmenu/installAllControllerBoundFlows.go b/cli/menu/mainmenu/installAllControllerBoundFlows.go
deleted file mode 100644
index 6f394d7..0000000
--- a/cli/menu/mainmenu/installAllControllerBoundFlows.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doInstallAllControllerBoundFlows(enterPressed bool) {
- fmt.Print("input: install_all_controller_bound_flows>")
-}
diff --git a/cli/menu/mainmenu/installAllSampleFlows.go b/cli/menu/mainmenu/installAllSampleFlows.go
deleted file mode 100644
index fedb7e3..0000000
--- a/cli/menu/mainmenu/installAllSampleFlows.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doInstallAllSampleFlows(enterPressed bool) {
- fmt.Print("input: install_all_sample_flows>")
-}
diff --git a/cli/menu/mainmenu/installDhcpFlows.go b/cli/menu/mainmenu/installDhcpFlows.go
deleted file mode 100644
index 3b71b35..0000000
--- a/cli/menu/mainmenu/installDhcpFlows.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doInstallDhcpFlows(enterPressed bool) {
- fmt.Print("input: install_dhcp_flows>")
-}
diff --git a/cli/menu/mainmenu/installEapolFlow.go b/cli/menu/mainmenu/installEapolFlow.go
deleted file mode 100644
index 5c68d98..0000000
--- a/cli/menu/mainmenu/installEapolFlow.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doInstallEapolFlow(enterPressed bool) {
- fmt.Print("input: install_eapol_flow>")
-}
diff --git a/cli/menu/mainmenu/launch.go b/cli/menu/mainmenu/launch.go
deleted file mode 100644
index ec5a40b..0000000
--- a/cli/menu/mainmenu/launch.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doLaunch(enterPressed bool) {
- fmt.Print("input: launch")
-}
diff --git a/cli/menu/mainmenu/load.go b/cli/menu/mainmenu/load.go
deleted file mode 100644
index 8b462b0..0000000
--- a/cli/menu/mainmenu/load.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doLoad(enterPressed bool) {
- fmt.Println("input: load>")
-}
diff --git a/cli/menu/mainmenu/log.go b/cli/menu/mainmenu/log.go
deleted file mode 100644
index 7f5a9bd..0000000
--- a/cli/menu/mainmenu/log.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doLog(enterPressed bool) {
- fmt.Print("input: log>")
-}
diff --git a/cli/menu/mainmenu/logicalDevice.go b/cli/menu/mainmenu/logicalDevice.go
deleted file mode 100644
index 2ba2874..0000000
--- a/cli/menu/mainmenu/logicalDevice.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doLogicalDevice(enterPressed bool) {
- fmt.Print("input: logical_device>")
-}
diff --git a/cli/menu/mainmenu/logicalDevices.go b/cli/menu/mainmenu/logicalDevices.go
deleted file mode 100644
index a178366..0000000
--- a/cli/menu/mainmenu/logicalDevices.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doLogicalDevices(enterPressed bool) {
- fmt.Print("input: logical_devices>")
-}
diff --git a/cli/menu/mainmenu/mainMenu.go b/cli/menu/mainmenu/mainMenu.go
deleted file mode 100644
index 8d45917..0000000
--- a/cli/menu/mainmenu/mainMenu.go
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import (
- "fmt"
-
- "github.com/bclicn/color"
- "github.com/opencord/voltha-go/cli/util"
- "google.golang.org/grpc"
-)
-
-/*
-Conn - the grpc connection to use for making calls to voltha core
-*/
-var Conn *grpc.ClientConn
-
-/*
-MainLoop - the loop which processes commands at the main level
-*/
-func MainLoop(conn *grpc.ClientConn) {
-
- inputPrompt := fmt.Sprint("(" + color.LightBlue("voltha") + ") ")
- // inputPromptSize := len(inputPrompt)
- Conn = conn
- mainFuncTable := make(map[string]func(bool))
- mainFuncTable["quit"] = util.Exit
- mainFuncTable["exit"] = nil
- mainFuncTable["cmdenvironment"] = doCmdEnvironment
- mainFuncTable["load"] = doLoad
- mainFuncTable["relative_load"] = doRelativeLoad
- mainFuncTable["reset_history"] = doResetHistory
- mainFuncTable["log"] = doLog
- mainFuncTable["launch"] = doLaunch
- mainFuncTable["restart"] = doRestart
- mainFuncTable["devices"] = doDevices
- mainFuncTable["device"] = doDevice
- mainFuncTable["logical_devices"] = doLogicalDevices
- mainFuncTable["logical_device"] = doLogicalDevice
- mainFuncTable["omci"] = doOmci
- mainFuncTable["pdb"] = doPdb
- mainFuncTable["version"] = doVersion
- mainFuncTable["health"] = doHealth
- mainFuncTable["preprovison_olt"] = doPreprovisionOlt
- mainFuncTable["enable"] = doEnable
- mainFuncTable["reboot"] = doReboot
- mainFuncTable["self_test"] = doSelfTest
- mainFuncTable["delete"] = doDelete
- mainFuncTable["disable"] = doDisable
- mainFuncTable["test"] = doTest
- mainFuncTable["alarm_filters"] = doAlarmFilters
- mainFuncTable["arrive_onus"] = doArriveOnus
- mainFuncTable["install_eapol_flow"] = doInstallEapolFlow
- mainFuncTable["install_all_controller_bound_flows"] = doInstallAllControllerBoundFlows
- mainFuncTable["install_all_sample_flows"] = doInstallAllSampleFlows
- mainFuncTable["install_dhcp_flows"] = doInstallDhcpFlows
- mainFuncTable["delete_all_flows"] = doDeleteAllFlows
- mainFuncTable["send_simulated_upstream_eapol"] = doSendSimulatedUpstreamEapol
- mainFuncTable["inject_eapol_start"] = doInjectEapolStart
- util.ProcessTable(mainFuncTable, inputPrompt)
-}
diff --git a/cli/menu/mainmenu/omci.go b/cli/menu/mainmenu/omci.go
deleted file mode 100644
index d648960..0000000
--- a/cli/menu/mainmenu/omci.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doOmci(enterPressed bool) {
- fmt.Print("input: ocmi>")
-}
diff --git a/cli/menu/mainmenu/pdb.go b/cli/menu/mainmenu/pdb.go
deleted file mode 100644
index ec44436..0000000
--- a/cli/menu/mainmenu/pdb.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doPdb(enterPressed bool) {
- fmt.Print("input: pdb>")
-}
diff --git a/cli/menu/mainmenu/preprovisionOlt.go b/cli/menu/mainmenu/preprovisionOlt.go
deleted file mode 100644
index effa8ed..0000000
--- a/cli/menu/mainmenu/preprovisionOlt.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doPreprovisionOlt(enterPressed bool) {
- fmt.Print("input preprovision_olt>")
-}
diff --git a/cli/menu/mainmenu/reboot.go b/cli/menu/mainmenu/reboot.go
deleted file mode 100644
index 7dcbd6e..0000000
--- a/cli/menu/mainmenu/reboot.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doReboot(enterPressed bool) {
- fmt.Print("input: reboot>")
-}
diff --git a/cli/menu/mainmenu/relativeLoad.go b/cli/menu/mainmenu/relativeLoad.go
deleted file mode 100644
index 1416e26..0000000
--- a/cli/menu/mainmenu/relativeLoad.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doRelativeLoad(enterPressed bool) {
- fmt.Print("input: relative_load>")
-}
diff --git a/cli/menu/mainmenu/resetHistory.go b/cli/menu/mainmenu/resetHistory.go
deleted file mode 100644
index 3fb86cd..0000000
--- a/cli/menu/mainmenu/resetHistory.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doResetHistory(enterPressed bool) {
- fmt.Print("input: reset_history>")
-}
diff --git a/cli/menu/mainmenu/restart.go b/cli/menu/mainmenu/restart.go
deleted file mode 100644
index a014f55..0000000
--- a/cli/menu/mainmenu/restart.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doRestart(enterPressed bool) {
- fmt.Print("input: restart>")
-}
diff --git a/cli/menu/mainmenu/selfTest.go b/cli/menu/mainmenu/selfTest.go
deleted file mode 100644
index 3ef6675..0000000
--- a/cli/menu/mainmenu/selfTest.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doSelfTest(enterPressed bool) {
- fmt.Print("input: self_test>")
-}
diff --git a/cli/menu/mainmenu/sendSimulatedUpstreamEapol.go b/cli/menu/mainmenu/sendSimulatedUpstreamEapol.go
deleted file mode 100644
index 22b1e47..0000000
--- a/cli/menu/mainmenu/sendSimulatedUpstreamEapol.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doSendSimulatedUpstreamEapol(enterPressed bool) {
- fmt.Print("input: send_simulated_upstream_eapol>")
-}
diff --git a/cli/menu/mainmenu/test.go b/cli/menu/mainmenu/test.go
deleted file mode 100644
index 768b0c2..0000000
--- a/cli/menu/mainmenu/test.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doTest(enterPressed bool) {
- fmt.Print("input: test>")
-}
diff --git a/cli/menu/mainmenu/version.go b/cli/menu/mainmenu/version.go
deleted file mode 100644
index 20c30a4..0000000
--- a/cli/menu/mainmenu/version.go
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mainmenu
-
-import "fmt"
-
-func doVersion(enterPressed bool) {
- fmt.Print("input: version>")
-}
diff --git a/cli/util/menuProcessor.go b/cli/util/menuProcessor.go
deleted file mode 100644
index db2387d..0000000
--- a/cli/util/menuProcessor.go
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package util
-
-import (
- "fmt"
- "os"
-
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
-)
-
-/*
-ProcessTable parses table structure and executes functions
-*/
-func ProcessTable(functionTable map[string]func(bool), inputPrompt string) {
- keys := []string{}
- for k := range functionTable {
- keys = append(keys, k)
- }
- var b = make([]byte, 1)
- input := ""
- fmt.Print(inputPrompt)
- for {
- _, err := os.Stdin.Read(b)
- if err != nil {
- log.Errorw("unable-to-read-from-stdin-file", log.Fields{"error": err})
- }
- char := string(b)
- if char == "\t" || char == "\n" || char == "?" {
- fmt.Println("")
- ret, prompt := Test(input, keys)
- if len(ret) == 1 {
- input = ret[0]
- if input == "exit" {
- return
- }
- if char == "\n" {
- Route(input, functionTable, true)
- } else {
- Route(input, functionTable, false)
- }
- input = ""
- fmt.Print(inputPrompt)
- } else if len(ret) == 0 {
- input = ""
- fmt.Println("\nInvalid Input ")
- fmt.Print(inputPrompt)
- } else if len(ret) == 0 {
- } else {
-
- fmt.Println(ret)
- input = prompt
- fmt.Print(inputPrompt)
- fmt.Print(prompt)
- }
- } else if char == " " {
- _, ok := functionTable[input]
- if ok {
- Route(input, functionTable, false)
- fmt.Print(inputPrompt)
- input = ""
- } else {
- ret, prompt := Test(input, keys)
- if len(ret) == 1 {
- input = ret[0]
- Route(input, functionTable, false)
- input = ""
- fmt.Print(inputPrompt)
- } else if len(ret) == 0 {
- input = ""
- fmt.Println("\nInvalid Input ")
- fmt.Print(inputPrompt)
- } else {
-
- fmt.Println(ret)
- input = prompt
- fmt.Print(inputPrompt + input)
- }
- }
-
- } else if b[0] == 127 || char == "\b" {
- sz := len(input)
-
- if sz > 0 {
- fmt.Print("\b \b")
- input = input[:sz-1]
- }
- } else {
- fmt.Print(char)
- input += char
- }
- }
-}
diff --git a/cli/util/parseCmd.go b/cli/util/parseCmd.go
deleted file mode 100644
index aa78589..0000000
--- a/cli/util/parseCmd.go
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package util
-
-import (
- "os"
- "strings"
-)
-
-// Test makes a bunch on new commands available
-func Test(chars string, values []string) ([]string, string) {
-
- var ret []string
- for i := 0; i < len(values); i++ {
- if strings.HasPrefix(values[i], chars) {
- ret = append(ret, values[i])
- }
- }
- if len(ret) == 0 {
- return ret, ""
- }
- shortIndex := 0
- if len(ret) > 1 {
- for i := 0; i < len(ret); i++ {
- if len(ret[i]) < len(ret[shortIndex]) {
- shortIndex = i
- }
- }
- }
- for i := len(chars); i < len(ret[shortIndex]); i++ {
- inAllWords := true
- for j := 0; j < len(ret); j++ {
- inAllWords = inAllWords && ret[j][i] == ret[shortIndex][i]
- }
- if inAllWords {
- chars += string(ret[shortIndex][i])
- } else {
- return ret, chars
- }
-
- }
-
- return ret, chars
-}
-
-// Route will fetch information with respect to table fields
-func Route(command string, table map[string]func(bool), enterPressed bool) {
- cmd := table[command]
- cmd(enterPressed)
-
-}
-
-// Exit will come out of connected session
-func Exit(notUsed bool) {
- os.Exit(0)
-}
diff --git a/cli/util/tableGen.go b/cli/util/tableGen.go
deleted file mode 100644
index 7672eb5..0000000
--- a/cli/util/tableGen.go
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package util
-
-import (
- "fmt"
- "strings"
-)
-
-// BuildTable populates input data in tabular format
-func BuildTable(keys []string, rows []map[string]string) (string, error) {
- var returnString string
- fieldSizes := make(map[string]int)
-
- for i := 0; i < len(rows); i++ {
- for key, value := range rows[i] {
- currentSize := len(value)
- if currentSize > fieldSizes[key] {
- fieldSizes[key] = currentSize
- }
-
- }
- }
- for i := 0; i < len(keys); i++ {
- currentSize := len(keys[i])
- if currentSize > fieldSizes[keys[i]] {
- fieldSizes[keys[i]] = currentSize
- }
- }
- bottom := "+"
-
- for i := 0; i < len(rows); i++ {
- header := "|"
- line := "|"
- for j := 0; j < len(keys); j++ {
- key := keys[j]
- value := rows[i][key]
- if i == 0 {
- pad := 2 + fieldSizes[key] - len(key)
- field := fmt.Sprintf("%s%s|", strings.Repeat(" ", pad), key)
- spacer := fmt.Sprintf("%s+", strings.Repeat("-", fieldSizes[key]+2))
- header = header + field
- bottom = bottom + spacer
- }
- pad := 2 + fieldSizes[key] - len(value)
- field := fmt.Sprintf("%s%s|", strings.Repeat(" ", pad), value)
- line = line + field
-
- }
- if i == 0 {
- returnString = bottom + "\n" + header + "\n" + bottom + "\n"
- }
-
- returnString = returnString + line + "\n"
- }
- returnString = returnString + bottom + "\n"
-
- return returnString, nil
-
-}
diff --git a/compose/ro_core.yml b/compose/ro_core.yml
deleted file mode 100644
index d23013c..0000000
--- a/compose/ro_core.yml
+++ /dev/null
@@ -1,38 +0,0 @@
----
-# Copyright 2018 the original author or authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-version: '2'
-services:
- ro_core:
- image: voltha-ro-core
- entrypoint:
- - /app/ro_core
- - -kv_store_type=etcd
- - -kv_store_host=${DOCKER_HOST_IP}
- - -kv_store_port=2379
- - -grpc_port=50057
- - -banner=true
- - -ro_core_topic=rocore
- - -log_level=0
- ports:
- - 50057:50057
- volumes:
- - "/var/run/docker.sock:/tmp/docker.sock"
- networks:
- - default
-
-networks:
- default:
- driver: bridge
diff --git a/docker/Dockerfile.ro_core b/docker/Dockerfile.ro_core
deleted file mode 100644
index 60a5a1f..0000000
--- a/docker/Dockerfile.ro_core
+++ /dev/null
@@ -1,93 +0,0 @@
-# Copyright 2016 the original author or authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# -------------
-# Build stage
-
-FROM golang:1.12-alpine3.9 AS build-env
-
-# Install required packages
-RUN apk add --no-cache \
- wget=1.20.3-r0 \
- git=2.20.2-r0 \
- make=4.2.1-r2 \
- build-base=0.5-r1 \
- protobuf=3.6.1-r1 \
- protobuf-dev=3.6.1-r1
-
-# Golang container has GOPATH set to /go by default. Hence, need to explicitly enable
-# Go modules while using folder /go/src under GOPATH as build path; lest go modules
-# will be disabled
-ENV GO111MODULE=on
-
-# Use Standard go build directory structure
-WORKDIR /go/src
-
-# Copy common files.
-COPY common ./common
-COPY db ./db
-COPY vendor ./vendor
-
-# Copy files.
-COPY ro_core ./ro_core
-COPY go.mod ./
-COPY go.sum ./
-
-ARG org_label_schema_version=unknown
-ARG org_label_schema_vcs_url=unknown
-ARG org_label_schema_vcs_ref=unknown
-ARG org_label_schema_build_date=unknown
-ARG org_opencord_vcs_commit_date=unknown
-ARG org_opencord_vcs_dirty=unknown
-
-# Build
-WORKDIR /go/src/ro_core
-SHELL ["/bin/ash", "-o", "pipefail", "-c"]
-RUN go build -mod=vendor -o /go/bin/ro_core \
- -ldflags \
- "-X github.com/opencord/voltha-lib-go/v3/pkg/version.version=$org_label_schema_version \
- -X github.com/opencord/voltha-lib-go/v3/pkg/version.vcsRef=$org_label_schema_vcs_ref \
- -X github.com/opencord/voltha-lib-go/v3/pkg/version.vcsDirty=$org_opencord_vcs_dirty \
- -X github.com/opencord/voltha-lib-go/v3/pkg/version.goVersion=$(go version 2>&1 | sed -E 's/.*go([0-9]+\.[0-9]+\.[0-9]+).*/\1/g') \
- -X github.com/opencord/voltha-lib-go/v3/pkg/version.os=$(go env GOHOSTOS) \
- -X github.com/opencord/voltha-lib-go/v3/pkg/version.arch=$(go env GOHOSTARCH) \
- -X github.com/opencord/voltha-lib-go/v3/pkg/version.buildTime=$org_label_schema_build_date"
-
-# -------------
-# Image creation stage
-
-FROM alpine:3.9.4
-
-# Set the working directory
-WORKDIR /app
-
-# Copy required files
-COPY --from=build-env /go/bin/ro_core /app/
-
-# Label image
-ARG org_label_schema_version=unknown
-ARG org_label_schema_vcs_url=unknown
-ARG org_label_schema_vcs_ref=unknown
-ARG org_label_schema_build_date=unknown
-ARG org_opencord_vcs_commit_date=unknown
-ARG org_opencord_vcs_dirty=unknown
-
-LABEL org.label-schema.schema-version=1.0 \
- org.label-schema.name=voltha-ro-core \
- org.label-schema.version=$org_label_schema_version \
- org.label-schema.vcs-url=$org_label_schema_vcs_url \
- org.label-schema.vcs-ref=$org_label_schema_vcs_ref \
- org.label-schema.build-date=$org_label_schema_build_date \
- org.opencord.vcs-commit-date=$org_opencord_vcs_commit_date \
- org.opencord.vcs-dirty=$org_opencord_vcs_dirty
diff --git a/go.mod b/go.mod
index 51eded6..1c71efe 100644
--- a/go.mod
+++ b/go.mod
@@ -3,7 +3,6 @@
go 1.12
require (
- github.com/bclicn/color v0.0.0-20180711051946-108f2023dc84
github.com/gogo/protobuf v1.3.0
github.com/golang/protobuf v1.3.2
github.com/google/uuid v1.1.1
diff --git a/go.sum b/go.sum
index 542ac38..b2ff9d1 100644
--- a/go.sum
+++ b/go.sum
@@ -17,8 +17,6 @@
github.com/armon/go-metrics v0.0.0-20190430140413-ec5e00d3c878 h1:EFSB7Zo9Eg91v7MJPVsifUysc/wPdN+NOnVe6bWbdBM=
github.com/armon/go-metrics v0.0.0-20190430140413-ec5e00d3c878/go.mod h1:3AMJUQhVx52RsWOnlkpikZr01T/yAVN2gn0861vByNg=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
-github.com/bclicn/color v0.0.0-20180711051946-108f2023dc84 h1:cutFptzj+ospnc1PETUqcSVTH3VQ44Bi0rpt3nE9gvo=
-github.com/bclicn/color v0.0.0-20180711051946-108f2023dc84/go.mod h1:Va9ap1qxjAWkIVaW1E9rH0aNgE8SDI5A4n8Ds8P0fAA=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0 h1:HWo1m869IqiPhD389kmkxeTalrjNbbJTC8LXupb+sl0=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
diff --git a/ro_core/config/config.go b/ro_core/config/config.go
deleted file mode 100644
index 8d856ff..0000000
--- a/ro_core/config/config.go
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package config
-
-import (
- "flag"
- "fmt"
- "os"
- "time"
-
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
-)
-
-// RO Core service default constants
-const (
- ConsulStoreName = "consul"
- EtcdStoreName = "etcd"
- defaultInstanceID = "rocore001"
- defaultGrpcPort = 50057
- defaultGrpcHost = ""
- defaultKVStoreType = EtcdStoreName
- defaultKVStoreTimeout = 5 //in seconds
- defaultKVStoreHost = "127.0.0.1"
- defaultKVStorePort = 2379 // Consul = 8500; Etcd = 2379
- defaultKVTxnKeyDelTime = 60
- defaultLogLevel = 0
- defaultBanner = false
- defaultDisplayVersionOnly = false
- defaultCoreTopic = "rocore"
- defaultROCoreEndpoint = "rocore"
- defaultROCoreKey = "pki/voltha.key"
- defaultROCoreCert = "pki/voltha.crt"
- defaultROCoreCA = "pki/voltha-CA.pem"
- defaultAffinityRouterTopic = "affinityRouter"
- defaultProbeHost = ""
- defaultProbePort = 8080
- defaultLiveProbeInterval = 60 * time.Second
- defaultNotLiveProbeInterval = 5 * time.Second // Probe more frequently to detect Recovery early
- defaultCoreTimeout = 59 * time.Second
- defaultMaxConnectionRetries = -1 // retries forever
- defaultConnectionRetryInterval = 2 * time.Second // in seconds
-)
-
-// ROCoreFlags represents the set of configurations used by the read-only core service
-type ROCoreFlags struct {
- // Command line parameters
- InstanceID string
- ROCoreEndpoint string
- GrpcHost string
- GrpcPort int
- KVStoreType string
- KVStoreTimeout int // in seconds
- KVStoreHost string
- KVStorePort int
- KVTxnKeyDelTime int
- CoreTopic string
- LogLevel int
- Banner bool
- DisplayVersionOnly bool
- ROCoreKey string
- ROCoreCert string
- ROCoreCA string
- AffinityRouterTopic string
- ProbeHost string
- ProbePort int
- LiveProbeInterval time.Duration
- NotLiveProbeInterval time.Duration
- CoreTimeout time.Duration
- MaxConnectionRetries int
- ConnectionRetryInterval time.Duration
-}
-
-func init() {
- _, err := log.AddPackage(log.JSON, log.WarnLevel, nil)
- if err != nil {
- log.Errorw("unable-to-register-package-to-the-log-map", log.Fields{"error": err})
- }
-}
-
-// NewROCoreFlags returns a new ROCore config
-func NewROCoreFlags() *ROCoreFlags {
- var roCoreFlag = ROCoreFlags{ // Default values
- InstanceID: defaultInstanceID,
- ROCoreEndpoint: defaultROCoreEndpoint,
- GrpcHost: defaultGrpcHost,
- GrpcPort: defaultGrpcPort,
- KVStoreType: defaultKVStoreType,
- KVStoreTimeout: defaultKVStoreTimeout,
- KVStoreHost: defaultKVStoreHost,
- KVStorePort: defaultKVStorePort,
- KVTxnKeyDelTime: defaultKVTxnKeyDelTime,
- CoreTopic: defaultCoreTopic,
- LogLevel: defaultLogLevel,
- Banner: defaultBanner,
- DisplayVersionOnly: defaultDisplayVersionOnly,
- ROCoreKey: defaultROCoreKey,
- ROCoreCert: defaultROCoreCert,
- ROCoreCA: defaultROCoreCA,
- AffinityRouterTopic: defaultAffinityRouterTopic,
- ProbeHost: defaultProbeHost,
- ProbePort: defaultProbePort,
- LiveProbeInterval: defaultLiveProbeInterval,
- NotLiveProbeInterval: defaultNotLiveProbeInterval,
- CoreTimeout: defaultCoreTimeout,
- MaxConnectionRetries: defaultMaxConnectionRetries,
- ConnectionRetryInterval: defaultConnectionRetryInterval,
- }
- return &roCoreFlag
-}
-
-// ParseCommandArguments parses the arguments when running read-only core service
-func (cf *ROCoreFlags) ParseCommandArguments() {
-
- help := fmt.Sprintf("RO core endpoint address")
- flag.StringVar(&(cf.ROCoreEndpoint), "vcore-endpoint", defaultROCoreEndpoint, help)
-
- help = fmt.Sprintf("GRPC server - host")
- flag.StringVar(&(cf.GrpcHost), "grpc_host", defaultGrpcHost, help)
-
- help = fmt.Sprintf("GRPC server - port")
- flag.IntVar(&(cf.GrpcPort), "grpc_port", defaultGrpcPort, help)
-
- help = fmt.Sprintf("RO Core topic")
- flag.StringVar(&(cf.CoreTopic), "ro_core_topic", defaultCoreTopic, help)
-
- help = fmt.Sprintf("Affinity Router topic")
- flag.StringVar(&(cf.AffinityRouterTopic), "affinity_router_topic", defaultAffinityRouterTopic, help)
-
- help = fmt.Sprintf("KV store type")
- flag.StringVar(&(cf.KVStoreType), "kv_store_type", defaultKVStoreType, help)
-
- help = fmt.Sprintf("The default timeout when making a kv store request")
- flag.IntVar(&(cf.KVStoreTimeout), "kv_store_request_timeout", defaultKVStoreTimeout, help)
-
- help = fmt.Sprintf("KV store host")
- flag.StringVar(&(cf.KVStoreHost), "kv_store_host", defaultKVStoreHost, help)
-
- help = fmt.Sprintf("KV store port")
- flag.IntVar(&(cf.KVStorePort), "kv_store_port", defaultKVStorePort, help)
-
- help = fmt.Sprintf("The time to wait before deleting a completed transaction key")
- flag.IntVar(&(cf.KVTxnKeyDelTime), "kv_txn_delete_time", defaultKVTxnKeyDelTime, help)
-
- help = fmt.Sprintf("Log level")
- flag.IntVar(&(cf.LogLevel), "log_level", defaultLogLevel, help)
-
- help = fmt.Sprintf("Show startup banner log lines")
- flag.BoolVar(&cf.Banner, "banner", defaultBanner, help)
-
- help = fmt.Sprintf("Show version information and exit")
- flag.BoolVar(&cf.DisplayVersionOnly, "version", defaultDisplayVersionOnly, help)
-
- help = fmt.Sprintf("The address on which to listen to answer liveness and readiness probe queries over HTTP.")
- flag.StringVar(&(cf.ProbeHost), "probe_host", defaultProbeHost, help)
-
- help = fmt.Sprintf("The port on which to listen to answer liveness and readiness probe queries over HTTP.")
- flag.IntVar(&(cf.ProbePort), "probe_port", defaultProbePort, help)
-
- help = fmt.Sprintf("Time interval between liveness probes while in a live state")
- flag.DurationVar(&(cf.LiveProbeInterval), "live_probe_interval", defaultLiveProbeInterval, help)
-
- help = fmt.Sprintf("Time interval between liveness probes while in a not live state")
- flag.DurationVar(&(cf.NotLiveProbeInterval), "not_live_probe_interval", defaultNotLiveProbeInterval, help)
-
- help = fmt.Sprintf("The maximum time the core will wait while attempting to connect to a dependent component duration")
- flag.DurationVar(&(cf.CoreTimeout), "core_timeout", defaultCoreTimeout, help)
-
- help = fmt.Sprintf("The number of retries to connect to a dependent component")
- flag.IntVar(&(cf.MaxConnectionRetries), "max_connection_retries", defaultMaxConnectionRetries, help)
-
- help = fmt.Sprintf("The duration between each connection retry attempt ")
- flag.DurationVar(&(cf.ConnectionRetryInterval), "connection_retry_interval", defaultConnectionRetryInterval, help)
-
- flag.Parse()
-
- containerName := getContainerInfo()
- if len(containerName) > 0 {
- cf.InstanceID = containerName
- }
-
-}
-
-func getContainerInfo() string {
- return os.Getenv("HOSTNAME")
-}
diff --git a/ro_core/config/config_test.go b/ro_core/config/config_test.go
deleted file mode 100644
index fb03cbb..0000000
--- a/ro_core/config/config_test.go
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package config
-
-import (
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/stretchr/testify/assert"
- "os"
- "testing"
-)
-
-const (
- /*
- * This sets the LogLevel of the Voltha logger. It's pinned to FatalLevel here, as we
- * generally don't want to see logger output, even when running go test in verbose
- * mode. Even "Error" level messages are expected to be output by some unit tests.
- *
- * If you are developing a unit test, and experiencing problems or wish additional
- * debugging from Voltha, then changing this constant to log.DebugLevel may be
- * useful.
- */
-
- VOLTHALogLevel = log.FatalLevel
-)
-
-func localInit() {
-
- // Logger must be configured or bad things happen
- _, err := log.SetDefaultLogger(log.JSON, VOLTHALogLevel, log.Fields{"instanceId": 1})
- if err != nil {
- panic(err)
- }
-}
-
-func checkConfigFlags(t *testing.T, cf *ROCoreFlags) {
-
- if cf.ROCoreEndpoint != defaultROCoreEndpoint {
- t.Errorf("ROCoreEndpoint want %s, got %s", defaultROCoreEndpoint, cf.ROCoreEndpoint)
- }
- if cf.GrpcHost != defaultGrpcHost {
- t.Errorf("GrpcHost want %s, got %s", defaultGrpcHost, cf.GrpcHost)
- }
- if cf.GrpcPort != defaultGrpcPort {
- t.Errorf("GrpcPort want %d, got %d", defaultGrpcPort, cf.GrpcPort)
- }
- if cf.KVStoreType != defaultKVStoreType {
- t.Errorf("KVStoreType want %s, got %s", defaultKVStoreType, cf.KVStoreType)
- }
- if cf.KVStoreTimeout != defaultKVStoreTimeout {
- t.Errorf("KVStoreTimeout want %d, got %d", defaultKVStoreTimeout, cf.KVStoreTimeout)
- }
- if cf.KVStoreHost != defaultKVStoreHost {
- t.Errorf("KVStoreHost want %s, got %s", defaultKVStoreHost, cf.KVStoreHost)
- }
- if cf.KVStorePort != defaultKVStorePort {
- t.Errorf("KVStorePort want %d, got %d", defaultKVStorePort, cf.KVStorePort)
- }
- if cf.KVTxnKeyDelTime != defaultKVTxnKeyDelTime {
- t.Errorf("KVTxnKeyDelTime want %d, got %d", defaultKVTxnKeyDelTime, cf.KVTxnKeyDelTime)
- }
- if cf.CoreTopic != defaultCoreTopic {
- t.Errorf("CoreTopic want %s, got %s", defaultCoreTopic, cf.CoreTopic)
- }
- if cf.LogLevel != defaultLogLevel {
- t.Errorf("LogLevel want %d, got %d", defaultLogLevel, cf.LogLevel)
- }
- if cf.Banner != defaultBanner {
- t.Errorf("Banner want %v, got %v", defaultBanner, cf.Banner)
- }
- if cf.DisplayVersionOnly != defaultDisplayVersionOnly {
- t.Errorf("DisplayVersionOnly want %v, got %v", defaultDisplayVersionOnly, cf.DisplayVersionOnly)
- }
- if cf.ROCoreKey != defaultROCoreKey {
- t.Errorf("ROCoreKey want %s, got %s", defaultROCoreKey, cf.ROCoreKey)
- }
- if cf.ROCoreCert != defaultROCoreCert {
- t.Errorf("ROCoreCert want %s, got %s", defaultROCoreCert, cf.ROCoreCert)
- }
- if cf.ROCoreCA != defaultROCoreCA {
- t.Errorf("ROCoreCA want %s, got %s", defaultROCoreCA, cf.ROCoreCA)
- }
- if cf.AffinityRouterTopic != defaultAffinityRouterTopic {
- t.Errorf("AffinityRouterTopic want %s, got %s", defaultAffinityRouterTopic, cf.AffinityRouterTopic)
- }
- if cf.ProbeHost != defaultProbeHost {
- t.Errorf("ProbeHost want %s, got %s", defaultProbeHost, cf.ProbeHost)
- }
- if cf.ProbePort != defaultProbePort {
- t.Errorf("ProbePort want %d, got %d", defaultProbePort, cf.ProbePort)
- }
-}
-
-func TestNewROCoreFlags(t *testing.T) {
- localInit()
-
- var testStr string
-
- configFlags := NewROCoreFlags()
- assert.NotNil(t, configFlags)
-
- configFlags.ParseCommandArguments()
- checkConfigFlags(t, configFlags)
-
- seErr := os.Setenv("HOSTNAME", "PC-4")
- if seErr == nil {
- testStr = getContainerInfo()
- assert.NotNil(t, testStr)
- t.Logf("hostname: %s \n", testStr)
- if testStr != "PC-4" {
- t.Errorf("getContainerInfo failed. want: %s, got: %s", "PC-3", testStr)
- }
- } else {
- testStr = getContainerInfo()
- assert.NotNil(t, testStr)
- }
-}
diff --git a/ro_core/core/common_test.go b/ro_core/core/common_test.go
deleted file mode 100644
index 44f8d65..0000000
--- a/ro_core/core/common_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
-)
-
-const (
- /*
- * This sets the LogLevel of the Voltha logger. It's pinned to FatalLevel here, as we
- * generally don't want to see logger output, even when running go test in verbose
- * mode. Even "Error" level messages are expected to be output by some unit tests.
- *
- * If you are developing a unit test, and experiencing problems or wish additional
- * debugging from Voltha, then changing this constant to log.DebugLevel may be
- * useful.
- */
-
- VolthaLogLevel = log.FatalLevel
-)
-
-// Unit test initialization. This init() function handles all unit tests in
-// the current directory.
-func init() {
- // Logger must be configured or bad things happen
- _, err := log.SetDefaultLogger(log.JSON, VolthaLogLevel, log.Fields{"instanceID": 1})
- if err != nil {
- panic(err)
- }
-}
diff --git a/ro_core/core/core.go b/ro_core/core/core.go
deleted file mode 100644
index 2a20784..0000000
--- a/ro_core/core/core.go
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package core
-
-import (
- "context"
- "fmt"
-
- "time"
-
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-go/ro_core/config"
- "github.com/opencord/voltha-lib-go/v3/pkg/db"
- "github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore"
- grpcserver "github.com/opencord/voltha-lib-go/v3/pkg/grpc"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-lib-go/v3/pkg/probe"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "google.golang.org/grpc"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-)
-
-// Core holds all information of read only core service
-type Core struct {
- instanceID string
- genericMgr *ModelProxyManager
- deviceMgr *DeviceManager
- logicalDeviceMgr *LogicalDeviceManager
- grpcServer *grpcserver.GrpcServer
- grpcNBIAPIHandler *APIHandler
- config *config.ROCoreFlags
- clusterDataRoot model.Root
- localDataRoot model.Root
- clusterDataProxy *model.Proxy
- localDataProxy *model.Proxy
- exitChannel chan int
- kvClient kvstore.Client
- backend db.Backend
-}
-
-func init() {
- _, err := log.AddPackage(log.JSON, log.DebugLevel, nil)
- if err != nil {
- log.Errorw("unable-to-register-package-to-the-log-map", log.Fields{"error": err})
- }
-}
-
-// NewCore instantiates core service parameters
-func NewCore(ctx context.Context, id string, cf *config.ROCoreFlags, kvClient kvstore.Client) *Core {
- var core Core
- core.instanceID = id
- core.exitChannel = make(chan int, 1)
- core.config = cf
- core.kvClient = kvClient
-
- // Configure backend to push Liveness Status at least every cf.LiveProbeInterval / 2 seconds
- // so as to avoid trigger of Liveness check (due to Liveness timeout) when backend is alive
- livenessChannelInterval := cf.LiveProbeInterval / 2
-
- // Setup the KV store
- // Do not call NewBackend constructor; it creates its own KV client
- // Commented the backend for now until the issue between the model and the KV store
- // is resolved.
- core.backend = db.Backend{
- Client: kvClient,
- StoreType: cf.KVStoreType,
- Host: cf.KVStoreHost,
- Port: cf.KVStorePort,
- Timeout: cf.KVStoreTimeout,
- LivenessChannelInterval: livenessChannelInterval,
- PathPrefix: "service/voltha"}
- core.clusterDataRoot = model.NewRoot(&voltha.Voltha{}, &core.backend)
- core.localDataRoot = model.NewRoot(&voltha.CoreInstance{}, &core.backend)
-
- return &core
-}
-
-// waitUntilKVStoreReachableOrMaxTries will wait until it can connect to a KV store or until maxtries has been reached
-func (core *Core) waitUntilKVStoreReachableOrMaxTries(ctx context.Context, maxRetries int, retryInterval time.Duration) error {
- log.Infow("verifying-KV-store-connectivity", log.Fields{"host": core.config.KVStoreHost,
- "port": core.config.KVStorePort, "retries": maxRetries, "retryInterval": retryInterval})
-
- // Get timeout in seconds with 1 second set as minimum
- timeout := int(core.config.CoreTimeout.Seconds())
- if timeout < 1 {
- timeout = 1
- }
- count := 0
- for {
- if !core.kvClient.IsConnectionUp(timeout) {
- log.Info("KV-store-unreachable")
- if maxRetries != -1 {
- if count >= maxRetries {
- return status.Error(codes.Unavailable, "kv store unreachable")
- }
- }
- count++
- // Take a nap before retrying
- time.Sleep(retryInterval)
- log.Infow("retry-KV-store-connectivity", log.Fields{"retryCount": count, "maxRetries": maxRetries, "retryInterval": retryInterval})
-
- } else {
- break
- }
- }
- log.Info("KV-store-reachable")
- return nil
-}
-
-// Start will start core adapter services
-func (core *Core) Start(ctx context.Context) error {
- var err error
- log.Info("starting-adaptercore", log.Fields{"coreId": core.instanceID})
-
- // Wait until connection to KV Store is up
- if err := core.waitUntilKVStoreReachableOrMaxTries(ctx, core.config.MaxConnectionRetries, core.config.ConnectionRetryInterval); err != nil {
- log.Fatal("Unable-to-connect-to-KV-store")
- }
-
- probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusRunning)
-
- core.clusterDataProxy, err = core.clusterDataRoot.CreateProxy(context.Background(), "/", false)
- if err != nil {
- probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusNotReady)
- return fmt.Errorf("Failed to create cluster data proxy")
- }
- core.localDataProxy, err = core.localDataRoot.CreateProxy(context.Background(), "/", false)
- if err != nil {
- probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusNotReady)
- return fmt.Errorf("Failed to create local cluster data proxy")
- }
- core.genericMgr = newModelProxyManager(core.clusterDataProxy)
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
- core.logicalDeviceMgr = newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- go core.startDeviceManager(ctx)
- go core.startLogicalDeviceManager(ctx)
- go core.startGRPCService(ctx)
- go core.monitorKvstoreLiveness(ctx)
-
- log.Info("adaptercore-started")
- return nil
-}
-
-// Stop will stop core services
-func (core *Core) Stop(ctx context.Context) {
- log.Info("stopping-adaptercore")
- if core.exitChannel != nil {
- core.exitChannel <- 1
- }
- // Stop all the started services
- if core.grpcServer != nil {
- core.grpcServer.Stop()
- }
- if core.logicalDeviceMgr != nil {
- core.logicalDeviceMgr.stop(ctx)
- }
- if core.deviceMgr != nil {
- core.deviceMgr.stop(ctx)
- }
- log.Info("adaptercore-stopped")
-}
-
-//startGRPCService creates the grpc service handlers, registers it to the grpc server
-// and starts the server
-func (core *Core) startGRPCService(ctx context.Context) {
- // create an insecure gserver server
- core.grpcServer = grpcserver.NewGrpcServer(core.config.GrpcHost, core.config.GrpcPort, nil, false, probe.GetProbeFromContext(ctx))
- log.Info("grpc-server-created")
-
- core.grpcNBIAPIHandler = NewAPIHandler(core.genericMgr, core.deviceMgr, core.logicalDeviceMgr)
- core.logicalDeviceMgr.setGrpcNbiHandler(core.grpcNBIAPIHandler)
- // Create a function to register the core GRPC service with the GRPC server
- f := func(gs *grpc.Server) {
- voltha.RegisterVolthaServiceServer(
- gs,
- core.grpcNBIAPIHandler,
- )
- }
-
- core.grpcServer.AddService(f)
- log.Info("grpc-service-added")
-
- /*
- * Start the GRPC server
- *
- * This is a bit sub-optimal here as the grpcServer.Start call does not return (blocks)
- * until something fails, but we want to send a "start" status update. As written this
- * means that we are actually sending the "start" status update before the server is
- * started, which means it is possible that the status is "running" before it actually is.
- *
- * This means that there is a small window in which the core could return its status as
- * ready, when it really isn't.
- */
- probe.UpdateStatusFromContext(ctx, "grpc-service", probe.ServiceStatusRunning)
-
- // Start the server
- log.Info("grpc-server-started")
- core.grpcServer.Start(context.Background())
-
- probe.UpdateStatusFromContext(ctx, "grpc-service", probe.ServiceStatusStopped)
-}
-
-func (core *Core) startDeviceManager(ctx context.Context) {
- // TODO: Interaction between the logicaldevicemanager and devicemanager should mostly occur via
- // callbacks. For now, until the model is ready, devicemanager will keep a reference to the
- // logicaldevicemanager to initiate the creation of logical devices
- log.Info("starting-DeviceManager")
- core.deviceMgr.start(ctx, core.logicalDeviceMgr)
- log.Info("started-DeviceManager")
-}
-
-func (core *Core) startLogicalDeviceManager(ctx context.Context) {
- log.Info("starting-Logical-DeviceManager")
- core.logicalDeviceMgr.start(ctx)
- log.Info("started-Logical-DeviceManager")
-}
-
-/*
-* Thread to monitor kvstore Liveness (connection status)
-*
-* This function constantly monitors Liveness State of kvstore as reported
-* periodically by backend and updates the Status of kv-store service registered
-* with ro_core probe.
-*
-* If no liveness event has been seen within a timeout, then the thread will make
-* an trigger a "liveness" check, which will in turn trigger a liveness event on
-* the liveness channel, true or false depending on whether the attempt succeeded.
-*
-* The gRPC server in turn monitors the state of the readiness probe and will
-* start issuing UNAVAILABLE response while the probe is not ready.
- */
-func (core *Core) monitorKvstoreLiveness(ctx context.Context) {
- log.Info("start-monitoring-kvstore-liveness")
-
- // Instruct backend to create Liveness channel for transporting state updates
- livenessChannel := core.backend.EnableLivenessChannel()
-
- log.Debug("enabled-kvstore-liveness-channel")
-
- // Default state for kvstore is not alive
- timeout := core.config.NotLiveProbeInterval
- for {
- timeoutTimer := time.NewTimer(timeout)
- select {
-
- case liveness := <-livenessChannel:
- log.Debugw("received-liveness-change-notification", log.Fields{"liveness": liveness})
-
- if !liveness {
- probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusNotReady)
-
- if core.grpcServer != nil {
- log.Info("kvstore-set-server-notready")
- }
-
- timeout = core.config.NotLiveProbeInterval
- } else {
- probe.UpdateStatusFromContext(ctx, "kv-store", probe.ServiceStatusRunning)
-
- if core.grpcServer != nil {
- log.Info("kvstore-set-server-ready")
- }
-
- timeout = core.config.LiveProbeInterval
- }
-
- if !timeoutTimer.Stop() {
- <-timeoutTimer.C
- }
-
- case <-timeoutTimer.C:
- log.Info("kvstore-perform-liveness-check-on-timeout")
-
- // Trigger Liveness check if no liveness update received within the timeout period.
- // The Liveness check will push Live state to same channel which this routine is
- // reading and processing. This, do it asynchronously to avoid blocking for
- // backend response and avoid any possibility of deadlock
- go core.backend.PerformLivenessCheck(core.config.KVStoreTimeout)
- }
- }
-}
diff --git a/ro_core/core/core_test.go b/ro_core/core/core_test.go
deleted file mode 100644
index 5af1048..0000000
--- a/ro_core/core/core_test.go
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "context"
- "errors"
- "fmt"
- "testing"
-
- "github.com/opencord/voltha-go/ro_core/config"
- "github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-lib-go/v3/pkg/mocks"
- ic "github.com/opencord/voltha-protos/v3/go/inter_container"
- "github.com/phayes/freeport"
- "github.com/stretchr/testify/assert"
-)
-
-type roCore struct {
- kvClient kvstore.Client
- config *config.ROCoreFlags
- halted bool
- exitChannel chan int
- //For test
- receiverChannels []<-chan *ic.InterContainerMessage
-}
-
-func newROCore(cf *config.ROCoreFlags) *roCore {
- var roCoreV roCore
- roCoreV.config = cf
- roCoreV.halted = false
- roCoreV.exitChannel = make(chan int, 1)
- roCoreV.receiverChannels = make([]<-chan *ic.InterContainerMessage, 0)
- return &roCoreV
-}
-
-func newKVClient(storeType string, address string, timeout int) (kvstore.Client, error) {
-
- log.Infow("kv-store-type", log.Fields{"store": storeType})
- switch storeType {
- case "consul":
- return kvstore.NewConsulClient(address, timeout)
- case "etcd":
- return kvstore.NewEtcdClient(address, timeout)
- }
- return nil, errors.New("unsupported-kv-store")
-}
-
-func makeTestNewCore() (*config.ROCoreFlags, *roCore) {
-
- clientPort, err := freeport.GetFreePort()
- if err == nil {
- peerPort, err := freeport.GetFreePort()
- if err != nil {
- log.Fatal(err)
- }
- etcdServer := mocks.StartEtcdServer(mocks.MKConfig("voltha.mock.test", clientPort, peerPort, "voltha.lib.mocks.etcd", "error"))
- if etcdServer == nil {
- log.Fatal("Embedded server failed to start")
- }
- clientAddr := fmt.Sprintf("localhost:%d", clientPort)
-
- roCoreFlgs := config.NewROCoreFlags()
- roC := newROCore(roCoreFlgs)
- if (roC != nil) && (roCoreFlgs != nil) {
- cli, err := newKVClient("etcd", clientAddr, 5)
- if err == nil {
- roC.kvClient = cli
- return roCoreFlgs, roC
- }
- etcdServer.Stop()
- log.Fatal("Failed to create an Etcd client")
- }
- }
- return nil, nil
-}
-
-func TestNewCore(t *testing.T) {
-
- var ctx context.Context
-
- roCoreFlgs, roC := makeTestNewCore()
- assert.NotNil(t, roCoreFlgs)
- assert.NotNil(t, roC)
- core := NewCore(ctx, "ro_core", roCoreFlgs, roC.kvClient)
- assert.NotNil(t, core)
-}
-
-func TestNewCoreStartStop(t *testing.T) {
-
- var ctx context.Context
-
- roCoreFlgs, roC := makeTestNewCore()
- assert.NotNil(t, roCoreFlgs)
- assert.NotNil(t, roC)
- core := NewCore(ctx, "ro_core", roCoreFlgs, roC.kvClient)
- assert.NotNil(t, core)
-
- err := core.Start(ctx)
- assert.Nil(t, err)
- core.Stop(ctx)
-}
diff --git a/ro_core/core/device_agent.go b/ro_core/core/device_agent.go
deleted file mode 100644
index 109d060..0000000
--- a/ro_core/core/device_agent.go
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package core
-
-import (
- "context"
- "sync"
-
- "github.com/gogo/protobuf/proto"
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-)
-
-// DeviceAgent holds device specific information
-type DeviceAgent struct {
- deviceID string
- deviceType string
- lastData *voltha.Device
- deviceMgr *DeviceManager
- clusterDataProxy *model.Proxy
- exitChannel chan int
- lockDevice sync.RWMutex
-}
-
-//newDeviceAgent creates a new device agent along as creating a unique ID for the device and set the device state to
-//preprovisioning
-func newDeviceAgent(device *voltha.Device, deviceMgr *DeviceManager, cdProxy *model.Proxy) *DeviceAgent {
- var agent DeviceAgent
- agent.deviceID = device.Id
- agent.deviceType = device.Type
- agent.lastData = device
- agent.deviceMgr = deviceMgr
- agent.exitChannel = make(chan int, 1)
- agent.clusterDataProxy = cdProxy
- agent.lockDevice = sync.RWMutex{}
- return &agent
-}
-
-// start save the device to the data model and registers for callbacks on that device
-func (agent *DeviceAgent) start(ctx context.Context, loadFromDb bool) error {
- agent.lockDevice.Lock()
- defer agent.lockDevice.Unlock()
- log.Debugw("starting-device-agent", log.Fields{"device": agent.lastData})
- if loadFromDb {
- if device, err := agent.clusterDataProxy.Get(ctx, "/devices/"+agent.deviceID, 0, false, ""); err != nil {
- log.Errorw("failed-to-get-device", log.Fields{"error": err})
- return err
- } else if device != nil {
- if d, ok := device.(*voltha.Device); ok {
- agent.lastData = proto.Clone(d).(*voltha.Device)
- }
- } else {
- log.Errorw("failed-to-load-device", log.Fields{"deviceID": agent.deviceID})
- return status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
- }
- log.Debugw("device-loaded-from-dB", log.Fields{"device": agent.lastData})
- }
- log.Debug("device-agent-started")
- return nil
-}
-
-// stop stops the device agent. Not much to do for now
-func (agent *DeviceAgent) stop(ctx context.Context) {
- agent.lockDevice.Lock()
- defer agent.lockDevice.Unlock()
- log.Debug("stopping-device-agent")
- agent.exitChannel <- 1
- log.Debug("device-agent-stopped")
-}
-
-// GetDevice retrieves the latest device information from the data model
-func (agent *DeviceAgent) getDevice() (*voltha.Device, error) {
- agent.lockDevice.Lock()
- defer agent.lockDevice.Unlock()
- if device, err := agent.clusterDataProxy.Get(context.Background(), "/devices/"+agent.deviceID, 0, false, ""); err != nil {
- log.Errorw("failed-to-get-device", log.Fields{"error": err})
- return nil, err
- } else if device != nil {
- if d, ok := device.(*voltha.Device); ok {
- cloned := proto.Clone(d).(*voltha.Device)
- return cloned, nil
- }
- }
- return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
-}
-
-// ListDevicePorts retrieves the ports information for a particular device.
-func (agent *DeviceAgent) ListDevicePorts(ctx context.Context) (*voltha.Ports, error) {
- log.Debugw("ListDevicePorts", log.Fields{"id": agent.deviceID})
- ports := &voltha.Ports{}
- if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
- ports.Items = append(ports.Items, device.GetPorts()...)
- return ports, nil
- }
- return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
-}
-
-// ListDevicePmConfigs retrieves the ports information for a particular device.
-func (agent *DeviceAgent) ListDevicePmConfigs(ctx context.Context) (*voltha.PmConfigs, error) {
- log.Debugw("ListDevicePmConfigs", log.Fields{"id": agent.deviceID})
- if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
- return device.GetPmConfigs(), nil
- }
- return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
-}
-
-// ListDeviceFlows retrieves the ports information for a particular device.
-func (agent *DeviceAgent) ListDeviceFlows(ctx context.Context) (*voltha.Flows, error) {
- log.Debugw("ListDeviceFlows", log.Fields{"id": agent.deviceID})
- if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
- return device.GetFlows(), nil
- }
- return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
-}
-
-// ListDeviceFlowGroups retrieves the ports information for a particular device.
-func (agent *DeviceAgent) ListDeviceFlowGroups(ctx context.Context) (*voltha.FlowGroups, error) {
- log.Debugw("ListDeviceFlowGroups", log.Fields{"id": agent.deviceID})
- if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
- return device.GetFlowGroups(), nil
- }
- return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
-}
-
-// GetImageDownloadStatus retrieves the download status of an image of a particular device.
-func (agent *DeviceAgent) GetImageDownloadStatus(ctx context.Context, imageName string) (*voltha.ImageDownload, error) {
- log.Debugw("GetImageDownloadStatus", log.Fields{"id": agent.deviceID})
- if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
- for _, img := range device.GetImageDownloads() {
- if img.GetName() == imageName {
- return img, nil
- }
- }
- return nil, status.Errorf(codes.NotFound, "device-%s, image-%s", agent.deviceID, imageName)
- }
- return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
-}
-
-// GetImageDownload retrieves the image download for a particular device.
-func (agent *DeviceAgent) GetImageDownload(ctx context.Context, imageName string) (*voltha.ImageDownload, error) {
- log.Debugw("GetImageDownload", log.Fields{"id": agent.deviceID})
- if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
- for _, img := range device.GetImageDownloads() {
- if img.GetName() == imageName {
- return img, nil
- }
- }
- return nil, status.Errorf(codes.NotFound, "device-%s, image-%s", agent.deviceID, imageName)
- }
- return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
-}
-
-// ListImageDownloads retrieves the image downloads for a particular device.
-func (agent *DeviceAgent) ListImageDownloads(ctx context.Context) (*voltha.ImageDownloads, error) {
- log.Debugw("ListImageDownloads", log.Fields{"id": agent.deviceID})
- if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
- return &voltha.ImageDownloads{Items: device.GetImageDownloads()}, nil
- }
- return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
-}
-
-// GetImages retrieves the list of images for a particular device.
-func (agent *DeviceAgent) GetImages(ctx context.Context) (*voltha.Images, error) {
- log.Debugw("GetImages", log.Fields{"id": agent.deviceID})
- if device, _ := agent.deviceMgr.GetDevice(agent.deviceID); device != nil {
- return device.GetImages(), nil
- }
- return nil, status.Errorf(codes.NotFound, "device-%s", agent.deviceID)
-}
diff --git a/ro_core/core/device_agent_test.go b/ro_core/core/device_agent_test.go
deleted file mode 100644
index 9634408..0000000
--- a/ro_core/core/device_agent_test.go
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "testing"
-
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-go/ro_core/config"
- "github.com/opencord/voltha-lib-go/v3/pkg/db"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "github.com/stretchr/testify/assert"
-)
-
-func TestNewDeviceAgent(t *testing.T) {
-
- var core Core
- core.instanceID = "ro_core"
- core.config = config.NewROCoreFlags()
- backend := db.Backend{
- Client: core.kvClient,
- StoreType: core.config.KVStoreType,
- Host: core.config.KVStoreHost,
- Port: core.config.KVStorePort,
- Timeout: core.config.KVStoreTimeout,
- PathPrefix: "service/voltha"}
- core.clusterDataRoot = model.NewRoot(&voltha.Voltha{}, &backend)
- core.genericMgr = newModelProxyManager(core.clusterDataProxy)
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
-
- devAgent := newDeviceAgent(&voltha.Device{Id: "new_device"}, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, devAgent)
-
-}
diff --git a/ro_core/core/device_manager.go b/ro_core/core/device_manager.go
deleted file mode 100644
index aaa4a73..0000000
--- a/ro_core/core/device_manager.go
+++ /dev/null
@@ -1,389 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package core
-
-import (
- "context"
- "sync"
-
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-lib-go/v3/pkg/probe"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-)
-
-// DeviceManager represents device manager related information
-type DeviceManager struct {
- deviceAgents sync.Map
- logicalDeviceMgr *LogicalDeviceManager
- clusterDataProxy *model.Proxy
- coreInstanceID string
- exitChannel chan int
-}
-
-func newDeviceManager(cdProxy *model.Proxy, coreInstanceID string) *DeviceManager {
- var deviceMgr DeviceManager
- deviceMgr.exitChannel = make(chan int, 1)
- deviceMgr.coreInstanceID = coreInstanceID
- deviceMgr.clusterDataProxy = cdProxy
- return &deviceMgr
-}
-
-func (dMgr *DeviceManager) start(ctx context.Context, logicalDeviceMgr *LogicalDeviceManager) {
- log.Info("starting-device-manager")
- dMgr.logicalDeviceMgr = logicalDeviceMgr
- probe.UpdateStatusFromContext(ctx, "device-manager", probe.ServiceStatusRunning)
- log.Info("device-manager-started")
-}
-
-func (dMgr *DeviceManager) stop(ctx context.Context) {
- log.Info("stopping-device-manager")
- dMgr.exitChannel <- 1
- probe.UpdateStatusFromContext(ctx, "device-manager", probe.ServiceStatusStopped)
- log.Info("device-manager-stopped")
-}
-
-func sendResponse(ctx context.Context, ch chan interface{}, result interface{}) {
- if ctx.Err() == nil {
- // Returned response only of the ctx has not been cancelled/timeout/etc
- // Channel is automatically closed when a context is Done
- ch <- result
- log.Debugw("sendResponse", log.Fields{"result": result})
- } else {
- // Should the transaction be reverted back?
- log.Debugw("sendResponse-context-error", log.Fields{"context-error": ctx.Err()})
- }
-}
-
-func (dMgr *DeviceManager) addDeviceAgentToMap(agent *DeviceAgent) {
- if _, exist := dMgr.deviceAgents.Load(agent.deviceID); !exist {
- dMgr.deviceAgents.Store(agent.deviceID, agent)
- }
-}
-
-func (dMgr *DeviceManager) deleteDeviceAgentToMap(agent *DeviceAgent) {
- dMgr.deviceAgents.Delete(agent.deviceID)
-}
-
-func (dMgr *DeviceManager) getDeviceAgent(deviceID string) *DeviceAgent {
- if agent, ok := dMgr.deviceAgents.Load(deviceID); ok {
- return agent.(*DeviceAgent)
- }
- // Try to load into memory - loading will also create the device agent
- if err := dMgr.load(deviceID); err == nil {
- if agent, ok := dMgr.deviceAgents.Load(deviceID); ok {
- return agent.(*DeviceAgent)
- }
- }
- return nil
-}
-
-// listDeviceIDsFromMap returns the list of device IDs that are in memory
-func (dMgr *DeviceManager) listDeviceIDsFromMap() *voltha.IDs {
- result := &voltha.IDs{Items: make([]*voltha.ID, 0)}
- dMgr.deviceAgents.Range(func(key, value interface{}) bool {
- result.Items = append(result.Items, &voltha.ID{Id: key.(string)})
- return true
- })
- return result
-}
-
-// GetDevice will returns a device, either from memory or from the dB, if present
-func (dMgr *DeviceManager) GetDevice(id string) (*voltha.Device, error) {
- log.Debugw("GetDevice", log.Fields{"deviceid": id})
- if agent := dMgr.getDeviceAgent(id); agent != nil {
- return agent.getDevice()
- }
- return nil, status.Errorf(codes.NotFound, "%s", id)
-}
-
-// IsDeviceInCache returns true if device exists in cache
-func (dMgr *DeviceManager) IsDeviceInCache(id string) bool {
- _, exist := dMgr.deviceAgents.Load(id)
- return exist
-}
-
-// IsRootDevice returns true if root device is present in either memory or db
-func (dMgr *DeviceManager) IsRootDevice(id string) (bool, error) {
- device, err := dMgr.GetDevice(id)
- if err != nil {
- return false, err
- }
- return device.Root, nil
-}
-
-// ListDevices retrieves the latest devices from the data model
-func (dMgr *DeviceManager) ListDevices() (*voltha.Devices, error) {
- log.Debug("ListDevices")
- result := &voltha.Devices{}
- if devices, err := dMgr.clusterDataProxy.List(context.Background(), "/devices", 0, false, ""); err != nil {
- log.Errorw("failed-to-list-devices", log.Fields{"error": err})
- return nil, err
- } else if devices != nil {
- for _, device := range devices.([]interface{}) {
- // If device is not in memory then set it up
- if !dMgr.IsDeviceInCache(device.(*voltha.Device).Id) {
- agent := newDeviceAgent(device.(*voltha.Device), dMgr, dMgr.clusterDataProxy)
- if err := agent.start(context.TODO(), true); err != nil {
- log.Warnw("failure-starting-agent", log.Fields{"deviceID": device.(*voltha.Device).Id})
- agent.stop(context.TODO())
- } else {
- dMgr.addDeviceAgentToMap(agent)
- }
- }
- result.Items = append(result.Items, device.(*voltha.Device))
- }
- }
- return result, nil
-}
-
-// loadDevice loads the deviceID in memory, if not present
-func (dMgr *DeviceManager) loadDevice(deviceID string) (*DeviceAgent, error) {
- log.Debugw("loading-device", log.Fields{"deviceID": deviceID})
- // Sanity check
- if deviceID == "" {
- return nil, status.Error(codes.InvalidArgument, "deviceID empty")
- }
- if !dMgr.IsDeviceInCache(deviceID) {
- agent := newDeviceAgent(&voltha.Device{Id: deviceID}, dMgr, dMgr.clusterDataProxy)
- if err := agent.start(context.TODO(), true); err != nil {
- agent.stop(context.TODO())
- return nil, err
- }
- dMgr.addDeviceAgentToMap(agent)
- }
- if agent := dMgr.getDeviceAgent(deviceID); agent != nil {
- return agent, nil
- }
- return nil, status.Error(codes.NotFound, deviceID) // This should nto happen
-}
-
-// loadRootDeviceParentAndChildren loads the children and parents of a root device in memory
-func (dMgr *DeviceManager) loadRootDeviceParentAndChildren(device *voltha.Device) error {
- log.Debugw("loading-parent-and-children", log.Fields{"deviceID": device.Id})
- if device.Root {
- // Scenario A
- if device.ParentId != "" {
- // Load logical device if needed.
- if err := dMgr.logicalDeviceMgr.load(device.ParentId); err != nil {
- log.Warnw("failure-loading-logical-device", log.Fields{"lDeviceID": device.ParentId})
- }
- } else {
- log.Debugw("no-parent-to-load", log.Fields{"deviceID": device.Id})
- }
- // Load all child devices, if needed
- if childDeviceIDs, err := dMgr.getAllChildDeviceIDs(device); err == nil {
- for _, childDeviceID := range childDeviceIDs {
- if _, err := dMgr.loadDevice(childDeviceID); err != nil {
- log.Warnw("failure-loading-device", log.Fields{"deviceID": childDeviceID})
- return err
- }
- }
- log.Debugw("loaded-children", log.Fields{"deviceID": device.Id, "numChildren": len(childDeviceIDs)})
- } else {
- log.Debugw("no-child-to-load", log.Fields{"deviceID": device.Id})
- }
- }
- return nil
-}
-
-// load loads the deviceID in memory, if not present, and also loads its accompanying parents and children. Loading
-// in memory is for improved performance. It is not imperative that a device needs to be in memory when a request
-// acting on the device is received by the core. In such a scenario, the Core will load the device in memory first
-// and the proceed with the request.
-func (dMgr *DeviceManager) load(deviceID string) error {
- log.Debug("load...")
- // First load the device - this may fail in case the device was deleted intentionally by the other core
- var dAgent *DeviceAgent
- var err error
- if dAgent, err = dMgr.loadDevice(deviceID); err != nil {
- log.Warnw("failure-loading-device", log.Fields{"deviceID": deviceID})
- return err
- }
- // Get the loaded device details
- var device *voltha.Device
- if device, err = dAgent.getDevice(); err != nil {
- return err
- }
-
- // If the device is in Pre-provisioning or deleted state stop here
- if device.AdminState == voltha.AdminState_PREPROVISIONED || device.AdminState == voltha.AdminState_DELETED {
- return nil
- }
-
- // Now we face two scenarios
- if device.Root {
- // Load all children as well as the parent of this device (logical_device)
- if err := dMgr.loadRootDeviceParentAndChildren(device); err != nil {
- log.Warnw("failure-loading-device-parent-and-children", log.Fields{"deviceID": deviceID})
- return err
- }
- log.Debugw("successfully-loaded-parent-and-children", log.Fields{"deviceID": deviceID})
- } else {
- // Scenario B - use the parentID of that device (root device) to trigger the loading
- if device.ParentId != "" {
- return dMgr.load(device.ParentId)
- }
- }
- return nil
-}
-
-// ListDeviceIDs retrieves the latest device IDs information from the data model (memory data only)
-func (dMgr *DeviceManager) ListDeviceIDs() (*voltha.IDs, error) {
- log.Debug("ListDeviceIDs")
- // Report only device IDs that are in the device agent map
- return dMgr.listDeviceIDsFromMap(), nil
-}
-
-//ReconcileDevices is a request to a voltha core to managed a list of devices based on their IDs
-func (dMgr *DeviceManager) ReconcileDevices(ctx context.Context, ids *voltha.IDs, ch chan interface{}) {
- log.Debug("ReconcileDevices")
- var res interface{}
- if ids != nil {
- toReconcile := len(ids.Items)
- reconciled := 0
- for _, id := range ids.Items {
- // Act on the device only if its not present in the agent map
- if !dMgr.IsDeviceInCache(id.Id) {
- // Device ID not in memory
- log.Debugw("reconciling-device", log.Fields{"id": id.Id})
- // Load device from dB
- agent := newDeviceAgent(&voltha.Device{Id: id.Id}, dMgr, dMgr.clusterDataProxy)
- if err := agent.start(context.TODO(), true); err != nil {
- log.Warnw("failure-loading-device", log.Fields{"deviceID": id.Id})
- agent.stop(context.TODO())
- } else {
- dMgr.addDeviceAgentToMap(agent)
- reconciled++
- }
- } else {
- reconciled++
- }
- }
- if toReconcile != reconciled {
- res = status.Errorf(codes.DataLoss, "less-device-reconciled:%d/%d", reconciled, toReconcile)
- }
- } else {
- res = status.Errorf(codes.InvalidArgument, "empty-list-of-ids")
- }
- sendResponse(ctx, ch, res)
-}
-
-// ListDevicePorts returns ports details for a specific device
-func (dMgr *DeviceManager) ListDevicePorts(ctx context.Context, deviceID string) (*voltha.Ports, error) {
- log.Debugw("ListDevicePorts", log.Fields{"deviceid": deviceID})
- if agent := dMgr.getDeviceAgent(deviceID); agent != nil {
- return agent.ListDevicePorts(ctx)
- }
- return nil, status.Errorf(codes.NotFound, "%s", deviceID)
-
-}
-
-// ListDevicePmConfigs returns PM config details for a specific device
-func (dMgr *DeviceManager) ListDevicePmConfigs(ctx context.Context, deviceID string) (*voltha.PmConfigs, error) {
- log.Debugw("ListDevicePmConfigs", log.Fields{"deviceid": deviceID})
- if agent := dMgr.getDeviceAgent(deviceID); agent != nil {
- return agent.ListDevicePmConfigs(ctx)
- }
- return nil, status.Errorf(codes.NotFound, "%s", deviceID)
-
-}
-
-// ListDeviceFlows returns flow details for a specific device
-func (dMgr *DeviceManager) ListDeviceFlows(ctx context.Context, deviceID string) (*voltha.Flows, error) {
- log.Debugw("ListDeviceFlows", log.Fields{"deviceid": deviceID})
- if agent := dMgr.getDeviceAgent(deviceID); agent != nil {
- return agent.ListDeviceFlows(ctx)
- }
- return nil, status.Errorf(codes.NotFound, "%s", deviceID)
-}
-
-// ListDeviceFlowGroups returns flow group details for a specific device
-func (dMgr *DeviceManager) ListDeviceFlowGroups(ctx context.Context, deviceID string) (*voltha.FlowGroups, error) {
- log.Debugw("ListDeviceFlowGroups", log.Fields{"deviceid": deviceID})
- if agent := dMgr.getDeviceAgent(deviceID); agent != nil {
- return agent.ListDeviceFlowGroups(ctx)
- }
- return nil, status.Errorf(codes.NotFound, "%s", deviceID)
-
-}
-
-// GetImageDownloadStatus returns the download status of an image of a particular device
-func (dMgr *DeviceManager) GetImageDownloadStatus(ctx context.Context, deviceID string, imageName string) (*voltha.ImageDownload, error) {
- log.Debugw("GetImageDownloadStatus", log.Fields{"deviceid": deviceID, "imagename": imageName})
- if agent := dMgr.getDeviceAgent(deviceID); agent != nil {
- return agent.GetImageDownloadStatus(ctx, imageName)
- }
- return nil, status.Errorf(codes.NotFound, "%s", deviceID)
-
-}
-
-// GetImageDownload return the download details for a specific image entry
-func (dMgr *DeviceManager) GetImageDownload(ctx context.Context, deviceID string, imageName string) (*voltha.ImageDownload, error) {
- log.Debugw("GetImageDownload", log.Fields{"deviceid": deviceID, "imagename": imageName})
- if agent := dMgr.getDeviceAgent(deviceID); agent != nil {
- return agent.GetImageDownload(ctx, imageName)
- }
- return nil, status.Errorf(codes.NotFound, "%s", deviceID)
-
-}
-
-// ListImageDownloads returns all image downloads known to the system
-func (dMgr *DeviceManager) ListImageDownloads(ctx context.Context, deviceID string) (*voltha.ImageDownloads, error) {
- log.Debugw("ListImageDownloads", log.Fields{"deviceid": deviceID})
- if agent := dMgr.getDeviceAgent(deviceID); agent != nil {
- return agent.ListImageDownloads(ctx)
- }
- return nil, status.Errorf(codes.NotFound, "%s", deviceID)
-
-}
-
-// GetImages returns all images for a specific device entry
-func (dMgr *DeviceManager) GetImages(ctx context.Context, deviceID string) (*voltha.Images, error) {
- log.Debugw("GetImages", log.Fields{"deviceid": deviceID})
- if agent := dMgr.getDeviceAgent(deviceID); agent != nil {
- return agent.GetImages(ctx)
- }
- return nil, status.Errorf(codes.NotFound, "%s", deviceID)
-
-}
-
-func (dMgr *DeviceManager) getParentDevice(childDevice *voltha.Device) *voltha.Device {
- // Sanity check
- if childDevice.Root {
- // childDevice is the parent device
- return childDevice
- }
- parentDevice, _ := dMgr.GetDevice(childDevice.ParentId)
- return parentDevice
-}
-
-//getAllChildDeviceIDs is a helper method to get all the child device IDs from the device passed as parameter
-func (dMgr *DeviceManager) getAllChildDeviceIDs(parentDevice *voltha.Device) ([]string, error) {
- log.Debugw("getAllChildDeviceIDs", log.Fields{"parentDeviceID": parentDevice.Id})
- childDeviceIDs := make([]string, 0)
- if parentDevice != nil {
- for _, port := range parentDevice.Ports {
- for _, peer := range port.Peers {
- childDeviceIDs = append(childDeviceIDs, peer.DeviceId)
- }
- }
- }
- return childDeviceIDs, nil
-}
diff --git a/ro_core/core/device_manager_test.go b/ro_core/core/device_manager_test.go
deleted file mode 100644
index 510eb45..0000000
--- a/ro_core/core/device_manager_test.go
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "testing"
-
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-go/ro_core/config"
- "github.com/opencord/voltha-lib-go/v3/pkg/db"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "github.com/stretchr/testify/assert"
-)
-
-func MakeTestDevManagerConfig() (*Core, error) {
- var core Core
- core.instanceID = "ro_core"
- core.config = config.NewROCoreFlags()
- backend := db.Backend{
- Client: core.kvClient,
- StoreType: core.config.KVStoreType,
- Host: core.config.KVStoreHost,
- Port: core.config.KVStorePort,
- Timeout: core.config.KVStoreTimeout,
- PathPrefix: "service/voltha"}
- core.clusterDataRoot = model.NewRoot(&voltha.Voltha{}, &backend)
- core.genericMgr = newModelProxyManager(core.clusterDataProxy)
-
- return &core, nil
-}
-func TestNewDeviceManager(t *testing.T) {
-
- core, _ := MakeTestDevManagerConfig()
-
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
- assert.NotNil(t, core.deviceMgr)
-}
-
-func TestListDeviceIds(t *testing.T) {
-
- core, _ := MakeTestDevManagerConfig()
-
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
- assert.NotNil(t, core.deviceMgr)
-
- myIds, _ := core.deviceMgr.ListDeviceIDs()
- assert.NotNil(t, myIds)
-}
-
-func TestGetDeviceAgent(t *testing.T) {
-
- // Tests also methods addDeviceAgentToMap,
- // listDeviceIdsFromMap
- // deleteDeviceAgentToMap
-
- core, _ := MakeTestDevManagerConfig()
-
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
- assert.NotNil(t, core.deviceMgr)
-
- devAgent := newDeviceAgent(&voltha.Device{Id: "new_device"}, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, devAgent)
-
- // addDeviceAgentToMap
- core.deviceMgr.addDeviceAgentToMap(devAgent)
-
- // listDeviceIdsFromMap
- myIDs := core.deviceMgr.listDeviceIDsFromMap()
- assert.NotNil(t, myIDs)
-
- // getDeviceAgent
- myDevAgent := core.deviceMgr.getDeviceAgent(devAgent.deviceID)
- assert.NotNil(t, myDevAgent)
-
- // deleteDeviceAgentToMap
- core.deviceMgr.deleteDeviceAgentToMap(devAgent)
-}
-
-func TestLoadDevice(t *testing.T) {
-
- core, _ := MakeTestDevManagerConfig()
-
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
- assert.NotNil(t, core.deviceMgr)
-
- devAgent := newDeviceAgent(&voltha.Device{Id: "new_device"}, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, devAgent)
-
- // addDeviceAgentToMap
- core.deviceMgr.addDeviceAgentToMap(devAgent)
-
- myDev, err := core.deviceMgr.loadDevice("new_device")
- assert.NotNil(t, myDev)
- assert.Nil(t, err)
-}
-
-func TestIsDeviceInCache(t *testing.T) {
-
- // Tests also methods addDeviceAgentToMap,
- // listDeviceIdsFromMap
- // deleteDeviceAgentToMap
-
- core, _ := MakeTestDevManagerConfig()
-
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
- assert.NotNil(t, core.deviceMgr)
-
- devAgent := newDeviceAgent(&voltha.Device{Id: "new_device"}, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, devAgent)
-
- // addDeviceAgentToMap
- core.deviceMgr.addDeviceAgentToMap(devAgent)
-
- isInCache := core.deviceMgr.IsDeviceInCache(devAgent.deviceID)
- assert.True(t, isInCache)
-
- // deleteDeviceAgentToMap
- core.deviceMgr.deleteDeviceAgentToMap(devAgent)
-
- isInCacheDel := core.deviceMgr.IsDeviceInCache(devAgent.deviceID)
- assert.False(t, isInCacheDel)
-}
-
-func TestLoadRootDeviceParentAndChildren(t *testing.T) {
-
- core, _ := MakeTestDevManagerConfig()
-
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
- assert.NotNil(t, core.deviceMgr)
-
- devAgent := newDeviceAgent(&voltha.Device{Id: "new_device"}, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, devAgent)
-
- // addDeviceAgentToMap
- core.deviceMgr.addDeviceAgentToMap(devAgent)
-
- err := core.deviceMgr.loadRootDeviceParentAndChildren(devAgent.lastData)
- assert.Nil(t, err)
-}
-
-func TestGetParentDevice(t *testing.T) {
-
- core, _ := MakeTestDevManagerConfig()
-
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
- assert.NotNil(t, core.deviceMgr)
-
- devAgent := newDeviceAgent(&voltha.Device{Id: "new_device"}, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, devAgent)
-
- // addDeviceAgentToMap
- core.deviceMgr.addDeviceAgentToMap(devAgent)
-
- myDev := core.deviceMgr.getParentDevice(devAgent.lastData)
- assert.Nil(t, myDev)
-}
-
-func TestGetAllChildDeviceIds(t *testing.T) {
-
- core, _ := MakeTestDevManagerConfig()
-
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
- assert.NotNil(t, core.deviceMgr)
-
- devAgent := newDeviceAgent(&voltha.Device{Id: "new_device"}, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, devAgent)
-
- // addDeviceAgentToMap
- core.deviceMgr.addDeviceAgentToMap(devAgent)
-
- myIds, err := core.deviceMgr.getAllChildDeviceIDs(devAgent.lastData)
- assert.NotNil(t, myIds)
- assert.Nil(t, err)
-}
diff --git a/ro_core/core/grpc_nbi_api_handler.go b/ro_core/core/grpc_nbi_api_handler.go
deleted file mode 100644
index 8fdc03c..0000000
--- a/ro_core/core/grpc_nbi_api_handler.go
+++ /dev/null
@@ -1,345 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package core
-
-import (
- "context"
- "errors"
-
- "github.com/golang/protobuf/ptypes/empty"
- da "github.com/opencord/voltha-go/common/core/northbound/grpc"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-protos/v3/go/common"
- "github.com/opencord/voltha-protos/v3/go/omci"
- "github.com/opencord/voltha-protos/v3/go/openflow_13"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/metadata"
- "google.golang.org/grpc/status"
-)
-
-// APIHandler represents API handler related information
-type APIHandler struct {
- commonMgr *ModelProxyManager
- deviceMgr *DeviceManager
- logicalDeviceMgr *LogicalDeviceManager
- da.DefaultAPIHandler
-}
-
-// NewAPIHandler creates API handler
-func NewAPIHandler(generalMgr *ModelProxyManager, deviceMgr *DeviceManager, lDeviceMgr *LogicalDeviceManager) *APIHandler {
- handler := &APIHandler{
- commonMgr: generalMgr,
- deviceMgr: deviceMgr,
- logicalDeviceMgr: lDeviceMgr,
- }
- return handler
-}
-
-// isTestMode is a helper function to determine a function is invoked for testing only
-func isTestMode(ctx context.Context) bool {
- md, _ := metadata.FromIncomingContext(ctx)
- _, exist := md[common.TestModeKeys_api_test.String()]
- return exist
-}
-
-// waitForNilResponseOnSuccess is a helper function to wait for a response on channel ch where an nil
-// response is expected in a successful scenario
-func waitForNilResponseOnSuccess(ctx context.Context, ch chan interface{}) (*empty.Empty, error) {
- select {
- case res := <-ch:
- if res == nil {
- return new(empty.Empty), nil
- } else if err, ok := res.(error); ok {
- return new(empty.Empty), err
- } else {
- log.Warnw("unexpected-return-type", log.Fields{"result": res})
- err = status.Errorf(codes.Internal, "%s", res)
- return new(empty.Empty), err
- }
- case <-ctx.Done():
- log.Debug("client-timeout")
- return nil, ctx.Err()
- }
-}
-
-// UpdateLogLevel updates log level to the requested level in specific packaged if mentioned
-func (*APIHandler) UpdateLogLevel(ctx context.Context, logging *voltha.Logging) (*empty.Empty, error) {
- log.Debugw("UpdateLogLevel-request", log.Fields{"package": logging.PackageName, "intval": int(logging.Level)})
- out := new(empty.Empty)
- if logging.PackageName == "" {
- log.SetAllLogLevel(int(logging.Level))
- log.SetDefaultLogLevel(int(logging.Level))
- } else if logging.PackageName == "default" {
- log.SetDefaultLogLevel(int(logging.Level))
- } else {
- log.SetPackageLogLevel(logging.PackageName, int(logging.Level))
- }
-
- return out, nil
-}
-
-// GetLogLevels returns log levels for requested packages
-func (APIHandler) GetLogLevels(ctx context.Context, in *voltha.LoggingComponent) (*voltha.Loggings, error) {
- logLevels := &voltha.Loggings{}
-
- // do the per-package log levels
- for _, packageName := range log.GetPackageNames() {
- level, err := log.GetPackageLogLevel(packageName)
- if err != nil {
- return nil, err
- }
- logLevel := &voltha.Logging{
- ComponentName: in.ComponentName,
- PackageName: packageName,
- Level: voltha.LogLevel_Types(level)}
- logLevels.Items = append(logLevels.Items, logLevel)
- }
-
- // now do the default log level
- logLevel := &voltha.Logging{
- ComponentName: in.ComponentName,
- PackageName: "default",
- Level: voltha.LogLevel_Types(log.GetDefaultLogLevel())}
- logLevels.Items = append(logLevels.Items, logLevel)
-
- return logLevels, nil
-}
-
-// GetVoltha returns the contents of all components (i.e. devices, logical_devices, ...)
-func (handler *APIHandler) GetVoltha(ctx context.Context, empty *empty.Empty) (*voltha.Voltha, error) {
- log.Debug("GetVoltha")
- return handler.commonMgr.GetVoltha(ctx)
-}
-
-// ListCoreInstances returns details on the running core containers
-func (handler *APIHandler) ListCoreInstances(ctx context.Context, empty *empty.Empty) (*voltha.CoreInstances, error) {
- log.Debug("ListCoreInstances")
- return handler.commonMgr.ListCoreInstances(ctx)
-}
-
-// GetCoreInstance returns the details of a specific core container
-func (handler *APIHandler) GetCoreInstance(ctx context.Context, id *voltha.ID) (*voltha.CoreInstance, error) {
- log.Debugw("GetCoreInstance", log.Fields{"id": id})
- return handler.commonMgr.GetCoreInstance(ctx, id.Id)
-}
-
-// ListAdapters returns the contents of all adapters known to the system
-func (handler *APIHandler) ListAdapters(ctx context.Context, empty *empty.Empty) (*voltha.Adapters, error) {
- log.Debug("ListDevices")
- return handler.commonMgr.ListAdapters(ctx)
-}
-
-// GetDevice returns the details a specific device
-func (handler *APIHandler) GetDevice(ctx context.Context, id *voltha.ID) (*voltha.Device, error) {
- log.Debugw("GetDevice-request", log.Fields{"id": id})
- return handler.deviceMgr.GetDevice(id.Id)
-}
-
-// ListDevices returns the contents of all devices known to the system
-func (handler *APIHandler) ListDevices(ctx context.Context, empty *empty.Empty) (*voltha.Devices, error) {
- log.Debug("ListDevices")
- devices, err := handler.deviceMgr.ListDevices()
- if err != nil {
- log.Errorw("failed-to-list-devices", log.Fields{"error": err})
- return nil, err
- }
- return devices, nil
-}
-
-// ListDeviceIds returns the list of device ids managed by a voltha core
-func (handler *APIHandler) ListDeviceIds(ctx context.Context, empty *empty.Empty) (*voltha.IDs, error) {
- log.Debug("ListDeviceIDs")
- if isTestMode(ctx) {
- out := &voltha.IDs{Items: make([]*voltha.ID, 0)}
- return out, nil
- }
- return handler.deviceMgr.ListDeviceIDs()
-}
-
-// ListDevicePorts returns the ports details for a specific device entry
-func (handler *APIHandler) ListDevicePorts(ctx context.Context, id *voltha.ID) (*voltha.Ports, error) {
- log.Debugw("ListDevicePorts", log.Fields{"deviceid": id})
- return handler.deviceMgr.ListDevicePorts(ctx, id.Id)
-}
-
-// ListDevicePmConfigs returns the PM config details for a specific device entry
-func (handler *APIHandler) ListDevicePmConfigs(ctx context.Context, id *voltha.ID) (*voltha.PmConfigs, error) {
- log.Debugw("ListDevicePmConfigs", log.Fields{"deviceid": id})
- return handler.deviceMgr.ListDevicePmConfigs(ctx, id.Id)
-}
-
-// ListDeviceFlows returns the flow details for a specific device entry
-func (handler *APIHandler) ListDeviceFlows(ctx context.Context, id *voltha.ID) (*voltha.Flows, error) {
- log.Debugw("ListDeviceFlows", log.Fields{"deviceid": id})
- return handler.deviceMgr.ListDeviceFlows(ctx, id.Id)
-}
-
-// ListDeviceFlowGroups returns the flow group details for a specific device entry
-func (handler *APIHandler) ListDeviceFlowGroups(ctx context.Context, id *voltha.ID) (*voltha.FlowGroups, error) {
- log.Debugw("ListDeviceFlowGroups", log.Fields{"deviceid": id})
- return handler.deviceMgr.ListDeviceFlowGroups(ctx, id.Id)
-}
-
-// ListDeviceTypes returns all the device types known to the system
-func (handler *APIHandler) ListDeviceTypes(ctx context.Context, empty *empty.Empty) (*voltha.DeviceTypes, error) {
- log.Debug("ListDeviceTypes")
- return handler.commonMgr.ListDeviceTypes(ctx)
-}
-
-// GetDeviceType returns the device type for a specific device entry
-func (handler *APIHandler) GetDeviceType(ctx context.Context, id *voltha.ID) (*voltha.DeviceType, error) {
- log.Debugw("GetDeviceType", log.Fields{"typeid": id})
- return handler.commonMgr.GetDeviceType(ctx, id.Id)
-}
-
-// ListDeviceGroups returns all the device groups known to the system
-func (handler *APIHandler) ListDeviceGroups(ctx context.Context, empty *empty.Empty) (*voltha.DeviceGroups, error) {
- log.Debug("ListDeviceGroups")
- return handler.commonMgr.ListDeviceGroups(ctx)
-}
-
-// GetDeviceGroup returns a specific device group entry
-func (handler *APIHandler) GetDeviceGroup(ctx context.Context, id *voltha.ID) (*voltha.DeviceGroup, error) {
- log.Debugw("GetDeviceGroup", log.Fields{"groupid": id})
- return handler.commonMgr.GetDeviceGroup(ctx, id.Id)
-}
-
-// GetImageDownloadStatus returns the download status for a specific image entry
-func (handler *APIHandler) GetImageDownloadStatus(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
- log.Debugw("GetImageDownloadStatus", log.Fields{"deviceid": img.GetId(), "imagename": img.GetName()})
- return handler.deviceMgr.GetImageDownloadStatus(ctx, img.GetId(), img.GetName())
-}
-
-// GetImageDownload return the download details for a specific image entry
-func (handler *APIHandler) GetImageDownload(ctx context.Context, img *voltha.ImageDownload) (*voltha.ImageDownload, error) {
- log.Debugw("GetImageDownload", log.Fields{"deviceid": img.GetId(), "imagename": img.GetName()})
- return handler.deviceMgr.GetImageDownload(ctx, img.GetId(), img.GetName())
-}
-
-// ListImageDownloads returns all image downloads known to the system
-func (handler *APIHandler) ListImageDownloads(ctx context.Context, id *voltha.ID) (*voltha.ImageDownloads, error) {
- log.Debugw("GetImageDownload", log.Fields{"deviceid": id})
- return handler.deviceMgr.ListImageDownloads(ctx, id.Id)
-}
-
-// GetImages returns all images for a specific device entry
-func (handler *APIHandler) GetImages(ctx context.Context, id *voltha.ID) (*voltha.Images, error) {
- log.Debugw("GetImages", log.Fields{"deviceid": id})
- return handler.deviceMgr.GetImages(ctx, id.Id)
-}
-
-// ListEventFilters return all event filters known to the system
-func (handler *APIHandler) ListEventFilters(ctx context.Context, empty *empty.Empty) (*voltha.EventFilters, error) {
- log.Debug("ListEventFilters")
- return handler.commonMgr.ListEventFilters(ctx)
-}
-
-// GetEventFilter returns a filter for a specific device
-func (handler *APIHandler) GetEventFilter(ctx context.Context, id *voltha.ID) (*voltha.EventFilters, error) {
- log.Debugw("GetEventFilter", log.Fields{"deviceid": id})
- return handler.commonMgr.GetEventFilter(ctx, id.Id)
-}
-
-//ReconcileDevices is a request to a voltha core to managed a list of devices based on their IDs
-func (handler *APIHandler) ReconcileDevices(ctx context.Context, ids *voltha.IDs) (*empty.Empty, error) {
- log.Debug("ReconcileDevices")
- if isTestMode(ctx) {
- out := new(empty.Empty)
- return out, nil
- }
- ch := make(chan interface{})
- defer close(ch)
- go handler.deviceMgr.ReconcileDevices(ctx, ids, ch)
- return waitForNilResponseOnSuccess(ctx, ch)
-}
-
-// GetLogicalDevice returns the details for a specific logical device entry
-func (handler *APIHandler) GetLogicalDevice(ctx context.Context, id *voltha.ID) (*voltha.LogicalDevice, error) {
- log.Debugw("GetLogicalDevice-request", log.Fields{"id": id})
- return handler.logicalDeviceMgr.getLogicalDevice(id.Id)
-}
-
-// ListLogicalDevices returns all logical devices known to the system
-func (handler *APIHandler) ListLogicalDevices(ctx context.Context, empty *empty.Empty) (*voltha.LogicalDevices, error) {
- log.Debug("ListLogicalDevices")
- return handler.logicalDeviceMgr.listLogicalDevices()
-}
-
-// ListLogicalDevicePorts returns port details for a specific logical device entry
-func (handler *APIHandler) ListLogicalDevicePorts(ctx context.Context, id *voltha.ID) (*voltha.LogicalPorts, error) {
- log.Debugw("ListLogicalDevicePorts", log.Fields{"logicaldeviceid": id})
- return handler.logicalDeviceMgr.ListLogicalDevicePorts(ctx, id.Id)
-}
-
-// ListLogicalDeviceFlows returns flow details for a specific logical device entry
-func (handler *APIHandler) ListLogicalDeviceFlows(ctx context.Context, id *voltha.ID) (*voltha.Flows, error) {
- log.Debugw("ListLogicalDeviceFlows", log.Fields{"logicaldeviceid": id})
- return handler.logicalDeviceMgr.ListLogicalDeviceFlows(ctx, id.Id)
-}
-
-// ListLogicalDeviceFlowGroups returns flow group details for a specific logical device entry
-func (handler *APIHandler) ListLogicalDeviceFlowGroups(ctx context.Context, id *voltha.ID) (*voltha.FlowGroups, error) {
- log.Debugw("ListLogicalDeviceFlows", log.Fields{"logicaldeviceid": id})
- return handler.logicalDeviceMgr.ListLogicalDeviceFlowGroups(ctx, id.Id)
-}
-
-// SelfTest - TODO
-func (handler *APIHandler) SelfTest(ctx context.Context, id *voltha.ID) (*voltha.SelfTestResponse, error) {
- log.Debugw("SelfTest-request", log.Fields{"id": id})
- if isTestMode(ctx) {
- resp := &voltha.SelfTestResponse{Result: voltha.SelfTestResponse_SUCCESS}
- return resp, nil
- }
- return nil, errors.New("UnImplemented")
-}
-
-// GetAlarmDeviceData - @TODO useless stub, what should this actually do?
-func (handler *APIHandler) GetAlarmDeviceData(
- ctx context.Context,
- in *common.ID,
-) (*omci.AlarmDeviceData, error) {
- log.Debug("GetAlarmDeviceData-stub")
- return nil, nil
-}
-
-// GetMeterStatsOfLogicalDevice - @TODO useless stub, what should this actually do?
-func (handler *APIHandler) GetMeterStatsOfLogicalDevice(
- ctx context.Context,
- in *common.ID,
-) (*openflow_13.MeterStatsReply, error) {
- log.Debug("GetMeterStatsOfLogicalDevice-stub")
- return nil, nil
-}
-
-// GetMibDeviceData - @TODO useless stub, what should this actually do?
-func (handler *APIHandler) GetMibDeviceData(
- ctx context.Context,
- in *common.ID,
-) (*omci.MibDeviceData, error) {
- log.Debug("GetMibDeviceData-stub")
- return nil, nil
-}
-
-// SimulateAlarm - @TODO useless stub, what should this actually do?
-func (handler *APIHandler) SimulateAlarm(
- ctx context.Context,
- in *voltha.SimulateAlarmRequest,
-) (*common.OperationResp, error) {
- log.Debug("SimulateAlarm-stub")
- return nil, nil
-}
diff --git a/ro_core/core/grpc_nbi_api_handler_test.go b/ro_core/core/grpc_nbi_api_handler_test.go
deleted file mode 100644
index a62f8e5..0000000
--- a/ro_core/core/grpc_nbi_api_handler_test.go
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "context"
- "strconv"
- "testing"
-
- "github.com/opencord/voltha-go/ro_core/config"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-protos/v3/go/common"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "github.com/phayes/freeport"
- "github.com/stretchr/testify/assert"
-)
-
-func MakeTestGrpcNbiConfig() *Core {
- var ctx context.Context
- var core *Core
- var roCoreFlgs *config.ROCoreFlags
- var roC *roCore
-
- freePort, errP := freeport.GetFreePort()
- if errP == nil {
- freePortStr := strconv.Itoa(freePort)
-
- roCoreFlgs = config.NewROCoreFlags()
- roC = newROCore(roCoreFlgs)
- if (roC != nil) && (roCoreFlgs != nil) {
- addr := "127.0.0.1" + ":" + freePortStr
- cli, err := newKVClient("etcd", addr, 5)
- if err == nil {
- roC.kvClient = cli
- core = NewCore(ctx, "ro_core", roCoreFlgs, roC.kvClient)
- }
- }
- }
-
- return core
-}
-
-func TestNewAPIHandler_grpc(t *testing.T) {
- core := MakeTestGrpcNbiConfig()
- assert.NotNil(t, core)
-
- // NewAPIHandler declares, initializes and returns an handler struct
- apiHdl := NewAPIHandler(core.genericMgr, core.deviceMgr, core.logicalDeviceMgr)
- assert.NotNil(t, apiHdl)
-}
-
-func TestUpdateLogLevel_grpc(t *testing.T) {
- core := MakeTestGrpcNbiConfig()
- assert.NotNil(t, core)
-
- var testCtx = context.Background()
- testLogDef := &voltha.Logging{
- ComponentName: "testing",
- PackageName: "default",
- Level: voltha.LogLevel_Types(log.GetDefaultLogLevel())}
- testLogEmpty := &voltha.Logging{
- ComponentName: "testing",
- PackageName: "",
- Level: voltha.LogLevel_Types(log.GetDefaultLogLevel())}
- testLog := &voltha.Logging{
- ComponentName: "testing",
- PackageName: "testing",
- Level: voltha.LogLevel_Types(log.GetDefaultLogLevel())}
- testLog3 := &voltha.Logging{
- ComponentName: "testing",
- PackageName: "github.com/opencord/voltha-go/ro_core/core",
- Level: 3 /*voltha.LogLevel_LogLevel(log.GetDefaultLogLevel())*/}
- ahndl := NewAPIHandler(core.genericMgr, core.deviceMgr, core.logicalDeviceMgr)
-
- type args struct {
- ctx context.Context
- logging *voltha.Logging
- }
- tests := []struct {
- name string
- ah *APIHandler
- args args
- want int
- wantErr error
- }{
- {"TestUpdateLogLevel-1", ahndl, args{testCtx, testLogDef}, log.DebugLevel, nil},
- {"TestUpdateLogLevel-2", ahndl, args{testCtx, testLogEmpty}, log.FatalLevel, nil},
- {"TestUpdateLogLevel-3", ahndl, args{testCtx, testLog}, log.FatalLevel, nil},
- {"TestUpdateLogLevel-4", ahndl, args{testCtx, testLog3}, log.ErrorLevel, nil},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- _, gotErr := tt.ah.UpdateLogLevel(tt.args.ctx, tt.args.logging)
- if tt.wantErr != gotErr {
- t.Errorf("Error")
- }
- for _, packageNames := range log.GetPackageNames() {
- logLev, errLogLev := log.GetPackageLogLevel(packageNames)
- if errLogLev == nil {
- if packageNames == "github.com/opencord/voltha-go/ro_core/core" {
- if logLev != tt.want {
- t.Errorf("Error. Want %d, Got %d", tt.want, logLev)
- }
- }
- }
- }
- })
- }
-}
-
-func TestGetLogLevels_grpc(t *testing.T) {
- core := MakeTestGrpcNbiConfig()
- assert.NotNil(t, core)
-
- testCtx := context.Background()
- testLc := new(common.LoggingComponent)
- testLc.ComponentName = "testing"
-
- ahndl := NewAPIHandler(core.genericMgr, core.deviceMgr, core.logicalDeviceMgr)
-
- type args struct {
- ctx context.Context
- testLc *voltha.LoggingComponent
- }
- tests := []struct {
- name string
- ah *APIHandler
- args args
- want int
- wantErr error
- }{
- {"TestGetLogLevels-1", ahndl, args{testCtx, testLc}, log.DebugLevel, nil},
- {"TestGetLogLevels-2", ahndl, args{testCtx, testLc}, log.InfoLevel, nil},
- {"TestGetLogLevels-3", ahndl, args{testCtx, testLc}, log.WarnLevel, nil},
- {"TestGetLogLevels-4", ahndl, args{testCtx, testLc}, log.ErrorLevel, nil},
- {"TestGetLogLevels-5", ahndl, args{testCtx, testLc}, log.FatalLevel, nil},
- {"TestGetLogLevels-6", ahndl, args{testCtx, testLc}, log.ErrorLevel, nil},
- }
- for itt, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // itt index match log levels to test (from DEBUG=0, to FATAL=6)
- log.SetPackageLogLevel("github.com/opencord/voltha-go/ro_core/core", itt)
- logLevs, gotErr := tt.ah.GetLogLevels(tt.args.ctx, tt.args.testLc)
- if (logLevs == nil) || (gotErr != nil) {
- t.Errorf("Error %v\n", gotErr)
- }
- for _, lli := range logLevs.Items {
- if lli.PackageName == "github.com/opencord/voltha-go/ro_core/core" {
- if int(lli.Level) != tt.want {
- t.Errorf("logLev wanted %v logLev %v \n", tt.want, lli.Level)
- }
- }
- }
- })
- }
-
-}
diff --git a/ro_core/core/logical_device_agent.go b/ro_core/core/logical_device_agent.go
deleted file mode 100644
index 374b2aa..0000000
--- a/ro_core/core/logical_device_agent.go
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package core
-
-import (
- "context"
- "sync"
-
- "github.com/gogo/protobuf/proto"
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-)
-
-// LogicalDeviceAgent represents logical device agent related information
-type LogicalDeviceAgent struct {
- logicalDeviceID string
- lastData *voltha.LogicalDevice
- rootDeviceID string
- deviceMgr *DeviceManager
- ldeviceMgr *LogicalDeviceManager
- clusterDataProxy *model.Proxy
- exitChannel chan int
- lockLogicalDevice sync.RWMutex
-}
-
-func newLogicalDeviceAgent(id string, deviceID string, ldeviceMgr *LogicalDeviceManager, deviceMgr *DeviceManager, cdProxy *model.Proxy) *LogicalDeviceAgent {
- var agent LogicalDeviceAgent
- agent.exitChannel = make(chan int, 1)
- agent.logicalDeviceID = id
- agent.rootDeviceID = deviceID
- agent.deviceMgr = deviceMgr
- agent.clusterDataProxy = cdProxy
- agent.ldeviceMgr = ldeviceMgr
- agent.lockLogicalDevice = sync.RWMutex{}
- return &agent
-}
-
-// start creates the logical device and add it to the data model
-func (agent *LogicalDeviceAgent) start(ctx context.Context, loadFromDb bool) error {
- log.Infow("starting-logical_device-agent", log.Fields{"logicaldeviceID": agent.logicalDeviceID, "loadFromdB": loadFromDb})
- agent.lockLogicalDevice.Lock()
- defer agent.lockLogicalDevice.Unlock()
- if loadFromDb {
- // load from dB - the logical may not exist at this time. On error, just return and the calling function
- // will destroy this agent.
- if logicalDevice, err := agent.clusterDataProxy.Get(ctx, "/logical_devices/"+agent.logicalDeviceID, 0, false, ""); err != nil {
- log.Errorw("failed-to-get-logical-device", log.Fields{"error": err})
- return err
- } else if logicalDevice != nil {
- if lDevice, ok := logicalDevice.(*voltha.LogicalDevice); ok {
- agent.lastData = proto.Clone(lDevice).(*voltha.LogicalDevice)
- }
- } else {
- log.Errorw("failed-to-load-device", log.Fields{"logicaldeviceID": agent.logicalDeviceID})
- return status.Errorf(codes.NotFound, "logicaldeviceID-%s", agent.logicalDeviceID)
- }
- }
- log.Info("logical_device-agent-started")
- return nil
-}
-
-// stop terminates the logical device agent.
-func (agent *LogicalDeviceAgent) stop(ctx context.Context) {
- log.Info("stopping-logical_device-agent")
- agent.lockLogicalDevice.Lock()
- defer agent.lockLogicalDevice.Unlock()
- //Remove the logical device from the model
- agent.exitChannel <- 1
- log.Info("logical_device-agent-stopped")
-}
-
-// GetLogicalDevice locks the logical device model and then retrieves the latest logical device information
-func (agent *LogicalDeviceAgent) GetLogicalDevice() (*voltha.LogicalDevice, error) {
- log.Debug("GetLogicalDevice")
- agent.lockLogicalDevice.Lock()
- defer agent.lockLogicalDevice.Unlock()
- if logicalDevice, err := agent.clusterDataProxy.Get(context.Background(), "/logical_devices/"+agent.logicalDeviceID, 0, false, ""); err != nil {
- log.Errorw("failed-to-get-logical-device", log.Fields{"error": err})
- return nil, err
- } else if logicalDevice != nil {
- if lDevice, ok := logicalDevice.(*voltha.LogicalDevice); ok {
- return lDevice, nil
- }
- }
- return nil, status.Errorf(codes.NotFound, "logical_device-%s", agent.logicalDeviceID)
-}
-
-// ListLogicalDevicePorts returns all logical device ports details
-func (agent *LogicalDeviceAgent) ListLogicalDevicePorts() (*voltha.LogicalPorts, error) {
- log.Debug("ListLogicalDevicePorts")
- if logicalDevice, _ := agent.ldeviceMgr.getLogicalDevice(agent.logicalDeviceID); logicalDevice != nil {
- lPorts := make([]*voltha.LogicalPort, 0)
- lPorts = append(lPorts, logicalDevice.Ports...)
- return &voltha.LogicalPorts{Items: lPorts}, nil
- }
- return nil, status.Errorf(codes.NotFound, "logical_device-%s", agent.logicalDeviceID)
-}
-
-// ListLogicalDeviceFlows - listFlows locks the logical device model and then retrieves the latest flow information
-func (agent *LogicalDeviceAgent) ListLogicalDeviceFlows() (*voltha.Flows, error) {
- log.Debug("ListLogicalDeviceFlows")
- if logicalDevice, _ := agent.ldeviceMgr.getLogicalDevice(agent.logicalDeviceID); logicalDevice != nil {
- return logicalDevice.GetFlows(), nil
- }
- return nil, status.Errorf(codes.NotFound, "logical_device-%s", agent.logicalDeviceID)
-}
-
-// ListLogicalDeviceFlowGroups - listFlowGroups locks the logical device model and then retrieves the latest flow groups information
-func (agent *LogicalDeviceAgent) ListLogicalDeviceFlowGroups() (*voltha.FlowGroups, error) {
- log.Debug("ListLogicalDeviceFlowGroups")
- if logicalDevice, _ := agent.ldeviceMgr.getLogicalDevice(agent.logicalDeviceID); logicalDevice != nil {
- return logicalDevice.GetFlowGroups(), nil
- }
- return nil, status.Errorf(codes.NotFound, "logical_device-%s", agent.logicalDeviceID)
-}
diff --git a/ro_core/core/logical_device_agent_test.go b/ro_core/core/logical_device_agent_test.go
deleted file mode 100644
index 18e8c97..0000000
--- a/ro_core/core/logical_device_agent_test.go
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "context"
- "github.com/opencord/voltha-go/ro_core/config"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/phayes/freeport"
- "github.com/stretchr/testify/assert"
- "strconv"
- "testing"
-)
-
-func MakeTestLogDevAgConfig() (*Core, error) {
- var ctx context.Context
- var core *Core
- var roCoreFlgs *config.ROCoreFlags
- var roC *roCore
-
- freePort, errP := freeport.GetFreePort()
- if errP == nil {
- freePortStr := strconv.Itoa(freePort)
-
- roCoreFlgs = config.NewROCoreFlags()
- roC = newROCore(roCoreFlgs)
-
- if (roC != nil) && (roCoreFlgs != nil) {
- addr := "127.0.0.1" + ":" + freePortStr
- cli, err := newKVClient("etcd", addr, 5)
- if err == nil {
- roC.kvClient = cli
- //return roCoreFlgs, roC
- }
- }
- }
-
- core = NewCore(ctx, "ro_core", roCoreFlgs, roC.kvClient)
- return core, nil
-}
-
-// newLogicalDeviceAgent test
-func TestNewLogicalDeviceAgent(t *testing.T) {
- core, _ := MakeTestLogDevAgConfig()
- assert.NotNil(t, core)
- logAgent := newLogicalDeviceAgent("log-dev", "", core.logicalDeviceMgr, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, logAgent)
-}
-
-// GetLogicalDevice, Flows, Ports test
-func TestGetLogicalDevice(t *testing.T) {
- core, _ := MakeTestLogDevAgConfig()
- assert.NotNil(t, core)
-
- var err1 error
- if core.clusterDataProxy, err1 = core.localDataRoot.CreateProxy(context.Background(), "/", false); err1 != nil {
- log.Errorw("failed-to-create-cluster-proxy", log.Fields{"error": err1})
- assert.NotNil(t, err1)
- }
-
- logDevMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, logDevMgr)
-
- logAgent := newLogicalDeviceAgent("log-dev-ag", "", logDevMgr, core.deviceMgr, logDevMgr.clusterDataProxy)
- assert.NotNil(t, logAgent)
-
- logDevMgr.addLogicalDeviceAgentToMap(logAgent)
-
- logDev, err := logAgent.GetLogicalDevice()
- assert.Nil(t, logDev)
- assert.NotNil(t, err)
-
- Flws, err := logAgent.ListLogicalDeviceFlows()
- assert.Nil(t, Flws)
- assert.NotNil(t, err)
- FlwsGrp, err := logAgent.ListLogicalDeviceFlowGroups()
- assert.Nil(t, FlwsGrp)
- assert.NotNil(t, err)
-
- logDevPorts, err := logAgent.ListLogicalDevicePorts()
- assert.Nil(t, logDevPorts)
- assert.NotNil(t, err)
-
-}
diff --git a/ro_core/core/logical_device_manager.go b/ro_core/core/logical_device_manager.go
deleted file mode 100644
index e9e433f..0000000
--- a/ro_core/core/logical_device_manager.go
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package core
-
-import (
- "context"
- "sync"
-
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-lib-go/v3/pkg/probe"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-)
-
-// LogicalDeviceManager represents logical device manager related information
-type LogicalDeviceManager struct {
- logicalDeviceAgents sync.Map
- deviceMgr *DeviceManager
- grpcNbiHdlr *APIHandler
- clusterDataProxy *model.Proxy
- exitChannel chan int
- lockLogicalDeviceAgentsMap sync.RWMutex
-}
-
-func newLogicalDeviceManager(deviceMgr *DeviceManager, cdProxy *model.Proxy) *LogicalDeviceManager {
- var logicalDeviceMgr LogicalDeviceManager
- logicalDeviceMgr.exitChannel = make(chan int, 1)
- logicalDeviceMgr.deviceMgr = deviceMgr
- logicalDeviceMgr.clusterDataProxy = cdProxy
- logicalDeviceMgr.lockLogicalDeviceAgentsMap = sync.RWMutex{}
- return &logicalDeviceMgr
-}
-
-func (ldMgr *LogicalDeviceManager) setGrpcNbiHandler(grpcNbiHandler *APIHandler) {
- ldMgr.grpcNbiHdlr = grpcNbiHandler
-}
-
-func (ldMgr *LogicalDeviceManager) start(ctx context.Context) {
- log.Info("starting-logical-device-manager")
- probe.UpdateStatusFromContext(ctx, "logical-device-manager", probe.ServiceStatusRunning)
- log.Info("logical-device-manager-started")
-}
-
-func (ldMgr *LogicalDeviceManager) stop(ctx context.Context) {
- log.Info("stopping-logical-device-manager")
- ldMgr.exitChannel <- 1
- probe.UpdateStatusFromContext(ctx, "logical-device-manager", probe.ServiceStatusStopped)
- log.Info("logical-device-manager-stopped")
-}
-
-func (ldMgr *LogicalDeviceManager) addLogicalDeviceAgentToMap(agent *LogicalDeviceAgent) {
- if _, exist := ldMgr.logicalDeviceAgents.Load(agent.logicalDeviceID); !exist {
- ldMgr.logicalDeviceAgents.Store(agent.logicalDeviceID, agent)
- }
-}
-
-// getLogicalDeviceAgent returns the logical device agent. If the device is not in memory then the device will
-// be loaded from dB and a logical device agent created to managed it.
-func (ldMgr *LogicalDeviceManager) getLogicalDeviceAgent(logicalDeviceID string) *LogicalDeviceAgent {
- agent, ok := ldMgr.logicalDeviceAgents.Load(logicalDeviceID)
- if ok {
- return agent.(*LogicalDeviceAgent)
- }
- // Try to load into memory - loading will also create the logical device agent
- if err := ldMgr.load(logicalDeviceID); err == nil {
- if agent, ok = ldMgr.logicalDeviceAgents.Load(logicalDeviceID); ok {
- return agent.(*LogicalDeviceAgent)
- }
- }
- return nil
-}
-
-func (ldMgr *LogicalDeviceManager) deleteLogicalDeviceAgent(logicalDeviceID string) {
- ldMgr.logicalDeviceAgents.Delete(logicalDeviceID)
-}
-
-// GetLogicalDevice provides a cloned most up to date logical device
-func (ldMgr *LogicalDeviceManager) getLogicalDevice(id string) (*voltha.LogicalDevice, error) {
- log.Debugw("getlogicalDevice", log.Fields{"logicaldeviceid": id})
- if agent := ldMgr.getLogicalDeviceAgent(id); agent != nil {
- return agent.GetLogicalDevice()
- }
- return nil, status.Errorf(codes.NotFound, "%s", id)
-}
-
-//listLogicalDevices returns the list of all logical devices
-func (ldMgr *LogicalDeviceManager) listLogicalDevices() (*voltha.LogicalDevices, error) {
- log.Debug("ListAllLogicalDevices")
- result := &voltha.LogicalDevices{}
- if logicalDevices, err := ldMgr.clusterDataProxy.List(context.Background(), "/logical_devices", 0, false,
- ""); err != nil {
- log.Errorw("failed-to-list-devices", log.Fields{"error": err})
- return nil, err
- } else if logicalDevices != nil {
- for _, logicalDevice := range logicalDevices.([]interface{}) {
- result.Items = append(result.Items, logicalDevice.(*voltha.LogicalDevice))
- }
- }
- return result, nil
-}
-
-// load loads a logical device manager in memory
-func (ldMgr *LogicalDeviceManager) load(lDeviceID string) error {
- log.Debugw("loading-logical-device", log.Fields{"lDeviceID": lDeviceID})
- // To prevent a race condition, let's hold the logical device agent map lock. This will prevent a loading and
- // a create logical device callback from occurring at the same time.
- if ldAgent, _ := ldMgr.logicalDeviceAgents.Load(lDeviceID); ldAgent == nil {
- // Logical device not in memory - create a temp logical device Agent and let it load from memory
- agent := newLogicalDeviceAgent(lDeviceID, "", ldMgr, ldMgr.deviceMgr, ldMgr.clusterDataProxy)
- if err := agent.start(context.TODO(), true); err != nil {
- agent.stop(context.TODO())
- return err
- }
- ldMgr.logicalDeviceAgents.Store(agent.logicalDeviceID, agent)
- }
- // TODO: load the child device
- return nil
-}
-
-func (ldMgr *LogicalDeviceManager) getLogicalDeviceID(device *voltha.Device) (*string, error) {
- // Device can either be a parent or a child device
- if device.Root {
- // Parent device. The ID of a parent device is the logical device ID
- return &device.ParentId, nil
- }
- // Device is child device
- // retrieve parent device using child device ID
- if parentDevice := ldMgr.deviceMgr.getParentDevice(device); parentDevice != nil {
- return &parentDevice.ParentId, nil
- }
- return nil, status.Errorf(codes.NotFound, "%s", device.Id)
-}
-
-func (ldMgr *LogicalDeviceManager) getLogicalPortID(device *voltha.Device) (*voltha.LogicalPortId, error) {
- // Get the logical device where this device is attached
- var lDeviceID *string
- var err error
- if lDeviceID, err = ldMgr.getLogicalDeviceID(device); err != nil {
- return nil, err
- }
- var lDevice *voltha.LogicalDevice
- if lDevice, err = ldMgr.getLogicalDevice(*lDeviceID); err != nil {
- return nil, err
- }
- // Go over list of ports
- for _, port := range lDevice.Ports {
- if port.DeviceId == device.Id {
- return &voltha.LogicalPortId{Id: *lDeviceID, PortId: port.Id}, nil
- }
- }
- return nil, status.Errorf(codes.NotFound, "%s", device.Id)
-}
-
-// ListLogicalDevicePorts returns port details for a specific logical device entry
-func (ldMgr *LogicalDeviceManager) ListLogicalDevicePorts(ctx context.Context, id string) (*voltha.LogicalPorts, error) {
- log.Debugw("ListLogicalDevicePorts", log.Fields{"logicaldeviceid": id})
- if agent := ldMgr.getLogicalDeviceAgent(id); agent != nil {
- return agent.ListLogicalDevicePorts()
- }
- return nil, status.Errorf(codes.NotFound, "%s", id)
-
-}
-
-// ListLogicalDeviceFlows returns flow details for a specific logical device entry
-func (ldMgr *LogicalDeviceManager) ListLogicalDeviceFlows(ctx context.Context, id string) (*voltha.Flows, error) {
- log.Debugw("ListLogicalDeviceFlows", log.Fields{"logicaldeviceid": id})
- if agent := ldMgr.getLogicalDeviceAgent(id); agent != nil {
- return agent.ListLogicalDeviceFlows()
- }
- return nil, status.Errorf(codes.NotFound, "%s", id)
-
-}
-
-// ListLogicalDeviceFlowGroups returns flow group details for a specific logical device entry
-func (ldMgr *LogicalDeviceManager) ListLogicalDeviceFlowGroups(ctx context.Context, id string) (*voltha.FlowGroups, error) {
- log.Debugw("ListLogicalDeviceFlowGroups", log.Fields{"logicaldeviceid": id})
- if agent := ldMgr.getLogicalDeviceAgent(id); agent != nil {
- return agent.ListLogicalDeviceFlowGroups()
- }
- return nil, status.Errorf(codes.NotFound, "%s", id)
-
-}
-
-func (ldMgr *LogicalDeviceManager) getLogicalPort(lPortID *voltha.LogicalPortId) (*voltha.LogicalPort, error) {
- // Get the logical device where this device is attached
- var err error
- var lDevice *voltha.LogicalDevice
- if lDevice, err = ldMgr.getLogicalDevice(lPortID.Id); err != nil {
- return nil, err
- }
- // Go over list of ports
- for _, port := range lDevice.Ports {
- if port.Id == lPortID.PortId {
- return port, nil
- }
- }
- return nil, status.Errorf(codes.NotFound, "%s-%s", lPortID.Id, lPortID.PortId)
-}
diff --git a/ro_core/core/logical_device_manager_test.go b/ro_core/core/logical_device_manager_test.go
deleted file mode 100644
index 7e91d37..0000000
--- a/ro_core/core/logical_device_manager_test.go
+++ /dev/null
@@ -1,485 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "context"
- "reflect"
- "testing"
-
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-go/ro_core/config"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-protos/v3/go/openflow_13"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "github.com/stretchr/testify/assert"
-)
-
-func MakeTestNewCoreConfig() *Core {
- var core Core
- core.instanceID = "ro_core"
- var err error
- core.config = config.NewROCoreFlags()
- core.clusterDataRoot = model.NewRoot(&voltha.Voltha{}, nil)
- core.clusterDataProxy, err = core.clusterDataRoot.CreateProxy(context.Background(), "/", false)
- if err != nil {
- log.With(log.Fields{"error": err}).Fatal("Cannot create cluster data proxy")
- }
- core.genericMgr = newModelProxyManager(core.clusterDataProxy)
- core.deviceMgr = newDeviceManager(core.clusterDataProxy, core.instanceID)
-
- return &core
-}
-
-func TestNewLogicalDeviceManager(t *testing.T) {
- core := MakeTestNewCoreConfig()
-
- logicalDevMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, logicalDevMgr)
-}
-
-func TestAddLogicalDeviceAgentToMap(t *testing.T) {
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- // Before ADD
- ldAgentNil := ldMgr.getLogicalDeviceAgent("id")
- assert.Nil(t, ldAgentNil)
-
- /*** Case: addLogicalDeviceAgentToMap() is Success ***/
- ldAgent := newLogicalDeviceAgent("id", "", ldMgr, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldAgent)
- ldMgr.addLogicalDeviceAgentToMap(ldAgent)
-
- // Verify ADD is successful
- ldAgentNotNil := ldMgr.getLogicalDeviceAgent("id")
- assert.NotNil(t, ldAgentNotNil)
- assert.Equal(t, "id", ldAgentNotNil.logicalDeviceID)
-}
-
-func TestGetLogicalDeviceAgent(t *testing.T) {
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: getLogicalDeviceAgent() is NIL ***/
- ldAgentNil := ldMgr.getLogicalDeviceAgent("id")
- assert.Nil(t, ldAgentNil)
-
- /*** Case: getLogicalDeviceAgent() is Success ***/
- ldAgent := newLogicalDeviceAgent("id", "", ldMgr, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldAgent)
- ldMgr.addLogicalDeviceAgentToMap(ldAgent)
- ldAgentNotNil := ldMgr.getLogicalDeviceAgent("id")
- assert.NotNil(t, ldAgentNotNil)
- assert.Equal(t, "id", ldAgentNotNil.logicalDeviceID)
-}
-
-func TestDeleteLogicalDeviceAgent(t *testing.T) {
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: deleteLogicalDeviceAgent() with Invalid Value ***/
- ldAgentNilChk := ldMgr.getLogicalDeviceAgent("invalid_id")
- assert.Nil(t, ldAgentNilChk)
- ldMgr.deleteLogicalDeviceAgent("invalid_id")
-
- /*** Case: deleteLogicalDeviceAgent() is Success ***/
- // Initialize and Add Logical Device Agent
- ldAgent := newLogicalDeviceAgent("id", "", ldMgr, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldAgent)
- ldMgr.addLogicalDeviceAgentToMap(ldAgent)
-
- // Verify ADD is successful
- ldAgentNotNil := ldMgr.getLogicalDeviceAgent("id")
- assert.NotNil(t, ldAgentNotNil)
- assert.Equal(t, "id", ldAgentNotNil.logicalDeviceID)
-
- // Method under Test
- ldMgr.deleteLogicalDeviceAgent("id")
-
- // Verify DEL is successful
- ldAgentNil := ldMgr.getLogicalDeviceAgent("id")
- assert.Nil(t, ldAgentNil)
-}
-
-func TestLdMgrGetLogicalDevice(t *testing.T) {
- wantResult := &voltha.LogicalDevice{}
-
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: getLogicalDevice() is NIL ***/
- logicalDevNil, errNotNil := ldMgr.getLogicalDevice("id")
- assert.Nil(t, logicalDevNil)
- assert.NotNil(t, errNotNil)
-
- /*** Case: getLogicalDevice() is Success ***/
- // Add Data
- added, err := core.clusterDataProxy.Add(
- context.Background(),
- "/logical_devices",
- &voltha.LogicalDevice{
- Id: "id",
- },
- "")
- if err != nil {
- log.Errorw("failed-to-add-logical-device", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add logical device")
- }
- ldAgent := newLogicalDeviceAgent("id", "device_id", ldMgr, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldAgent)
- ldMgr.addLogicalDeviceAgentToMap(ldAgent)
-
- // Verify Add is successful
- ldAgentNotNil := ldMgr.getLogicalDeviceAgent("id")
- assert.NotNil(t, ldAgentNotNil)
- assert.Equal(t, "id", ldAgentNotNil.logicalDeviceID)
-
- // Verify getLogicalDevice() is NOT NIL
- logicalDevNotNil, errNil := ldMgr.getLogicalDevice("id")
- assert.NotNil(t, logicalDevNotNil)
- assert.Nil(t, errNil)
- if reflect.TypeOf(logicalDevNotNil) != reflect.TypeOf(wantResult) {
- t.Errorf("GetLogicalDevice() = %v, want %v", logicalDevNotNil, wantResult)
- }
- assert.Equal(t, "id", logicalDevNotNil.Id)
-}
-
-func TestListLogicalDevices(t *testing.T) {
- wantResult := &voltha.LogicalDevices{}
-
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: listLogicalDevices() is Empty ***/
- result, error := ldMgr.listLogicalDevices()
- assert.NotNil(t, result)
- assert.Nil(t, error)
- if reflect.TypeOf(result) != reflect.TypeOf(wantResult) {
- t.Errorf("ListLogicalDevices() = %v, want %v", result, wantResult)
- }
- assert.Empty(t, result)
-}
-
-func TestLoad(t *testing.T) {
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: Error Scenario ***/
- error := ldMgr.load("id")
- assert.NotNil(t, error)
-}
-
-func TestGetLogicalDeviceId(t *testing.T) {
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: Logical Device Id Found ***/
- result0, error0 := ldMgr.getLogicalDeviceID(&voltha.Device{Id: "id", Root: true, ParentId: "parent_id"})
- assert.NotNil(t, result0)
- assert.Nil(t, error0)
-
- /*** Case: Logical Device Id Not Found ***/
- result1, error1 := ldMgr.getLogicalDeviceID(&voltha.Device{Id: "id", ParentId: "parent_id"})
- assert.Nil(t, result1)
- assert.NotNil(t, error1)
-}
-
-func TestGetLogicalPortId(t *testing.T) {
- wantResult := &voltha.LogicalPortId{}
-
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: Logical Port Id Not Found: getLogicalDeviceId() Error ***/
- result0, error0 := ldMgr.getLogicalPortID(&voltha.Device{Id: "id", ParentId: "parent_id"})
- assert.Nil(t, result0)
- assert.NotNil(t, error0)
-
- /*** Case: Logical Port Id Not Found: getLogicalDevice() Error ***/
- result1, error1 := ldMgr.getLogicalPortID(&voltha.Device{Id: "id", Root: true, ParentId: "parent_id"})
- assert.Nil(t, result1)
- assert.NotNil(t, error1)
-
- /*** Case: Logical Port Id Found ***/
- device := &voltha.Device{Id: "id", Root: true, ParentId: "parent_id"}
-
- // Add Data
- added, err := core.clusterDataProxy.Add(
- context.Background(),
- "/logical_devices",
- &voltha.LogicalDevice{
- Id: "parent_id",
- Ports: []*voltha.LogicalPort{
- {
- Id: "123",
- DeviceId: "id",
- },
- },
- },
- "")
- if err != nil {
- log.Errorw("failed-to-add-logical-device", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add logical device")
- }
- ldAgent := newLogicalDeviceAgent("parent_id", "device_id", ldMgr, core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldAgent)
- ldMgr.addLogicalDeviceAgentToMap(ldAgent)
-
- // Verify Add is successful
- ldAgentNotNil := ldMgr.getLogicalDeviceAgent("parent_id")
- assert.NotNil(t, ldAgentNotNil)
- assert.Equal(t, "parent_id", ldAgentNotNil.logicalDeviceID)
-
- // Verify getLogicalPortId() is Success
- result2, error2 := ldMgr.getLogicalPortID(device)
- assert.NotNil(t, result2)
- assert.Nil(t, error2)
- if reflect.TypeOf(result2) != reflect.TypeOf(wantResult) {
- t.Errorf("GetLogicalPortId() = %v, want %v", result2, wantResult)
- }
- assert.Equal(t, "parent_id", result2.Id)
-}
-
-func TestListLogicalDevicePorts(t *testing.T) {
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: Logical Device Ports Not Found ***/
- result0, error0 := ldMgr.ListLogicalDevicePorts(context.Background(), "id")
- assert.Nil(t, result0)
- assert.NotNil(t, error0)
-
- /*** Case: Logical Device Ports Found ***/
- wantResult := &voltha.LogicalPorts{
- Items: []*voltha.LogicalPort{
- {
- Id: "123",
- },
- },
- }
-
- // Add Data
- added, err := core.clusterDataProxy.Add(
- context.Background(),
- "/logical_devices",
- &voltha.LogicalDevice{
- Id: "id",
- Ports: []*voltha.LogicalPort{
- {
- Id: "123",
- },
- },
- },
- "")
- if err != nil {
- log.Errorw("failed-to-add-logical-device", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add logical device")
- }
- ldAgent := newLogicalDeviceAgent("id", "", ldMgr, core.deviceMgr, core.clusterDataProxy)
- ldMgr.addLogicalDeviceAgentToMap(ldAgent)
-
- // Verify Add is successful
- ldAgentNotNil := ldMgr.getLogicalDeviceAgent("id")
- assert.NotNil(t, ldAgentNotNil)
- assert.Equal(t, "id", ldAgentNotNil.logicalDeviceID)
-
- // Verify ListLogicalDevicePorts() is Success
- result1, error1 := ldMgr.ListLogicalDevicePorts(context.Background(), "id")
- assert.NotNil(t, result1)
- assert.Nil(t, error1)
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("ListLogicalDevicePorts() = %v, want %v", result1, wantResult)
- }
- assert.Equal(t, wantResult, result1)
-}
-
-func TestListLogicalDeviceFlows(t *testing.T) {
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: Logical Device Flows Not Found ***/
- result0, error0 := ldMgr.ListLogicalDeviceFlows(context.Background(), "id")
- assert.Nil(t, result0)
- assert.NotNil(t, error0)
-
- /*** Case: Logical Device Flows Found ***/
- wantResult := &voltha.Flows{}
-
- // Add Data
- added, err := core.clusterDataProxy.Add(
- context.Background(),
- "/logical_devices",
- &voltha.LogicalDevice{
- Id: "id",
- Flows: &openflow_13.Flows{
- Items: []*openflow_13.OfpFlowStats{
- &openflow_13.OfpFlowStats{
- Id: 1111,
- },
- },
- },
- },
- "")
- if err != nil {
- log.Errorw("failed-to-add-logical-device", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add logical device")
- }
- ldAgent := newLogicalDeviceAgent("id", "", ldMgr, core.deviceMgr, core.clusterDataProxy)
- ldMgr.addLogicalDeviceAgentToMap(ldAgent)
-
- // Verify Add is successful
- ldAgentNotNil := ldMgr.getLogicalDeviceAgent("id")
- assert.NotNil(t, ldAgentNotNil)
- assert.Equal(t, "id", ldAgentNotNil.logicalDeviceID)
-
- // Verify ListLogicalDeviceFlows() is Success
- result1, error1 := ldMgr.ListLogicalDeviceFlows(context.Background(), "id")
- assert.NotNil(t, result1)
- assert.Nil(t, error1)
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("ListLogicalDeviceFlows() = %v, want %v", result1, wantResult)
- }
- assert.NotEmpty(t, result1)
-}
-
-func TestListLogicalDeviceFlowGroups(t *testing.T) {
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: Logical Device Flow Groups Not Found ***/
- result0, error0 := ldMgr.ListLogicalDeviceFlowGroups(context.Background(), "id")
- assert.Nil(t, result0)
- assert.NotNil(t, error0)
-
- /*** Case: Logical Device Flow Groups Found ***/
- wantResult := &voltha.FlowGroups{}
-
- // Add Data
- added, err := core.clusterDataProxy.Add(
- context.Background(),
- "/logical_devices",
- &voltha.LogicalDevice{
- Id: "id",
- FlowGroups: &openflow_13.FlowGroups{
- Items: []*openflow_13.OfpGroupEntry{
- {
- Stats: &openflow_13.OfpGroupStats{
- GroupId: 1,
- },
- },
- },
- },
- },
- "")
- if err != nil {
- log.Errorw("failed-to-add-logical-device", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add logical device")
- }
- ldAgent := newLogicalDeviceAgent("id", "", ldMgr, core.deviceMgr, core.clusterDataProxy)
- ldMgr.addLogicalDeviceAgentToMap(ldAgent)
-
- // Verify Add is successful
- ldAgentNotNil := ldMgr.getLogicalDeviceAgent("id")
- assert.NotNil(t, ldAgentNotNil)
- assert.Equal(t, "id", ldAgentNotNil.logicalDeviceID)
-
- // Verify ListLogicalDeviceFlowGroups() is Success
- result1, error1 := ldMgr.ListLogicalDeviceFlowGroups(context.Background(), "id")
- assert.NotNil(t, result1)
- assert.Nil(t, error1)
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("ListLogicalDeviceFlowGroups() = %v, want %v", result1, wantResult)
- }
- assert.NotEmpty(t, result1)
-}
-
-func TestGetLogicalPort(t *testing.T) {
- core := MakeTestNewCoreConfig()
- ldMgr := newLogicalDeviceManager(core.deviceMgr, core.clusterDataProxy)
- assert.NotNil(t, ldMgr)
-
- /*** Case: Logical Port Not Found: getLogicalDevice() Error ***/
- result0, error0 := ldMgr.getLogicalPort(&voltha.LogicalPortId{Id: "id", PortId: "123"})
- assert.Nil(t, result0)
- assert.NotNil(t, error0)
-
- /*** Case: Logical Port Found ***/
- wantResult := &voltha.LogicalPort{Id: "123"}
-
- // Add Data
- added, err := core.clusterDataProxy.Add(
- context.Background(),
- "/logical_devices",
- &voltha.LogicalDevice{
- Id: "id",
- Ports: []*voltha.LogicalPort{
- {
- Id: "123",
- },
- },
- },
- "")
- if err != nil {
- log.Errorw("failed-to-add-logical-device", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add logical device")
- }
- ldAgent := newLogicalDeviceAgent("id", "", ldMgr, core.deviceMgr, core.clusterDataProxy)
- ldMgr.addLogicalDeviceAgentToMap(ldAgent)
-
- // Verify Add is successful
- ldAgentNotNil := ldMgr.getLogicalDeviceAgent("id")
- assert.NotNil(t, ldAgentNotNil)
- assert.Equal(t, "id", ldAgentNotNil.logicalDeviceID)
-
- // Verify getLogicalPort() is Success
- result1, error1 := ldMgr.getLogicalPort(&voltha.LogicalPortId{Id: "id", PortId: "123"})
- assert.NotNil(t, result1)
- assert.Nil(t, error1)
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("getLogicalPort() = %v, want %v", result1, wantResult)
- }
- assert.Equal(t, wantResult, result1)
-}
diff --git a/ro_core/core/model_proxy.go b/ro_core/core/model_proxy.go
deleted file mode 100644
index 3775540..0000000
--- a/ro_core/core/model_proxy.go
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package core
-
-import (
- "context"
- "strings"
- "sync"
-
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-)
-
-// ModelProxy controls requests made to the data model
-type ModelProxy struct {
- rootProxy *model.Proxy
- basePath string
- mutex sync.RWMutex
-}
-
-func newModelProxy(basePath string, rootProxy *model.Proxy) *ModelProxy {
- ga := &ModelProxy{}
- ga.rootProxy = rootProxy
-
- if strings.HasPrefix(basePath, "/") {
- ga.basePath = basePath
- } else {
- ga.basePath = "/" + basePath
- }
-
- return ga
-}
-
-// Get retrieves information at the provided path
-func (mp *ModelProxy) Get(parts ...string) (interface{}, error) {
- mp.mutex.Lock()
- defer mp.mutex.Unlock()
-
- rawPath := []string{mp.basePath}
- rawPath = append(rawPath, parts...)
- path := strings.Join(rawPath, "/")
-
- log.Debugw("get-data", log.Fields{"path": path})
-
- if data, err := mp.rootProxy.Get(context.Background(), path, 1, false, ""); err != nil {
- log.Errorw("failed-to-retrieve-data-from-model-proxy", log.Fields{"error": err})
- return nil, err
- } else if data != nil {
- return data, nil
- }
- return nil, status.Errorf(codes.NotFound, "data-path: %s", path)
-}
diff --git a/ro_core/core/model_proxy_manager.go b/ro_core/core/model_proxy_manager.go
deleted file mode 100644
index 42d0ad6..0000000
--- a/ro_core/core/model_proxy_manager.go
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package core
-
-import (
- "context"
- "encoding/json"
-
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-lib-go/v3/pkg/version"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-)
-
-// DataModelType - Enumerated type to keep track of miscellaneous data path agents
-type DataModelType int
-
-// Enumerated list of data path agents
-const (
- Adapters DataModelType = 1 + iota
- EventFilters
- CoreInstances
- DeviceTypes
- DeviceGroups
- Voltha
-)
-
-// SentinelAdapterID is used to watch adapters in kv
-const SentinelAdapterID = "adapter_sentinel"
-
-// String equivalent for data path agents
-var commonTypes = []string{
- "Adapters",
- "EventFilters",
- "CoreInstances",
- "DeviceTypes",
- "DeviceGroups",
- "Voltha",
-}
-
-// String converts the enumerated data path agent value to its string equivalent
-func (t DataModelType) String() string {
- return commonTypes[t-1]
-}
-
-// MultipleValuesMsg represents multiple values message
-const MultipleValuesMsg = "Expected a single value for KV query for an instance (%s) of type '%s', but received multiple values"
-
-// ModelProxyManager controls requests made to the miscellaneous data path agents
-type ModelProxyManager struct {
- modelProxy map[string]*ModelProxy
- clusterDataProxy *model.Proxy
-}
-
-func newModelProxyManager(cdProxy *model.Proxy) *ModelProxyManager {
- var mgr ModelProxyManager
- mgr.modelProxy = make(map[string]*ModelProxy)
- mgr.clusterDataProxy = cdProxy
- return &mgr
-}
-
-// GetVoltha - GetDeviceType returns the device type associated to the provided id
-func (mpMgr *ModelProxyManager) GetVoltha(ctx context.Context) (*voltha.Voltha, error) {
- log.Debug("GetVoltha")
-
- /*
- * For now, encode all the version information into a JSON object and
- * pass that back as "version" so the client can get all the
- * information associated with the version. Long term the API should
- * better accomidate this, but for now this will work.
- */
- data, err := json.Marshal(&version.VersionInfo)
- info := version.VersionInfo.Version
- if err != nil {
- log.Warnf("Unable to encode version information as JSON: %s", err.Error())
- } else {
- info = string(data)
- }
-
- return &voltha.Voltha{
- Version: info,
- }, nil
-}
-
-// ListCoreInstances returns all the core instances known to the system
-func (mpMgr *ModelProxyManager) ListCoreInstances(ctx context.Context) (*voltha.CoreInstances, error) {
- log.Debug("ListCoreInstances")
-
- // TODO: Need to retrieve the list of registered cores
-
- return &voltha.CoreInstances{}, status.Errorf(codes.NotFound, "no-core-instances")
-}
-
-// GetCoreInstance returns the core instance associated to the provided id
-func (mpMgr *ModelProxyManager) GetCoreInstance(ctx context.Context, id string) (*voltha.CoreInstance, error) {
- log.Debugw("GetCoreInstance", log.Fields{"id": id})
-
- // TODO: Need to retrieve the list of registered cores
-
- return &voltha.CoreInstance{}, status.Errorf(codes.NotFound, "core-instance-%s", id)
-}
-
-// ListAdapters returns all the device types known to the system
-func (mpMgr *ModelProxyManager) ListAdapters(ctx context.Context) (*voltha.Adapters, error) {
- log.Debug("ListAdapters")
-
- var agent *ModelProxy
- var exists bool
- var adapter *voltha.Adapter
-
- if agent, exists = mpMgr.modelProxy[Adapters.String()]; !exists {
- agent = newModelProxy("adapters", mpMgr.clusterDataProxy)
- mpMgr.modelProxy[Adapters.String()] = agent
- }
-
- adapters := &voltha.Adapters{}
- if items, err := agent.Get(); err != nil {
- return nil, status.Errorf(codes.Internal, err.Error())
- } else if items != nil {
- list, ok := items.([]interface{})
- if !ok {
- list = []interface{}{items}
- }
- for _, item := range list {
- adapter = item.(*voltha.Adapter)
- if adapter.Id != SentinelAdapterID { // don't report the sentinel
- adapters.Items = append(adapters.Items, adapter)
- }
- }
- log.Debugw("retrieved-adapters", log.Fields{"adapters": adapters})
- return adapters, nil
- }
-
- return adapters, status.Errorf(codes.NotFound, "no-adapters")
-}
-
-// ListDeviceTypes returns all the device types known to the system
-func (mpMgr *ModelProxyManager) ListDeviceTypes(ctx context.Context) (*voltha.DeviceTypes, error) {
- log.Debug("ListDeviceTypes")
-
- var agent *ModelProxy
- var exists bool
-
- if agent, exists = mpMgr.modelProxy[DeviceTypes.String()]; !exists {
- agent = newModelProxy("device_types", mpMgr.clusterDataProxy)
- mpMgr.modelProxy[DeviceTypes.String()] = agent
- }
-
- deviceTypes := &voltha.DeviceTypes{}
- if items, err := agent.Get(); err != nil {
- return nil, status.Errorf(codes.Internal, err.Error())
- } else if items != nil {
- list, ok := items.([]interface{})
- if !ok {
- list = []interface{}{items}
- }
- for _, item := range list {
- deviceTypes.Items = append(deviceTypes.Items, item.(*voltha.DeviceType))
- }
- return deviceTypes, nil
- }
-
- return deviceTypes, status.Errorf(codes.NotFound, "no-device-types")
-}
-
-// GetDeviceType returns the device type associated to the provided id
-func (mpMgr *ModelProxyManager) GetDeviceType(ctx context.Context, id string) (*voltha.DeviceType, error) {
- log.Debugw("GetDeviceType", log.Fields{"id": id})
-
- var agent *ModelProxy
- var exists bool
-
- if agent, exists = mpMgr.modelProxy[DeviceTypes.String()]; !exists {
- agent = newModelProxy("device_types", mpMgr.clusterDataProxy)
- mpMgr.modelProxy[DeviceTypes.String()] = agent
- }
-
- if deviceType, err := agent.Get(id); err != nil {
- return nil, status.Errorf(codes.Internal, err.Error())
- } else if deviceType != nil {
- _, ok := deviceType.(*voltha.DeviceType)
- if !ok {
- return nil, status.Errorf(codes.Internal, MultipleValuesMsg,
- id, DeviceTypes.String())
- }
- return deviceType.(*voltha.DeviceType), nil
- }
-
- return &voltha.DeviceType{}, status.Errorf(codes.NotFound, "device-type-%s", id)
-}
-
-// ListDeviceGroups returns all the device groups known to the system
-func (mpMgr *ModelProxyManager) ListDeviceGroups(ctx context.Context) (*voltha.DeviceGroups, error) {
- log.Debug("ListDeviceGroups")
-
- var agent *ModelProxy
- var exists bool
-
- if agent, exists = mpMgr.modelProxy[DeviceGroups.String()]; !exists {
- agent = newModelProxy("device_groups", mpMgr.clusterDataProxy)
- mpMgr.modelProxy[DeviceGroups.String()] = agent
- }
-
- deviceGroups := &voltha.DeviceGroups{}
- if items, err := agent.Get(); err != nil {
- return nil, status.Errorf(codes.Internal, err.Error())
- } else if items != nil {
- list, ok := items.([]interface{})
- if !ok {
- list = []interface{}{items}
- }
- for _, item := range list {
- deviceGroups.Items = append(deviceGroups.Items, item.(*voltha.DeviceGroup))
- }
- return deviceGroups, nil
- }
-
- return deviceGroups, status.Errorf(codes.NotFound, "no-device-groups")
-}
-
-// GetDeviceGroup returns the device group associated to the provided id
-func (mpMgr *ModelProxyManager) GetDeviceGroup(ctx context.Context, id string) (*voltha.DeviceGroup, error) {
- log.Debugw("GetDeviceGroup", log.Fields{"id": id})
-
- var agent *ModelProxy
- var exists bool
-
- if agent, exists = mpMgr.modelProxy[DeviceGroups.String()]; !exists {
- agent = newModelProxy("device_groups", mpMgr.clusterDataProxy)
- mpMgr.modelProxy[DeviceGroups.String()] = agent
- }
-
- if deviceGroup, err := agent.Get(id); err != nil {
- return nil, status.Errorf(codes.Internal, err.Error())
- } else if deviceGroup != nil {
- _, ok := deviceGroup.(*voltha.DeviceGroup)
- if !ok {
- return nil, status.Errorf(codes.Internal, MultipleValuesMsg,
- id, DeviceGroups.String())
- }
- return deviceGroup.(*voltha.DeviceGroup), nil
- }
-
- return &voltha.DeviceGroup{}, status.Errorf(codes.NotFound, "device-group-%s", id)
-}
-
-// ListEventFilters returns all the event filters known to the system
-func (mpMgr *ModelProxyManager) ListEventFilters(ctx context.Context) (*voltha.EventFilters, error) {
- log.Debug("ListEventFilters")
-
- var agent *ModelProxy
- var exists bool
-
- if agent, exists = mpMgr.modelProxy[EventFilters.String()]; !exists {
- agent = newModelProxy("event_filters", mpMgr.clusterDataProxy)
- mpMgr.modelProxy[EventFilters.String()] = agent
- }
-
- eventFilters := &voltha.EventFilters{}
- if items, err := agent.Get(); err != nil {
- return nil, status.Errorf(codes.Internal, err.Error())
- } else if items != nil {
- list, ok := items.([]interface{})
- if !ok {
- list = []interface{}{items}
- }
- for _, item := range list {
- eventFilters.Filters = append(eventFilters.Filters, item.(*voltha.EventFilter))
- }
- return eventFilters, nil
- }
-
- return eventFilters, status.Errorf(codes.NotFound, "no-event-filters")
-}
-
-// GetEventFilter returns the event filter associated to the provided device id
-func (mpMgr *ModelProxyManager) GetEventFilter(ctx context.Context, id string) (*voltha.EventFilters, error) {
- log.Debugw("GetEventFilter", log.Fields{"id": id})
-
- var agent *ModelProxy
- var exists bool
-
- if agent, exists = mpMgr.modelProxy[EventFilters.String()]; !exists {
- agent = newModelProxy("event_filters", mpMgr.clusterDataProxy)
- mpMgr.modelProxy[EventFilters.String()] = agent
- }
-
- if _, err := agent.Get(id); err != nil {
- return nil, status.Errorf(codes.Internal, err.Error())
- }
- //TODO: VOL-2305 Code to get filters for a particular device once Event filtering mechanism is implemented
-
- return &voltha.EventFilters{}, status.Errorf(codes.NotFound, "event-filter-%s", id)
-}
diff --git a/ro_core/core/model_proxy_manager_test.go b/ro_core/core/model_proxy_manager_test.go
deleted file mode 100644
index b23781b..0000000
--- a/ro_core/core/model_proxy_manager_test.go
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "context"
- "reflect"
- "testing"
-
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "github.com/stretchr/testify/assert"
-)
-
-func makeModelProxyManagerObj() *ModelProxyManager {
- cdRoot := model.NewRoot(&voltha.Voltha{}, nil)
- cdProxy, err := cdRoot.CreateProxy(context.Background(), "/", false)
- if err != nil {
- log.With(log.Fields{"error": err}).Fatal("Failed to create model proxy manager")
- }
- mpMgr := newModelProxyManager(cdProxy)
- return mpMgr
-}
-
-func TestNewModelProxyManager(t *testing.T) {
- type args struct {
- clusterDataProxy *model.Proxy
- }
- tests := []struct {
- name string
- args args
- want *ModelProxyManager
- }{
- {"NewModelProxyManager", args{&model.Proxy{}}, &ModelProxyManager{}},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := newModelProxyManager(tt.args.clusterDataProxy); reflect.TypeOf(got) != reflect.TypeOf(tt.want) {
- t.Errorf("newModelProxy() = %v, want %v", got, tt.want)
- }
- })
- }
-}
-
-func TestGetVoltha(t *testing.T) {
- wantResult := &voltha.Voltha{}
- mpMgr := makeModelProxyManagerObj()
- result, err := mpMgr.GetVoltha(context.Background())
- if reflect.TypeOf(result) != reflect.TypeOf(wantResult) {
- t.Errorf("GetVoltha() = %v, want %v", result, wantResult)
- }
- assert.NotNil(t, result)
- assert.Nil(t, err)
-}
-
-func TestListCoreInstances(t *testing.T) {
- wantResult := &voltha.CoreInstances{}
- mpMgr := makeModelProxyManagerObj()
- result, err := mpMgr.ListCoreInstances(context.Background())
- if reflect.TypeOf(result) != reflect.TypeOf(wantResult) {
- t.Errorf("ListCoreInstances() = %v, want %v", result, wantResult)
- }
- assert.Nil(t, result.Items)
- assert.NotNil(t, err)
-}
-
-func TestGetCoreInstance(t *testing.T) {
- wantResult := &voltha.CoreInstance{}
- mpMgr := makeModelProxyManagerObj()
- result, err := mpMgr.GetCoreInstance(context.Background(), "id")
- if reflect.TypeOf(result) != reflect.TypeOf(wantResult) {
- t.Errorf("GetCoreInstance() = %v, want %v", result, wantResult)
- }
- assert.NotNil(t, err)
-}
-
-func TestListAdapters(t *testing.T) {
- wantResult := &voltha.Adapters{
- Items: []*voltha.Adapter{
- {
- Id: "id",
- },
- },
- }
-
- mpMgr := makeModelProxyManagerObj()
-
- // Case 1: Not Found
- result0, err0 := mpMgr.ListAdapters(context.Background())
- if reflect.TypeOf(result0) != reflect.TypeOf(wantResult) {
- t.Errorf("ListAdapters() = %v, want %v", result0, wantResult)
- }
- assert.Nil(t, result0.Items)
- assert.Nil(t, err0)
-
- // Case 2: Found
- added, err := mpMgr.clusterDataProxy.Add(context.Background(), "/adapters", &voltha.Adapter{Id: "id"}, "")
- if err != nil {
- log.Errorw("failed-to-add-adapter-to-cluster-proxy", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add adapter")
- }
- result1, err1 := mpMgr.ListAdapters(context.Background())
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("ListAdapters() = %v, want %v", result1, wantResult)
- }
- assert.NotNil(t, result1.Items)
- assert.Nil(t, err1)
- assert.Equal(t, wantResult, result1)
-}
-
-func TestListDeviceTypes(t *testing.T) {
- wantResult := &voltha.DeviceTypes{
- Items: []*voltha.DeviceType{
- {
- Id: "id",
- },
- },
- }
-
- mpMgr := makeModelProxyManagerObj()
-
- // Case 1: Not Found
- result0, err0 := mpMgr.ListDeviceTypes(context.Background())
- if reflect.TypeOf(result0) != reflect.TypeOf(wantResult) {
- t.Errorf("ListDeviceTypes() = %v, want %v", result0, wantResult)
- }
- assert.Nil(t, result0.Items)
- assert.Nil(t, err0)
-
- // Case 2: Found
- added, err := mpMgr.clusterDataProxy.Add(context.Background(), "/device_types", &voltha.DeviceType{Id: "id"}, "")
- if err != nil {
- log.Errorw("failed-to-add-device-types-to-cluster-proxy", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add device type")
- }
- result1, err1 := mpMgr.ListDeviceTypes(context.Background())
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("ListDeviceTypes() = %v, want %v", result1, wantResult)
- }
- assert.NotNil(t, result1.Items)
- assert.Nil(t, err1)
- assert.Equal(t, wantResult, result1)
-}
-
-func TestGetDeviceType(t *testing.T) {
- wantResult := &voltha.DeviceType{}
- mpMgr := makeModelProxyManagerObj()
-
- // Case 1: Not Found
- result0, err0 := mpMgr.GetDeviceType(context.Background(), "id")
- if reflect.TypeOf(result0) != reflect.TypeOf(wantResult) {
- t.Errorf("GetDeviceType() = %v, want %v", result0, wantResult)
- }
- assert.Nil(t, result0)
- assert.NotNil(t, err0)
-
- // Case 2: Found
- added, err := mpMgr.clusterDataProxy.Add(context.Background(), "/device_types", &voltha.DeviceType{Id: "id"}, "")
- if err != nil {
- log.Errorw("failed-to-add-adapter-to-device-types-proxy", log.Fields{"error": err})
- assert.NotNil(t, err)
- } else if added == nil {
- t.Error("Failed to add device type")
- }
- result1, err1 := mpMgr.GetDeviceType(context.Background(), "id")
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("GetDeviceType() = %v, want %v", result1, wantResult)
- }
- assert.NotNil(t, result1)
- assert.Nil(t, err1)
- assert.Equal(t, "id", result1.Id)
-}
-
-func TestListDeviceGroups(t *testing.T) {
- wantResult := &voltha.DeviceGroups{
- Items: []*voltha.DeviceGroup{
- {
- Id: "id",
- },
- },
- }
-
- mpMgr := makeModelProxyManagerObj()
-
- // Case 1: Not Found
- result0, err0 := mpMgr.ListDeviceGroups(context.Background())
- if reflect.TypeOf(result0) != reflect.TypeOf(wantResult) {
- t.Errorf("ListDeviceGroups() = %v, want %v", result0, wantResult)
- }
- assert.Nil(t, result0.Items)
- assert.Nil(t, err0)
-
- // Case 2: Found
- added, err := mpMgr.clusterDataProxy.Add(context.Background(), "/device_groups", &voltha.DeviceGroup{Id: "id"}, "")
- if err != nil {
- log.Errorw("failed-to-add-device-groups-to-cluster-proxy", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add device group")
- }
- result1, err1 := mpMgr.ListDeviceGroups(context.Background())
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("ListDeviceGroups() = %v, want %v", result1, wantResult)
- }
- assert.NotNil(t, result1.Items)
- assert.Nil(t, err1)
- assert.Equal(t, wantResult, result1)
-}
-
-func TestGetDeviceGroup(t *testing.T) {
- wantResult := &voltha.DeviceGroup{}
- mpMgr := makeModelProxyManagerObj()
-
- // Case 1: Not Found
- result0, err0 := mpMgr.GetDeviceGroup(context.Background(), "id")
- if reflect.TypeOf(result0) != reflect.TypeOf(wantResult) {
- t.Errorf("GetDeviceGroup() = %v, want %v", result0, wantResult)
- }
- assert.Nil(t, result0)
- assert.NotNil(t, err0)
-
- // Case 2: Found
- added, err := mpMgr.clusterDataProxy.Add(context.Background(), "/device_groups", &voltha.DeviceGroup{Id: "id"}, "")
- if err != nil {
- log.Errorw("failed-to-add-device-groups-to-cluster-proxy", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add device group")
- }
- result1, err1 := mpMgr.GetDeviceGroup(context.Background(), "id")
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("GetDeviceGroup() = %v, want %v", result1, wantResult)
- }
- assert.NotNil(t, result1)
- assert.Nil(t, err1)
- assert.Equal(t, "id", result1.Id)
-}
-
-func TestListEventFilters(t *testing.T) {
- wantResult := &voltha.EventFilters{
- Filters: []*voltha.EventFilter{
- {
- Id: "id",
- },
- },
- }
-
- mpMgr := makeModelProxyManagerObj()
-
- // Case 1: Not Found
- result0, err0 := mpMgr.ListEventFilters(context.Background())
- if reflect.TypeOf(result0) != reflect.TypeOf(wantResult) {
- t.Errorf("ListEventFilters() = %v, want %v", result0, wantResult)
- }
- assert.Nil(t, result0.Filters)
- assert.Nil(t, err0)
-
- // Case 2: Found
- added, err := mpMgr.clusterDataProxy.Add(context.Background(), "/event_filters", &voltha.EventFilter{Id: "id"}, "")
- if err != nil {
- log.Errorw("failed-to-add-alarm-filters-to-cluster-proxy", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add event filter")
- }
- result1, err1 := mpMgr.ListEventFilters(context.Background())
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("ListEventFilters() = %v, want %v", result1, wantResult)
- }
- assert.NotNil(t, result1.Filters)
- assert.Nil(t, err1)
- assert.Equal(t, wantResult, result1)
-}
-
-func TestGetEventFilter(t *testing.T) {
- wantResult := &voltha.EventFilters{
- Filters: []*voltha.EventFilter{
- {
- Id: "id",
- },
- },
- }
-
- mpMgr := makeModelProxyManagerObj()
-
- // Case 1: Not Found
- result0, _ := mpMgr.GetEventFilter(context.Background(), "id")
- if reflect.TypeOf(result0) != reflect.TypeOf(wantResult) {
- t.Errorf("GetEventFilters() = %v, want %v", result0, wantResult)
- }
- assert.Nil(t, result0)
- // Case 2: Found
- //added, err := mpMgr.clusterDataProxy.Add(context.Background(), "/alarm_filters", &voltha.EventFilter{Id: "id"}, "")
- added, err := mpMgr.clusterDataProxy.Add(context.Background(), "/event_filters", &voltha.EventFilter{Id: "id"}, "")
- if err != nil {
- log.Errorw("failed-to-add-adapter-to-alarm-filter-to-proxy", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- if added == nil {
- t.Error("Failed to add event filter")
- }
- result1, err1 := mpMgr.ListEventFilters(context.Background())
- if reflect.TypeOf(result1) != reflect.TypeOf(wantResult) {
- t.Errorf("GetEventFilters() = %v, want %v", result1, wantResult)
- }
- assert.NotNil(t, result1)
- assert.Nil(t, err1)
- assert.Equal(t, wantResult, result1)
-
-}
diff --git a/ro_core/core/model_proxy_test.go b/ro_core/core/model_proxy_test.go
deleted file mode 100644
index 41f814c..0000000
--- a/ro_core/core/model_proxy_test.go
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright 2019-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package core
-
-import (
- "context"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/stretchr/testify/assert"
- "reflect"
- "testing"
-
- "github.com/opencord/voltha-go/db/model"
- "github.com/opencord/voltha-protos/v3/go/voltha"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-)
-
-type fields struct {
- rootProxy *model.Proxy
- basePath string
-}
-
-func getModelProxyPathNotFound(t *testing.T) *fields {
- var modelProxy fields
-
- TestProxyRoot := model.NewRoot(&voltha.Voltha{}, nil)
- TestProxyRootProxy, err := TestProxyRoot.CreateProxy(context.Background(), "/", false)
- if err != nil {
- log.Errorw("failed-to-create-test-proxy", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- modelProxy.rootProxy = TestProxyRootProxy
- modelProxy.basePath = "base_path"
-
- return &modelProxy
-}
-
-func getModelProxyPathFound(t *testing.T) *fields {
- var modelProxy fields
-
- TestProxyRoot := model.NewRoot(&voltha.Voltha{}, nil)
- TestProxyRootProxy, err := TestProxyRoot.CreateProxy(context.Background(), "/", false)
- if err != nil {
- log.Errorw("failed-to-create-test-proxy", log.Fields{"error": err})
- assert.NotNil(t, err)
- }
- modelProxy.rootProxy = TestProxyRootProxy
- modelProxy.basePath = "devices"
-
- return &modelProxy
-}
-
-func testModelProxyObject(testModelProxy *fields) *ModelProxy {
- return &ModelProxy{
- rootProxy: testModelProxy.rootProxy,
- basePath: testModelProxy.basePath,
- }
-}
-
-func TestNewModelProxy(t *testing.T) {
- type args struct {
- basePath string
- rootProxy *model.Proxy
- }
- tests := []struct {
- name string
- args args
- want *ModelProxy
- }{
- {"NewModelProxy-1", args{"base_path", &model.Proxy{}}, &ModelProxy{}},
- {"NewModelProxy-2", args{"/base_path", &model.Proxy{}}, &ModelProxy{}},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := newModelProxy(tt.args.basePath, tt.args.rootProxy); reflect.TypeOf(got) != reflect.TypeOf(tt.want) {
- t.Errorf("newModelProxy() = %v, want %v", got, tt.want)
- }
- })
- }
-}
-
-func TestModelProxy_Get(t *testing.T) {
- tests := []struct {
- name string
- fields *fields
- wantErr error
- }{
- {"Get-PathNotFound", getModelProxyPathNotFound(t), status.Errorf(codes.NotFound, "data-path: base_path")},
- {"Get-PathFound", getModelProxyPathFound(t), nil},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- ModelProxyObj := testModelProxyObject(tt.fields)
- _, err := ModelProxyObj.Get()
- if err != nil && reflect.TypeOf(err) != reflect.TypeOf(tt.wantErr) {
- t.Errorf("Get() error = %t, wantErr %t", err, tt.wantErr)
- }
- })
- }
-}
diff --git a/ro_core/main.go b/ro_core/main.go
deleted file mode 100644
index 141a07f..0000000
--- a/ro_core/main.go
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package main
-
-import (
- "context"
- "errors"
- "fmt"
- "os"
- "os/signal"
- "strconv"
- "syscall"
- "time"
-
- "github.com/opencord/voltha-go/ro_core/config"
- c "github.com/opencord/voltha-go/ro_core/core"
- "github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "github.com/opencord/voltha-lib-go/v3/pkg/probe"
- "github.com/opencord/voltha-lib-go/v3/pkg/version"
- ic "github.com/opencord/voltha-protos/v3/go/inter_container"
-)
-
-type roCore struct {
- kvClient kvstore.Client
- config *config.ROCoreFlags
- halted bool
- exitChannel chan int
- core *c.Core
- //For test
- receiverChannels []<-chan *ic.InterContainerMessage
-}
-
-func init() {
- _, err := log.AddPackage(log.JSON, log.DebugLevel, nil)
- if err != nil {
- log.Errorw("unable-to-register-package-to-the-log-map", log.Fields{"error": err})
- }
-}
-
-func newKVClient(storeType string, address string, timeout int) (kvstore.Client, error) {
-
- log.Infow("kv-store-type", log.Fields{"store": storeType})
- switch storeType {
- case "consul":
- return kvstore.NewConsulClient(address, timeout)
- case "etcd":
- return kvstore.NewEtcdClient(address, timeout)
- }
- return nil, errors.New("unsupported-kv-store")
-}
-
-func newROCore(cf *config.ROCoreFlags) *roCore {
- var roCore roCore
- roCore.config = cf
- roCore.halted = false
- roCore.exitChannel = make(chan int, 1)
- roCore.receiverChannels = make([]<-chan *ic.InterContainerMessage, 0)
- return &roCore
-}
-
-func (ro *roCore) setKVClient() error {
- addr := ro.config.KVStoreHost + ":" + strconv.Itoa(ro.config.KVStorePort)
- client, err := newKVClient(ro.config.KVStoreType, addr, ro.config.KVStoreTimeout)
- if err != nil {
- ro.kvClient = nil
- log.Error(err)
- return err
- }
- ro.kvClient = client
- return nil
-}
-
-func (ro *roCore) start(ctx context.Context) {
- log.Info("Starting RW Core components")
-
- // If the context has a probe then fetch it and register our services
- var p *probe.Probe
- if value := ctx.Value(probe.ProbeContextKey); value != nil {
- if _, ok := value.(*probe.Probe); ok {
- p = value.(*probe.Probe)
- p.RegisterService(
- "kv-store",
- "device-manager",
- "logical-device-manager",
- "grpc-service",
- )
- }
- }
-
- // Setup KV Client
- log.Debugw("create-kv-client", log.Fields{"kvstore": ro.config.KVStoreType})
-
- if err := ro.setKVClient(); err != nil {
- log.Fatalw("failed-to-connect-kv-client", log.Fields{"error": err})
- return
- }
-
- // Create the core service
- ro.core = c.NewCore(ctx, ro.config.InstanceID, ro.config, ro.kvClient)
-
- if p != nil {
- p.UpdateStatus("kv-store", probe.ServiceStatusPrepared)
- }
-
- // start the core
- if err := ro.core.Start(ctx); err != nil {
- log.Fatalf("failed-to-start-rocore", log.Fields{"error": err})
- }
-}
-
-func (ro *roCore) stop(ctx context.Context) {
- // Stop leadership tracking
- ro.halted = true
-
- // send exit signal
- ro.exitChannel <- 0
-
- // Cleanup - applies only if we had a kvClient
- if ro.kvClient != nil {
- // Release all reservations
- if err := ro.kvClient.ReleaseAllReservations(); err != nil {
- log.Infow("fail-to-release-all-reservations", log.Fields{"error": err})
- }
- // Close the DB connection
- ro.kvClient.Close()
- }
-
- ro.core.Stop(ctx)
-}
-
-func waitForExit() int {
- signalChannel := make(chan os.Signal, 1)
- signal.Notify(signalChannel,
- syscall.SIGHUP,
- syscall.SIGINT,
- syscall.SIGTERM,
- syscall.SIGQUIT)
-
- exitChannel := make(chan int)
-
- go func() {
- s := <-signalChannel
- switch s {
- case syscall.SIGHUP,
- syscall.SIGINT,
- syscall.SIGTERM,
- syscall.SIGQUIT:
- log.Infow("closing-signal-received", log.Fields{"signal": s})
- exitChannel <- 0
- default:
- log.Infow("unexpected-signal-received", log.Fields{"signal": s})
- exitChannel <- 1
- }
- }()
-
- code := <-exitChannel
- return code
-}
-
-func printBanner() {
- fmt.Println()
- fmt.Println(" ____ ___ ____ ")
- fmt.Println("| _ \\ / _ \\ / ___|___ _ __ ___ ")
- fmt.Println("| |_) | | | | | / _ \\| '__/ _ \\")
- fmt.Println("| _ <| |_| | |__| (_) | | | __/")
- fmt.Println("|_| \\_\\\\___/ \\____\\___/|_| \\___|")
- fmt.Println()
-
-}
-
-func printVersion() {
- fmt.Println("VOLTHA Read-Only Core")
- fmt.Println(version.VersionInfo.String(" "))
-}
-
-func main() {
- start := time.Now()
-
- cf := config.NewROCoreFlags()
- cf.ParseCommandArguments()
-
- //// Setup logging
-
- //Setup default logger - applies for packages that do not have specific logger set
- if _, err := log.SetDefaultLogger(log.JSON, cf.LogLevel, log.Fields{"instanceID": cf.InstanceID}); err != nil {
- log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
- }
-
- // Update all loggers (provisionned via init) with a common field
- if err := log.UpdateAllLoggers(log.Fields{"instanceID": cf.InstanceID}); err != nil {
- log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
- }
-
- log.SetPackageLogLevel("github.com/opencord/voltha-go/ro_core/core", log.DebugLevel)
-
- defer func() {
- err := log.CleanUp()
- if err != nil {
- log.Errorw("unable-to-flush-any-buffered-log-entries", log.Fields{"error": err})
- }
- }()
-
- // Print verison / build information and exit
- if cf.DisplayVersionOnly {
- printVersion()
- return
- }
-
- // Print banner if specified
- if cf.Banner {
- printBanner()
- }
-
- log.Infow("ro-core-config", log.Fields{"config": *cf})
-
- // Create the RO Core
- ro := newROCore(cf)
-
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
-
- /*
- * Create and start the liveness and readiness container management probes. This
- * is done in the main function so just in case the main starts multiple other
- * objects there can be a single probe end point for the process.
- */
- p := &probe.Probe{}
- go p.ListenAndServe(fmt.Sprintf("%s:%d", ro.config.ProbeHost, ro.config.ProbePort))
-
- // Add the probe to the context to pass to all the services started
- probeCtx := context.WithValue(ctx, probe.ProbeContextKey, p)
-
- // Start the RO core
- go ro.start(probeCtx)
-
- code := waitForExit()
- log.Infow("received-a-closing-signal", log.Fields{"code": code})
-
- // Cleanup before leaving
- ro.stop(probeCtx)
-
- elapsed := time.Since(start)
- log.Infow("ro-core-run-time", log.Fields{"core": ro.config.InstanceID, "time": elapsed / time.Second})
-}
diff --git a/tests/afrouter/arouter_test.json b/tests/afrouter/arouter_test.json
deleted file mode 100644
index d58f26d..0000000
--- a/tests/afrouter/arouter_test.json
+++ /dev/null
@@ -1,205 +0,0 @@
-{
- "servers": [
- {
- "name": "grpc_command",
- "port": 5000,
- "address":"",
- "type": "grpc",
- "routers": [
- {
- "_TODO":"Suport a router list, remove the package and service from the router",
- "package":"voltha",
- "service":"VolthaService",
- "router":"vcore"
- }
- ]
- }
- ],
- "routers": [
- {
- "name":"vcore",
- "package": "voltha",
- "service": "VolthaService",
- "routes": [
- {
- "name":"dev_manager",
- "proto_descriptor":"voltha.pb",
- "type":"rpc_affinity_message",
- "association":"round_robin",
- "routing_field": "id",
- "backend_cluster":"vcore",
- "_COMMENT":"Methods are naturally southbound affinity binding unless otherwise specified below",
- "methods":[ "CreateDevice",
- "EnableLogicalDevicePort",
- "DisableLogicalDevicePort",
- "UpdateLogicalDeviceFlowTable",
- "UpdateLogicalDeviceFlowGroupTable",
- "EnableDevice",
- "DisableDevice",
- "RebootDevice",
- "DeleteDevice",
- "DownloadImage",
- "CancelImageDownload",
- "ActivateImageUpdate",
- "RevertImageUpdate",
- "UpdateDevicePmConfigs",
- "CreateAlarmFilter",
- "UpdateAlarmFilter",
- "DeleteAlarmFilter",
- "SelfTest"],
- "_COMMENT":"If a method is northbound affinity binding then association is used to route",
- "_COMMENT":"but affinity is not set southbound but only based on the response",
- "_COMMENT":"Methods here MUST be specified above, this overrides thier default beahvior",
- "nb_binding_methods":["CreateDevice"],
- "_TODO":"Overrides not implemented yet, config ignored",
- "overrides": [
- {"methods":["abc","def"], "routing_field":"id"},
- {"methods":["ghi","jkl"]},
- {"method":"mno", "routing_field":"id"},
- {"method":"pqr"}
- ]
- },
- {
- "name":"control",
- "type":"round_robin",
- "association":"round_robin",
- "backend_cluster":"vcore",
- "methods":[
- "UpdateLogLevel"
- ]
- },
- {
- "name":"read_only",
- "type":"round_robin",
- "association":"round_robin",
- "backend_cluster":"vcore",
- "methods":[ "ListDevicePorts",
- "ListDevicePmConfigs",
- "GetImages",
- "GetImageDownloadStatus",
- "GetImageDownload",
- "ListImageDownloads",
- "ListDeviceFlows",
- "ListDeviceFlowGroups",
- "ListLogicalDeviceFlows",
- "ListLogicalDeviceFlowGroups",
- "ListDevices",
- "GetDevice",
- "GetDeviceType",
- "GetDeviceGroup",
- "GetLogicalDevice",
- "GetAlarmFilter",
- "ListLogicalDevices",
- "ListLogicalDevicePorts",
- "GetLogicalDevicePort",
- "GetVoltha",
- "ListCoreInstances",
- "ListAdapters",
- "ListDeviceIds",
- "ListDeviceTypes",
- "ListDeviceGroups",
- "ListAlarmFilters",
- "GetCoreInstance"
- ]
- },
- {
- "name":"dev_manager_ofagent",
- "type":"binding",
- "_association":"round_robin",
- "binding": {
- "type":"header",
- "field":"voltha_backend_name",
- "method":"Subscribe",
- "association":"round_robin"
- },
- "backend_cluster":"vcore",
- "methods":["StreamPacketsOut",
- "Subscribe",
- "ListLogicalDevices",
- "ListDeviceFlowGroups",
- "ListLogicalDeviceFlowGroups",
- "ListDeviceFlows",
- "UpdateLogicalDeviceFlowTable",
- "UpdateLogicalDeviceFlowGroupTable",
- "ListLogicalDeviceFlows"
- ],
- "_TODO":"Overrides not implemented yet, config ignored",
- "overrides": [
- {"methods":["abc","def"], "routing_field":"id"},
- {"methods":["ghi","jkl"]},
- {"method":"mno", "routing_field":"id"},
- {"method":"pqr"}
- ]
- }
- ]
- }
- ],
- "backend_clusters": [
- {
- "name":"vcore",
- "backends":[ {
- "name":"vcore1",
- "type":"active_active",
- "association": {
- "strategy":"serial_number",
- "location":"header",
- "_TODO":"The key below needs to be implemented, currently hard coded",
- "key":"voltha_serial_number"
- },
- "connections": [ {
- "name":"vcore11",
- "addr":"127.0.0.1",
- "port":"5011"
- },
- {
- "name":"vcore12",
- "addr":"127.0.0.1",
- "port":"5012"
- }]
- },
- {
- "name":"vcore2",
- "type":"active_active",
- "association": {
- "strategy":"serial_number",
- "location":"header",
- "key":"voltha_serial_number"
- },
- "connections": [ {
- "name":"vcore21",
- "addr":"127.0.0.1",
- "port":"5021"
- },
- {
- "name":"vcore22",
- "addr":"127.0.0.1",
- "port":"5022"
- }]
- },
- {
- "name":"vcore3",
- "type":"active_active",
- "association": {
- "strategy":"serial_number",
- "location":"header",
- "key":"voltha_serial_number"
- },
- "connections": [ {
- "name":"vcore31",
- "addr":"127.0.0.1",
- "port":"5031"
- },
- {
- "name":"vcore32",
- "addr":"127.0.0.1",
- "port":"5032"
- }]
- }]
- }
- ],
- "api": {
- "_comment":"If this isn't defined then no api is available for dynamic configuration and queries",
- "address":"",
- "port":55554
- }
-}
diff --git a/tests/afrouter/suites/main.json b/tests/afrouter/suites/main.json
deleted file mode 100644
index 594bc8a..0000000
--- a/tests/afrouter/suites/main.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
-"__COMMENT":"Top level test driver file",
-"suites": [
- "test1",
- "test2",
- "test3"
- ]
-}
diff --git a/tests/afrouter/suites/test1/test1.json b/tests/afrouter/suites/test1/test1.json
deleted file mode 100644
index 14be12c..0000000
--- a/tests/afrouter/suites/test1/test1.json
+++ /dev/null
@@ -1,223 +0,0 @@
-{
- "environment":{
- "cmdLine":"afrouter -logLevel 1 -config arouter_test.json",
- "protoFiles": [
- {
- "importPath":"github.com/opencord/voltha-protos/v3/go/",
- "service":"VolthaService",
- "package":"voltha"
- },
- {
- "importPath":"github.com/opencord/voltha-protos/v3/go/",
- "service":"Configuration",
- "package":"afrouter"
- }
- ],
- "Junk": [
- {
- "importPath":"github.com/opencord/voltha-protos/v3/go/",
- "service":"Configuration",
- "package":"afrouter"
- }
- ],
- "imports": [
- "github.com/opencord/voltha-protos/v3/go/common"
- ],
- "protoDesc":"voltha.pb",
- "protoSubst": [
- {
- "from":"google.protobuf.Empty",
- "to":"empty.Empty"
- }
- ],
- "clients": {
- "imports": [
- "github.com/golang/protobuf/ptypes/empty",
- "github.com/opencord/voltha-protos/v3/go/openflow_13",
- "github.com/opencord/voltha-protos/v3/go/common"
- ],
- "endpoints": [
- {
- "name":"client",
- "port":"5000"
- },
- {
- "name":"stats",
- "port":"55554"
- }
- ]
- },
- "servers": {
- "imports": [
- "github.com/golang/protobuf/ptypes/empty",
- "github.com/opencord/voltha-protos/v3/go/openflow_13",
- "github.com/opencord/voltha-protos/v3/go/common",
- "github.com/opencord/voltha-protos/v3/go/omci"
- ],
- "endpoints": [
- {
- "name":"core11",
- "port":"5011"
- },
- {
- "name":"core12",
- "port":"5012"
- },
- {
- "name":"core21",
- "port":"5021"
- },
- {
- "name":"core22",
- "port":"5022"
- },
- {
- "name":"core31",
- "port":"5031"
- },
- {
- "name":"core32",
- "port":"5032"
- },
- {
- "name":"roCore1",
- "port":"5001"
- },
- {
- "name":"roCore2",
- "port":"5002"
- },
- {
- "name":"roCore3",
- "port":"5003"
- }
- ]
- }
- },
- "tests":[
- {
- "name":"Test CreateDevice",
- "send": {
- "client":"client",
- "method":"CreateDevice",
- "param":"{Type:\"simulated_olt\"}",
- "expect":"{Id:\"abcd1234\",Type:\"simulated_olt\"}",
- "_meta":"",
- "_expectMeta":""
- },
- "servers": [
- {
- "name":"core11",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"0"
- }
- ]
- },
- {
- "name":"core12",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"0"
- }
- ]
- }
- ]
- },
- {
- "name":"Test GetDevice",
- "send": {
- "client":"client",
- "method":"GetDevice",
- "param":"{Id:\"abcd1234\"}",
- "expect":"{Id:\"abcd1234\",Type:\"simulated_olt\"}",
- "_meta":"",
- "_expectMeta":""
- },
- "servers": [
- {
- "name":"core11",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"1"
- }
- ]
- },
- {
- "name":"core12",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"1"
- }
- ]
- }
- ]
- },
- {
- "name":"Test Subscribe",
- "send": {
- "client":"client",
- "method":"Subscribe",
- "param":"{OfagentId:\"Agent007\"}",
- "meta": [
- {
- "key":"voltha_backend_name",
- "value":""
- }
- ],
- "expect":"{OfagentId:\"Agent007\",VolthaId:\"core11\"}",
- "expectMeta": [
- {
- "key":"voltha_backend_name",
- "value":"vcore1"
- }
- ]
- },
- "servers": [
- {
- "name":"core11",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"2"
- },
- {
- "key":"voltha_backend_name",
- "value":""
- }
- ]
- },
- {
- "name":"core12",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"2"
- },
- {
- "key":"voltha_backend_name",
- "value":""
- }
- ]
- }
- ]
- },
- {
- "name":"Get goroutine count",
- "infoOnly":true,
- "send": {
- "client":"stats",
- "method":"GetGoroutineCount",
- "param":"{}",
- "meta": [ ],
- "expect":"{Count:43}",
- "expectMeta": [ ]
- },
- "servers": [ ]
- }
- ]
-}
diff --git a/tests/afrouter/suites/test2/test2.go b/tests/afrouter/suites/test2/test2.go
deleted file mode 100644
index 68ce93c..0000000
--- a/tests/afrouter/suites/test2/test2.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// +build integration
-
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package main
-
-import (
- "os"
- //"fmt"
- //"flag"
- //"path"
- //"bufio"
- //"errors"
- //"os/exec"
- //"strconv"
- //"io/ioutil"
- //"encoding/json"
- "text/template"
- //"github.com/golang/protobuf/proto"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- //pb "github.com/golang/protobuf/protoc-gen-go/descriptor"
-)
-
-type test struct {
- Core int
- SerNo int
-}
-
-type suite struct {
- CrTests []test
- GetTests []test
-}
-
-const SUITE_LEN = 55000
-
-//const SUITE_LEN = 100
-
-func main() {
-
- var ary suite
-
- // Setup logging
- if _, err := log.SetDefaultLogger(log.JSON, 0, nil); err != nil {
- log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
- }
-
- for i := 0; i < SUITE_LEN; i++ {
- ary.CrTests = append(ary.CrTests, test{Core: (i % 3) + 1, SerNo: i})
- ary.GetTests = append(ary.GetTests, test{Core: (i % 3) + 1, SerNo: i + SUITE_LEN})
- }
-
- // Load the template to execute
- t := template.Must(template.New("").ParseFiles("./test2.tmpl.json"))
- if f, err := os.Create("test2.json"); err == nil {
- defer f.Close()
- if err := t.ExecuteTemplate(f, "test2.tmpl.json", ary); err != nil {
- log.Errorf("Unable to execute template for test2.tmpl.json: %v", err)
- }
- } else {
- log.Errorf("Couldn't create file test2.json: %v", err)
- }
- return
-}
diff --git a/tests/afrouter/suites/test2/test2.tmpl.json b/tests/afrouter/suites/test2/test2.tmpl.json
deleted file mode 100644
index 34ea334..0000000
--- a/tests/afrouter/suites/test2/test2.tmpl.json
+++ /dev/null
@@ -1,239 +0,0 @@
-{
- "environment":{
- "cmdLine":"afrouter -config arouter_test.json -logLevel 1",
- "protoFiles": [
- {
- "importPath":"github.com/opencord/voltha-protos/v3/go/",
- "service":"VolthaService",
- "package":"voltha"
- },
- {
- "importPath":"github.com/opencord/voltha-protos/v3/go/",
- "service":"Configuration",
- "package":"afrouter"
- }
- ],
- "imports": [
- "github.com/golang/protobuf/ptypes/empty",
- "github.com/opencord/voltha-protos/v3/go/common"
- ],
- "protoDesc":"voltha.pb",
- "protoSubst": [
- {
- "from":"google.protobuf.Empty",
- "to":"empty.Empty"
- }
- ],
- "clients": {
- "imports": [
- "github.com/golang/protobuf/ptypes/empty",
- "github.com/opencord/voltha-protos/v3/go/openflow_13",
- "github.com/opencord/voltha-protos/v3/go/common"
- ],
- "endpoints": [
- {
- "name":"client",
- "port":"5000"
- },
- {
- "name":"stats",
- "port":"55554"
- }
- ]
- },
- "servers": {
- "imports": [
- "github.com/golang/protobuf/ptypes/empty",
- "github.com/opencord/voltha-protos/v3/go/openflow_13",
- "github.com/opencord/voltha-protos/v3/go/omci",
- "github.com/opencord/voltha-protos/v3/go/common"
- ],
- "endpoints": [
- {
- "name":"core11",
- "port":"5011"
- },
- {
- "name":"core12",
- "port":"5012"
- },
- {
- "name":"core21",
- "port":"5021"
- },
- {
- "name":"core22",
- "port":"5022"
- },
- {
- "name":"core31",
- "port":"5031"
- },
- {
- "name":"core32",
- "port":"5032"
- }
- ]
- }
- },
- "tests":[
- {{range $k,$v := .CrTests}}
- {
- "name":"Test CreateDevice",
- "send": {
- "client":"client",
- "method":"CreateDevice",
- "param":"{Type:\"simulated_olt\"}",
- "expect":"{Id:\"abcd1234{{$k}}\",Type:\"simulated_olt\"}",
- "_meta":""
- },
- "servers": [
- {
- "name":"core{{$v.Core}}1",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"{{$v.SerNo}}"
- }
- ]
- },
- {
- "name":"core{{$v.Core}}2",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"{{$v.SerNo}}"
- }
- ]
- }
- ]
- },
- {{end}}
- {{range $k,$v := .GetTests}}
- {
- "name":"Test EnableDevice",
- "send": {
- "client":"client",
- "_method":"GetDevice",
- "method":"EnableDevice",
- "param":"{Id:\"abcd1234{{$k}}\"}",
- "expect":"{}",
- "_expect":"{Id:\"abcd1234{{$k}}\",Type:\"simulated_olt\"}",
- "_meta":""
- },
- "servers": [
- {
- "name":"core{{$v.Core}}1",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"{{$v.SerNo}}"
- }
- ]
- },
- {
- "name":"core{{$v.Core}}2",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"{{$v.SerNo}}"
- }
- ]
- }
- ]
- },
- {{end}}
- {
- "name":"Test GetDevice",
- "send": {
- "client":"client",
- "method":"GetDevice",
- "param":"{Id:\"abcd12340\"}",
- "expect":"{Id:\"abcd12340\",Type:\"simulated_olt\"}",
- "_meta":""
- },
- "servers": [
- {
- "name":"core11",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"110000"
- }
- ]
- },
- {
- "name":"core12",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"110000"
- }
- ]
- }
- ]
- },
- {
- "name":"Test Subscribe",
- "send": {
- "client":"client",
- "method":"Subscribe",
- "param":"{OfagentId:\"Agent007\"}",
- "meta": [
- {
- "key":"voltha_backend_name",
- "value":""
- }
- ],
- "expect":"{OfagentId:\"Agent007\",VolthaId:\"core11\"}",
- "expectMeta": [
- {
- "key":"voltha_backend_name",
- "value":"vcore1"
- }
- ]
- },
- "servers": [
- {
- "name":"core11",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"110001"
- },
- {
- "key":"voltha_backend_name",
- "value":""
- }
- ]
- },
- {
- "name":"core12",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"110001"
- },
- {
- "key":"voltha_backend_name",
- "value":""
- }
- ]
- }
- ]
- },
- {
- "_COMMENT":"If this test case fails, there could be a goroutine leak",
- "name":"Get goroutine count",
- "send": {
- "client":"stats",
- "method":"GetGoroutineCount",
- "param":"{}",
- "meta": [ ],
- "expect":"{Count:43}",
- "expectMeta": [ ]
- },
- "servers": [ ]
- }
- ]
-}
diff --git a/tests/afrouter/suites/test3/test3.go b/tests/afrouter/suites/test3/test3.go
deleted file mode 100644
index 956152b..0000000
--- a/tests/afrouter/suites/test3/test3.go
+++ /dev/null
@@ -1,420 +0,0 @@
-// +build integration
-
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package main
-
-import (
- "fmt"
- "os"
- //"flag"
- //"path"
- //"bufio"
- "errors"
- //"os/exec"
- //"strconv"
- "io/ioutil"
- //"encoding/json"
- "text/template"
- //"github.com/golang/protobuf/proto"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- //pb "github.com/golang/protobuf/protoc-gen-go/descriptor"
-)
-
-// This test suite validates that the different method types get routed
-// properly. That is, rw methods to the rw cores and ro methods to the
-// ro cores
-type test struct {
- Name string
- Core int
- SerNo int
- Method string
- Param string
- Expect string
-}
-
-type tests struct {
- RoTests []test
- RwTests []test
- CtlTests []test
-}
-
-var roMethods []test = []test{
- {
- Name: "Test GetVoltha",
- Method: "GetVoltha", // rpc GetVoltha(google.protobuf.Empty) returns(Voltha)
- Param: "{}",
- Expect: `{Version:\"abcdef\"}`,
- },
- /*
- {
- Name: "Test ListCoreInstances",
- Method: "ListCoreInstances", // rpc ListCoreInstances(google.protobuf.Empty) returns(CoreInstances)
- Param: "{}",
- Expect: `{Items:[]*voltha.CoreInstance{&voltha.CoreInstance{InstanceId:\"ABC\",Health:&voltha.HealthStatus{State:0}}}}`,
- },
- {
- Name: "Test GetCoreInstance",
- Method: "GetCoreInstance", // rpc GetCoreInstance(ID) returns(CoreInstance)
- Param: `{Id:\"arou8390\"}`,
- Expect: `{InstanceId:\"arou8390\", Health:&voltha.HealthStatus{State:0}}`,
- },*/
- {
- Name: "Test ListAdapters",
- Method: "ListAdapters", // rpc ListAdapters(google.protobuf.Empty) returns(Adapters)
- Param: "{}",
- Expect: `{Items:[]*voltha.Adapter{&voltha.Adapter{Id:\"ABC\", Vendor:\"afrouterTest\", Version:\"Version 1.0\"}}}`,
- },
- {
- Name: "Test ListLogicalDevices",
- Method: "ListLogicalDevices", // rpc ListLogicalDevices(google.protobuf.Empty) returns(LogicalDevices)
- Param: "{}",
- Expect: `{Items:[]*voltha.LogicalDevice{&voltha.LogicalDevice{Id:\"LDevId\", DatapathId:64, RootDeviceId:\"Root\"}}}`,
- },
- {
- Name: "Test GetLogicalDevice",
- Method: "GetLogicalDevice", // rpc GetLogicalDevice(ID) returns(LogicalDevice)
- Param: `{Id:\"ABC123XYZ\"}`,
- Expect: `{Id:\"ABC123XYZ\", DatapathId:64, RootDeviceId:\"Root-of:ABC123XYZ\"}`,
- },
- {
- Name: "Test ListLogicalDevicePorts",
- Method: "ListLogicalDevicePorts", // rpc ListLogicalDevicePorts(ID) returns(LogicalPorts)
- Param: `{Id:\"ABC123XYZ\"}`,
- Expect: `{Items:[]*voltha.LogicalPort{&voltha.LogicalPort{Id:\"PortId-1\", DeviceId:\"ABC12XYZ\", DevicePortNo:64, RootPort:true},&voltha.LogicalPort{Id:\"PortId-2\", DeviceId:\"ABC12XYZ\", DevicePortNo:64, RootPort:false}}}`,
- },
- {
- Name: "Test GetLogicalDevicePort",
- Method: "GetLogicalDevicePort", // rpc GetLogicalDevicePort(LogicalPortId) returns(LogicalPort)
- Param: `{Id:\"PortId-1\"}`,
- Expect: `{Id:\"PortId-1\", DeviceId:\"ABC12XYZ\", DevicePortNo:64, RootPort:true}`,
- },
- {
- Name: "Test ListLogicalDeviceFlows",
- Method: "ListLogicalDeviceFlows", // rpc ListLogicalDeviceFlows(ID) returns(openflow_13.Flows)
- Param: `{Id:\"Flow-ABC123XYZ\"}`,
- Expect: `{Items:[]*openflow_13.OfpFlowStats{&openflow_13.OfpFlowStats{Id:1, TableId:2, DurationSec:12, Priority:0},&openflow_13.OfpFlowStats{Id:1, TableId:2, DurationSec:12, Priority:0}}}`,
- },
- {
- Name: "Test ListLogicalDeviceFlowGroups",
- Method: "ListLogicalDeviceFlowGroups", // rpc ListLogicalDeviceFlowGroups(ID) returns(openflow_13.FlowGroups)
- Param: `{Id:\"Flow-ABC123XYZ\"}`,
- Expect: `{Items:[]*openflow_13.OfpGroupEntry{&openflow_13.OfpGroupEntry{Desc:&openflow_13.OfpGroupDesc{GroupId:12}, Stats:&openflow_13.OfpGroupStats{GroupId:1, RefCount:1, PacketCount:3}}}}`,
- },
- {
- Name: "Test ListDevices",
- Method: "ListDevices", // rpc ListDevices(google.protobuf.Empty) returns(Devices)
- Param: `{}`,
- Expect: `{Items:[]*voltha.Device{&voltha.Device{Id:\"ABC123XYZ\", Type:\"SomeDeviceType\", Root:false, ParentId:\"ZYX321CBA\"},&voltha.Device{Id:\"ZYX321CBA\", Type:\"SomeDeviceType\", Root:true, ParentId:\"ROOT\"}}}`,
- },
- {
- Name: "Test ListDeviceIds",
- Method: "ListDeviceIds", // rpc ListDeviceIds(google.protobuf.Empty) returns(IDs)
- Param: `{}`,
- Expect: `{Items:[]*voltha.ID{&voltha.ID{Id:\"ABC123XYZ\"},&voltha.ID{Id:\"ZYX321CBA\"}}}`,
- },
- {
- Name: "Test GetDevice",
- Method: "GetDevice", // rpc GetDevice(ID) returns(Device)
- Param: `{Id:\"ZYX321CBA\"}`,
- Expect: `{Id:\"ABC123XYZ\", Type:\"SomeDeviceType\", Root:false, ParentId:\"ZYX321CBA\"}`,
- },
- {
- Name: "Test GetImageDownloadStatus",
- Method: "GetImageDownloadStatus", // rpc GetImageDownloadStatus(ImageDownload) returns(ImageDownload)
- Param: `{Id:\"Image-ZYX321CBA\"}`,
- Expect: `{Id:\"Image-ABC123XYZ\", Name:\"SomeName\", Url:\"Some URL\", Crc:123456}`,
- },
- {
- Name: "Test GetImageDownload",
- Method: "GetImageDownload", // rpc GetImageDownload(ImageDownload) returns(ImageDownload)
- Param: `{Id:\"Image-ZYX321CBA\"}`,
- Expect: `{Id:\"Image-ABC123XYZ\", Name:\"SomeName\", Url:\"Some URL\", Crc:123456}`,
- },
- {
- Name: "Test ListImageDownloads",
- Method: "ListImageDownloads", // rpc ListImageDownloads(ID) returns(ImageDownloads)
- Param: `{Id:\"ZYX321CBA\"}`,
- Expect: `{Items:[]*voltha.ImageDownload{&voltha.ImageDownload{Id:\"Image1-ABC123XYZ\", Name:\"SomeName\", Url:\"Some URL\", Crc:123456}, &voltha.ImageDownload{Id:\"Image2-ABC123XYZ\", Name:\"SomeName\", Url:\"Some other URL\", Crc:654321}}}`,
- },
- {
- Name: "Test ListDevicePorts",
- Method: "ListDevicePorts", // rpc ListDevicePorts(ID) returns(Ports)
- Param: `{}`,
- Expect: `{Items:[]*voltha.Port{&voltha.Port{PortNo:100000, Label:\"Port one hundred thousand\", DeviceId:\"ZYX321CBA\"},&voltha.Port{PortNo:100001, Label:\"Port one hundred thousand and one\", DeviceId:\"ZYX321CBA\"}}}`,
- },
- {
- Name: "Test ListDevicePmConfigs",
- Method: "ListDevicePmConfigs", // rpc ListDevicePmConfigs(ID) returns(PmConfigs)
- Param: `{}`,
- Expect: `{Id:\"ABC123XYZ\", DefaultFreq: 10000, Grouped:false, FreqOverride:false, Metrics:[]*voltha.PmConfig{&voltha.PmConfig{Name:\"Speed\", Enabled: true, SampleFreq:10000}, &voltha.PmConfig{Name:\"Errors\", Enabled: true, SampleFreq:10000}}}`,
- },
- {
- Name: "Test ListDeviceFlows",
- Method: "ListDeviceFlows", // rpc ListDeviceFlows(ID) returns(openflow_13.Flows)
- Param: `{Id:\"Flow-ABC123XYZ\"}`,
- Expect: `{Items:[]*openflow_13.OfpFlowStats{&openflow_13.OfpFlowStats{Id:1, TableId:2, DurationSec:12, Priority:0},&openflow_13.OfpFlowStats{Id:1, TableId:2, DurationSec:12, Priority:0}}}`,
- },
- {
- Name: "Test ListDeviceFlowGroups",
- Method: "ListDeviceFlowGroups", // rpc ListDeviceFlowGroups(ID) returns(openflow_13.FlowGroups)
- Param: `{Id:\"Flow-ABC123XYZ\"}`,
- Expect: `{Items:[]*openflow_13.OfpGroupEntry{&openflow_13.OfpGroupEntry{Desc:&openflow_13.OfpGroupDesc{GroupId:12}, Stats:&openflow_13.OfpGroupStats{GroupId:1, RefCount:1, PacketCount:3}}}}`,
- },
- {
- Name: "Test ListDeviceTypes",
- Method: "ListDeviceTypes", // rpc ListDeviceTypes(google.protobuf.Empty) returns(DeviceTypes)
- Param: `{}`,
- Expect: `{Items:[]*voltha.DeviceType{&voltha.DeviceType{Id:\"ABC123XYZ\", VendorId:\"Ciena\", Adapter:\"SAOS\"},&voltha.DeviceType{Id:\"ZYX321CBA\", VendorId:\"Ciena\", Adapter:\"SAOS-Tibit\"}}}`,
- },
- {
- Name: "Test GetDeviceType",
- Method: "GetDeviceType", // rpc GetDeviceType(ID) returns(DeviceType)
- Param: `{Id:\"ZYX321CBA\"}`,
- Expect: `{Id:\"ZYX321CBA\", VendorId:\"Ciena\", Adapter:\"SAOS-Tibit\"}`,
- },
- {
- Name: "Test ListDeviceGroups",
- Method: "ListDeviceGroups", // rpc ListDeviceGroups(google.protobuf.Empty) returns(DeviceGroups)
- Param: `{}`,
- Expect: `{Items:[]*voltha.DeviceGroup{&voltha.DeviceGroup{Id:\"group-ABC123XYZ\", LogicalDevices: []*voltha.LogicalDevice{&voltha.LogicalDevice{Id:\"LDevId\", DatapathId:64, RootDeviceId:\"Root\"}}, Devices: []*voltha.Device{&voltha.Device{Id:\"ABC123XYZ\", Type:\"SomeDeviceType\", Root:false, ParentId:\"ZYX321CBA\"},&voltha.Device{Id:\"ZYX321CBA\", Type:\"SomeDeviceType\", Root:true, ParentId:\"ROOT\"}}}}}`,
- },
- {
- Name: "Test GetDeviceGroup",
- Method: "GetDeviceGroup", // rpc GetDeviceGroup(ID) returns(DeviceGroup)
- Param: `{Id:\"ZYX321CBA\"}`,
- Expect: `{Id:\"group-ABC123XYZ\", LogicalDevices: []*voltha.LogicalDevice{&voltha.LogicalDevice{Id:\"LDevId\", DatapathId:64, RootDeviceId:\"Root\"}}, Devices: []*voltha.Device{&voltha.Device{Id:\"ABC123XYZ\", Type:\"SomeDeviceType\", Root:false, ParentId:\"ZYX321CBA\"},&voltha.Device{Id:\"ZYX321CBA\", Type:\"SomeDeviceType\", Root:true, ParentId:\"ROOT\"}}}`,
- },
- {
- Name: "Test ListEventFilters",
- Method: "ListEventFilters", // rpc ListEventFilters(google.protobuf.Empty) returns(EventFilters)
- Param: `{}`,
- Expect: `{Filters:[]*voltha.EventFilter{&voltha.EventFilter{Id:\"ABC123XYZ\", DeviceId: \"Device123\", Enable: \"True\", EventType: \"DeviceEvent\", Rules: []*voltha.EventFilterRule{&voltha.EventFilterRule{Value:\"Rule Value\"}}}}}`,
- },
- {
- Name: "Test GetEventFilter",
- Method: "GetEventFilter", // rpc GetEventFilter(ID) returns(EventFilters)
- Param: `{Id:\"ABC123XYZ\"}`,
- Expect: `{Filters:[]*voltha.EventFilter{&voltha.EventFilter{Id:\"ABC123XYZ\", DeviceId: \"Device123\", Enable: \"True\", EventType: \"DeviceEvent\", Rules: []*voltha.EventFilterRule{&voltha.EventFilterRule{Value:\"Rule Value\"}}}}}`,
- },
- {
- Name: "Test GetImages",
- Method: "GetImages", // rpc GetImages(ID) returns(Images)
- Param: `{Id:\"ZYX321CBA\"}`,
- Expect: `{Image: []*voltha.Image{&voltha.Image{Name:\"Image1\", Version: \"0.1\", Hash:\"123@\", InstallDatetime:\"Yesterday\", IsActive:true, IsCommitted:true, IsValid:false},&voltha.Image{Name:\"Image2\", Version: \"0.2\", Hash:\"ABC@\", InstallDatetime:\"Today\", IsActive:false, IsCommitted:false, IsValid:false}}}`,
- },
-}
-
-var ctlMethods []test = []test{
- {
- Name: "Test UpdateLogLevel",
- Method: "UpdateLogLevel", // rpc UpdateLogLevel(Logging) returns(google.protobuf.Empty)
- Param: `{Level: 0, PackageName:\"abc123\"}`,
- Expect: "{}",
- },
-}
-
-var rwMethods []test = []test{
- {
- Name: "Test EnableLogicalDevicePort",
- Method: "EnableLogicalDevicePort", // rpc EnableLogicalDevicePort(LogicalPortId) returns(google.protobuf.Empty)
- Param: `{Id:\"ZYX321CBA\", PortId:\"100,000\"}`,
- Expect: `{}`,
- },
- {
- Name: "Test DisableLogicalDevicePort",
- Method: "DisableLogicalDevicePort", // rpc DisableLogicalDevicePort(LogicalPortId) returns(google.protobuf.Empty)
- Param: `{Id:\"ABC123XYZ\", PortId:\"100,000\"}`,
- Expect: `{}`,
- },
- {
- Name: "Test UpdateLogicalDeviceFlowTable",
- Method: "UpdateLogicalDeviceFlowTable", // rpc UpdateLogicalDeviceFlowTable(openflow_13.FlowTableUpdate)
- Param: `{Id:\"XYZ123ABC\", FlowMod:&openflow_13.OfpFlowMod{Cookie:10, CookieMask:255, TableId:10000, Command:openflow_13.OfpFlowModCommand_OFPFC_ADD}}`,
- Expect: `{}`,
- },
- {
- Name: "Test UpdateLogicalDeviceFlowGroupTable",
- Method: "UpdateLogicalDeviceFlowGroupTable", // rpc UpdateLogicalDeviceFlowGroupTable(openflow_13.FlowGroupTableUpdate)
- Param: `{Id:\"ZYX123ABC\", GroupMod:&openflow_13.OfpGroupMod{Command:openflow_13.OfpGroupModCommand_OFPGC_ADD, Type:openflow_13.OfpGroupType_OFPGT_INDIRECT, GroupId:255}}`,
- Expect: `{}`,
- },
- //"ReconcileDevices", // rpc ReconcileDevices(IDs) returns(google.protobuf.Empty)
- {
- Name: "Test CreateDevice",
- Method: "CreateDevice", // rpc CreateDevice(Device) returns(Device)
- Param: `{Type:\"simulated_OLT\"}`,
- Expect: `{Id:\"ZYX321ABC\", Type:\"\"}`,
- },
- {
- Name: "Test EnableDevice",
- Method: "EnableDevice", // rpc EnableDevice(ID) returns(google.protobuf.Empty)
- Param: `{Id:\"XYZ321ABC\"}`,
- Expect: `{}`,
- },
- {
- Name: "Test DisableDevice",
- Method: "DisableDevice", // rpc DisableDevice(ID) returns(google.protobuf.Empty)
- Param: `{Id:\"XYZ123CBA\"}`,
- Expect: `{}`,
- },
- {
- Name: "Test RebootDevice",
- Method: "RebootDevice", // rpc RebootDevice(ID) returns(google.protobuf.Empty)
- Param: `{Id:\"ZYX123CBA\"}`,
- Expect: `{}`,
- },
- {
- Name: "Test DeleteDevice",
- Method: "DeleteDevice", // rpc DeleteDevice(ID) returns(google.protobuf.Empty)
- Param: `{Id:\"CBA123XYZ\"}`,
- Expect: `{}`,
- },
- {
- Name: "Test DownloadImage",
- Method: "DownloadImage", // rpc DownloadImage(ImageDownload) returns(OperationResp)
- Param: `{Id:\"CBA321XYZ\", Name:\"Image-1\", Crc: 54321}`,
- Expect: `{Code:voltha.OperationResp_OPERATION_SUCCESS, AdditionalInfo:\"It worked!\"}`,
- },
- {
- Name: "Test CancelImageDownload",
- Method: "CancelImageDownload", // rpc CancelImageDownload(ImageDownload) returns(OperationResp)
- Param: `{Id:\"CBA321ZYX\", Name:\"Image-1\", Crc: 54321}`,
- Expect: `{Code:voltha.OperationResp_OPERATION_SUCCESS, AdditionalInfo:\"It worked!\"}`,
- },
- {
- Name: "Test ActivateImageUpdate",
- Method: "ActivateImageUpdate", // rpc ActivateImageUpdate(ImageDownload) returns(OperationResp)
- Param: `{Id:\"ABC321ZYX\", Name:\"Image-1\", Crc: 54321}`,
- Expect: `{Code:voltha.OperationResp_OPERATION_FAILURE, AdditionalInfo:\"It bombed!\"}`,
- },
- {
- Name: "Test RevertImageUpdate",
- Method: "RevertImageUpdate", // rpc RevertImageUpdate(ImageDownload) returns(OperationResp)
- Param: `{Id:\"ABC123ZYX\", Name:\"Image-1\", Crc: 54321}`,
- Expect: `{Code:voltha.OperationResp_OPERATION_FAILURE, AdditionalInfo:\"It bombed!\"}`,
- },
- {
- Name: "Test UpdateDevicePmConfigs",
- Method: "UpdateDevicePmConfigs", // rpc UpdateDevicePmConfigs(voltha.PmConfigs) returns(google.protobuf.Empty)
- Param: `{Id:\"CBA123ZYX\", DefaultFreq:1000000, Grouped: false, FreqOverride: false}`,
- Expect: `{}`,
- },
- {
- Name: "Test CreateEventFilter",
- Method: "CreateEventFilter", // rpc CreateEventFilter(EventFilter) returns(EventFilter)
- // Param: `{Id:\"abc123xyz\", Rules:[]*voltha.EventFilterRule{&voltha.AlarmFilterRule{Key:voltha.AlarmFilterRuleKey_type, Value:\"Type man, it's the type!\"}, &voltha.AlarmFilterRule{Key:voltha.AlarmFilterRuleKey_category, Value:\"Category yeah!\"}}}`,
- Param: `{Id:\"abc123xyz\", DeviceId: \"Device123\", Enable: True, EventType: \"device_event\", Rules:[]*voltha.EventFilterRule{&voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_category, Value:\"Equipment\"}, &voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_sub_category, Value:\"ONU\"}, &voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_device_event_type, Value:\"dying_gasp_event\"}}}`,
- Expect: `{Id:\"abc123xyz\", DeviceId: \"Device123\", Enable: True, EventType: \"device_event\", Rules:[]*voltha.EventFilterRule{&voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_category, Value:\"Equipment\"}, &voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_sub_category, Value:\"ONU\"}, &voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_device_event_type, Value:\"dying_gasp_event\"}}}`,
- },
- {
- Name: "Test UpdateEventFilter",
- Method: "UpdateEventFilter", // rpc UpdateEventFilter(EventFilter) returns(EventFilter)
- Param: `{Id:\"abc123xyz\", DeviceId: \"Device123\", Enable: True, EventType: \"device_event\", Rules:[]*voltha.EventFilterRule{&voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_category, Value:\"Equipment\"}, &voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_sub_category, Value:\"ONU\"}, &voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_device_event_type, Value:\"dying_gasp_event\"}}}`,
- Expect: `{Id:\"abc123xyz\", DeviceId: \"Device123\", Enable: True, EventType: \"device_event\", Rules:[]*voltha.EventFilterRule{&voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_category, Value:\"Equipment\"}, &voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_sub_category, Value:\"ONU\"}, &voltha.EventFilterRule{Key:voltha.EventFilterRuleKey_device_event_type, Value:\"dying_gasp_event\"}}}`,
- },
- {
- Name: "Test DeleteEventFilter",
- Method: "DeleteEventFilter", // rpc DeleteEventFilter(EventFilter) returns(google.protobuf.Empty)
- Param: `{Id:\"acb123xyz\"}`,
- Expect: `{}`,
- },
- {
- Name: "Test SelfTest",
- Method: "SelfTest", // rpc SelfTest(ID) returns(SelfTestResponse)
- Param: `{Id:\"bac123xyz\"}`,
- Expect: `{Result:voltha.SelfTestResponse_UNKNOWN_ERROR}`,
- },
-} /*
-// "StreamPacketsOut", // rpc StreamPacketsOut(stream openflow_13.PacketOut)
-// "ReceivePacketsIn", // rpc ReceivePacketsIn(google.protobuf.Empty)
-// "ReceiveChangeEvents", // rpc ReceiveChangeEvents(google.protobuf.Empty)
- "Subscribe ", // rpc Subscribe (OfAgentSubscriber) returns (OfAgentSubscriber)
-
-}
-*/
-
-func dumpFile(fileNm string) error {
- // Dump the generated file for debugging purposes
- if c, err := ioutil.ReadFile(fileNm); err == nil {
- fmt.Print(string(c))
- } else {
- e := errors.New(fmt.Sprintf("Could not read the file '%s', %v", fileNm, err))
- return e
- }
- return nil
-}
-
-func main() {
-
- //var rwAry []test
- //var roAry []test
- var serNo int = 0
-
- // Setup logging
- if _, err := log.SetDefaultLogger(log.JSON, 0, nil); err != nil {
- log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
- }
-
- core := 0
- for k, _ := range roMethods {
- roMethods[k].SerNo = serNo
- roMethods[k].Core = (core % 3) + 1
- log.Infof("Processing method %s, serNo: %d", roMethods[k].Method, roMethods[k].SerNo)
- serNo++
- core++
- }
-
- // New round robin starts here because of the different route
- core = 0
- for k, _ := range rwMethods {
- rwMethods[k].SerNo = serNo
- rwMethods[k].Core = (core % 3) + 1
- log.Infof("Processing method %s, serNo: %d", rwMethods[k].Method, rwMethods[k].SerNo)
- serNo++
- core++
- }
-
- // New round robin starts here because of the different route
- core = 0
- for k, _ := range ctlMethods {
- ctlMethods[k].SerNo = serNo
- ctlMethods[k].Core = (core % 3) + 1
- log.Infof("Processing method %s, serNo: %d", ctlMethods[k].Method, ctlMethods[k].SerNo)
- serNo++
- core++
- }
-
- tsts := tests{RoTests: roMethods, RwTests: rwMethods, CtlTests: ctlMethods}
-
- t := template.Must(template.New("").ParseFiles("./test3.tmpl.json"))
- if f, err := os.Create("test3.json"); err == nil {
- _ = f
- defer f.Close()
- if err := t.ExecuteTemplate(f, "test3.tmpl.json", tsts); err != nil {
- log.Errorf("Unable to execute template for test3.tmpl.json: %v", err)
- }
- } else {
- log.Errorf("Couldn't create file test3.json: %v", err)
- }
-
- // Dump the generated file for debugging purposes
- //if err := dumpFile("test3.json"); err != nil {
- // log.Error(err)
- //}
-
-}
diff --git a/tests/afrouter/suites/test3/test3.tmpl.json b/tests/afrouter/suites/test3/test3.tmpl.json
deleted file mode 100644
index 75d678b..0000000
--- a/tests/afrouter/suites/test3/test3.tmpl.json
+++ /dev/null
@@ -1,252 +0,0 @@
-{
- "environment":{
- "cmdLine":"afrouter -config arouter_test.json -logLevel 1",
- "protoFiles": [
- {
- "importPath":"github.com/opencord/voltha-protos/v3/go/",
- "service":"VolthaService",
- "package":"voltha"
- },
- {
- "importPath":"github.com/opencord/voltha-protos/v3/go/",
- "service":"Configuration",
- "package":"afrouter"
- }
- ],
- "imports": [
- "github.com/golang/protobuf/ptypes/empty",
- "github.com/opencord/voltha-protos/v3/go/openflow_13",
- "github.com/opencord/voltha-protos/v3/go/common"
- ],
- "protoDesc":"voltha.pb",
- "protoSubst": [
- {
- "from":"google.protobuf.Empty",
- "to":"empty.Empty"
- }
- ],
- "clients": {
- "imports": [
- "github.com/golang/protobuf/ptypes/empty",
- "github.com/opencord/voltha-protos/v3/go/openflow_13",
- "github.com/opencord/voltha-protos/v3/go/common"
- ],
- "endpoints": [
- {
- "name":"client",
- "port":"5000"
- },
- {
- "name":"stats",
- "port":"55554"
- }
- ]
- },
- "servers": {
- "imports": [
- "github.com/golang/protobuf/ptypes/empty",
- "github.com/opencord/voltha-protos/v3/go/openflow_13",
- "github.com/opencord/voltha-protos/v3/go/omci",
- "github.com/opencord/voltha-protos/v3/go/common"
- ],
- "endpoints": [
- {
- "name":"core11",
- "port":"5011"
- },
- {
- "name":"core12",
- "port":"5012"
- },
- {
- "name":"core21",
- "port":"5021"
- },
- {
- "name":"core22",
- "port":"5022"
- },
- {
- "name":"core31",
- "port":"5031"
- },
- {
- "name":"core32",
- "port":"5032"
- },
- {
- "name":"roCore1",
- "port":"5001"
- },
- {
- "name":"roCore2",
- "port":"5002"
- },
- {
- "name":"roCore3",
- "port":"5003"
- }
- ]
- }
- },
- "tests":[
- {{range $k,$v := .RoTests}}
- {
- "name":"{{$v.Name}}",
- "send": {
- "client":"client",
- "method":"{{$v.Method}}",
- "param":"{{$v.Param}}",
- "expect":"{{$v.Expect}}",
- "_meta":""
- },
- "servers": [
- {
- "name":"core{{$v.Core}}1",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"{{$v.SerNo}}"
- }
- ]
- },
- {
- "name":"core{{$v.Core}}2",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"{{$v.SerNo}}"
- }
- ]
- }
- ]
- },
- {{end}}
- {{range $k,$v := .RwTests}}
- {
- "name":"{{$v.Name}}",
- "send": {
- "client":"client",
- "method":"{{$v.Method}}",
- "param":"{{$v.Param}}",
- "expect":"{{$v.Expect}}",
- "_meta":""
- },
- "servers": [
- {
- "name":"core{{$v.Core}}1",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"{{$v.SerNo}}"
- }
- ]
- },
- {
- "name":"core{{$v.Core}}2",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"{{$v.SerNo}}"
- }
- ]
- }
- ]
- },
- {{end}}
- {{range $k,$v := .CtlTests}}
- {
- "name":"{{$v.Name}}",
- "send": {
- "client":"client",
- "method":"{{$v.Method}}",
- "param":"{{$v.Param}}",
- "expect":"{{$v.Expect}}",
- "_meta":""
- },
- "servers": [
- {
- "name":"core{{$v.Core}}1",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"{{$v.SerNo}}"
- }
- ]
- },
- {
- "name":"core{{$v.Core}}2",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"{{$v.SerNo}}"
- }
- ]
- }
- ]
- },
- {{end}}
- {
- "name":"Test Subscribe",
- "send": {
- "client":"client",
- "method":"Subscribe",
- "param":"{OfagentId:\"Agent007\"}",
- "meta": [
- {
- "key":"voltha_backend_name",
- "value":""
- }
- ],
- "expect":"{OfagentId:\"Agent007\",VolthaId:\"core11\"}",
- "expectMeta": [
- {
- "key":"voltha_backend_name",
- "value":"vcore1"
- }
- ]
- },
- "servers": [
- {
- "name":"core11",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"44"
- },
- {
- "key":"voltha_backend_name",
- "value":""
- }
- ]
- },
- {
- "name":"core12",
- "meta": [
- {
- "key":"voltha_serial_number",
- "value":"44"
- },
- {
- "key":"voltha_backend_name",
- "value":""
- }
- ]
- }
- ]
- },
- {
- "_COMMENT":"If this test case fails, there could be a goroutine leak",
- "name":"Get goroutine count",
- "send": {
- "client":"stats",
- "method":"GetGoroutineCount",
- "param":"{}",
- "meta": [ ],
- "expect":"{Count:43}",
- "expectMeta": [ ]
- },
- "servers": [ ]
- }
- ]
-}
diff --git a/tests/afrouter/templates/client.go.tmpl b/tests/afrouter/templates/client.go.tmpl
deleted file mode 100644
index 79bad83..0000000
--- a/tests/afrouter/templates/client.go.tmpl
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package main
-
-import (
- "fmt"
- "errors"
- "encoding/json"
- "google.golang.org/grpc"
- "golang.org/x/net/context"
- "google.golang.org/grpc/metadata"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- // Values generated by the go template
- {{range .Imports}}
- "{{.}}"
- {{end}}
- {{range .ProtoImports}}
- {{.Short}} "{{.Package}}"
- {{end}}
- // End go template values
-)
-
-{{if .Ct}}{{else}}
-type clientCtl struct {
- send func(string, context.Context, interface{}, string, metadata.MD) error
- cncl context.CancelFunc
- ctx context.Context
-}
-{{end}}
-
-type {{.Name}}ClientConn struct {
- conn * grpc.ClientConn
- control * clientCtl
-}
-
-
-var {{.Name}}Client *{{.Name}}ClientConn
-
-
-func {{.Name}}Connect() (*{{.Name}}ClientConn, error) {
- log.Infof("Connecting client {{.Name}} to addr:127.0.0.1, port:{{.Port}}")
- // Dial doesn't block, it just returns and continues connecting in the background.
- // Check back later to confirm and increase the connection count.
- cl := &{{.Name}}ClientConn{control:&clientCtl{}}
- ctx, cnclFnc := context.WithCancel(context.Background())
- cl.control.cncl = cnclFnc
- cl.control.ctx = ctx
- if conn, err := grpc.Dial("127.0.0.1:{{.Port}}", grpc.WithInsecure()); err != nil {
- log.Errorf("Dialng connection :%v",err)
- return nil, err
- } else {
- cl.conn = conn
- }
- {{.Name}}Client = cl
- cl.control.send = {{.Name}}Send
- clients["{{.Name}}"] = cl.control
- return cl, nil
-}
-
-// This function will make the requested RPC with the supplied
-// parameter and validate that the response matches the expected
-// value provided. It will return nil if successful or an error
-// if not.
-func {{.Name}}Send(mthd string, ctx context.Context, param interface{},
- expect string, expectMeta metadata.MD) error {
- switch mthd {
- {{range .Methods}}
- case "{{.Name}}":
- var hdr metadata.MD
- switch param.(type) {
- case *{{.Param}}:
- {{if .Ss}}
- _=hdr
- {{else if .Cs}}
- _=hdr
- {{else}}
- client := {{.Pkg}}.New{{.Svc}}Client({{$.Name}}Client.conn)
- res, err := client.{{.Name}}(ctx, param.(*{{.Param}}), grpc.Header(&hdr))
- if err != nil {
- return errors.New("Error sending method {{.Name}}")
- }
- // Marshal the result and compare it to the expected
- // value.
- if resS,err := json.Marshal(res); err == nil {
- if string(resS) != expect {
- stats.testLog("Unexpected result returned expected '%s' got '%s'\n", expect, string(resS))
- return errors.New("Unexpected result on method {{.Name}}")
- }
- } else {
- return errors.New("Error Marshaling the reply for method {{.Name}}")
- }
- // Now validate the metadata in the response
- for k,v := range expectMeta {
- if rv,ok := hdr[k]; ok == true {
- if rv[0] != v[0] {
- stats.testLog("Mismatch on returned metadata for key '%s' expected '%s' and got '%s'\n", k, v, rv)
- err = errors.New("Failure on returned metadata")
- }
- } else {
- stats.testLog("Returned metadata missing key '%s'; expected value '%s' at that key\n", k, v)
- err = errors.New("Failure on returned metadata")
- }
- }
- return err
- default:
- return errors.New("Invalid parameter type for method {{.Name}}")
- {{end}}
- }
- {{end}}
- default:
- return errors.New(fmt.Sprintf("Unexpected method %s in send", mthd))
- }
- return nil
-}
-
diff --git a/tests/afrouter/templates/clientInit.go.tmpl b/tests/afrouter/templates/clientInit.go.tmpl
deleted file mode 100644
index e8f4836..0000000
--- a/tests/afrouter/templates/clientInit.go.tmpl
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package main
-
-var clients map[string]*clientCtl
-
-func clientInit() error {
- clients = make(map[string]*clientCtl)
- {{range .}}
- if _,err := {{.Name}}Connect(); err != nil {
- return err
- }
- {{end}}
- return nil
-}
-
-
diff --git a/tests/afrouter/templates/main.go.tmpl b/tests/afrouter/templates/main.go.tmpl
deleted file mode 100644
index f1bb3ed..0000000
--- a/tests/afrouter/templates/main.go.tmpl
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// The template for the tester.
-// This template is filled in by the
-// test driver based on the configuration.
-
-package main
-
-import (
- "os"
- "time"
- "os/exec"
- "strings"
- "context"
- //slog "log"
- //"google.golang.org/grpc/grpclog"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
-)
-
-func startSut(cmdStr string) (*exec.Cmd, context.CancelFunc, error) {
- var err error = nil
-
- cmdAry := strings.Fields(cmdStr)
- log.Infof("Running the affinity router: %s",cmdStr)
- //ctx, cncl := context.WithCancel(context.Background())
- ctx, cncl := context.WithCancel(context.Background())
- cmd := exec.CommandContext(ctx, cmdAry[0], cmdAry[1:]...)
- cmd.Stdin = os.Stdin
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
- if err = cmd.Start(); err != nil {
- log.Errorf("Failed to run the affinity router: %s %v", cmdStr,err)
- }
- time.Sleep(1 * time.Second) // Give the command time to get started
- return cmd, cncl, err
-}
-
-func cleanUp(cmd *exec.Cmd, cncl context.CancelFunc) {
- cncl()
- cmd.Wait()
-}
-
-func main() {
- var err error
-
- // Setup logging
- if _, err = log.SetDefaultLogger(log.JSON, 1, nil); err != nil {
- log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
- }
- defer log.CleanUp()
-
- if len(os.Args) < 2 {
- log.Fatalf("Stat file name parameter missing for %s. Aborting...", os.Args[0])
- } else {
- statFn = os.Args[1]
- }
-
- if stats,err = readStats(statFn); err != nil {
- log.Error(err)
- return
- }
- defer writeStats(statFn, stats)
-
- // Add a stat entry for this run
-
- stats.appendNew()
- tsIdx := len(stats.TestSuites) - 1
- stats.TestSuites[tsIdx].Name = os.Args[0]
-
-
- // Initialize the servers
- if err := serverInit(); err != nil {
- log.Errorf("Error initializing server: %v", err)
- return
- }
-
- // Start the sofware under test
- cmd, cnclFunc, err := startSut("./{{.Command}}");
- defer cleanUp(cmd, cnclFunc)
- if err != nil {
- return
- }
-
- // Initialize the clients
- if err := clientInit(); err != nil {
- log.Errorf("Error initializing client: %v", err)
- return
- }
-
- log.Infof("The servers are: %v",servers)
-
- // Run all the test cases now
- log.Infof("Executing tests")
-
- //log.Infof("Stats struct: %v", stats)
- runTests()
-
-}
diff --git a/tests/afrouter/templates/runAll.go.tmpl b/tests/afrouter/templates/runAll.go.tmpl
deleted file mode 100644
index d270b68..0000000
--- a/tests/afrouter/templates/runAll.go.tmpl
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// The template for the tester.
-// This template is filled in by the
-// test driver based on the configuration.
-
-package main
-
-import (
- "os"
- //"time"
- "fmt"
- "os/exec"
- "io/ioutil"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
-)
-
-
-func main() {
- var cmd *exec.Cmd
- var cmdStr string
- // Setup logging
- if _, err := log.SetDefaultLogger(log.JSON, 0, nil); err != nil {
- log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
- }
-
- defer log.CleanUp()
-
- statFn = "stats.json"
-
- log.Info("Running tests")
- if err:= os.Chdir(os.Args[1]); err != nil {
- log.Error("Could not change directory to %s: %v", os.Args[1], err)
- }
-
- if err := initStats(statFn); err != nil {
- log.Error(err)
- return
- }
-
- {{range .}}
- cmdStr = "./"+"{{.}}"+".e"
-
- log.Infof("Running test suite %s",cmdStr)
- cmd = exec.Command(cmdStr, statFn)
- cmd.Stdin = os.Stdin
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
- if err := cmd.Run(); err != nil {
- log.Errorf("Test '%s' failed", cmdStr)
- }
- {{end}}
- // Open the results file and output it.
- if s,err := readStats(statFn); err != nil {
- log.Error(err)
- return
- } else {
- stats = s
- }
-
- //log.Infof("Stats are: %v", stats)
- if resFile, err := ioutil.ReadFile(statFn); err == nil {
- fmt.Println(string(resFile))
- } else {
- log.Error("Could not load the stats file 'stats.json'")
- }
- fmt.Println("Test result summary")
- for _,v := range stats.TestSuites {
- fmt.Printf("Test suite: %s\n", v.Name[2:len(v.Name)-2])
- pass := 0
- fail := 0
- total := 0
- for _,v1 := range v.TestCases {
- total++
- if v1.Result == true {
- pass++
- } else {
- fail++
- }
- }
- fmt.Printf("\tTotal test cases: %d\n", total)
- fmt.Printf("\t\tTotal passed test cases: %d\n", pass)
- fmt.Printf("\t\tTotal failed test cases: %d\n", fail)
- }
- log.Info("Tests complete")
-}
diff --git a/tests/afrouter/templates/runTests.go.tmpl b/tests/afrouter/templates/runTests.go.tmpl
deleted file mode 100644
index 62b938d..0000000
--- a/tests/afrouter/templates/runTests.go.tmpl
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-package main
-
-import (
-{{if .HasFuncs}}
- "fmt"
- "time"
- "errors"
- "context"
- "encoding/json"
- //"golang.org/x/net/context"
- "google.golang.org/grpc/metadata"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
-{{end}}
- {{range .Imports}}
- {{if .Used}}
- "{{.Package}}"
- {{end}}
- {{end}}
- {{range .ProtoImports}}
- {{if .Used}}
- {{.Short}} "{{.Package}}"
- {{end}}
- {{end}}
-)
-
-
-{{if .FileNum}}
-{{else}}
-var glCtx context.Context
-
-func resetChannels() {
- // Drain all channels of data
- for _,v := range servers {
- done := false
- for {
- select {
- case _ = <-v.incmg:
- case _ = <-v.replyData:
- default:
- done = true
- }
- if done == true {
- break
- }
- }
- }
-}
-
-type testData struct {
- function func(int, string, string, []string,[]string,[]string,
- map[string][]string,interface{}, interface{}) error
- testNum int
- testName string
- sendClient string
- srvrs []string
- sendMeta []string
- expectMeta []string // Send Meta
- srvMeta map[string][]string
- parm interface{}
- ret interface{}
-}
-
-func addTestSlot(stats * TestRun) {
- tsIdx := len(stats.TestSuites) - 1
- stats.TestSuites[tsIdx].TestCases =
- append(stats.TestSuites[tsIdx].TestCases, TestCase{Info:[]string{}})
-}
-{{end}}
-
-{{if .FileNum}}
-func runTests{{.FileNum}}() {
-{{else}}
-func runTests() {
-{{end}}
- tsIdx := len(stats.TestSuites) - 1
- tests := []testData {
- {{$ofs := .Offset}}
- {{range $k,$v := .Tests}}
- testData {
- {{$v.Send.Method}}_test,
- {{$k}} + {{$ofs}},
- "{{$v.Name}}",
- "{{$v.Send.Client}}",
- []string{ {{range $sk,$sv := $v.Srvr}} "{{$sv.Name}}",{{end}} },
- []string{ {{range $mk,$mv := $v.Send.MetaData}}"{{$mv.Key}}","{{$mv.Val}}",{{end}} },
- []string{ {{range $mk,$mv := $v.Send.ExpectMeta}}"{{$mv.Key}}","{{$mv.Val}}",{{end}} },
- map[string][]string {
- {{range $sk,$sv := $v.Srvr}}
- "{{$sv.Name}}":[]string {
- {{range $mk, $mv := $sv.Meta}}
- "{{$mv.Key}}","{{$mv.Val}}",
- {{end}}
- },
- {{end}}
- },
- &{{$v.Send.ParamType}}{{$v.Send.Param}},
- &{{$v.Send.ExpectType}}{{$v.Send.Expect}},
- },
- {{end}}
- }
-
- for _,v := range tests {
- addTestSlot(stats)
- stats.TestSuites[tsIdx].TestCases[v.testNum].Title = v.testName
- if err := v.function(
- v.testNum,
- v.testName,
- v.sendClient,
- v.srvrs,
- v.sendMeta,
- v.expectMeta,
- v.srvMeta,
- v.parm,
- v.ret); err != nil {
- stats.TestSuites[tsIdx].TestCases[v.testNum].Result = false
- } else {
- stats.TestSuites[tsIdx].TestCases[v.testNum].Result = true
- }
- }
- {{if .FileNum}}
- {{else}}
- {{range $k,$v := .RunTestsCallList}}
- {{$v}}()
- {{end}}
- {{end}}
- return
- //resetChannels()
-}
-
-{{range $k,$v := .Funcs }}
-{{if $v.CodeGenerated}}
-{{else}}
-func {{$k}}_test(testNum int, testName string, sendClient string, srvrs []string,
- sendMeta []string, expectMeta []string, srvrMeta map[string][]string,
- parm interface{}, ret interface{}) error {
-
- var rtrn error = nil
- var cancel context.CancelFunc
- var repl *reply
-
- log.Debug("Running Test %d",testNum)
- glCtx, cancel = context.WithTimeout(context.Background(), 900*time.Millisecond)
- defer cancel()
-
- cl := clients[sendClient]
- // Create the server's reply data structure
- switch r := ret.(type) {
- case *{{$v.ReturnType}}:
- repl = &reply{repl:r}
- default:
- log.Errorf("Invalid type in call to {{$k}}_test expecting {{$v.ReturnType}} got %T", ret)
- }
- // Send the reply data structure to each of the servers
- for _,v := range srvrs {
- if servers[v] == nil {
- err := errors.New(fmt.Sprintf("Server %s is nil", v))
- log.Error(err)
- return err
- }
- // Start a go routine to send the the reply data to the
- // server. The go routine blocks until the server picks
- // up the data or the timeout is exceeded.
- go func (ctx context.Context, srv string) {
- select {
- case servers[srv].replyData <- repl:
- case <-ctx.Done():
- rtrn := errors.New(fmt.Sprintf("Could not provide server %s with reply data",srv))
- log.Error(rtrn)
- stats.testLog("%s\n", rtrn.Error())
- }
- }(glCtx,v)
- }
-
- // Now call the RPC with the data provided
- if expct,err := json.Marshal(repl.repl); err != nil {
- log.Errorf("Marshaling the reply for test %s: %v",testName, err)
- } else {
- // Create the context for the call
- ctx := context.Background()
- for i:=0; i<len(sendMeta); i += 2 {
- ctx = metadata.AppendToOutgoingContext(ctx, sendMeta[i], sendMeta[i+1])
- }
- var md map[string]string = make(map[string]string)
- for i:=0; i<len(expectMeta); i+=2 {
- md[expectMeta[i]] = expectMeta[i+1]
- }
- expectMd := metadata.New(md)
- if err := cl.send("{{$k}}", ctx, parm, string(expct), expectMd); err != nil {
- log.Errorf("Test case %s failed!: %v", testName, err)
- rtrn = err
- }
- }
-
- // Now read the servers' information to validate it
- var s *serverCtl
- var payload string
- var i *incoming
- if pld, err := json.Marshal(parm); err != nil {
- log.Errorf("Marshaling paramter for test %s: %v", testName, err)
- } else {
- payload = string(pld)
- }
- for _,v := range srvrs {
- s = servers[v]
- // Oddly sometimes the data isn't in the channel yet when we come to read it.
- select {
- case i = <-s.incmg:
- if i.payload != payload {
- rtrn = errors.New(fmt.Sprintf("Mismatched payload expected '%s', got '%s'", payload, i.payload))
- log.Error(rtrn.Error())
- stats.testLog("%s\n", rtrn.Error())
- }
- for j:=0; j<len(srvrMeta[v]); j+=2 {
- if mv,ok := i.meta[srvrMeta[v][j]]; ok == true {
- if srvrMeta[v][j+1] != mv[0] {
- rtrn=errors.New(fmt.Sprintf("Mismatched metadata on server '%s' expected '%s', got '%s'", srvrMeta[v][j], srvrMeta[v][j+1], mv[0]))
- log.Error(rtrn.Error())
- stats.testLog("%s\n", rtrn.Error())
- }
- }
- }
- case <-glCtx.Done():
- rtrn = errors.New(fmt.Sprintf("Timeout: no response data available for server %s (%s)", v, testName))
- stats.testLog("%s\n", rtrn.Error())
- log.Error(rtrn)
- }
- }
-
- return rtrn
-}
-{{end}}
-{{end}}
diff --git a/tests/afrouter/templates/server.go.tmpl b/tests/afrouter/templates/server.go.tmpl
deleted file mode 100644
index 0830b12..0000000
--- a/tests/afrouter/templates/server.go.tmpl
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// The template for the tester.
-// This template is filled in by the
-// test driver based on the configuration.
-
-package main
-
-import (
- "fmt"
- "net"
- "errors"
- "encoding/json"
- "google.golang.org/grpc"
- "golang.org/x/net/context"
- "google.golang.org/grpc/metadata"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- // Values generated by the go template
- {{range .Imports}}
- "{{.}}"
- {{end}}
- {{range .ProtoImports}}
- {{.Short}} "{{.Package}}"
- {{end}}
- // End go template values
-)
-
-// The channels to get fed the expected results by the test driver.
-//var {{.Name}}Meta <-chan string
-////var {{.Name}}Payload <-chan string
-
-{{if .Ct}}{{else}}
-type reply struct {
- repl interface{}
-}
-type incoming struct {
- meta metadata.MD
- payload string
-}
-type serverCtl struct {
- replyData chan * reply
- incmg chan * incoming
-}
-{{end}}
-
-type {{.Name}}TestServer struct {
- control *serverCtl
- srv *grpc.Server
-}
-
-/*
-func init() {
- {{if .Ct}}{{else}}
- if _, err := log.SetDefaultLogger(log.JSON, 0, nil); err != nil {
- log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
- }
- {{end}}
- {{.Name}}ListenAndServe()
-}
-*/
-
-
-func {{.Name}}ListenAndServe() error {
- var s {{.Name}}TestServer
-
- s.control = &serverCtl{replyData:make(chan *reply), incmg:make(chan *incoming)}
- servers["{{.Name}}"] = s.control
-
- log.Debugf("Starting server %s on port %d", "{{.Name}}", {{.Port}})
- // THe test head always uses localhost 127.0.0.1
- addr := fmt.Sprintf("127.0.0.1:%d", {{.Port}})
-
- // Create the gRPC server
- s.srv = grpc.NewServer()
-
-{{range .ProtoImports}}
- // Register the handler object
- {{.Short}}.Register{{.Service}}Server(s.srv, s)
-{{end}}
-
- // Create the channel to listen on
- lis, err := net.Listen("tcp", addr)
- if err != nil {
- log.Errorf("could not listen on %s: %s", addr, err)
- return err
- }
-
- // Serve and Listen
- go func() {
- if err = s.srv.Serve(lis); err != nil {
- log.Errorf("grpc serve error: %s", err)
- return
- }
- }()
-
- return err
-}
-
-{{range .Methods}}
-{{if .Ss}}
-func (ts {{$.Name}}TestServer) {{.Name}}(in *{{.Param}}, srvr {{.Pkg}}.{{.Svc}}_{{.Name}}Server) error {
- log.Debug("Serving server streaming {{$.Name}}")
- return nil
-}
-{{else if .Cs}}
-func (ts {{$.Name}}TestServer) {{.Name}}({{.Pkg}}.{{.Svc}}_{{.Name}}Server) error {
- log.Debug("Serving client streaming {{$.Name}}")
- return nil
-}
-{{else}}
-func (ts {{$.Name}}TestServer) {{.Name}}(ctx context.Context, in *{{.Param}}) (*{{.Rtrn}}, error) {
- var r * incoming = &incoming{}
- //log.Debug("Serving {{$.Name}}")
- // Read the metadata
- if md,ok := metadata.FromIncomingContext(ctx); ok == false {
- log.Error("Getting matadata during call to {{.Name}}")
- } else {
- r.meta = md.Copy()
- }
- // Read the data sent to the function
- if parm,err := json.Marshal(in); err != nil {
- log.Error("Marshalling the {{.Param}} for {{.Name}}")
- } else {
- r.payload = string(parm)
- }
- // Send the server information back to the test framework
- go func(ctx context.Context) {
- select {
- case ts.control.incmg <- r:
- return
- case <-ctx.Done():
- return
-
- }
- }(glCtx)
- // Read the value that needs to be returned from the channel
- select {
- case d := <-ts.control.replyData:
- switch r := d.repl.(type) {
- case *{{.Rtrn}}:
- return r, nil
- default:
- return nil, errors.New("Mismatched type in call to {{.Name}}")
- }
- case <-glCtx.Done():
- return nil, errors.New("Timeout: nothing in the reply data channel in call to {{.Name}}, sending nil")
- }
- return &{{.Rtrn}}{},nil
-}
-{{end}}
-{{end}}
-
diff --git a/tests/afrouter/templates/serverInit.go.tmpl b/tests/afrouter/templates/serverInit.go.tmpl
deleted file mode 100644
index e97e6ff..0000000
--- a/tests/afrouter/templates/serverInit.go.tmpl
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package main
-
-var servers map[string]*serverCtl
-
-func serverInit() error {
- servers = make(map[string]*serverCtl)
- {{range .}}
- if err := {{.Name}}ListenAndServe(); err != nil {
- return err
- }
- {{end}}
- return nil
-}
-
-
diff --git a/tests/afrouter/templates/stats.go.tmpl b/tests/afrouter/templates/stats.go.tmpl
deleted file mode 100644
index 3eb4008..0000000
--- a/tests/afrouter/templates/stats.go.tmpl
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// The template for the tester.
-// This template is filled in by the
-// test driver based on the configuration.
-
-package main
-
-import (
- "os"
- "fmt"
- //slog "log"
- "io/ioutil"
- "encoding/json"
- //"google.golang.org/grpc/grpclog"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
-)
-
-type TestCase struct {
- Title string `json:"title"`
- Result bool `json:"passed"`
- Info []string `json:"info"`
-}
-
-type TestSuite struct {
- Name string `json:"name"`
- Info []string `json:"info"`
- TestCases []TestCase `json:"testCases"`
-}
-
-type TestRun struct {
- TestSuites []TestSuite
-}
-
-func (tr * TestRun) testLog(format string, a ...interface{}) {
-
- tridx := len(tr.TestSuites) - 1
- tcidx := len(tr.TestSuites[tridx].TestCases) - 1
-
- tr.TestSuites[tridx].TestCases[tcidx].Info =
- append(tr.TestSuites[tridx].TestCases[tcidx].Info, fmt.Sprintf(format, a...))
-
-}
-
-func (tr * TestRun) suiteLog(format string, a ...interface{}) {
-
- tridx := len(tr.TestSuites) - 1
-
- tr.TestSuites[tridx].Info =
- append(tr.TestSuites[tridx].Info, fmt.Sprintf(format, a...))
-
-}
-
-func readStats(statFn string) (*TestRun, error) {
- // Check if the stats file exists
- if _,err := os.Stat(statFn); err != nil {
- // Nothing to do, just return
- return &TestRun{}, nil
- }
- rtrn := &TestRun{}
- // The file is there, read it an unmarshal it into the stats struct
- if statBytes, err := ioutil.ReadFile(statFn); err != nil {
- log.Error(err)
- return nil, err
- } else if err := json.Unmarshal(statBytes, rtrn); err != nil {
- log.Error(err)
- return nil, err
- }
- return rtrn, nil
-}
-
-func writeStats(statFn string, stats * TestRun) error {
- // Check if the stats file exists
- // The file is there, read it an unmarshal it into the stats struct
- if statBytes, err := json.MarshalIndent(stats, ""," "); err != nil {
- log.Error(err)
- return err
- } else if err := ioutil.WriteFile(statFn+".new", statBytes, 0644); err != nil {
- log.Error(err)
- return err
- }
- if err := os.Rename(statFn, statFn+"~"); err != nil {
- log.Error(err)
- return err
- }
- if err := os.Rename(statFn+".new", statFn); err != nil {
- log.Error(err)
- return err
- }
- return nil
-}
-
-func (tr * TestRun) appendNew() {
- tr.TestSuites = append(tr.TestSuites, TestSuite{})
-}
-
-func initStats(statFn string) error {
- s := &TestRun{}
-
- if statBytes, err := json.MarshalIndent(s, ""," "); err != nil {
- log.Error(err)
- return err
- } else if err := ioutil.WriteFile(statFn, statBytes, 0644); err != nil {
- log.Error(err)
- return err
- }
-
- return nil
-}
-
-
-var statFn string
-var stats *TestRun
diff --git a/tests/afrouter/tester.go b/tests/afrouter/tester.go
deleted file mode 100644
index b6dcd3c..0000000
--- a/tests/afrouter/tester.go
+++ /dev/null
@@ -1,853 +0,0 @@
-// +build integration
-
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// gRPC affinity router with active/active backends
-
-package main
-
-import (
- "encoding/json"
- "errors"
- "flag"
- "fmt"
- "github.com/golang/protobuf/proto"
- pb "github.com/golang/protobuf/protoc-gen-go/descriptor"
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
- "io/ioutil"
- "math"
- "os"
- "os/exec"
- "path"
- "regexp"
- "strconv"
- "text/template"
-)
-
-const MAX_CT = 500
-
-type TestConfig struct {
- configFile *string
- logLevel *int
- grpcLog *bool
- Suites []string `json:"suites"`
-}
-
-type Connection struct {
- Name string `json:"name"`
- Port string `json:"port"`
-}
-
-type EndpointList struct {
- Imports []string `json:"imports"`
- Endpoints []Connection `json:"endPoints"`
-}
-
-type ProtoFile struct {
- ImportPath string `json:"importPath"`
- Service string `json:"service"`
- Package string `json:"package"`
-}
-
-type ProtoSubst struct {
- From string `json:"from"`
- To string `json:"to"`
-}
-
-type Environment struct {
- Command string `json:"cmdLine"`
- ProtoFiles []ProtoFile `json:"protoFiles"`
- ProtoDesc string `json:"protoDesc"`
- Clients EndpointList `json:"clients"`
- Servers EndpointList `json:"servers"`
- Imports []string `json:"imports"`
- ProtoSubsts []ProtoSubst `json:"protoSubst"`
-}
-
-type Rpc struct {
- Client string `json:"client"`
- Method string `json:"method"`
- Param string `json:"param"`
- Expect string `json:"expect"`
- MetaData []MetaD `json:"meta"`
- ExpectMeta []MetaD `json:"expectMeta"`
-}
-
-type MetaD struct {
- Key string `json:"key"`
- Val string `json:"value"`
-}
-
-type Server struct {
- Name string `json:"name"`
- Meta []MetaD `json:"meta"`
-}
-
-type Test struct {
- Name string `json:"name"`
- InfoOnly bool `json:"infoOnly"`
- Send Rpc `json:"send"`
- Servers []Server `json:"servers"`
-}
-
-type TestSuite struct {
- Env Environment `json:"environment"`
- Tests []Test `json:"tests"`
-}
-
-type ProtoImport struct {
- Service string
- Short string
- Package string
- Used bool
-}
-
-type SendItem struct {
- Client string
- Method string
- Param string
- ParamType string
- Expect string
- ExpectType string
- MetaData []MetaD
- ExpectMeta []MetaD
-}
-
-type TestCase struct {
- Name string
- InfoOnly bool
- Send SendItem
- Srvr []Server
-}
-
-type MethodTypes struct {
- ParamType string
- ReturnType string
- CodeGenerated bool
-}
-
-type Import struct {
- Package string
- Used bool
-}
-
-type TestList struct {
- ProtoImports []ProtoImport
- Imports []Import
- Tests []TestCase
- Funcs map[string]MethodTypes
- RunTestsCallList []string
- FileNum int
- //NextFile int
- HasFuncs bool
- Offset int
-}
-
-type ClientConfig struct {
- Ct int
- Name string
- Port string
- Imports []string
- Methods map[string]*mthd
- ProtoImports []ProtoImport
-}
-
-type ServerConfig struct {
- Ct int
- Name string
- Port string
- Imports []string
- Methods map[string]*mthd
- ProtoImports []ProtoImport
-}
-
-type mthd struct {
- Pkg string
- Svc string
- Name string
- Param string
- Rtrn string
- Ss bool // Server streaming
- Cs bool // Clieent streaming
-}
-
-func parseCmd() (*TestConfig, error) {
- config := &TestConfig{}
- cmdParse := flag.NewFlagSet(path.Base(os.Args[0]), flag.ContinueOnError)
- config.configFile = cmdParse.String("config", "suites.json", "The configuration file for the affinity router tester")
- config.logLevel = cmdParse.Int("logLevel", 0, "The log level for the affinity router tester")
- config.grpcLog = cmdParse.Bool("grpclog", false, "Enable GRPC logging")
-
- err := cmdParse.Parse(os.Args[1:])
- if err != nil {
- //return err
- return nil, errors.New("Error parsing the command line")
- }
- return config, nil
-}
-
-func (conf *TestConfig) loadConfig() error {
-
- configF, err := os.Open(*conf.configFile)
- log.Info("Loading configuration from: ", *conf.configFile)
- if err != nil {
- log.Error(err)
- return err
- }
-
- defer configF.Close()
-
- if configBytes, err := ioutil.ReadAll(configF); err != nil {
- log.Error(err)
- return err
- } else if err := json.Unmarshal(configBytes, conf); err != nil {
- log.Error(err)
- return err
- }
-
- return nil
-}
-
-func (suite *TestSuite) loadSuite(suiteN string) error {
- // Check if there's a corresponding go file for the suite.
- // If it is present then the json test suite file is a
- // template. Compile the go file and run it to process
- // the template.
- if _, err := os.Stat(suiteN + "/" + suiteN + ".go"); err == nil {
- // Compile and run the the go file
- log.Infof("Suite '%s' is a template, compiling '%s'", suiteN, suiteN+".go")
- cmd := exec.Command("go", "build", "-o", suiteN+".te", suiteN+".go")
- cmd.Stdin = os.Stdin
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
- cmd.Dir = suiteN
- if err := cmd.Run(); err != nil {
- log.Errorf("Error running the compile command:%v", err)
- }
- cmd = exec.Command("./" + suiteN + ".te")
- cmd.Stdin = os.Stdin
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
- cmd.Dir = suiteN
- if err := cmd.Run(); err != nil {
- log.Errorf("Error running the %s command:%v", suiteN+".te", err)
- }
- }
- suiteF, err := os.Open(suiteN + "/" + suiteN + ".json")
- log.Infof("Loading test suite from: %s", suiteN+"/"+suiteN+".json")
- if err != nil {
- log.Error(err)
- return err
- }
-
- defer suiteF.Close()
-
- if suiteBytes, err := ioutil.ReadAll(suiteF); err != nil {
- log.Error(err)
- return err
- } else if err := json.Unmarshal(suiteBytes, suite); err != nil {
- log.Error(err)
- return err
- }
-
- return nil
-}
-
-func loadProtoMap(fileName string, pkg string, svc string, substs []ProtoSubst) (map[string]*mthd, error) {
- var mthds map[string]*mthd = make(map[string]*mthd)
- var rtrn_err bool
-
- // Load the protobuf descriptor file
- protoDescriptor := &pb.FileDescriptorSet{}
- fb, err := ioutil.ReadFile(fileName)
- if err != nil {
- log.Errorf("Could not open proto file '%s'", fileName)
- rtrn_err = true
- }
- err = proto.Unmarshal(fb, protoDescriptor)
- if err != nil {
- log.Errorf("Could not unmarshal %s, %v", "proto.pb", err)
- rtrn_err = true
- }
-
- var substM map[string]string = make(map[string]string)
- // Create a substitution map
- log.Debugf("Creating import map")
- for _, v := range substs {
- log.Debugf("Mapping from %s to %s", v.From, v.To)
- substM[v.From] = v.To
- }
-
- // Build the a map containing the method as the key
- // and the paramter and return types as the fields
- for _, f := range protoDescriptor.File {
- if *f.Package == pkg {
- for _, s := range f.Service {
- if *s.Name == svc {
- log.Debugf("Loading package data '%s' for service '%s'", *f.Package, *s.Name)
- // Now create a map keyed by method name with the value being the
- // field number of the route selector.
- //var ok bool
- for _, m := range s.Method {
- // Find the input type in the messages and extract the
- // field number and save it for future reference.
- log.Debugf("Processing method (%s(%s) (%s){}", *m.Name, (*m.InputType)[1:], (*m.OutputType)[1:])
- mthds[*m.Name] = &mthd{Pkg: pkg, Svc: svc, Name: *m.Name, Param: (*m.InputType)[1:],
- Rtrn: (*m.OutputType)[1:]}
- if m.ClientStreaming != nil && *m.ClientStreaming == true {
- log.Debugf("Method %s is a client streaming method", *m.Name)
- mthds[*m.Name].Cs = true
- }
- if m.ServerStreaming != nil && *m.ServerStreaming == true {
- log.Debugf("Method %s is a server streaming method", *m.Name)
- mthds[*m.Name].Ss = true
- }
- // Perform the required substitutions
- if _, ok := substM[mthds[*m.Name].Param]; ok == true {
- mthds[*m.Name].Param = substM[mthds[*m.Name].Param]
- }
- if _, ok := substM[mthds[*m.Name].Rtrn]; ok == true {
- mthds[*m.Name].Rtrn = substM[mthds[*m.Name].Rtrn]
- }
- }
- }
- }
- }
- }
- if rtrn_err {
- return nil, errors.New(fmt.Sprintf("Failed to load protobuf descriptor file '%s'", fileName))
- }
- return mthds, nil
-}
-
-// Server source code generation
-func generateServers(conf *TestConfig, suiteDir string, ts *TestSuite,
- t *template.Template) error {
- var servers []ServerConfig
-
- for k, v := range ts.Env.Servers.Endpoints {
- log.Infof("Generating the code for server[%d]: %s", k, v.Name)
- sc := &ServerConfig{Name: v.Name, Port: v.Port, Ct: k, Imports: ts.Env.Servers.Imports,
- Methods: make(map[string]*mthd)}
- for k1, v1 := range ts.Env.ProtoFiles {
- imp := &ProtoImport{Short: "pb" + strconv.Itoa(k1),
- Package: v1.ImportPath + v1.Package,
- Service: v1.Service,
- Used: true}
- imp = &ProtoImport{Short: v1.Package,
- Package: v1.ImportPath + v1.Package,
- Service: v1.Service,
- Used: true}
- sc.ProtoImports = append(sc.ProtoImports, *imp)
- // Compile the template from the file
- log.Debugf("Proto substs: %v", ts.Env.ProtoSubsts)
- if mthds, err := loadProtoMap(ts.Env.ProtoDesc, v1.Package,
- v1.Service, ts.Env.ProtoSubsts); err != nil {
- log.Errorf("Unable to process proto descriptor file %s for package: %s, service: %s",
- ts.Env.ProtoDesc, v1.Package, v1.Service)
- return err
- } else {
- //Generate all the function calls required by the
- for k, v := range mthds {
- sc.Methods[k] = v
- }
- //sc.Methods = mthds
- }
- }
- log.Debugf("Server: %v", *sc)
- // Save this server for the next steop
- servers = append(servers, *sc)
- // Open an output file to put the output in.
- if f, err := os.Create(suiteDir + "/" + v.Name + ".go"); err == nil {
- defer f.Close()
- //if err := t.ExecuteTemplate(os.Stdout, "server.go.tmpl", *sc); err != nil {}
- if err := t.ExecuteTemplate(f, "server.go.tmpl", *sc); err != nil {
- log.Errorf("Unable to execute template for server[%d]: %s: %v", k, v.Name, err)
- return err
- }
- }
- }
- // Generate the server initialization code
- if f, err := os.Create(suiteDir + "/serverInit.go"); err == nil {
- defer f.Close()
- //if err := t.ExecuteTemplate(os.Stdout, "server.go.tmpl", *sc); err != nil {}
- if err := t.ExecuteTemplate(f, "serverInit.go.tmpl", servers); err != nil {
- log.Errorf("Unable to execute template for serverInit.go: %v", err)
- return err
- }
- }
-
- return nil
-}
-
-func generateClients(conf *TestConfig, suiteDir string, ts *TestSuite,
- t *template.Template) error {
- var clients []ClientConfig
- for k, v := range ts.Env.Clients.Endpoints {
- log.Infof("Generating the code for client[%d]: %s", k, v.Name)
- cc := &ClientConfig{Name: v.Name, Port: v.Port, Ct: k, Imports: ts.Env.Clients.Imports,
- Methods: make(map[string]*mthd)}
- for _, v1 := range ts.Env.ProtoFiles {
- imp := &ProtoImport{Short: v1.Package,
- Package: v1.ImportPath + v1.Package,
- Service: v1.Service}
- cc.ProtoImports = append(cc.ProtoImports, *imp)
- // Compile the template from the file
- log.Debugf("Proto substs: %v", ts.Env.ProtoSubsts)
- if mthds, err := loadProtoMap(ts.Env.ProtoDesc, v1.Package,
- v1.Service, ts.Env.ProtoSubsts); err != nil {
- log.Errorf("Unable to process proto descriptor file %s for package: %s, service: %s",
- ts.Env.ProtoDesc, v1.Package, v1.Service)
- return err
- } else {
- // Add to the known methods
- for k, v := range mthds {
- cc.Methods[k] = v
- }
- }
- }
- clients = append(clients, *cc)
- if f, err := os.Create(suiteDir + "/" + v.Name + "_client.go"); err == nil {
- _ = f
- defer f.Close()
- if err := t.ExecuteTemplate(f, "client.go.tmpl", cc); err != nil {
- log.Errorf("Unable to execute template for client.go: %v", err)
- return err
- }
- } else {
- log.Errorf("Couldn't create file %s : %v", suiteDir+"/"+v.Name+"_client.go", err)
- return err
- }
- }
- if f, err := os.Create(suiteDir + "/clientInit.go"); err == nil {
- defer f.Close()
- //if err := t.ExecuteTemplate(os.Stdout, "server.go.tmpl", *sc); err != nil {}
- if err := t.ExecuteTemplate(f, "clientInit.go.tmpl", clients); err != nil {
- log.Errorf("Unable to execute template for clientInit.go: %v", err)
- return err
- }
- }
- return nil
-}
-
-func serverExists(srvr string, ts *TestSuite) bool {
- for _, v := range ts.Env.Servers.Endpoints {
- if v.Name == srvr {
- return true
- }
- }
- return false
-}
-
-func getPackageList(tests []TestCase) map[string]struct{} {
- var rtrn map[string]struct{} = make(map[string]struct{})
- var p string
- var e string
- r := regexp.MustCompile(`^([^.]+)\..*$`)
- for _, v := range tests {
- pa := r.FindStringSubmatch(v.Send.ParamType)
- if len(pa) == 2 {
- p = pa[1]
- } else {
- log.Errorf("Internal error regexp returned %v", pa)
- }
- ea := r.FindStringSubmatch(v.Send.ExpectType)
- if len(ea) == 2 {
- e = ea[1]
- } else {
- log.Errorf("Internal error regexp returned %v", pa)
- }
- if _, ok := rtrn[p]; ok == false {
- rtrn[p] = struct{}{}
- }
- if _, ok := rtrn[e]; ok == false {
- rtrn[e] = struct{}{}
- }
- }
- return rtrn
-}
-
-func fixupProtoImports(protoImports []ProtoImport, used map[string]struct{}) []ProtoImport {
- var rtrn []ProtoImport
- //log.Infof("Updating imports %v, using %v", protoImports, used)
- for _, v := range protoImports {
- //log.Infof("Looking for package %s", v.Package)
- if _, ok := used[v.Short]; ok == true {
- rtrn = append(rtrn, ProtoImport{
- Service: v.Service,
- Short: v.Short,
- Package: v.Package,
- Used: true,
- })
- } else {
- rtrn = append(rtrn, ProtoImport{
- Service: v.Service,
- Short: v.Short,
- Package: v.Package,
- Used: false,
- })
- }
- }
- //log.Infof("After update %v", rtrn)
- return rtrn
-}
-
-func fixupImports(imports []Import, used map[string]struct{}) []Import {
- var rtrn []Import
- var p string
- re := regexp.MustCompile(`^.*/([^/]+)$`)
- //log.Infof("Updating imports %v, using %v", protoImports, used)
- for _, v := range imports {
- //log.Infof("Looking for match in %s", v.Package)
- pa := re.FindStringSubmatch(v.Package)
- if len(pa) == 2 {
- p = pa[1]
- } else {
- log.Errorf("Substring match failed, regexp returned %v", pa)
- }
- //log.Infof("Looking for package %s", v.Package)
- if _, ok := used[p]; ok == true {
- rtrn = append(rtrn, Import{
- Package: v.Package,
- Used: true,
- })
- } else {
- rtrn = append(rtrn, Import{
- Package: v.Package,
- Used: false,
- })
- }
- }
- //log.Infof("After update %v", rtrn)
- return rtrn
-}
-
-func generateTestCases(conf *TestConfig, suiteDir string, ts *TestSuite,
- t *template.Template) error {
- var mthdMap map[string]*mthd
- mthdMap = make(map[string]*mthd)
- // Generate the test cases
- log.Info("Generating the test cases: runTests.go")
- tc := &TestList{Funcs: make(map[string]MethodTypes),
- FileNum: 0, HasFuncs: false,
- Offset: 0}
- for _, v := range ts.Env.Imports {
- tc.Imports = append(tc.Imports, Import{Package: v, Used: true})
- }
-
- // Load the proto descriptor file
- for _, v := range ts.Env.ProtoFiles {
- imp := &ProtoImport{Short: v.Package,
- Package: v.ImportPath + v.Package,
- Service: v.Service,
- Used: true}
- tc.ProtoImports = append(tc.ProtoImports, *imp)
- // Compile the template from the file
- log.Debugf("Proto substs: %v", ts.Env.ProtoSubsts)
- if mthds, err := loadProtoMap(ts.Env.ProtoDesc, v.Package,
- v.Service, ts.Env.ProtoSubsts); err != nil {
- log.Errorf("Unable to process proto descriptor file %s for package: %s, service: %s",
- ts.Env.ProtoDesc, v.Package, v.Service)
- return err
- } else {
- // Add to the known methods
- for k, v := range mthds {
- mthdMap[k] = v
- }
- }
- }
- // Since the input file can possibly be a template with loops that
- // make multiple calls to exactly the same method with potentially
- // different parameters it is best to try to optimize for that case.
- // Creating a function for each method used will greatly reduce the
- // code size and repetition. In the case where a method is used only
- // once the resulting code will be bigger but this is an acceptable
- // tradeoff to allow huge suites that call the same method repeatedly
- // to test for leaks.
-
- // The go compiler has trouble compiling files that are too large. In order
- // to mitigate that, It's necessary to create more smaller files than the
- // single one large one while making sure that the functions for the distinct
- // methods are only defined once in one of the files.
-
- // Yet another hiccup with the go compiler, it doesn't like deep function
- // nesting meaning that each runTests function can't call the next without
- // eventually blowing the stack check. In order to work around this, the
- // first runTests function needs to call all the others in sequence to
- // keep the stack depth constant.
-
- // Counter limiting the number of tests to output to each file
- maxCt := MAX_CT
-
- // Get the list of distinct methods
- //for _,v := range ts.Tests {
- // if _,ok := tc.Funcs[v.Send.Method]; ok == false {
- // tc.Funcs[v.Send.Method] = MethodTypes{ParamType:mthdMap[v.Send.Method].Param,
- // ReturnType:mthdMap[v.Send.Method].Rtrn}
- // }
- //}
- for i := 1; i < int(math.Ceil(float64(len(ts.Tests))/float64(MAX_CT))); i++ {
- tc.RunTestsCallList = append(tc.RunTestsCallList, "runTests"+strconv.Itoa(i))
- }
-
- // Create the test data structure for the template
- for _, v := range ts.Tests {
- var test TestCase
-
- if _, ok := tc.Funcs[v.Send.Method]; ok == false {
- tc.Funcs[v.Send.Method] = MethodTypes{ParamType: mthdMap[v.Send.Method].Param,
- ReturnType: mthdMap[v.Send.Method].Rtrn,
- CodeGenerated: false}
- tc.HasFuncs = true
- }
-
- test.Name = v.Name
- test.InfoOnly = v.InfoOnly
- test.Send.Client = v.Send.Client
- test.Send.Method = v.Send.Method
- test.Send.Param = v.Send.Param
- test.Send.ParamType = mthdMap[test.Send.Method].Param
- test.Send.Expect = v.Send.Expect
- test.Send.ExpectType = mthdMap[test.Send.Method].Rtrn
- for _, v1 := range v.Send.MetaData {
- test.Send.MetaData = append(test.Send.MetaData, v1)
- }
- for _, v1 := range v.Send.ExpectMeta {
- test.Send.ExpectMeta = append(test.Send.ExpectMeta, v1)
- }
- for _, v1 := range v.Servers {
- var srvr Server
- if serverExists(v1.Name, ts) == false {
- log.Errorf("Server '%s' is not defined!!", v1.Name)
- return errors.New(fmt.Sprintf("Failed to build test case %s", v.Name))
- }
- srvr.Name = v1.Name
- srvr.Meta = v1.Meta
- test.Srvr = append(test.Srvr, srvr)
- }
- tc.Tests = append(tc.Tests, test)
- if maxCt--; maxCt == 0 {
- // Get the list of proto pacakges required for this file
- pkgs := getPackageList(tc.Tests)
- // Adjust the proto import data accordingly
- tc.ProtoImports = fixupProtoImports(tc.ProtoImports, pkgs)
- tc.Imports = fixupImports(tc.Imports, pkgs)
- //log.Infof("The packages needed are: %v", pkgs)
- if f, err := os.Create(suiteDir + "/runTests" + strconv.Itoa(tc.FileNum) + ".go"); err == nil {
- if err := t.ExecuteTemplate(f, "runTests.go.tmpl", tc); err != nil {
- log.Errorf("Unable to execute template for runTests.go: %v", err)
- }
- f.Close()
- } else {
- log.Errorf("Couldn't create file %s : %v",
- suiteDir+"/runTests"+strconv.Itoa(tc.FileNum)+".go", err)
- }
- tc.FileNum++
- //tc.NextFile++
- maxCt = MAX_CT
- // Mark the functions as generated.
- tc.Tests = []TestCase{}
- for k, v := range tc.Funcs {
- tc.Funcs[k] = MethodTypes{ParamType: v.ParamType,
- ReturnType: v.ReturnType,
- CodeGenerated: true}
- }
- tc.HasFuncs = false
- tc.Offset += MAX_CT
- //tmp,_ := strconv.Atoi(tc.Offset)
- //tc.Offset = strconv.Itoa(tmp+500)
- }
- }
- //tc.NextFile = 0
- // Get the list of proto pacakges required for this file
- pkgs := getPackageList(tc.Tests)
- // Adjust the proto import data accordingly
- tc.ProtoImports = fixupProtoImports(tc.ProtoImports, pkgs)
- tc.Imports = fixupImports(tc.Imports, pkgs)
- //log.Infof("The packages needed are: %v", pkgs)
- if f, err := os.Create(suiteDir + "/runTests" + strconv.Itoa(tc.FileNum) + ".go"); err == nil {
- if err := t.ExecuteTemplate(f, "runTests.go.tmpl", tc); err != nil {
- log.Errorf("Unable to execute template for runTests.go: %v", err)
- }
- f.Close()
- } else {
- log.Errorf("Couldn't create file %s : %v",
- suiteDir+"/runTests"+strconv.Itoa(tc.FileNum)+".go", err)
- }
-
- //if f,err := os.Create(suiteDir+"/runTests.go"); err == nil {
- // if err := t.ExecuteTemplate(f, "runTests.go.tmpl", tc); err != nil {
- // log.Errorf("Unable to execute template for runTests.go: %v", err)
- // }
- // f.Close()
- //} else {
- // log.Errorf("Couldn't create file %s : %v", suiteDir+"/runTests.go", err)
- //}
- return nil
-}
-
-func generateTestSuites(conf *TestConfig, srcDir string, outDir string) error {
-
- // Create a directory for the tests
- if err := os.Mkdir(srcDir, 0777); err != nil {
- log.Errorf("Unable to create directory 'tests':%v\n", err)
- return err
- }
-
- for k, v := range conf.Suites {
- var suiteDir string = srcDir + "/" + v
- log.Debugf("Suite[%d] - %s", k, v)
- ts := &TestSuite{}
- ts.loadSuite(v)
- log.Debugf("Suite %s: %v", v, ts)
- log.Infof("Processing test suite %s", v)
-
- t := template.Must(template.New("").ParseFiles("../templates/server.go.tmpl",
- "../templates/serverInit.go.tmpl",
- "../templates/client.go.tmpl",
- "../templates/clientInit.go.tmpl",
- "../templates/runTests.go.tmpl",
- "../templates/stats.go.tmpl",
- "../templates/main.go.tmpl"))
- // Create a directory for he source code for this test suite
- if err := os.Mkdir(suiteDir, 0777); err != nil {
- log.Errorf("Unable to create directory '%s':%v\n", v, err)
- return err
- }
- // Generate the server source files
- if err := generateServers(conf, suiteDir, ts, t); err != nil {
- log.Errorf("Unable to generate server source files: %v", err)
- return err
- }
- // Generate the client source files
- if err := generateClients(conf, suiteDir, ts, t); err != nil {
- log.Errorf("Unable to generate client source files: %v", err)
- return err
- }
- // Generate the test case source file
- if err := generateTestCases(conf, suiteDir, ts, t); err != nil {
- log.Errorf("Unable to generate test case source file: %v", err)
- return err
- }
-
- // Finally generate the main file
- log.Info("Generating main.go")
- if f, err := os.Create(suiteDir + "/main.go"); err == nil {
- if err := t.ExecuteTemplate(f, "main.go.tmpl", ts.Env); err != nil {
- log.Errorf("Unable to execute template for main.go: %v", err)
- }
- f.Close()
- } else {
- log.Errorf("Couldn't create file %s : %v", suiteDir+"/main.go", err)
- }
-
- log.Infof("Copying over common modules")
- if f, err := os.Create(suiteDir + "/stats.go"); err == nil {
- if err := t.ExecuteTemplate(f, "stats.go.tmpl", ts.Env); err != nil {
- log.Errorf("Unable to execute template for stats.go: %v", err)
- }
- f.Close()
- } else {
- log.Errorf("Couldn't create file %s : %v", suiteDir+"/stats.go", err)
- }
-
- log.Infof("Compiling test suite: %s in directory %s", v, suiteDir)
- if err := os.Chdir(suiteDir); err != nil {
- log.Errorf("Could not change to directory '%s':%v", suiteDir, err)
- }
- cmd := exec.Command("go", "build", "-o", outDir+"/"+v+".e")
- cmd.Stdin = os.Stdin
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
- if err := cmd.Run(); err != nil {
- log.Errorf("Error running the compile command:%v", err)
- }
- if err := os.Chdir("../../suites"); err != nil {
- log.Errorf("Could not change to directory '%s':%v", "../../suites", err)
- }
- }
- return nil
-
-}
-
-func generateTestDriver(conf *TestConfig, srcDir string, outDir string) error {
- // Generate the main test driver file
- if err := os.Mkdir(srcDir, 0777); err != nil {
- log.Errorf("Unable to create directory 'driver':%v\n", err)
- return err
- }
- t := template.Must(template.New("").ParseFiles("../templates/runAll.go.tmpl",
- "../templates/stats.go.tmpl"))
- if f, err := os.Create(srcDir + "/runAll.go"); err == nil {
- if err := t.ExecuteTemplate(f, "runAll.go.tmpl", conf.Suites); err != nil {
- log.Errorf("Unable to execute template for runAll.go: %v", err)
- }
- f.Close()
- } else {
- log.Errorf("Couldn't create file %s : %v", srcDir+"/runAll.go", err)
- }
- if f, err := os.Create(srcDir + "/stats.go"); err == nil {
- if err := t.ExecuteTemplate(f, "stats.go.tmpl", conf.Suites); err != nil {
- log.Errorf("Unable to execute template for stats.go: %v", err)
- }
- f.Close()
- } else {
- log.Errorf("Couldn't create file %s : %v", srcDir+"/stats.go", err)
- }
-
- // Compile the test driver file
- log.Info("Compiling the test driver")
- if err := os.Chdir("../tests/driver"); err != nil {
- log.Errorf("Could not change to directory 'driver':%v", err)
- }
- cmd := exec.Command("go", "build", "-o", outDir+"/runAll")
- cmd.Stdin = os.Stdin
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
- if err := cmd.Run(); err != nil {
- log.Errorf("Error running the compile command:%v", err)
- }
- if err := os.Chdir("../../suites"); err != nil {
- log.Errorf("Could not change to directory 'driver':%v", err)
- }
-
- return nil
-}
-
-func main() {
-
- conf, err := parseCmd()
- if err != nil {
- fmt.Printf("Error: %v\n", err)
- return
- }
-
- // Setup logging
- if _, err := log.SetDefaultLogger(log.JSON, *conf.logLevel, nil); err != nil {
- log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
- }
-
- defer log.CleanUp()
-
- // Parse the config file
- if err := conf.loadConfig(); err != nil {
- log.Error(err)
- }
-
- generateTestSuites(conf, "../tests", "/src/tests")
- generateTestDriver(conf, "../tests/driver", "/src/tests")
- return
-}
diff --git a/tests/afrouter/tester/main.go b/tests/afrouter/tester/main.go
deleted file mode 100644
index b733efc..0000000
--- a/tests/afrouter/tester/main.go
+++ /dev/null
@@ -1,39 +0,0 @@
-// +build integration
-
-/*
- * Copyright 2018-present Open Networking Foundation
-
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
-
- * http://www.apache.org/licenses/LICENSE-2.0
-
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// The template for the tester.
-// This template is filled in by the
-// test driver based on the configuration.
-
-package main
-
-import (
- "github.com/opencord/voltha-lib-go/v3/pkg/log"
-)
-
-func main() {
- // Setup logging
- /*
- if _, err := log.SetDefaultLogger(log.JSON, 0, nil); err != nil {
- log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
- }
- */
-
- defer log.CleanUp()
-
- log.Info("Template runs!")
-}
diff --git a/vendor/github.com/bclicn/color/LICENSE b/vendor/github.com/bclicn/color/LICENSE
deleted file mode 100644
index c22bc5f..0000000
--- a/vendor/github.com/bclicn/color/LICENSE
+++ /dev/null
@@ -1,23 +0,0 @@
-
-The MIT License (MIT)
-
-Copyright (c) 2016-2018 bcli
-
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/vendor/github.com/bclicn/color/README.md b/vendor/github.com/bclicn/color/README.md
deleted file mode 100644
index 1065950..0000000
--- a/vendor/github.com/bclicn/color/README.md
+++ /dev/null
@@ -1,43 +0,0 @@
-# GoLang Colorized Output
-
-GoLang colorized output library for Mac & Linux Shell, [中文版说明](README_CN.md)
-
-## Showcase
-![img](showcase.jpg)
-
-## Install
-
-1. __Make sure__ your've read [GoLang Official File Structure](https://golang.org/doc/code.html)
-2. Make sure you've set a correct GOPATH
-3. `$ go get github.com/bclicn/color`
-4. In your script, `import "github.com/bclicn/color"` then call `color.Test()`
-5. Use `fmt.Println("Hello" + color.Red("World"))` to assemble a colorized output
-6. API examples available in `color-test.go`
-
-## Quick (brainless) Usage
-
-1. Download `color.go`
-2. Modify its `package color` to `package main`
-3. Put your script under the same directory and write `fmt.Println(Red("I'm red !!!"))`
-4. Run `go run color.go yourScript.go`
-5. Or build by `go build color.go yourScript.go`
-
-## A simple test script
-
- package main
-
- import (
- "fmt"
- "github.com/bclicn/color"
- )
-
- func main(){
- fmt.Println(color.Red("Red output"))
- color.Test()
- }
-
-## License
-
-[MIT](LICENSE)
-
-bcli, 2018-7-11
diff --git a/vendor/github.com/bclicn/color/README_CN.md b/vendor/github.com/bclicn/color/README_CN.md
deleted file mode 100644
index 25b447e..0000000
--- a/vendor/github.com/bclicn/color/README_CN.md
+++ /dev/null
@@ -1,43 +0,0 @@
-# GoLang 彩色输出
-
-用于Mac和Linux Shell的GoLang彩色文字输出, [English Version](README.md)
-
-## 效果展示
-![img](showcase.jpg)
-
-## 安装
-
-1. __确保__你已经读过 [GoLang官方文件结构](https://golang.org/doc/code.html)
-2. 确保你的GOPATH环境变量正确
-3. `go get github.com/bclicn/color`
-3. 在你的脚本中,`import "github.com/bclicn/color"` 然后调用 `color.Test()`查看全部效果
-5. 使用`fmt.Println("Hello" + color.Red("World"))`进行彩色输出
-4. API调用示例在`color-test.go`
-
-## 快速(无脑)使用
-
-1. 下载`color.go`
-2. 将其第一行的`package color`改为`package main`
-3. 把你的脚本放在同一个文件夹下,直接调用如`fmt.Println(Red("I'm red !!!"))`
-4. 运行`go run color.go yourScript.go`
-5. 你也可以直接`go build color.go yourScript.go`
-
-## 快速调用示例
-
- package main
-
- import (
- "fmt"
- "github.com/bclicn/color"
- )
-
- func main(){
- fmt.Println(color.Red("Red output"))
- color.Test()
- }
-
-## License
-
-[MIT](LICENSE)
-
-bcli, 2018-7-11
diff --git a/vendor/github.com/bclicn/color/color-test.go b/vendor/github.com/bclicn/color/color-test.go
deleted file mode 100644
index 59e9b5b..0000000
--- a/vendor/github.com/bclicn/color/color-test.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package color
-
-import (
- "fmt"
-)
-
-// github.com/bclicn/color
-// colorized output for Mac & Linux terminal
-// version: 1.0.0
-// author: bcli, bclicn@gmail.com, 2016-11-4
-// see: http://misc.flogisoft.com/bash/tip_colors_and_formatting
-// usage:
-// For official code layout
-// $ go get github.com/bclicn/color
-// # in your project
-// import "github.com/bclicn/color"
-// func main() {
-// color.Test()
-// }
-
-func ColorTest() {
-
- const HEAD = " "
- const TAIL = " "
-
- // regular
- fmt.Println(HEAD + Black("black") + TAIL)
- fmt.Println(HEAD + Red("red") + TAIL)
- fmt.Println(HEAD + Green("green") + TAIL)
- fmt.Println(HEAD + Yellow("yellow") + TAIL)
- fmt.Println(HEAD + Blue("blue") + TAIL)
- fmt.Println(HEAD + Purple("purple") + TAIL)
- fmt.Println(HEAD + Cyan("cyan") + TAIL)
- fmt.Println(HEAD + LightGray("light gray") + TAIL)
- fmt.Println(HEAD + DarkGray("dark gray") + TAIL)
- fmt.Println(HEAD + LightRed("light red") + TAIL)
- fmt.Println(HEAD + LightGreen("light green") + TAIL)
- fmt.Println(HEAD + LightYellow("light yellow") + TAIL)
- fmt.Println(HEAD + LightBlue("light blue") + TAIL)
- fmt.Println(HEAD + LightPurple("light purple") + TAIL)
- fmt.Println(HEAD + LightCyan("light cyan") + TAIL)
- fmt.Println(HEAD + White("white") + TAIL)
-
- // bold
- fmt.Println(HEAD + BBlack("bold black") + TAIL)
- fmt.Println(HEAD + BRed("bold red") + TAIL)
- fmt.Println(HEAD + BGreen("bold green") + TAIL)
- fmt.Println(HEAD + BYellow("bold yellow") + TAIL)
- fmt.Println(HEAD + BBlue("bold blue") + TAIL)
- fmt.Println(HEAD + BPurple("bold purple") + TAIL)
- fmt.Println(HEAD + BCyan("bold cyan") + TAIL)
- fmt.Println(HEAD + BLightGray("bold light gray") + TAIL)
- fmt.Println(HEAD + BDarkGray("bold dark gray") + TAIL)
- fmt.Println(HEAD + BLightRed("bold light red") + TAIL)
- fmt.Println(HEAD + BLightGreen("bold light green") + TAIL)
- fmt.Println(HEAD + BLightYellow("bold light yellow") + TAIL)
- fmt.Println(HEAD + BLightBlue("bold light blue") + TAIL)
- fmt.Println(HEAD + BLightPurple("bold light purple") + TAIL)
- fmt.Println(HEAD + BLightCyan("bold light cyan") + TAIL)
- fmt.Println(HEAD + BWhite("bold white") + TAIL)
-
- // background
- fmt.Println(HEAD + GBlack("background black") + TAIL)
- fmt.Println(HEAD + GRed("background red") + TAIL)
- fmt.Println(HEAD + GGreen("background green") + TAIL)
- fmt.Println(HEAD + GYellow("background yellow") + TAIL)
- fmt.Println(HEAD + GBlue("background blue") + TAIL)
- fmt.Println(HEAD + GPurple("background purple") + TAIL)
- fmt.Println(HEAD + GCyan("background cyan") + TAIL)
- fmt.Println(HEAD + GLightGray("background light gray") + TAIL)
- fmt.Println(HEAD + GDarkGray("background dark gray") + TAIL)
- fmt.Println(HEAD + GLightRed("background light red") + TAIL)
- fmt.Println(HEAD + GLightGreen("background light green") + TAIL)
- fmt.Println(HEAD + GLightYellow("background light yellow") + TAIL)
- fmt.Println(HEAD + GLightBlue("background light blue") + TAIL)
- fmt.Println(HEAD + GLightPurple("background light purple") + TAIL)
- fmt.Println(HEAD + GLightCyan("background light cyan") + TAIL)
- fmt.Println(HEAD + GWhite("background white") + TAIL)
-
- // special
- fmt.Println("A " + Bold("bold") + " text")
- fmt.Println("This is a " + Dim("dimmed") + " text")
- fmt.Println("Add a " + Underline("underline"))
- fmt.Println("Use " + Invert("invert") + " to highlight your text")
- fmt.Println("Your password is:" + Hide("myPass"))
- fmt.Println("OMG I'm " + Blink("blinking") + " !!!") // blinking works only on mac
-}
diff --git a/vendor/github.com/bclicn/color/color.go b/vendor/github.com/bclicn/color/color.go
deleted file mode 100644
index ce7fc83..0000000
--- a/vendor/github.com/bclicn/color/color.go
+++ /dev/null
@@ -1,330 +0,0 @@
-// github.com/bclicn/color
-// colorized output for Mac & Linux terminal
-// version: 1.0.0
-// author: bcli, bclicn@gmail.com, 2018-7-11
-// see: http://misc.flogisoft.com/bash/tip_colors_and_formatting
-// usage:
-// Official layout
-// $ go get github.com/bclicn/color
-// # in your project
-// import "github.com/bclicn/color"
-// func main() {
-// fmt.Println(color.Red("I'm red!"))
-// color.Test()
-// }
-
-package color
-
-import (
- "strconv"
-)
-
-const (
- // common
- reset = "\033[0m" // auto reset the rest of text to default color
- normal = 0
- bold = 1 // increase this value if you want bolder text
- // special
- dim = 2
- underline = 4
- blink = 5
- reverse = 7
- hidden = 8
- // color
- black = 30 // default = 39
- red = 31
- green = 32
- yellow = 33
- blue = 34
- purple = 35 // purple = magenta
- cyan = 36
- lightGray = 37
- darkGray = 90
- lightRed = 91
- lightGreen = 92
- lightYellow = 93
- lightBlue = 94
- lightPurple = 95
- lightCyan = 96
- white = 97
-)
-
-// you can use custom color code and font size by calling this function
-func Render(colorCode int, fontSize int, content string) string {
- return "\033[" + strconv.Itoa(fontSize) + ";" + strconv.Itoa(colorCode) + "m" + content + reset
-}
-
-// black text (use this with caution since most geeks use dark console)
-func Black(txt string) string {
- return Render(black, normal, txt)
-}
-
-// red text
-func Red(txt string) string {
- return Render(red, normal, txt)
-}
-
-// green text
-func Green(txt string) string {
- return Render(green, normal, txt)
-}
-
-// yellow text
-func Yellow(txt string) string {
- return Render(yellow, normal, txt)
-}
-
-// blue text
-func Blue(txt string) string {
- return Render(blue, normal, txt)
-}
-
-// purple text
-func Purple(txt string) string {
- return Render(purple, normal, txt)
-}
-
-// cyan text
-func Cyan(txt string) string {
- return Render(cyan, normal, txt)
-}
-
-// light gray text
-func LightGray(txt string) string {
- return Render(lightGray, normal, txt)
-}
-
-// dark gray text
-func DarkGray(txt string) string {
- return Render(darkGray, normal, txt)
-}
-
-// light red text
-func LightRed(txt string) string {
- return Render(lightRed, normal, txt)
-}
-
-// light green text
-func LightGreen(txt string) string {
- return Render(lightGreen, normal, txt)
-}
-
-// light yellow text
-func LightYellow(txt string) string {
- return Render(lightYellow, normal, txt)
-}
-
-// light blue text
-func LightBlue(txt string) string {
- return Render(lightBlue, normal, txt)
-}
-
-// light purple text
-func LightPurple(txt string) string {
- return Render(lightPurple, normal, txt)
-}
-
-// light cyan text
-func LightCyan(txt string) string {
- return Render(lightCyan, normal, txt)
-}
-
-// white text
-func White(txt string) string {
- return Render(white, normal, txt)
-}
-
-// black text (use this with caution since most geeks use dark console)
-func BBlack(txt string) string {
- return Render(black, bold, txt)
-}
-
-// bold red
-func BRed(txt string) string {
- return Render(red, bold, txt)
-}
-
-// bold green
-func BGreen(txt string) string {
- return Render(green, bold, txt)
-}
-
-// bold yellow
-func BYellow(txt string) string {
- return Render(yellow, bold, txt)
-}
-
-// bold blue
-func BBlue(txt string) string {
- return Render(blue, bold, txt)
-}
-
-// bold purple
-func BPurple(txt string) string {
- return Render(purple, bold, txt)
-}
-
-// bold cyan
-func BCyan(txt string) string {
- return Render(cyan, bold, txt)
-}
-
-// bold light gray
-func BLightGray(txt string) string {
- return Render(lightGray, bold, txt)
-}
-
-// bold dark gray
-func BDarkGray(txt string) string {
- return Render(darkGray, bold, txt)
-}
-
-// bold light red
-func BLightRed(txt string) string {
- return Render(lightRed, bold, txt)
-}
-
-// bold light green
-func BLightGreen(txt string) string {
- return Render(lightGreen, bold, txt)
-}
-
-// bold light yellow
-func BLightYellow(txt string) string {
- return Render(lightYellow, bold, txt)
-}
-
-// bold light blue
-func BLightBlue(txt string) string {
- return Render(lightBlue, bold, txt)
-}
-
-// bold light purple
-func BLightPurple(txt string) string {
- return Render(lightPurple, bold, txt)
-}
-
-// bold light cyan
-func BLightCyan(txt string) string {
- return Render(lightCyan, bold, txt)
-}
-
-// bold white
-func BWhite(txt string) string {
- return Render(white, bold, txt)
-}
-
-// black background (use this with caution since most of geeks use dark console)
-func GBlack(txt string) string {
- return Render(black+1, normal, txt)
-}
-
-// red background
-func GRed(txt string) string {
- return Render(red+1, normal, txt)
-}
-
-// green background
-func GGreen(txt string) string {
- return Render(green+1, normal, txt)
-}
-
-// yellow background
-func GYellow(txt string) string {
- return Render(yellow+1, normal, txt)
-}
-
-// blue background
-func GBlue(txt string) string {
- return Render(blue+1, normal, txt)
-}
-
-// purple background
-func GPurple(txt string) string {
- return Render(purple+1, normal, txt)
-}
-
-// cyan background
-func GCyan(txt string) string {
- return Render(cyan+1, normal, txt)
-}
-
-// light gray background
-func GLightGray(txt string) string {
- return Render(lightGray+1, normal, txt)
-}
-
-// dark gray background
-func GDarkGray(txt string) string {
- return Render(darkGray+1, normal, txt)
-}
-
-// light red background
-func GLightRed(txt string) string {
- return Render(lightRed+1, normal, txt)
-}
-
-// light green background
-func GLightGreen(txt string) string {
- return Render(lightGreen+1, normal, txt)
-}
-
-// light yellow background
-func GLightYellow(txt string) string {
- return Render(lightYellow+1, normal, txt)
-}
-
-// blue background
-func GLightBlue(txt string) string {
- return Render(lightBlue+1, normal, txt)
-}
-
-// light purple background
-func GLightPurple(txt string) string {
- return Render(lightPurple+1, normal, txt)
-}
-
-// light cyan background
-func GLightCyan(txt string) string {
- return Render(lightCyan+1, normal, txt)
-}
-
-// give text a white background
-func GWhite(txt string) string {
- return Render(white+1, normal, txt)
-}
-
-// bold text
-func Bold(txt string) string {
- return Render(bold, normal, txt)
-}
-
-// dimmed text
-func Dim(txt string) string {
- return Render(dim, normal, txt)
-}
-
-// underlined text
-func Underline(txt string) string {
- return Render(underline, 0, txt)
-}
-
-// make given text blink, not supported by all consoles
-func Blink(txt string) string {
- return Render(blink, normal, txt)
-}
-
-// invert the color of text and its background
-func Invert(txt string) string {
- return Render(reverse, normal, txt)
-}
-
-// hide given text, useful for password input
-func Hide(txt string) string {
- return Render(hidden, normal, txt)
-}
-
-// test all functions
-func Test() {
- ColorTest()
-}
diff --git a/vendor/github.com/bclicn/color/showcase.jpg b/vendor/github.com/bclicn/color/showcase.jpg
deleted file mode 100644
index 39f270c..0000000
--- a/vendor/github.com/bclicn/color/showcase.jpg
+++ /dev/null
Binary files differ
diff --git a/vendor/modules.txt b/vendor/modules.txt
index bede00a..ea98501 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -4,8 +4,6 @@
github.com/Shopify/sarama
# github.com/armon/go-metrics v0.0.0-20190430140413-ec5e00d3c878
github.com/armon/go-metrics
-# github.com/bclicn/color v0.0.0-20180711051946-108f2023dc84
-github.com/bclicn/color
# github.com/beorn7/perks v1.0.0
github.com/beorn7/perks/quantile
# github.com/bsm/sarama-cluster v2.1.15+incompatible
@@ -104,19 +102,19 @@
github.com/opencord/voltha-lib-go/v3/pkg/log
github.com/opencord/voltha-lib-go/v3/pkg/db
github.com/opencord/voltha-lib-go/v3/pkg/db/kvstore
+github.com/opencord/voltha-lib-go/v3/pkg/kafka
github.com/opencord/voltha-lib-go/v3/pkg/probe
github.com/opencord/voltha-lib-go/v3/pkg/version
-github.com/opencord/voltha-lib-go/v3/pkg/grpc
-github.com/opencord/voltha-lib-go/v3/pkg/kafka
github.com/opencord/voltha-lib-go/v3/pkg/flows
+github.com/opencord/voltha-lib-go/v3/pkg/grpc
github.com/opencord/voltha-lib-go/v3/pkg/adapters/adapterif
github.com/opencord/voltha-lib-go/v3/pkg/adapters/common
-github.com/opencord/voltha-lib-go/v3/pkg/mocks
github.com/opencord/voltha-lib-go/v3/pkg/adapters
+github.com/opencord/voltha-lib-go/v3/pkg/mocks
# github.com/opencord/voltha-protos/v3 v3.0.0
github.com/opencord/voltha-protos/v3/go/common
-github.com/opencord/voltha-protos/v3/go/voltha
github.com/opencord/voltha-protos/v3/go/openflow_13
+github.com/opencord/voltha-protos/v3/go/voltha
github.com/opencord/voltha-protos/v3/go/inter_container
github.com/opencord/voltha-protos/v3/go/omci
# github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2
@@ -245,20 +243,20 @@
go.uber.org/zap/internal/exit
# golang.org/x/crypto v0.0.0-20191001170739-f9e2070545dc
golang.org/x/crypto/bcrypt
-golang.org/x/crypto/blowfish
golang.org/x/crypto/md4
-golang.org/x/crypto/ssh/terminal
+golang.org/x/crypto/blowfish
golang.org/x/crypto/pbkdf2
+golang.org/x/crypto/ssh/terminal
# golang.org/x/net v0.0.0-20190930134127-c5a3c61f89f3
golang.org/x/net/trace
+golang.org/x/net/proxy
golang.org/x/net/internal/timeseries
golang.org/x/net/http2
golang.org/x/net/http2/hpack
-golang.org/x/net/proxy
-golang.org/x/net/http/httpguts
-golang.org/x/net/idna
golang.org/x/net/context
golang.org/x/net/internal/socks
+golang.org/x/net/http/httpguts
+golang.org/x/net/idna
# golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24
golang.org/x/sys/unix
golang.org/x/sys/windows
@@ -279,10 +277,10 @@
google.golang.org/grpc/codes
google.golang.org/grpc/metadata
google.golang.org/grpc/status
+google.golang.org/grpc/credentials
google.golang.org/grpc/balancer
google.golang.org/grpc/balancer/roundrobin
google.golang.org/grpc/connectivity
-google.golang.org/grpc/credentials
google.golang.org/grpc/encoding
google.golang.org/grpc/encoding/proto
google.golang.org/grpc/grpclog
@@ -304,8 +302,8 @@
google.golang.org/grpc/serviceconfig
google.golang.org/grpc/stats
google.golang.org/grpc/tap
-google.golang.org/grpc/balancer/base
google.golang.org/grpc/credentials/internal
+google.golang.org/grpc/balancer/base
google.golang.org/grpc/binarylog/grpc_binarylog_v1
google.golang.org/grpc/internal/syscall
google.golang.org/grpc/health