-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
283 lines (237 loc) · 9.23 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// This file is part of the eliona project.
// Copyright © 2022 LEICOM iTEC AG. All Rights Reserved.
// ______ _ _
// | ____| (_)
// | |__ | |_ ___ _ __ __ _
// | __| | | |/ _ \| '_ \ / _` |
// | |____| | | (_) | | | | (_| |
// |______|_|_|\___/|_| |_|\__,_|
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package main
import (
"coffeecloud/apiserver"
"coffeecloud/apiservices"
"coffeecloud/coffeecloud"
"coffeecloud/conf"
"coffeecloud/eliona"
"context"
"fmt"
"github.com/eliona-smart-building-assistant/go-eliona/app"
"github.com/eliona-smart-building-assistant/go-utils/db"
"net/http"
"strconv"
"time"
"github.com/eliona-smart-building-assistant/go-utils/common"
utilshttp "github.com/eliona-smart-building-assistant/go-utils/http"
"github.com/eliona-smart-building-assistant/go-utils/log"
)
func initialization() {
ctx := context.Background()
// Necessary to close used init resources
conn := db.NewInitConnectionWithContextAndApplicationName(ctx, app.AppName())
defer conn.Close(ctx)
// Init the app before the first run.
app.Init(conn, app.AppName(),
app.ExecSqlFile("conf/init.sql"),
eliona.Init,
)
}
func collectData() {
configs, err := conf.GetConfigs(context.Background())
if err != nil {
log.Fatal("conf", "couldn't read configs from DB: %v", err)
return
}
if len(configs) == 0 {
log.Info("conf", "no configs in DB")
return
}
for _, config := range configs {
// Skip config if disabled and set inactive
if !conf.IsConfigEnabled(config) {
if conf.IsConfigActive(config) {
_, err := conf.SetConfigActiveState(context.Background(), config, false)
if err != nil {
log.Fatal("conf", "couldn't set config active state to DB: %v", err)
return
}
}
continue
}
// Signals that this config is active
if !conf.IsConfigActive(config) {
_, err := conf.SetConfigActiveState(context.Background(), config, true)
if err != nil {
log.Fatal("conf", "couldn't set config active state to DB: %v", err)
return
}
log.Info("conf", "collecting initialized with Configuration %d:\n"+
"Enable: %t\n"+
"Refresh Interval: %d\n"+
"Request Timeout: %d\n"+
"Active: %t\n"+
"Project IDs: %v\n",
*config.Id,
*config.Enable,
config.RefreshInterval,
*config.RequestTimeout,
*config.Active,
*config.ProjectIDs)
}
common.RunOnceWithParam(func(config apiserver.Configuration) {
log.Info("main", "collecting %d started", *config.Id)
groups, err := collectGroupedMachines(config)
if err != nil {
log.Error("coffeecloud", "error collection machines: %v", err)
return
} else {
err = sendGroupedMachinesAndData(config, groups)
if err != nil {
log.Error("coffeecloud", "error sending assets and data: %v", err)
return
} else {
log.Info("main", "collecting %d successful finished", *config.Id)
}
}
time.Sleep(time.Second * time.Duration(config.RefreshInterval))
}, config, *config.Id)
}
}
func sendGroupedMachinesAndData(config apiserver.Configuration, groups []eliona.MachineGroup) error {
if config.ProjectIDs == nil || len(*config.ProjectIDs) == 0 {
log.Info("eliona", "No project id defined in configuration %d. No data is send to Eliona.", config.Id)
return nil
}
for _, projectId := range *config.ProjectIDs {
rootAssetId, err := createAssetFirstTime(*config.Id, projectId, eliona.CoffeeCloudRootAssetType, nil, eliona.CoffeeCloudRootAssetType, "CoffeeCloud")
if err != nil {
return fmt.Errorf("create root asset first time: %w", err)
}
for _, group := range groups {
groupAssetId, err := createAssetFirstTime(*config.Id, projectId, eliona.CoffeeCloudGroupAssetType+"_"+group.GroupID, &rootAssetId, eliona.CoffeeCloudGroupAssetType, group.GroupName)
if err != nil {
return fmt.Errorf("create group asset first time: %w", err)
}
for _, machine := range group.Machines {
machineAssetId, err := createAssetFirstTime(*config.Id, projectId, eliona.CoffeeCloudMachineAssetType+"_"+machine.MachineID, &groupAssetId, eliona.CoffeeCloudMachineAssetType, machine.MachineName)
if err != nil {
return fmt.Errorf("create machine asset first time: %w", err)
}
err = eliona.UpsertData(machineAssetId, eliona.CoffeeCloudMachineAssetType, machine)
if err != nil {
return fmt.Errorf("upserting machine data: %w", err)
}
}
}
}
return nil
}
func collectGroupedMachines(config apiserver.Configuration) ([]eliona.MachineGroup, error) {
var eliGroups []eliona.MachineGroup
ccToken, err := coffeecloud.GetAuthToken(config.Url, config.Username, config.Password, time.Duration(*config.RequestTimeout)*time.Second)
if err != nil {
return eliGroups, fmt.Errorf("getting access token: %w", err)
}
if ccToken == nil {
return eliGroups, fmt.Errorf("no access token received: %w", err)
}
ccGroups, err := coffeecloud.GetGroups(config.Url, config.ApiKey, *ccToken, time.Duration(*config.RequestTimeout)*time.Second)
if err != nil {
return eliGroups, fmt.Errorf("getting groups: %w", err)
}
for _, ccGroup := range ccGroups {
log.Debug("coffeecloud", "found group %s", ccGroup.Name)
eliGroup := eliona.MachineGroup{
GroupID: strconv.Itoa(int(ccGroup.ID)),
GroupName: ccGroup.Name,
}
shouldUse, err := eliona.AdheresToFilter(eliGroup, config.AssetFilter)
if err != nil {
return eliGroups, fmt.Errorf("filtering group %s: %w", eliGroup.GroupName, err)
}
if !shouldUse {
continue
}
ccMachines, err := coffeecloud.GetMachines(config.Url, config.ApiKey, *ccToken, ccGroup.ID, time.Duration(*config.RequestTimeout)*time.Second)
if err != nil {
return eliGroups, fmt.Errorf("getting machines: %w", err)
}
ccMachineErrors, err := coffeecloud.GetMachineErrors(config.Url, config.ApiKey, *ccToken, ccGroup.ID, time.Duration(*config.RequestTimeout)*time.Second)
if err != nil {
return eliGroups, fmt.Errorf("getting machine errors: %w", err)
}
ccHealthStatuses, err := coffeecloud.GetHealthStatuses(config.Url, config.ApiKey, *ccToken, ccGroup.ID, time.Duration(*config.RequestTimeout)*time.Second)
if err != nil {
return eliGroups, fmt.Errorf("getting health statuses: %w", err)
}
for serialNumber, ccMachine := range ccMachines {
log.Debug("coffeecloud", "found machine %s", ccMachine.MachineName)
eliMachine := eliona.Machine{
MachineID: ccMachine.ID,
MachineName: ccMachine.MachineName,
SerialNumber: serialNumber,
Firmware: ccMachine.Origin.Firmware,
CupCount: ccMachine.NumberOfCups,
HoursSinceCleaned: ccMachine.HoursSinceClean,
}
if ccMachineError, exists := ccMachineErrors[serialNumber]; exists {
eliMachine.ErrorCode = ccMachineError.ErrorCode
eliMachine.ErrorText = ccMachineError.Error
eliMachine.ErrorDescription = ccMachineError.ErrorShort
}
if ccHealthyStatus, exists := ccHealthStatuses[serialNumber]; exists {
eliMachine.EngineStatus = ccHealthyStatus.HealthStatus
}
shouldUse, err = eliona.AdheresToFilter(eliMachine, config.AssetFilter)
if err != nil {
return eliGroups, fmt.Errorf("filtering machine %s: %w", eliMachine.MachineName, err)
}
if !shouldUse {
continue
}
eliGroup.Machines = append(eliGroup.Machines, eliMachine)
}
eliGroups = append(eliGroups, eliGroup)
}
return eliGroups, nil
}
func createAssetFirstTime(configId int64, projectId string, identifier string, parentId *int32, assetType string, name string) (int32, error) {
uniqueIdentifier := assetType + "_" + identifier
ctx := context.Background()
// check if asset already exists in app
assetId, err := conf.GetAssetId(ctx, configId, projectId, uniqueIdentifier)
if err != nil {
return 0, fmt.Errorf("get asset id for %s in app: %w", uniqueIdentifier, err)
}
// if not, create asset in Eliona also
if assetId == nil {
log.Debug("assets", "no asset id found for %s", uniqueIdentifier)
assetId, err = eliona.UpsertAsset(projectId, uniqueIdentifier, parentId, assetType, name)
if err != nil || assetId == nil {
return 0, fmt.Errorf("upserting root asset %s in Eliona: %w", uniqueIdentifier, err)
}
err = conf.InsertAsset(ctx, configId, *assetId, projectId, uniqueIdentifier)
if err != nil {
return 0, fmt.Errorf("insert asset %s in app: %w", uniqueIdentifier, err)
}
log.Debug("assets", "asset created for %s with id %d", uniqueIdentifier, *assetId)
} else {
log.Debug("assets", "asset already created for %s with id %d", uniqueIdentifier, *assetId)
}
return *assetId, nil
}
func listenApi() {
err := http.ListenAndServe(":"+common.Getenv("API_SERVER_PORT", "3000"), utilshttp.NewCORSEnabledHandler(
apiserver.NewRouter(
apiserver.NewConfigurationAPIController(apiservices.NewConfigurationApiService()),
apiserver.NewVersionAPIController(apiservices.NewVersionApiService()),
apiserver.NewCustomizationAPIController(apiservices.NewCustomizationApiService()),
)),
)
log.Fatal("main", "API server: %v", err)
}