diff options
Diffstat (limited to 'appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp')
11 files changed, 769 insertions, 1036 deletions
diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefActivator.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefActivator.java index 5485a70bd..fb1ae6788 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefActivator.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefActivator.java @@ -68,7 +68,7 @@ public class ChefActivator implements BundleActivator { /** * The logger to be used */ - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ChefActivator.class); + private final EELFLogger logger = EELFManager.getInstance().getLogger(ChefActivator.class); /** * The configuration object used to configure this bundle @@ -81,7 +81,7 @@ public class ChefActivator implements BundleActivator { * <p> * This method must complete and return to its caller in a timely manner. * </p> - * + * * @param context * The execution context of the bundle being started. * @throws java.lang.Exception @@ -97,7 +97,7 @@ public class ChefActivator implements BundleActivator { configuration = ConfigurationFactory.getConfiguration(); String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); logger.info(Msg.COMPONENT_INITIALIZING, appName, "chef adapter"); - adapter = new ChefAdapterImpl(configuration.getProperties()); + adapter = new ChefAdapterImpl(); if (registration == null) { logger.info(Msg.REGISTERING_SERVICE, appName, adapter.getAdapterName(), ChefAdapter.class.getSimpleName()); @@ -115,7 +115,7 @@ public class ChefActivator implements BundleActivator { * <p> * This method must complete and return to its caller in a timely manner. * </p> - * + * * @param context * The execution context of the bundle being stopped. * @throws java.lang.Exception diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefAdapter.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefAdapter.java index adf7e9ae1..3af963731 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefAdapter.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/ChefAdapter.java @@ -42,7 +42,7 @@ import org.openecomp.sdnc.sli.SvcLogicJavaPlugin; */ public interface ChefAdapter extends SvcLogicJavaPlugin { - /** + /** * The type of provider to be accessed to locate and operate on a virtual machine instance. This is used to load the * correct provider support through the CDP IaaS abstraction layer and can be OpenStackProvider, BareMetalProvider, * or any other supported provider type. @@ -82,7 +82,7 @@ public interface ChefAdapter extends SvcLogicJavaPlugin { * URL of the server)</dd> * </dl> * </p> - * + * * @param properties * A map of name-value pairs that supply the parameters needed by this method. The properties needed are * defined above. @@ -112,7 +112,7 @@ public interface ChefAdapter extends SvcLogicJavaPlugin { * URL of the server)</dd> * </dl> * </p> - * + * * @param properties * A map of name-value pairs that supply the parameters needed by this method. The properties needed are * defined above. @@ -142,7 +142,7 @@ public interface ChefAdapter extends SvcLogicJavaPlugin { * URL of the server)</dd> * </dl> * </p> - * + * * @param properties * A map of name-value pairs that supply the parameters needed by this method. The properties needed are * defined above. @@ -172,7 +172,7 @@ public interface ChefAdapter extends SvcLogicJavaPlugin { * URL of the server)</dd> * </dl> * </p> - * + * * @param properties * A map of name-value pairs that supply the parameters needed by this method. The properties needed are * defined above. @@ -188,7 +188,7 @@ public interface ChefAdapter extends SvcLogicJavaPlugin { /** * Returns the symbolic name of the adapter - * + * * @return The adapter name */ String getAdapterName(); @@ -196,33 +196,25 @@ public interface ChefAdapter extends SvcLogicJavaPlugin { // Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException; //Server migrateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException; - + void trigger(Map<String, String> params, SvcLogicContext ctx) ; - + void chefGet(Map<String, String> params, SvcLogicContext ctx) ; - + void chefPut(Map<String, String> params, SvcLogicContext ctx) ; - + void chefPost(Map<String, String> params, SvcLogicContext ctx) ; - + void chefDelete(Map<String, String> params, SvcLogicContext ctx) ; - + void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) ; - + void checkPushJob(Map<String, String> params, SvcLogicContext ctx) ; void pushJob(Map<String, String> params, SvcLogicContext ctx) ; - + void retrieveData (Map<String, String> params, SvcLogicContext ctx) ; - + void combineStrings (Map<String, String> params, SvcLogicContext ctx) ; - - void VnfcEnvironment (Map<String, String> params, SvcLogicContext ctx) ; - - void VnfcNodeobjects (Map<String, String> params, SvcLogicContext ctx) ; - - void VnfcPushJob (Map<String, String> params, SvcLogicContext ctx) ; - - void fetchResults (Map<String, String> params, SvcLogicContext ctx) ; } diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/ApiMethod.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/ApiMethod.java index dd7c86219..19e381ec5 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/ApiMethod.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/ApiMethod.java @@ -45,128 +45,125 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; public class ApiMethod { - private HttpClient client = null; - protected HttpRequestBase method = null; - protected HttpResponse response = null; - protected String reqBody = ""; - protected String userId = ""; - protected String pemPath = ""; - protected String chefPath = ""; - protected String organizations = ""; - protected int resCode=0; - protected String responseBody=""; - private String methodName = "GET"; - public String test = ""; - private int returnCode; - final String KEY_STORE_PATH = "/etc/chef/trusted_certs/mykeystore.jks"; - final String KEY_STORE_PASSWORD = "adminadmin"; - static -{ - System.setProperty("javax.net.ssl.trustStore", "/opt/app/bvc/chef/chefServerSSL.jks"); - System.setProperty("javax.net.ssl.trustStorePassword", "adminadmin"); - } - public ApiMethod(String methodName) { - - client=HttpClients.createDefault(); - this.methodName = methodName; - } - - public ApiMethod execute() { - String hashedPath = Utils.sha1AndBase64("/organizations/"+organizations+chefPath); - String hashedBody = Utils.sha1AndBase64(reqBody); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - String timeStamp = sdf.format(new Date()); - timeStamp = timeStamp.replace(" ", "T"); - timeStamp = timeStamp + "Z"; - - StringBuilder sb = new StringBuilder(); - sb.append("Method:").append(methodName).append("\n"); - sb.append("Hashed Path:").append(hashedPath).append("\n"); - sb.append("X-Ops-Content-Hash:").append(hashedBody).append("\n"); - sb.append("X-Ops-Timestamp:").append(timeStamp).append("\n"); - sb.append("X-Ops-UserId:").append(userId); - test = test + "sb " + sb + "\n"; - - String auth_String = Utils.signWithRSA(sb.toString(), pemPath); - String[] auth_headers = Utils.splitAs60(auth_String); - - method.addHeader("Content-type", "application/json"); - method.addHeader("X-Ops-Timestamp", timeStamp); - method.addHeader("X-Ops-Userid", userId); - method.addHeader("X-Chef-Version", "12.4.1"); - method.addHeader("Accept", "application/json"); - method.addHeader("X-Ops-Content-Hash", hashedBody); - method.addHeader("X-Ops-Sign", "version=1.0"); - - for (int i = 0; i < auth_headers.length; i++) { - method.addHeader("X-Ops-Authorization-" + (i + 1), auth_headers[i]); - } - - try{ - response = client.execute(method); - resCode = response.getStatusLine().getStatusCode(); - HttpEntity entity1 = response.getEntity(); - responseBody = EntityUtils.toString(entity1);} - catch(Exception ex){ - resCode=500; - responseBody=ex.getMessage(); - } - return this; - } - - public void setHeaders(Header[] headers) { - for (Header header : headers) { - this.method.addHeader(header); - } - } - - public String getResponseBodyAsString() { - return responseBody; - } - - public int getReturnCode() { - return resCode; - } - - public String getReqBody() { - return reqBody; - } - - public void setReqBody(String body) { - this.reqBody = body; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getPemPath() { - return pemPath; - } - - public void setPemPath(String pemPath) { - this.pemPath = pemPath; - } - - public String getChefPath() { - return chefPath; - } - - public void setChefPath(String chefPath) { - this.chefPath = chefPath; - } - - public String getOrganizations() { - return organizations; - } - - public void setOrganizations(String organizations) { - this.organizations = organizations; - } + private HttpClient client = null; + protected HttpRequestBase method = null; + protected HttpResponse response = null; + protected String reqBody = ""; + protected String userId = ""; + protected String pemPath = ""; + protected String chefPath = ""; + protected String organizations = ""; + protected int resCode=0; + protected String responseBody=""; + private String methodName = "GET"; + public String test = ""; + private int returnCode; + + public ApiMethod(String methodName) { + client=HttpClients.createDefault(); + this.methodName = methodName; + } + + public ApiMethod execute() { + String hashedPath = Utils.sha1AndBase64("/organizations/"+organizations+chefPath); + String hashedBody = Utils.sha1AndBase64(reqBody); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + String timeStamp = sdf.format(new Date()); + timeStamp = timeStamp.replace(" ", "T"); + timeStamp = timeStamp + "Z"; + + StringBuilder sb = new StringBuilder(); + sb.append("Method:").append(methodName).append("\n"); + sb.append("Hashed Path:").append(hashedPath).append("\n"); + sb.append("X-Ops-Content-Hash:").append(hashedBody).append("\n"); + sb.append("X-Ops-Timestamp:").append(timeStamp).append("\n"); + sb.append("X-Ops-UserId:").append(userId); + test = test + "sb " + sb + "\n"; + + String auth_String = Utils.signWithRSA(sb.toString(), pemPath); + String[] auth_headers = Utils.splitAs60(auth_String); + + method.addHeader("Content-type", "application/json"); + method.addHeader("X-Ops-Timestamp", timeStamp); + method.addHeader("X-Ops-Userid", userId); + method.addHeader("X-Chef-Version", "12.4.1"); + method.addHeader("Accept", "application/json"); + method.addHeader("X-Ops-Content-Hash", hashedBody); + method.addHeader("X-Ops-Sign", "version=1.0"); + + for (int i = 0; i < auth_headers.length; i++) { + method.addHeader("X-Ops-Authorization-" + (i + 1), auth_headers[i]); + } + /* + * test=test+this.method.getMethod()+"\n"; Header[] + * RHS=this.method.getHeaders(); for (int i = 0; i < RHS.length; i++) { + * test=test+RHS[i]+"\n"; } test=test+this.reqBody+"\n"; + */ + try{ + response = client.execute(method); + resCode = response.getStatusLine().getStatusCode(); + HttpEntity entity1 = response.getEntity(); + responseBody = EntityUtils.toString(entity1);} + catch(Exception ex){ + resCode=500; + responseBody=ex.getMessage(); + } + return this; + } + + public void setHeaders(Header[] headers) { + for (Header header : headers) { + this.method.addHeader(header); + } + } + + public String getResponseBodyAsString() { + return responseBody; + } + + public int getReturnCode() { + return resCode; + } + + public String getReqBody() { + return reqBody; + } + + public void setReqBody(String body) { + this.reqBody = body; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getPemPath() { + return pemPath; + } + + public void setPemPath(String pemPath) { + this.pemPath = pemPath; + } + + public String getChefPath() { + return chefPath; + } + + public void setChefPath(String chefPath) { + this.chefPath = chefPath; + } + + public String getOrganizations() { + return organizations; + } + + public void setOrganizations(String organizations) { + this.organizations = organizations; + } } diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Delete.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Delete.java index 779311400..85206af36 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Delete.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Delete.java @@ -28,9 +28,9 @@ import org.apache.http.client.methods.HttpDelete; public class Delete extends ApiMethod{ - public Delete(HttpDelete method) { - super("DELETE"); - this.method = method; - } + public Delete(HttpDelete method) { + super("DELETE"); + this.method = method; + } } diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Get.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Get.java index 6cf36606a..948bff6af 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Get.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Get.java @@ -28,9 +28,8 @@ import org.apache.http.client.methods.HttpGet; public class Get extends ApiMethod{ - public Get(HttpGet method) { - super("GET"); - this.method = method; - } - + public Get(HttpGet method) { + super("GET"); + this.method = method; + } } diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Post.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Post.java index 417f84eed..5e00b09a4 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Post.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Post.java @@ -29,18 +29,18 @@ import org.apache.http.entity.StringEntity; public class Post extends ApiMethod{ - public Post(HttpRequestBase method) { - super("POST"); - this.method = method; - } - - public ApiMethod body(String body){ - this.reqBody = body; - StringEntity params =new StringEntity (body,"UTF-8"); - params.setContentType("application/json"); - HttpPost post = (HttpPost) method; - post.setEntity(params); - return this; - } + public Post(HttpRequestBase method) { + super("POST"); + this.method = method; + } + + public ApiMethod body(String body){ + this.reqBody = body; + StringEntity params =new StringEntity (body,"UTF-8"); + params.setContentType("application/json"); + HttpPost post = (HttpPost) method; + post.setEntity(params); + return this; + } } diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Put.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Put.java index 8dea5296a..fa57c1117 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Put.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefapi/Put.java @@ -29,18 +29,18 @@ import org.apache.http.entity.StringEntity; public class Put extends ApiMethod{ - public Put(HttpRequestBase method) { - super("PUT"); - this.method = method; - } - - public ApiMethod body(String body){ - this.reqBody = body; - StringEntity params =new StringEntity (body,"UTF-8"); - params.setContentType("application/json"); - HttpPut put = (HttpPut) method; - put.setEntity(params); - return this; - } + public Put(HttpRequestBase method) { + super("PUT"); + this.method = method; + } + + public ApiMethod body(String body){ + this.reqBody = body; + StringEntity params =new StringEntity (body,"UTF-8"); + params.setContentType("application/json"); + HttpPut put = (HttpPut) method; + put.setEntity(params); + return this; + } } diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/ChefApiClient.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/ChefApiClient.java index 945ebc261..7aa63193b 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/ChefApiClient.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/ChefApiClient.java @@ -27,66 +27,61 @@ import org.apache.http.client.methods.*; import org.openecomp.appc.adapter.chef.chefapi.*; public class ChefApiClient { - private String endpoint; - private String userId; - private String pemPath; - private String organizations; + private String endpoint; + private String userId; + private String pemPath; + private String organizations; - + /** + * + * @param userId user name correspond to the pem key + * @param pemPath path of the auth key + * @param endpoint chef api server address + */ + public ChefApiClient(String userId, String pemPath, String endpoint,String organizations){ + this.userId = userId; + this.pemPath = pemPath; + this.endpoint = endpoint; + this.organizations=organizations; + } - - /** - * - * @param userId user name correspond to the pem key - * @param pemPath path of the auth key - * @param endpoint chef api server address - */ - public ChefApiClient(String userId, String pemPath, String endpoint,String organizations){ - this.userId = userId; - this.pemPath = pemPath; - this.endpoint = endpoint; - this.organizations=organizations; - } + /** + * + * @param path in the endpoint. e.g /clients + * @return + */ + public Get get(String path){ + Get get = new Get(new HttpGet(endpoint+path)); + get.setPemPath(pemPath); + get.setUserId(userId); + get.setOrganizations(organizations); + get.setChefPath(path); + return get; + } - /** - * - * @param path in the endpoint. e.g /clients - * @return - */ - public Get get(String path){ - Get get = new Get(new HttpGet(endpoint+path)); - get.setPemPath(pemPath); - get.setUserId(userId); - get.setOrganizations(organizations); - get.setChefPath(path); - return get; - } - - public Put put(String path){ - Put put = new Put(new HttpPut(endpoint+path)); - put.setPemPath(pemPath); - put.setUserId(userId); - put.setOrganizations(organizations); - put.setChefPath(path); - return put; + public Put put(String path){ + Put put = new Put(new HttpPut(endpoint+path)); + put.setPemPath(pemPath); + put.setUserId(userId); + put.setOrganizations(organizations); + put.setChefPath(path); + return put; } - public Post post(String path){ - Post post = new Post(new HttpPost(endpoint+path)); - post.setPemPath(pemPath); - post.setUserId(userId); - post.setOrganizations(organizations); - post.setChefPath(path); - return post; - } - - public Delete delete(String path){ - Delete del = new Delete(new HttpDelete(endpoint+path)); - del.setPemPath(pemPath); - del.setUserId(userId); - del.setOrganizations(organizations); - del.setChefPath(path); - return del; - } + public Post post(String path){ + Post post = new Post(new HttpPost(endpoint+path)); + post.setPemPath(pemPath); + post.setUserId(userId); + post.setOrganizations(organizations); + post.setChefPath(path); + return post; + } - + public Delete delete(String path){ + Delete del = new Delete(new HttpDelete(endpoint+path)); + del.setPemPath(pemPath); + del.setUserId(userId); + del.setOrganizations(organizations); + del.setChefPath(path); + return del; + } } diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/Utils.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/Utils.java index 07c983a43..d20228e04 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/Utils.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/chefclient/Utils.java @@ -44,64 +44,70 @@ import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.openssl.PEMKeyPair; public class Utils { - private Utils(){} - - public static String sha1AndBase64(String inStr) { - MessageDigest md = null; - String outStr = null; - byte[] outbty = null; - try { - md = MessageDigest.getInstance("SHA-1"); - byte[] digest = md.digest(inStr.getBytes()); - outbty = Base64.encode(digest); - } catch (NoSuchAlgorithmException nsae) { - nsae.printStackTrace(); - } - return new String(outbty); - } - - public static String signWithRSA(String inStr, String pemPath) { - byte[] outStr = null; - Security.addProvider(new BouncyCastleProvider()); - try (FileReader fr = new FileReader(pemPath); - BufferedReader br = new BufferedReader(fr)) { - PEMParser pemParser = new PEMParser(br); - JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); - Object object = pemParser.readObject(); - KeyPair kp = converter.getKeyPair((PEMKeyPair) object);; - PrivateKey privateKey = kp.getPrivate(); - Signature instance = Signature.getInstance("RSA"); - instance.initSign(privateKey); - instance.update(inStr.getBytes()); + private Utils(){} - byte[] signature = instance.sign(); - outStr = Base64.encode(signature); - String tmp = new String(outStr); - } catch (InvalidKeyException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (SignatureException e) { - e.printStackTrace(); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - return new String(outStr); - } - - public static String[] splitAs60(String inStr) { - int count = inStr.length() / 60; - String[] out = new String[count + 1]; + public static String sha1AndBase64(String inStr) { + MessageDigest md = null; + String outStr = null; + byte[] outbty = null; + try { + md = MessageDigest.getInstance("SHA-1"); + byte[] digest = md.digest(inStr.getBytes()); + outbty = Base64.encode(digest); + } catch (NoSuchAlgorithmException nsae) { + nsae.printStackTrace(); + } + return new String(outbty); + } + + public static String signWithRSA(String inStr, String pemPath) { + byte[] outStr = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(pemPath)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + Security.addProvider(new BouncyCastleProvider()); + try { + + PEMParser pemParser = new PEMParser(br); + JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); + Object object = pemParser.readObject(); + KeyPair kp = converter.getKeyPair((PEMKeyPair) object);; + PrivateKey privateKey = kp.getPrivate(); + Signature instance = Signature.getInstance("RSA"); + instance.initSign(privateKey); + instance.update(inStr.getBytes()); + + byte[] signature = instance.sign(); + outStr = Base64.encode(signature); + String tmp = new String(outStr); + } catch (InvalidKeyException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (SignatureException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return new String(outStr); + } + + public static String[] splitAs60(String inStr) { + int count = inStr.length() / 60; + String[] out = new String[count + 1]; + + for (int i = 0; i < count; i++) { + String tmp = inStr.substring(i * 60, i * 60 + 60); + out[i] = tmp; + } + if (inStr.length() > count * 60) { + String tmp = inStr.substring(count * 60, inStr.length()); + out[count] = tmp; + } + return out; + } - for (int i = 0; i < count; i++) { - String tmp = inStr.substring(i * 60, i * 60 + 60); - out[i] = tmp; - } - if (inStr.length() > count * 60) { - String tmp = inStr.substring(count * 60, inStr.length()); - out[count] = tmp; - } - return out; - } - } diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/ChefAdapterImpl.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/ChefAdapterImpl.java index 5326b66b4..048d362d4 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/ChefAdapterImpl.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/ChefAdapterImpl.java @@ -24,747 +24,491 @@ package org.openecomp.appc.adapter.chef.impl; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.regex.Pattern; -import java.util.*; - - +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.json.JSONObject; import org.openecomp.appc.Constants; import org.openecomp.appc.adapter.chef.ChefAdapter; -import org.openecomp.appc.adapter.chef.chefapi.*; -import org.openecomp.appc.adapter.chef.chefclient.*; +import org.openecomp.appc.adapter.chef.chefapi.ApiMethod; +import org.openecomp.appc.adapter.chef.chefclient.ChefApiClient; import org.openecomp.appc.configuration.Configuration; import org.openecomp.appc.configuration.ConfigurationFactory; -import org.openecomp.appc.exceptions.APPCException; -import org.openecomp.appc.exceptions.UnknownProviderException; -import org.openecomp.appc.i18n.Msg; -import org.openecomp.appc.pool.Pool; -import org.openecomp.appc.pool.PoolExtensionException; -import org.openecomp.appc.util.StructuredPropertyHelper; -import org.openecomp.appc.util.StructuredPropertyHelper.Node; -import com.att.cdp.exceptions.ContextConnectionException; -import com.att.cdp.exceptions.ResourceNotFoundException; -import com.att.cdp.exceptions.TimeoutException; -import com.att.cdp.exceptions.ZoneException; -import com.att.cdp.pal.util.StringHelper; -import com.att.cdp.zones.ComputeService; -import com.att.cdp.zones.Context; -import com.att.cdp.zones.ImageService; -import com.att.cdp.zones.Provider; -import com.att.cdp.zones.model.Image; -import com.att.cdp.zones.model.Server; -import com.att.cdp.zones.model.ServerBootSource; -import com.att.cdp.zones.model.Server.Status; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.i18n.EELFResourceManager; import org.openecomp.sdnc.sli.SvcLogicContext; -import org.slf4j.MDC; - -import java.net.InetAddress; -import java.util.Locale; -import java.util.UUID; - -import org.apache.http.*; -import org.apache.http.client.*; -import org.apache.http.client.methods.*; -import org.apache.http.impl.client.*; -import org.apache.http.util.EntityUtils; - -import static com.att.eelf.configuration.Configuration.*; - -import java.io.IOException; - -import java.net.InetAddress; -import java.io.BufferedInputStream; import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Properties; -//chef -import org.openecomp.appc.adapter.chef.chefapi.*; -import org.openecomp.appc.adapter.chef.chefclient.*; - -//json -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; +import java.util.Map; + /** * This class implements the {@link ChefAdapter} interface. This interface * defines the behaviors that our service provides. */ public class ChefAdapterImpl implements ChefAdapter { - - // chef server Initialize variable - public String clientName = ""; - public String clientPrivatekey = ""; - public String chefserver = ""; - public String serverAddress = ""; - public String organizations = ""; - @SuppressWarnings("nls") - public static final String MDC_ADAPTER = "adapter"; - - @SuppressWarnings("nls") - public static final String MDC_SERVICE = "service"; - - @SuppressWarnings("nls") - public static final String OUTCOME_FAILURE = "failure"; - - @SuppressWarnings("nls") - public static final String OUTCOME_SUCCESS = "success"; - - @SuppressWarnings("nls") - public static final String PROPERTY_PROVIDER = "provider"; - - @SuppressWarnings("nls") - public static final String PROPERTY_PROVIDER_IDENTITY = "identity"; - - @SuppressWarnings("nls") - public static final String PROPERTY_PROVIDER_NAME = "name"; - - @SuppressWarnings("nls") - public static final String PROPERTY_PROVIDER_TENANT = "tenant"; - - @SuppressWarnings("nls") - public static final String PROPERTY_PROVIDER_TENANT_NAME = "name"; - - @SuppressWarnings("nls") - public static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR - - @SuppressWarnings("nls") - public static final String PROPERTY_PROVIDER_TENANT_USERID = "userid"; - - @SuppressWarnings("nls") - public static final String PROPERTY_PROVIDER_TYPE = "type"; - - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class); - - private static final char LPAREN = '('; - - private static final char NL = '\n'; - - private static final char QUOTE = '\''; - - private static final char RPAREN = ')'; - - private static final char SPACE = ' '; - - public ChefAdapterImpl() { - initialize(); - - } - - public ChefAdapterImpl(boolean initialize) { - - if (initialize) { - initialize(); - - } - } - - public ChefAdapterImpl(Properties props) { - initialize(); - - } - - public ChefAdapterImpl(String key) { - initialize(); - - } - - - @Override - public String getAdapterName() { - return "chef adapter"; - } - - - @SuppressWarnings("nls") - @Override - public void VnfcEnvironment(Map<String, String> params, SvcLogicContext ctx) { - logger.info("environment of VNF-C"); - chefInfo(params); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - String env = params.get("Environment"); - if(env.equals("")){ - chefServerResult(rc, "200", "Skip Environment block ");} - else{ - JSONObject env_J = new JSONObject(env); - String envName = env_J.getString("name"); - int code; - String message = null; - if (privateKeyCheck()) { - // update the details of an environment on the Chef server. - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.put("/environments/"+envName).body(env); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - if(code == 404 ){ - //need create a new environment - am = cac.post("/environments").body(env); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - } - - } else { - code = 500; - message = "Cannot find the private key in the APPC file system, please load the private key to " - + clientPrivatekey; - } - chefServerResult(rc, Integer.toString(code), message); - } - } - - - @SuppressWarnings("nls") - @Override - public void VnfcNodeobjects(Map<String, String> params, SvcLogicContext ctx) { - logger.info("update the nodeObjects of VNF-C"); - chefInfo(params); - String nodeList_S = params.get("NodeList"); - String node_S = params.get("Node"); - nodeList_S = nodeList_S.replace("[",""); - nodeList_S = nodeList_S.replace("]",""); - nodeList_S = nodeList_S.replace("\"",""); - nodeList_S = nodeList_S.replace(" ",""); - List<String> nodes = Arrays.asList(nodeList_S.split("\\s*,\\s*")); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - int code=200; - String message = null; - if (privateKeyCheck()) { - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - - for(int i = 0; i < nodes.size(); i++){ - String nodeName=nodes.get(i); - JSONObject node_J = new JSONObject(node_S); - node_J.remove("name"); - node_J.put("name",nodeName); - String nodeObject=node_J.toString(); - logger.info(nodeObject); - ApiMethod am = cac.put("/nodes/"+nodeName).body(nodeObject); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - if(code != 200){ - break; - } - - } - }else{ - code = 500; - message = "Cannot find the private key in the APPC file system, please load the private key to " - + clientPrivatekey; - } - chefServerResult(rc, Integer.toString(code), message); - } - - - @SuppressWarnings("nls") - @Override - public void VnfcPushJob(Map<String, String> params, SvcLogicContext ctx) { - chefInfo(params); - String nodeList = params.get("NodeList"); - String isCallback = params.get("CallbackCapable"); - String chefAction = "/pushy/jobs"; - //need work on this - String pushRequest=""; - if(isCallback.equals("true")){ - String requestId = params.get("RequestId"); - String callbackUrl = params.get("CallbackUrl"); - pushRequest="{"+ - "\"command\": \"chef-client\","+ - "\"run_timeout\": 300,"+ - "\"nodes\":" +nodeList +","+ - "\"env\": {\"RequestId\": \""+ requestId +"\", \"CallbackUrl\": \""+ callbackUrl +"\"},"+ - "\"capture_output\": true"+ - "}"; - }else{ - pushRequest="{"+ - "\"command\": \"chef-client\","+ - "\"run_timeout\": 300,"+ - "\"nodes\":" +nodeList +","+ - "\"env\": {},"+ - "\"capture_output\": true"+ - "}"; - } - RequestContext rc = new RequestContext(ctx); - - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.post(chefAction).body(pushRequest); - - am.execute(); - int code = am.getReturnCode(); - String message = am.getResponseBodyAsString(); - if (code == 201) { - int startIndex = message.indexOf("jobs") + 5; - int endIndex = message.length() - 2; - String jobID = message.substring(startIndex, endIndex); - svcLogic.setAttribute("jobID", jobID); - logger.info(jobID); - } - chefServerResult(rc, Integer.toString(code), message); - } - - - @SuppressWarnings("nls") - @Override - public void fetchResults (Map<String, String> params, SvcLogicContext ctx) { - chefInfo(params); - String nodeList_S = params.get("NodeList"); - nodeList_S = nodeList_S.replace("[",""); - nodeList_S = nodeList_S.replace("]",""); - nodeList_S = nodeList_S.replace("\"",""); - nodeList_S = nodeList_S.replace(" ",""); - List<String> nodes = Arrays.asList(nodeList_S.split("\\s*,\\s*")); - JSONObject Result = new JSONObject(); - String returnCode= "200"; - String returnMessage=""; - for (int i = 0; i < nodes.size(); i++){ - String node=nodes.get(i); - String chefAction="/nodes/"+node; - int code; - String message = null; - if (privateKeyCheck()) { - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.get(chefAction); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - } else { - code = 500; - message = "Cannot find the private key in the APPC file system, please load the private key to " - + clientPrivatekey; - } - if (code==200){ - JSONObject nodeResult = new JSONObject(); - JSONObject allNodeData = new JSONObject(message); - String attribute= "PushJobOutput"; - String resultData; - allNodeData=allNodeData.getJSONObject("normal"); - try { - resultData = allNodeData.getString(attribute); - } catch (Exception exc1) { - try { - resultData = allNodeData.getJSONObject(attribute).toString(); - } catch (Exception exc2) { - try { - resultData = allNodeData.getJSONArray(attribute).toString(); - }catch (Exception exc3){ - returnCode = "500"; - returnMessage="cannot find "+attribute; - break; - } - } - } - nodeResult.put(attribute,resultData); - - Result.put(node,nodeResult); - }else{ - returnCode="500"; - returnMessage = message+" Cannot access: "+ node; - break; - } - - } - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - if (!returnCode.equals("500")){ - returnMessage=Result.toString(); - returnCode="200"; - } - chefServerResult(rc, returnCode, returnMessage); - } - - - - /** - * build node object - */ - - @SuppressWarnings("nls") - @Override - public void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) { - logger.info("nodeObejctBuilder"); - String name = params.get("org.openecomp.appc.instance.nodeobject.name"); - String normal = params.get("org.openecomp.appc.instance.nodeobject.normal"); - String overrides = params.get("org.openecomp.appc.instance.nodeobject.overrides"); - String defaults = params.get("org.openecomp.appc.instance.nodeobject.defaults"); - String run_list = params.get("org.openecomp.appc.instance.nodeobject.run_list"); - String chef_environment = params.get("org.openecomp.appc.instance.nodeobject.chef_environment"); - String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults - + "},\"chef_type\":\"node\",\"run_list\":[" + run_list + "],\"override\":{" + overrides - + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\"" - + chef_environment + "\"}"; - logger.info(nodeObject); - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setAttribute("org.openecomp.appc.chef.nodeObject", nodeObject); - - } - - /** - * Nicolas send get request to chef server - */ - - public void chefInfo(Map<String, String> params) { - clientName = params.get("org.openecomp.appc.instance.username"); - serverAddress = params.get("org.openecomp.appc.instance.serverAddress"); - organizations = params.get("org.openecomp.appc.instance.organizations"); - chefserver = "https://" + serverAddress + "/organizations/" + organizations; - clientPrivatekey = "/opt/app/bvc/chef/" + serverAddress + "/" + organizations + "/" + clientName + ".pem"; - } - - public Boolean privateKeyCheck() { - File f = new File(clientPrivatekey); - if (f.exists()) { - return true; - } else { - return false; - } - } - - @SuppressWarnings("nls") - @Override - public void retrieveData(Map<String, String> params, SvcLogicContext ctx) { - String contextData = "someValue"; - String allConfigData = params.get("org.openecomp.appc.instance.allConfig"); - String key = params.get("org.openecomp.appc.instance.key"); - String dgContext = params.get("org.openecomp.appc.instance.dgContext"); - JSONObject josnConfig = new JSONObject(allConfigData); - try { - contextData = josnConfig.getString(key); - } catch (Exception ex) { - try { - contextData = josnConfig.getJSONObject(key).toString(); - } catch (Exception exc) { - contextData = josnConfig.getJSONArray(key).toString(); - } - } - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setAttribute(dgContext, contextData); - } - - @SuppressWarnings("nls") - @Override - public void combineStrings(Map<String, String> params, SvcLogicContext ctx) { - - String String1 = params.get("org.openecomp.appc.instance.String1"); - String String2 = params.get("org.openecomp.appc.instance.String2"); - String dgContext = params.get("org.openecomp.appc.instance.dgContext"); - String contextData = String1 + String2; - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setAttribute(dgContext, contextData); - } - - - /** - * Send GET request to chef server - */ - - @SuppressWarnings("nls") - @Override - public void chefGet(Map<String, String> params, SvcLogicContext ctx) { - logger.info("chef get method"); - chefInfo(params); - String chefAction = params.get("org.openecomp.appc.instance.chefAction"); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - int code; - String message = null; - if (privateKeyCheck()) { - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.get(chefAction); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - } else { - code = 500; - message = "Cannot find the private key in the APPC file system, please load the private key to " - + clientPrivatekey; - } - chefServerResult(rc, Integer.toString(code), message); - - } - - /** - * send put request to chef server - */ - - @SuppressWarnings("nls") - @Override - public void chefPut(Map<String, String> params, SvcLogicContext ctx) { - chefInfo(params); - String chefAction = params.get("org.openecomp.appc.instance.chefAction"); - String CHEF_NODE_STR = params.get("org.openecomp.appc.instance.chefRequestBody"); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - int code; - String message = null; - if (privateKeyCheck()) { - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - - ApiMethod am = cac.put(chefAction).body(CHEF_NODE_STR); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - } else { - code = 500; - message = "Cannot find the private key in the APPC file system, please load the private key to " - + clientPrivatekey; - } - logger.info(code + " " + message); - chefServerResult(rc, Integer.toString(code), message); - - } - - /** - * Nicolas send Post request to chef server - */ - - @SuppressWarnings("nls") - @Override - public void chefPost(Map<String, String> params, SvcLogicContext ctx) { - chefInfo(params); - logger.info("chef Post method"); - logger.info(clientName + " " + clientPrivatekey + " " + chefserver + " " + organizations); - String CHEF_NODE_STR = params.get("org.openecomp.appc.instance.chefRequestBody"); - String chefAction = params.get("org.openecomp.appc.instance.chefAction"); - - // attributes="\"reconfig-test\":{\"secret\":\"newpass2\"}"; - // String CHEF_NODE_STR = - // "{\"json_class\":\"Chef::Node\",\"default\":{},\"chef_type\":\"node\",\"run_list\":[\""+runList+"\"],\"override\":{},\"automatic\":{},\"normal\":{"+attributes+"},\"name\":\"testnode\",\"chef_environment\":\"_default\"}"; - // String CHEF_NODE_STR = "{\"json_class\":\"Chef::Node\"}"; - // logger.info(vm_url); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - int code; - String message = null; - // should load pem from somewhere else - if (privateKeyCheck()) { - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - - // need pass path into it - // "/nodes/testnode" - ApiMethod am = cac.post(chefAction).body(CHEF_NODE_STR); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - } else { - code = 500; - message = "Cannot find the private key in the APPC file system, please load the private key to " - + clientPrivatekey; - } - logger.info(code + " " + message); - chefServerResult(rc, Integer.toString(code), message); - } - - /** - * Nicolas send delete request to chef server - */ - - @SuppressWarnings("nls") - @Override - public void chefDelete(Map<String, String> params, SvcLogicContext ctx) { - logger.info("chef delete method"); - chefInfo(params); - String chefAction = params.get("org.openecomp.appc.instance.chefAction"); - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - int code; - String message = null; - if (privateKeyCheck()) { - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.delete(chefAction); - am.execute(); - code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - } else { - code = 500; - message = "Cannot find the private key in the APPC file system, please load the private key to " - + clientPrivatekey; - } - logger.info(code + " " + message); - chefServerResult(rc, Integer.toString(code), message); - } - - - - - - - @SuppressWarnings("nls") - @Override - public void trigger(Map<String, String> params, SvcLogicContext ctx) { - logger.info("Run trigger method"); - String tVmIp = params.get("ip"); - // String tUrl = "http://" + tVmIp; - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - - HttpGet httpGet = new HttpGet(tVmIp); - try ( CloseableHttpClient httpClient = HttpClients.createDefault(); - CloseableHttpResponse response = httpClient.execute(httpGet); ) - { - int responseCode = response.getStatusLine().getStatusCode(); - HttpEntity entity = response.getEntity(); - String responseOutput = EntityUtils.toString(entity); - chefClientResult(rc, Integer.toString(responseCode), responseOutput); - doSuccess(rc); - } catch (Exception ex) { - doFailure(rc, 500, ex.toString()); - } - } - - - - - @SuppressWarnings("nls") - @Override - public void checkPushJob(Map<String, String> params, SvcLogicContext ctx) { - chefInfo(params); - String jobID = params.get("org.openecomp.appc.instance.jobid"); - int retryTimes = Integer.parseInt(params.get("org.openecomp.appc.instance.retryTimes")); - int retryInterval = Integer.parseInt(params.get("org.openecomp.appc.instance.retryInterval")); - String chefAction = "/pushy/jobs/" + jobID; - - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - String message = ""; - String status = ""; - for (int i = 0; i < retryTimes; i++) { - try { - Thread.sleep(retryInterval); // 1000 milliseconds is one second. - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.get(chefAction); - am.execute(); - int code = am.getReturnCode(); - message = am.getResponseBodyAsString(); - JSONObject obj = new JSONObject(message); - status = obj.getString("status"); - if (!status.equals("running")) { - logger.info(i + " time " + code + " " + status); - break; - } - - } - if (status.equals("complete")) { - svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", "200"); - svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", message); - } else { - if (status.equals("running")) { - svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", "202"); - svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", "chef client runtime out"); - } else { - svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", "500"); - svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", message); - } - } - } - - - @SuppressWarnings("nls") - @Override - public void pushJob(Map<String, String> params, SvcLogicContext ctx) { - chefInfo(params); - String pushRequest = params.get("org.openecomp.appc.instance.pushRequest"); - String chefAction = "/pushy/jobs"; - RequestContext rc = new RequestContext(ctx); - rc.isAlive(); - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); - ApiMethod am = cac.post(chefAction).body(pushRequest); - ; - am.execute(); - int code = am.getReturnCode(); - String message = am.getResponseBodyAsString(); - if (code == 201) { - int startIndex = message.indexOf("jobs") + 6; - int endIndex = message.length() - 2; - String jobID = message.substring(startIndex, endIndex); - svcLogic.setAttribute("org.openecomp.appc.jobID", jobID); - logger.info(jobID); - } - chefServerResult(rc, Integer.toString(code), message); - } - - @SuppressWarnings("static-method") - private void doFailure(RequestContext rc, int code, String message) { - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - String msg = (message == null) ? Integer.toString(code) : message; - if (msg.contains("\n")) { - msg = msg.substring(msg.indexOf("\n")); - } - - String status; - try { - status = Integer.toString(code); - } catch (Exception e) { - status = "500"; - } - svcLogic.setAttribute("chefAgent.code", status); - svcLogic.setAttribute("chefAgent.message", msg); - } - - - @SuppressWarnings("static-method") - private void doSuccess(RequestContext rc) { - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setAttribute("chefAgent.code", "200"); - } - - @SuppressWarnings("static-method") - private void chefServerResult(RequestContext rc, String code, String message) { - String msg = (message == null) ? " " : message; - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setStatus(OUTCOME_SUCCESS); - svcLogic.setAttribute("chefServerResult.code", code); - svcLogic.setAttribute("chefServerResult.message", message); - } - - @SuppressWarnings("static-method") - private void chefClientResult(RequestContext rc, String code, String message) { - String msg = (message == null) ? " " : message; - SvcLogicContext svcLogic = rc.getSvcLogicContext(); - svcLogic.setStatus(OUTCOME_SUCCESS); - svcLogic.setAttribute("chefClientResult.code", code); - svcLogic.setAttribute("chefClientResult.message", message); - } - - - private void initialize() { - - logger.info("init chef adapter!!!!!"); - - } - - + //chef server Initialize variable + private String clientName=""; + private String clientPrivatekey=""; + private String chefserver=""; + private String serverAddress=""; + private String organizations=""; + + /** + * The constant for the status code for a successful outcome + */ + private static final String OUTCOME_SUCCESS = "success"; + + /** + * The logger to be used + */ + private final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class); + + /** + * A reference to the adapter configuration object. + */ + private Configuration configuration; + + /** + * This default constructor is used as a work around because the activator + * wasnt getting called + */ + public ChefAdapterImpl() { + initialize(); + + } + + /** + * This constructor is used primarily in the test cases to bypass + * initialization of the adapter for isolated, disconnected testing + * + * @param initialize + * True if the adapter is to be initialized, can false if not + */ + public ChefAdapterImpl(boolean initialize) { + configuration = ConfigurationFactory.getConfiguration(); + if (initialize) { + initialize(); + + } + } + + public ChefAdapterImpl(String key) { + initialize(key); + + } + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + * @see org.openecomp.appc.adapter.chef.ChefAdapter#getAdapterName() + */ + @Override + public String getAdapterName() { + return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME); + } + + private void X__________________________________X() { + } + + /** + * @see org.openecomp.appc.adapter.chef.ChefAdapter#evacuateServer(java.util.Map, + * org.openecomp.sdnc.sli.SvcLogicContext) + */ + + private void X___________________________________X() { + } + + /** + * @see org.openecomp.appc.adapter.chef.ProviderAdapter#rebuildServer(java.util.Map, + * org.openecomp.sdnc.sli.SvcLogicContext) + */ + + + /** + * build node object + */ + + @SuppressWarnings("nls") + @Override + public void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) { + logger.info("nodeObejctBuilder"); + String name = params.get("org.openecomp.appc.instance.nodeobject.name"); + String normal = params.get("org.openecomp.appc.instance.nodeobject.normal"); + String overrides = params.get("org.openecomp.appc.instance.nodeobject.overrides"); + String defaults = params.get("org.openecomp.appc.instance.nodeobject.defaults"); + String run_list = params.get("org.openecomp.appc.instance.nodeobject.run_list"); + String chef_environment = params.get("org.openecomp.appc.instance.nodeobject.chef_environment"); + String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults + + "},\"chef_type\":\"node\",\"run_list\":[" + run_list + "],\"override\":{" + overrides + + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\"" + + chef_environment + "\"}"; + logger.info(nodeObject); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setAttribute("org.openecomp.appc.chef.nodeObject", nodeObject); + + } + + /** + * Nicolas send get request to chef server + */ + public void chefInfo(Map<String, String> params) { + clientName = params.get("org.openecomp.appc.instance.username"); + serverAddress = params.get("org.openecomp.appc.instance.serverAddress"); + organizations = params.get("org.openecomp.appc.instance.organizations"); + chefserver = "https://" + serverAddress + "/organizations/" + organizations; + clientPrivatekey = "/opt/app/bvc/chef/" + serverAddress + "/" + organizations + "/" + clientName + ".pem"; + } + + public Boolean privateKeyCheck() { + File f = new File(clientPrivatekey); + return f.exists(); + } + + @SuppressWarnings("nls") + @Override + public void retrieveData(Map<String, String> params, SvcLogicContext ctx) { + String allConfigData = params.get("org.openecomp.appc.instance.allConfig"); + String key = params.get("org.openecomp.appc.instance.key"); + String dgContext = params.get("org.openecomp.appc.instance.dgContext"); + JSONObject josnConfig = new JSONObject(allConfigData); + + String contextData; + try { + contextData = josnConfig.getString(key); + } catch (Exception ex) { + try { + contextData = josnConfig.getJSONObject(key).toString(); + } catch (Exception exc) { + contextData = josnConfig.getJSONArray(key).toString(); + } + } + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setAttribute(dgContext, contextData); + } + + @SuppressWarnings("nls") + @Override + public void combineStrings(Map<String, String> params, SvcLogicContext ctx) { + + String String1 = params.get("org.openecomp.appc.instance.String1"); + String String2 = params.get("org.openecomp.appc.instance.String2"); + String dgContext = params.get("org.openecomp.appc.instance.dgContext"); + String contextData = String1 + String2; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setAttribute(dgContext, contextData); + } + + + /** + * Send GET request to chef server + */ + + @SuppressWarnings("nls") + @Override + public void chefGet(Map<String, String> params, SvcLogicContext ctx) { + logger.info("chef get method"); + chefInfo(params); + String chefAction = params.get("org.openecomp.appc.instance.chefAction"); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + int code; + String message; + if (privateKeyCheck()) { + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + ApiMethod am = cac.get(chefAction); + am.execute(); + code = am.getReturnCode(); + message = am.getResponseBodyAsString(); + } else { + code = 500; + message = "Cannot find the private key in the APPC file system, please load the private key to " + + clientPrivatekey; + } + chefServerResult(rc, Integer.toString(code), message); + + } + + /** + * Send PUT request to chef server + */ + @SuppressWarnings("nls") + @Override + public void chefPut(Map<String, String> params, SvcLogicContext ctx) { + chefInfo(params); + String chefAction = params.get("org.openecomp.appc.instance.chefAction"); + String CHEF_NODE_STR = params.get("org.openecomp.appc.instance.chefRequestBody"); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + int code; + String message; + if (privateKeyCheck()) { + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + + ApiMethod am = cac.put(chefAction).body(CHEF_NODE_STR); + am.execute(); + code = am.getReturnCode(); + message = am.getResponseBodyAsString(); + } else { + code = 500; + message = "Cannot find the private key in the APPC file system, please load the private key to " + + clientPrivatekey; + } + logger.info(code + " " + message); + chefServerResult(rc, Integer.toString(code), message); + + } + + /** + * Nicolas send Post request to chef server + */ + + @SuppressWarnings("nls") + @Override + public void chefPost(Map<String, String> params, SvcLogicContext ctx) { + chefInfo(params); + logger.info("chef Post method"); + logger.info(clientName + " " + clientPrivatekey + " " + chefserver + " " + organizations); + String CHEF_NODE_STR = params.get("org.openecomp.appc.instance.chefRequestBody"); + String chefAction = params.get("org.openecomp.appc.instance.chefAction"); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + int code; + String message; + // should load pem from somewhere else + if (privateKeyCheck()) { + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + + // need pass path into it + // "/nodes/testnode" + ApiMethod am = cac.post(chefAction).body(CHEF_NODE_STR); + am.execute(); + code = am.getReturnCode(); + message = am.getResponseBodyAsString(); + } else { + code = 500; + message = "Cannot find the private key in the APPC file system, please load the private key to " + + clientPrivatekey; + } + logger.info(code + " " + message); + chefServerResult(rc, Integer.toString(code), message); + } + + /** + * Nicolas send delete request to chef server + */ + + @SuppressWarnings("nls") + @Override + public void chefDelete(Map<String, String> params, SvcLogicContext ctx) { + logger.info("chef delete method"); + chefInfo(params); + String chefAction = params.get("org.openecomp.appc.instance.chefAction"); + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + int code; + String message; + if (privateKeyCheck()) { + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + ApiMethod am = cac.delete(chefAction); + am.execute(); + code = am.getReturnCode(); + message = am.getResponseBodyAsString(); + } else { + code = 500; + message = "Cannot find the private key in the APPC file system, please load the private key to " + + clientPrivatekey; + } + logger.info(code + " " + message); + chefServerResult(rc, Integer.toString(code), message); + } + + + /** + * Trigger target vm run chef + */ + + @SuppressWarnings("nls") + @Override + public void trigger(Map<String, String> params, SvcLogicContext ctx) { + logger.info("Run trigger method"); + String tVmIp = params.get("org.openecomp.appc.instance.ip"); + //String tUrl = "http://" + tVmIp; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + try { + HttpGet httpGet = new HttpGet(tVmIp); + HttpClient httpClient = HttpClients.createDefault(); + HttpResponse response; + response = httpClient.execute(httpGet); + int responseCode=response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String responseOutput=EntityUtils.toString(entity); + chefClientResult(rc,Integer.toString(responseCode),responseOutput); + doSuccess(rc); + } catch (Exception ex) { + doFailure(rc, 500 , ex.toString()); + } + } + + + @SuppressWarnings("nls") + @Override + public void checkPushJob(Map<String, String> params, SvcLogicContext ctx) { + chefInfo(params); + String jobID = params.get("org.openecomp.appc.instance.jobid"); + int retryTimes = Integer.parseInt(params.get("org.openecomp.appc.instance.retryTimes")); + int retryInterval = Integer.parseInt(params.get("org.openecomp.appc.instance.retryInterval")); + String chefAction = "/pushy/jobs/" + jobID; + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + String message = ""; + String status = ""; + for (int i = 0; i < retryTimes; i++) { + try { + Thread.sleep(retryInterval); // 1000 milliseconds is one second. + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + ApiMethod am = cac.get(chefAction); + am.execute(); + int code = am.getReturnCode(); + message = am.getResponseBodyAsString(); + JSONObject obj = new JSONObject(message); + status = obj.getString("status"); + if (!status.equals("running")) { + logger.info(i + " time " + code + " " + status); + break; + } + + } + if (status.equals("complete")) { + svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", "200"); + svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", message); + } else { + if (status.equals("running")) { + svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", "202"); + svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", "chef client runtime out"); + } else { + svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", "500"); + svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", message); + } + } + } + + + @SuppressWarnings("nls") + @Override + public void pushJob(Map<String, String> params, SvcLogicContext ctx) { + chefInfo(params); + String pushRequest = params.get("org.openecomp.appc.instance.pushRequest"); + String chefAction = "/pushy/jobs"; + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations); + ApiMethod am = cac.post(chefAction).body(pushRequest); + + am.execute(); + int code = am.getReturnCode(); + String message = am.getResponseBodyAsString(); + if (code == 201) { + int startIndex = message.indexOf("jobs") + 6; + int endIndex = message.length() - 2; + String jobID = message.substring(startIndex, endIndex); + svcLogic.setAttribute("org.openecomp.appc.jobID", jobID); + logger.info(jobID); + } + chefServerResult(rc, Integer.toString(code), message); + } + + + @SuppressWarnings("static-method") + private void doFailure(RequestContext rc, int code, String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + String msg = (message == null) ? Integer.toString(code) : message; + if (msg.contains("\n")) { + msg = msg.substring(msg.indexOf("\n")); + } + + String status; + try { + status = Integer.toString(code); + } catch (Exception e) { + status = "500"; + } + svcLogic.setAttribute("org.openecomp.appc.chefAgent.code", status); + svcLogic.setAttribute("org.openecomp.appc.chefAgent.message", msg); + } + + /** + * @param rc + * The request context that manages the state and recovery of the + * request for the life of its processing. + */ + + @SuppressWarnings("static-method") + private void doSuccess(RequestContext rc) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setAttribute("org.openecomp.appc.chefAgent.code", "200"); + } + + + @SuppressWarnings("static-method") + private void chefServerResult(RequestContext rc, String code ,String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setStatus(OUTCOME_SUCCESS); + svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", code); + svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", message); + } + + @SuppressWarnings("static-method") + private void chefClientResult(RequestContext rc, String code ,String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setStatus(OUTCOME_SUCCESS); + svcLogic.setAttribute("org.openecomp.appc.chefClientResult.code", code); + svcLogic.setAttribute("org.openecomp.appc.chefClientResult.message", message); + } + + /** + * initialize the provider adapter by building the context cache + */ + private void initialize() { + configuration = ConfigurationFactory.getConfiguration(); + //need to fetch data from appc configurator or form some file in the appc vms + clientName="testnode"; + clientPrivatekey="/etc/chef/client.pem"; + serverAddress="http://example.com"; + organizations="test"; + chefserver=serverAddress+"/organizations/"+organizations; + logger.info("Initialize Chef Adapter"); + } + + private void initialize(String key) { + configuration = ConfigurationFactory.getConfiguration(); + //need to fetch data from appc configurator or form some file in the appc vms + clientName="testnode"; + clientPrivatekey=key; + serverAddress="http://example.com"; + organizations="test"; + chefserver=serverAddress+"/organizations/"+organizations; + logger.info("Initialize Chef Adapter"); + } } diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/RequestContext.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/RequestContext.java index 411176af9..836f6aaff 100644 --- a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/RequestContext.java +++ b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/RequestContext.java @@ -89,7 +89,7 @@ public class RequestContext { /** * Creates the request context - * + * * @param context * The service logic (SLI) context associated with the current DG */ @@ -146,7 +146,7 @@ public class RequestContext { /** * Check and count the connection attempt. - * + * * @return True if the connection should be attempted. False indicates that the number of retries has been exhausted * and it should NOT be attempted. */ @@ -183,7 +183,7 @@ public class RequestContext { * the total time used is less than or equal to the time to live limit, the method returns true. It is important to * call this method at the very beginning of the process so that all parts of the process are tracked. * </p> - * + * * @return True if the total time to live has not been exceeded. False indicates that the total time to live has * been exceeded and no further processing should be performed. */ @@ -217,7 +217,7 @@ public class RequestContext { /** * Sets the time to live to the value, expressed in seconds - * + * * @param time * The time to live, in seconds */ @@ -227,7 +227,7 @@ public class RequestContext { /** * Sets the time to live to the value, expressed in milliseconds - * + * * @param time * The time to live, in milliseconds */ |