2 // ========================LICENSE_START=================================
5 // Copyright (C) 2021: Nordix Foundation
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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===================================
32 "github.com/gorilla/mux"
33 log "github.com/sirupsen/logrus"
34 "oransc.org/usecase/oruclosedloop/internal/config"
35 "oransc.org/usecase/oruclosedloop/internal/linkfailure"
36 "oransc.org/usecase/oruclosedloop/internal/repository"
37 "oransc.org/usecase/oruclosedloop/internal/restclient"
40 const jobId = "14e7bb84-a44d-44c1-90b7-6995a92ad43c"
42 var jobRegistrationInfo = struct {
43 InfoTypeID string `json:"info_type_id"`
44 JobResultURI string `json:"job_result_uri"`
45 JobOwner string `json:"job_owner"`
46 JobDefinition interface{} `json:"job_definition"`
48 InfoTypeID: "STD_Fault_Messages",
50 JobOwner: "O-RU Closed Loop Usecase",
54 var client restclient.HTTPClient
55 var configuration *config.Config
56 var linkfailureConfig linkfailure.Configuration
57 var lookupService repository.LookupService
58 var consumerPort string
66 configuration = config.New()
68 log.SetLevel(configuration.LogLevel)
69 log.Debug("Using configuration: ", configuration)
71 consumerPort = fmt.Sprint(configuration.ConsumerPort)
72 jobRegistrationInfo.JobResultURI = configuration.ConsumerHost + ":" + consumerPort
74 linkfailureConfig = linkfailure.Configuration{
75 SDNRAddress: configuration.SDNRAddress,
76 SDNRUser: configuration.SDNRUser,
77 SDNRPassword: configuration.SDNPassword,
82 if err := validateConfiguration(configuration); err != nil {
83 log.Fatalf("Unable to start consumer due to configuration error: %v", err)
86 csvFileHelper := repository.NewCsvFileHelperImpl()
87 if initErr := initializeLookupService(csvFileHelper, configuration.ORUToODUMapFile); initErr != nil {
88 log.Fatalf("Unable to create LookupService due to inability to get O-RU-ID to O-DU-ID map. Cause: %v", initErr)
91 var cert tls.Certificate
92 if c, err := restclient.CreateClientCertificate(configuration.ConsumerCertPath, configuration.ConsumerKeyPath); err == nil {
95 log.Fatalf("Stopping producer due to error: %v", err)
97 client = restclient.CreateRetryClient(cert)
101 os.Exit(1) // If the startServer function exits, it is because there has been a failure in the server, so we exit.
105 deleteOnShutdown(make(chan os.Signal, 1))
112 func validateConfiguration(configuration *config.Config) error {
113 if configuration.ConsumerHost == "" || configuration.ConsumerPort == 0 {
114 return fmt.Errorf("consumer host and port must be provided")
117 if configuration.ConsumerCertPath == "" || configuration.ConsumerKeyPath == "" {
118 return fmt.Errorf("missing CONSUMER_CERT and/or CONSUMER_KEY")
124 func initializeLookupService(csvFileHelper repository.CsvFileHelper, csvFile string) error {
125 lookupService = repository.NewLookupServiceImpl(csvFileHelper, csvFile)
126 return lookupService.Init()
129 func getRouter() *mux.Router {
130 messageHandler := linkfailure.NewLinkFailureHandler(lookupService, linkfailureConfig, client)
133 r.HandleFunc("/", messageHandler.MessagesHandler).Methods(http.MethodPost).Name("messageHandler")
134 r.HandleFunc("/status", statusHandler).Methods(http.MethodGet).Name("status")
135 r.HandleFunc("/admin/start", startHandler).Methods(http.MethodPost).Name("start")
136 r.HandleFunc("/admin/stop", stopHandler).Methods(http.MethodPost).Name("stop")
143 if restclient.IsUrlSecure(configuration.ConsumerHost) {
144 err = http.ListenAndServeTLS(fmt.Sprintf(":%v", configuration.ConsumerPort), configuration.ConsumerCertPath, configuration.ConsumerKeyPath, getRouter())
146 err = http.ListenAndServe(fmt.Sprintf(":%v", configuration.ConsumerPort), getRouter())
149 log.Errorf("Server stopped unintentionally due to: %v. Deleteing job.", err)
150 if deleteErr := deleteJob(); deleteErr != nil {
151 log.Errorf("Unable to delete consumer job due to: %v. Please remove job %v manually.", deleteErr, jobId)
156 func keepConsumerAlive() {
157 forever := make(chan int)
161 func startHandler(w http.ResponseWriter, r *http.Request) {
162 body, _ := json.Marshal(jobRegistrationInfo)
163 putErr := restclient.PutWithoutAuth(configuration.InfoCoordinatorAddress+"/data-consumer/v1/info-jobs/"+jobId, body, client)
165 http.Error(w, fmt.Sprintf("Unable to register consumer job due to: %v.", putErr), http.StatusBadRequest)
168 log.Debug("Registered job.")
172 func stopHandler(w http.ResponseWriter, r *http.Request) {
173 deleteErr := deleteJob()
174 if deleteErr != nil {
175 http.Error(w, fmt.Sprintf("Unable to delete consumer job due to: %v. Please remove job %v manually.", deleteErr, jobId), http.StatusBadRequest)
178 log.Debug("Deleted job.")
182 func statusHandler(w http.ResponseWriter, r *http.Request) {
183 runStatus := "started"
185 runStatus = "stopped"
187 fmt.Fprintf(w, `{"status": "%v"}`, runStatus)
190 func deleteOnShutdown(s chan os.Signal) {
191 signal.Notify(s, os.Interrupt)
192 signal.Notify(s, syscall.SIGTERM)
194 log.Info("Shutting down gracefully.")
195 if err := deleteJob(); err != nil {
196 log.Errorf("Unable to delete job on shutdown due to: %v. Please remove job %v manually.", err, jobId)
200 func deleteJob() error {
201 return restclient.Delete(configuration.InfoCoordinatorAddress+"/data-consumer/v1/info-jobs/"+jobId, client)