9a827e7ae69d02a38f5539be5e3c034e8e478b7b
[nonrtric.git] / dmaap-mediator-producer / internal / restclient / HTTPClient.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 restclient
22
23 import (
24         "bytes"
25         "crypto/tls"
26         "fmt"
27         "io"
28         "math"
29         "net/http"
30         "net/url"
31         "time"
32
33         "github.com/hashicorp/go-retryablehttp"
34         log "github.com/sirupsen/logrus"
35 )
36
37 // HTTPClient interface
38 type HTTPClient interface {
39         Get(url string) (*http.Response, error)
40
41         Do(*http.Request) (*http.Response, error)
42 }
43
44 type RequestError struct {
45         StatusCode int
46         Body       []byte
47 }
48
49 func (pe RequestError) Error() string {
50         return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", pe.StatusCode, string(pe.Body))
51 }
52
53 func Get(url string, client HTTPClient) ([]byte, error) {
54         if response, err := client.Get(url); err == nil {
55                 if isResponseSuccess(response.StatusCode) {
56                         defer response.Body.Close()
57                         if responseData, err := io.ReadAll(response.Body); err == nil {
58                                 return responseData, nil
59                         } else {
60                                 return nil, err
61                         }
62                 } else {
63                         return nil, getRequestError(response)
64                 }
65         } else {
66                 return nil, err
67         }
68 }
69
70 func Put(url string, body []byte, client HTTPClient) error {
71         return do(http.MethodPut, url, body, client)
72 }
73
74 func Post(url string, body []byte, client HTTPClient) error {
75         return do(http.MethodPost, url, body, client)
76 }
77
78 func do(method string, url string, body []byte, client HTTPClient) error {
79         if req, reqErr := http.NewRequest(method, url, bytes.NewBuffer(body)); reqErr == nil {
80                 req.Header.Set("Content-Type", "application/json")
81                 if response, respErr := client.Do(req); respErr == nil {
82                         if isResponseSuccess(response.StatusCode) {
83                                 return nil
84                         } else {
85                                 return getRequestError(response)
86                         }
87                 } else {
88                         return respErr
89                 }
90         } else {
91                 return reqErr
92         }
93 }
94
95 func isResponseSuccess(statusCode int) bool {
96         return statusCode >= http.StatusOK && statusCode <= 299
97 }
98
99 func getRequestError(response *http.Response) RequestError {
100         defer response.Body.Close()
101         responseData, _ := io.ReadAll(response.Body)
102         putError := RequestError{
103                 StatusCode: response.StatusCode,
104                 Body:       responseData,
105         }
106         return putError
107 }
108
109 func CreateClientCertificate(certPath string, keyPath string) (tls.Certificate, error) {
110         if cert, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil {
111                 return cert, nil
112         } else {
113                 return tls.Certificate{}, fmt.Errorf("cannot create x509 keypair from cert file %s and key file %s due to: %v", certPath, keyPath, err)
114         }
115 }
116
117 func CreateRetryClient(cert tls.Certificate) *http.Client {
118         rawRetryClient := retryablehttp.NewClient()
119         rawRetryClient.Logger = leveledLogger{}
120         rawRetryClient.RetryWaitMax = time.Minute
121         rawRetryClient.RetryMax = math.MaxInt
122         rawRetryClient.HTTPClient.Transport = getSecureTransportWithoutVerify(cert)
123
124         client := rawRetryClient.StandardClient()
125         return client
126 }
127
128 func CreateClientWithoutRetry(cert tls.Certificate, timeout time.Duration) *http.Client {
129         return &http.Client{
130                 Timeout:   timeout,
131                 Transport: getSecureTransportWithoutVerify(cert),
132         }
133 }
134
135 func getSecureTransportWithoutVerify(cert tls.Certificate) *http.Transport {
136         return &http.Transport{
137                 TLSClientConfig: &tls.Config{
138                         Certificates: []tls.Certificate{
139                                 cert,
140                         },
141                         InsecureSkipVerify: true,
142                 },
143         }
144 }
145
146 func IsUrlSecure(configUrl string) bool {
147         u, _ := url.Parse(configUrl)
148         return u.Scheme == "https"
149 }
150
151 // Used to get leveled logging in the RetryClient
152 type leveledLogger struct {
153 }
154
155 func (ll leveledLogger) Error(msg string, keysAndValues ...interface{}) {
156         log.WithFields(getFields(keysAndValues)).Error(msg)
157 }
158 func (ll leveledLogger) Info(msg string, keysAndValues ...interface{}) {
159         log.WithFields(getFields(keysAndValues)).Info(msg)
160 }
161 func (ll leveledLogger) Debug(msg string, keysAndValues ...interface{}) {
162         log.WithFields(getFields(keysAndValues)).Debug(msg)
163 }
164 func (ll leveledLogger) Warn(msg string, keysAndValues ...interface{}) {
165         log.WithFields(getFields(keysAndValues)).Warn(msg)
166 }
167
168 func getFields(keysAndValues []interface{}) log.Fields {
169         fields := log.Fields{}
170         for i := 0; i < len(keysAndValues); i = i + 2 {
171                 fields[fmt.Sprint(keysAndValues[i])] = keysAndValues[i+1]
172         }
173         return fields
174 }