use of com.microsoft.azure.vmagent.exceptions.AzureCloudException in project azure-vm-agents-plugin by jenkinsci.
the class AzureVMAgentCleanUpTask method cleanVMs.
private void cleanVMs(ExecutionEngine executionEngine) {
LOGGER.log(getNormalLoggingLevel(), "Beginning");
for (Computer computer : Jenkins.get().getComputers()) {
if (computer instanceof AzureVMComputer) {
AzureVMComputer azureComputer = (AzureVMComputer) computer;
final AzureVMAgent agentNode = azureComputer.getNode();
// If the machine is not offline, then don't do anything.
if (!azureComputer.isOffline()) {
continue;
}
// builds.
if (!azureComputer.isIdle()) {
continue;
}
// should stay (this could be for investigation).
if (azureComputer.isSetOfflineByUser()) {
LOGGER.log(getNormalLoggingLevel(), "Node {0} was set offline by user, skipping", agentNode.getDisplayName());
continue;
}
// If the machine is in "keep" state, skip
if (agentNode.isCleanUpBlocked()) {
LOGGER.log(getNormalLoggingLevel(), "Node {0} blocked to cleanup", agentNode.getDisplayName());
continue;
}
// deleted in the background. Remove from Jenkins if that is the case.
if (!AzureVMManagementServiceDelegate.virtualMachineExists(agentNode)) {
LOGGER.log(getNormalLoggingLevel(), "Node {0} doesn't exist, removing", agentNode.getDisplayName());
try {
Jenkins.get().removeNode(agentNode);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Node {0} could not be removed: {1}", new Object[] { agentNode.getDisplayName(), e.getMessage() });
}
continue;
}
// Machine exists but is in either DELETE or SHUTDOWN state.
// Execute that action.
Callable<Void> task = () -> {
// Depending on the cleanup action, run the appropriate
if (agentNode.getCleanUpAction() == CleanUpAction.DELETE) {
LOGGER.log(getNormalLoggingLevel(), "Deleting {0}", agentNode.getDisplayName());
agentNode.deprovision(agentNode.getCleanUpReason());
} else if (agentNode.getCleanUpAction() == CleanUpAction.SHUTDOWN) {
LOGGER.log(getNormalLoggingLevel(), "Shutting down {0}", agentNode.getDisplayName());
agentNode.shutdown(agentNode.getCleanUpReason());
// We shut down the agent properly. Mark the agent
// as "KEEP" so that it doesn't get deleted.
agentNode.blockCleanUpAction();
} else {
throw new IllegalStateException("Unknown cleanup action");
}
return null;
};
try {
final int maxRetries = 3;
final int waitInterval = 10;
final int defaultTimeOutInSeconds = 30 * 60;
executionEngine.executeAsync(task, new DefaultRetryStrategy(maxRetries, waitInterval, defaultTimeOutInSeconds));
} catch (AzureCloudException exception) {
// No need to throw exception back, just log and move on.
LOGGER.log(Level.WARNING, "Failed to shutdown/delete " + agentNode.getDisplayName(), exception);
// In case the node had a non-delete cleanup action before,
// set the cleanup action to delete
agentNode.setCleanUpAction(CleanUpAction.DELETE, Messages._Failed_Initial_Shutdown_Or_Delete());
}
}
}
LOGGER.log(getNormalLoggingLevel(), "Completed");
}
use of com.microsoft.azure.vmagent.exceptions.AzureCloudException in project azure-vm-agents-plugin by jenkinsci.
the class AzureVMCloud method waitUntilJNLPNodeIsOnline.
/**
* Wait till a node that connects through JNLP comes online and connects to
* Jenkins.
*
* @param agent Node to wait for
* @throws AzureCloudException If the wait time expires or other exception happens
*/
private void waitUntilJNLPNodeIsOnline(final AzureVMAgent agent) throws AzureCloudException {
LOGGER.log(Level.INFO, "Azure Cloud: waitUntilOnline: for agent {0}", agent.getDisplayName());
Callable<String> callableTask = new Callable<String>() {
@Override
public String call() {
try {
Computer computer = agent.toComputer();
if (computer != null) {
computer.waitUntilOnline();
}
} catch (InterruptedException e) {
// just ignore
}
return "success";
}
};
Future<String> future = getThreadPool().submit(callableTask);
try {
// 30 minutes is decent time for the node to be alive
final int timeoutInMinutes = 30;
String result = future.get(timeoutInMinutes, TimeUnit.MINUTES);
LOGGER.log(Level.INFO, "Azure Cloud: waitUntilOnline: node {0} is alive, result {1}", new Object[] { agent.getDisplayName(), result });
} catch (Exception ex) {
throw AzureCloudException.create(String.format("Azure Cloud: waitUntilOnline: " + "Failure waiting {0} till online", agent.getDisplayName()), ex);
} finally {
future.cancel(true);
}
}
use of com.microsoft.azure.vmagent.exceptions.AzureCloudException in project azure-vm-agents-plugin by jenkinsci.
the class AzureVMManagementServiceDelegate method verifyTemplate.
/**
* Verifies template configuration by making server calls if needed.
*/
public List<String> verifyTemplate(String templateName, String labels, String location, String virtualMachineSize, String storageAccountName, String storageAccountType, String noOfParallelJobs, String imageTopLevelType, AzureVMAgentTemplate.ImageReferenceTypeClass imageReferenceType, String builtInImage, String osType, String agentLaunchMethod, String initScript, String credentialsId, String virtualNetworkName, String virtualNetworkResourceGroupName, String subnetName, AzureVMCloudBaseRetentionStrategy retentionStrategy, String jvmOptions, String resourceGroupName, boolean returnOnSingleError, boolean usePrivateIP, String nsgName) {
List<String> errors = new ArrayList<>();
// Load configuration
try {
String validationResult;
// Verify basic info about the template
// Verify number of parallel jobs
validationResult = verifyTemplateName(templateName);
addValidationResultIfFailed(validationResult, errors);
if (returnOnSingleError && errors.size() > 0) {
return errors;
}
validationResult = verifyNoOfExecutors(noOfParallelJobs);
addValidationResultIfFailed(validationResult, errors);
if (returnOnSingleError && errors.size() > 0) {
return errors;
}
validationResult = verifyRetentionTime(retentionStrategy);
addValidationResultIfFailed(validationResult, errors);
if (returnOnSingleError && errors.size() > 0) {
return errors;
}
// verify password
String adminPassword = "";
try {
StandardUsernamePasswordCredentials creds = AzureUtil.getCredentials(credentialsId);
adminPassword = creds.getPassword().getPlainText();
} catch (AzureCloudException e) {
LOGGER.log(Level.SEVERE, "Could not load the VM credentials", e);
}
validationResult = verifyAdminPassword(adminPassword);
addValidationResultIfFailed(validationResult, errors);
if (returnOnSingleError && errors.size() > 0) {
return errors;
}
// verify JVM Options
validationResult = verifyJvmOptions(jvmOptions);
addValidationResultIfFailed(validationResult, errors);
if (returnOnSingleError && errors.size() > 0) {
return errors;
}
validationResult = verifyImageParameters(imageTopLevelType, imageReferenceType, builtInImage, osType);
addValidationResultIfFailed(validationResult, errors);
if (returnOnSingleError && errors.size() > 0) {
return errors;
}
verifyTemplateAsync(location, imageTopLevelType, imageReferenceType, builtInImage, storageAccountName, storageAccountType, virtualNetworkName, virtualNetworkResourceGroupName, subnetName, resourceGroupName, errors, usePrivateIP, nsgName);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error validating template", e);
errors.add("Error occurred while validating Azure Profile");
}
return errors;
}
use of com.microsoft.azure.vmagent.exceptions.AzureCloudException in project azure-vm-agents-plugin by jenkinsci.
the class AzureVMManagementServiceDelegate method attachPublicIP.
public void attachPublicIP(AzureVMAgent azureAgent, AzureVMAgentTemplate template) throws AzureCloudException {
VirtualMachine vm;
try {
vm = azureClient.virtualMachines().getByResourceGroup(template.getResourceGroupName(), azureAgent.getNodeName());
} catch (Exception e) {
throw AzureCloudException.create(e);
}
LOGGER.log(Level.INFO, "Trying to attach a public IP to the agent {0}", azureAgent.getNodeName());
if (vm != null) {
// check if the VM already has a public IP
if (vm.getPrimaryPublicIPAddress() == null) {
try {
vm.getPrimaryNetworkInterface().update().withNewPrimaryPublicIPAddress(azureClient.publicIpAddresses().define(azureAgent.getNodeName() + "IPName").withRegion(template.getLocation()).withExistingResourceGroup(template.getResourceGroupName()).withLeafDomainLabel(azureAgent.getNodeName())).apply();
} catch (Exception e) {
throw AzureCloudException.create(e);
}
setVirtualMachineDetails(azureAgent, template);
} else {
LOGGER.log(Level.INFO, "Agent {0} already has a public IP", azureAgent.getNodeName());
}
} else {
LOGGER.log(Level.WARNING, "Could not find agent {0} in Azure", azureAgent.getNodeName());
}
}
use of com.microsoft.azure.vmagent.exceptions.AzureCloudException in project azure-vm-agents-plugin by jenkinsci.
the class AzureVMManagementServiceDelegate method getCloudBlobContainer.
public BlobContainerClient getCloudBlobContainer(AzureResourceManager azureClient, String resourceGroupName, String targetStorageAccount, String blobContainerName) throws AzureCloudException {
StorageAccount storageAccount;
try {
storageAccount = azureClient.storageAccounts().getByResourceGroup(resourceGroupName, targetStorageAccount);
} catch (Exception e) {
throw AzureCloudException.create(e);
}
BlobServiceClient account = getCloudStorageAccount(storageAccount);
return getCloudBlobContainer(account, blobContainerName);
}
Aggregations