Merge "CCSDK-1603:Changes in 'Config via netconf' BP to pull data from AAI"
[ccsdk/cds.git] / cds-ui / server / src / controllers / blueprint-rest.controller.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018-19 IBM Intellectual Property. All rights reserved.
5 ===================================================================
6
7 Unless otherwise specified, all software contained herein is licensed
8 under the Apache License, Version 2.0 (the License);
9 you may not use this software except in compliance with the License.
10 You may obtain a copy of the License at
11
12     http://www.apache.org/licenses/LICENSE-2.0
13
14 Unless required by applicable law or agreed to in writing, software
15 distributed under the License is distributed on an "AS IS" BASIS,
16 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 See the License for the specific language governing permissions and
18 limitations under the License.
19 ============LICENSE_END============================================
20 */
21
22
23
24 import {
25   Count,
26   CountSchema,
27   Filter,
28   repository,
29   Where,
30 } from '@loopback/repository';
31 import {
32   post,
33   param,
34   get,
35   getFilterSchemaFor,
36   getWhereSchemaFor,
37   patch,
38   put,
39   del,
40   requestBody,
41   Request,
42   Response,
43   RestBindings,
44 } from '@loopback/rest';
45 import { Blueprint } from '../models';
46 import { inject } from '@loopback/core';
47 import { BlueprintService } from '../services';
48 import * as fs from 'fs';
49 import * as multiparty from 'multiparty';
50 import * as request_lib from 'request';
51 import { processorApiConfig, appConfig } from '../config/app-config';
52 import { bluePrintManagementServiceGrpcClient } from '../clients/blueprint-management-service-grpc-client';
53
54 export class BlueprintRestController {
55   constructor(
56     @inject('services.BlueprintService')
57     public bpservice: BlueprintService,
58   ) { }
59
60   @get('/controllerblueprint/all', {
61     responses: {
62       '200': {
63         description: 'Blueprint model instance',
64         content: { 'application/json': { schema: { 'x-ts-type': Blueprint } } },
65       },
66     },
67   })
68   async getall() {
69     return await this.bpservice.getAllblueprints();
70   }
71
72   @get('/controllerblueprint/paged', {
73     responses: {
74       '200': {
75         description: 'Blueprint model instance with pagination',
76         content: { 'application/json': { schema: { 'x-ts-type': Blueprint } } },
77       },
78     },
79   })
80   async getPagedBlueprints(
81     @param.query.number('limit') limit: number, 
82     @param.query.number('offset') offset: number, 
83     @param.query.string('sort') sort: string) {
84     return await this.bpservice.getPagedBueprints(limit, offset, sort);
85   }
86
87  @get('/controllerblueprint/meta-data/{keyword}', {
88     responses: {
89       '200': {
90         description: 'Blueprint model instance',
91         content: { 'application/json': { schema: { 'x-ts-type': Blueprint } } },
92       },
93     },
94   })
95   async getAllPacakgesByKeword(@param.path.string('keyword') keyword: string) {
96     return await this.bpservice.getBlueprintsByKeyword(keyword);
97   }
98
99
100
101   @get('/controllerblueprint/searchByTags/{tags}', {
102     responses: {
103       '200': {
104         content: { 'application/json': {} },
105       },
106     },
107   })
108   async getByTags(@param.path.string('tags') tags: string) {
109     return await this.bpservice.getByTags(tags);
110   }
111
112   @post('/controllerblueprint/create-blueprint')
113   async upload(
114     @requestBody({
115       description: 'multipart/form-data value.',
116       required: true,
117       content: {
118         'multipart/form-data': {
119           // Skip body parsing
120           'x-parser': 'stream',
121           schema: { type: 'object' },
122         },
123       },
124     })
125     request: Request,
126     @inject(RestBindings.Http.RESPONSE) response: Response,
127   ): Promise<Response> {
128     return new Promise((resolve, reject) => {
129       this.getFileFromMultiPartForm(request).then(file => {
130         // if (appConfig.action.deployBlueprint.grpcEnabled)
131         if (appConfig.action.grpcEnabled)
132           return this.uploadFileToBlueprintProcessorGrpc(file, "DRAFT", response);
133         else
134           return this.uploadFileToBlueprintController(file, "/blueprint-model/", response);
135       }, err => {
136         reject(err);
137       });
138     });
139     // return new Promise((resolve, reject) => {
140     //   this.getFileFromMultiPartForm(request).then(file => {
141     //     this.uploadFileToBlueprintController(file, "/blueprint-model/", response).then(resp => {
142     //       resolve(resp);
143     //     }, err => {
144     //       reject(err);
145     //     });
146     //   }, err => {
147     //     reject(err);
148     //   });
149     // });
150   }
151
152   @post('/controllerblueprint/publish')
153   async publish(
154     @requestBody({
155       description: 'multipart/form-data value.',
156       required: true,
157       content: {
158         'multipart/form-data': {
159           // Skip body parsing
160           'x-parser': 'stream',
161           schema: { type: 'object' },
162         },
163       },
164     })
165     request: Request,
166     @inject(RestBindings.Http.RESPONSE) response: Response,
167   ): Promise<Response> {
168     return new Promise((resolve, reject) => {
169       this.getFileFromMultiPartForm(request).then(file => {
170         // if (appConfig.action.deployBlueprint.grpcEnabled)
171         if (appConfig.action.grpcEnabled)
172           return this.uploadFileToBlueprintProcessorGrpc(file, "PUBLISH", response);
173         else
174           return this.uploadFileToBlueprintController(file, "/blueprint-model/publish/", response);
175       }, err => {
176         reject(err);
177       });
178     });
179     // return new Promise((resolve, reject) => {
180     //   this.getFileFromMultiPartForm(request).then(file => {
181     //     this.uploadFileToBlueprintController(file, "/blueprint-model/publish/", response).then(resp => {
182     //       resolve(resp);
183     //     }, err => {
184     //       reject(err);
185     //     });
186     //   }, err => {
187     //     reject(err);
188     //   });
189     // });
190   }
191
192   @post('/controllerblueprint/enrich-blueprint')
193   async enrich(
194     @requestBody({
195       description: 'multipart/form-data value.',
196       required: true,
197       content: {
198         'multipart/form-data': {
199           // Skip body parsing
200           'x-parser': 'stream',
201           schema: { type: 'object' },
202         },
203       },
204     })
205     request: Request,
206     @inject(RestBindings.Http.RESPONSE) response: Response,
207   ): Promise<Response> {
208     return new Promise((resolve, reject) => {
209       this.getFileFromMultiPartForm(request).then(file => {
210         if (appConfig.action.grpcEnabled)
211           return this.uploadFileToBlueprintProcessorGrpc(file, "ENRICH", response);
212         else
213           return this.uploadFileToBlueprintController(file, "/blueprint-model/enrich/", response)
214         //   this.uploadFileToBlueprintController(file, "/blueprint-model/enrich/", response).then(resp => {
215         //     resolve(resp);
216         //   }, err => {
217         //     reject(err);
218         //   });
219         // }, err => {
220         //   reject(err);
221       });
222     });
223   }
224
225   @get('/controllerblueprint/download-blueprint/{name}/{version}')
226   async download(
227     @param.path.string('name') name: string,
228     @param.path.string('version') version: string,
229     @inject(RestBindings.Http.RESPONSE) response: Response,
230   ): Promise<Response> {
231
232     if (appConfig.action.grpcEnabled)
233       return this.downloadFileFromBlueprintProcessorGrpc(name, version, response);
234     else
235       return this.downloadFileFromBlueprintController("/blueprint-model/download/by-name/" + name + "/version/" + version, response);
236   }
237
238
239   async getFileFromMultiPartForm(request: Request): Promise<multiparty.File> {
240     return new Promise((resolve, reject) => {
241       let form = new multiparty.Form();
242       form.parse(request, (err: any, fields: any, files: { [x: string]: any[]; }) => {
243         if (err) reject(err);
244         let file = files['file'][0]; // get the file from the returned files object
245         if (!file) {
246           reject('File was not found in form data.');
247         } else {
248           resolve(file);
249         }
250       });
251     })
252   }
253
254   @post('/controllerblueprint/deploy-blueprint')
255   async deploy(
256     @requestBody({
257       description: 'multipart/form-data value.',
258       required: true,
259       content: {
260         'multipart/form-data': {
261           // Skip body parsing
262           'x-parser': 'stream',
263           schema: { type: 'object' },
264         },
265       },
266     })
267     request: Request,
268     @inject(RestBindings.Http.RESPONSE) response: Response,
269   ): Promise<Response> {
270     return new Promise((resolve, reject) => {
271       this.getFileFromMultiPartForm(request).then(file => {
272         // if (appConfig.action.deployBlueprint.grpcEnabled)
273         if (appConfig.action.grpcEnabled)
274           return this.uploadFileToBlueprintProcessorGrpc(file, "PUBLISH", response);
275         else
276           return this.uploadFileToBlueprintProcessor(file, "/execution-service/upload/", response);
277       }, err => {
278         reject(err);
279       });
280     });
281   }
282
283   async uploadFileToBlueprintController(file: multiparty.File, uri: string, response: Response): Promise<Response> {
284     return this.uploadFileToBlueprintService(file, processorApiConfig.http.url + uri, processorApiConfig.http.authToken, response);
285   }
286
287   async uploadFileToBlueprintProcessor(file: multiparty.File, uri: string, response: Response): Promise<Response> {
288     return this.uploadFileToBlueprintService(file, processorApiConfig.http.url + uri, processorApiConfig.http.authToken, response);
289   }
290
291   async uploadFileToBlueprintService(file: multiparty.File, url: string, authToken: string, response: Response): Promise<Response> {
292     let options = {
293       url: url,
294       headers: {
295         Authorization: authToken,
296         'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
297       },
298       formData: {
299         file: {
300           value: fs.createReadStream(file.path),
301           options: {
302             filename: 'cba.zip',
303             contentType: 'application/zip'
304           }
305         }
306       }
307     };
308
309     var removeTempFile = () => {
310       fs.unlink(file.path, (err: any) => {
311         if (err) {
312           console.error(err);
313         }
314       });
315     }
316
317     return new Promise((resolve, reject) => {
318       request_lib.post(options)
319         .on("error", err => {
320           reject(err);
321         })
322         .pipe(response)
323         .once("finish", () => {
324           removeTempFile();
325           resolve(response);
326         });
327     })
328   }
329
330   async downloadFileFromBlueprintController(uri: string, response: Response): Promise<Response> {
331     return this.downloadFileFromBlueprintService(processorApiConfig.http.url + uri, processorApiConfig.http.authToken, response);
332   }
333
334   async downloadFileFromBlueprintService(url: string, authToken: string, response: Response): Promise<Response> {
335     let options = {
336       url: url,
337       headers: {
338         Authorization: authToken,
339       }
340     };
341     return new Promise((resolve, reject) => {
342       request_lib.get(options)
343         .on("error", err => {
344           reject(err);
345         })
346         .pipe(response)
347         .once("finish", () => {
348           resolve(response);
349         });
350     })
351   }
352
353   async uploadFileToBlueprintProcessorGrpc(file: multiparty.File, actionName: string, response: Response): Promise<Response> {
354     return new Promise<Response>((resolve, reject) => {
355       bluePrintManagementServiceGrpcClient.uploadBlueprint(file.path, actionName).then(output => {
356         response.send(output.status.message);
357         resolve(response);
358       }, err => {
359         response.status(500).send(err);
360         resolve(response);
361       });
362     });
363   }
364   async downloadFileFromBlueprintProcessorGrpc(blueprintName: string, blueprintVersion: string, response: Response): Promise<Response> {
365     return new Promise<Response>((resolve, reject) => {
366       bluePrintManagementServiceGrpcClient.downloadBlueprint(blueprintName, blueprintVersion)
367         .then(output => {
368           response.send(output.status.message);
369           resolve(response);
370         }, err => {
371           response.status(500).send(err);
372           resolve(response);
373         });
374     });
375   }
376 }