Merge "Uplift of PMS source from ONAP"
[nonrtric.git] / test / usecases / oruclosedlooprecovery / goversion / main.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2021: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package main
22
23 import (
24         "encoding/json"
25         "fmt"
26         "net/http"
27         "time"
28
29         "github.com/gorilla/mux"
30         log "github.com/sirupsen/logrus"
31         "oransc.org/usecase/oruclosedloop/internal/config"
32         "oransc.org/usecase/oruclosedloop/internal/linkfailure"
33         "oransc.org/usecase/oruclosedloop/internal/repository"
34         "oransc.org/usecase/oruclosedloop/internal/restclient"
35 )
36
37 const timeoutHTTPClient = time.Second * 5
38 const jobId = "14e7bb84-a44d-44c1-90b7-6995a92ad43c"
39
40 var infoCoordAddress string
41 var linkfailureConfig linkfailure.Configuration
42 var lookupService repository.LookupService
43 var host string
44 var port string
45 var client restclient.HTTPClient
46
47 func init() {
48         configuration := config.New()
49
50         client = &http.Client{
51                 Timeout: timeoutHTTPClient,
52         }
53
54         log.SetLevel(configuration.LogLevel)
55
56         if err := validateConfiguration(configuration); err != nil {
57                 log.Fatalf("Unable to start consumer due to: %v", err)
58         }
59         host = configuration.ConsumerHost
60         port = fmt.Sprint(configuration.ConsumerPort)
61
62         csvFileHelper := repository.NewCsvFileHelperImpl()
63         if initErr := initializeLookupService(csvFileHelper, configuration); initErr != nil {
64                 log.Fatalf("Unable to create LookupService due to inability to get O-RU-ID to O-DU-ID map. Cause: %v", initErr)
65         }
66
67         infoCoordAddress = configuration.InfoCoordinatorAddress
68
69         linkfailureConfig = linkfailure.Configuration{
70                 SDNRAddress:  configuration.SDNRHost + ":" + fmt.Sprint(configuration.SDNRPort),
71                 SDNRUser:     configuration.SDNRUser,
72                 SDNRPassword: configuration.SDNPassword,
73         }
74 }
75
76 func validateConfiguration(configuration *config.Config) error {
77         if configuration.ConsumerHost == "" || configuration.ConsumerPort == 0 {
78                 return fmt.Errorf("consumer host and port must be provided")
79         }
80         return nil
81 }
82
83 func initializeLookupService(csvFileHelper repository.CsvFileHelper, configuration *config.Config) error {
84         lookupService = repository.NewLookupServiceImpl(csvFileHelper, configuration.ORUToODUMapFile)
85         if initErr := lookupService.Init(); initErr != nil {
86                 return initErr
87         }
88         return nil
89 }
90
91 func main() {
92         defer deleteJob()
93         messageHandler := linkfailure.NewLinkFailureHandler(lookupService, linkfailureConfig, client)
94         r := mux.NewRouter()
95         r.HandleFunc("/", messageHandler.MessagesHandler).Methods(http.MethodPost)
96         r.HandleFunc("/admin/start", startHandler).Methods(http.MethodPost)
97         r.HandleFunc("/admin/stop", stopHandler).Methods(http.MethodPost)
98         log.Error(http.ListenAndServe(":"+port, r))
99 }
100
101 func startHandler(w http.ResponseWriter, r *http.Request) {
102         jobRegistrationInfo := struct {
103                 InfoTypeId    string      `json:"info_type_id"`
104                 JobResultUri  string      `json:"job_result_uri"`
105                 JobOwner      string      `json:"job_owner"`
106                 JobDefinition interface{} `json:"job_definition"`
107         }{
108                 InfoTypeId:    "STD_Fault_Messages",
109                 JobResultUri:  host + ":" + port,
110                 JobOwner:      "O-RU Closed Loop Usecase",
111                 JobDefinition: "{}",
112         }
113         body, _ := json.Marshal(jobRegistrationInfo)
114         putErr := restclient.PutWithoutAuth(infoCoordAddress+"/data-consumer/v1/info-jobs/"+jobId, body, client)
115         if putErr != nil {
116                 http.Error(w, fmt.Sprintf("Unable to register consumer job: %v", putErr), http.StatusBadRequest)
117                 return
118         }
119         log.Debug("Registered job.")
120 }
121
122 func stopHandler(w http.ResponseWriter, r *http.Request) {
123         deleteErr := deleteJob()
124         if deleteErr != nil {
125                 http.Error(w, fmt.Sprintf("Unable to delete consumer job: %v", deleteErr), http.StatusBadRequest)
126                 return
127         }
128         log.Debug("Deleted job.")
129 }
130
131 func deleteJob() error {
132         return restclient.Delete(infoCoordAddress+"/data-consumer/v1/info-jobs/"+jobId, client)
133 }