-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathgroupRegistryMongoDB.js
More file actions
326 lines (287 loc) · 10.6 KB
/
groupRegistryMongoDB.js
File metadata and controls
326 lines (287 loc) · 10.6 KB
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/*
* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of fiware-iotagent-lib
*
* fiware-iotagent-lib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* fiware-iotagent-lib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with fiware-iotagent-lib.
* If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::daniel.moranjimenez@telefonica.com
*
* Modified by: Daniel Calvo - ATOS Research & Innovation
*/
const logger = require('logops');
const dbService = require('../../model/dbConn');
const intoTrans = require('../common/domain').intoTrans;
const fillService = require('./../common/domain').fillService;
const alarmsInt = require('../common/alarmManagement').intercept;
const constants = require('../../constants');
const errors = require('../../errors');
const Group = require('../../model/Group');
const async = require('async');
let context = {
op: 'IoTAgentNGSI.MongoDBGroupRegister'
};
const attributeList = [
'url',
'resource',
'apikey',
'type',
'endpoint',
'transport',
'service',
'subservice',
'description',
'trust',
'cbHost',
'timezone',
'timestamp',
'commands',
'lazy',
'attributes',
'staticAttributes',
'internalAttributes',
'autoprovision',
'explicitAttrs',
'expressionLanguage',
'defaultEntityNameConjunction',
'ngsiVersion',
'entityNameExp',
'payloadType'
];
/**
* Generates a handler for the save device group operations. The handler will take the customary error and the saved
* device group as the parameters (and pass the serialized DAO as the callback value).
*
* @return {Function} The generated handler.
*/
function saveGroupHandler(groupDAO, callback) {
/* eslint-disable-next-line no-unused-vars */
return function saveHandler(error, result) {
if (error) {
logger.debug(fillService(context, groupDAO), 'Error storing device group information: %s', error);
callback(new errors.InternalDbError(error));
} else {
callback(null, groupDAO.toObject());
}
};
}
function createGroup(group, callback) {
/* eslint-disable-next-line new-cap */
const groupObj = new Group.model();
attributeList.forEach((key) => {
groupObj[key] = group[key];
});
logger.debug(
context,
'Storing device group with id [%s], type [%s], apikey [%s] and resource [%s]',
groupObj._id,
groupObj.type,
groupObj.apikey,
groupObj.resource
);
groupObj.save(function saveHandler(error, groupDAO) {
if (error) {
if (error.code === 11000) {
logger.debug(
context,
'Duplicate group entry with resource [%s] and apiKey [%s]',
group.resource,
group.apikey
);
callback(new errors.DuplicateGroup(group));
} else {
logger.debug(context, 'Error storing device group information: %s', error);
callback(new errors.InternalDbError(error));
}
} else {
callback(null, groupDAO.toObject());
}
});
}
/**
* List all the groups created in the IoT Agent.
*
* @param {Number} service Service for wich all the configurations want to be retrieved.
* @param {Number} limit Maximum number of entries to return.
* @param {Number} offset Number of entries to skip for pagination.
*/
function listGroups(service, limit, offset, callback) {
const condition = {};
function toObjectFn(obj) {
return obj.toObject();
}
if (service) {
condition.service = service;
}
const query = Group.model.find(condition).sort();
if (limit) {
query.limit(parseInt(limit, 10));
}
if (offset) {
query.skip(parseInt(offset, 10));
}
async.series(
[query.exec.bind(query), Group.model.countDocuments.bind(Group.model, condition)],
function (error, results) {
callback(error, {
count: results[1],
services: results[0].map(toObjectFn)
});
}
);
}
function getById(id, callback) {
context = fillService(context, { service: 'n/a', subservice: 'n/a' });
logger.debug(context, 'Looking for device group with id [%s].', id);
const query = Group.model.findOne({ _id: id });
query.select({ __v: 0 });
query.lean().exec(function handleGet(error, data) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting group: %s', error);
callback(new errors.InternalDbError(error));
} else if (data) {
context = fillService(context, data);
logger.debug(context, 'Device group data found: %j', data);
callback(null, data);
} else {
logger.debug(context, 'Device group [%s] not found.', id);
callback(new errors.DeviceGroupNotFound(id));
}
});
}
/**
* List all the groups created in the IoT Agent for a service and a subservice.
*
* @param {String} service Service used to filter the groups.
* @param {String} subservice Subservice used to filter the groups.
* @param {Function} callback The callback function.
*/
function find(service, subservice, callback) {
const condition = {};
function toObjectFn(obj) {
return obj.toObject();
}
condition.service = service;
condition.subservice = subservice;
const query = Group.model.find(condition).sort();
async.series(
[query.exec.bind(query), Group.model.countDocuments.bind(Group.model, condition)],
function (error, results) {
callback(error, {
count: results[1],
services: results[0].map(toObjectFn)
});
}
);
}
function findOneInMongoDB(queryObj, fields, callback) {
const query = Group.model.findOne({
$or: [{ apikey: queryObj.apikey }, { type: queryObj.type }]
});
query.select({ __v: 0 });
query.lean().exec(function handleGet(error, data) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting group: %s', error);
callback(new errors.InternalDbError(error));
} else if (data) {
context = fillService(context, data);
queryObj.resource = data.resource;
logger.debug(context, 'Device group data found: %j', data);
callback(null, data);
} else {
logger.debug(context, 'Device group for fields [%j] not found: [%j]', fields, queryObj);
callback(new errors.DeviceGroupNotFound(fields, queryObj));
}
});
}
function findBy(fields) {
return function () {
const queryObj = {};
let i = 0;
/* eslint-disable prefer-rest-params */
while (typeof arguments[i] !== 'function') {
if (arguments[i]) {
queryObj[fields[i]] = arguments[i];
}
i++;
}
const callback = arguments[i];
/* eslint-enable prefer-rest-params */
context = fillService(context, { service: 'n/a', subservice: 'n/a' });
logger.debug(context, 'Looking for group params %j with queryObj %j', fields, queryObj);
findOneInMongoDB(queryObj, fields, callback);
};
}
function update(id, body, callback) {
logger.debug(context, 'Storing updated values for configuration [%s]:\n%s', id, JSON.stringify(body, null, 4));
getById(id, function (error, group) {
if (error) {
callback(error);
} else {
attributeList.forEach((key) => {
if (body[key] !== undefined) {
group[key] = body[key];
}
});
/* eslint-disable-next-line new-cap */
const groupObj = new Group.model(group);
groupObj.isNew = false;
groupObj.save(saveGroupHandler(groupObj, callback));
}
});
}
function remove(id, callback) {
logger.debug(context, 'Removing device group with id [%s]', id);
getById(id, function (error, deviceGroup) {
if (error) {
callback(error);
} else {
Group.model.deleteOne({ _id: id }, function (error) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);
callback(new errors.InternalDbError(error));
} else {
logger.debug(context, 'Device [%s] successfully removed.', id);
callback(null, deviceGroup);
}
});
}
});
}
function init(newConfig, callback) {
callback(null);
}
function clear(callback) {
dbService.db.db.dropDatabase(callback);
}
exports.create = alarmsInt(constants.MONGO_ALARM + '_01', intoTrans(context, createGroup));
exports.list = alarmsInt(constants.MONGO_ALARM + '_02', intoTrans(context, listGroups));
exports.init = alarmsInt(constants.MONGO_ALARM + '_03', intoTrans(context, init));
exports.find = alarmsInt(constants.MONGO_ALARM + '_04', intoTrans(context, find));
exports.findType = alarmsInt(
constants.MONGO_ALARM + '_05',
intoTrans(context, findBy(['service', 'subservice', 'type', 'apikey']))
);
exports.findTypeSilently = intoTrans(context, findBy(['service', 'subservice', 'type', 'apikey']));
exports.findSilently = intoTrans(context, findBy(['service', 'subservice', 'apikey']));
exports.findBy = alarmsInt(constants.MONGO_ALARM + '_06', intoTrans(context, findBy));
exports.get = alarmsInt(constants.MONGO_ALARM + '_07', intoTrans(context, findBy(['resource', 'apikey'])));
exports.getSilently = intoTrans(context, findBy(['resource', 'apikey']));
exports.getType = alarmsInt(constants.MONGO_ALARM + '_08', intoTrans(context, findBy(['type'])));
exports.getTypeSilently = intoTrans(context, findBy(['type']));
exports.update = alarmsInt(constants.MONGO_ALARM + '_09', intoTrans(context, update));
exports.remove = alarmsInt(constants.MONGO_ALARM + '_10', intoTrans(context, remove));
exports.clear = alarmsInt(constants.MONGO_ALARM + '_11', intoTrans(context, clear));