-
Notifications
You must be signed in to change notification settings - Fork 50
/
rest.api.js
318 lines (302 loc) · 10.8 KB
/
rest.api.js
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
/*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
var http = require('http'),
config = process.mainModule.exports.config,
logutils = require('../utils/log.utils'),
messages = require('./messages'),
appErrors = require('../errors/app.errors'),
util = require('util'),
commonUtils = require('../utils/common.utils'),
restler = require('restler'),
fs = require('fs'),
global = require('./global'),
httpsOp = require('./httpsoptions.api'),
request = require('request'),
discClient = require('./discoveryclient.api');
if (!module.parent) {
logutils.logger.warn(util.format(messages.warn.invalid_mod_call, module.filename));
process.exit(1);
}
/**
* Constructor to API server access.
* @param {Object} Parameters required to define a new API server
*/
function APIServer(params)
{
var self = this;
self.hostname = params.server;
self.port = params.port;
self.xml2jsSettings = params.xml2jsSettings || {};
self.isRawData = (null != params.isRawData) ? params.isRawData : false;
self.api = new self.API(self, params.apiName);
}
/**
* Authenticate and call the callback function on successful authentication.
* @param {Function} Callback function
*/
APIServer.prototype.authorize = function (callback)
{
var self = this;
// TODO: Implement Authentication.
self.cb(callback);
};
/**
* Constructor to API.
* @param {Object} API server object
* @param {String} Name of the API
*/
APIServer.prototype.API = function (self, apiName)
{
self.name = apiName;
return {
hostname:self.hostname,
port:self.port,
name:apiName,
get:function (url, callback, headers) {
var s = this,
obj = { url:s.hostname, path:url, method:'GET', port:s.port,
headers:headers, xml2jsSettings:self.xml2jsSettings };
self.makeCall(restler.get, obj, callback, false);
},
post:function (url, data, callback, headers) {
var s = this,
obj = { url:s.hostname, path:url, method:'POST', port:s.port,
data:data, headers:headers,
xml2jsSettings:self.xml2jsSettings};
self.makeCall(restler.post, obj, callback, false);
},
put:function (url, data, callback, headers) {
var s = this,
obj = { url:s.hostname, path:url, method:'PUT', port:s.port,
data:data, headers:headers,
xml2jsSettings:self.xml2jsSettings };
self.makeCall(restler.put, obj, callback, false);
},
delete:function (url, callback, headers) {
var s = this,
obj = { url:s.hostname, path:url, method:'DELETE', port:s.port,
headers:headers , xml2jsSettings:self.xml2jsSettings};
self.makeCall(restler.del, obj, callback, false);
}
};
};
/**
* Check if given callback is a function and call it.
* @param {Function} Callback function
*/
APIServer.prototype.cb = function (cb)
{
if (typeof cb == 'function') {
cb();
}
};
/**
* Update the host/port from discovery server response
* @param {params} {object} Parameters
*/
APIServer.prototype.updateDiscoveryServiceParams = function (params)
{
var server = null;
var self = this;
var apiServerType = self.name;
var discService = null;
if (false == config.serviceEndPointFromConfig) {
/* Do not update through Discovery */
switch(apiServerType) {
case global.label.VNCONFIG_API_SERVER:
case global.label.OPS_API_SERVER:
case global.label.API_SERVER:
case global.label.OPSERVER:
return params;
default:
break;
}
}
discService = discClient.getDiscServiceByApiServerType(apiServerType);
if (discService) {
/* We are sending only the first IP */
if (discService['ip-address'] != null) {
params.url = discService['ip-address'];
}
if (discService['port'] != null) {
params.port = discService['port'];
}
}
return params;
}
/**
* Make a https call to server.
* @param {options} {object} Parameters
* @param {callback} {function} Callback function once response comes
* from Server
*/
APIServer.prototype.makeHttpsRestCall = function (options, callback)
{
request(options, function(err, response, data) {
callback(err, data, response);
});
}
/** Retry the REST API Call, once it fails
* @param {err} {object} error object got from previous error response
* @param {restApi} {function} restler API based on method
* @param {params} {object} Parameters
* @param {response} {object} Response Object
* @param {callback} {function} Callback function once response comes
* from Server
* @param {isRetry} {bool} boolean flag if it is already a retry call
*/
APIServer.prototype.retryMakeCall = function(err, restApi, params,
response, callback, isRetry)
{
var self = this;
/* Check if the error code is ECONNREFUSED or ETIMEDOUT, if yes then
* issue once again discovery subscribe request, the remote server
* may be down, so discovery server should send the Up Servers now
*/
if ((true == process.mainModule.exports['discServEnable']) &&
(('ECONNREFUSED' == err.code) || ('ETIMEDOUT' == err.code))) {
if (false == isRetry) {
/* Only one time send a retry */
discClient.sendDiscSubMessageOnDemand(self.name);
}
var reqParams = null;
reqParams = discClient.resetServicesByParams(params, self.name);
if (null != reqParams) {
return self.makeCall(restApi, reqParams, callback, true);
}
}
error = new appErrors.RESTServerError(util.format(err));
error['custom'] = true;
error['responseCode'] = ((null != response) &&
(null != response.statusCode)) ?
response.statusCode :
global.HTTP_STATUS_INTERNAL_ERROR;
error['code'] = err.code;
callback(error, '', response);
}
/**
* Send the parsed response data to APP
* @param {data} {object} response data either in xml/json format
* @param {xml2jsSettings} {object} config for xml2js knob
* @param {response} {object} response object
* @param {callback} {function} Callback function to call once data parsing is done
*/
APIServer.prototype.sendParsedDataToApp = function(data, xml2jsSettings,
response, callback)
{
if (true == this.isRawData) {
callback(null, data, response);
return;
}
/* Data is xml/json format */
restler.parsers.xml(data, function(err, xml2JsonData) {
if (err) {
/* This MUST be a JSON response, response can be
* JSON.stringify (if auto), else parsed if (json)
*/
try {
var JSONData = JSON.parse(data);
callback(null, JSONData, response);
} catch(e) {
callback(null, data, response);
}
} else {
/* XML Response */
callback(null, xml2JsonData, response);
}
}, xml2jsSettings);
}
/**
* Make a call to API server.
* @param {restApi} {function} restler API based on method
* @param {params} {object} Parameters
* @param {callback} {function} Callback function once response comes
from API Server
*/
APIServer.prototype.makeCall = function (restApi, params, callback, isRetry)
{
var self = this;
var reqUrl = null;
var options = {};
var method = params['method'];
var xml2jsSettings = params['xml2jsSettings'];
options['headers'] = params['headers'] || {};
options['method'] = method;
options['headers']['Content-Length'] = (data) ? data.toString().length : 0;
if ((method == 'POST') || (method == 'PUT')) {
/* When we need to send the data along with options (POST/PUT)
we need to specify the Content-Type as App/JSON with JSON.stringify
of the data, otherwise, restler treats it as
application/x-www-form-urlencoded as Content-Type and encodes
the data accordingly. Restler also changes Content-Type when
an empty data object is passed for GET queries, so make sure
we are don't pass it.
*/
var data = commonUtils.getApiPostData(params['path'], params['data']);
options['data'] = data || {};
options['headers']['Content-Type'] = 'application/json';
}
params = self.updateDiscoveryServiceParams(params);
options['parser'] = restler.parsers.auto;
options = httpsOp.updateHttpsSecureOptions(self.name, options);
if ((null != options['headers']) &&
(null != options['headers']['protocol']) &&
(global.PROTOCOL_HTTPS == options['headers']['protocol'])) {
delete options['headers']['protocol'];
reqUrl = global.HTTPS_URL + params.url + ':' + params.port + params.path;
options['uri'] = reqUrl;
options['body'] = options['data'];
if (('POST' != method) && ('PUT' != method)) {
delete options['data'];
delete options['body'];
}
self.makeHttpsRestCall(options, function(err, data, response) {
if (null != err) {
try {
logutils.logger.error('URL [' + reqUrl + ']' +
' returned error [' +
JSON.stringify(err) + ']');
} catch(e) {
logutils.logger.error('URL [' + reqUrl + ']' +
' returned error [' + err + ']');
}
self.retryMakeCall(err, restApi, params, response, callback, false);
} else {
self.sendParsedDataToApp(data, xml2jsSettings, response,
callback);
}
});
return;
}
reqUrl = global.HTTP_URL + params.url + ':' + params.port + params.path;
if (null != options['headers']) {
delete options['headers']['protocol'];
delete options['headers']['noRedirectToLogout'];
}
restApi(reqUrl, options).on('complete', function(data, response) {
if (data instanceof Error ||
parseInt(response.statusCode) >= 400) {
try {
logutils.logger.error('URL [' + reqUrl + ']' +
' returned error [' + JSON.stringify(data) + ']');
} catch(e) {
logutils.logger.error('URL [' + reqUrl + ']' +
' returned error [' + data + ']');
}
self.retryMakeCall(data, restApi, params, response, callback, false);
} else {
self.sendParsedDataToApp(data, xml2jsSettings, response, callback);
}
});
}
// Export this as a module.
module.exports.getAPIServer = function (params)
{
return new APIServer(params);
};
// Export this as a module.
module.exports.getSOAPApiServer= function (params)
{
return new APIServer(params);
};