blob: 930fbd2f23c309db0da44745da0698096be16f3a [file] [log] [blame]
Dinesh Belwalkar01217962019-05-23 21:51:16 +00001// Copyright 2018 Open Networking Foundation
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package main
16
17import (
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000018 "crypto/tls"
19 "encoding/json"
Dinesh Belwalkar01217962019-05-23 21:51:16 +000020 "fmt"
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000021 "github.com/Shopify/sarama"
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000022 empty "github.com/golang/protobuf/ptypes/empty"
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +000023 "github.com/opencord/device-management/proto"
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +000024 logrus "github.com/sirupsen/logrus"
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000025 "golang.org/x/net/context"
26 "google.golang.org/grpc"
27 "google.golang.org/grpc/codes"
28 "google.golang.org/grpc/status"
29 "io/ioutil"
Dinesh Belwalkar41229602019-06-21 16:58:06 +000030 "net"
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +000031 "net/http"
Dinesh Belwalkar8af8d7d2019-05-29 21:00:50 +000032 "os"
33 "os/signal"
mc862dad02019-08-06 20:52:51 +000034 "path"
mccd7e9502019-12-16 22:04:13 +000035 "strconv"
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +000036 "strings"
37 "time"
Dinesh Belwalkar01217962019-05-23 21:51:16 +000038)
39
mce7028402019-07-18 04:10:01 +000040//globals
mc20a4b5f2019-10-16 20:28:24 +000041const RF_DEFAULT_PROTOCOL = "https://"
42const RF_DATA_COLLECT_THRESHOLD = 5
43const RF_DATA_COLLECT_DUMMY_INTERVAL = 1000
mce7028402019-07-18 04:10:01 +000044const CONTENT_TYPE = "application/json"
45
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +000046var (
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +000047 importerTopic = "importer"
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +000048)
49
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +000050var redfish_resources = [...]string{"/redfish/v1/Chassis", "/redfish/v1/Systems", "/redfish/v1/EthernetSwitches"}
mc862dad02019-08-06 20:52:51 +000051var pvmount = os.Getenv("DEVICE_MANAGEMENT_PVMOUNT")
52var subscriptionListPath string
mce7028402019-07-18 04:10:01 +000053
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +000054type scheduler struct {
55 getdata *time.Ticker
56 quit chan bool
mc20a4b5f2019-10-16 20:28:24 +000057 getdataend chan bool
mce7028402019-07-18 04:10:01 +000058}
59
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +000060type device struct {
61 Subscriptions map[string]string `json:"ss"`
62 Freq uint32 `json:"freq"`
63 Datacollector scheduler `json:"-"`
64 Freqchan chan uint32 `json:"-"`
65 Eventtypes []string `json:"eventtypes"`
66 Datafile *os.File `json:"-"`
Dinesh Belwalkar41229602019-06-21 16:58:06 +000067}
68
69type Server struct {
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +000070 devicemap map[string]*device
71 gRPCserver *grpc.Server
72 dataproducer sarama.AsyncProducer
73 httpclient *http.Client
Dinesh Belwalkar41229602019-06-21 16:58:06 +000074}
75
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000076func (s *Server) ClearCurrentEventList(c context.Context, info *importer.Device) (*empty.Empty, error) {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +000077 logrus.Info("Received ClearCurrentEventList")
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000078 ip_address := info.IpAddress
mccd7e9502019-12-16 22:04:13 +000079 if msg, ok := s.validate_ip(ip_address, true, true); !ok {
80 return nil, status.Errorf(codes.InvalidArgument, msg)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000081 }
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +000082 for event := range s.devicemap[ip_address].Subscriptions {
mc20a4b5f2019-10-16 20:28:24 +000083 rtn := s.remove_subscription(ip_address, event)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000084 if !rtn {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +000085 logrus.WithFields(logrus.Fields{
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000086 "Event": event,
87 }).Info("Error removing event")
88 }
89 }
mc20a4b5f2019-10-16 20:28:24 +000090 s.update_data_file(ip_address)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000091 return &empty.Empty{}, nil
92}
93
94func (s *Server) GetCurrentEventList(c context.Context, info *importer.Device) (*importer.EventList, error) {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +000095 logrus.Info("Received GetCurrentEventList")
mccd7e9502019-12-16 22:04:13 +000096 if msg, ok := s.validate_ip(info.IpAddress, true, true); !ok {
97 return nil, status.Errorf(codes.InvalidArgument, msg)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +000098 }
99 currentevents := new(importer.EventList)
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000100 for event := range s.devicemap[info.IpAddress].Subscriptions {
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000101 currentevents.Events = append(currentevents.Events, event)
102 }
103 return currentevents, nil
104}
105
mc20a4b5f2019-10-16 20:28:24 +0000106func (s *Server) GetEventList(c context.Context, info *importer.Device) (*importer.EventList, error) {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000107 logrus.Info("Received GetEventList")
mccd7e9502019-12-16 22:04:13 +0000108 if msg, ok := s.validate_ip(info.IpAddress, true, true); !ok {
109 return nil, status.Errorf(codes.InvalidArgument, msg)
110 }
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000111 eventstobesubscribed := new(importer.EventList)
mccd7e9502019-12-16 22:04:13 +0000112 eventstobesubscribed.Events = s.devicemap[info.IpAddress].Eventtypes
mc20a4b5f2019-10-16 20:28:24 +0000113 if eventstobesubscribed.Events == nil {
mccd7e9502019-12-16 22:04:13 +0000114 return nil, status.Errorf(codes.NotFound, "No events found\n")
mc20a4b5f2019-10-16 20:28:24 +0000115 }
mce7028402019-07-18 04:10:01 +0000116 return eventstobesubscribed, nil
Dinesh Belwalkarf57ee2e2019-07-11 17:46:00 +0000117}
118
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000119func (s *Server) SetFrequency(c context.Context, info *importer.FreqInfo) (*empty.Empty, error) {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000120 logrus.Info("Received SetFrequency")
mccd7e9502019-12-16 22:04:13 +0000121 if msg, ok := s.validate_ip(info.IpAddress, true, true); !ok {
122 return nil, status.Errorf(codes.InvalidArgument, msg)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000123 }
mc20a4b5f2019-10-16 20:28:24 +0000124 if info.Frequency > 0 && info.Frequency < RF_DATA_COLLECT_THRESHOLD {
mccd7e9502019-12-16 22:04:13 +0000125 return nil, status.Errorf(codes.InvalidArgument, "Invalid interval\n")
mc20a4b5f2019-10-16 20:28:24 +0000126 }
mc862dad02019-08-06 20:52:51 +0000127 s.devicemap[info.IpAddress].Freqchan <- info.Frequency
mc20a4b5f2019-10-16 20:28:24 +0000128 s.devicemap[info.IpAddress].Freq = info.Frequency
129 s.update_data_file(info.IpAddress)
mce7028402019-07-18 04:10:01 +0000130 return &empty.Empty{}, nil
Dinesh Belwalkarf57ee2e2019-07-11 17:46:00 +0000131}
132
mccd7e9502019-12-16 22:04:13 +0000133func (s *Server) SubscribeGivenEvents(c context.Context, subeventlist *importer.GivenEventList) (*empty.Empty, error) {
mc20a4b5f2019-10-16 20:28:24 +0000134 errstring := ""
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000135 logrus.Info("Received SubsrcribeEvents")
mce7028402019-07-18 04:10:01 +0000136 //Call API to subscribe events
137 ip_address := subeventlist.EventIpAddress
mccd7e9502019-12-16 22:04:13 +0000138 if msg, ok := s.validate_ip(ip_address, true, true); !ok {
139 return nil, status.Errorf(codes.InvalidArgument, msg)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000140 }
141 if len(subeventlist.Events) <= 0 {
mccd7e9502019-12-16 22:04:13 +0000142 return nil, status.Errorf(codes.InvalidArgument, "Event list is empty\n")
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000143 }
mce7028402019-07-18 04:10:01 +0000144 for _, event := range subeventlist.Events {
mc862dad02019-08-06 20:52:51 +0000145 if _, ok := s.devicemap[ip_address].Subscriptions[event]; !ok {
mccd7e9502019-12-16 22:04:13 +0000146 supported := false
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000147 for _, e := range s.devicemap[ip_address].Eventtypes {
mccd7e9502019-12-16 22:04:13 +0000148 if e == event {
149 supported = true
150 rtn := s.add_subscription(ip_address, event)
151 if !rtn {
152 errstring = errstring + "failed to subscribe event " + ip_address + " " + event + "\n"
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000153 logrus.WithFields(logrus.Fields{
mccd7e9502019-12-16 22:04:13 +0000154 "Event": event,
155 }).Info("Error adding event")
156 }
157 break
158 }
159 }
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000160 if !supported {
mccd7e9502019-12-16 22:04:13 +0000161 errstring = errstring + "event " + event + " not supported\n"
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000162 logrus.WithFields(logrus.Fields{
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000163 "Event": event,
mccd7e9502019-12-16 22:04:13 +0000164 }).Info("not supported")
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000165 }
mc862dad02019-08-06 20:52:51 +0000166 } else {
mc20a4b5f2019-10-16 20:28:24 +0000167 errstring = errstring + "event " + event + " already subscribed\n"
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000168 logrus.WithFields(logrus.Fields{
mc862dad02019-08-06 20:52:51 +0000169 "Event": event,
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000170 }).Info("Already Subscribed")
mc862dad02019-08-06 20:52:51 +0000171 }
mce7028402019-07-18 04:10:01 +0000172 }
mc20a4b5f2019-10-16 20:28:24 +0000173 s.update_data_file(ip_address)
174 if errstring != "" {
175 return &empty.Empty{}, status.Errorf(codes.InvalidArgument, errstring)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000176 }
mce7028402019-07-18 04:10:01 +0000177 return &empty.Empty{}, nil
Dinesh Belwalkarf57ee2e2019-07-11 17:46:00 +0000178}
179
mccd7e9502019-12-16 22:04:13 +0000180func (s *Server) UnsubscribeGivenEvents(c context.Context, unsubeventlist *importer.GivenEventList) (*empty.Empty, error) {
mc20a4b5f2019-10-16 20:28:24 +0000181 errstring := ""
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000182 logrus.Info("Received UnSubsrcribeEvents")
mc862dad02019-08-06 20:52:51 +0000183 ip_address := unsubeventlist.EventIpAddress
mccd7e9502019-12-16 22:04:13 +0000184 if msg, ok := s.validate_ip(ip_address, true, true); !ok {
185 return nil, status.Errorf(codes.InvalidArgument, msg)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000186 }
187
188 if len(unsubeventlist.Events) <= 0 {
mccd7e9502019-12-16 22:04:13 +0000189 return nil, status.Errorf(codes.InvalidArgument, "Event list is empty\n")
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000190 }
mc862dad02019-08-06 20:52:51 +0000191 //Call API to unsubscribe events
mc862dad02019-08-06 20:52:51 +0000192 for _, event := range unsubeventlist.Events {
193 if _, ok := s.devicemap[ip_address].Subscriptions[event]; ok {
mc20a4b5f2019-10-16 20:28:24 +0000194 rtn := s.remove_subscription(ip_address, event)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000195 if !rtn {
mc20a4b5f2019-10-16 20:28:24 +0000196 errstring = errstring + "failed to unsubscribe event " + ip_address + " " + event + "\n"
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000197 logrus.WithFields(logrus.Fields{
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000198 "Event": event,
199 }).Info("Error removing event")
200 }
201 } else {
mc20a4b5f2019-10-16 20:28:24 +0000202 errstring = errstring + "event " + event + " not found\n"
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000203 logrus.WithFields(logrus.Fields{
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000204 "Event": event,
205 }).Info("was not Subscribed")
206 }
207 }
mc20a4b5f2019-10-16 20:28:24 +0000208 s.update_data_file(ip_address)
Dinesh Belwalkarf57ee2e2019-07-11 17:46:00 +0000209
mc20a4b5f2019-10-16 20:28:24 +0000210 if errstring != "" {
211 return &empty.Empty{}, status.Errorf(codes.InvalidArgument, errstring)
212 }
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000213 return &empty.Empty{}, nil
Dinesh Belwalkarf57ee2e2019-07-11 17:46:00 +0000214}
215
mc20a4b5f2019-10-16 20:28:24 +0000216func (s *Server) update_data_file(ip_address string) {
217 f := s.devicemap[ip_address].Datafile
218 if f != nil {
219 b, err := json.Marshal(s.devicemap[ip_address])
220 if err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000221 logrus.Errorf("Update_data_file %s", err)
mc20a4b5f2019-10-16 20:28:24 +0000222 } else {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000223 err := f.Truncate(0)
224 if err != nil {
225 logrus.Errorf("err Trunate %s", err)
226 return
227 }
228 pos, err := f.Seek(0, 0)
229 if err != nil {
230 logrus.Errorf("err Seek %s", err)
231 return
232 }
233 fmt.Println("moved back to", pos)
mc20a4b5f2019-10-16 20:28:24 +0000234 n, err := f.Write(b)
235 if err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000236 logrus.Errorf("err wrote %d bytes", n)
237 logrus.Errorf("write error to file %s", err)
mc20a4b5f2019-10-16 20:28:24 +0000238 }
239 }
240 } else {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000241 logrus.Errorf("file handle is nil %s", ip_address)
mc20a4b5f2019-10-16 20:28:24 +0000242 }
243}
244
mce7028402019-07-18 04:10:01 +0000245func (s *Server) collect_data(ip_address string) {
mc862dad02019-08-06 20:52:51 +0000246 freqchan := s.devicemap[ip_address].Freqchan
247 ticker := s.devicemap[ip_address].Datacollector.getdata
248 donechan := s.devicemap[ip_address].Datacollector.quit
mce7028402019-07-18 04:10:01 +0000249 for {
250 select {
Dinesh Belwalkara0493ad2019-07-22 19:58:42 +0000251 case freq := <-freqchan:
mce7028402019-07-18 04:10:01 +0000252 ticker.Stop()
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000253 if freq > 0 {
254 ticker = time.NewTicker(time.Duration(freq) * time.Second)
mc20a4b5f2019-10-16 20:28:24 +0000255 s.devicemap[ip_address].Datacollector.getdata = ticker
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000256 }
257 case err := <-s.dataproducer.Errors():
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000258 logrus.Errorf("Failed to produce message:%s", err)
mce7028402019-07-18 04:10:01 +0000259 case <-ticker.C:
mc20a4b5f2019-10-16 20:28:24 +0000260 for _, resource := range redfish_resources {
261 data := s.get_status(ip_address, resource)
262 for _, str := range data {
263 str = "Device IP: " + ip_address + " " + str
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000264 logrus.Infof("collected data %s", str)
mc20a4b5f2019-10-16 20:28:24 +0000265 b := []byte(str)
266 msg := &sarama.ProducerMessage{Topic: importerTopic, Value: sarama.StringEncoder(b)}
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000267 s.dataproducer.Input() <- msg
268 logrus.Info("Produce message")
mce7028402019-07-18 04:10:01 +0000269 }
270 }
271 case <-donechan:
272 ticker.Stop()
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000273 logrus.Info("getdata ticker stopped")
mc20a4b5f2019-10-16 20:28:24 +0000274 s.devicemap[ip_address].Datacollector.getdataend <- true
mce7028402019-07-18 04:10:01 +0000275 return
276 }
277 }
278}
Dinesh Belwalkarf57ee2e2019-07-11 17:46:00 +0000279
mc20a4b5f2019-10-16 20:28:24 +0000280func (s *Server) DeleteDeviceList(c context.Context, list *importer.DeviceListByIp) (*empty.Empty, error) {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000281 logrus.Info("DeleteDeviceList received")
mc20a4b5f2019-10-16 20:28:24 +0000282 errstring := ""
283 for _, ip := range list.Ip {
284 if _, ok := s.devicemap[ip]; !ok {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000285 logrus.Infof("Device not found %s ", ip)
mc20a4b5f2019-10-16 20:28:24 +0000286 errstring = errstring + "Device " + ip + " not found\n"
287 continue
288 }
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000289 for event := range s.devicemap[ip].Subscriptions {
mc20a4b5f2019-10-16 20:28:24 +0000290 rtn := s.remove_subscription(ip, event)
291 if !rtn {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000292 logrus.WithFields(logrus.Fields{
mc20a4b5f2019-10-16 20:28:24 +0000293 "Event": event,
294 }).Info("Error removing event")
295 }
296 }
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000297 logrus.Infof("deleting device %s", ip)
mc20a4b5f2019-10-16 20:28:24 +0000298 s.devicemap[ip].Datacollector.quit <- true
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000299
mc20a4b5f2019-10-16 20:28:24 +0000300 f := s.devicemap[ip].Datafile
301 if f != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000302 logrus.Infof("deleteing file %s", f.Name())
mc20a4b5f2019-10-16 20:28:24 +0000303 err := f.Close()
304 if err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000305 logrus.Errorf("error closing file %s %s", f.Name(), err)
mc20a4b5f2019-10-16 20:28:24 +0000306 errstring = errstring + "error closing file " + f.Name() + "\n"
307 }
308 err = os.Remove(f.Name())
309 if err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000310 logrus.Errorf("error deleting file %s Error:%s ", f.Name(), err)
mc20a4b5f2019-10-16 20:28:24 +0000311 }
312 } else {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000313 logrus.Errorf("File not found %s", errstring+"file "+ip+" not found")
mc20a4b5f2019-10-16 20:28:24 +0000314 }
315 <-s.devicemap[ip].Datacollector.getdataend
316 delete(s.devicemap, ip)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000317 }
mc20a4b5f2019-10-16 20:28:24 +0000318 if errstring != "" {
319 return &empty.Empty{}, status.Errorf(codes.InvalidArgument, errstring)
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000320 }
Dinesh Belwalkarf57ee2e2019-07-11 17:46:00 +0000321 return &empty.Empty{}, nil
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000322}
mc6a9f01a2019-06-26 21:31:23 +0000323
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +0000324func (s *Server) SendDeviceList(c context.Context, list *importer.DeviceList) (*empty.Empty, error) {
mc20a4b5f2019-10-16 20:28:24 +0000325 errstring := ""
326 for _, dev := range list.Device {
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +0000327 ip_address := dev.IpAddress
mccd7e9502019-12-16 22:04:13 +0000328 if msg, ok := s.validate_ip(ip_address, false, false); !ok {
329 errstring = errstring + msg
mc20a4b5f2019-10-16 20:28:24 +0000330 continue
331 }
mc20a4b5f2019-10-16 20:28:24 +0000332 if dev.Frequency > 0 && dev.Frequency < RF_DATA_COLLECT_THRESHOLD {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000333 logrus.Errorf("Device %s data collection interval %d out of range", ip_address, dev.Frequency)
mc20a4b5f2019-10-16 20:28:24 +0000334 errstring = errstring + "Device " + ip_address + " data collection frequency out of range\n"
335 continue
336 }
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +0000337 d := device{
mc20a4b5f2019-10-16 20:28:24 +0000338 Subscriptions: make(map[string]string),
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +0000339 Freq: dev.Frequency,
mc20a4b5f2019-10-16 20:28:24 +0000340 Datacollector: scheduler{
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +0000341 quit: make(chan bool),
mc20a4b5f2019-10-16 20:28:24 +0000342 getdataend: make(chan bool),
343 },
344 Freqchan: make(chan uint32),
345 }
346 s.devicemap[ip_address] = &d
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000347 logrus.Infof("Configuring %s", ip_address)
mc20a4b5f2019-10-16 20:28:24 +0000348
349 /* if initial interval is 0, create a dummy ticker, which is stopped right away, so getdata is not nil */
350 freq := dev.Frequency
351 if freq == 0 {
352 freq = RF_DATA_COLLECT_DUMMY_INTERVAL
353 }
354 s.devicemap[ip_address].Datacollector.getdata = time.NewTicker(time.Duration(freq) * time.Second)
355 if dev.Frequency == 0 {
356 s.devicemap[ip_address].Datacollector.getdata.Stop()
357 }
358
359 eventtypes := s.get_event_types(ip_address)
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000360 for _, event := range eventtypes {
361 s.devicemap[ip_address].Eventtypes = append(s.devicemap[ip_address].Eventtypes, event)
362 if !s.add_subscription(ip_address, event) {
363 errstring = errstring + "failed to subscribe event " + ip_address + " " + event + "\n"
mc20a4b5f2019-10-16 20:28:24 +0000364 }
365 }
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000366
mc20a4b5f2019-10-16 20:28:24 +0000367 go s.collect_data(ip_address)
368 s.devicemap[ip_address].Datafile = get_data_file(ip_address)
369 s.update_data_file(ip_address)
370 }
371 if errstring != "" {
372 return &empty.Empty{}, status.Errorf(codes.InvalidArgument, errstring)
373 }
374 return &empty.Empty{}, nil
375}
376
377func (s *Server) GetCurrentDevices(c context.Context, e *importer.Empty) (*importer.DeviceListByIp, error) {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000378 logrus.Infof("In Received GetCurrentDevices")
dileepbk86ef0102019-11-13 00:08:33 +0000379
380 if len(s.devicemap) == 0 {
mccd7e9502019-12-16 22:04:13 +0000381 return nil, status.Errorf(codes.NotFound, "No Device found\n")
dileepbk86ef0102019-11-13 00:08:33 +0000382 }
mc20a4b5f2019-10-16 20:28:24 +0000383 dl := new(importer.DeviceListByIp)
dileepbk86ef0102019-11-13 00:08:33 +0000384 for k, v := range s.devicemap {
385 if v != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000386 logrus.Infof("IpAdd[%s] \n", k)
dileepbk86ef0102019-11-13 00:08:33 +0000387 dl.Ip = append(dl.Ip, k)
388 }
389 }
390 return dl, nil
391}
392
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000393func NewGrpcServer(grpcport string) (l net.Listener, g *grpc.Server, e error) {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000394 logrus.Infof("Listening %s\n", grpcport)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000395 g = grpc.NewServer()
396 l, e = net.Listen("tcp", grpcport)
397 return
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000398}
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000399func (s *Server) startgrpcserver() {
400 logrus.Info("starting gRPC Server")
Scott Bakerbdb962b2020-04-03 10:53:36 -0700401 listener, gserver, err := NewGrpcServer(GlobalConfig.LocalGrpc)
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000402 if err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000403 logrus.Errorf("Failed to create gRPC server: %s ", err)
404 panic(err)
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000405 }
406 s.gRPCserver = gserver
407 importer.RegisterDeviceManagementServer(gserver, s)
408 if err := gserver.Serve(listener); err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000409 logrus.Errorf("Failed to run gRPC server: %s ", err)
410 panic(err)
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000411 }
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000412
413}
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000414func (s *Server) kafkaCloseProducer() {
415 if err := s.dataproducer.Close(); err != nil {
Dinesh Belwalkare1e85ad2019-07-31 23:06:47 +0000416 panic(err)
417 }
418
419}
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000420func (s *Server) kafkaInit() {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000421 logrus.Info("Starting kafka init to Connect to broker: ")
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000422 config := sarama.NewConfig()
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000423 config.Producer.RequiredAcks = sarama.WaitForAll
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000424 config.Producer.Retry.Max = 10
Scott Bakerbdb962b2020-04-03 10:53:36 -0700425 producer, err := sarama.NewAsyncProducer([]string{GlobalConfig.Kafka}, config)
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000426 if err != nil {
427 panic(err)
428 }
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000429 s.dataproducer = producer
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000430}
431
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000432func (s *Server) handle_events(w http.ResponseWriter, r *http.Request) {
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000433 signals := make(chan os.Signal, 1)
434 signal.Notify(signals, os.Interrupt)
435
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000436 logrus.Info(" IN Handle Event ")
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000437 if r.Method == "POST" {
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000438 Body, err := ioutil.ReadAll(r.Body)
439 if err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000440 logrus.Errorf("Error getting HTTP data %s", err)
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000441 }
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000442 defer r.Body.Close()
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000443 logrus.Info("Received Event Message ")
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000444 fmt.Printf("%s\n", Body)
445 message := &sarama.ProducerMessage{
446 Topic: importerTopic,
447 Value: sarama.StringEncoder(Body),
448 }
Dinesh Belwalkare1e85ad2019-07-31 23:06:47 +0000449 s.dataproducer.Input() <- message
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000450 }
451}
452
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000453func (s *Server) runServer() {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000454 logrus.Info("Starting HTTP Server")
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000455 http.HandleFunc("/", s.handle_events)
Scott Bakerbdb962b2020-04-03 10:53:36 -0700456 err := http.ListenAndServeTLS(GlobalConfig.Local, "https-server.crt", "https-server.key", nil)
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000457 if err != nil {
458 panic(err)
459 }
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000460}
461
mccd7e9502019-12-16 22:04:13 +0000462/* validate_ip() verifies if the ip and port are valid and already registered then return the truth value of the desired state specified by the following 2 switches,
463 want_registered: 'true' if the fact of an ip is registered is the desired state
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000464 include_port: 'true' further checks if <ip>:<port#> does exist in the devicemap in case an ip is found registered
mccd7e9502019-12-16 22:04:13 +0000465*/
466func (s *Server) validate_ip(ip_address string, want_registered bool, include_port bool) (msg string, ok bool) {
467 msg = ""
468 ok = false
469 if !strings.Contains(ip_address, ":") {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000470 logrus.Errorf("Incorrect IP address %s, expected format <ip>:<port #>", ip_address)
mccd7e9502019-12-16 22:04:13 +0000471 msg = "Incorrect IP address format (<ip>:<port #>)\n"
472 return
473 }
474 splits := strings.Split(ip_address, ":")
475 ip, port := splits[0], splits[1]
476 if net.ParseIP(ip) == nil {
Scott Bakerbdb962b2020-04-03 10:53:36 -0700477 // also check to see if it's a valid hostname
478 if _, err := net.LookupIP(ip); err != nil {
479 logrus.Errorf("Invalid IP address %s", ip)
480 msg = "Invalid IP address " + ip + "\n"
481 return
482 }
mccd7e9502019-12-16 22:04:13 +0000483 }
484 if _, err := strconv.Atoi(port); err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000485 logrus.Errorf("Port # %s is not an integer", port)
mccd7e9502019-12-16 22:04:13 +0000486 msg = "Port # " + port + " needs to be an integer\n"
487 return
488 }
489 for k := range s.devicemap {
490 if strings.HasPrefix(k, ip) {
491 if !want_registered {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000492 logrus.Errorf("Device ip %s already registered", ip)
mccd7e9502019-12-16 22:04:13 +0000493 msg = "Device ip " + ip + " already registered\n"
494 return
495 } else if include_port {
496 if _, found := s.devicemap[ip_address]; found {
497 ok = true
498 return
499 } else {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000500 logrus.Errorf("Device %s not registered", ip_address)
mccd7e9502019-12-16 22:04:13 +0000501 msg = "Device " + ip_address + " not registered\n"
502 return
503 }
504 } else {
505 ok = true
506 return
507 }
508 }
509 }
510 if want_registered {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000511 logrus.Errorf("Device %s not registered", ip_address)
mccd7e9502019-12-16 22:04:13 +0000512 msg = "Device " + ip_address + " not registered\n"
513 return
514 }
515 ok = true
516 return
517}
518
mc862dad02019-08-06 20:52:51 +0000519func (s *Server) init_data_persistence() {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000520 logrus.Info("Retrieving persisted data")
mc862dad02019-08-06 20:52:51 +0000521 subscriptionListPath = pvmount + "/subscriptions"
522 if err := os.MkdirAll(subscriptionListPath, 0777); err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000523 logrus.Errorf("MkdirAll %s", err)
mc862dad02019-08-06 20:52:51 +0000524 } else {
mc20a4b5f2019-10-16 20:28:24 +0000525 files, err := ioutil.ReadDir(subscriptionListPath)
mc862dad02019-08-06 20:52:51 +0000526 if err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000527 logrus.Errorf("ReadDir %s", err)
mc862dad02019-08-06 20:52:51 +0000528 } else {
mc20a4b5f2019-10-16 20:28:24 +0000529 for _, f := range files {
530 b, err := ioutil.ReadFile(path.Join(subscriptionListPath, f.Name()))
mc862dad02019-08-06 20:52:51 +0000531 if err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000532 logrus.Errorf("Readfile %s", err)
mc20a4b5f2019-10-16 20:28:24 +0000533 } else if f.Size() > 0 {
534 ip := f.Name()
mc862dad02019-08-06 20:52:51 +0000535 d := device{}
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000536 err := json.Unmarshal(b, &d)
537 if err != nil {
538 logrus.Errorf("Unmarshal %s", err)
539 return
540 }
mc862dad02019-08-06 20:52:51 +0000541 s.devicemap[ip] = &d
mc20a4b5f2019-10-16 20:28:24 +0000542 freq := s.devicemap[ip].Freq
543
544 /* if initial interval is 0, create a dummy ticker, which is stopped right away, so getdata is not nil */
545 if freq == 0 {
546 freq = RF_DATA_COLLECT_DUMMY_INTERVAL
547 }
548 s.devicemap[ip].Datacollector.getdata = time.NewTicker(time.Duration(freq) * time.Second)
549 if s.devicemap[ip].Freq == 0 {
550 s.devicemap[ip].Datacollector.getdata.Stop()
551 }
552
mc862dad02019-08-06 20:52:51 +0000553 s.devicemap[ip].Datacollector.quit = make(chan bool)
mc20a4b5f2019-10-16 20:28:24 +0000554 s.devicemap[ip].Datacollector.getdataend = make(chan bool)
mc862dad02019-08-06 20:52:51 +0000555 s.devicemap[ip].Freqchan = make(chan uint32)
mc20a4b5f2019-10-16 20:28:24 +0000556 s.devicemap[ip].Datafile = get_data_file(ip)
mc862dad02019-08-06 20:52:51 +0000557 go s.collect_data(ip)
558 }
559 }
560 }
561 }
562}
563
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000564func init() {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000565 Formatter := new(logrus.TextFormatter)
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000566 Formatter.TimestampFormat = "02-01-2006 15:04:05"
567 Formatter.FullTimestamp = true
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000568 logrus.SetFormatter(Formatter)
569 logrus.Info("log Connecting to broker:")
570 logrus.Info("log Listening to http server ")
Dinesh Belwalkare1e85ad2019-07-31 23:06:47 +0000571 //sarama.Logger = log.New()
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000572}
573
mc20a4b5f2019-10-16 20:28:24 +0000574func get_data_file(ip string) *os.File {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000575 logrus.Info("get_data_file")
mc862dad02019-08-06 20:52:51 +0000576 if pvmount == "" {
577 return nil
578 }
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000579 f, err := os.OpenFile(subscriptionListPath+"/"+ip, os.O_CREATE|os.O_RDWR, 0664)
mc862dad02019-08-06 20:52:51 +0000580 if err != nil {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000581 logrus.Errorf("Openfile err %s", err)
mc862dad02019-08-06 20:52:51 +0000582 }
583 return f
584}
Dinesh Belwalkarb6b2b302019-06-06 17:30:44 +0000585
mc20a4b5f2019-10-16 20:28:24 +0000586func (s *Server) close_data_files() {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000587 for ip := range s.devicemap {
mc20a4b5f2019-10-16 20:28:24 +0000588 s.devicemap[ip].Datafile.Close()
589 }
590}
591
Dinesh Belwalkar01217962019-05-23 21:51:16 +0000592func main() {
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000593 logrus.Info("Starting Device-management Container")
mc862dad02019-08-06 20:52:51 +0000594
Scott Bakerbdb962b2020-04-03 10:53:36 -0700595 ParseCommandLine()
596 ProcessGlobalOptions()
597 ShowGlobalOptions()
598
mc862dad02019-08-06 20:52:51 +0000599 http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
600 client := &http.Client{
601 Timeout: 10 * time.Second,
Dinesh Belwalkarb5db83f2019-10-24 17:27:58 +0000602 }
mc862dad02019-08-06 20:52:51 +0000603
Dinesh Belwalkar72ecafb2019-12-12 00:08:56 +0000604 s := Server{
605 devicemap: make(map[string]*device),
606 httpclient: client,
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000607 }
mc862dad02019-08-06 20:52:51 +0000608
609 s.kafkaInit()
Dinesh Belwalkar41229602019-06-21 16:58:06 +0000610 go s.runServer()
611 go s.startgrpcserver()
mc862dad02019-08-06 20:52:51 +0000612
613 if pvmount != "" {
614 s.init_data_persistence()
615 }
616
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000617 quit := make(chan os.Signal, 10)
Dinesh Belwalkar8af8d7d2019-05-29 21:00:50 +0000618 signal.Notify(quit, os.Interrupt)
619
Dinesh Belwalkara6ba07d2020-01-10 23:22:34 +0000620 sig := <-quit
621 logrus.Infof("Shutting down:%d", sig)
622 s.kafkaCloseProducer()
623 s.close_data_files()
Dinesh Belwalkar01217962019-05-23 21:51:16 +0000624}