diff --git a/src/main/java/de/ugoe/cs/rwm/mocci/AbsExecutor.java b/src/main/java/de/ugoe/cs/rwm/mocci/AbsExecutor.java new file mode 100644 index 0000000000000000000000000000000000000000..e9040dd0444e84086e31f069378d841787898e82 --- /dev/null +++ b/src/main/java/de/ugoe/cs/rwm/mocci/AbsExecutor.java @@ -0,0 +1,287 @@ +package de.ugoe.cs.rwm.mocci; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.StringWriter; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + +import org.apache.commons.io.IOUtils; +import org.eclipse.cmf.occi.core.Entity; + +import de.ugoe.cs.rwm.docci.connector.Connector; + +/** + * Contains multiple methods required by every Executor + * + * @author erbel + * + */ +public abstract class AbsExecutor { + protected Connector connector; + protected Integer maxTries; + private static final String ENCODINGCHARSET = "UTF-8"; + + /** + * Establish a HttpURLConnection to the given address using the given REST + * method, output, contentType and authToken. + * + * @param address + * Address of the REST interface. + * @param method + * CRUD operation to be used. + * @param output + * Boolean to define doOutput. + * @param contentType + * Type of content. + * @param authToken + * Authentication token to be used. + * @return HttpURLConnection for further adjustment + */ + @Deprecated + protected HttpURLConnection establishConnection(String address, String method, Boolean output, String contentType, + String authToken) { + try { + URL url = new URL(address); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setDoOutput(output); + if (method != null) { + conn.setRequestMethod(method); + } + if (contentType != null) { + conn.setRequestProperty("Content-Type", contentType); + } + if (authToken != null) { + conn.setRequestProperty("X-Auth-token", authToken); + } + return conn; + + } catch (MalformedURLException e) { + System.out.println("Malformed URL: " + address); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } + + /** + * Establish a HttpURLConnection to the given address using the given REST + * method, output, contentType and authToken. + * + * @param address + * Address of the REST interface. + * @param method + * CRUD operation to be used. + * @param output + * Boolean to define doOutput. + * @param contentType + * Type of content. + * @return HttpURLConnection for further adjustment + */ + protected HttpURLConnection establishConnection(String address, String method, Boolean output, String contentType) { + try { + URL url = new URL(address); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setDoOutput(output); + if (contentType != null) { + conn.setRequestProperty("Content-Type", contentType); + } + if (method != null) { + conn.setRequestMethod(method); + } + return conn; + + } catch (MalformedURLException e) { + System.out.println("Malformed URL: " + address); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } + + /** + * Checks whether the connection is successful. Otherwise the HTTPResponse code + * is logged. + * + * @param conn + * HttpURLConnection to be checked. + * @return Boolean whether connection is successful. + */ + protected boolean connectionSuccessful(HttpURLConnection conn) { + try { + if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED + && conn.getResponseCode() != HttpURLConnection.HTTP_OK + && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT) { + System.out.println("Failed: " + conn.getURL() + " HTTP error code: " + conn.getResponseCode()); + // log.error("Failed: "+ conn.getURL() + " HTTP error code: "+ + // conn.getResponseCode() + " " +conn.getRequestProperties()); + conn.disconnect(); + return false; + } + } catch (IOException e) { + conn.disconnect(); + e.printStackTrace(); + } + return true; + } + + /** + * Writes the String input as input into the HttpUrlConnection conn. + * + * @param conn + * HttpURLConnection to be used. + * @param input + * Input for the Connection conn. + */ + protected void writeInput(HttpURLConnection conn, String input) { + try { + OutputStream os; + os = conn.getOutputStream(); + os.write(input.getBytes(ENCODINGCHARSET)); + os.flush(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * Returns the output from the connection as concatenated String. On fault a + * null is returned. + * + * @param conn + * HttpURLConnection to be read. + * @return Output of th HTTP Connection. + */ + protected String getOutput(HttpURLConnection conn) { + int responseCode = getResponseCode(conn); + if (200 <= responseCode && responseCode <= 299) { + return getInputStream(conn); + + } else { + return getErrorStream(conn); + + } + } + + private String getErrorStream(HttpURLConnection conn) { + InputStreamReader isr = null; + StringWriter writer = new StringWriter(); + try { + if (conn.getErrorStream() != null) { + isr = new InputStreamReader(conn.getErrorStream(), ENCODINGCHARSET); + IOUtils.copy(isr, writer); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } finally { + if (isr != null) { + try { + isr.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + return writer.toString(); + + /* + * StringBuffer sb = new StringBuffer(); if (is != null) { InputStreamReader isr + * = null; BufferedReader br = null; try { isr = new InputStreamReader(is); br = + * new BufferedReader(isr); sb = new StringBuffer(); String inputLine = ""; + * while ((inputLine = br.readLine()) != null) { sb.append(inputLine); } + * LOG.info("ERRORSTREAM: " + sb); return sb.toString(); } catch (IOException + * e1) { LOG.info("Could not retrieve error stream"); return ""; } finally { if + * (br != null) { try { br.close(); } catch (IOException e) { + * LOG.info("Could not close BufferedReader while retrieving errorstream"); + * e.printStackTrace(); } } + * + * if (isr != null) { try { isr.close(); } catch (IOException e1) { + * LOG.info("Could not close InputStreamReader while retrieving errorstream"); } + * } } } return null; + */ + } + + private String getInputStream(HttpURLConnection conn) { + try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), ENCODINGCHARSET))) { + StringBuffer sb = new StringBuffer(); + String inputLine = ""; + while ((inputLine = br.readLine()) != null) { + sb.append(inputLine); + } + return sb.toString(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + } + + private int getResponseCode(HttpURLConnection conn) { + int code; + try { + code = conn.getResponseCode(); + } catch (IOException e) { + code = 0; + e.printStackTrace(); + } + return code; + } + + /** + * Adapts address, so that the address contains the path of OCCI element to be + * created. E.g. Adds compute/storage or network to the path. + * + * @param entity + * to be provisioned. + * @return adapted address. + */ + protected String getEntityKindURI(Entity entity) { + // String address = Deployer.adress; + String address = this.connector.getAddress(); + if (entity.getKind().getTerm().equals("networkinterface")) { + address += "/networklink/"; + } else { + address += "/" + entity.getKind().getTerm() + "/"; + } + return address; + } + + /** + * Logs the respones of a request stored in the passed String output. + * + * @param output + * Output of the REST response. + */ + protected void logResponseOfRequest(String output) { + System.out.println("Rest response: " + output); + } + + /** + * Returns Connector of the Executor object. + * + * @return connector Current Connector of the Executor object. + */ + public Connector getConn() { + return connector; + } + + /** + * Sets Connector of the Executor object. + * + * @param conn + * Desired Connector of the Executor object. + */ + public void setConn(Connector conn) { + this.connector = conn; + } +} diff --git a/src/main/java/de/ugoe/cs/rwm/mocci/MAPE.java b/src/main/java/de/ugoe/cs/rwm/mocci/MAPE.java new file mode 100644 index 0000000000000000000000000000000000000000..32accb4b230918068e2a66f77040d3fbbf7a85e6 --- /dev/null +++ b/src/main/java/de/ugoe/cs/rwm/mocci/MAPE.java @@ -0,0 +1,246 @@ +package de.ugoe.cs.rwm.mocci; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.eclipse.cmf.occi.core.AttributeState; +import org.eclipse.cmf.occi.core.Configuration; +import org.eclipse.cmf.occi.core.Link; +import org.eclipse.cmf.occi.core.impl.OCCIFactoryImpl; +import org.eclipse.cmf.occi.infrastructure.Compute; +import org.eclipse.cmf.occi.infrastructure.ComputeStatus; +import org.eclipse.cmf.occi.infrastructure.impl.InfrastructureFactoryImpl; +import org.eclipse.emf.common.util.BasicEList; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.resource.Resource; +import org.modmacao.occi.platform.Component; +import org.modmacao.occi.platform.Componentlink; +import org.modmacao.occi.platform.PlatformPackage; +import org.modmacao.occi.platform.impl.PlatformFactoryImpl; + +import de.ugoe.cs.rwm.docci.MartDeployer; +import de.ugoe.cs.rwm.docci.ModelUtility; +import de.ugoe.cs.rwm.docci.connector.Connector; +import de.ugoe.cs.rwm.docci.connector.LocalhostConnector; +import de.ugoe.cs.rwm.docci.executor.Executor; +import de.ugoe.cs.rwm.tocci.Transformator; +import de.ugoe.cs.rwm.tocci.TransformatorFactory; +import de.ugoe.cs.rwm.tocci.occi2openstack.OCCI2OPENSTACKTransformator; +import monitoring.Datagatherer; +import monitoring.Dataprocessor; +import monitoring.Monitorableproperty; +import monitoring.Resultprovider; +import monitoring.Sensor; +import monitoring.impl.MonitoringFactoryImpl; + +/**Making javadoc happy. + * @author erbel + * + */ +public class MAPE { + static String manNWid = "urn:uuid:29d78078-fb4c-47aa-a9af-b8aaf3339590"; + static String manNWRuntimeId = "75a4639e-9ce7-4058-b859-8a711b0e2e7b"; + static String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC6H7Ydi45BTHid4qNppGAi5mzjbnZgt7bi6xLGmZG9CiLmhMsxOuk3Z05Nn+pmoN98qS0eY8S240PPk5VOlYqBY0vdRAwrZSHHaLdMp6I7ARNrI2KraYduweqz7ZQxPXQfwIeYx2HKQxEF2r+4//Fo4WfgdBkLuulvl/Gw3TUzJNQHvgpaiNo9+PI5CZydHnZbjUkRikS12pT+CbNKj+0QKeQztbCd41aKxDv5H0DjltVRcpPppv4dmiU/zoCAIngWLO1PPgfYWyze8Z9IoyBT7Qdg30U91TYZBuxzXR5lq7Fh64y/IZ/SjdOdSIvIuDjtmJDULRdLJzrvubrKY+YH Generated-by-Nova"; + static String userData = "I2Nsb3VkLWNvbmZpZwoKIyBVcGdyYWRlIHRoZSBpbnN0YW5jZSBvbiBmaXJzdCBib290CiMgKGllIHJ1biBhcHQtZ2V0IHVwZ3JhZGUpCiMKIyBEZWZhdWx0OiBmYWxzZQojIEFsaWFzZXM6IGFwdF91cGdyYWRlCnBhY2thZ2VfdXBncmFkZTogdHJ1ZQoKcGFja2FnZXM6CiAtIHB5dGhvbgoKd3JpdGVfZmlsZXM6CiAgLSBwYXRoOiAvZXRjL25ldHdvcmsvaW50ZXJmYWNlcy5kLzUwLWNsb3VkLWluaXQuY2ZnCiAgICBjb250ZW50OiB8CiAgICAgIGF1dG8gbG8KICAgICAgaWZhY2UgbG8gaW5ldCBsb29wYmFjawogICAgICAKICAgICAgYXV0byBlbnMwCiAgICAgIGFsbG93LWhvdHBsdWcgZW5zMAogICAgICBpZmFjZSBlbnMwIGluZXQgZGhjcAogICAgICAKICAgICAgYXV0byBlbnMxCiAgICAgIGFsbG93LWhvdHBsdWcgZW5zMQogICAgICBpZmFjZSBlbnMxIGluZXQgZGhjcAogICAgICAKICAgICAgYXV0byBlbnMyCiAgICAgIGFsbG93LWhvdHBsdWcgZW5zMgogICAgICBpZmFjZSBlbnMyIGluZXQgZGhjcAogICAgICAKICAgICAgYXV0byBlbnMzCiAgICAgIGFsbG93LWhvdHBsdWcgZW5zMwogICAgICBpZmFjZSBlbnMzIGluZXQgZGhjcAogICAgICAKICAgICAgYXV0byBlbnM0CiAgICAgIGFsbG93LWhvdHBsdWcgZW5zNAogICAgICBpZmFjZSBlbnM0IGluZXQgZGhjcAogICAgICAKICAgICAgYXV0byBlbnM1CiAgICAgIGFsbG93LWhvdHBsdWcgZW5zNQogICAgICBpZmFjZSBlbnM1IGluZXQgZGhjcAogICAgICAKICAgICAgYXV0byBlbnM2CiAgICAgIGFsbG93LWhvdHBsdWcgZW5zNgogICAgICBpZmFjZSBlbnM2IGluZXQgZGhjcAogICAgICAKICAgICAgYXV0byBlbnM3CiAgICAgIGFsbG93LWhvdHBsdWcgZW5zNwogICAgICBpZmFjZSBlbnM3IGluZXQgZGhjcAogICAgICAKICAgICAgYXV0byBlbnM4CiAgICAgIGFsbG93LWhvdHBsdWcgZW5zOAogICAgICBpZmFjZSBlbnM4IGluZXQgZGhjcAogICAgICAKICAgICAgYXV0byBlbnM5CiAgICAgIGFsbG93LWhvdHBsdWcgZW5zOQogICAgICBpZmFjZSBlbnM5IGluZXQgZGhjcAogICAgICAKICAgICAgYXV0byBlbnMxMAogICAgICBhbGxvdy1ob3RwbHVnIGVuczEwCiAgICAgIGlmYWNlIGVuczEwIGluZXQgZGhjcAoKIyMj"; + protected static final Path RUNTIMEPATH = Paths.get(System.getProperty("user.home") + "/.rwm/runtime.occic"); + static Connector conn = new LocalhostConnector("localhost", 8080, "ubuntu"); + static MartDeployer deployer = new MartDeployer(conn); + static MartExecutor executor = new MartExecutor(conn); + static InfrastructureFactoryImpl iFactory = new InfrastructureFactoryImpl(); + static OCCIFactoryImpl factory = new OCCIFactoryImpl(); + static MonitoringFactoryImpl mFactory = new MonitoringFactoryImpl(); + static PlatformFactoryImpl pFactory = new PlatformFactoryImpl(); + static Resource runtimeModel; + + /**Making javadoc happy. + * @param args Making javadoc happy. + */ + public static void main(String[] args) { + RegistryAndLoggerSetup.setup(); + + String query = "/monitorableproperty?attribute=monitoring.result&value=Critical"; + initialDeploy(); + String monitor =""; + String analysis =""; + + + + + while(true) { + try { + monitor = monitor(query); + analysis = analyze(monitor); + runtimeModel = plan(analysis); + execute(runtimeModel); + System.out.println("Sleep 10000"); + Thread.sleep(10000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + } + +private static String monitor(String query) { + MartExecutor exec = new MartExecutor(conn); + String result = exec.executeGetOperation(query); + System.out.println("Monitor: " + result); + return exec.executeGetOperation(query); +} + +private static String analyze(String monitor) { + + if(monitor.contains("/compute/")){ + System.out.println("Analyze: Critical Compute Detected"); + return "upScale"; + } + else { + System.out.println("Analyze: No Critical Compute Detected"); + return "downScale"; + } +} + +private static Resource plan(String analysis) { + System.out.println("Planning:"); + switch (analysis) { + case "upScale": System.out.println("upScale!"); + return upScaleNodes(); + case "downScale": System.out.println("downScale!"); + return downScaleNodes(); + } + return null; +} + + +private static void execute(Resource runtimeModel) { + deployer.deploy(runtimeModel); + + } + + + + + +private static Resource downScaleNodes() { + EList<EObject> toDelete = new BasicEList<EObject>(); + + runtimeModel = ModelUtility.loadOCCIintoEMFResource(conn.loadRuntimeModel(RUNTIMEPATH)); + System.out.println(((Configuration) runtimeModel.getContents().get(0)).getResources()); + for(org.eclipse.cmf.occi.core.Resource res : ((Configuration) runtimeModel.getContents().get(0)).getResources()) { + if(res instanceof Compute) { + Compute comp = (Compute) res; + if(comp.getTitle().contains("worker-additional")) { + toDelete.add(comp); + toDelete.addAll(linksAndComponents(comp)); + break; + + } + + } + + } + System.out.println(((Configuration) runtimeModel.getContents().get(0)).getResources()); + runtimeModel.getContents().removeAll(toDelete); + System.out.println("Deleting Compute:" + toDelete); + System.out.println(((Configuration) runtimeModel.getContents().get(0)).getResources()); + return runtimeModel; + +} + +private static EList<EObject> linksAndComponents(Compute comp) { + EList<EObject> toDelete = new BasicEList<EObject>(); + toDelete.addAll(comp.getLinks()); + toDelete.addAll(comp.getRlinks()); + + for(Link link: comp.getRlinks()) { + if(link.getSource() instanceof Component) { + toDelete.add(link.getSource()); + } + if(link instanceof Monitorableproperty) { + toDelete.add(link.getSource()); + } + } + + return toDelete; +} + +private static Resource upScaleNodes() { + runtimeModel = ModelUtility.loadOCCIintoEMFResource(conn.loadRuntimeModel(RUNTIMEPATH)); + Configuration config = ((Configuration) runtimeModel.getContents().get(0)); + + Compute comp = iFactory.createCompute(); + comp.setTitle("hadoop-worker-additional"); + comp.setOcciComputeState(ComputeStatus.ACTIVE); + AttributeState attr = factory.createAttributeState(); + attr.setName("occi.compute.state"); + attr.setValue("active"); + comp.getAttributes().add(attr); + ((Configuration) runtimeModel.getContents().get(0)).getResources().add(comp); + System.out.println("Compute Node added"); + //executor.executeOperation("PUT", comp, null); + + Sensor sens = mFactory.createSensor(); + sens.setTitle("CPUSensor"); + config.getResources().add(sens); + //executor.executeOperation("PUT", sens, null); + + Monitorableproperty mp = mFactory.createMonitorableproperty(); + mp.setTitle("monProp"); + mp.setMonitoringProperty("CPU"); + mp.setSource(sens); + mp.setTarget(comp); + //executor.executeOperation("PUT", mp, null); + + Datagatherer dg = mFactory.createDatagatherer(); + dg.setTitle("CPUGatherer"); + config.getResources().add(dg); + executor.executeOperation("PUT", dg, null); + Componentlink c1 = pFactory.createComponentlink(); + c1.setSource(sens); + c1.setTarget(dg); + //executor.executeOperation("PUT", c1, null); + + Dataprocessor dp = mFactory.createDataprocessor(); + dp.setTitle("CPUProcessor"); + config.getResources().add(dp); + //executor.executeOperation("PUT", dp, null); + Componentlink c2 = pFactory.createComponentlink(); + c2.setSource(sens); + c2.setTarget(dp); + //executor.executeOperation("PUT", c2, null); + + Resultprovider rp = mFactory.createResultprovider(); + rp.setTitle("CPUProvider"); + config.getResources().add(rp); + //executor.executeOperation("PUT", rp, null); + Componentlink c3 = pFactory.createComponentlink(); + c3.setSource(sens); + c3.setTarget(rp); + //executor.executeOperation("PUT", c3, null); + + return runtimeModel; + } + + +public static void initialDeploy() { + Path occiPath = Paths.get(ModelUtility.getPathToResource("occi/hadoopClusterNewExtWithMem.occic")); + Resource model = ModelUtility.loadOCCIintoEMFResource(occiPath); + + System.out.println("OCCI2OCCITransformator"); + Transformator trans = TransformatorFactory.getTransformator("OCCI2OCCI"); + trans.transform(model, occiPath); + + OCCI2OPENSTACKTransformator trans2 = OCCI2OPENSTACKTransformator.getInstance(); + trans2.setTransformationProperties(manNWRuntimeId, sshKey, userData, manNWid); + + trans2.transform(occiPath, occiPath); + + + + + deployer.deploy(occiPath); +} + + +} \ No newline at end of file diff --git a/src/main/java/de/ugoe/cs/rwm/mocci/MartExecutor.java b/src/main/java/de/ugoe/cs/rwm/mocci/MartExecutor.java new file mode 100644 index 0000000000000000000000000000000000000000..b30446735ed98a6278a7e5fefde5e40b90f88a5e --- /dev/null +++ b/src/main/java/de/ugoe/cs/rwm/mocci/MartExecutor.java @@ -0,0 +1,373 @@ +package de.ugoe.cs.rwm.mocci; + +import java.net.HttpURLConnection; + +import org.eclipse.cmf.occi.core.Action; +import org.eclipse.cmf.occi.core.AttributeState; +import org.eclipse.cmf.occi.core.Entity; +import org.eclipse.cmf.occi.core.Link; +import org.eclipse.cmf.occi.core.Mixin; +import org.eclipse.cmf.occi.core.MixinBase; +import org.eclipse.emf.ecore.EObject; + +import de.ugoe.cs.rwm.docci.connector.Connector; + +/** + * Handles execution of OCCI Model Elements. + * + * @author erbel + * + */ +public class MartExecutor extends AbsExecutor { + + /** + * Creates an Executor to the OCCI API of the specified connection. Sets + * maxTries to 3. + * + * @param conn + */ + public MartExecutor(Connector conn) { + this.connector = conn; + this.maxTries = 3; + } + + /** + * Creates Executor to the OCCI API of the specified connection. maxTries is + * hereby the maximum amount of retries for a request. Should be at least 2 to + * handle connection issues. + * + * @param conn + * @param maxTries + */ + public MartExecutor(Connector conn, int maxTries) { + this.connector = conn; + this.maxTries = maxTries; + } + + public String executeOperation(String operation, EObject element, EObject action) { + Boolean success = false; + String output = ""; + int count = 0; + + while (success == false && count < maxTries) { + if (operation.equals("POST") && action == null) { + output = executePostOperation(element); + } else if (operation.equals("PUT")) { + output = executePutOperation(element); + } else if (operation.equals("GET")) { + output = executeGetOperation(element); + } else if (operation.equals("DELETE")) { + output = executeDeleteOperation(element); + } else if (operation.equals("POST") && action != null) { + output = executeActionOperation(element, action); + } + + // TODO: Output kommt eigentlich immer; + if (output != null) { + success = true; + } + + if (success == false) { + count++; + try { + System.out.println(operation + " Failed: " + ((Entity) element).getTitle() + " Rerequest in 5s!"); + Thread.sleep(5000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + return output; + } + + /** + * Performs a POST(Action) request on the EObject element with the Action stored + * in EObject eAction. + * + * @param element + * @param eAction + * @return + */ + private String executeActionOperation(EObject element, EObject eAction) { + Entity entity = (Entity) element; + Action action = (Action) eAction; + + String adaptedAddress = "http://" + connector.getAddress() + ":" + connector.getPort() + getLocation(entity); + adaptedAddress += "?action="; + adaptedAddress += action.getTerm(); + HttpURLConnection conn = establishConnection(adaptedAddress, "POST", true, "text/occi"); + + conn.setRequestProperty("Category", generateCategoryHeader(action)); + conn.setRequestProperty("Accept", "application/json"); + System.out.println("POST " + conn.getURL() + " -H 'Content-Type: " + conn.getRequestProperty("Content-Type") + "' " + + " -H 'Category: " + conn.getRequestProperty("Category") + "' "); + + if (connectionSuccessful(conn)) { + String output = getOutput(conn); + return output; + } else { + conn.disconnect(); + return null; + } + } + + private String getLocation(Entity ent) { + if (ent.getLocation() != null && ent.getLocation().isEmpty() == false) { + return ent.getLocation(); + } else { + StringBuilder location = new StringBuilder(); + location.append("/"); + location.append(ent.getKind().getTerm()); + location.append("/"); + location.append(ent.getId()); + location.append("/"); + return location.toString(); + } + } + + /** + * Returns generated Category header for the passed action. + * + * @param action + * @return + */ + private String generateCategoryHeader(Action action) { + String category = action.getTerm() + "; " + "scheme=\"" + action.getScheme() + "\"; " + "class=\"action\""; + return category; + } + + /** + * Returns output of GET request for the passed Entity EObject extracted. + * + * @param extracted + * @return Output of the GET request. + */ + public String executeGetOperation(EObject extracted) { + Entity entity = (Entity) extracted; + String adaptedAddress = "http://" + connector.getAddress() + ":" + connector.getPort() + getLocation(entity); + HttpURLConnection conn = establishConnection(adaptedAddress, null, false, null); + conn.setRequestProperty("Accept", "application/json"); + + System.out.println("GET" + " " + adaptedAddress); + + return getOutput(conn); + } + + public String executeGetOperation(String query) { + String adaptedAddress = "http://" + connector.getAddress() + ":" + connector.getPort() + query; + HttpURLConnection conn = establishConnection(adaptedAddress, null, false, null); + conn.setRequestProperty("Accept", "application/json"); + + System.out.println("GET" + " " + adaptedAddress); + + return getOutput(conn); + } + + /** + * Issues a cloud session token required for authorization. + * + * @param user + * @param password + * @param project + * @param address + * @return cloud session token + */ + @Deprecated + public String createToken(String user, String password, String project, String address) { + return ""; + } + + /** + * Performs POST request to provision the Resource described by the EObject + * element. + * + * @param element + * @return + */ + private String executePostOperation(EObject element) { + if (element instanceof Entity) { + Entity entity = (Entity) element; + return postEntity(entity); + } else if (element instanceof Mixin) { + Mixin mixin = (Mixin) element; + if (mixin.getScheme().equals("http://schemas.modmacao.org/usermixins#")) { + return postUserMixin(mixin); + } + } + throw new IllegalArgumentException("Can not post element: " + element); + + } + + private String postUserMixin(Mixin mixin) { + String adaptedAddress = "http://" + connector.getAddress() + ":" + connector.getPort() + "/-/"; + HttpURLConnection conn = establishConnection(adaptedAddress, "POST", true, "text/occi"); + conn.setRequestProperty("Category", generateUserMixinHeader(mixin)); + conn.setRequestProperty("Accept", "application/json"); + System.out.println("POST" + " " + conn.getURL() + " Category: " + conn.getRequestProperty("Category")); + + if (connectionSuccessful(conn)) { + String output = getOutput(conn); + conn.disconnect(); + return output; + } else { + conn.disconnect(); + return null; // getOutput(conn); + } + } + + private String generateUserMixinHeader(Mixin mixin) { + String category = ""; + category = mixin.getTerm() + "; " + "scheme=\"" + mixin.getScheme() + "\"; " + "class=\"mixin\"; " + + "location=\"/usermixins/\""; + return category; + } + + private String postEntity(Entity entity) { + String adaptedAddress = "http://" + connector.getAddress() + ":" + connector.getPort() + getLocation(entity); + HttpURLConnection conn = establishConnection(adaptedAddress, "POST", true, "text/occi"); + conn.setRequestProperty("Category", generateCategoryHeader(entity)); + conn.setRequestProperty("X-OCCI-Attribute", generateAttributeHeader(entity)); + conn.setRequestProperty("Accept", "application/json"); + System.out.println("POST " + conn.getURL() + " -H 'Content-Type: " + conn.getRequestProperty("Content-Type") + "' " + + " -H 'Category: " + conn.getRequestProperty("Category") + "' " + " -H 'X-OCCI-Attribute:" + + conn.getRequestProperty("X-OCCI-Attribute") + "' "); + + if (connectionSuccessful(conn)) { + String output = getOutput(conn); + conn.disconnect(); + return output; + } else { + conn.disconnect(); + return null; // getOutput(conn); + } + } + + /** + * Performs DELETE request to deprovision Resource described by the EObject + * element. + * + * @param element + * @return + */ + private String executeDeleteOperation(EObject element) { + Entity entity = (Entity) element; + String adaptedAddress = "http://" + connector.getAddress() + ":" + connector.getPort() + getLocation(entity); + HttpURLConnection conn = establishConnection(adaptedAddress, "DELETE", false, null); + conn.setRequestProperty("Accept", "application/json"); + System.out.println("DELETE" + " " + conn.getURL()); + if (connectionSuccessful(conn)) { + String output = getOutput(conn); + conn.disconnect(); + return output; + } else { + conn.disconnect(); + return null; + } + } + + /** + * Generates X-OCCI-Attribute header for the HttpURLConnection. + * + * @param entity + * containing the Attributes. + * @return String containing the X-OCCI-Attribute Header. + */ + private String generateAttributeHeader(Entity entity) { + StringBuffer attributes = new StringBuffer(); + + if (entity instanceof Link) { + Link link = (Link) entity; + attributes.append("occi.core.source=\"" + getLocation(link.getSource()) + "\","); + attributes.append("occi.core.target=\"" + getLocation(link.getTarget()) + "\","); + } + + for (AttributeState state : entity.getAttributes()) { + if ((state.getName().equals("occi.core.target") || state.getName().equals("occi.core.source")) == false) { + attributes.append(state.getName() + "=\"" + state.getValue() + "\", "); + } + } + + for (MixinBase base : entity.getParts()) { + for (AttributeState baseState : base.getAttributes()) { + attributes.append(baseState.getName() + "=\"" + baseState.getValue() + "\", "); + } + } + + System.out.println(attributes); + return attributes.substring(0, attributes.lastIndexOf(",")); + } + + /** + * Generates Category header for the HttpURLConnection. + * + * @param entity + * containing the Attributes. + * @return String containing the Category Header. + */ + private String generateCategoryHeader(Entity entity) { + StringBuffer category = new StringBuffer(); + category.append(entity.getKind().getTerm() + "; " + "scheme=\"" + entity.getKind().getScheme() + "\"; " + + "class=\"kind\""); + + for (Mixin mixin : entity.getMixins()) { + category.append( + ", " + mixin.getTerm() + "; " + "scheme=\"" + mixin.getScheme() + "\"; " + "class=\"mixin\""); + } + return category.toString(); + } + + /** + * Executes PUT requested based on the Resource described in the EObject + * element. + * + * @param element + * Element to PUT + * @return Connection Output. + */ + public String executePutOperation(EObject element) { + Entity entity = (Entity) element; + String adaptedAddress = "http://" + connector.getAddress() + ":" + connector.getPort() + getLocation(entity); + HttpURLConnection conn = establishConnection(adaptedAddress, "PUT", true, "text/occi"); + conn.setRequestProperty("Category", generateCategoryHeader(entity)); + conn.setRequestProperty("X-OCCI-Attribute", generateAttributeHeader(entity)); + conn.setRequestProperty("Accept", "application/json"); + System.out.println("PUT " + conn.getURL() + " -H 'Content-Type: " + conn.getRequestProperty("Content-Type") + "' " + + " -H 'Category: " + conn.getRequestProperty("Category") + "' " + " -H 'X-OCCI-Attribute:" + + conn.getRequestProperty("X-OCCI-Attribute") + "' "); + + if (connectionSuccessful(conn)) { + String output = getOutput(conn); + conn.disconnect(); + + /* + * try { LOG.info("Waiting for configuration: 10000ms."); Thread.sleep(10000); } + * catch (InterruptedException e) { // TODO Auto-generated catch block + * e.printStackTrace(); } + */ + + return output; + } else { + conn.disconnect(); + System.out.println("Request failed: " + getOutput(conn)); + return null;// getOutput(conn); + } + } + + /** + * Returns registered usermixins. + * + * @return String containing the REST response when asking for usermixins. + */ + public String getUsermixins() { + String adaptedAddress = "http://" + connector.getAddress() + ":" + connector.getPort() + "/-/"; + HttpURLConnection conn = establishConnection(adaptedAddress, null, false, null); + conn.setRequestProperty("Accept", "application/json"); + + System.out.println("GET" + " " + adaptedAddress); + String output = getOutput(conn); + System.out.println(output); + return output; + } +} diff --git a/src/main/java/de/ugoe/cs/rwm/mocci/RegistryAndLoggerSetup.java b/src/main/java/de/ugoe/cs/rwm/mocci/RegistryAndLoggerSetup.java new file mode 100644 index 0000000000000000000000000000000000000000..fc0579a7efbed390699787ac2627aa86c6df22db --- /dev/null +++ b/src/main/java/de/ugoe/cs/rwm/mocci/RegistryAndLoggerSetup.java @@ -0,0 +1,80 @@ +package de.ugoe.cs.rwm.mocci; + +import org.apache.log4j.Level; +import org.apache.log4j.Logger; +import org.eclipse.cmf.occi.core.OCCIPackage; +import org.eclipse.cmf.occi.core.util.OcciRegistry; +import org.eclipse.cmf.occi.infrastructure.InfrastructurePackage; +import org.modmacao.ansibleconfiguration.AnsibleconfigurationPackage; +import org.modmacao.occi.platform.PlatformPackage; +import org.modmacao.placement.PlacementPackage; + +import de.ugoe.cs.rwm.cocci.Comparator; +import de.ugoe.cs.rwm.docci.Deployer; +import de.ugoe.cs.rwm.docci.connector.Connector; +import de.ugoe.cs.rwm.docci.executor.Executor; +import de.ugoe.cs.rwm.docci.provisioner.Provisioner; +import de.ugoe.cs.rwm.docci.retriever.ModelRetriever; +import de.ugoe.cs.rwm.tocci.Transformator; +import modmacao.ModmacaoPackage; +import monitoring.MonitoringPackage; +import openstackruntime.OpenstackruntimePackage; +import ossweruntime.OssweruntimePackage; +import workflow.WorkflowPackage; + +public class RegistryAndLoggerSetup { + public static void setup() { + loggerSetup(); + registrySetup(); + + + } + + private static void loggerSetup() { + Logger.getLogger(Transformator.class.getName()).setLevel(Level.OFF); + Logger.getLogger(Connector.class.getName()).setLevel(Level.OFF); + Logger.getLogger(ModelRetriever.class.getName()).setLevel(Level.OFF); + Logger.getLogger(Comparator.class.getName()).setLevel(Level.OFF); + Logger.getLogger(Provisioner.class.getName()).setLevel(Level.INFO); + Logger.getLogger(Deployer.class.getName()).setLevel(Level.OFF); + Logger.getLogger(Executor.class.getName()).setLevel(Level.OFF); + } + + private static void registrySetup() { + + InfrastructurePackage.eINSTANCE.eClass(); + OCCIPackage.eINSTANCE.eClass(); + ModmacaoPackage.eINSTANCE.eClass(); + OpenstackruntimePackage.eINSTANCE.eClass(); + PlacementPackage.eINSTANCE.eClass(); + WorkflowPackage.eINSTANCE.eClass(); + OssweruntimePackage.eINSTANCE.eClass(); + AnsibleconfigurationPackage.eINSTANCE.eClass(); + MonitoringPackage.eINSTANCE.eClass(); + + PlatformPackage.eINSTANCE.eClass(); + OcciRegistry.getInstance().registerExtension("http://schemas.modmacao.org/occi/platform#", + PlatformPackage.class.getClassLoader().getResource("model/platform.occie").toString()); + + OcciRegistry.getInstance().registerExtension("http://schemas.modmacao.org/modmacao#", + ModmacaoPackage.class.getClassLoader().getResource("model/modmacao.occie").toString()); + OcciRegistry.getInstance().registerExtension("http://schemas.modmacao.org/openstack/runtime#", + OpenstackruntimePackage.class.getClassLoader().getResource("model/openstackruntime.occie").toString()); + OcciRegistry.getInstance().registerExtension("http://schemas.modmacao.org/openstack/swe#", + OssweruntimePackage.class.getClassLoader().getResource("model/openstackruntime.occie").toString()); + OcciRegistry.getInstance().registerExtension("http://schemas.modmacao.org/placement#", + PlacementPackage.class.getClassLoader().getResource("model/placement.occie").toString()); + OcciRegistry.getInstance().registerExtension("http://schemas.ogf.org/occi/infrastructure#", + InfrastructurePackage.class.getClassLoader().getResource("model/Infrastructure.occie").toString()); + OcciRegistry.getInstance().registerExtension("http://schemas.ogf.org/occi/core#", + OCCIPackage.class.getClassLoader().getResource("model/Core.occie").toString()); + OcciRegistry.getInstance().registerExtension("http://schemas.ugoe.cs.rwm/workflow#", + OCCIPackage.class.getClassLoader().getResource("model/workflow.occie").toString()); + OcciRegistry.getInstance().registerExtension("http://schemas.modmacao.org/openstack/swe#", + OCCIPackage.class.getClassLoader().getResource("model/ossweruntime.occie").toString()); + OcciRegistry.getInstance().registerExtension("http://schemas.modmacao.org/occi/ansible#", + OCCIPackage.class.getClassLoader().getResource("model/ansibleconfiguration.occie").toString()); + OcciRegistry.getInstance().registerExtension("http://schemas.ugoe.cs.rwm/monitoring#", + MonitoringPackage.class.getClassLoader().getResource("model/monitoring.occie").toString()); + } +}