3 const each = require('async/each')
4 const eachLimit = require('async/eachLimit')
5 const values = require('lodash/values')
6 const mongoose = require('mongoose')
7 const waterfall = require('async/waterfall')
9 const constants = require('../initializers/constants')
10 const logger = require('../helpers/logger')
11 const requests = require('../helpers/requests')
13 const Pod = mongoose.model('Pod')
16 let lastRequestTimestamp = 0
18 // ---------------------------------------------------------------------------
20 const RequestSchema = mongoose.Schema({
21 request: mongoose.Schema.Types.Mixed,
24 enum: [ values(constants.REQUEST_ENDPOINTS) ]
28 type: mongoose.Schema.Types.ObjectId,
34 RequestSchema.statics = {
43 RequestSchema.pre('save', function (next) {
46 if (self.to.length === 0) {
47 Pod.listAllIds(function (err, podIds) {
48 if (err) return next(err)
51 if (podIds.length === 0) return
61 mongoose.model('Request', RequestSchema)
63 // ------------------------------ STATICS ------------------------------
65 function activate () {
66 logger.info('Requests scheduler activated.')
67 lastRequestTimestamp = Date.now()
70 timer = setInterval(function () {
71 lastRequestTimestamp = Date.now()
72 makeRequests.call(self)
73 }, constants.REQUESTS_INTERVAL)
76 function deactivate () {
77 logger.info('Requests scheduler deactivated.')
83 removeAll.call(this, function (err) {
84 if (err) logger.error('Cannot flush the requests.', { error: err })
88 function forceSend () {
89 logger.info('Force requests scheduler sending.')
90 makeRequests.call(this)
93 function list (callback) {
94 this.find({ }, callback)
97 function remainingMilliSeconds () {
98 if (timer === null) return -1
100 return constants.REQUESTS_INTERVAL - (Date.now() - lastRequestTimestamp)
103 // ---------------------------------------------------------------------------
105 // Make a requests to friends of a certain type
106 function makeRequest (toPod, requestEndpoint, requestsToMake, callback) {
107 if (!callback) callback = function () {}
111 encrypt: true, // Security
112 sign: true, // To prove our identity
114 path: '/api/' + constants.API_VERSION + '/remote/' + requestEndpoint,
115 data: requestsToMake // Requests we need to make
118 // Make multiple retry requests to all of pods
119 // The function fire some useful callbacks
120 requests.makeSecureRequest(params, function (err, res) {
121 if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) {
123 'Error sending secure request to %s pod.',
126 error: err || new Error('Status code not 20x : ' + res.statusCode)
130 return callback(false)
133 return callback(true)
137 // Make all the requests of the scheduler
138 function makeRequests () {
141 // We limit the size of the requests (REQUESTS_LIMIT)
142 // We don't want to stuck with the same failing requests so we get a random list
143 listWithLimitAndRandom.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
145 logger.error('Cannot get the list of requests.', { err: err })
149 // If there are no requests, abort
150 if (requests.length === 0) {
151 logger.info('No requests to make.')
155 logger.info('Making requests to friends.')
157 // We want to group requests by destinations pod and endpoint
158 const requestsToMakeGrouped = {}
160 requests.forEach(function (poolRequest) {
161 poolRequest.to.forEach(function (toPodId) {
162 const hashKey = toPodId + poolRequest.endpoint
163 if (!requestsToMakeGrouped[hashKey]) {
164 requestsToMakeGrouped[hashKey] = {
166 endpoint: poolRequest.endpoint,
167 ids: [], // pool request ids, to delete them from the DB in the future
168 datas: [] // requests data,
172 requestsToMakeGrouped[hashKey].ids.push(poolRequest._id)
173 requestsToMakeGrouped[hashKey].datas.push(poolRequest.request)
180 eachLimit(Object.keys(requestsToMakeGrouped), constants.REQUESTS_IN_PARALLEL, function (hashKey, callbackEach) {
181 const requestToMake = requestsToMakeGrouped[hashKey]
183 // FIXME: mongodb request inside a loop :/
184 Pod.load(requestToMake.toPodId, function (err, toPod) {
186 logger.error('Error finding pod by id.', { err: err })
187 return callbackEach()
190 // Maybe the pod is not our friend anymore so simply remove it
192 const requestIdsToDelete = requestToMake.ids
194 logger.info('Removing %d requests of unexisting pod %s.', requestIdsToDelete.length, requestToMake.toPodId)
195 removePodOf.call(self, requestIdsToDelete, requestToMake.toPodId)
196 return callbackEach()
199 makeRequest(toPod, requestToMake.endpoint, requestToMake.datas, function (success) {
200 if (success === true) {
201 logger.debug('Removing requests for %s pod.', requestToMake.toPodId, { requestsIds: requestToMake.ids })
203 goodPods.push(requestToMake.toPodId)
205 // Remove the pod id of these request ids
206 removePodOf.call(self, requestToMake.ids, requestToMake.toPodId, callbackEach)
208 badPods.push(requestToMake.toPodId)
214 // All the requests were made, we update the pods score
215 updatePodsScore(goodPods, badPods)
216 // Flush requests with no pod
217 removeWithEmptyTo.call(self)
222 // Remove pods with a score of 0 (too many requests where they were unreachable)
223 function removeBadPods () {
225 function findBadPods (callback) {
226 Pod.listBadPods(function (err, pods) {
228 logger.error('Cannot find bad pods.', { error: err })
232 return callback(null, pods)
236 function removeTheseBadPods (pods, callback) {
237 if (pods.length === 0) return callback(null, 0)
239 each(pods, function (pod, callbackEach) {
240 pod.remove(callbackEach)
242 return callback(err, pods.length)
245 ], function (err, numberOfPodsRemoved) {
247 logger.error('Cannot remove bad pods.', { error: err })
248 } else if (numberOfPodsRemoved) {
249 logger.info('Removed %d pods.', numberOfPodsRemoved)
251 logger.info('No need to remove bad pods.')
256 function updatePodsScore (goodPods, badPods) {
257 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
259 Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
260 if (err) logger.error('Cannot increment scores of good pods.')
263 Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
264 if (err) logger.error('Cannot decrement scores of bad pods.')
269 function listWithLimitAndRandom (limit, callback) {
272 self.count(function (err, count) {
273 if (err) return callback(err)
275 let start = Math.floor(Math.random() * count) - limit
276 if (start < 0) start = 0
278 self.find().sort({ _id: 1 }).skip(start).limit(limit).exec(callback)
282 function removeAll (callback) {
283 this.remove({ }, callback)
286 function removePodOf (requestsIds, podId, callback) {
287 if (!callback) callback = function () {}
289 this.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback)
292 function removeWithEmptyTo (callback) {
293 if (!callback) callback = function () {}
295 this.remove({ to: { $size: 0 } }, callback)