3 // ========================LICENSE_START=================================
6 // Copyright (C) 2023: Nordix Foundation
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
19 // ========================LICENSE_END===================================
24 jsoniter "github.com/json-iterator/go"
25 log "github.com/sirupsen/logrus"
26 "main/common/dataTypes"
28 "main/components/kafkacollector"
38 var ics_server = os.Getenv("ICS")
39 var self = os.Getenv("SELF")
41 // This are optional - set if using SASL protocol is used towards kafka
42 var creds_grant_type = os.Getenv("CREDS_GRANT_TYPE")
44 var bootstrapserver = os.Getenv("KAFKA_SERVER")
46 const config_file = "application_configuration.json"
47 const producer_name = "kafka-producer"
49 var producer_instance_name string = producer_name
51 const reader_queue_length = 100 //Per type job
52 const writer_queue_length = 100 //Per info job
54 var files_volume = os.Getenv("FILES_VOLUME")
56 var data_out_channel = make(chan *dataTypes.KafkaPayload, writer_queue_length)
57 var writer_control = make(chan dataTypes.WriterControl, 1)
59 const registration_delay_short = 2
60 const registration_delay_long = 120
62 const failedMessageLabel = " - failed"
68 // Lock for all internal data
69 var datalock sync.Mutex
72 Init dataTypes.AppStates = iota
77 const registeringProducer = "Registering producer: "
82 //log.SetLevel(log.InfoLevel)
83 log.SetLevel(log.TraceLevel)
85 log.Info("Server starting...")
88 log.Panic("Env SELF not configured")
90 if bootstrapserver == "" {
91 log.Panic("Env KAFKA_SERVER not set")
94 log.Panic("Env ICS not set")
96 if os.Getenv("KP") != "" {
97 producer_instance_name = producer_instance_name + "-" + os.Getenv("KP")
100 go kafkacollector.StartTopicWriter(writer_control, data_out_channel)
102 //Setup proc for periodic type registration
103 var eventChan = make(chan int) //Channel for stopping the proc
104 go periodicRegistration(eventChan)
106 //Wait for term/int signal do try to shut down gracefully
107 sigs := make(chan os.Signal, 1)
108 signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
111 fmt.Printf("Received signal %s - application will terminate\n", sig)
112 eventChan <- 0 // Stop periodic registration
114 defer datalock.Unlock()
115 AppState = Terminating
120 //Wait until all go routines has exited
123 fmt.Println("main routine exit")
124 fmt.Println("server stopped")
127 // == Core functions ==//
128 // Run periodic registration of producers
129 func periodicRegistration(evtch chan int) {
134 if msg == 0 { // Stop thread
137 case <-time.After(time.Duration(delay) * time.Second):
138 ok := registerProducer()
140 delay = registration_delay_long
142 if delay < registration_delay_long {
143 delay += registration_delay_short
145 delay = registration_delay_short
152 func registerProducer() bool {
154 log.Info(registeringProducer, producer_instance_name)
156 file, err := os.ReadFile(config_file)
158 log.Error("Cannot read config file: ", config_file)
160 log.Error(registeringProducer, producer_instance_name, failedMessageLabel)
163 data := dataTypes.DataTypes{}
164 err = jsoniter.Unmarshal([]byte(file), &data)
166 log.Error("Cannot parse config file: ", config_file)
168 log.Error(registeringProducer, producer_instance_name, failedMessageLabel)
171 var newTypeNames []string
173 for i := 0; i < len(data.ProdDataTypes); i++ {
174 t1 := make(map[string]interface{})
175 t2 := make(map[string]interface{})
177 t2["schema"] = "http://json-schema.org/draft-07/schema#"
178 t2["title"] = data.ProdDataTypes[i].ID
179 t2["description"] = data.ProdDataTypes[i].ID
180 t2["type"] = "object"
182 t1["info_job_data_schema"] = t2
184 json, err := jsoniter.Marshal(t1)
186 log.Error("Cannot create json for type: ", data.ProdDataTypes[i].ID)
188 log.Error(registeringProducer, producer_instance_name, failedMessageLabel)
191 ok := utils.SendHttpRequest(json, http.MethodPut, "http://"+ics_server+"/data-producer/v1/info-types/"+data.ProdDataTypes[i].ID, true, creds_grant_type != "")
193 log.Error("Cannot register type: ", data.ProdDataTypes[i].ID)
195 log.Error(registeringProducer, producer_instance_name, failedMessageLabel)
198 newTypeNames = append(newTypeNames, data.ProdDataTypes[i].ID)
203 log.Debug("Registering types: ", newTypeNames)
205 defer datalock.Unlock()
207 for _, v := range data.ProdDataTypes {
208 log.Info("Adding type job for type: ", v.ID, " Type added to configuration")
212 dataTypes.InfoTypes = data
213 log.Debug("Datatypes: ", dataTypes.InfoTypes)
214 log.Info(registeringProducer, producer_instance_name, " - OK")
218 func startTypeJob(dp dataTypes.DataType) {
219 log.Info("Starting type job: ", dp.ID)
220 jobRecord := dataTypes.TypeJobRecord{}
222 jobRecord.Job_control = make(chan dataTypes.JobControl, 1)
223 jobRecord.Reader_control = make(chan dataTypes.ReaderControl, 1)
224 jobRecord.Data_in_channel = make(chan *dataTypes.KafkaPayload, reader_queue_length)
225 jobRecord.InfoType = dp.ID
226 jobRecord.InputTopic = dp.KafkaInputTopic
227 jobRecord.GroupId = "kafka-procon-" + dp.ID
228 jobRecord.ClientId = dp.ID + "-" + os.Getenv("KP")
231 case "xml-file-data-to-filestore":
232 go kafkacollector.StartJobXmlFileData(dp.ID, jobRecord.Job_control, jobRecord.Data_in_channel, data_out_channel, "", "pm-files-json")
233 case "xml-file-data":
234 go kafkacollector.StartJobXmlFileData(dp.ID, jobRecord.Job_control, jobRecord.Data_in_channel, data_out_channel, files_volume, "")
238 go kafkacollector.StartTopicReader(dp.KafkaInputTopic, dp.ID, jobRecord.Reader_control, jobRecord.Data_in_channel, jobRecord.GroupId, jobRecord.ClientId)
240 dataTypes.TypeJobs[dp.ID] = jobRecord
241 log.Debug("Type job input type: ", dp.InputJobType)