Merge "Added tests and improvements"
authorHenrik Andersson <henrik.b.andersson@est.tech>
Fri, 19 Nov 2021 09:54:48 +0000 (09:54 +0000)
committerGerrit Code Review <gerrit@o-ran-sc.org>
Fri, 19 Nov 2021 09:54:48 +0000 (09:54 +0000)
27 files changed:
dmaap-mediator-producer/internal/jobs/jobs_test.go
dmaap-mediator-producer/internal/server/server_test.go
dmaap-mediator-producer/stub/consumer/consumerstub.go
dmaap-mediator-producer/stub/dmaap/mrstub.go
docker-compose/.env [new file with mode: 0644]
docker-compose/a1-sim/docker-compose.yaml
docker-compose/dmaap-mediator-go/docker-compose.yaml
docker-compose/dmaap-mediator-java/docker-compose.yaml
docker-compose/ecs/docker-compose.yaml
docker-compose/policy-service/docker-compose.yaml
docker-compose/rapp/docker-compose.yaml
test/usecases/oruclosedlooprecovery/goversion/.gitignore
test/usecases/oruclosedlooprecovery/goversion/README.md
test/usecases/oruclosedlooprecovery/goversion/go.mod
test/usecases/oruclosedlooprecovery/goversion/go.sum
test/usecases/oruclosedlooprecovery/goversion/internal/config/config.go
test/usecases/oruclosedlooprecovery/goversion/internal/config/config_test.go
test/usecases/oruclosedlooprecovery/goversion/internal/linkfailure/linkfailurehandler.go
test/usecases/oruclosedlooprecovery/goversion/internal/restclient/client.go
test/usecases/oruclosedlooprecovery/goversion/internal/restclient/client_test.go
test/usecases/oruclosedlooprecovery/goversion/main.go
test/usecases/oruclosedlooprecovery/goversion/main_test.go
test/usecases/oruclosedlooprecovery/goversion/mocks/Server.go [deleted file]
test/usecases/oruclosedlooprecovery/goversion/security/consumer.crt [new file with mode: 0644]
test/usecases/oruclosedlooprecovery/goversion/security/consumer.key [new file with mode: 0644]
test/usecases/oruclosedlooprecovery/goversion/stub/producer/producerstub.go [moved from test/usecases/oruclosedlooprecovery/goversion/simulator/producer.go with 100% similarity]
test/usecases/oruclosedlooprecovery/goversion/stub/sdnr/sdnrstub.go [new file with mode: 0644]

index e48e68d..552b5fa 100644 (file)
@@ -177,7 +177,7 @@ func TestAddJobToJobsManager_shouldStartPollAndDistributeMessages(t *testing.T)
        distributeClientMock := NewTestClient(func(req *http.Request) *http.Response {
                if req.URL.String() == "http://consumerHost/target" {
                        assertions.Equal(req.Method, "POST")
-                       assertions.Equal(messages, getBodyAsString(req))
+                       assertions.Equal(messages, getBodyAsString(req, t))
                        assertions.Equal("application/json", req.Header.Get("Content-Type"))
                        wg.Done()
                        return &http.Response{
@@ -208,7 +208,8 @@ func TestAddJobToJobsManager_shouldStartPollAndDistributeMessages(t *testing.T)
        }
 
        wg.Add(1) // Wait till the distribution has happened
-       jobsManager.AddJobFromRESTCall(jobInfo)
+       err := jobsManager.AddJobFromRESTCall(jobInfo)
+       assertions.Nil(err)
 
        if waitTimeout(&wg, 2*time.Second) {
                t.Error("Not all calls to server were made")
@@ -287,8 +288,10 @@ func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
        }
 }
 
-func getBodyAsString(req *http.Request) string {
+func getBodyAsString(req *http.Request, t *testing.T) string {
        buf := new(bytes.Buffer)
-       buf.ReadFrom(req.Body)
+       if _, err := buf.ReadFrom(req.Body); err != nil {
+               t.Fail()
+       }
        return buf.String()
 }
index 5c2027a..1d458c9 100644 (file)
@@ -136,7 +136,7 @@ func TestAddInfoJobHandler(t *testing.T) {
        for _, tt := range tests {
                t.Run(tt.name, func(t *testing.T) {
                        jobHandlerMock := jobhandler.JobHandler{}
-                       jobHandlerMock.On("AddJob", tt.args.job).Return(tt.args.mockReturn)
+                       jobHandlerMock.On("AddJobFromRESTCall", tt.args.job).Return(tt.args.mockReturn)
 
                        callbackHandlerUnderTest := NewProducerCallbackHandler(&jobHandlerMock)
 
@@ -148,7 +148,7 @@ func TestAddInfoJobHandler(t *testing.T) {
 
                        assertions.Equal(tt.wantedStatus, responseRecorder.Code, tt.name)
                        assertions.Contains(responseRecorder.Body.String(), tt.wantedBody, tt.name)
-                       jobHandlerMock.AssertCalled(t, "AddJob", tt.args.job)
+                       jobHandlerMock.AssertCalled(t, "AddJobFromRESTCall", tt.args.job)
                })
        }
 }
@@ -156,7 +156,7 @@ func TestAddInfoJobHandler(t *testing.T) {
 func TestDeleteJob(t *testing.T) {
        assertions := require.New(t)
        jobHandlerMock := jobhandler.JobHandler{}
-       jobHandlerMock.On("DeleteJob", mock.Anything).Return(nil)
+       jobHandlerMock.On("DeleteJobFromRESTCall", mock.Anything).Return(nil)
 
        callbackHandlerUnderTest := NewProducerCallbackHandler(&jobHandlerMock)
 
@@ -168,7 +168,7 @@ func TestDeleteJob(t *testing.T) {
 
        assertions.Equal("", responseRecorder.Body.String())
 
-       jobHandlerMock.AssertCalled(t, "DeleteJob", "job1")
+       jobHandlerMock.AssertCalled(t, "DeleteJobFromRESTCall", "job1")
 }
 
 func newRequest(method string, url string, jobInfo *jobs.JobInfo, t *testing.T) *http.Request {
index 03e67c0..5cbcaea 100644 (file)
@@ -44,7 +44,7 @@ func main() {
        registerJob(*port)
 
        fmt.Print("Starting consumer on port: ", *port)
-       http.ListenAndServe(fmt.Sprintf(":%v", *port), nil)
+       fmt.Println(http.ListenAndServe(fmt.Sprintf(":%v", *port), nil))
 }
 
 func registerJob(port int) {
index 82ae08d..36ffa39 100644 (file)
@@ -57,7 +57,7 @@ func main() {
        http.HandleFunc("/events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/STD_Fault_Messages", handleData)
 
        fmt.Print("Starting mr on port: ", *port)
-       http.ListenAndServeTLS(fmt.Sprintf(":%v", *port), "../../security/producer.crt", "../../security/producer.key", nil)
+       fmt.Println(http.ListenAndServeTLS(fmt.Sprintf(":%v", *port), "../../security/producer.crt", "../../security/producer.key", nil))
 
 }
 
diff --git a/docker-compose/.env b/docker-compose/.env
new file mode 100644 (file)
index 0000000..6fc3528
--- /dev/null
@@ -0,0 +1,64 @@
+#  ============LICENSE_START===============================================
+#  Copyright (C) 2021 Nordix Foundation. All rights reserved.
+#  ========================================================================
+#  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.
+#  ============LICENSE_END=================================================
+#
+
+#PMS
+PMS_IMAGE_BASE="nexus3.o-ran-sc.org:10002/o-ran-sc/nonrtric-policy-agent"
+PMS_IMAGE_TAG="2.2.0"
+
+#A1_SIM
+A1_SIM_IMAGE_BASE="nexus3.o-ran-sc.org:10002/o-ran-sc/a1-simulator"
+A1_SIM_IMAGE_TAG="2.1.0"
+
+#RAPP
+RAPP_IMAGE_BASE="nexus3.o-ran-sc.org:10002/o-ran-sc/nonrtric-r-app-catalogue"
+RAPP_IMAGE_TAG="1.0.0"
+
+#CONTROL_PANEL
+CONTROL_PANEL_IMAGE_BASE="nexus3.o-ran-sc.org:10002/o-ran-sc/nonrtric-controlpanel"
+CONTROL_PANEL_IMAGE_TAG="2.2.0"
+
+#GATEWAY
+NONRTRIC_GATEWAY_IMAGE_BASE="nexus3.o-ran-sc.org:10002/o-ran-sc/nonrtric-gateway"
+NONRTRIC_GATEWAY_IMAGE_TAG="1.0.0"
+
+#ECS
+ECS_IMAGE_BASE="nexus3.o-ran-sc.org:10002/o-ran-sc/nonrtric-enrichment-coordinator-service"
+ECS_IMAGE_TAG="1.1.0"
+
+#CONSUMER
+CONSUMER_IMAGE_BASE="eexit/mirror-http-server"
+CONSUMER_IMAGE_TAG="latest"
+
+#ORU
+ORU_APP_IMAGE_BASE="nexus3.o-ran-sc.org:10002/o-ran-sc/nonrtric-o-ru-closed-loop-recovery"
+ORU_APP_IMAGE_TAG="1.0.0"
+
+#DB
+DB_IMAGE_BASE="mysql/mysql-server"
+DB_IMAGE_TAG="5.6"
+
+#A1CONTROLLER
+A1CONTROLLER_IMAGE_BASE="nexus3.onap.org:10002/onap/sdnc-image"
+A1CONTROLLER_IMAGE_TAG="2.1.2"
+
+#DMAAP_MEDIATOR_GO
+DMAAP_MEDIATOR_GO_BASE="nexus3.o-ran-sc.org:10004/o-ran-sc/nonrtric-dmaap-mediator-producer"
+DMAAP_MEDIATOR_GO_TAG="1.0,0"
+
+#DMAAP_MEDIATOR_JAVA
+DMAAP_MEDIATOR_JAVA_BASE="nexus3.o-ran-sc.org:10003/o-ran-sc/nonrtric-dmaap-adaptor"
+DMAAP_MEDIATOR_JAVA_TAG="1.0.0-SNAPSHOT"
\ No newline at end of file
index 9366ff1..8467946 100644 (file)
@@ -22,7 +22,7 @@ networks:
 
 services:
   a1-sim-OSC:
-    image: nexus3.o-ran-sc.org:10002/o-ran-sc/a1-simulator:2.1.0
+    image: "${A1_SIM_IMAGE_BASE}:${A1_SIM_IMAGE_TAG}"
     container_name: a1-sim-OSC
     networks:
       - default
@@ -35,7 +35,7 @@ services:
       - ALLOW_HTTP=true
 
   a1-sim-STD:
-    image: nexus3.o-ran-sc.org:10002/o-ran-sc/a1-simulator:2.1.0
+    image: "${A1_SIM_IMAGE_BASE}:${A1_SIM_IMAGE_TAG}"
     container_name: a1-sim-STD
     networks:
       - default
@@ -48,7 +48,7 @@ services:
       - ALLOW_HTTP=true
 
   a1-sim-STD-v2:
-    image: nexus3.o-ran-sc.org:10002/o-ran-sc/a1-simulator:2.1.0
+    image: "${A1_SIM_IMAGE_BASE}:${A1_SIM_IMAGE_TAG}"
     container_name: a1-sim-STD-v2
     networks:
       - default
index 340d158..4efdf57 100644 (file)
@@ -22,18 +22,15 @@ networks:
 
 services:
   dmaap-mediator-go:
-    image: nexus3.o-ran-sc.org:10004/o-ran-sc/nonrtric-dmaap-mediator-producer:1.0.0
+    image: "${DMAAP_MEDIATOR_GO_BASE}:${DMAAP_MEDIATOR_GO_TAG}"
     container_name: dmaap-mediator-go
     environment:
       - INFO_PRODUCER_HOST=http://consumer
-      - LOG_LEVEL=Debug
       - INFO_PRODUCER_PORT=8088
       - INFO_COORD_ADDR=http://ecs:8083
-      - MR_HOST=http://dmaap-mr
-      - MR_PORT=3904
-      - INFO_PRODUCER_SUPERVISION_CALLBACK_HOST=http://consumer
-      - INFO_PRODUCER_SUPERVISION_CALLBACK_PORT=8088
-      - INFO_JOB_CALLBACK_HOST=http://consumer
-      - INFO_JOB_CALLBACK_PORT=8088
+      - DMAAP_MR_ADDR=http://dmaap-mr:3904
+      - PRODUCER_CERT_PATH=security/producer.crt
+      - PRODUCER_KEY_PATH=security/producer.key
+      - LOG_LEVEL=Debug
     networks:
       - default
\ No newline at end of file
index 1d53de4..5cfe809 100644 (file)
@@ -22,7 +22,7 @@ networks:
 
 services:
   dmaap-mediator-java:
-    image: nexus3.o-ran-sc.org:10003/o-ran-sc/nonrtric-dmaap-adaptor:1.0.0-SNAPSHOT
+    image: "${DMAAP_MEDIATOR_JAVA_BASE}:${DMAAP_MEDIATOR_JAVA_TAG}"
     container_name: dmaap-mediator-java
     networks:
       - default
index 376f734..6de293f 100644 (file)
@@ -22,7 +22,7 @@ networks:
 
 services:
   ecs:
-    image: nexus3.o-ran-sc.org:10003/o-ran-sc/nonrtric-enrichment-coordinator-service:1.2.0-SNAPSHOT
+    image: "${ECS_IMAGE_BASE}:${ECS_IMAGE_TAG}"
     container_name: ecs
     networks:
       default:
@@ -32,7 +32,7 @@ services:
       - 8083:8083
       - 8434:8434
   consumer:
-    image: eexit/mirror-http-server
+    image: "${CONSUMER_IMAGE_BASE}:${CONSUMER_IMAGE_TAG}"
     container_name: consumer
     networks:
       - default
index a593e2e..2dfc38c 100644 (file)
@@ -22,7 +22,7 @@ networks:
 
 services:
   policy-agent:
-    image: nexus3.o-ran-sc.org:10004/o-ran-sc/nonrtric-policy-agent:2.3.0
+    image: "${PMS_IMAGE_BASE}:${PMS_IMAGE_TAG}"
     container_name: policy-agent
     networks:
       default:
index ade37f7..5477588 100644 (file)
@@ -22,7 +22,7 @@ networks:
 
 services:
   r-app:
-    image: nexus3.o-ran-sc.org:10004/o-ran-sc/nonrtric-r-app-catalogue:1.1.0
+    image: "${RAPP_IMAGE_BASE}:${RAPP_IMAGE_TAG}"
     container_name: r-app
     networks:
       default:
index 1ca37b3..ec542c1 100644 (file)
@@ -2,25 +2,52 @@
 
 This consumer creates a job of type `STD_Fault_Messages` in the Information Coordinator Service (ICS). When it recieves messages, it checks if they are link failure messages. If they are, it checks if the event severity is other than normal. If so, it looks up the O-DU ID mapped to the O-RU the message originates from and sends a configuration message to the O-DU through SDNC. If the event severity is normal, then it logs, on `Debug` level, that the link failure has been cleared.
 
-The producer takes a number of environment variables, described below, as configuration.
+## Configuration
+
+The consumer takes a number of environment variables, described below, as configuration.
 
 >- CONSUMER_HOST        **Required**. The host for the consumer.                                   Example: `http://mrproducer`
->- CONSUMER_HOST        **Required**. The port for the consumer.                                   Example: `8095`
->- LOG_LEVEL            Optional. The log level, which can be `Error`, `Warn`, `Info` or `Debug`.  Defaults to `Info`.
+>- CONSUMER_PORT        **Required**. The port for the consumer.                                   Example: `8095`
+>- CONSUMER_CERT_PATH   **Required**. The path to the certificate to use for https.                Defaults to `security/producer.crt`
+>- CONSUMER_KEY_PATH    **Required**. The path to the key to the certificate to use for https.     Defaults to `security/producer.key`
 >- INFO_COORD_ADDR      Optional. The address of the Information Coordinator.                      Defaults to `http://enrichmentservice:8083`.
->- SDNR_HOST            Optional. The host for SDNR.                                               Defaults to `http://localhost`.
->- SDNR_PORT            Optional. The port for SDNR.                                               Defaults to `3904`.
+>- SDNR_ADDRESS         Optional. The address for SDNR.                                            Defaults to `http://localhost:3904`.
 >- SDNR_USER            Optional. The user for the SDNR.                                           Defaults to `admin`.
 >- SDNR_PASSWORD        Optional. The password for the SDNR user.                                  Defaults to `Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U`.
 >- ORU_TO_ODU_MAP_FILE  Optional. The file containing the mapping from O-RU ID to O-DU ID.         Defaults to `o-ru-to-o-du-map.csv`.
+>- LOG_LEVEL            Optional. The log level, which can be `Error`, `Warn`, `Info` or `Debug`.  Defaults to `Info`.
+
+Any of the addresses used by this product can be configured to use https, by specifying it as the scheme of the address URI. The client will not use server certificate verification. The consumer's own callback will only listen to the scheme configured in the scheme of the consumer host address.
+
+The configured public key and cerificate shall be PEM-encoded. A self signed certificate and key are provided in the `security` folder of the project. These files should be replaced for production. To generate a self signed key and certificate, use the example code below:
+
+    openssl req -new -x509 -sha256 -key server.key -out server.crt -days 3650
 
-The creation of the job is not done when the consumer is started. Instead the consumer provides a REST API where it can be started and stopped, described below.
+T## Functionality
+
+he creation of the job is not done when the consumer is started. Instead the consumer provides a REST API where it can be started and stopped, described below.
 
 >- /start  Creates the job in ICS.
 >- /stop   Deletes the job in ICS.
 
 If the consumer is shut down with a SIGTERM, it will also delete the job before exiting.
 
+## Development
+
+To make it easy to test during development of the consumer, two stubs are provided in the `stub` folder.
+
+One, under the `producer` folder, called `producer` that stubs the producer and pushes an array with one message with `eventSeverity` alternating between `NORMAL` and `CRITICAL`. To build and start the stub, do the following:
+>1. cd stub/producer
+>2. go build
+>3. ./producer
+
+One, under the `sdnr` folder, called `sdnr` that at startup will listen for REST calls and print the body of them. By default, it listens to the port `3904`, but his can be overridden by passing a `-port [PORT]` flag when starting the stub. To build and start the stub, do the following:
+>1. cd stub/sdnr
+>2. go build
+>3. ./sdnr
+
+Mocks needed for unit tests have been generated using `github.com/stretchr/testify/mock` and are checked in under the `mocks` folder. **Note!** Keep in mind that if any of the mocked interfaces change, a new mock for that interface must be generated and checked in.
+
 ## License
 
 Copyright (C) 2021 Nordix Foundation.
index 754bba1..2eaa371 100644 (file)
@@ -9,10 +9,14 @@ require (
 
 require (
        github.com/davecgh/go-spew v1.1.1 // indirect
-       github.com/google/uuid v1.3.0 // indirect
-       github.com/gorilla/mux v1.8.0 // indirect
+       github.com/gorilla/mux v1.8.0
        github.com/pmezard/go-difflib v1.0.0 // indirect
        github.com/stretchr/objx v0.1.1 // indirect
        golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 // indirect
        gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect
 )
+
+require (
+       github.com/hashicorp/go-cleanhttp v0.5.1 // indirect
+       github.com/hashicorp/go-retryablehttp v0.7.0 // indirect
+)
index 6ce7604..970999b 100644 (file)
@@ -5,6 +5,11 @@ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
 github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
 github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
 github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
+github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM=
+github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
+github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ=
+github.com/hashicorp/go-retryablehttp v0.7.0 h1:eu1EI/mbirUgP5C8hVsTNaGZreBDlYiwC1FZWkvQPQ4=
+github.com/hashicorp/go-retryablehttp v0.7.0/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY=
 github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
 github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
index 43656b7..718f435 100644 (file)
@@ -21,6 +21,7 @@
 package config
 
 import (
+       "fmt"
        "os"
        "strconv"
 
@@ -28,31 +29,37 @@ import (
 )
 
 type Config struct {
-       LogLevel               log.Level
        ConsumerHost           string
        ConsumerPort           int
        InfoCoordinatorAddress string
-       SDNRHost               string
-       SDNRPort               int
+       SDNRAddress            string
        SDNRUser               string
        SDNPassword            string
        ORUToODUMapFile        string
+       ConsumerCertPath       string
+       ConsumerKeyPath        string
+       LogLevel               log.Level
 }
 
 func New() *Config {
        return &Config{
-               LogLevel:               getLogLevel(),
                ConsumerHost:           getEnv("CONSUMER_HOST", ""),
                ConsumerPort:           getEnvAsInt("CONSUMER_PORT", 0),
                InfoCoordinatorAddress: getEnv("INFO_COORD_ADDR", "http://enrichmentservice:8083"),
-               SDNRHost:               getEnv("SDNR_HOST", "http://localhost"),
-               SDNRPort:               getEnvAsInt("SDNR_PORT", 3904),
+               SDNRAddress:            getEnv("SDNR_ADDR", "http://localhost:3904"),
                SDNRUser:               getEnv("SDNR_USER", "admin"),
                SDNPassword:            getEnv("SDNR_PASSWORD", "Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U"),
                ORUToODUMapFile:        getEnv("ORU_TO_ODU_MAP_FILE", "o-ru-to-o-du-map.csv"),
+               ConsumerCertPath:       getEnv("CONSUMER_CERT_PATH", "security/consumer.crt"),
+               ConsumerKeyPath:        getEnv("CONSUMER_KEY_PATH", "security/consumer.key"),
+               LogLevel:               getLogLevel(),
        }
 }
 
+func (c Config) String() string {
+       return fmt.Sprintf("ConsumerHost: %v, ConsumerPort: %v, InfoCoordinatorAddress: %v, SDNRAddress: %v, SDNRUser: %v, SDNRPassword: %v, ORUToODUMapFile: %v, ConsumerCertPath: %v, ConsumerKeyPath: %v, LogLevel: %v", c.ConsumerHost, c.ConsumerPort, c.InfoCoordinatorAddress, c.SDNRAddress, c.SDNRUser, c.SDNPassword, c.ORUToODUMapFile, c.ConsumerCertPath, c.ConsumerKeyPath, c.LogLevel)
+}
+
 func getEnv(key string, defaultVal string) string {
        if value, exists := os.LookupEnv(key); exists {
                return value
index a5b1624..3d9983a 100644 (file)
@@ -31,28 +31,30 @@ import (
 
 func TestNew_envVarsSetConfigContainSetValues(t *testing.T) {
        assertions := require.New(t)
-       os.Setenv("LOG_LEVEL", "Debug")
        os.Setenv("CONSUMER_HOST", "consumerHost")
        os.Setenv("CONSUMER_PORT", "8095")
        os.Setenv("INFO_COORD_ADDR", "infoCoordAddr")
-       os.Setenv("SDNR_HOST", "sdnrHost")
-       os.Setenv("SDNR_PORT", "3908")
+       os.Setenv("SDNR_ADDR", "sdnrHost:3908")
        os.Setenv("SDNR_USER", "admin")
        os.Setenv("SDNR_PASSWORD", "pwd")
        os.Setenv("ORU_TO_ODU_MAP_FILE", "file")
+       os.Setenv("CONSUMER_CERT_PATH", "cert")
+       os.Setenv("CONSUMER_KEY_PATH", "key")
+       os.Setenv("LOG_LEVEL", "Debug")
        t.Cleanup(func() {
                os.Clearenv()
        })
        wantConfig := Config{
-               LogLevel:               log.DebugLevel,
                ConsumerHost:           "consumerHost",
                ConsumerPort:           8095,
                InfoCoordinatorAddress: "infoCoordAddr",
-               SDNRHost:               "sdnrHost",
-               SDNRPort:               3908,
+               SDNRAddress:            "sdnrHost:3908",
                SDNRUser:               "admin",
                SDNPassword:            "pwd",
                ORUToODUMapFile:        "file",
+               ConsumerCertPath:       "cert",
+               ConsumerKeyPath:        "key",
+               LogLevel:               log.DebugLevel,
        }
 
        got := New()
@@ -70,15 +72,16 @@ func TestNew_faultyIntValueSetConfigContainDefaultValueAndWarnInLog(t *testing.T
                os.Clearenv()
        })
        wantConfig := Config{
-               LogLevel:               log.InfoLevel,
                ConsumerHost:           "",
                ConsumerPort:           0,
                InfoCoordinatorAddress: "http://enrichmentservice:8083",
-               SDNRHost:               "http://localhost",
-               SDNRPort:               3904,
+               SDNRAddress:            "http://localhost:3904",
                SDNRUser:               "admin",
                SDNPassword:            "Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U",
                ORUToODUMapFile:        "o-ru-to-o-du-map.csv",
+               ConsumerCertPath:       "security/consumer.crt",
+               ConsumerKeyPath:        "security/consumer.key",
+               LogLevel:               log.InfoLevel,
        }
 
        got := New()
@@ -99,15 +102,16 @@ func TestNew_envFaultyLogLevelConfigContainDefaultValues(t *testing.T) {
                os.Clearenv()
        })
        wantConfig := Config{
-               LogLevel:               log.InfoLevel,
                ConsumerHost:           "",
                ConsumerPort:           0,
                InfoCoordinatorAddress: "http://enrichmentservice:8083",
-               SDNRHost:               "http://localhost",
-               SDNRPort:               3904,
+               SDNRAddress:            "http://localhost:3904",
                SDNRUser:               "admin",
                SDNPassword:            "Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U",
                ORUToODUMapFile:        "o-ru-to-o-du-map.csv",
+               ConsumerCertPath:       "security/consumer.crt",
+               ConsumerKeyPath:        "security/consumer.key",
+               LogLevel:               log.InfoLevel,
        }
        got := New()
        assertions.Equal(&wantConfig, got)
index 01f121a..3aecf45 100644 (file)
@@ -76,10 +76,10 @@ func (lfh LinkFailureHandler) sendUnlockMessage(oRuId string) {
                if error := restclient.Put(lfh.config.SDNRAddress+sdnrPath, unlockMessage, lfh.client, lfh.config.SDNRUser, lfh.config.SDNRPassword); error == nil {
                        log.Debugf("Sent unlock message for O-RU: %v to O-DU: %v.", oRuId, oDuId)
                } else {
-                       log.Warn(error)
+                       log.Warn("Send of unlock message failed due to ", error)
                }
        } else {
-               log.Warn(err)
+               log.Warn("Send of unlock message failed due to ", err)
        }
 
 }
index 036819a..fdd0549 100644 (file)
@@ -22,9 +22,15 @@ package restclient
 
 import (
        "bytes"
+       "crypto/tls"
        "fmt"
        "io"
+       "math"
        "net/http"
+       "net/url"
+       "time"
+
+       "github.com/hashicorp/go-retryablehttp"
 )
 
 type RequestError struct {
@@ -33,7 +39,7 @@ type RequestError struct {
 }
 
 func (e RequestError) Error() string {
-       return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", e.StatusCode, string(e.Body))
+       return fmt.Sprintf("error response with status: %v and body: %v", e.StatusCode, string(e.Body))
 }
 
 // HTTPClient interface
@@ -55,6 +61,40 @@ func Delete(url string, client HTTPClient) error {
        return do(http.MethodDelete, url, nil, client)
 }
 
+func CreateClientCertificate(certPath string, keyPath string) (tls.Certificate, error) {
+       if cert, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil {
+               return cert, nil
+       } else {
+               return tls.Certificate{}, fmt.Errorf("cannot create x509 keypair from cert file %s and key file %s due to: %v", certPath, keyPath, err)
+       }
+}
+
+func CreateRetryClient(cert tls.Certificate) *http.Client {
+       rawRetryClient := retryablehttp.NewClient()
+       rawRetryClient.RetryWaitMax = time.Minute
+       rawRetryClient.RetryMax = math.MaxInt
+       rawRetryClient.HTTPClient.Transport = getSecureTransportWithoutVerify(cert)
+
+       client := rawRetryClient.StandardClient()
+       return client
+}
+
+func IsUrlSecure(configUrl string) bool {
+       u, _ := url.Parse(configUrl)
+       return u.Scheme == "https"
+}
+
+func getSecureTransportWithoutVerify(cert tls.Certificate) *http.Transport {
+       return &http.Transport{
+               TLSClientConfig: &tls.Config{
+                       Certificates: []tls.Certificate{
+                               cert,
+                       },
+                       InsecureSkipVerify: true,
+               },
+       }
+}
+
 func do(method string, url string, body []byte, client HTTPClient, userInfo ...string) error {
        if req, reqErr := http.NewRequest(method, url, bytes.NewBuffer(body)); reqErr == nil {
                if body != nil {
index 8271fd0..2c915fd 100644 (file)
@@ -21,11 +21,16 @@ package restclient
 
 import (
        "bytes"
+       "crypto/tls"
        "fmt"
        "io/ioutil"
+       "math"
        "net/http"
+       "reflect"
        "testing"
+       "time"
 
+       "github.com/hashicorp/go-retryablehttp"
        "github.com/stretchr/testify/mock"
        "github.com/stretchr/testify/require"
        "oransc.org/usecase/oruclosedloop/mocks"
@@ -38,7 +43,7 @@ func TestRequestError_Error(t *testing.T) {
                StatusCode: http.StatusBadRequest,
                Body:       []byte("error"),
        }
-       assertions.Equal("Request failed due to error response with status: 400 and body: error", actualError.Error())
+       assertions.Equal("error response with status: 400 and body: error", actualError.Error())
 }
 
 func TestPutWithoutAuth(t *testing.T) {
@@ -167,3 +172,63 @@ func Test_doErrorCases(t *testing.T) {
                })
        }
 }
+
+func Test_createClientCertificate(t *testing.T) {
+       assertions := require.New(t)
+       wantedCert, _ := tls.LoadX509KeyPair("../../security/consumer.crt", "../../security/consumer.key")
+       type args struct {
+               certPath string
+               keyPath  string
+       }
+       tests := []struct {
+               name     string
+               args     args
+               wantCert tls.Certificate
+               wantErr  error
+       }{
+               {
+                       name: "Paths to cert info ok should return cerftificate",
+                       args: args{
+                               certPath: "../../security/consumer.crt",
+                               keyPath:  "../../security/consumer.key",
+                       },
+                       wantCert: wantedCert,
+               },
+               {
+                       name: "Paths to cert info not ok should return error with info about error",
+                       args: args{
+                               certPath: "wrong_cert",
+                               keyPath:  "wrong_key",
+                       },
+                       wantErr: fmt.Errorf("cannot create x509 keypair from cert file wrong_cert and key file wrong_key due to: open wrong_cert: no such file or directory"),
+               },
+       }
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       cert, err := CreateClientCertificate(tt.args.certPath, tt.args.keyPath)
+                       assertions.Equal(tt.wantCert, cert, tt.name)
+                       assertions.Equal(tt.wantErr, err, tt.name)
+               })
+       }
+}
+
+func Test_CreateRetryClient(t *testing.T) {
+       assertions := require.New(t)
+
+       client := CreateRetryClient(tls.Certificate{})
+
+       transport := client.Transport
+       assertions.Equal("*retryablehttp.RoundTripper", reflect.TypeOf(transport).String())
+       retryableTransport := transport.(*retryablehttp.RoundTripper)
+       retryableClient := retryableTransport.Client
+       assertions.Equal(time.Minute, retryableClient.RetryWaitMax)
+       assertions.Equal(math.MaxInt, retryableClient.RetryMax)
+}
+
+func TestIsUrlSecured(t *testing.T) {
+       assertions := require.New(t)
+
+       assertions.True(IsUrlSecure("https://url"))
+
+       assertions.False(IsUrlSecure("http://url"))
+}
index bef9e24..b7d6895 100644 (file)
 package main
 
 import (
+       "crypto/tls"
        "encoding/json"
        "fmt"
        "net/http"
        "os"
        "os/signal"
        "syscall"
-       "time"
 
        "github.com/gorilla/mux"
        log "github.com/sirupsen/logrus"
@@ -41,7 +41,6 @@ type Server interface {
        ListenAndServe() error
 }
 
-const timeoutHTTPClient = time.Second * 5
 const jobId = "14e7bb84-a44d-44c1-90b7-6995a92ad43c"
 
 var jobRegistrationInfo = struct {
@@ -70,16 +69,13 @@ func doInit() {
        configuration = config.New()
 
        log.SetLevel(configuration.LogLevel)
-
-       client = &http.Client{
-               Timeout: timeoutHTTPClient,
-       }
+       log.Debug("Using configuration: ", configuration)
 
        consumerPort = fmt.Sprint(configuration.ConsumerPort)
        jobRegistrationInfo.JobResultUri = configuration.ConsumerHost + ":" + consumerPort
 
        linkfailureConfig = linkfailure.Configuration{
-               SDNRAddress:  configuration.SDNRHost + ":" + fmt.Sprint(configuration.SDNRPort),
+               SDNRAddress:  configuration.SDNRAddress,
                SDNRUser:     configuration.SDNRUser,
                SDNRPassword: configuration.SDNPassword,
        }
@@ -95,12 +91,16 @@ func main() {
                log.Fatalf("Unable to create LookupService due to inability to get O-RU-ID to O-DU-ID map. Cause: %v", initErr)
        }
 
+       var cert tls.Certificate
+       if c, err := restclient.CreateClientCertificate(configuration.ConsumerCertPath, configuration.ConsumerKeyPath); err == nil {
+               cert = c
+       } else {
+               log.Fatalf("Stopping producer due to error: %v", err)
+       }
+       client = restclient.CreateRetryClient(cert)
+
        go func() {
-               startServer(&http.Server{
-                       Addr:    ":" + consumerPort,
-                       Handler: getRouter(),
-               })
-               deleteJob()
+               startServer()
                os.Exit(1) // If the startServer function exits, it is because there has been a failure in the server, so we exit.
        }()
 
@@ -116,6 +116,11 @@ func validateConfiguration(configuration *config.Config) error {
        if configuration.ConsumerHost == "" || configuration.ConsumerPort == 0 {
                return fmt.Errorf("consumer host and port must be provided")
        }
+
+       if configuration.ConsumerCertPath == "" || configuration.ConsumerKeyPath == "" {
+               return fmt.Errorf("missing CONSUMER_CERT and/or CONSUMER_KEY")
+       }
+
        return nil
 }
 
@@ -135,8 +140,14 @@ func getRouter() *mux.Router {
        return r
 }
 
-func startServer(server Server) {
-       if err := server.ListenAndServe(); err != nil {
+func startServer() {
+       var err error
+       if restclient.IsUrlSecure(configuration.ConsumerHost) {
+               err = http.ListenAndServeTLS(fmt.Sprintf(":%v", configuration.ConsumerPort), configuration.ConsumerCertPath, configuration.ConsumerKeyPath, getRouter())
+       } else {
+               err = http.ListenAndServe(fmt.Sprintf(":%v", configuration.ConsumerPort), getRouter())
+       }
+       if err != nil {
                log.Errorf("Server stopped unintentionally due to: %v. Deleteing job.", err)
                if deleteErr := deleteJob(); deleteErr != nil {
                        log.Error(fmt.Sprintf("Unable to delete consumer job due to: %v. Please remove job %v manually.", deleteErr, jobId))
index 99419bf..3fcb23e 100644 (file)
@@ -54,15 +54,16 @@ func Test_init(t *testing.T) {
        doInit()
 
        wantedConfiguration := &config.Config{
-               LogLevel:               log.InfoLevel,
                ConsumerHost:           "consumerHost",
                ConsumerPort:           8095,
                InfoCoordinatorAddress: "http://enrichmentservice:8083",
-               SDNRHost:               "http://localhost",
-               SDNRPort:               3904,
+               SDNRAddress:            "http://localhost:3904",
                SDNRUser:               "admin",
                SDNPassword:            "Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U",
                ORUToODUMapFile:        "o-ru-to-o-du-map.csv",
+               ConsumerCertPath:       "security/consumer.crt",
+               ConsumerKeyPath:        "security/consumer.key",
+               LogLevel:               log.InfoLevel,
        }
        assertions.Equal(wantedConfiguration, configuration)
 
@@ -70,7 +71,7 @@ func Test_init(t *testing.T) {
        assertions.Equal(wantedConfiguration.ConsumerHost+":"+fmt.Sprint(wantedConfiguration.ConsumerPort), jobRegistrationInfo.JobResultUri)
 
        wantedLinkFailureConfig := linkfailure.Configuration{
-               SDNRAddress:  wantedConfiguration.SDNRHost + ":" + fmt.Sprint(wantedConfiguration.SDNRPort),
+               SDNRAddress:  wantedConfiguration.SDNRAddress,
                SDNRUser:     wantedConfiguration.SDNRUser,
                SDNRPassword: wantedConfiguration.SDNPassword,
        }
@@ -92,8 +93,10 @@ func Test_validateConfiguration(t *testing.T) {
                        name: "Valid config, should return nil",
                        args: args{
                                configuration: &config.Config{
-                                       ConsumerHost: "host",
-                                       ConsumerPort: 80,
+                                       ConsumerHost:     "host",
+                                       ConsumerPort:     80,
+                                       ConsumerCertPath: "security/consumer.crt",
+                                       ConsumerKeyPath:  "security/consumer.key",
                                },
                        },
                },
@@ -188,28 +191,6 @@ func Test_getRouter_shouldContainAllPathsWithHandlers(t *testing.T) {
        assertions.Equal("/admin/stop", path)
 }
 
-func Test_startServer_shouldDeleteJobWhenServerStopsWithErrorAndLog(t *testing.T) {
-       assertions := require.New(t)
-
-       var buf bytes.Buffer
-       log.SetOutput(&buf)
-
-       os.Setenv("CONSUMER_PORT", "wrong")
-       t.Cleanup(func() {
-               log.SetOutput(os.Stderr)
-       })
-
-       mockServer := &mocks.Server{}
-       mockServer.On("ListenAndServe").Return(errors.New("Server failure"))
-
-       startServer(mockServer)
-
-       log := buf.String()
-       assertions.Contains(log, "level=error")
-       assertions.Contains(log, "Server stopped unintentionally due to: Server failure. Deleteing job.")
-       assertions.Contains(log, "Please remove job 14e7bb84-a44d-44c1-90b7-6995a92ad43c manually")
-}
-
 func Test_startHandler(t *testing.T) {
        assertions := require.New(t)
 
diff --git a/test/usecases/oruclosedlooprecovery/goversion/mocks/Server.go b/test/usecases/oruclosedlooprecovery/goversion/mocks/Server.go
deleted file mode 100644 (file)
index ad16503..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-// Code generated by mockery v1.0.0. DO NOT EDIT.
-
-package mocks
-
-import mock "github.com/stretchr/testify/mock"
-
-// Server is an autogenerated mock type for the Server type
-type Server struct {
-       mock.Mock
-}
-
-// ListenAndServe provides a mock function with given fields:
-func (_m *Server) ListenAndServe() error {
-       ret := _m.Called()
-
-       var r0 error
-       if rf, ok := ret.Get(0).(func() error); ok {
-               r0 = rf()
-       } else {
-               r0 = ret.Error(0)
-       }
-
-       return r0
-}
diff --git a/test/usecases/oruclosedlooprecovery/goversion/security/consumer.crt b/test/usecases/oruclosedlooprecovery/goversion/security/consumer.crt
new file mode 100644 (file)
index 0000000..0f6d8a3
--- /dev/null
@@ -0,0 +1,21 @@
+-----BEGIN CERTIFICATE-----
+MIIDXzCCAkegAwIBAgIUEbuDTP0ixwxCxCQ9tR5DijGCbtkwDQYJKoZIhvcNAQEL
+BQAwPzELMAkGA1UEBhMCc2UxDDAKBgNVBAoMA0VTVDERMA8GA1UECwwIRXJpY3Nz
+b24xDzANBgNVBAMMBnNlcnZlcjAeFw0yMTEwMTkxNDA1MzVaFw0zMTEwMTcxNDA1
+MzVaMD8xCzAJBgNVBAYTAnNlMQwwCgYDVQQKDANFU1QxETAPBgNVBAsMCEVyaWNz
+c29uMQ8wDQYDVQQDDAZzZXJ2ZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
+AoIBAQDnH4imV8kx/mXz6BDbq8e4oZGqGgv7V837iNspj/zIZXhEMP9311fdsZEE
+Y6VWU47bSYRn2xJOP+wmfKewbw0OcEWu/RkdvO7Y0VIVrlbEJYu88ZjK14dMUpfe
+72iMbTc5q2uYi0ImB5/m3jyMSXgso6NDWuvXrp2VSWjb1tG++des9rhvyrZyNrua
+I4iOnMvvuc71gvHol7appRu3+LRTQFYsAizdfHEQ9k949MZH4fiIu5NmCT/wNJVo
+uUZYYJseFhOlIANaXn6qmz7kKVYfxfV+Z5EccaRixaClCFwyRdmjgLyyeuI4/QPD
+x9PjmGmf6eOEC2ZHBi4OHwjIzmLnAgMBAAGjUzBRMB0GA1UdDgQWBBRjeDLPpLm2
+W623wna7xBCbHxtxVjAfBgNVHSMEGDAWgBRjeDLPpLm2W623wna7xBCbHxtxVjAP
+BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAbFUAWFZaIMXmd5qv/
+xJYr1oPJpsmbgWGRWZWDZqbUabvWObyXlDJWIau60BerfcC5TmyElBjTyONSGwCT
+tq+SVB0PXpgqa8ZQ25Ytn2AMDFWhrGbOefCXs6te3HGq6BNubTWrOVIvJypCwC95
++iXVuDd4eg+n2fWv7h7fZRZHum/zLoRxB2lKoMMbc/BQX9hbtP6xyvIVvaYdhcJw
+VzJJGIDqpMiMH6IBaOFSmgfOyGblGKAicj3E3kpGBfadLx3R+9V6aG7zyBnVbr2w
+YJbV2Ay4PrF+PTpCMB/mNwC5RBTYHpSNdrCMSyq3I+QPVJq8dPJr7fd1Uwl3WHqX
+FV0h
+-----END CERTIFICATE-----
diff --git a/test/usecases/oruclosedlooprecovery/goversion/security/consumer.key b/test/usecases/oruclosedlooprecovery/goversion/security/consumer.key
new file mode 100644 (file)
index 0000000..5346bb7
--- /dev/null
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDnH4imV8kx/mXz
+6BDbq8e4oZGqGgv7V837iNspj/zIZXhEMP9311fdsZEEY6VWU47bSYRn2xJOP+wm
+fKewbw0OcEWu/RkdvO7Y0VIVrlbEJYu88ZjK14dMUpfe72iMbTc5q2uYi0ImB5/m
+3jyMSXgso6NDWuvXrp2VSWjb1tG++des9rhvyrZyNruaI4iOnMvvuc71gvHol7ap
+pRu3+LRTQFYsAizdfHEQ9k949MZH4fiIu5NmCT/wNJVouUZYYJseFhOlIANaXn6q
+mz7kKVYfxfV+Z5EccaRixaClCFwyRdmjgLyyeuI4/QPDx9PjmGmf6eOEC2ZHBi4O
+HwjIzmLnAgMBAAECggEBAMq1lZyPkh8PCUyLVX3VhC4jRybyAWBI+piKx+4EI6l/
+laP5dZcegCoo+w/mdbTpRHqAWGjec4e9+Nkoq8rLG6B2SCfaRJUYiEQSEvSBHAid
+BZqKK4B82GXQavNU91Vy1OT3vD7mpPXF6jEK6gAA0C4Wt7Lzo7ZfqEavRBDMsNnV
+jOxLwWJCFSKhfeA6grJCnagmEDKSxxazlNBgCahjPf/+IRJZ7Vk4Zjq+I/5nWKf8
+lYaQExKDIANuM/jMRnYVq5k4g2MKHUADWGTSvG1DMJiMHzdxb2miZovpIkEE86bC
+wKBuele9IR6Rb/wygYj7WdaWysZ081OT7mNyju08e4ECgYEA8+q7vv4Nlz8bAcmY
+Ip5517s15M5D9iLsE2Q5m9Zs99rUyQv0E8ekpChhtTSdvj+eNl39O4hji46Gyceu
+MYPfNL7+YWaFDxuyaXEe/OFuKbFqgE1p08HXFcQJCvgqD1MWO5b9BRDc0qpNFIA8
+eN9xFBMQ2UFaALBMAup7Ef85q4kCgYEA8pKOAIsgmlnO8P9cPzkMC1oozslraAti
+1JnOJjwPLoHFubtH2u7WoIkSvNfeNwfrsVXwAP0m7C8p7qhYppS+0XGjKpYNSezK
+1GCqCVv8R1m+AsSseSUUaQCmEydd+gQbBq3r4u3wU3ylrgAoR3m+7SVyhvD+vbwI
+7+zfj+O3zu8CgYEAqaAsQH5c5Tm1hmCztB+RjD1dFWl8ScevdSzWA1HzJcrA/6+Y
+ZckI7kBG8sVMjemgFR735FbNI1hS1DBRK44Rw5SvQv0Qu5j/UeShMCt1ePkwn1k2
+p1S+Rxy1TTOXzGBzra0q+ELpzncwc3lalJSPBu7bYLrZ5HC167E1NSbQ7EECgYBo
+e/IIj+TyNz7pFcVhQixK84HiWGYYQddHJhzi4TnU2XcWonG3/uqZ6ZEVoJIJ+DJw
+h0jC1EggscwJDaBp2GY9Bwq2PD3rGsDfK+fx8ho/jYtH2/lCkVMyS2I9m9Zh68TM
+YrvZWo4LGASxZ0XyS6GOunOTZlkD1uuulMRTUU4KJwKBgQCwyjs0/ElVFvO0lPIC
+JJ//B5rqI7hNMJuTBvr4yiqVZdbgFukaU7FBVyNYDMpZi/nRbpglm+psFcwXtL8n
+bHOIGLkh8vB7OuETRYhXs567lPYtO4BmHZlXW70Sq/0xqi/Mmz1RuEg4SQ1Ug5oy
+wG6IV5EWSQAhsGirdybQ+bY7Kw==
+-----END PRIVATE KEY-----
diff --git a/test/usecases/oruclosedlooprecovery/goversion/stub/sdnr/sdnrstub.go b/test/usecases/oruclosedlooprecovery/goversion/stub/sdnr/sdnrstub.go
new file mode 100644 (file)
index 0000000..b59dbd9
--- /dev/null
@@ -0,0 +1,49 @@
+// -
+//   ========================LICENSE_START=================================
+//   O-RAN-SC
+//   %%
+//   Copyright (C) 2021: Nordix 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.
+//   ========================LICENSE_END===================================
+//
+
+package main
+
+import (
+       "flag"
+       "fmt"
+       "io"
+       "net/http"
+
+       "github.com/gorilla/mux"
+)
+
+func main() {
+       port := flag.Int("port", 3904, "The port this SDNR stub will listen on")
+       flag.Parse()
+
+       r := mux.NewRouter()
+       r.HandleFunc("/rests/data/network-topology:network-topology/topology=topology-netconf/node={O-DU-ID}/yang-ext:mount/o-ran-sc-du-hello-world:network-function/du-to-ru-connection={O-RU-ID}", handleData)
+
+       fmt.Println("Starting SDNR on port: ", *port)
+       http.ListenAndServe(fmt.Sprintf(":%v", *port), r)
+
+}
+
+func handleData(w http.ResponseWriter, req *http.Request) {
+       defer req.Body.Close()
+       if reqData, err := io.ReadAll(req.Body); err == nil {
+               fmt.Println("SDNR received body: ", string(reqData))
+       }
+}