Merge "Sample consumer to get kafka broker from ICS"
[nonrtric.git] / service-exposure / rapps-rapp-helloworld-invoker1.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: 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 package main
21
22 import (
23         "bytes"
24         "flag"
25         "fmt"
26         "github.com/prometheus/client_golang/prometheus"
27         "github.com/prometheus/client_golang/prometheus/promhttp"
28         "io/ioutil"
29         "net/http"
30         "strings"
31         "time"
32 )
33
34
35 var gatewayHost string
36 var gatewayPort string
37 var securityEnabled string
38 var useGateway string
39 var rapp string
40 var methods string
41 var healthy bool = true
42 var ttime time.Time
43
44 const (
45         namespace             = "istio-nonrtric"
46         scope                 = "email"
47         client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
48 )
49
50 var (
51         reqDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
52                 Name:    "rapp_http_request_duration_seconds",
53                 Help:    "Duration of the last request call.",
54                 Buckets: []float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
55         }, []string{"app", "func", "handler", "method", "code"})
56         reqBytes = prometheus.NewSummaryVec(prometheus.SummaryOpts{
57                 Name: "rapp_bytes_summary",
58                 Help: "Summary of bytes transferred over http",
59         }, []string{"app", "func", "handler", "method", "code"})
60 )
61
62
63 func MakeRequest(client *http.Client, prefix string, method string, ch chan string) {
64         var service = strings.Split(prefix, "/")[1]
65         var gatewayUrl = "http://" + gatewayHost + ":" + gatewayPort
66         var jsonValue []byte = []byte{}
67         var restUrl string = ""
68
69         if securityEnabled != "true" {
70                 gatewayUrl = "http://" + service + "." + namespace + ":80"
71                 prefix = ""
72         }
73
74         restUrl = gatewayUrl + prefix
75         resp := &http.Response{}
76
77         timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
78                 reqDuration.WithLabelValues("rapp-helloworld-invoker1", "MakeRequest", resp.Request.URL.Path, resp.Request.Method,
79                         resp.Status).Observe(v)
80         }))
81         defer timer.ObserveDuration()
82         fmt.Printf("Making get request to %s\n", restUrl)
83         req, err := http.NewRequest(method, restUrl, bytes.NewBuffer(jsonValue))
84         if err != nil {
85                 fmt.Printf("Got error %s", err.Error())
86         }
87         req.Header.Set("Content-type", "application/json")
88
89         resp, err = client.Do(req)
90         if err != nil {
91                 fmt.Printf("Got error %s", err.Error())
92         }
93
94         defer resp.Body.Close()
95         body, _ := ioutil.ReadAll(resp.Body)
96         reqBytes.WithLabelValues("rapp-helloworld-invoker1", "MakeRequest", req.URL.Path, req.Method,
97                 resp.Status).Observe(float64(resp.ContentLength))
98
99         respString := string(body[:])
100         if respString == "RBAC: access denied" {
101                 respString += " for " + service + " " + strings.ToLower(method) + " request"
102         }
103         fmt.Printf("Received response for %s %s request - %s\n", service, strings.ToLower(method), respString)
104         ch <- prefix + "," + method
105 }
106
107 func health(res http.ResponseWriter, req *http.Request) {
108         if healthy {
109                 res.WriteHeader(http.StatusOK)
110                 res.Write([]byte("healthy"))
111         } else {
112                 res.WriteHeader(http.StatusInternalServerError)
113                 res.Write([]byte("unhealthy"))
114         }
115 }
116
117 func main() {
118         ttime = time.Now()
119         time.Sleep(3 * time.Second)
120         prometheus.Register(reqDuration)
121         prometheus.Register(reqBytes)
122
123         flag.StringVar(&gatewayHost, "gatewayHost", "istio-ingressgateway.istio-system", "Gateway Host")
124         flag.StringVar(&gatewayPort, "gatewayPort", "80", "Gateway Port")
125         flag.StringVar(&useGateway, "useGateway", "Y", "Connect to services through API gateway")
126         flag.StringVar(&securityEnabled, "securityEnabled", "true", "Security is required to use this application")
127         flag.StringVar(&rapp, "rapp", "rapp-helloworld-provider", "Name of rapp to invoke")
128         flag.StringVar(&methods, "methods", "GET", "Methods to access application")
129         flag.Parse()
130
131         healthHandler := http.HandlerFunc(health)
132         http.Handle("/health", healthHandler)
133         http.Handle("/metrics", promhttp.Handler())
134         go func() {
135                 http.ListenAndServe(":9000", nil)
136         }()
137
138         ioutil.WriteFile("init.txt", []byte("Initialization done."), 0644)
139
140         client := &http.Client{
141                 Timeout: time.Second * 10,
142         }
143
144         ch := make(chan string)
145         var prefixArray []string = []string{"/" + rapp}
146         var methodArray []string = []string{methods}
147         for _, prefix := range prefixArray {
148                 for _, method := range methodArray {
149                         go MakeRequest(client, prefix, method, ch)
150                 }
151         }
152
153
154         for r := range ch {
155                 go func(resp string) {
156                         time.Sleep(10 * time.Second)
157                         elements := strings.Split(resp, ",")
158                         prefix := elements[0]
159                         method := elements[1]
160                         MakeRequest(client, prefix, method, ch)
161                 }(r)
162         }
163 }