5ab48ab0be92ee5b1007f9588a25484160fcb241
[ric-plt/xapp-frame.git] / pkg / xapp / xapp.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 AT&T Intellectual Property.
4   Copyright (c) 2019 Nokia
5
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9
10        http://www.apache.org/licenses/LICENSE-2.0
11
12    Unless required by applicable law or agreed to in writing, software
13    distributed under the License is distributed on an "AS IS" BASIS,
14    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    See the License for the specific language governing permissions and
16    limitations under the License.
17 ==================================================================================
18 */
19
20 package xapp
21
22 import (
23         "fmt"
24         "github.com/spf13/viper"
25         "net/http"
26         "os"
27         "os/signal"
28         "sync/atomic"
29         "syscall"
30         "time"
31 )
32
33 type ReadyCB func(interface{})
34 type ShutdownCB func()
35
36 var (
37         // XApp is an application instance
38         Rmr           *RMRClient
39         Sdl           *SDLClient
40         Rnib          *RNIBClient
41         Resource      *Router
42         Metric        *Metrics
43         Logger        *Log
44         Config        Configurator
45         Subscription  *Subscriber
46         Alarm         *AlarmClient
47         readyCb       ReadyCB
48         readyCbParams interface{}
49         shutdownCb    ShutdownCB
50         shutdownFlag  int32
51         shutdownCnt   int32
52 )
53
54 func IsReady() bool {
55         return Rmr != nil && Rmr.IsReady() && Sdl != nil && Sdl.IsReady()
56 }
57
58 func SetReadyCB(cb ReadyCB, params interface{}) {
59         readyCb = cb
60         readyCbParams = params
61 }
62
63 func XappReadyCb(params interface{}) {
64         Alarm = NewAlarmClient(viper.GetString("moId"), viper.GetString("name"))
65         if readyCb != nil {
66                 readyCb(readyCbParams)
67         }
68 }
69
70 func SetShutdownCB(cb ShutdownCB) {
71         shutdownCb = cb
72 }
73
74 func InstallSignalHandler() {
75         //
76         // Signal handlers to really exit program.
77         // shutdownCb can hang until application has
78         // made all needed gracefull shutdown actions
79         // hardcoded limit for shutdown is 20 seconds
80         //
81         interrupt := make(chan os.Signal, 1)
82         signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
83         //signal handler function
84         go func() {
85                 for range interrupt {
86                         if atomic.CompareAndSwapInt32(&shutdownFlag, 0, 1) {
87                                 // close function
88                                 go func() {
89                                         timeout := int(20)
90                                         sentry := make(chan struct{})
91                                         defer close(sentry)
92
93                                         // close callback
94                                         go func() {
95                                                 if shutdownCb != nil {
96                                                         shutdownCb()
97                                                 }
98                                                 sentry <- struct{}{}
99                                         }()
100                                         select {
101                                         case <-time.After(time.Duration(timeout) * time.Second):
102                                                 Logger.Info("xapp-frame shutdown callback took more than %d seconds", timeout)
103                                         case <-sentry:
104                                                 Logger.Info("xapp-frame shutdown callback handled within %d seconds", timeout)
105                                         }
106                                         os.Exit(0)
107                                 }()
108                         } else {
109                                 newCnt := atomic.AddInt32(&shutdownCnt, 1)
110                                 Logger.Info("xapp-frame shutdown already ongoing. Forced exit counter %d/%d ", newCnt, 5)
111                                 if newCnt >= 5 {
112                                         Logger.Info("xapp-frame shutdown forced exit")
113                                         os.Exit(0)
114                                 }
115                                 continue
116                         }
117
118                 }
119         }()
120 }
121
122 func init() {
123         // Load xapp configuration
124         Logger = LoadConfig()
125
126         Logger.SetLevel(viper.GetInt("controls.logger.level"))
127         Resource = NewRouter()
128         Config = Configurator{}
129         Metric = NewMetrics(viper.GetString("metrics.url"), viper.GetString("metrics.namespace"), Resource.router)
130         Subscription = NewSubscriber(viper.GetString("subscription.host"), viper.GetInt("subscription.timeout"))
131         Sdl = NewSDLClient(viper.GetString("db.namespace"))
132         Rnib = NewRNIBClient()
133
134         InstallSignalHandler()
135 }
136
137 func RunWithParams(c MessageConsumer, sdlcheck bool) {
138         Rmr = NewRMRClient()
139         Rmr.SetReadyCB(XappReadyCb, nil)
140
141         host := fmt.Sprintf(":%d", GetPortData("http").Port)
142         go http.ListenAndServe(host, Resource.router)
143         Logger.Info(fmt.Sprintf("Xapp started, listening on: %s", host))
144         if sdlcheck {
145                 Sdl.TestConnection()
146         }
147         Rmr.Start(c)
148 }
149
150 func Run(c MessageConsumer) {
151         RunWithParams(c, true)
152 }