summaryrefslogtreecommitdiffstats
path: root/lib/dcae-deployments.js
blob: 193f6b9649065393ef19bf16362b76f7bbd9796c (plain)
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
/*
Copyright(c) 2017-2018 AT&T Intellectual Property. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
*/

/* Handle the /dcae-deployments API */

"use strict";

/* Set this code up as a "sub-app"--lets us get the mountpoint for creating links */
const app = require('express')();
app.set('x-powered-by', false);
app.set('etag', false);

const bodyParser = require('body-parser');
const deploy = require('./deploy');
const middleware = require('./middleware');
const inv = require('./inventory');
const log = require('./logging').getLogger();

/* Pick up config exported by main */
const config = process.mainModule.exports.config;
const inventory = inv({url: config.inventory.url});

/* Set up middleware stack for initial processing of request */
app.use(middleware.checkType('application/json'));		// Validate type
app.use(bodyParser.json({strict: true}));				// Parse body as JSON
app.use(function(req, res, next) {
	log.info(req.dcaeReqId,
		"new req: " + req.method + " " + req.originalUrl +
		" from: " + req.ip + " body: " + JSON.stringify(req.body)
	);
	next();
});


/* Return a promise for a blueprint for the given service type ID */
const getBlueprint = function(req, serviceTypeId) {
	return inventory.getBlueprintByType(req, serviceTypeId)
	.then(function (blueprintInfo) {
		if (!blueprintInfo.blueprint) {
			var e = new Error("No service type with ID " + serviceTypeId);
			e.status = 404;
			throw e;
		}
		return blueprintInfo;
	})
};

/* Generate self and status links object for responses */
const createLinks = function(req, deploymentId, executionId) {
	var baseURL = req.protocol + '://' + req.get('Host') + req.app.mountpath + '/' + deploymentId;
    return {
    	self: baseURL,
		status: baseURL + '/operation/' + executionId
	};
};

/* Generate a success response body for PUT and DELETE operations */
const createResponse = function(req, result) {
	return {
		requestId: req.dcaeReqId,
		links: createLinks(req, result.deploymentId, result.executionId)
	};
};

/* Look up running (or in process of deploying) instances of the given service type */
app.get('/', function (req, res, next) {
	var services = []

	var searchTerm;
	req.query['serviceTypeId'] && (searchTerm = {typeId: req.query['serviceTypeId']});

	inventory.getServicesByType(req, searchTerm)
	.then(function (result) {
		var deployments = result.map(function(service){
			return {
				href: req.protocol + '://' + req.get('Host') + req.app.mountpath + '/' + service.deploymentId
			};
		})
		res.status(200).json({requestId: req.dcaeReqId, deployments: deployments});
		log.audit(req, 200);
	})
	.catch(next);   /* Let the error handler send response and log the error */
});

/* Accept an incoming deployment request */
app.put('/:deploymentId', function(req, res, next) {

	/* Make sure there's a serviceTypeId in the body */
	if (!req.body['serviceTypeId']) {
		var e = new Error ('Missing required parameter serviceTypeId');
		e.status = 400;
		throw e;
	}

	/* Make sure the deploymentId doesn't already exist */
	inventory.verifyUniqueDeploymentId(req, req.params['deploymentId'])

	/* Get the blueprint for this service type */
	.then(function(res) {
		return getBlueprint(req, req.body['serviceTypeId']);
	})

	/* Add this new service instance to inventory
	 * Easier to remove from inventory if deployment fails than vice versa
	 * Also lets client check for deployed/deploying instances if client wants to limit number of instances
	 */
	.then(function (blueprintInfo) {
		req.dcaeBlueprint = blueprintInfo.blueprint;
		return inventory.addService(req, req.params['deploymentId'], blueprintInfo.typeId, "dummyVnfId", "dummyVnfType", "dummyLocation");
	})

	/* Upload blueprint, create deployment and start install workflow (but don't wait for completion */
	.then (function() {
		req.dcaeAddedToInventory = true;
		return deploy.launchBlueprint(req, req.params['deploymentId'], req.dcaeBlueprint, req.body['inputs']);
	})

	/* Send the HTTP response indicating workflow has started */
	.then(function(result) {
		res.status(202).json(createResponse(req, result));
		log.audit(req, 202, "Execution ID: " + result.executionId);
		return result;
	})

	/* Finish deployment--wait for the install workflow to complete, retrieve and annotate outputs */
	.then(function(result) {
		return deploy.finishInstallation(req, result.deploymentId, result.executionId);
	})

	/* Log completion in audit log */
	.then (function(result) {
		log.audit(req, 200, "Deployed id: " + req.params['deploymentId']);
	})

	/* All errors show up here */
	.catch(function(error) {

		/* If we haven't already sent a response, let the error handler send response and log the error */
		if (!res.headersSent) {

			/* If we made an inventory entry, remove it */
			if (req.dcaeAddedToInventory) {
				inventory.deleteService(req, req.params['deploymentId'])
				.catch(function(error) {
					log.error(error, req);
				});
			}

			next(error);
		}
		else {
			/* Already sent the response, so just log error */
			/* Don't remove from inventory, because there is a deployment on CM that might need to be removed */
			error.message = "Error deploying deploymentId " + req.params['deploymentId'] + ": " + error.message
						  + " " + (error.stack || "").replace(/\n/g, " ");
			log.error(error, req);
			log.audit(req, 500, error.message);
		}

	});
});

/* Delete a running service instance */
app.delete('/:deploymentId', function(req, res, next) {

	/* Launch the uninstall workflow */
	deploy.launchUninstall(req, req.params['deploymentId'])

	/* Delete the service from inventory */
	.then(function(result) {
		return inventory.deleteService(req, req.params['deploymentId'])
		.then (function() {
			return result;
		});
	})

	/* Send the HTTP response indicating workflow has started */
	.then(function(result) {
		res.status(202).send(createResponse(req, result));
		log.audit(req, 202, "ExecutionId: " + result.executionId);
		return result;
	})

	/* Finish the delete processing--wait for the uninstall to complete, delete deployment, delete blueprint */
	.then(function(result) {
		return deploy.finishUninstall(req, result.deploymentId, result.executionId);
	})

	/* Log completion in audit log */
	.then(function(result) {
		log.audit(req, 200, "Undeployed id: " + req.params['deploymentId']);
	})

	/* All errors show up here */
	.catch(function(error) {
		/* If we haven't already sent a response, give it to the error handler to send response */
		if (!res.headersSent) {
			next(error);
		}
		else {
			/* Error happened after we sent the response--log it */
			error.message = "Error undeploying deploymentId " + req.params['deploymentId'] + ": " + error.message
						  + " " + (error.stack || "").replace(/\n/g, " ");
			log.error(error, req);
			log.audit(req, 500, error.message);
		}
	});
});

/* Get the status of a workflow execution */
app.get('/:deploymentId/operation/:executionId', function(req, res, next){
	deploy.getExecutionStatus(req, req.params['executionId'])

	/* Send success response */
	.then(function(result) {
		result.requestId = req.dcaeReqId;
		result.links = createLinks(req, req.params['deploymentId'], req.params['executionId']);
		res.status(200).json(result);
		log.audit(req, 200,  "Workflow type: " + result.operationType + " -- execution status: " + result.status);
	})

	.catch(next);		/* Let the error handler send the response and log the error */

});

module.exports = app;