Skip to content

Commit

Permalink
Error handling for get cloud image calls (#81)
Browse files Browse the repository at this point in the history
* intoducing unique IAAS infrastracture for cloud providers

* processing IAAS get cloud images error so it return the Internal Server Error

* remove authorisation exception
  • Loading branch information
ankicabarisic authored Jul 22, 2024
1 parent 042b61f commit bdb072f
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,4 @@ public class Cluster {
@Column(name = "ENV", columnDefinition = "text", length = 65535)
@JsonProperty("env-var-script")
private String envVars;

}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.Validate;
import org.json.JSONArray;
import org.json.JSONObject;
Expand Down Expand Up @@ -113,7 +116,7 @@ public Integer addClouds(String sessionId, List<CloudDefinition> clouds) throws
repositoryService.saveCredentials(credentials);
newCloud.setCredentials(credentials);

String dummyInfraName = "iamadummy" + newCloud.getCloudProviderName();
String dummyInfraName = "iamadummy" + newCloud.getCloudProviderName() + "_" + newCloud.getCloudId();
connectorIaasGateway.defineInfrastructure(dummyInfraName, newCloud, "");
newCloud.setDummyInfrastructureName(dummyInfraName);

Expand Down Expand Up @@ -348,25 +351,35 @@ public Boolean removeByonCloudNS(String sessionId, PACloud cloud, Boolean preemp
* This function returns the list of all available images related to a registered cloud
* @param sessionId A valid session id
* @param cloudId A valid cloud identifier
* @return A list of available images
* @return A list of available images for a registered cloud
*/

public List<Image> getCloudImages(String sessionId, String cloudId) throws NotConnectedException {
List<Image> allImages = getAllCloudImages(sessionId);
List<Image> filteredImages = new LinkedList<>();
PACloud paCloud = repositoryService.getPACloud(cloudId);

if (paCloud != null) {
JSONArray imagesArray = connectorIaasGateway.getImages(paCloud.getDummyInfrastructureName());
List<String> imagesIDs = IntStream.range(0, imagesArray.length())
.mapToObj(imagesArray::get)
.map(image -> cloudId + "/" + ((JSONObject) image).optString("id"))
.collect(Collectors.toList());
LOGGER.debug("Filtering images related to cloud ID \'" + cloudId + "\'.");
allImages.stream().filter(blaTest -> imagesIDs.contains(blaTest.getId())).forEach(filteredImages::add);
return filteredImages;
try {
JSONArray imagesArray = connectorIaasGateway.getImages(paCloud.getDummyInfrastructureName());
List<String> imagesIDs = IntStream.range(0, imagesArray.length())
.mapToObj(imagesArray::get)
.map(image -> cloudId + "/" + ((JSONObject) image).optString("id"))
.collect(Collectors.toList());
LOGGER.debug("Filtering images related to cloud ID '{}'.", cloudId);
allImages.stream().filter(image -> imagesIDs.contains(image.getId())).forEach(filteredImages::add);
} catch (RuntimeException e) {
LOGGER.error("Failed to get images for cloud {}: {}", cloudId, e.getMessage(), e);
throw new InternalServerErrorException("Error while retrieving images for cloud: " + cloudId, e);
}
} else {
LOGGER.warn("Cloud ID \'" + cloudId + "\' is not found in DB. getAllCloudImages() will return all images.");
return allImages;
LOGGER.warn("Cloud ID '{}' is not found in SAL DB.", cloudId);
throw new InternalServerErrorException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("Cloud ID '" + cloudId + "' is not found in SAL DB.")
.build());
}

return filteredImages;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
*/
package org.ow2.proactive.sal.service.service.infrastructure;

import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
Expand Down Expand Up @@ -92,14 +93,26 @@ public JSONObject getNodeCandidates(String nodeSourceName, String region, String
public JSONArray getImages(String nodeSourceName) {
Validate.notNull(nodeSourceName, "nodeSourceName must not be null");
LOGGER.info("Retrieving images for cloud " + nodeSourceName);
JSONArray images = null;

URIBuilder uriBuilder = new URIBuilder(new URL(paURL).toURI());
URI requestUri = uriBuilder.setPath(CONNECTOR_IAAS_PATH + "/infrastructures/" + nodeSourceName + "/images")
.build();

images = ConnectionHelper.sendGetArrayRequestAndReturnArrayResponse(requestUri);
LOGGER.info("Images retrieved for cloud {}. Images: {}", nodeSourceName, images);
JSONArray images = new JSONArray();

try {
URIBuilder uriBuilder = new URIBuilder(new URL(paURL).toURI());
URI requestUri = uriBuilder.setPath(CONNECTOR_IAAS_PATH + "/infrastructures/" + nodeSourceName + "/images")
.build();

images = ConnectionHelper.sendGetArrayRequestAndReturnArrayResponse(requestUri);
if (images.isEmpty()) {
LOGGER.info("No images found for cloud {}", nodeSourceName);
} else {
LOGGER.info("Images retrieved for cloud {}. Images: {}", nodeSourceName, images);
}
} catch (IOException e) {
LOGGER.error("An error occurred while retrieving images for cloud {}: {}",
nodeSourceName,
e.getMessage(),
e);
throw new RuntimeException("Failed to retrieve images", e); // Convert to unchecked exception if necessary
}

return images;
}
Expand Down Expand Up @@ -152,8 +165,7 @@ public void defineInfrastructure(String infrastructureName, PACloud cloud, Strin
cloud.getCredentials().getDomain() + "\"}, \"region\": \"" + region + "\"}";
break;
default:
throw new IllegalArgumentException("The infrastructure " + cloud.getCloudProviderName() +
" is not handled yet.");
throw new IllegalArgumentException("The infrastructure " + infrastructureName + " is not handled yet.");
}

try (OutputStream os = connection.getOutputStream()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@
package org.ow2.proactive.sal.service.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;

import org.jboss.netty.handler.codec.http.HttpMethod;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

Expand All @@ -46,13 +48,16 @@ private ConnectionHelper() {
}

@SneakyThrows
private static BufferedReader sendGetRequestAndReturnBufferedResponse(HttpURLConnection connection) {
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
LOGGER.error("Failed : HTTP error code : {}", connection.getResponseCode());
return null;
private static BufferedReader sendGetRequestAndReturnBufferedResponse(HttpURLConnection connection)
throws IOException {
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
String errorMessage = "Failed: HTTP error code: " + responseCode;
LOGGER.error(errorMessage);
throw new IOException(errorMessage);
}

return new BufferedReader(new InputStreamReader((connection.getInputStream())));
return new BufferedReader(new InputStreamReader(connection.getInputStream()));
}

@SneakyThrows
Expand All @@ -71,17 +76,51 @@ public static JSONObject sendGetRequestAndReturnObjectResponse(URI requestUri) {
}

@SneakyThrows
public static JSONArray sendGetArrayRequestAndReturnArrayResponse(URI requestUri) {
HttpURLConnection connection = (HttpURLConnection) requestUri.toURL().openConnection();
connection.setRequestMethod(HttpMethod.GET.toString());
LOGGER.debug("requestUri = {}", requestUri);

BufferedReader br = sendGetRequestAndReturnBufferedResponse(connection);

JSONArray result = (br != null) ? new JSONArray(new JSONTokener(br)) : null;

connection.disconnect();
public static JSONArray sendGetArrayRequestAndReturnArrayResponse(URI requestUri) throws IOException {
HttpURLConnection connection = null;
BufferedReader br = null;
JSONArray result = new JSONArray();

try {
connection = (HttpURLConnection) requestUri.toURL().openConnection();
connection.setRequestMethod(HttpMethod.GET.toString());
LOGGER.debug("requestUri = {}", requestUri);

br = sendGetRequestAndReturnBufferedResponse(connection);
if (br != null) {
result = new JSONArray(new JSONTokener(br));
} else {
LOGGER.warn("No response received from request to {}", requestUri);
}
} catch (IOException e) {
LOGGER.error("IO exception occurred while making request to {}: {}", requestUri, e.getMessage(), e);
throw e; // Rethrow IOException to be handled by the calling method
} catch (JSONException e) {
LOGGER.error("JSON parsing error occurred while processing response from {}: {}",
requestUri,
e.getMessage(),
e);
throw new IOException("JSON parsing error occurred", e); // Wrap and throw as IOException
} catch (Exception e) {
LOGGER.error("An unexpected error occurred while processing request to {}: {}",
requestUri,
e.getMessage(),
e);
throw new IOException("Unexpected error occurred", e); // Wrap and throw as IOException
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
LOGGER.warn("Failed to close BufferedReader: {}", e.getMessage(), e);
}
}
if (connection != null) {
connection.disconnect();
}
}

return result;
}

}

0 comments on commit bdb072f

Please sign in to comment.