1 // ============LICENSE_START===============================================
2 // Copyright (C) 2023 Nordix Foundation. All rights reserved.
3 // ========================================================================
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
8 // http://www.apache.org/licenses/LICENSE-2.0
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 // ============LICENSE_END=================================================
38 "github.com/confluentinc/confluent-kafka-go/kafka"
39 "github.com/gorilla/mux"
40 jsoniter "github.com/json-iterator/go"
41 log "github.com/sirupsen/logrus"
42 "golang.org/x/oauth2/clientcredentials"
45 type JobDefinition struct {
46 InfoTypeID string `json:"info_type_id"`
47 JobOwner string `json:"job_owner"`
48 JobResultURI string `json:"job_result_uri"`
49 JobDefinition struct {
50 KafkaOutputTopic string `json:"kafkaOutputTopic"`
51 FilterType string `json:"filterType"`
52 Filter json.RawMessage `json:"filter"`
54 Topic string `json:"topic"`
55 BootStrapServers string `json:"bootStrapServers"`
56 } `json:"deliveryInfo"`
57 } `json:"job_definition"`
60 const jobdef = "/config/jobDefinition.json"
62 var rapp_id = os.Getenv("APPID")
64 var rapp_ns = os.Getenv("APPNS")
66 var bootstrapserver = os.Getenv("KAFKA_SERVER")
68 var topic = os.Getenv("TOPIC")
70 var ics_server = os.Getenv("ICS")
72 var jwt_file = os.Getenv("JWT_FILE")
74 var ssl_path = os.Getenv("SSLPATH")
76 var gzipped_data = os.Getenv("GZIP")
78 var log_payload = os.Getenv("LOG_PAYLOAD")
80 // These are optional - if rapp is fethcing the token instead of the side car
81 var creds_grant_type = os.Getenv("CREDS_GRANT_TYPE")
82 var creds_client_secret = os.Getenv("CREDS_CLIENT_SECRET")
83 var creds_client_id = os.Getenv("CREDS_CLIENT_ID")
84 var creds_service_url = os.Getenv("AUTH_SERVICE_URL")
90 var msg_corrupted_count int = 0
92 var jobid = "<not-set>"
93 var consumer_type = "<not-set>"
97 var appStatus = "INIT"
99 var msg_per_sec int = 0
101 var httpclient = &http.Client{}
106 log.SetLevel(log.InfoLevel)
107 log.SetLevel(log.DebugLevel)
109 log.Info("Server starting...")
111 if creds_service_url != "" {
112 log.Warn("Disabling jwt retrieval from side car")
117 log.Error("Env APPID not set")
122 log.Error("Env APPNS not set")
126 if bootstrapserver == "" {
127 log.Error("Env KAFKA_SERVER not set")
132 log.Error("Env TOPIC not set")
136 if ics_server == "" {
137 log.Error("Env ICS not set")
141 rtr := mux.NewRouter()
142 rtr.HandleFunc("/statistics", statistics)
143 rtr.HandleFunc("/status", status)
144 rtr.HandleFunc("/logging/{level}", logging_level)
145 rtr.HandleFunc("/logging", logging_level)
146 rtr.HandleFunc("/", alive)
148 //For perf/mem profiling
149 rtr.HandleFunc("/custom_debug_path/profile", pprof.Profile)
151 http.Handle("/", rtr)
153 fileBytes, err := os.ReadFile(jobdef)
155 log.Error("Cannot read job defintion file: ", jobdef, err)
158 fmt.Println("FROM FILE")
159 fmt.Println(string(fileBytes))
161 job_json := JobDefinition{}
162 err = jsoniter.Unmarshal([]byte(fileBytes), &job_json)
164 log.Error("Cannot parse job defintion file: ", jobdef, err)
167 job_type := job_json.InfoTypeID
168 job_json.JobDefinition.KafkaOutputTopic = topic
169 job_json.JobDefinition.DeliveryInfo.Topic = topic
170 job_json.JobDefinition.DeliveryInfo.BootStrapServers = bootstrapserver
172 gid = "pm-rapp-" + job_type + "-" + rapp_id
174 jobid = "rapp-job-" + job_type + "-" + rapp_id
176 json_bytes, err := json.Marshal(job_json)
178 log.Error("Cannot marshal job json", err)
182 json_str := string(json_bytes)
184 if strings.HasPrefix(bootstrapserver, "http://") {
185 if creds_service_url != "" {
186 consumer_type = "accesstoken strimzi bridge consumer"
187 retrive_token_strimzi()
190 go read_kafka_messages()
194 if ics_server != "" {
196 log.Debug("Registring job: ", jobid, " json: ", json_str)
197 ok, _ = send_http_request([]byte(json_str), http.MethodPut, "http://"+ics_server+"/data-consumer/v1/info-jobs/"+jobid, "", currentToken, 0, false)
199 log.Info("Failed to register job: ", jobid, " - retrying")
200 time.Sleep(time.Second)
204 log.Info("No job registered - read from topic only")
206 if strings.HasPrefix(bootstrapserver, "http://") {
207 go read_bridge_messages()
213 http_server := &http.Server{Addr: ":" + http_port, Handler: nil}
215 sigs := make(chan os.Signal, 1)
216 signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
218 fmt.Println("Setting handler for signal sigint and sigterm")
220 appStatus = "TERMINATING"
221 fmt.Printf("Received signal %s - application will terminate\n", sig)
223 if strings.HasPrefix(bootstrapserver, "http://") {
224 log.Debug("stopping strimzi consumer for job: ", jobid)
225 ok, _ = send_http_request(nil, http.MethodDelete, bootstrapserver+"/consumers/"+gid+"/instances/"+cid, "", currentToken, 0, false)
227 log.Info("Failed to delete consumer "+cid+" in group: ", gid, " - retrying")
232 if ics_server != "" {
234 log.Debug("stopping job: ", jobid, " json: ", json_str)
235 ok, _ = send_http_request(nil, http.MethodDelete, "http://"+ics_server+"/data-consumer/v1/info-jobs/"+jobid, "", currentToken, 0, false)
237 log.Info("Failed to stop job: ", jobid, " - retrying")
238 time.Sleep(time.Second)
242 http_server.Shutdown(context.Background())
244 appStatus = "RUNNING"
245 log.Info("Starting http service...")
246 err = http_server.ListenAndServe()
247 if err == http.ErrServerClosed { // graceful shutdown
248 log.Info("http server shutdown...")
250 } else if err != nil {
251 log.Error("http server error: ", err)
252 log.Info("http server shutdown...")
256 //Wait until all go routines has exited
259 log.Warn("main routine exit")
260 log.Warn("server is stopping...")
263 // Simple alive check
264 func alive(w http.ResponseWriter, req *http.Request) {
268 // Get/Set logging level
269 func logging_level(w http.ResponseWriter, req *http.Request) {
270 vars := mux.Vars(req)
271 if level, ok := vars["level"]; ok {
272 if req.Method == http.MethodPut {
275 log.SetLevel(log.TraceLevel)
277 log.SetLevel(log.DebugLevel)
279 log.SetLevel(log.InfoLevel)
281 log.SetLevel(log.WarnLevel)
283 log.SetLevel(log.ErrorLevel)
285 log.SetLevel(log.FatalLevel)
287 log.SetLevel(log.PanicLevel)
289 w.WriteHeader(http.StatusNotFound)
292 w.WriteHeader(http.StatusMethodNotAllowed)
295 if req.Method == http.MethodGet {
297 if log.IsLevelEnabled(log.PanicLevel) {
299 } else if log.IsLevelEnabled(log.FatalLevel) {
301 } else if log.IsLevelEnabled(log.ErrorLevel) {
303 } else if log.IsLevelEnabled(log.WarnLevel) {
305 } else if log.IsLevelEnabled(log.InfoLevel) {
307 } else if log.IsLevelEnabled(log.DebugLevel) {
309 } else if log.IsLevelEnabled(log.TraceLevel) {
312 w.Header().Set("Content-Type", "application/text")
315 w.WriteHeader(http.StatusMethodNotAllowed)
321 func status(w http.ResponseWriter, req *http.Request) {
322 if req.Method != http.MethodGet {
323 w.WriteHeader(http.StatusMethodNotAllowed)
327 _, err := w.Write([]byte(appStatus))
329 w.WriteHeader(http.StatusInternalServerError)
330 log.Error("Cannot send statistics json")
335 // producer statictics, all jobs
336 func statistics(w http.ResponseWriter, req *http.Request) {
337 if req.Method != http.MethodGet {
338 w.WriteHeader(http.StatusMethodNotAllowed)
341 m := make(map[string]interface{})
342 log.Debug("rapp statictics")
344 req.Header.Set("Content-Type", "application/json; charset=utf-8")
345 m["number-of-messages"] = strconv.Itoa(msg_count)
346 m["number-of-corrupted-messages"] = strconv.Itoa(msg_corrupted_count)
350 m["kafka consumer type"] = consumer_type
351 m["server"] = bootstrapserver
353 m["messages per sec"] = msg_per_sec
355 json, err := json.Marshal(m)
357 w.WriteHeader(http.StatusInternalServerError)
358 log.Error("Cannot marshal statistics json")
361 _, err = w.Write(json)
363 w.WriteHeader(http.StatusInternalServerError)
364 log.Error("Cannot send statistics json")
369 func calc_average() {
373 time.Sleep(60 * time.Second)
374 msg_per_sec = (msg_count - v) / 60
378 func send_http_request(jsonData []byte, method string, url string, contentType string, accessToken string, alt_ok_response int, returnJson bool) (bool, map[string]interface{}) {
380 var req *http.Request
383 req, err = http.NewRequest(method, url, bytes.NewBuffer(jsonData))
385 log.Error("Cannot create http request method: ", method, " url: ", url)
388 if contentType == "" {
389 req.Header.Set("Content-Type", "application/json; charset=utf-8")
391 req.Header.Set("Content-Type", contentType)
394 req, err = http.NewRequest(method, url, nil)
396 log.Error("Cannot create http request method: ", method, " url: ", url)
400 if jwt_file != "" || creds_service_url != "" {
401 if accessToken != "" {
402 req.Header.Set("Authorization", "Bearer "+accessToken)
404 log.Error("Cannot create http request for url: ", url, " - token missing")
408 log.Debug("Http request: ", req)
409 resp, err2 := httpclient.Do(req)
411 log.Error("Cannot send http request, method: ", method, "url: ", url)
413 if resp.StatusCode == 200 || resp.StatusCode == 201 || resp.StatusCode == 204 {
416 defer resp.Body.Close()
417 body, err3 := ioutil.ReadAll(resp.Body)
419 log.Error("Cannot read body, method: ", method, ", url: ", url, " resp: ", resp.StatusCode)
422 var responseJson map[string]interface{}
423 err := json.Unmarshal(body, &responseJson)
425 log.Error("Received msg not json? - cannot unmarshal")
428 fmt.Println(string(body))
429 log.Debug("Accepted response code: ", resp.StatusCode)
430 return true, responseJson
434 log.Debug("Accepted response code: ", resp.StatusCode)
437 if alt_ok_response != 0 && resp.StatusCode == alt_ok_response {
440 defer resp.Body.Close()
441 body, err3 := ioutil.ReadAll(resp.Body)
443 log.Error("Cannot read body, method: ", method, ", url: ", url, " resp: ", resp.StatusCode)
446 var responseJson map[string]interface{}
447 err := json.Unmarshal(body, &responseJson)
449 log.Error("Received msg not json? - cannot unmarshal")
452 fmt.Println(string(body))
453 log.Debug("Accepted alternative response code: ", resp.StatusCode)
454 return true, responseJson
458 log.Error("Bad response, method: ", method, " url: ", url, " resp: ", resp.StatusCode, " resp: ", resp)
466 func retrive_token_strimzi() {
467 log.Debug("Get token inline - strimzi comm")
469 conf := &clientcredentials.Config{
470 ClientID: creds_client_id,
471 ClientSecret: creds_client_secret,
472 TokenURL: creds_service_url,
474 var modExpiry = time.Now()
477 token, err := conf.Token(context.Background())
479 log.Warning("Cannot fetch access token: ", err, " - retrying ")
480 time.Sleep(time.Second)
483 log.Debug("token: ", token)
484 log.Debug("TokenValue: ", token.AccessToken)
485 log.Debug("Expiration: ", token.Expiry)
486 modExpiry = token.Expiry.Add(-time.Minute)
487 log.Debug("Modified expiration: ", modExpiry)
488 currentToken = token.AccessToken
491 log.Debug("Initial token ok")
492 diff := modExpiry.Sub(time.Now())
495 case <-time.After(diff):
497 token, err := conf.Token(context.Background())
499 log.Warning("Cannot fetch access token: ", err, " - retrying ")
500 time.Sleep(time.Second)
503 log.Debug("token: ", token)
504 log.Debug("TokenValue: ", token.AccessToken)
505 log.Debug("Expiration: ", token.Expiry)
506 modExpiry = token.Expiry.Add(-time.Minute)
507 log.Debug("Modified expiration: ", modExpiry)
508 currentToken = token.AccessToken
511 diff = modExpiry.Sub(time.Now())
516 func retrive_token(c *kafka.Consumer) {
517 log.Debug("Get token inline")
518 conf := &clientcredentials.Config{
519 ClientID: creds_client_id,
520 ClientSecret: creds_client_secret,
521 TokenURL: creds_service_url,
523 token, err := conf.Token(context.Background())
525 log.Warning("Cannot fetch access token: ", err)
526 c.SetOAuthBearerTokenFailure(err.Error())
529 extensions := map[string]string{}
530 log.Debug("token: ", token)
531 log.Debug("TokenValue: ", token.AccessToken)
532 log.Debug("Expiration: ", token.Expiry)
533 t := token.Expiry.Add(-time.Minute)
534 log.Debug("Modified expiration: ", t)
535 oauthBearerToken := kafka.OAuthBearerToken{
536 TokenValue: token.AccessToken,
538 Extensions: extensions,
540 log.Debug("Setting new token to consumer")
541 setTokenError := c.SetOAuthBearerToken(oauthBearerToken)
542 currentToken = token.AccessToken
543 if setTokenError != nil {
544 log.Warning("Cannot cannot set token in client: ", setTokenError)
545 c.SetOAuthBearerTokenFailure(setTokenError.Error())
549 func gzipWrite(w io.Writer, data *[]byte) error {
550 gw, err1 := gzip.NewWriterLevel(w, gzip.BestSpeed)
556 _, err2 := gw.Write(*data)
560 func read_bridge_messages() {
562 consumer_type = "unsecure strimzi bridge consumer"
563 if creds_service_url != "" {
564 consumer_type = "accesstoken strimzi bridge consumer"
567 log.Debug("Cleaning consumer "+cid+" in group: ", gid)
568 ok, _ = send_http_request(nil, http.MethodDelete, bootstrapserver+"/consumers/"+gid+"/instances/"+cid, "", currentToken, 0, false)
570 log.Info("Failed to delete consumer "+cid+" in group: ", gid, " - it may not exist - ok")
572 var bridge_base_url = ""
574 json_str := "{\"name\": \"" + cid + "\", \"auto.offset.reset\": \"latest\",\"format\": \"json\"}"
576 log.Debug("Creating consumer "+cid+" in group: ", gid)
577 var respJson map[string]interface{}
578 ok, respJson = send_http_request([]byte(json_str), http.MethodPost, bootstrapserver+"/consumers/"+gid, "application/vnd.kafka.v2+json", currentToken, 409, true) //409 if consumer already exists
580 bridge_base_url = fmt.Sprintf("%s", respJson["base_uri"])
582 log.Info("Failed create consumer "+cid+" in group: ", gid, " - retrying")
583 time.Sleep(time.Second)
588 json_str = "{\"topics\": [\"" + topic + "\"]}"
591 log.Debug("Subscribing to topic: ", topic)
592 ok, _ = send_http_request([]byte(json_str), http.MethodPost, bridge_base_url+"/subscription", "application/vnd.kafka.v2+json", currentToken, 0, false)
594 log.Info("Failed subscribe to topic: ", topic, " - retrying")
595 time.Sleep(time.Second)
600 log.Debug("Reading messages on topic: ", topic)
602 var req *http.Request
604 url := bridge_base_url + "/records"
606 req, err = http.NewRequest(http.MethodGet, url, nil)
608 log.Error("Cannot create http request method: GET, url: ", url)
609 time.Sleep(1 * time.Second)
612 req.Header.Set("accept", "application/vnd.kafka.json.v2+json")
614 if creds_service_url != "" {
615 if currentToken != "" {
616 req.Header.Add("authorization", currentToken)
618 log.Error("Cannot create http request for url: ", url, " - token missing")
619 time.Sleep(1 * time.Second)
624 values := req.URL.Query()
625 values.Add("timeout", "10000")
626 req.URL.RawQuery = values.Encode()
630 resp, err2 := httpclient.Do(req)
632 log.Error("Cannot send http request, method: GET, url: ", url)
633 time.Sleep(1 * time.Second)
636 body, err := ioutil.ReadAll(resp.Body)
638 if resp.StatusCode == 200 || resp.StatusCode == 201 || resp.StatusCode == 204 {
639 log.Debug("Accepted response code: ", resp.StatusCode)
642 log.Error("Cannot read body, method: GET, url: ", url, " resp: ", resp.StatusCode)
644 var responseJson []interface{}
645 err := json.Unmarshal(body, &responseJson)
647 log.Error("Received msg not json? - cannot unmarshal")
648 msg_corrupted_count++
650 if len(responseJson) == 0 {
651 log.Debug("No message")
654 for _, item := range responseJson {
655 j, err := json.MarshalIndent(item, "", " ")
657 log.Error("Message in array not json? - cannot unmarshal")
658 msg_corrupted_count++
661 if log_payload != "" {
662 fmt.Println("Message: " + string(j))
669 log.Debug("Commiting message")
670 ok, _ = send_http_request(nil, http.MethodPost, bridge_base_url+"/offsets", "", currentToken, 0, false)
672 log.Info("Failed to commit message")
676 log.Error("Bad response, method: GET, url: ", url, " resp: ", resp.StatusCode)
677 log.Error("Bad response, data: ", string(body))
684 func read_kafka_messages() {
685 var c *kafka.Consumer = nil
686 log.Info("Creating kafka consumer...")
689 if jwt_file == "" && creds_service_url == "" {
691 log.Info("unsecure consumer")
692 consumer_type = "kafka unsecure consumer"
693 c, err = kafka.NewConsumer(&kafka.ConfigMap{
694 "bootstrap.servers": bootstrapserver,
697 "auto.offset.reset": "latest",
700 log.Info("ssl consumer")
701 consumer_type = "kafka ssl consumer"
702 c, err = kafka.NewConsumer(&kafka.ConfigMap{
703 "bootstrap.servers": bootstrapserver,
706 "auto.offset.reset": "latest",
707 "security.protocol": "SSL",
708 "ssl.key.location": ssl_path + "/clt.key",
709 "ssl.certificate.location": ssl_path + "/clt.crt",
710 "ssl.ca.location": ssl_path + "/ca.crt",
715 panic("SSL cannot be configued with JWT_FILE or RAPP_AUTH_SERVICE_URL")
717 log.Info("sasl consumer")
718 consumer_type = "kafka sasl unsecure consumer"
719 c, err = kafka.NewConsumer(&kafka.ConfigMap{
720 "bootstrap.servers": bootstrapserver,
723 "auto.offset.reset": "latest",
724 "sasl.mechanism": "OAUTHBEARER",
725 "security.protocol": "SASL_PLAINTEXT",
729 log.Warning("Cannot create kafka consumer - retrying, error: ", err)
730 time.Sleep(1 * time.Second)
734 log.Info("Creating kafka consumer - ok")
735 log.Info("Start subscribing to topic: ", topic)
738 err = c.SubscribeTopics([]string{topic}, nil)
740 log.Info("Topic reader cannot start subscribing on topic: ", topic, " - retrying -- error details: ", err)
742 log.Info("Topic reader subscribing on topic: ", topic)
747 fileModTime := time.Now()
750 fileInfo, err := os.Stat(jwt_file)
752 if fileModTime != fileInfo.ModTime() {
753 log.Debug("JWT file is updated")
754 fileModTime = fileInfo.ModTime()
755 fileBytes, err := ioutil.ReadFile(jwt_file)
757 log.Error("JWT file read error: ", err)
759 fileString := string(fileBytes)
760 log.Info("JWT: ", fileString)
762 t15 := time.Second * 300
764 oauthBearerToken := kafka.OAuthBearerToken{
765 TokenValue: fileString,
768 log.Debug("Setting new token to consumer")
769 setTokenError := c.SetOAuthBearerToken(oauthBearerToken)
770 if setTokenError != nil {
771 log.Warning("Cannot cannot set token in client: ", setTokenError)
775 log.Debug("JWT file not updated - OK")
778 log.Error("JWT does not exist: ", err)
783 log.Debug(" Nothing to consume on topic: ", topic)
786 switch e := ev.(type) {
788 var pdata *[]byte = &e.Value
789 if gzipped_data != "" {
791 err = gzipWrite(&buf, pdata)
793 log.Warning("Cannot unzip data")
797 fmt.Println("Unzipped data")
801 buf := &bytes.Buffer{}
803 if err := json.Indent(buf, *pdata, "", " "); err != nil {
804 log.Warning("Received msg not json?")
806 fmt.Println(buf.String())
808 fmt.Println("Number of received json msgs: " + strconv.Itoa(msg_count))
813 fmt.Fprintf(os.Stderr, "%% Error: %v: %v\n", e.Code(), e)
815 case kafka.OAuthBearerTokenRefresh:
817 oart, ok := ev.(kafka.OAuthBearerTokenRefresh)
825 fmt.Printf("Ignored %v\n", e)