4bf4ec630469526359adc3e256be20b9a737b2e2
[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         "crypto/tls"
25         "encoding/json"
26         "fmt"
27         "net/http"
28         "os"
29         "os/signal"
30         "syscall"
31
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"
38 )
39
40 const jobId = "14e7bb84-a44d-44c1-90b7-6995a92ad43c"
41
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"`
47 }{
48         InfoTypeID:    "STD_Fault_Messages",
49         JobResultURI:  "",
50         JobOwner:      "O-RU Closed Loop Usecase",
51         JobDefinition: "{}",
52 }
53
54 var client restclient.HTTPClient
55 var configuration *config.Config
56 var linkfailureConfig linkfailure.Configuration
57 var lookupService repository.LookupService
58 var consumerPort string
59
60 func init() {
61         doInit()
62 }
63
64 func doInit() {
65         configuration = config.New()
66
67         log.SetLevel(configuration.LogLevel)
68         log.Debug("Using configuration: ", configuration)
69
70         consumerPort = fmt.Sprint(configuration.ConsumerPort)
71         jobRegistrationInfo.JobResultURI = configuration.ConsumerHost + ":" + consumerPort
72
73         linkfailureConfig = linkfailure.Configuration{
74                 SDNRAddress:  configuration.SDNRAddress,
75                 SDNRUser:     configuration.SDNRUser,
76                 SDNRPassword: configuration.SDNPassword,
77         }
78 }
79
80 func main() {
81         if err := validateConfiguration(configuration); err != nil {
82                 log.Fatalf("Unable to start consumer due to configuration error: %v", err)
83         }
84
85         csvFileHelper := repository.NewCsvFileHelperImpl()
86         if initErr := initializeLookupService(csvFileHelper, configuration.ORUToODUMapFile); initErr != nil {
87                 log.Fatalf("Unable to create LookupService due to inability to get O-RU-ID to O-DU-ID map. Cause: %v", initErr)
88         }
89
90         var cert tls.Certificate
91         if c, err := restclient.CreateClientCertificate(configuration.ConsumerCertPath, configuration.ConsumerKeyPath); err == nil {
92                 cert = c
93         } else {
94                 log.Fatalf("Stopping producer due to error: %v", err)
95         }
96         client = restclient.CreateRetryClient(cert)
97
98         go func() {
99                 startServer()
100                 os.Exit(1) // If the startServer function exits, it is because there has been a failure in the server, so we exit.
101         }()
102
103         go func() {
104                 deleteOnShutdown(make(chan os.Signal, 1))
105                 os.Exit(0)
106         }()
107
108         keepConsumerAlive()
109 }
110
111 func validateConfiguration(configuration *config.Config) error {
112         if configuration.ConsumerHost == "" || configuration.ConsumerPort == 0 {
113                 return fmt.Errorf("consumer host and port must be provided")
114         }
115
116         if configuration.ConsumerCertPath == "" || configuration.ConsumerKeyPath == "" {
117                 return fmt.Errorf("missing CONSUMER_CERT and/or CONSUMER_KEY")
118         }
119
120         return nil
121 }
122
123 func initializeLookupService(csvFileHelper repository.CsvFileHelper, csvFile string) error {
124         lookupService = repository.NewLookupServiceImpl(csvFileHelper, csvFile)
125         return lookupService.Init()
126 }
127
128 func getRouter() *mux.Router {
129         messageHandler := linkfailure.NewLinkFailureHandler(lookupService, linkfailureConfig, client)
130
131         r := mux.NewRouter()
132         r.HandleFunc("/", messageHandler.MessagesHandler).Methods(http.MethodPost).Name("messageHandler")
133         r.HandleFunc("/admin/start", startHandler).Methods(http.MethodPost).Name("start")
134         r.HandleFunc("/admin/stop", stopHandler).Methods(http.MethodPost).Name("stop")
135
136         return r
137 }
138
139 func startServer() {
140         var err error
141         if restclient.IsUrlSecure(configuration.ConsumerHost) {
142                 err = http.ListenAndServeTLS(fmt.Sprintf(":%v", configuration.ConsumerPort), configuration.ConsumerCertPath, configuration.ConsumerKeyPath, getRouter())
143         } else {
144                 err = http.ListenAndServe(fmt.Sprintf(":%v", configuration.ConsumerPort), getRouter())
145         }
146         if err != nil {
147                 log.Errorf("Server stopped unintentionally due to: %v. Deleteing job.", err)
148                 if deleteErr := deleteJob(); deleteErr != nil {
149                         log.Errorf("Unable to delete consumer job due to: %v. Please remove job %v manually.", deleteErr, jobId)
150                 }
151         }
152 }
153
154 func keepConsumerAlive() {
155         forever := make(chan int)
156         <-forever
157 }
158
159 func startHandler(w http.ResponseWriter, r *http.Request) {
160         body, _ := json.Marshal(jobRegistrationInfo)
161         putErr := restclient.PutWithoutAuth(configuration.InfoCoordinatorAddress+"/data-consumer/v1/info-jobs/"+jobId, body, client)
162         if putErr != nil {
163                 http.Error(w, fmt.Sprintf("Unable to register consumer job due to: %v.", putErr), http.StatusBadRequest)
164                 return
165         }
166         log.Debug("Registered job.")
167 }
168
169 func stopHandler(w http.ResponseWriter, r *http.Request) {
170         deleteErr := deleteJob()
171         if deleteErr != nil {
172                 http.Error(w, fmt.Sprintf("Unable to delete consumer job due to: %v. Please remove job %v manually.", deleteErr, jobId), http.StatusBadRequest)
173                 return
174         }
175         log.Debug("Deleted job.")
176 }
177
178 func deleteOnShutdown(s chan os.Signal) {
179         signal.Notify(s, os.Interrupt)
180         signal.Notify(s, syscall.SIGTERM)
181         <-s
182         log.Info("Shutting down gracefully.")
183         if err := deleteJob(); err != nil {
184                 log.Errorf("Unable to delete job on shutdown due to: %v. Please remove job %v manually.", err, jobId)
185         }
186 }
187
188 func deleteJob() error {
189         return restclient.Delete(configuration.InfoCoordinatorAddress+"/data-consumer/v1/info-jobs/"+jobId, client)
190 }