83e841e6263829ccf9d47cb6d5c3fb03e7093716
[osm/UI.git] / skyquake / plugins / accounts / api / accounts.js
1 /*
2 *
3 * Copyright 2016 RIFT.IO Inc
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 var request = require('request');
20 var Promise = require('bluebird');
21 var rp = require('request-promise');
22 var utils = require('../../../framework/core/api_utils/utils.js');
23 var constants = require('../../../framework/core/api_utils/constants.js');
24 var _ = require('underscore');
25 var Cloud = require('./cloud_account/cloudAccount')
26 var Sdn = require('./sdn_account/sdnAccount')
27 var ConfigAgent = require('./config_agent/configAgent')
28 var Accounts = {};
29 var nameSpace = {
30 cloud: 'cloud',
31 sdn: 'sdn-account',
32 'config-agent': 'config-agent'
33 };
34 Accounts.get = function(req) {
35 return new Promise(function(resolve, reject) {
36 if (req.params.type || req.params.name) {
37 getAccount(req)
38 .then(function(data) {
39 resolve({
40 statusCode: 200,
41 data: Object.assign(data, {
42 type: req.params.type
43 })
44 });
45 }, function(reason) {
46 reject(reason);
47 })
48 } else {
49 getAll(req, resolve, reject);
50 }
51 });
52
53 function getAll(req, resolve, reject) {
54 Promise.all([
55 Cloud.get(req),
56 Sdn.get(req),
57 ConfigAgent.get(req)
58 ]).then(function(result) {
59 var ReturnData = {
60 cloud: result[0],
61 sdn: result[1],
62 'config-agent': result[2]
63 };
64 ReturnData.cloud.type = 'cloud';
65 ReturnData.sdn.type = 'sdn';
66 ReturnData['config-agent'].type = 'config';
67 resolve({
68 statusCode: 200,
69 data: ReturnData
70 });
71 }, function(reason) {
72 reject(reason);
73 })
74 }
75 }
76
77 Accounts.update = updateAccount;
78 Accounts.create = updateAccount;
79 Accounts.delete = deleteAccount;
80 Accounts.refreshAccountConnectionStatus = refreshAccountConnectionStatus
81 function getAccount(req) {
82 return new Promise(function(resolve, reject) {
83 var self = this;
84 var api_server = req.query["api_server"];
85 var id = req.params.id || req.params.name;
86 var requestHeaders = {};
87 var type = nameSpace[req.params.type];
88 var url = utils.confdPort(api_server) + '/api/operational/' + type;
89 //SDN model doesn't follow convention
90 if (type != 'sdn-account') {
91 url += '/account';
92 }
93 if (id) {
94 url += '/' + id;
95 }
96
97 _.extend(
98 requestHeaders,
99 id ? constants.HTTP_HEADERS.accept.data : constants.HTTP_HEADERS.accept.collection, {
100 'Authorization': req.get('Authorization')
101 }
102 );
103
104 request({
105 url: url + '?deep',
106 type: 'GET',
107 headers: requestHeaders,
108 forever: constants.FOREVER_ON,
109 rejectUnauthorized: false
110 },
111 function(error, response, body) {
112 var data;
113 var objKey = 'rw-' + type + ':account';
114 //SDN model doesn't follow convention
115 if (type == 'sdn-account') {
116 objKey = 'rw-sdn:sdn-account';
117 }
118 if (utils.validateResponse(type.toUpperCase() + '.get', error, response, body, resolve, reject)) {
119 try {
120 data = JSON.parse(response.body);
121 if (!id) {
122 data = data.collection;
123 }
124
125 data = data[objKey]
126 } catch (e) {
127 console.log('Problem with "' + type.toUpperCase() + '.get"', e);
128 var err = {};
129 err.statusCode = 500;
130 err.errorMessage = {
131 error: 'Problem with "' + type.toUpperCase() + '.get": ' + e
132 }
133 return reject(err);
134 }
135 return resolve({
136 statusCode: response.statusCode,
137 data: data
138 });
139 };
140 });
141 });
142 }
143
144 function updateAccount(req) {
145 var self = this;
146 var id = req.params.id || req.params.name;
147 var api_server = req.query["api_server"];
148 var type = nameSpace[req.params.type];
149 var data = req.body;
150 var requestHeaders = {};
151 var createData = {};
152 var url = utils.confdPort(api_server) + '/api/config/' + type;
153 var method = 'POST'
154 if (!id) {
155 if (type == 'sdn-account') {
156 createData = {
157 'sdn-account': Array.isArray(data) ? data : [data]
158 }
159 } else {
160 createData = {
161 'account': Array.isArray(data) ? data : [data]
162 }
163 }
164 console.log('Creating ' + type + ' account: ', createData);
165 } else {
166 method = 'PUT';
167 if (type == 'sdn-account') {
168 url += '/' + id;
169 createData['rw-sdn:sdn-account'] = Array.isArray(data) ? data : [data];
170
171 } else {
172 url += '/account/' + id;
173 createData['rw-' + type + ':account'] = Array.isArray(data) ? data : [data];
174 }
175 //createData = createData[0];
176 }
177
178
179
180 return new Promise(function(resolve, reject) {
181 _.extend(requestHeaders,
182 constants.HTTP_HEADERS.accept.data,
183 constants.HTTP_HEADERS.content_type.data, {
184 'Authorization': req.get('Authorization')
185 });
186 request({
187 url: url,
188 method: method,
189 headers: requestHeaders,
190 forever: constants.FOREVER_ON,
191 rejectUnauthorized: false,
192 json: createData,
193 }, function(error, response, body) {
194 if (utils.validateResponse(type.toUpperCase() + '.' + method, error, response, body, resolve, reject)) {
195 return resolve({
196 statusCode: response.statusCode,
197 data: JSON.stringify(response.body)
198 });
199 };
200 });
201 })
202 }
203
204 function deleteAccount(req) {
205 var self = this;
206 var id = req.params.id || req.params.name;
207 var api_server = req.query["api_server"];
208 var type = nameSpace[req.params.type];
209 var data = req.body;
210 var requestHeaders = {};
211 var createData = {};
212 var url = utils.confdPort(api_server) + '/api/config/' + type;
213 if (type == 'sdn-account') {
214 url += '/' + id;
215 } else {
216 url += '/account/' + id;
217 }
218 return new Promise(function(resolve, reject) {
219 _.extend(requestHeaders,
220 constants.HTTP_HEADERS.accept.data,
221 constants.HTTP_HEADERS.content_type.data, {
222 'Authorization': req.get('Authorization')
223 });
224 request({
225 url: url,
226 method: 'DELETE',
227 headers: requestHeaders,
228 forever: constants.FOREVER_ON,
229 rejectUnauthorized: false,
230 }, function(error, response, body) {
231 if (utils.validateResponse(type.toUpperCase() + '.DELETE', error, response, body, resolve, reject)) {
232 return resolve({
233 statusCode: response.statusCode,
234 data: JSON.stringify(response.body)
235 });
236 };
237 });
238 })
239 }
240
241 function refreshAccountConnectionStatus (req) {
242 var api_server = req.query['api_server'];
243 var Name = req.params.name;
244 var Type = req.params.type;
245 var jsonData = {
246 input: {}
247 };
248 var rpcInfo = {
249 sdn: {
250 label: 'sdn-account',
251 rpc: 'update-sdn-status'
252 },
253 'config': {
254 label: 'cfg-agent-account',
255 rpc: 'update-cfg-agent-status'
256 },
257 cloud: {
258 label: 'cloud-account',
259 rpc: 'update-cloud-status'
260 }
261 }
262 jsonData.input[rpcInfo[Type].label] = Name;
263 var headers = _.extend({},
264 constants.HTTP_HEADERS.accept.data,
265 constants.HTTP_HEADERS.content_type.data, {
266 'Authorization': req.get('Authorization')
267 }
268 );
269 return new Promise(function(resolve, reject) {
270
271 request({
272 uri: utils.confdPort(api_server) + '/api/operations/' + rpcInfo[Type].rpc,
273 method: 'POST',
274 headers: headers,
275 forever: constants.FOREVER_ON,
276 rejectUnauthorized: false,
277 json: jsonData
278 }, function(error, response, body) {
279 if (utils.validateResponse('RPC.refreshAccountConnectionStatus', error, response, body, resolve, reject)) {
280
281 resolve({
282 statusCode: response.statusCode,
283 data: body
284 });
285 }
286 });
287 }).catch(function(error) {
288 console.log('Error refreshing account info');
289 });
290 };
291
292 module.exports = Accounts;