Implement secure communications
[nonrtric.git] / dmaap-mediator-producer / 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         "fmt"
26         "net/http"
27         "time"
28
29         "github.com/hashicorp/go-retryablehttp"
30         log "github.com/sirupsen/logrus"
31         "oransc.org/nonrtric/dmaapmediatorproducer/internal/config"
32         "oransc.org/nonrtric/dmaapmediatorproducer/internal/jobs"
33         "oransc.org/nonrtric/dmaapmediatorproducer/internal/restclient"
34         "oransc.org/nonrtric/dmaapmediatorproducer/internal/server"
35 )
36
37 var configuration *config.Config
38
39 func init() {
40         configuration = config.New()
41 }
42
43 func main() {
44         log.SetLevel(configuration.LogLevel)
45         log.Debug("Initializing DMaaP Mediator Producer")
46         if err := validateConfiguration(configuration); err != nil {
47                 log.Fatalf("Stopping producer due to error: %v", err)
48         }
49         callbackAddress := fmt.Sprintf("%v:%v", configuration.InfoProducerHost, configuration.InfoProducerPort)
50
51         var retryClient restclient.HTTPClient
52         if cert, err := createClientCertificate(); err == nil {
53                 retryClient = createRetryClient(cert)
54         } else {
55                 log.Fatalf("Stopping producer due to error: %v", err)
56         }
57
58         jobHandler := jobs.NewJobHandlerImpl("configs/type_config.json", retryClient, &http.Client{
59                 Timeout: time.Second * 5,
60         })
61         if err := registerTypesAndProducer(jobHandler, configuration.InfoCoordinatorAddress, callbackAddress, retryClient); err != nil {
62                 log.Fatalf("Stopping producer due to: %v", err)
63         }
64
65         log.Debug("Starting DMaaP Mediator Producer")
66         go func() {
67                 log.Debugf("Starting callback server at port %v", configuration.InfoProducerPort)
68                 r := server.NewRouter(jobHandler)
69                 log.Fatalf("Server stopped: %v", http.ListenAndServeTLS(fmt.Sprintf(":%v", configuration.InfoProducerPort), configuration.ProducerCertPath, configuration.ProducerKeyPath, r))
70         }()
71
72         go jobHandler.RunJobs(configuration.DMaaPMRAddress)
73
74         keepProducerAlive()
75 }
76
77 func validateConfiguration(configuration *config.Config) error {
78         if configuration.InfoProducerHost == "" {
79                 return fmt.Errorf("missing INFO_PRODUCER_HOST")
80         }
81         if configuration.ProducerCertPath == "" || configuration.ProducerKeyPath == "" {
82                 return fmt.Errorf("missing PRODUCER_CERT and/or PRODUCER_KEY")
83         }
84         return nil
85 }
86
87 func createClientCertificate() (*tls.Certificate, error) {
88         if cert, err := tls.LoadX509KeyPair(configuration.ProducerCertPath, configuration.ProducerKeyPath); err == nil {
89                 return &cert, nil
90         } else {
91                 return nil, fmt.Errorf("cannot create x509 keypair from cert file %s and key file %s", configuration.ProducerCertPath, configuration.ProducerKeyPath)
92         }
93 }
94
95 func createRetryClient(cert *tls.Certificate) *http.Client {
96         rawRetryClient := retryablehttp.NewClient()
97         rawRetryClient.RetryWaitMax = time.Minute
98         rawRetryClient.RetryMax = int(^uint(0) >> 1)
99         rawRetryClient.HTTPClient.Transport = &http.Transport{
100                 TLSClientConfig: &tls.Config{
101                         Certificates: []tls.Certificate{
102                                 *cert,
103                         },
104                         InsecureSkipVerify: true,
105                 },
106         }
107
108         return rawRetryClient.StandardClient()
109 }
110
111 func registerTypesAndProducer(jobHandler jobs.JobTypeHandler, infoCoordinatorAddress string, callbackAddress string, client restclient.HTTPClient) error {
112         registrator := config.NewRegistratorImpl(infoCoordinatorAddress, client)
113         if types, err := jobHandler.GetTypes(); err == nil {
114                 if regErr := registrator.RegisterTypes(types); regErr != nil {
115                         return fmt.Errorf("unable to register all types due to: %v", regErr)
116                 }
117         } else {
118                 return fmt.Errorf("unable to get types to register due to: %v", err)
119         }
120         producer := config.ProducerRegistrationInfo{
121                 InfoProducerSupervisionCallbackUrl: callbackAddress + server.StatusPath,
122                 SupportedInfoTypes:                 jobHandler.GetSupportedTypes(),
123                 InfoJobCallbackUrl:                 callbackAddress + server.AddJobPath,
124         }
125         if err := registrator.RegisterProducer("DMaaP_Mediator_Producer", &producer); err != nil {
126                 return fmt.Errorf("unable to register producer due to: %v", err)
127         }
128         return nil
129 }
130
131 func keepProducerAlive() {
132         forever := make(chan int)
133         <-forever
134 }