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{
}
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")
}
}
-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()
}
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)
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)
})
}
}
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)
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 {
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) {
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))
}
--- /dev/null
+# ============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
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
- 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
- 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
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
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
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:
- 8083:8083
- 8434:8434
consumer:
- image: eexit/mirror-http-server
+ image: "${CONSUMER_IMAGE_BASE}:${CONSUMER_IMAGE_TAG}"
container_name: consumer
networks:
- default
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:
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:
.history
oruclosedloop
-simulator
+producer
+sdnr
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.
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
+)
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=
package config
import (
+ "fmt"
"os"
"strconv"
)
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
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()
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()
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)
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)
}
}
import (
"bytes"
+ "crypto/tls"
"fmt"
"io"
+ "math"
"net/http"
+ "net/url"
+ "time"
+
+ "github.com/hashicorp/go-retryablehttp"
)
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
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 {
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"
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) {
})
}
}
+
+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"))
+}
package main
import (
+ "crypto/tls"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
- "time"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
ListenAndServe() error
}
-const timeoutHTTPClient = time.Second * 5
const jobId = "14e7bb84-a44d-44c1-90b7-6995a92ad43c"
var jobRegistrationInfo = struct {
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,
}
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.
}()
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
}
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))
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)
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,
}
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",
},
},
},
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)
+++ /dev/null
-// 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
-}
--- /dev/null
+-----BEGIN CERTIFICATE-----
+MIIDXzCCAkegAwIBAgIUEbuDTP0ixwxCxCQ9tR5DijGCbtkwDQYJKoZIhvcNAQEL
+BQAwPzELMAkGA1UEBhMCc2UxDDAKBgNVBAoMA0VTVDERMA8GA1UECwwIRXJpY3Nz
+b24xDzANBgNVBAMMBnNlcnZlcjAeFw0yMTEwMTkxNDA1MzVaFw0zMTEwMTcxNDA1
+MzVaMD8xCzAJBgNVBAYTAnNlMQwwCgYDVQQKDANFU1QxETAPBgNVBAsMCEVyaWNz
+c29uMQ8wDQYDVQQDDAZzZXJ2ZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
+AoIBAQDnH4imV8kx/mXz6BDbq8e4oZGqGgv7V837iNspj/zIZXhEMP9311fdsZEE
+Y6VWU47bSYRn2xJOP+wmfKewbw0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QixK84HiWGYYQddHJhzi4TnU2XcWonG3/uqZ6ZEVoJIJ+DJw
+h0jC1EggscwJDaBp2GY9Bwq2PD3rGsDfK+fx8ho/jYtH2/lCkVMyS2I9m9Zh68TM
+YrvZWo4LGASxZ0XyS6GOunOTZlkD1uuulMRTUU4KJwKBgQCwyjs0/ElVFvO0lPIC
+JJ//B5rqI7hNMJuTBvr4yiqVZdbgFukaU7FBVyNYDMpZi/nRbpglm+psFcwXtL8n
+bHOIGLkh8vB7OuETRYhXs567lPYtO4BmHZlXW70Sq/0xqi/Mmz1RuEg4SQ1Ug5oy
+wG6IV5EWSQAhsGirdybQ+bY7Kw==
+-----END PRIVATE KEY-----
--- /dev/null
+// -
+// ========================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))
+ }
+}