Example #1
0
                                azureCloud.createServer(launchparamsazure, function(err, instanceData) {
                                    if (err) {
                                        logger.error('azure createServer error', err);
                                        callback({
                                            message: "unable to create vm in azure"
                                        });
                                        return;
                                    }

                                    var credentials = {
                                        username: launchparamsazure.username,
                                        password: launchparamsazure.password
                                    };
                                    var paramRunList = [];
                                    if (launchParams && launchParams.version) {
                                        paramRunList = launchParams.version.runlist;
                                    }

                                    credentialcryptography.encryptCredential(credentials, function(err, encryptedCredentials) {
                                        if (err) {
                                            logger.error('azure encryptCredential error', err);
                                            callback({
                                                message: "azure encryptCredential error"
                                            });
                                            return;
                                        }
                                        logger.debug('Credentials encrypted..');
                                        logger.debug('OS Launched');
                                        logger.debug(JSON.stringify(instanceData));
                                        //Creating instance in catalyst

                                        var instance = {
                                            //name: launchparams.VMName,
                                            name: launchParams.blueprintName,
                                            orgId: launchParams.orgId,
                                            orgName: launchParams.orgName,
                                            bgId: launchParams.bgId,
                                            bgName: launchParams.bgName,
                                            projectId: launchParams.projectId,
                                            projectName: launchParams.projectName,
                                            envId: launchParams.envId,
                                            environmentName: launchParams.envName,
                                            providerId: self.cloudProviderId,
                                            providerType: self.cloudProviderType,
                                            keyPairId: 'azure',
                                            region: self.region,
                                            chefNodeName: launchparamsazure.VMName,
                                            runlist: paramRunList,
                                            platformId: launchparamsazure.VMName,
                                            appUrls: launchParams.appUrls,
                                            instanceIP: 'pending',
                                            instanceState: 'pending',
                                            bootStrapStatus: 'waiting',
                                            users: launchParams.users,
                                            instanceType: self.instanceType,
                                            catUser: launchParams.sessionUser,
                                            hardware: {
                                                platform: 'azure',
                                                platformVersion: 'unknown',
                                                architecture: 'unknown',
                                                memory: {
                                                    total: 'unknown',
                                                    free: 'unknown',
                                                },
                                                os: self.instanceOS
                                            },
                                            credentials: {
                                                username: encryptedCredentials.username,
                                                password: encryptedCredentials.password
                                            },
                                            chef: {
                                                serverId: self.infraManagerId,
                                                chefNodeName: launchparamsazure.VMName
                                            },
                                            blueprintData: {
                                                blueprintId: launchParams.blueprintData._id,
                                                blueprintName: launchParams.blueprintData.name,
                                                templateId: launchParams.blueprintData.templateId,
                                                templateType: launchParams.blueprintData.templateType,
                                                iconPath: launchParams.blueprintData.iconpath
                                            }

                                        };

                                        logger.debug('Instance Data');
                                        logger.debug(JSON.stringify(instance));

                                        instancesDao.createInstance(instance, function(err, data) {
                                            if (err) {
                                                logger.error("Failed to create Instance", err);
                                                callback({
                                                    message: "Failed to create instance in db"
                                                })
                                                return;
                                            }

                                            instance.id = data._id;
                                            var timestampStarted = new Date().getTime();
                                            var actionLog = instancesDao.insertBootstrapActionLog(instance.id, instance.runlist, launchParams.sessionUser, timestampStarted);
                                            var logsReferenceIds = [instance.id, actionLog._id];
                                            logsDao.insertLog({
                                                referenceId: logsReferenceIds,
                                                err: false,
                                                log: "Waiting for instance ok state",
                                                timestamp: timestampStarted
                                            });

                                            var instanceLog = {
                                                actionId: actionLog._id,
                                                instanceId: instance.id,
                                                orgName: launchParams.orgName,
                                                bgName: launchParams.bgName,
                                                projectName: launchParams.projectName,
                                                envName: launchParams.envName,
                                                status: "pending",
                                                actionStatus: "waiting",
                                                platformId: launchparamsazure.VMName,
                                                blueprintName: launchParams.blueprintData.name,
                                                data: paramRunList,
                                                platform: "unknown",
                                                os: self.instanceOS,
                                                size: self.instanceType,
                                                user: launchParams.sessionUser,
                                                createdOn: new Date().getTime(),
                                                startedOn: new Date().getTime(),
                                                providerType: self.cloudProviderType,
                                                action: "Bootstrap",
                                                logs: [{
                                                    err: false,
                                                    log: "Waiting for instance ok state",
                                                    timestamp: new Date().getTime()
                                                }]
                                            };

                                            instanceLogModel.createOrUpdate(actionLog._id, instance.id, instanceLog, function(err, logData) {
                                                if (err) {
                                                    logger.error("Failed to create or update instanceLog: ", err);
                                                }
                                            });


                                            logger.debug('Returned from Create Instance. About to wait for instance ready state');


                                            //waiting for server to become active
                                            logger.debug('Returned from Create Instance.' + instcount + ' of ' + self.instanceCount + '  About to send response');

                                            azureinstid.push(instance.id);
                                            if (azureinstid.length >= parseInt(self.instanceCount)) {
                                                callback(null, {
                                                    "id": azureinstid,
                                                    "message": "instance launch success"
                                                });
                                                logger.debug('Should have sent the response.');
                                            }

                                            azureCloud.waitforserverready(launchparamsazure.VMName, launchparamsazure.username, launchparamsazure.password, function(err, publicip) {

                                                if (!err) {
                                                    logger.debug('Instance Ready....');
                                                    logger.debug(JSON.stringify(data)); // logger.debug(data);
                                                    logger.debug('About to bootstrap Instance');
                                                    //identifying pulic ip

                                                    instancesDao.updateInstanceIp(instance.id, publicip, function(err, updateCount) {
                                                        if (err) {
                                                            logger.error("instancesDao.updateInstanceIp Failed ==>", err);
                                                            return;
                                                        }
                                                        logger.debug('Instance ip Updated');
                                                    });
                                                    instancesDao.updateInstanceState(instance.id, "running", function(err, updateCount) {
                                                        if (err) {
                                                            logger.error("instancesDao.updateInstanceState Failed ==>", err);
                                                            return;
                                                        }
                                                        logger.debug('Instance state Updated');
                                                    });

                                                    logsDao.insertLog({
                                                        referenceId: logsReferenceIds,
                                                        err: false,
                                                        log: "Instance Ready..about to bootstrap",
                                                        timestamp: timestampStarted
                                                    });

                                                    instanceLog.status = "running";
                                                    instanceLog.logs = {
                                                        err: false,
                                                        log: "Instance Ready..about to bootstrap",
                                                        timestamp: new Date().getTime()
                                                    };
                                                    instanceLogModel.createOrUpdate(actionLog._id, instance.id, instanceLog, function(err, logData) {
                                                        if (err) {
                                                            logger.error("Failed to create or update instanceLog: ", err);
                                                        }
                                                    });

                                                    var port = '';

                                                    if (instance.hardware.os === 'windows') {
                                                        port = '5985';
                                                    } else {
                                                        port = '22';
                                                    }
                                                    var repoData = {};
                                                    repoData['projectId'] = launchParams.blueprintData.projectId;
                                                    if (launchParams.blueprintData.nexus.repoName) {
                                                        repoData['repoName'] = launchParams.blueprintData.nexus.repoName;
                                                    } else if (launchParams.blueprintData.docker.image) {
                                                        repoData['repoName'] = launchParams.blueprintData.docker.image;
                                                    }
                                                    launchParams.blueprintData.getCookBookAttributes(instance.instanceIP, repoData, function(err, jsonAttributes) {
                                                        var runlist = instance.runlist;
                                                        logger.debug("launchParams.blueprintData.extraRunlist: ", JSON.stringify(launchParams.blueprintData.extraRunlist));
                                                        if (launchParams.blueprintData.extraRunlist) {
                                                            runlist = launchParams.blueprintData.extraRunlist.concat(instance.runlist);
                                                        }

                                                        logger.debug("runlist: ", JSON.stringify(runlist));
                                                        launchParams.infraManager.bootstrapInstance({
                                                            instanceIp: publicip,
                                                            runlist: runlist,
                                                            instanceUsername: launchparamsazure.username,
                                                            instancePassword: launchparamsazure.password, //should be the encryped file 
                                                            nodeName: launchparamsazure.VMName,
                                                            environment: launchParams.envName,
                                                            instanceOS: instance.hardware.os,
                                                            jsonAttributes: jsonAttributes,
                                                            port: port
                                                        }, function(err, code) {
                                                            fs.unlink(decryptedPemFile, function(err) {
                                                                logger.debug("Deleting decryptedPemFile..");
                                                                if (err) {
                                                                    logger.error("Error in deleting decryptedPemFile..");
                                                                }

                                                                fs.unlink(decryptedKeyFile, function(err) {
                                                                    logger.debug("Deleting decryptedKeyFile ..");
                                                                    if (err) {
                                                                        logger.error("Error in deleting decryptedKeyFile..");
                                                                    }
                                                                });
                                                            });

                                                            if (err) {
                                                                instancesDao.updateInstanceBootstrapStatus(instance.id, 'failed', function(err, updateData) {
                                                                    if (err) {
                                                                        logger.error("Unable to set instance bootstarp status. code 0", err);
                                                                    }
                                                                });

                                                                var timestampEnded = new Date().getTime();
                                                                logsDao.insertLog({
                                                                    referenceId: logsReferenceIds,
                                                                    err: true,
                                                                    log: "Bootstrap failed",
                                                                    timestamp: timestampEnded
                                                                });
                                                                instancesDao.updateActionLog(instance.id, actionLog._id, false, timestampEnded);
                                                                instanceLog.endedOn = new Date().getTime();
                                                                instanceLog.actionStatus = "failed";
                                                                instanceLog.logs = {
                                                                    err: true,
                                                                    log: "Bootstrap failed",
                                                                    timestamp: new Date().getTime()
                                                                };
                                                                instanceLogModel.createOrUpdate(actionLog._id, instance.id, instanceLog, function(err, logData) {
                                                                    if (err) {
                                                                        logger.error("Failed to create or update instanceLog: ", err);
                                                                    }
                                                                });
                                                                return;
                                                            }

                                                            logger.debug("Azure vm bootstrap code:", code);

                                                            if (code == 0) {
                                                                instancesDao.updateInstanceBootstrapStatus(instance.id, 'success', function(err, updateData) {
                                                                    if (err) {
                                                                        logger.error("Unable to set instance bootstarp status. code 0", err);
                                                                    }

                                                                });

                                                                var timestampEnded = new Date().getTime();

                                                                logsDao.insertLog({
                                                                    referenceId: logsReferenceIds,
                                                                    err: false,
                                                                    log: "Instance Bootstraped successfully",
                                                                    timestamp: timestampEnded
                                                                });
                                                                instancesDao.updateActionLog(instance.id, actionLog._id, true, timestampEnded);
                                                                instanceLog.endedOn = new Date().getTime();
                                                                instanceLog.actionStatus = "success";
                                                                instanceLog.logs = {
                                                                    err: false,
                                                                    log: "Instance Bootstraped successfully",
                                                                    timestamp: new Date().getTime()
                                                                };
                                                                instanceLogModel.createOrUpdate(actionLog._id, instance.id, instanceLog, function(err, logData) {
                                                                    if (err) {
                                                                        logger.error("Failed to create or update instanceLog: ", err);
                                                                    }
                                                                });

                                                                launchParams.infraManager.getNode(instance.chefNodeName, function(err, nodeData) {
                                                                    if (err) {
                                                                        logger.error("Failed chef.getNode", err);
                                                                        return;
                                                                    }
                                                                    instanceLog.platform = nodeData.automatic.platform;
                                                                    instanceLogModel.createOrUpdate(actionLog._id, instance.id, instanceLog, function(err, logData) {
                                                                        if (err) {
                                                                            logger.error("Failed to create or update instanceLog: ", err);
                                                                        }
                                                                    });
                                                                    var hardwareData = {};
                                                                    hardwareData.architecture = nodeData.automatic.kernel.machine;
                                                                    hardwareData.platform = nodeData.automatic.platform;
                                                                    hardwareData.platformVersion = nodeData.automatic.platform_version;
                                                                    hardwareData.memory = {
                                                                        total: 'unknown',
                                                                        free: 'unknown'
                                                                    };
                                                                    if (nodeData.automatic.memory) {
                                                                        hardwareData.memory.total = nodeData.automatic.memory.total;
                                                                        hardwareData.memory.free = nodeData.automatic.memory.free;
                                                                    }
                                                                    hardwareData.os = instance.hardware.os;
                                                                    instancesDao.setHardwareDetails(instance.id, hardwareData, function(err, updateData) {
                                                                        if (err) {
                                                                            logger.error("Unable to set instance hardware details  code (setHardwareDetails)", err);
                                                                        } else {
                                                                            logger.debug("Instance hardware details set successessfully");
                                                                        }
                                                                    });

                                                                });

                                                            } else {

                                                                instancesDao.updateInstanceBootstrapStatus(instance.id, 'failed', function(err, updateData) {
                                                                    if (err) {
                                                                        logger.error("Unable to set instance bootstarp status code != 0", err);
                                                                    } else {
                                                                        logger.debug("Instance bootstrap status set to failed");
                                                                    }
                                                                });
                                                                var timestampEnded = new Date().getTime();
                                                                logsDao.insertLog({
                                                                    referenceId: logsReferenceIds,
                                                                    err: false,
                                                                    log: "Bootstrap Failed",
                                                                    timestamp: timestampEnded
                                                                });
                                                                instancesDao.updateActionLog(instance.id, actionLog._id, false, timestampEnded);
                                                                instanceLog.endedOn = new Date().getTime();
                                                                instanceLog.actionStatus = "failed";
                                                                instanceLog.logs = {
                                                                    err: false,
                                                                    log: "Bootstrap Failed",
                                                                    timestamp: new Date().getTime()
                                                                };
                                                                instanceLogModel.createOrUpdate(actionLog._id, instance.id, instanceLog, function(err, logData) {
                                                                    if (err) {
                                                                        logger.error("Failed to create or update instanceLog: ", err);
                                                                    }
                                                                });


                                                            }
                                                        }, function(stdOutData) {

                                                            logsDao.insertLog({
                                                                referenceId: logsReferenceIds,
                                                                err: false,
                                                                log: stdOutData.toString('ascii'),
                                                                timestamp: new Date().getTime()
                                                            });

                                                            instanceLog.logs = {
                                                                err: false,
                                                                log: stdOutData.toString('ascii'),
                                                                timestamp: new Date().getTime()
                                                            };
                                                            instanceLogModel.createOrUpdate(actionLog._id, instance.id, instanceLog, function(err, logData) {
                                                                if (err) {
                                                                    logger.error("Failed to create or update instanceLog: ", err);
                                                                }
                                                            });



                                                        }, function(stdErrData) {

                                                            //retrying 4 times before giving up.
                                                            logsDao.insertLog({
                                                                referenceId: logsReferenceIds,
                                                                err: true,
                                                                log: stdErrData.toString('ascii'),
                                                                timestamp: new Date().getTime()
                                                            });

                                                            instanceLog.logs = {
                                                                err: false,
                                                                log: stdErrData.toString('ascii'),
                                                                timestamp: new Date().getTime()
                                                            };
                                                            instanceLogModel.createOrUpdate(actionLog._id, instance.id, instanceLog, function(err, logData) {
                                                                if (err) {
                                                                    logger.error("Failed to create or update instanceLog: ", err);
                                                                }
                                                            });

                                                        });
                                                    });



                                                } else {
                                                    logger.debug('Err Creating Instance:' + err);
                                                    return;
                                                }
                                            });



                                        }); //close of createInstance
                                        //res.send(data);
                                    });
                                }); //close createServer
Example #2
0
			function addAndBootstrapInstance(instanceData) {


				var credentials = {
					username: instanceData.username,
					password: instanceData.password
				};

				credentialcryptography.encryptCredential(credentials, function(err, encryptedCredentials) {
					if (err) {
						logger.error('azure encryptCredential error', err);
						callback({
							message: "Unable to encryptCredential"
						});
						return;
					}
					logger.debug('Credentials encrypted..');

					//Creating instance in catalyst

					var instance = {

						name: instanceData.name,
						orgId: launchParams.orgId,
						orgName:launchParams.orgName,
						bgId: launchParams.bgId,
						bgName: launchParams.bgName,
						projectId: launchParams.projectId,
						projectName: launchParams.projectName,
						envId: launchParams.envId,
						environmentName: launchParams.envName,
						providerId: self.cloudProviderId,
						providerType: 'azure',
						keyPairId: 'azure',
						region:self.region,
						chefNodeName: instanceData.name,
						runlist: instanceData.runlist,
						platformId: instanceData.name,
						appUrls: appUrls,
						instanceIP: instanceData.ip,
						instanceState: 'running',
						bootStrapStatus: 'waiting',
						users: launchParams.users,
						hardware: {
							platform: 'unknown',
							platformVersion: 'unknown',
							architecture: 'unknown',
							memory: {
								total: 'unknown',
								free: 'unknown',
							},
							os: instanceData.os
						},
						credentials: {
							username: encryptedCredentials.username,
							password: encryptedCredentials.password
						},
						chef: {
							serverId: self.infraManagerId,
							chefNodeName: instanceData.name
						},
						blueprintData: {
							blueprintId: launchParams.blueprintData._id,
							blueprintName: launchParams.blueprintData.name,
							templateId: launchParams.blueprintData.templateId,
							templateType: launchParams.blueprintData.templateType,
							iconPath: launchParams.blueprintData.iconpath
						},
						armId: instanceData.armId

					};
					logger.debug('Creating instance in catalyst');
					instancesDao.createInstance(instance, function(err, data) {
						if (err) {
							logger.error("Failed to create Instance", err);
							callback({
								message: "Unable to create instance in db"
							})
							return;
						}
						instance.id = data._id;
						var timestampStarted = new Date().getTime();
						var actionLog = instancesDao.insertBootstrapActionLog(instance.id, instance.runlist, launchParams.sessionUser, timestampStarted);
						var logsReferenceIds = [instance.id, actionLog._id];
						logsDao.insertLog({
							referenceId: logsReferenceIds,
							err: false,
							log: "Waiting for instance ok state",
							timestamp: timestampStarted
						});


						//decrypting pem file
						var cryptoConfig = appConfig.cryptoSettings;
						var tempUncryptedPemFileLoc = appConfig.tempDir + uuid.v4();
						credentialcryptography.decryptCredential(instance.credentials, function(err, decryptedCredential) {
							if (err) {
								instancesDao.updateInstanceBootstrapStatus(instance.id, 'failed', function(err, updateData) {
									if (err) {
										logger.error("Unable to set instance bootstarp status", err);
									} else {
										logger.debug("Instance bootstrap status set to failed");
									}
								});
								var timestampEnded = new Date().getTime();
								logsDao.insertLog({
									referenceId: logsReferenceIds,
									err: true,
									log: "Unable to decrpt pem file. Bootstrap failed",
									timestamp: timestampEnded
								});
								instancesDao.updateActionLog(instance.id, actionLog._id, false, timestampEnded);

								if (instance.hardware.os != 'windows')
									return;
							}
							var repoData = {};
							repoData['projectId'] = launchParams.blueprintData.projectId;
							if (launchParams.blueprintData.nexus.repoName) {
								repoData['repoName'] = launchParams.blueprintData.nexus.repoName;
							} else if (launchParams.blueprintData.docker.image) {
								repoData['repoName'] = launchParams.blueprintData.docker.image;
							}
							launchParams.blueprintData.getCookBookAttributes(instance.instanceIP, repoData, function(err, jsonAttributes) {
								var runlist = instance.runlist;
								logger.debug("launchParams.blueprintData.extraRunlist: ", JSON.stringify(launchParams.blueprintData.extraRunlist));
								if (launchParams.blueprintData.extraRunlist) {
									runlist = launchParams.blueprintData.extraRunlist.concat(instance.runlist);
								}

								logger.debug("runlist: ", JSON.stringify(runlist));
								launchParams.infraManager.bootstrapInstance({
									instanceIp: instance.instanceIP,
									instancePassword: decryptedCredential.password,
									runlist: runlist,
									instanceUsername: instance.credentials.username,
									nodeName: instance.chef.chefNodeName,
									environment: launchParams.envName,
									instanceOS: instance.hardware.os,
									jsonAttributes: jsonAttributes
								}, function(err, code) {

									logger.error('process stopped ==> ', err, code);
									if (err) {
										logger.error("knife launch err ==>", err);
										instancesDao.updateInstanceBootstrapStatus(instance.id, 'failed', function(err, updateData) {

										});
										var timestampEnded = new Date().getTime();
										logsDao.insertLog({
											referenceId: logsReferenceIds,
											err: true,
											log: "Bootstrap failed",
											timestamp: timestampEnded
										});
										instancesDao.updateActionLog(instance.id, actionLog._id, false, timestampEnded);


									} else {
										if (code == 0) {
											instancesDao.updateInstanceBootstrapStatus(instance.id, 'success', function(err, updateData) {
												if (err) {
													logger.error("Unable to set instance bootstarp status. code 0", err);
												} else {
													logger.debug("Instance bootstrap status set to success");
												}
											});
											var timestampEnded = new Date().getTime();
											logsDao.insertLog({
												referenceId: logsReferenceIds,
												err: false,
												log: "Instance Bootstraped successfully",
												timestamp: timestampEnded
											});
											instancesDao.updateActionLog(instance.id, actionLog._id, true, timestampEnded);


											launchParams.infraManager.getNode(instance.chefNodeName, function(err, nodeData) {
												if (err) {
													logger.error("Failed chef.getNode", err);
													return;
												}
												var hardwareData = {};
												hardwareData.architecture = nodeData.automatic.kernel.machine;
												hardwareData.platform = nodeData.automatic.platform;
												hardwareData.platformVersion = nodeData.automatic.platform_version;
												hardwareData.memory = {
													total: 'unknown',
													free: 'unknown'
												};
												if (nodeData.automatic.memory) {
													hardwareData.memory.total = nodeData.automatic.memory.total;
													hardwareData.memory.free = nodeData.automatic.memory.free;
												}
												hardwareData.os = instance.hardware.os;
												instancesDao.setHardwareDetails(instance.id, hardwareData, function(err, updateData) {
													if (err) {
														logger.error("Unable to set instance hardware details  code (setHardwareDetails)", err);
													} else {
														logger.debug("Instance hardware details set successessfully");
													}
												});
												//Checking docker status and updating
												var _docker = new Docker();
												_docker.checkDockerStatus(instance.id,
													function(err, retCode) {
														if (err) {
															logger.error("Failed _docker.checkDockerStatus", err);
															return;


														}
														logger.debug('Docker Check Returned:' + retCode);
														if (retCode == '0') {
															instancesDao.updateInstanceDockerStatus(instance.id, "success", '', function(data) {
																logger.debug('Instance Docker Status set to Success');
															});

														}
													});

											});

										} else {
											instancesDao.updateInstanceBootstrapStatus(instance.id, 'failed', function(err, updateData) {
												if (err) {
													logger.error("Unable to set instance bootstarp status code != 0", err);
												} else {
													logger.debug("Instance bootstrap status set to failed");
												}
											});
											var timestampEnded = new Date().getTime();
											logsDao.insertLog({
												referenceId: logsReferenceIds,
												err: false,
												log: "Bootstrap Failed",
												timestamp: timestampEnded
											});
											instancesDao.updateActionLog(instance.id, actionLog._id, false, timestampEnded);

										}
									}

								}, function(stdOutData) {

									logsDao.insertLog({
										referenceId: logsReferenceIds,
										err: false,
										log: stdOutData.toString('ascii'),
										timestamp: new Date().getTime()
									});

								}, function(stdErrData) {

									//retrying 4 times before giving up.
									logsDao.insertLog({
										referenceId: logsReferenceIds,
										err: true,
										log: stdErrData.toString('ascii'),
										timestamp: new Date().getTime()
									});


								});
							});

						});

					});



				});

			}
Example #3
0
                vmwareCloud.createServer(appConfig.vmware.serviceHost, anImage.imageIdentifier, serverjson, function(err, createserverdata) {
                    if (err) {
                        callback({
                            message: "Server Behaved Unexpectedly"
                        });
                        return;
                    }
                    if (!err) {
                        //send the response back and create the instance 
                        

                        var credentials = {
                            username: anImage.userName,
                            password: anImage.instancePassword
                        };


                        var paramRunList = [];
                        if (launchParams && launchParams.version) {
                            paramRunList = launchParams.version.runlist;
                        }

                        credentialcryptography.encryptCredential(credentials, function(err, encryptedCredentials) {
                            if (err) {
                                logger.error('vmware encryptCredential error', err);
                                callback({
                                    message: "vmware encryption error"
                                })
                                return;
                            }

                            //create instaance
                            logger.debug('Credentials encrypted..');
                            logger.debug('OS Launched');
                            logger.debug(JSON.stringify(createserverdata));
                            //Creating instance in catalyst

                            var instance = {
                                name: launchParams.blueprintName,
                                orgId: launchParams.orgId,
                                bgId: launchParams.bgId,
                                projectId: launchParams.projectId,
                                envId: launchParams.envId,
                                providerId: self.cloudProviderId,
                                providerType: self.cloudProviderType,
                                keyPairId: 'unknown',
                                chefNodeName: createserverdata["vm_name"],
                                runlist: paramRunList,
                                platformId: createserverdata["vm_name"],
                                appUrls: launchParams.appUrls,
                                instanceIP: 'unknown',
                                instanceState: 'pending',
                                bootStrapStatus: 'waiting',
                                users: launchParams.users,
                                hardware: {
                                    platform: 'unknown',
                                    platformVersion: 'unknown',
                                    architecture: 'unknown',
                                    memory: {
                                        total: 'unknown',
                                        free: 'unknown',
                                    },
                                    os: self.instanceOS
                                },
                                credentials: {
                                    username: anImage.userName,
                                    password: anImage.instancePassword
                                },
                                chef: {
                                    serverId: self.infraManagerId,
                                    chefNodeName: createserverdata["vm_name"]
                                },
                                blueprintData: {
                                    blueprintId: launchParams.blueprintData._id,
                                    blueprintName: launchParams.blueprintData.name,
                                    templateId: launchParams.blueprintData.templateId,
                                    templateType: launchParams.blueprintData.templateType,
                                    iconPath: launchParams.blueprintData.iconpath
                                }

                            };

                            logger.debug('Instance Data');
                            logger.debug(JSON.stringify(instance));

                            instancesDao.createInstance(instance, function(err, data) {
                                if (err) {
                                    logger.error("Failed to create Instance", err);
                                    callback({
                                        message: "Unable to create instance in db"
                                    })
                                    return;
                                }

                                instance.id = data._id;
                                var timestampStarted = new Date().getTime();
                                var actionLog = instancesDao.insertBootstrapActionLog(instance.id, instance.runlist, launchParams.sessionUser, timestampStarted);
                                var logsReferenceIds = [instance.id, actionLog._id];
                                logsDao.insertLog({
                                    referenceId: logsReferenceIds,
                                    err: false,
                                    log: "Waiting for instance ok state",
                                    timestamp: timestampStarted
                                });

                                logger.debug('Returned from Create Instance. About to wait for instance ready state');


                                //waiting for server to become active
                                logger.debug('Returned from Create Instance. About to send response');
                                //res.send(200);
                                callback(null, {
                                    "id": [instance.id],
                                    "message": "instance launch success"
                                });
                                logger.debug('Should have sent the response.');
                                vmwareCloud.waitforserverready(appConfig.vmware.serviceHost, createserverdata["vm_name"], anImage.userName, anImage.instancePassword, function(err, publicip, vmdata) {
                                    if (err) {
                                        var timestampEnded = new Date().getTime();
                                        logger.error("Instance wait failes", err);
                                        instancesDao.updateInstanceBootstrapStatus(instance.id, 'failed', function(err, updateData) {
                                            if (err) {
                                                logger.error("Unable to set instance bootstarp status. code 0", err);
                                            } else {
                                                logger.debug("Instance bootstrap status set to success");
                                            }
                                        });
                                        logsDao.insertLog({
                                            referenceId: logsReferenceIds,
                                            err: true,
                                            log: 'Instance not responding. Bootstrap failed',
                                            timestamp: timestampEnded
                                        });
                                        instancesDao.updateActionLog(instance.id, actionLog._id, false, timestampEnded);

                                        return;
                                    }
                                    if (!err) {
                                        logger.debug('Instance Ready....');
                                        logger.debug(JSON.stringify(vmdata)); // logger.debug(data);
                                        logger.debug('About to bootstrap Instance');

                                        instancesDao.updateInstanceIp(instance.id, publicip, function(err, updateCount) {
                                            if (err) {
                                                logger.error("instancesDao.updateInstanceIp Failed ==>", err);
                                                return;
                                            }
                                            logger.debug('Instance ip Updated');
                                        });
                                        instancesDao.updateInstanceState(instance.id, "running", function(err, updateCount) {
                                            if (err) {
                                                logger.error("instancesDao.updateInstanceState Failed ==>", err);
                                                return;
                                            }
                                            logger.debug('Instance state Updated');
                                        });


                                        logsDao.insertLog({
                                            referenceId: logsReferenceIds,
                                            err: false,
                                            log: "Instance Ready..about to bootstrap",
                                            timestamp: timestampStarted
                                        });
                                        var repoData = {
                                            "projectId": launchParams.blueprintData.projectId,
                                            "repoName": launchParams.blueprintData.nexus.repoName
                                        };
                                        var repoData = {};
                                        repoData['projectId'] = launchParams.blueprintData.projectId;
                                        if (launchParams.blueprintData.nexus.repoName) {
                                            repoData['repoName'] = launchParams.blueprintData.nexus.repoName;
                                        } else if (launchParams.blueprintData.docker.image) {
                                            repoData['repoName'] = launchParams.blueprintData.docker.image;
                                        }
                                        launchParams.blueprintData.getCookBookAttributes(instance.instanceIP, repoData, function(err, jsonAttributes) {
                                            var runlist = instance.runlist;
                                            logger.debug("launchParams.blueprintData.extraRunlist: ", JSON.stringify(launchParams.blueprintData.extraRunlist));
                                            if (launchParams.blueprintData.extraRunlist) {
                                                runlist = launchParams.blueprintData.extraRunlist.concat(instance.runlist);
                                            }

                                            logger.debug("runlist: ", JSON.stringify(runlist));
                                            credentialcryptography.decryptCredential(instance.credentials, function(err, decryptedCredentials) {
                                                launchParams.infraManager.bootstrapInstance({
                                                    instanceIp: publicip,
                                                    runlist: runlist,
                                                    instanceUsername: anImage.userName,
                                                    instancePassword: decryptedCredentials.password, 
                                                    nodeName: createserverdata["vm_name"],
                                                    environment: launchParams.envName,
                                                    instanceOS: instance.hardware.os,
                                                    jsonAttributes: jsonAttributes
                                                }, function(err, code) {
                                                    var timestampEnded = new Date().getTime();
                                                    if (err) {
                                                        instancesDao.updateInstanceBootstrapStatus(instance.id, 'failed', function(err, updateData) {
                                                            if (err) {
                                                                logger.error("Unable to set instance bootstarp status. code 0", err);
                                                            } else {


                                                                logger.debug("Instance bootstrap status set to success");
                                                            }
                                                        });
                                                        logsDao.insertLog({
                                                            referenceId: logsReferenceIds,
                                                            err: true,
                                                            log: 'Bootstrap failed',
                                                            timestamp: timestampEnded
                                                        });
                                                        instancesDao.updateActionLog(instance.id, actionLog._id, false, timestampEnded);
                                                        return;
                                                    }
                                                    if (code == 0) {

                                                        instancesDao.updateInstanceBootstrapStatus(instance.id, 'success', function(err, updateData) {
                                                            if (err) {
                                                                logger.error("Unable to set instance bootstarp status. code 0", err);
                                                            } else {


                                                                logger.debug("Instance bootstrap status set to success");
                                                            }
                                                        });


                                                        launchParams.infraManager.getNode(instance.chefNodeName, function(err, nodeData) {
                                                            if (err) {
                                                                logger.error("Failed chef.getNode", err);
                                                                return;
                                                            }
                                                            var hardwareData = {};
                                                            hardwareData.architecture = nodeData.automatic.kernel.machine;
                                                            hardwareData.platform = nodeData.automatic.platform;
                                                            hardwareData.platformVersion = nodeData.automatic.platform_version;
                                                            hardwareData.memory = {
                                                                total: 'unknown',
                                                                free: 'unknown'
                                                            };
                                                            if (nodeData.automatic.memory) {
                                                                hardwareData.memory.total = nodeData.automatic.memory.total;
                                                                hardwareData.memory.free = nodeData.automatic.memory.free;
                                                            }
                                                            hardwareData.os = instance.hardware.os;
                                                            instancesDao.setHardwareDetails(instance.id, hardwareData, function(err, updateData) {
                                                                if (err) {
                                                                    logger.error("Unable to set instance hardware details  code (setHardwareDetails)", err);
                                                                } else {
                                                                    logger.debug("Instance hardware details set successessfully");
                                                                }
                                                            });
                                                            //Checking docker status and updating
                                                            var _docker = new Docker();
                                                            _docker.checkDockerStatus(instance.id,
                                                                function(err, retCode) {
                                                                    if (err) {
                                                                        logger.error("Failed _docker.checkDockerStatus", err);
                                                                        res.send(500);
                                                                        return;
                                                                        //res.end('200');

                                                                    }
                                                                    logger.debug('Docker Check Returned:' + retCode);
                                                                    if (retCode == '0') {
                                                                        instancesDao.updateInstanceDockerStatus(instance.id, "success", '', function(data) {
                                                                            logger.debug('Instance Docker Status set to Success');
                                                                        });

                                                                    }
                                                                });

                                                        });
                                                        logsDao.insertLog({
                                                            referenceId: logsReferenceIds,
                                                            err: false,
                                                            log: 'Instance Bootstraped Successfully.',
                                                            timestamp: timestampEnded
                                                        });
                                                        instancesDao.updateActionLog(instance.id, actionLog._id, true, timestampEnded);



                                                    } else {
                                                        instancesDao.updateInstanceBootstrapStatus(instance.id, 'failed', function(err, updateData) {
                                                            if (err) {
                                                                logger.error("Unable to set instance bootstarp status. code 0", err);
                                                            } else {


                                                                logger.debug("Instance bootstrap status set to success");
                                                            }
                                                        });
                                                        logsDao.insertLog({
                                                            referenceId: logsReferenceIds,
                                                            err: true,
                                                            log: 'Bootstrap failed',
                                                            timestamp: timestampEnded
                                                        });
                                                        instancesDao.updateActionLog(instance.id, actionLog._id, false, timestampEnded);
                                                        return;

                                                    }
                                                }, function(stdOutData) {

                                                    logsDao.insertLog({
                                                        referenceId: logsReferenceIds,
                                                        err: false,
                                                        log: stdOutData.toString('ascii'),
                                                        timestamp: new Date().getTime()
                                                    });


                                                }, function(stdErrData) {

                                                    //retrying 4 times before giving up.
                                                    logsDao.insertLog({
                                                        referenceId: logsReferenceIds,
                                                        err: true,
                                                        log: stdErrData.toString('ascii'),
                                                        timestamp: new Date().getTime()
                                                    });

                                                });
                                            });
                                        });

                                    }
                                }); //end of waitforserverready

                            }); //end of createInstance

                        });
                    }
                });
Example #4
0
                        configmgmtDao.getChefServerDetails(chefData.rowid, function(err, chefDetails) {
                            logger.debug("START getChefServerDetails");
                            if (err) {
                                res.send(500);
                                return;
                            }
                            if (!chefDetails) {
                                res.send(404);
                                return;
                            }
                            chef = new Chef({
                                userChefRepoLocation: chefDetails.chefRepoLocation,
                                chefUserName: chefDetails.loginname,
                                chefUserPemFile: chefDetails.userpemfile,
                                chefValidationPemFile: chefDetails.validatorpemfile,
                                hostedChefUrl: chefDetails.url,
                            });
                            credentialCryptography.encryptCredential(credentials, function(err, encryptedCredentials) {
                                if (err) {
                                    logger.debug("unable to encrypt credentials == >", err);
                                    return;
                                }

                                logger.debug('nodeip ==> ', nodeIp);
                                var instance = {
                                    name: node.name,
                                    orgId: orgId,
                                    bgId: bgId,
                                    projectId: projectId,
                                    envId: node.envId,
                                    chefNodeName: node.name,
                                    runlist: runlist,
                                    platformId: platformId,
                                    instanceIP: nodeIp,
                                    instanceState: 'running',
                                    bootStrapStatus: 'success',
                                    hardware: hardwareData,
                                    credentials: encryptedCredentials,
                                    chef: {
                                        serverId: chefDetails.rowid,
                                        chefNodeName: node.name
                                    },
                                    blueprintData: {
                                        blueprintName: node.name,
                                        templateId: "chef_import",
                                        iconPath: "../private/img/templateicons/chef_import.png"
                                    }
                                }

                                instancesDao.createInstance(instance, function(err, data) {
                                    if (err) {
                                        logger.debug(err, 'occured in inserting node in mongo');
                                        return;
                                    }
                                    logsDao.insertLog({
                                        referenceId: data._id,
                                        err: false,
                                        log: "Node Imported",
                                        timestamp: new Date().getTime()
                                    });

                                    logger.debug("Bootsrtapping instance..", instance, credentials, node.classification);
                                    logger.debug("IP::", instance.instanceIP);

                                    instance.id = data._id;
                                    var timestampStarted = new Date().getTime();
                                    var actionLog = instancesDao.insertBootstrapActionLog(instance.id, instance.runlist, req.session.user.cn, timestampStarted);
                                    var logsReferenceIds = [instance.id, actionLog._id];

                                    chef.bootstrapInstance({
                                        instanceIp: instance.instanceIP,
                                        runlist: instance.runlist,
                                        instanceUsername: credentials.username,
                                        instancePassword: credentials.password,
                                        nodeName: instance.name,
                                        environment: node.classification,
                                        instanceOS: instance.hardware.os,
                                        jsonAttributes: null,
                                        noSudo: true
                                    }, function(err, code) {
                                        if (code == 0) {
                                            instancesDao.updateInstanceBootstrapStatus(instance.id, 'success', function(err, updateData) {
                                                if (err) {
                                                    logger.error("Unable to set instance bootstarp status. code 0", err);
                                                } else {
                                                    logger.debug("Instance bootstrap status set to success");
                                                }
                                            });
                                        }
                                    }, function(stdOutData) {

                                        logsDao.insertLog({
                                            referenceId: logsReferenceIds,
                                            err: false,
                                            log: stdOutData.toString('ascii'),
                                            timestamp: new Date().getTime()
                                        });
                                        if (stdOutData.toString('ascii').indexOf("Chef Client finished") > 0) {
                                            instancesDao.updateInstanceBootstrapStatus(instance.id, 'success', function(err, updateData) {
                                                if (err) {
                                                    logger.error("Unable to set instance bootstarp status. code 0", err);
                                                } else {
                                                    logsDao.insertLog({
                                                        referenceId: logsReferenceIds,
                                                        err: false,
                                                        log: 'Instance Bootstraped Successfully',
                                                        timestamp: new Date().getTime()
                                                    });

                                                    logger.debug("Instance bootstrap status set to success");

                                                }
                                            });
                                        }

                                    }, function(stdErrData) {

                                        //retrying 4 times before giving up.
                                        logsDao.insertLog({
                                            referenceId: logsReferenceIds,
                                            err: true,
                                            log: stdErrData.toString('ascii'),
                                            timestamp: new Date().getTime()
                                        });

                                    });

                                    res.send(data);
                                    return

                                }); //end of create instance

                            }); //end of encryptCredential
                        }); //end of getChefServerDetails