diff options
author | SrikanthN <sn00469487@techmahindra.com> | 2019-01-29 21:02:15 +0530 |
---|---|---|
committer | SrikanthN <sn00469487@techmahindra.com> | 2019-01-29 21:02:15 +0530 |
commit | 28b6e97d3929f94f91c4bf57f1d0273d8c8a73e0 (patch) | |
tree | 2926aaf0dab2970403be793a3dabba3f33351dbf | |
parent | bb386b16dac2b9843625f7d7ad3b7b9efac17156 (diff) |
VES5.4.1 JAVA LIB-Agent Enhancements
HB-Fault-Measurement-Syslog-2Collector enhancements Issue-ID: VNFSDK-363
Change-Id: Ic37b8dc490c06d2d8ddf6a81b632f4dbd3893a36
Signed-off-by: SrikanthN <sn00469487@techmahindra.com>
20 files changed, 3259 insertions, 283 deletions
diff --git a/veslibrary/ves_javalibrary/evel_javalib2/pom.xml b/veslibrary/ves_javalibrary/evel_javalib2/pom.xml index 9ebbcef..9d0db82 100644 --- a/veslibrary/ves_javalibrary/evel_javalib2/pom.xml +++ b/veslibrary/ves_javalibrary/evel_javalib2/pom.xml @@ -82,6 +82,11 @@ ECOMP is a trademark and service mark of AT&T Intellectual Property. <version>1.2.17</version> </dependency> <dependency> + <groupId>com.googlecode.json-simple</groupId> + <artifactId>json-simple</artifactId> + <version>1.1.1</version> + </dependency> + <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> <version>1.1</version> diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/AgentMain.java b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/AgentMain.java index 7380d90..0dda0f5 100644 --- a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/AgentMain.java +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/AgentMain.java @@ -35,10 +35,14 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; +import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.MalformedURLException; +import java.io.UnsupportedEncodingException; import java.net.URL; +import java.nio.channels.InterruptedByTimeoutException; import java.security.KeyStore; +import java.time.Duration; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; @@ -57,219 +61,420 @@ import org.apache.log4j.BasicConfigurator; public class AgentMain { - -/**************************************************************************//** - * Error codes - * - * Error codes for EVEL low level interface - *****************************************************************************/ -public enum EVEL_ERR_CODES { - EVEL_SUCCESS, /** The operation was successful. */ - EVEL_ERR_GEN_FAIL, /** Non-specific failure. */ - EVEL_CURL_LIBRARY_FAIL, /** A cURL library operation failed. */ - EVEL_PTHREAD_LIBRARY_FAIL, /** A Posix threads operation failed. */ - EVEL_OUT_OF_MEMORY, /** A memory allocation failure occurred. */ - EVEL_EVENT_BUFFER_FULL, /** Too many events in the ring-buffer. */ - EVEL_EVENT_HANDLER_INACTIVE, /** Attempt to raise event when inactive. */ - EVEL_NO_METADATA, /** Failed to retrieve OpenStack metadata. */ - EVEL_BAD_METADATA, /** OpenStack metadata invalid format. */ - EVEL_BAD_JSON_FORMAT, /** JSON failed to parse correctly. */ - EVEL_JSON_KEY_NOT_FOUND, /** Failed to find the specified JSON key. */ - EVEL_MAX_ERROR_CODES /** Maximum number of valid error codes. */ -} - - private static final Logger logger = Logger.getLogger(AgentMain.class); - - private static String url = null; - private static URL vesurl = null; - private static URL vesbatchurl = null; - private static HttpURLConnection con = null; - private static String userpass = null; - private static String keystore_pth = null; - private static String jks_passw = null; - private static String key_passw = null; - private static String version = "5"; - - /* RingBuffer to forward messages on sending AgentDispatcher thread */ - private static RingBuffer ringb = new RingBuffer(100); - - Thread thr; - - /* AgentDispatcher loops on messages in RingBuffer and POSTs them - * to external Collector - */ + + /**************************************************************************//** + * Error codes + * + * Error codes for EVEL low level interface + *****************************************************************************/ + public enum EVEL_ERR_CODES { + EVEL_SUCCESS, /** The operation was successful. */ + EVEL_ERR_GEN_FAIL, /** Non-specific failure. */ + EVEL_CURL_LIBRARY_FAIL, /** A cURL library operation failed. */ + EVEL_PTHREAD_LIBRARY_FAIL, /** A Posix threads operation failed. */ + EVEL_OUT_OF_MEMORY, /** A memory allocation failure occurred. */ + EVEL_EVENT_BUFFER_FULL, /** Too many events in the ring-buffer. */ + EVEL_EVENT_HANDLER_INACTIVE, /** Attempt to raise event when inactive. */ + EVEL_NO_METADATA, /** Failed to retrieve OpenStack metadata. */ + EVEL_BAD_METADATA, /** OpenStack metadata invalid format. */ + EVEL_BAD_JSON_FORMAT, /** JSON failed to parse correctly. */ + EVEL_JSON_KEY_NOT_FOUND, /** Failed to find the specified JSON key. */ + EVEL_MAX_ERROR_CODES /** Maximum number of valid error codes. */ + } + + private static final Logger logger = Logger.getLogger(AgentMain.class); + + private static String url = null; + private static URL vesurl = null; + private static URL vesbatchurl = null; + private static HttpURLConnection con = null; + private static String userpass = null; + private static String keystorePath = null; + private static String jksPassw = null; + private static String keyPassw = null; + private static String version = "7"; + + + + private static String userpass2 = null; + private static String keystorePath2 = null; + private static String jksPassw2 = null; + private static String keyPassw2 = null; + private static String url2 = null; + private static URL vesurl2 = null; + private static URL vesbatchurl2 = null; + private static HttpURLConnection con2 = null; + + /* RingBuffer to forward messages on sending AgentDispatcher thread */ + private static RingBuffer ringb = new RingBuffer(100); + private static volatile boolean shouldStop = false; + + private static Thread thr; + + /* AgentDispatcher loops on messages in RingBuffer and POSTs them + * to external Collector + */ private static class AgentDispatcher implements Runnable { - - private String readStream(InputStream stream) throws Exception { - StringBuilder builder = new StringBuilder(); - try (BufferedReader in = new BufferedReader(new InputStreamReader(stream))) { - String line; - while ((line = in.readLine()) != null) { - builder.append(line); // + "\r\n"(no need, json has no line breaks!) - } - in.close(); - } - logger.error("Resp: " + builder.toString()); - //System.out.println("Resp: " + builder.toString()); - return builder.toString(); - } - - // Create a trust manager that does not validate certificate chains - TrustManager[] trustAllCerts = new TrustManager[] { - new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[0]; - } - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { + public static int httpResponse = 0; + public static int httpResponse2 = 0; + private void sendObject(EvelObject tosend){ + while(true) { + httpResponse = AgentMain.sendObjectWithReturn(tosend); + if((httpResponse >= 200 && httpResponse < 299) || httpResponse == 400) { + return; + } + httpResponse2 = AgentMain.sendObjectWithReturn2(tosend); + if((httpResponse2 >= 200 && httpResponse2 < 299) || httpResponse2 == 400) { + return; } - } - }; - - public void run() { - - String datatosend=null; - for(;;){ - EvelObject tosend = ringb.take(); - if( tosend != null && ((datatosend = (String) tosend.datastr) != null)) - { - //process data - logger.trace(url + "Got an event size "+datatosend.length()); - logger.trace(datatosend); - - try { - - if( tosend.type == false) - con = (HttpURLConnection) vesurl.openConnection(); - else - con = (HttpURLConnection) vesbatchurl.openConnection(); - - if (con instanceof HttpsURLConnection) { - HttpsURLConnection httpsConnection = (HttpsURLConnection) con; - - try { - - SSLContext sc = SSLContext.getInstance("TLSv1.2"); - /* Get the JKS contents */ - if( !keystore_pth.isEmpty() && !jks_passw.isEmpty() && !key_passw.isEmpty() ) - { - final KeyStore keyStore = KeyStore.getInstance("JKS"); - try (final InputStream is = new FileInputStream(keystore_pth)) { - keyStore.load(is, jks_passw.toCharArray()); - } - final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory - .getDefaultAlgorithm()); - kmf.init(keyStore, key_passw.toCharArray()); - final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory - .getDefaultAlgorithm()); - tmf.init(keyStore); - sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom()); - } - else - { - // Init the SSLContext with a TrustManager[] and SecureRandom() - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - } - httpsConnection.setDefaultHostnameVerifier(new HostnameVerifier() - { - public boolean verify(String hostname, SSLSession session) + else { + + try { + Thread.sleep(120000); + }catch(Exception ee) { + } + } + } + } + + + public void run() { + + String datatosend=null; + while (!shouldStop){ + EvelObject tosend = ringb.take(); + if( tosend != null && ((datatosend = (String) tosend.datastr) != null)) + { + sendObject(tosend); + } + else + { + logger.trace(url + "Waiting for events"); + try { + Thread.sleep(5); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.trace("Interrupted on "+url); + + + } + } + }//end while + + logger.trace("Caught stop event, emptying buffer before exiting"); + + while (!ringb.isEmpty()){ + EvelObject tosend = ringb.take(); + if( tosend != null && ((datatosend = (String) tosend.datastr) != null)) + { + sendObject(tosend); + } + } + logger.trace("Send buffer is empty, shutting down"); + }//end run + }//end AgentDispatcher + + public static int doPost(HttpURLConnection con, String dataToSend) throws IOException { + OutputStream os = con.getOutputStream(); + BufferedWriter writer = new BufferedWriter( + new OutputStreamWriter(os, "UTF-8")); + //Call writer POST + writer.write(dataToSend); + writer.flush(); + writer.close(); + os.close(); + //Handle the response code for POST request + return con.getResponseCode(); + } + + private static String readStream(InputStream stream) throws IOException { + StringBuilder builder = new StringBuilder(); + try (BufferedReader in = new BufferedReader(new InputStreamReader(stream))) { + String line; + while ((line = in.readLine()) != null) { + builder.append(line); // + "\r\n"(no need, json has no line breaks!) + } + in.close(); + } + logger.error("Resp: " + builder.toString()); + + return builder.toString(); + } + + // Create a trust manager that does not validate certificate chains + private static TrustManager[] trustAllCerts = new TrustManager[] { + new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[0]; + } + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + } + }; + + //Second Collector return object + public static final int sendObjectWithReturn2(EvelObject tosend){ + String datatosend = (String) tosend.datastr; + //process data + logger.trace(url2 + "Got an event size second collector "+datatosend.length()); + logger.trace(datatosend); + int respCode = 0; + Duration timeout = Duration.ofSeconds(2000); + try { + + if( tosend.type == false) + + con2 = (HttpURLConnection) vesurl2.openConnection(); + + else + con2 = (HttpURLConnection) vesbatchurl2.openConnection(); + + if (con2 instanceof HttpsURLConnection) { + + HttpsURLConnection httpsConnection = (HttpsURLConnection) con2; + + try { + + SSLContext sc = SSLContext.getInstance("TLSv1.2"); + /* Get the JKS contents */ + if( !keystorePath2.isEmpty() && !jksPassw2.isEmpty() && !keyPassw2.isEmpty() ) + { + final KeyStore keyStore = KeyStore.getInstance("JKS"); + try (final InputStream is = new FileInputStream(keystorePath2)) { + keyStore.load(is, jksPassw2.toCharArray()); + } + final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory + .getDefaultAlgorithm()); + kmf.init(keyStore, keyPassw2.toCharArray()); + final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory + .getDefaultAlgorithm()); + tmf.init(keyStore); + sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom()); + } + else + { + // Init the SSLContext with a TrustManager[] and SecureRandom() + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + } + httpsConnection.setDefaultHostnameVerifier(new HostnameVerifier() + { + public boolean verify(String hostname, SSLSession session) + { + return true; + } + }); + httpsConnection.setSSLSocketFactory(sc.getSocketFactory()); + con2 = httpsConnection; + + + } + + catch (final Exception exc) { + logger.error("SSL/TLS connection error"); + } + } + + //add reuqest header + con2.setRequestMethod("POST"); + // No caching, we want the real thing. + + con2.setUseCaches (false); + // Specify the content type. + + con2.setRequestProperty("Content-Type", "application/json"); + con2.setInstanceFollowRedirects( false ); + + //Basic username password authentication + String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass2.getBytes("UTF-8")); + con2.setRequestProperty ("Authorization", basicAuth); + + con2.setReadTimeout(15000 /* milliseconds */); + + con2.setConnectTimeout(15000 /* milliseconds */); + + // Send post request + con2.setDoOutput(true); + con2.setDoInput(true); + + con2.setFixedLengthStreamingMode(datatosend.length()); + + + + try { + respCode = AgentMain.doPost(con2, datatosend); + }catch (ConnectException ie) { + /* Handle the interruption. Or ignore it. */ + + + } + catch (InterruptedByTimeoutException ee) { + /* Handle the error. Or ignore it. */ + + + } + catch (IOException te) { + /* Handle the timeout. Or ignore it. */ + + + } + + + + + logger.trace(url2 + "Connection HTTP Response code :"+respCode); + if(respCode < HttpURLConnection.HTTP_OK ) { + logger.trace(url2 + " **INFO**"); + } + else if(respCode >= HttpURLConnection.HTTP_OK && respCode < HttpURLConnection.HTTP_MULT_CHOICE ) + { + logger.trace(url2 + " **OK**"); + + } + else if(respCode >= HttpURLConnection.HTTP_MULT_CHOICE && respCode < HttpURLConnection.HTTP_BAD_REQUEST ) + { + logger.warn(url2 + " **REDIRECTION**"); + + } + else if(respCode >= HttpURLConnection.HTTP_BAD_REQUEST ) + { + logger.warn(url2 + " **SERVER ERROR**"); + InputStream es = con2.getErrorStream(); + AgentMain.readStream(es); + } + + + return respCode; + } catch (ConnectException e) { + + } catch (IOException e) { + logger.error("Exception during POST", e); + + + return 0; + } + + return respCode; + + } + + + public static int sendObjectWithReturn(EvelObject tosend){ + String datatosend = (String) tosend.datastr; + //process data + logger.trace(url + "Got an event size "+datatosend.length()); + logger.trace(datatosend); + + try { + + if( tosend.type == false) + con = (HttpURLConnection) vesurl.openConnection(); + else + con = (HttpURLConnection) vesbatchurl.openConnection(); + + if (con instanceof HttpsURLConnection) { + HttpsURLConnection httpsConnection = (HttpsURLConnection) con; + + try { + + SSLContext sc = SSLContext.getInstance("TLSv1.2"); + /* Get the JKS contents */ + if( !keystorePath.isEmpty() && !jksPassw.isEmpty() && !keyPassw.isEmpty() ) + { + final KeyStore keyStore = KeyStore.getInstance("JKS"); + try (final InputStream is = new FileInputStream(keystorePath)) { + keyStore.load(is, jksPassw.toCharArray()); + } + final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory + .getDefaultAlgorithm()); + kmf.init(keyStore, keyPassw.toCharArray()); + final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory + .getDefaultAlgorithm()); + tmf.init(keyStore); + sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom()); + } + else + { + // Init the SSLContext with a TrustManager[] and SecureRandom() + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + } + httpsConnection.setDefaultHostnameVerifier(new HostnameVerifier() { - return true; - } - }); - httpsConnection.setSSLSocketFactory(sc.getSocketFactory()); - con = httpsConnection; - - } - catch (final Exception exc) { - exc.printStackTrace(); - logger.error("SSL/TLS connection error"); - } - } - - //add reuqest header - con.setRequestMethod("POST"); - // No caching, we want the real thing. - con.setUseCaches (false); - // Specify the content type. - con.setRequestProperty("Content-Type", "application/json"); - con.setInstanceFollowRedirects( false ); - //Basic username password authentication - String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8")); - con.setRequestProperty ("Authorization", basicAuth); - - con.setReadTimeout(15000 /* milliseconds */); - con.setConnectTimeout(15000 /* milliseconds */); - // Send post request - con.setDoOutput(true); - con.setDoInput(true); - - con.setFixedLengthStreamingMode(datatosend.length()); - OutputStream os = con.getOutputStream(); - BufferedWriter writer = new BufferedWriter( - new OutputStreamWriter(os, "UTF-8")); - //Call writer POST - writer.write(datatosend); - writer.flush(); - writer.close(); - os.close(); - //Handle the response code for POST request - int respCode = con.getResponseCode(); - logger.trace(url + "Connection HTTP Response code :"+respCode); - if(respCode < HttpURLConnection.HTTP_OK ) { - logger.trace(url + " **INFO**"); - } - else if(respCode >= HttpURLConnection.HTTP_OK && respCode < HttpURLConnection.HTTP_MULT_CHOICE ) - { - logger.trace(url + " **OK**"); - } - else if(respCode >= HttpURLConnection.HTTP_MULT_CHOICE && respCode < HttpURLConnection.HTTP_BAD_REQUEST ) - { - logger.warn(url + " **REDIRECTION**"); - } - else if(respCode >= HttpURLConnection.HTTP_BAD_REQUEST ) - { - logger.warn(url + " **SERVER ERROR**"); - - InputStream es = con.getErrorStream(); - readStream(es); - } - - - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - else - { - logger.trace(url + "Waiting for events"); - try { - Thread.sleep(5); - } catch (InterruptedException e) { - logger.trace("Interrupted on "+url); - e.printStackTrace(); - } - } - }//end for - }//end run - }//end AgentDispatcher + public boolean verify(String hostname, SSLSession session) + { + return true; + } + }); + httpsConnection.setSSLSocketFactory(sc.getSocketFactory()); + con = httpsConnection; + + } + catch (final Exception exc) { + logger.error("SSL/TLS connection error"); + } + } + + //add reuqest header + con.setRequestMethod("POST"); + // No caching, we want the real thing. + con.setUseCaches (false); + // Specify the content type. + con.setRequestProperty("Content-Type", "application/json"); + con.setInstanceFollowRedirects( false ); + //Basic username password authentication + String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8")); + con.setRequestProperty ("Authorization", basicAuth); + + con.setReadTimeout(15000 /* milliseconds */); + con.setConnectTimeout(15000 /* milliseconds */); + // Send post request + con.setDoOutput(true); + con.setDoInput(true); + + con.setFixedLengthStreamingMode(datatosend.length()); + int respCode = AgentMain.doPost(con, datatosend); + logger.trace(url + "Connection HTTP Response code :"+respCode); + if(respCode < HttpURLConnection.HTTP_OK ) { + logger.trace(url + " **INFO**"); + } + else if(respCode >= HttpURLConnection.HTTP_OK && respCode < HttpURLConnection.HTTP_MULT_CHOICE ) + { + logger.trace(url + " **OK**"); + } + else if(respCode >= HttpURLConnection.HTTP_MULT_CHOICE && respCode < HttpURLConnection.HTTP_BAD_REQUEST ) + { + logger.warn(url + " **REDIRECTION**"); + } + else if(respCode >= HttpURLConnection.HTTP_BAD_REQUEST ) + { + logger.warn(url + " **SERVER ERROR**"); + + InputStream es = con.getErrorStream(); + AgentMain.readStream(es); + } + + return respCode; + + } catch (IOException e) { + logger.error("Exception during POST", e); + return 0; + } + } + // Validate URL public static boolean isValidURL(String urlStr) { try { - URL url = new URL(urlStr); - return true; + URL url = new URL(urlStr); + return true; } catch (MalformedURLException e) { return false; } } - + /**************************************************************************//** * Library initialization. * @@ -278,7 +483,7 @@ public enum EVEL_ERR_CODES { * @note This function initializes the Java EVEL library interfaces. * Validates input parameters and starts the AgentDispatcher thread * - * @param event_api_url The API's URL. + * @param eventApiUrl The API's URL. * @param port The API's port. * @param path The optional path (may be NULL). * @param topic The optional topic part of the URL (may be NULL). @@ -291,78 +496,115 @@ public enum EVEL_ERR_CODES { * @retval ::EVEL_ERR_CODES On failure. *****************************************************************************/ public static EVEL_ERR_CODES evel_initialize( - String event_api_url, - int port, + String eventApiUrl, + int port, String path, String topic, String username, String password, - String keystore_path, - String jks_password, - String key_password, + String evelKeystorePath, + String evelJksPassword, + String evelKeyPassword, + String eventApiUrl2, + int port2, + String username2, + String password2, Level level) throws IOException { - EVEL_ERR_CODES rc = EVEL_ERR_CODES.EVEL_SUCCESS; - - EVEL_ENTER(); - - BasicConfigurator.configure(); - - /***************************************************************************/ - /* Check assumptions. */ - /***************************************************************************/ - assert(event_api_url != null); - assert(port > 1024); - assert(username != null); - - logger.setLevel(level); - - if( !isValidURL(event_api_url) ){ - System.out.println("Invalid Event API URL"); - logger.error("Invalid Event API URL"); - rc = EVEL_ERR_CODES.EVEL_ERR_GEN_FAIL; - System.exit(1); - } - - if(path == null){ - path = ""; - } else { - version += "/example_vnf"; - } - - keystore_pth = keystore_path; - jks_passw = jks_password; - key_passw = key_password; - - url = event_api_url+":"+Integer.toString(port)+path+"/eventListener/v"+version; - vesurl = null; - try { - vesurl = new URL(url); - vesbatchurl = new URL(url+"/eventBatch"); - } catch (MalformedURLException e) { - logger.info("Error in url input"); - e.printStackTrace(); - System.exit(1); - } - userpass = username + ":" + password; + EVEL_ERR_CODES rc = EVEL_ERR_CODES.EVEL_SUCCESS; + + EVEL_ENTER(); + + BasicConfigurator.configure(); + + /***************************************************************************/ + /* Check assumptions. */ + /***************************************************************************/ + assert(eventApiUrl != null); + assert(port > 1024); + assert(username != null); + + assert(eventApiUrl2 != null); + assert(port2 > 1024); + assert(username2 != null); + + logger.setLevel(level); + + if( !isValidURL(eventApiUrl) ){ + + logger.error("Invalid Event API URL"); + rc = EVEL_ERR_CODES.EVEL_ERR_GEN_FAIL; + System.exit(1); + } + + if( !isValidURL(eventApiUrl2) ){ + + logger.error("Invalid Event API URL"); + rc = EVEL_ERR_CODES.EVEL_ERR_GEN_FAIL; + System.exit(1); + } + + if(path == null){ + path = ""; + } else { + version += "/example_vnf"; + } + + keystorePath = evelKeystorePath; + jksPassw = evelJksPassword; + keyPassw = evelKeyPassword; + + keystorePath2 = evelKeystorePath; + jksPassw2 = evelJksPassword; + keyPassw2 = evelKeyPassword; + + url = eventApiUrl+":"+Integer.toString(port)+path+"/eventListener/v"+version; + vesurl = null; + + url2 = eventApiUrl2+":"+Integer.toString(port2)+path+"/eventListener/v"+version; + vesurl2 = null; + try { + vesurl = new URL(url); + vesbatchurl = new URL(url+"/eventBatch"); + + + vesurl2 = new URL(url2); + vesbatchurl2 = new URL(url2+"/eventBatch"); + } catch (MalformedURLException e) { + logger.info("Error in url input"); + + System.exit(1); + } + userpass = username + ":" + password; + + userpass2 = username2 + ":" + password2; logger.info("Starting Agent Dispatcher thread"); - Thread t = new Thread(new AgentDispatcher()); - t.start(); - + thr = new Thread(new AgentDispatcher()); + thr.start(); + EVEL_EXIT(); - return rc; - + return rc; + } - - private static void EVEL_EXIT() { - logger.trace("Exit VES Agent Main"); - } - - private static void EVEL_ENTER() { - logger.trace("Enter VES Agent Main"); - } - + + public static void evel_shutdown() { + if(shouldStop){ + logger.warn("evel_shutdown was called whilst the agent was already stopping - this has no effect"); + } + shouldStop = true; + logger.debug("Called evel_shutdown, will shutdown when the buffer is empty"); + } + + + private static void EVEL_EXIT() { + logger.trace("Exit VES Agent Main"); + } + + private static void EVEL_ENTER() { + logger.trace("Enter VES Agent Main"); + } + /**************************************************************************//** * Handle user formatted post message * @@ -375,16 +617,45 @@ public enum EVEL_ERR_CODES { * @retval boolean True On successful acceptance False on failure *****************************************************************************/ - public static boolean evel_post_event(EvelHeader obj) + public static boolean evel_post_event(EvelHeader obj) + { + if (shouldStop){ + logger.error("evel_post_event called whilst agent is shutting down - event will not be posted"); + return false; + } + String data = obj.evel_json_encode_event().toString(); + EvelObject myobj = new EvelObject(data,false); + boolean ret = ringb.put(myobj); + logger.info("Evel Post event ret:"+ret); + return ret; + } + + /**************************************************************************//** + * Handle user formatted post message, post the event, and return the HTTP error code + * + * @note This function handles VES 5.x formatted messages from all valid + * Domains and stores them in RingBuffer. + * + * @param obj VES 5.x formatted user messages with common header + * and optional specialized body + * + * @retval int The http code returned when sending the event + *****************************************************************************/ + + public static int evel_post_event_immediate(EvelHeader obj) { - String data = obj.evel_json_encode_event().toString(); - EvelObject myobj = new EvelObject(data,false); - boolean ret = ringb.put(myobj); - logger.info("Evel Post event ret:"+ret); - return ret; + if (shouldStop){ + logger.error("evel_post_event_immediate called while agent is shutting down - event will not be posted"); + return 0; + } + + String data = obj.evel_json_encode_event().toString(); + EvelObject myobj = new EvelObject(data,false); + int ret = AgentMain.sendObjectWithReturn(myobj); + logger.info("Evel Post event ret:"+ret); + return ret; } - /**************************************************************************//** * Handle user formatted post message * @@ -397,14 +668,16 @@ public enum EVEL_ERR_CODES { * @retval boolean True On successful acceptance False on failure *****************************************************************************/ - public static boolean evel_post_event(EvelBatch obj) + public static boolean evel_post_event(EvelBatch obj) { - String data = obj.evel_json_encode_event().toString(); - EvelObject myobj = new EvelObject(data,true); - boolean ret = ringb.put(myobj); - logger.info("Evel Post batch event ret:"+ret); - return ret; + if (shouldStop){ + logger.error("evel_post_event called whilst agent is shutting down - event will not be posted"); + return false; + } + String data = obj.evel_json_encode_event().toString(); + EvelObject myobj = new EvelObject(data,true); + boolean ret = ringb.put(myobj); + logger.info("Evel Post batch event ret:"+ret); + return ret; } - - } diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/EvelFault.java b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/EvelFault.java index 19bde72..4501b35 100644 --- a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/EvelFault.java +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/EvelFault.java @@ -288,7 +288,7 @@ public class EvelFault extends EvelHeader { * @param source_type The source type to convert.
* @returns The equivalent string.
*****************************************************************************/
- String evel_source_type(EVEL_SOURCE_TYPES source_type)
+ static String evel_source_type(EVEL_SOURCE_TYPES source_type)
{
String result;
diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/EvelSyslog.java b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/EvelSyslog.java index 4b972c4..1bdcaf0 100644 --- a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/EvelSyslog.java +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/EvelSyslog.java @@ -435,7 +435,7 @@ public class EvelSyslog extends EvelHeader { /* Mandatory fields */
/***************************************************************************/
JsonObjectBuilder obj = Json.createObjectBuilder()
- .add("eventSourceType", event_source_type.toString())
+ .add("eventSourceType", EvelFault.evel_source_type(event_source_type))
.add("syslogMsg", syslog_msg)
.add("syslogTag", syslog_tag)
.add("syslogFieldsVersion",version);
diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/RingBuffer.java b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/RingBuffer.java index 144fc24..8969a2a 100644 --- a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/RingBuffer.java +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/RingBuffer.java @@ -56,6 +56,10 @@ public class RingBuffer { this.writePos = 0;
this.available = 0;
}
+
+ public boolean isEmpty() {
+ return this.remainingCapacity() == this.capacity;
+ }
//returns available capacity
public int remainingCapacity() {
diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/DeviceData.java b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/DeviceData.java new file mode 100644 index 0000000..4be5b6b --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/DeviceData.java @@ -0,0 +1,118 @@ +package evel_javalibrary.att.com.loadbalance; +/**************************************************************************//** + * @file + * Measurement class + * + * This file implements the Measurement Event class which is intended to provide a + * simple wrapper around the complexity of AT&T's Vendor Event Listener API so + * that VNFs can use it to send CPU, Memory, Disk Measurements to Collector. + * + * License + * ------- + * Unless otherwise specified, all software contained herein is + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *****************************************************************************/ + +import java.io.Serializable; + +public class DeviceData implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 1L; + private String t0bytesIn; + private String t0bytesOut; + private String t0packetIn; + private String t0packetOut; + + private String t1Bytesin; + private String t1Bytesout; + private String t1Packetsin; + private String t1Packetsout; + + private String Instanceres02Command; + + public String getT0bytesIn() { + return t0bytesIn; + } + + public void setT0bytesIn(String t0bytesIn) { + this.t0bytesIn = t0bytesIn; + } + + public String getT0bytesOut() { + return t0bytesOut; + } + + public void setT0bytesOut(String t0bytesOut) { + this.t0bytesOut = t0bytesOut; + } + + public String getT0packetIn() { + return t0packetIn; + } + + public void setT0packetIn(String t0packetIn) { + this.t0packetIn = t0packetIn; + } + + public String getT0packetOut() { + return t0packetOut; + } + + public void setT0packetOut(String t0packetOut) { + this.t0packetOut = t0packetOut; + } + + public String getT1Bytesin() { + return t1Bytesin; + } + + public void setT1Bytesin(String t1Bytesin) { + this.t1Bytesin = t1Bytesin; + } + + public String getT1Bytesout() { + return t1Bytesout; + } + + public void setT1Bytesout(String t1Bytesout) { + this.t1Bytesout = t1Bytesout; + } + + public String getT1Packetsin() { + return t1Packetsin; + } + + public void setT1Packetsin(String t1Packetsin) { + this.t1Packetsin = t1Packetsin; + } + + public String getT1Packetsout() { + return t1Packetsout; + } + + public void setT1Packetsout(String t1Packetsout) { + this.t1Packetsout = t1Packetsout; + } + + public String getInstanceres02Command() { + return Instanceres02Command; + } + + public void setInstanceres02Command(String instanceres02Command) { + Instanceres02Command = instanceres02Command; + } + + +} diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/FaultData.java b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/FaultData.java new file mode 100644 index 0000000..e00c5d2 --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/FaultData.java @@ -0,0 +1,930 @@ +package evel_javalibrary.att.com.loadbalance; +/**************************************************************************//** + * @file + * Evel Fault Event class extends EvelHeader class + * + * This file implements the Evel Fault Event class which is intended to provide a + * simple wrapper around the complexity of AT&T's Vendor Event Listener API so + * that VNFs can use it to send Fault events. + * + * License + * ------- + * Unless otherwise specified, all software contained herein is + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *****************************************************************************/ + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + + +import org.apache.log4j.Level; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import evel_javalibrary.att.com.AgentMain; +import evel_javalibrary.att.com.EvelBatch; +import evel_javalibrary.att.com.EvelFault; +import evel_javalibrary.att.com.EvelFault.EVEL_SEVERITIES; +import evel_javalibrary.att.com.EvelFault.EVEL_SOURCE_TYPES; +import evel_javalibrary.att.com.EvelFault.EVEL_VF_STATUSES; +import evel_javalibrary.att.com.EvelHeader; + + + +public class FaultData{ + + + static HashMap<String, String> fault_config = new HashMap<>(); + static HashMap<String, String> interface_config = new HashMap<>(); + + static HashMap<String, String> faultConfig = new HashMap<>(); + + static HashMap<String, String> faultInstanceres01 = new HashMap<>(); + static HashMap<String, String> faultInstanceres02 = new HashMap<>(); + static HashMap<String, String> tempAlaramClearParameter = new HashMap<>(); + + + static HashMap<String, String> Instanceres02ClearParameter = new HashMap<>(); + + + static String[] resDevice =null; + static String[] tempInitres; + static String[] tempcommandres; + static String[] tempcommand02res; + static HashMap<String, String> faultConfigTempInit = new HashMap<>(); + static HashMap<String, String> faultConfigCommand = new HashMap<>(); + + + static String alarmCondition =""; + static String specificProblem = ""; + static String eventSeverity=""; + static String alarmInterfaceA =""; + + static String alarmConditionClear =""; + static String specificProblemClear = ""; + static String eventSeverityClear=""; + + static String Instance02alarmInterfaceA; + static String Instance02eventCategory; + static String Instance02eventSourceType; + static String Instance02eventName; + + static String ins02alarmConditionClear; + static String ins02specificProblemClear; + static String ins02eventSeverityClear; + + static String setAlarmCondition; + static String setSpecificProblem; + static String setEventSeverity; + + static String eventCategory =""; + static String eventSourceType =""; + static HashMap<String, String> hm = new HashMap<>(); + + static String linkStart = ""; + static int linkCount; + static String event_id1 = "fault"; + static String event_id = "00000000"; + static float bytes_in; + static float bytes_out; + static float packets_in; + static float packets_out; + + static float ins02Cmd; + + + static int falut_raised =0; + + + public final Runnable faultInstance01; + public final Runnable faultInstance02; + + public FaultData(){ + + faultInstance01 = new Runnable() { + + @Override + public void run() { + int gm_event_id = 1; + String event_id2=null; + + Long start_epoch_microsec = 0L; + Long last_epoch_microsec = 0L; + String hostName = hostName(); + try { + readFalutConfig(); + readVppMetrics(resDevice); + } catch (IOException | ParseException e1) { + + } + + + String[] intFaceMapFault = resDevice; + int numOfInterfacesFalut = 0; + if( intFaceMapFault != null) + numOfInterfacesFalut = intFaceMapFault.length; + if( numOfInterfacesFalut <= 0) { + + return; + } + + HashMap<String, DeviceData> falut_last_metrics = readVppMetrics(resDevice); + + while(true) { + try { + EvelBatch ebt = new EvelBatch(); + + for( String falut : intFaceMapFault ) { + + HashMap<String, DeviceData> falut_current_metrics = readVppMetrics(resDevice); + + + for( String tmp_device :falut_current_metrics.keySet() ) { + + + + int receivedOctetsDelta = Integer.parseInt((falut_current_metrics.get(tmp_device).getT1Bytesin()) ) + - Integer.parseInt((falut_last_metrics.get(tmp_device).getT0bytesIn())); + + int receivedTotalPacketsDelta = Integer.parseInt((falut_current_metrics.get(tmp_device).getT1Packetsin()) ) + - Integer.parseInt((falut_last_metrics.get(tmp_device).getT0packetIn())); + + int transmittedOctetsDelta = Integer.parseInt((falut_current_metrics.get(tmp_device).getT1Bytesout()) ) + - Integer.parseInt((falut_last_metrics.get(tmp_device).getT0bytesOut())); + + + + int transmittedTotalPacketsDelta = Integer.parseInt((falut_current_metrics.get(tmp_device).getT1Packetsout()) ) + - Integer.parseInt((falut_last_metrics.get(tmp_device).getT0packetOut())); + + + + + + + String alarmInterface = tmp_device; //resDevice[0]; + if((receivedOctetsDelta < Integer.parseInt((String)faultInstanceres01.get("tmp_lowWaterMark")) || transmittedOctetsDelta < Integer.parseInt((String)faultInstanceres01.get("tmp_lowWaterMark")) || + receivedTotalPacketsDelta < Integer.parseInt((String)faultInstanceres01.get("tmp_lowWaterMark")) || transmittedTotalPacketsDelta < Integer.parseInt((String)faultInstanceres01.get("tmp_lowWaterMark"))) && falut_raised == 0){ + event_id2 = event_id1+ event_id+(gm_event_id++); + EvelFault eveFalt = new EvelFault(faultInstanceres01.get("eventName"),event_id2, alarmCondition, specificProblem, + EvelHeader.PRIORITIES.EVEL_PRIORITY_LOW, + EVEL_SEVERITIES.EVEL_SEVERITY_MAJOR, + EVEL_SOURCE_TYPES.EVEL_SOURCE_ROUTER, + EVEL_VF_STATUSES.EVEL_VF_STATUS_IDLE); + if(eveFalt != null) { + + falut_raised =1; + + if( faultConfig.get("eventType")!=null) { + eveFalt.evel_fault_type_set(faultConfig.get("eventType")); + + start_epoch_microsec = last_epoch_microsec; + last_epoch_microsec = System.nanoTime()/1000; + + eveFalt.evel_last_epoch_set(start_epoch_microsec); + eveFalt.evel_start_epoch_set(last_epoch_microsec); + + eveFalt.evel_fault_category_set(eventCategory); + eveFalt.evel_fault_interface_set(alarmInterface.replaceAll("^[\"']+|[\"']+$", "")); + eveFalt.evel_nfcnamingcode_set(faultConfig.get("nfcNamingCode").toString()); + eveFalt.evel_nfnamingcode_set(faultConfig.get("nfNamingCode").toString()); + if(faultConfig.get("reportingEntityName") == null) { + eveFalt.evel_reporting_entity_name_set(hostName); + }else { + eveFalt.evel_reporting_entity_name_set(faultConfig.get("reportingEntityName").toString()); + } + eveFalt.evel_reporting_entity_id_set(faultConfig.get("reportingEntityId").toString()); + eveFalt.evel_header_set_sourceid(true,faultConfig.get("sourceId").toString()); + + if(faultConfig.get("sourceName") == null) { + eveFalt.evel_header_set_source_name(hostName); + }else { + eveFalt.evel_header_set_source_name(faultConfig.get("sourceName").toString()); + } + AgentMain.evel_post_event(eveFalt); + } + + } + + }else if((receivedOctetsDelta > Integer.parseInt((String)faultInstanceres01.get("tmp_lowWaterMark")) && transmittedOctetsDelta > Integer.parseInt((String)faultInstanceres01.get("tmp_lowWaterMark")) && + receivedTotalPacketsDelta > Integer.parseInt((String)faultInstanceres01.get("tmp_lowWaterMark")) && transmittedTotalPacketsDelta > Integer.parseInt((String)faultInstanceres01.get("tmp_lowWaterMark"))) && falut_raised == 1) { + + + event_id2 = event_id1+event_id+ (gm_event_id++); + EvelFault eveFalt = new EvelFault(faultInstanceres01.get("eventName"),event_id2, alarmConditionClear, specificProblemClear, + EvelHeader.PRIORITIES.EVEL_PRIORITY_LOW, + EVEL_SEVERITIES.EVEL_SEVERITY_NORMAL, + EVEL_SOURCE_TYPES.EVEL_SOURCE_ROUTER, + EVEL_VF_STATUSES.EVEL_VF_STATUS_IDLE); + + + + if(eveFalt != null) { + falut_raised =1; + + if( faultConfig.get("eventType")!=null) { + eveFalt.evel_fault_type_set(faultConfig.get("eventType")); + eveFalt.evel_fault_category_set(eventCategory); + eveFalt.evel_fault_interface_set(alarmInterface.replaceAll("^[\"']+|[\"']+$", "")); + + eveFalt.evel_nfcnamingcode_set(faultConfig.get("nfcNamingCode").toString()); + eveFalt.evel_nfnamingcode_set(faultConfig.get("nfNamingCode").toString()); + + if(faultConfig.get("reportingEntityName") == null) { + eveFalt.evel_reporting_entity_name_set(hostName); + }else { + eveFalt.evel_reporting_entity_name_set(faultConfig.get("reportingEntityName").toString()); + } + + + eveFalt.evel_reporting_entity_id_set(faultConfig.get("reportingEntityId").toString()); +// eveFalt.evel_nfVendorName_set(faultConfig.get("nfVendorName").toString()); + eveFalt.evel_header_set_sourceid(true,faultConfig.get("sourceId").toString()); + + if(faultConfig.get("sourceName") == null) { + eveFalt.evel_header_set_source_name(hostName); + }else { + eveFalt.evel_header_set_source_name(faultConfig.get("sourceName").toString()); + } + + +// eveFalt.evel_timeZoneOffset_set(faultConfig.get("timeZoneOffset").toString()); + AgentMain.evel_post_event(eveFalt); + + } + + } + + + + } + + + try { + String Ins01Interval=""; + long milliseconds = 60000; + if(faultInstanceres01.get("tmp_faultCheckInterval") == null) { + Ins01Interval = Long.toString(milliseconds); + }else { + Ins01Interval = faultInstanceres01.get("tmp_faultCheckInterval"); + } + Thread.sleep(Integer.parseInt(Ins01Interval)); + }catch(Exception e) {} + + } //for map keyset + + } //for intFaceMapFault + + + }catch (Exception e) { + + } + + + } + } + }; + + faultInstance02 = new Runnable() { + + @Override + public void run() { + int gm_event_id = 1; + String event_id2=null; + Long start_epoch_microsec = 0L; + Long last_epoch_microsec = 0L; + String hostName = hostName(); + try { + readFalutConfig(); + readVppMetrics(resDevice); + } catch (IOException | ParseException e1) { + + } + + + String[] intFaceMapFault = resDevice; + int numOfInterfacesFalut = 0; + if( intFaceMapFault != null) + numOfInterfacesFalut = intFaceMapFault.length; + if( numOfInterfacesFalut <= 0) { + + return; + } + + HashMap<String, DeviceData> falut_last_metrics = readVppMetrics(resDevice); + + while(true) { + try { + EvelBatch ebt = new EvelBatch(); + + HashMap<String, DeviceData> falutMetric = readVppMetrics(resDevice); + DeviceData mdGetdata = new DeviceData(); + String ins02cmd = mdGetdata.getInstanceres02Command(); + + + if(ins02Cmd < Integer.parseInt((String)falutMetric.get("Instanceres02Cmd").getInstanceres02Command())){ + + event_id2 = event_id1+ event_id+(gm_event_id++); + EvelFault eveFalt = new EvelFault(Instance02eventName,event_id2, setAlarmCondition, setSpecificProblem, + EvelHeader.PRIORITIES.EVEL_PRIORITY_LOW, + EVEL_SEVERITIES.EVEL_SEVERITY_MAJOR, + EVEL_SOURCE_TYPES.EVEL_SOURCE_VIRTUAL_MACHINE, + EVEL_VF_STATUSES.EVEL_VF_STATUS_IDLE); + + + if(eveFalt != null) { + + falut_raised =1; + + + + if( faultConfig.get("eventType")!=null) { + eveFalt.evel_fault_type_set(faultConfig.get("eventType")); + + start_epoch_microsec = last_epoch_microsec; + last_epoch_microsec = System.nanoTime()/1000; + + eveFalt.evel_last_epoch_set(start_epoch_microsec); + eveFalt.evel_start_epoch_set(last_epoch_microsec); + + eveFalt.evel_fault_category_set(Instance02eventCategory); + eveFalt.evel_fault_interface_set(Instance02alarmInterfaceA.replaceAll("^[\"']+|[\"']+$", "")); + + eveFalt.evel_nfcnamingcode_set(faultConfig.get("nfcNamingCode").toString()); + eveFalt.evel_nfnamingcode_set(faultConfig.get("nfNamingCode").toString()); + + if(faultConfig.get("reportingEntityName") == null) { + eveFalt.evel_reporting_entity_name_set(hostName); + }else { + eveFalt.evel_reporting_entity_name_set(faultConfig.get("reportingEntityName").toString()); + } + + + eveFalt.evel_reporting_entity_id_set(faultConfig.get("reportingEntityId").toString()); +// eveFalt.evel_nfVendorName_set(faultConfig.get("nfVendorName").toString()); + eveFalt.evel_header_set_sourceid(true,faultConfig.get("sourceId").toString()); + + if(faultConfig.get("sourceName") == null) { + eveFalt.evel_header_set_source_name(hostName); + }else { + eveFalt.evel_header_set_source_name(faultConfig.get("sourceName").toString()); + } + +// eveFalt.evel_timeZoneOffset_set(faultConfig.get("timeZoneOffset").toString()); + AgentMain.evel_post_event(eveFalt); + } + + } + + }else if(ins02Cmd > Integer.parseInt((String)falutMetric.get("Instanceres02Cmd").getInstanceres02Command())) { + + + event_id2 = event_id1+ event_id+(gm_event_id++); + EvelFault eveFalt = new EvelFault(Instance02eventName,event_id2, ins02alarmConditionClear, ins02specificProblemClear, + EvelHeader.PRIORITIES.EVEL_PRIORITY_LOW, + EVEL_SEVERITIES.EVEL_SEVERITY_NORMAL, + EVEL_SOURCE_TYPES.EVEL_SOURCE_VIRTUAL_MACHINE, + EVEL_VF_STATUSES.EVEL_VF_STATUS_IDLE); + + + + if(eveFalt != null) { + falut_raised =1; + + if( faultConfig.get("eventType")!=null) { + eveFalt.evel_fault_type_set(faultConfig.get("eventType")); + eveFalt.evel_fault_category_set(Instance02eventCategory); + eveFalt.evel_fault_interface_set(Instance02alarmInterfaceA.replaceAll("^[\"']+|[\"']+$", "")); + + eveFalt.evel_nfcnamingcode_set(faultConfig.get("nfcNamingCode").toString()); + eveFalt.evel_nfnamingcode_set(faultConfig.get("nfNamingCode").toString()); + + if(faultConfig.get("reportingEntityName") == null) { + eveFalt.evel_reporting_entity_name_set(hostName); + }else { + eveFalt.evel_reporting_entity_name_set(faultConfig.get("reportingEntityName").toString()); + } + + + eveFalt.evel_reporting_entity_id_set(faultConfig.get("reportingEntityId").toString()); + eveFalt.evel_header_set_sourceid(true,faultConfig.get("sourceId").toString()); + + if(faultConfig.get("sourceName") == null) { + eveFalt.evel_header_set_source_name(hostName); + }else { + eveFalt.evel_header_set_source_name(faultConfig.get("sourceName").toString()); + } + AgentMain.evel_post_event(eveFalt); + + } + + } + + + + } + + + try { + String Ins02Interval=""; + long milliseconds = 60000; + if(faultInstanceres02.get("tmp_faultCheckInterval") == null) { + Ins02Interval = Long.toString(milliseconds); + }else { + Ins02Interval = faultInstanceres02.get("tmp_faultCheckInterval"); + } + Thread.sleep(Integer.parseInt(Ins02Interval)); + }catch(Exception e) { + + } + + }catch (Exception e) { + + } + + + } + } + }; + + } + private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); + private static String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for ( int j = 0; j < bytes.length; j++ ) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = hexArray[v >>> 4]; + hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + } + return new String(hexChars); + } + public static String hostName() { + String hostname = "Unknown"; + String uuid = "Unknown"; + try + { + InetAddress addr; + addr = InetAddress.getLocalHost(); + hostname = addr.getHostName(); + } + catch (UnknownHostException ex) + { + + } + try{ + Enumeration<NetworkInterface> networks = + NetworkInterface.getNetworkInterfaces(); + while(networks.hasMoreElements()) { + NetworkInterface network = networks.nextElement(); + byte[] mac = network.getHardwareAddress(); + + if(hostname.equalsIgnoreCase("unknown")) + { + Enumeration inetAddrs = network.getInetAddresses(); + while(inetAddrs.hasMoreElements()){ + InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); + if (!inetAddr.isLoopbackAddress()) { + hostname = inetAddr.getHostAddress(); + break; + } + } + } + if (mac != null) { + uuid = bytesToHex(mac); + } + } + } catch (SocketException e) { + // TODO Auto-generated catch block + + } + + return hostname; + } + + + public static HashMap<String, String> readFalutConfig() throws IOException, ParseException { + + System.out.println("readFalutConfig calling out lo:"); + + List<String> list = new ArrayList<String>(); + JSONParser jsonParser = new JSONParser(); + try { + + FileReader reader = new FileReader("./src/main/java/evel_javalibrary/att/com/loadbalance/flt_config.json"); + JSONObject obj = (JSONObject) jsonParser.parse(reader); + Map.Entry directPair = null; + String directObject =""; + String[] directres; + Map directParameters = ((Map)obj.get("tmp_directParameters")); + Iterator<Map.Entry> itr1 = directParameters.entrySet().iterator(); + while (itr1.hasNext()) { + directPair = itr1.next(); + directObject=String.valueOf(directPair); + directres = directObject.split("="); + faultConfig.put(directres[0], directres[1]); + } + JSONArray arrJson = (JSONArray) directParameters.get("tmp_device"); + resDevice = new String[arrJson.size()]; + for(int i = 0; i < arrJson.size(); i++) + resDevice[i] = (String) arrJson.get(i); + + + //tmp_indirectParameters + Map.Entry indirectPair = null; + String indirectObject =""; + String[] indirectres; + Map indirectParameters = ((Map)obj.get("tmp_indirectParameters")); + Iterator<Map.Entry> itr2 = indirectParameters.entrySet().iterator(); + while (itr2.hasNext()) { + indirectPair = itr2.next(); + indirectObject=String.valueOf(indirectPair); + indirectres = indirectObject.split("="); + faultConfig.put(indirectres[0], indirectres[1]); + } + + + //tmp_faultInstance01 + Map.Entry faultInstancePair = null; + String faultInstanceObject =""; + String[] faultInstanceres; + Map faultInstanceParameters = ((Map)indirectParameters.get("tmp_faultInstance01")); + Iterator<Map.Entry> itr3 = faultInstanceParameters.entrySet().iterator(); + while (itr3.hasNext()) { + faultInstancePair = itr3.next(); + faultInstanceObject=String.valueOf(faultInstancePair); + faultInstanceres = faultInstanceObject.split("="); + faultInstanceres01.put(faultInstanceres[0], faultInstanceres[1]); + } + + + eventCategory = faultInstanceres01.get("eventCategory").toString(); + eventSourceType = faultInstanceres01.get("eventSourceType").toString(); + //tmp_init + Map.Entry tempInitPair = null; + String tempInitObject =""; + Map tempInitParameters = ((Map)faultInstanceParameters.get("tmp_init")); + Iterator<Map.Entry> itr4 = tempInitParameters.entrySet().iterator(); + while (itr4.hasNext()) { + tempInitPair = itr4.next(); + tempInitObject=String.valueOf(tempInitPair); + tempInitres = tempInitObject.split("="); + faultConfigTempInit.put(tempInitres[0], tempInitres[1]); + } + + String tmp_t0BytesOut = faultConfigTempInit.get("tmp_init"); + + + + //tmp_command + Map.Entry tempcommandPair = null; + String tempcommandObject =""; + Map tempcommandParameters = ((Map)faultInstanceParameters.get("tmp_command")); + Iterator<Map.Entry> itr5 = tempcommandParameters.entrySet().iterator(); + while (itr5.hasNext()) { + tempcommandPair = itr5.next(); + tempcommandObject=String.valueOf(tempcommandPair); + tempcommandres = tempcommandObject.split("="); + faultConfigCommand.put(tempcommandres[0], tempcommandres[1]); + } + + //tmp_alarmSetParameters + Map.Entry alarmSetPair = null; + String alarmSetObject =""; + String[] alarmSetres; + Map alarmSetParameters = ((Map)faultInstanceParameters.get("tmp_alarmSetParameters")); + Iterator<Map.Entry> itr6 = alarmSetParameters.entrySet().iterator(); + while (itr6.hasNext()) { + alarmSetPair = itr6.next(); + alarmSetObject=String.valueOf(alarmSetPair); + alarmSetres = alarmSetObject.split("="); + faultConfig.put(alarmSetres[0], alarmSetres[1]); + } + + + alarmCondition = faultConfig.get("alarmCondition").toString(); + specificProblem = faultConfig.get("specificProblem").toString(); + eventSeverity = faultConfig.get("eventSeverity").toString(); + + //tmp_alarmClearParameters + Map.Entry alarmClearPair = null; + String alarmClearObject =""; + String[] alarmClearres; + Map alarmClearParameters = ((Map)faultInstanceParameters.get("tmp_alarmClearParameters")); + Iterator<Map.Entry> itr7 = alarmClearParameters.entrySet().iterator(); + while (itr7.hasNext()) { + alarmClearPair = itr7.next(); + alarmClearObject=String.valueOf(alarmClearPair); + alarmClearres = alarmClearObject.split("="); + tempAlaramClearParameter.put(alarmClearres[0], alarmClearres[1]); + } + + alarmConditionClear = tempAlaramClearParameter.get("alarmCondition").toString(); + specificProblemClear = tempAlaramClearParameter.get("specificProblem").toString(); + eventSeverityClear = tempAlaramClearParameter.get("eventSeverity").toString(); + System.out.println("specificProblemClear data:"+ specificProblemClear); + + //tmp_faultInstance02 + Map.Entry faultInstance02Pair = null; + String faultInstance02Object =""; + String[] faultInstance02res; + Map faultInstance02Parameters = ((Map)indirectParameters.get("tmp_faultInstance02")); + Iterator<Map.Entry> itr8 = faultInstance02Parameters.entrySet().iterator(); + while (itr8.hasNext()) { + faultInstance02Pair = itr8.next(); + faultInstance02Object=String.valueOf(faultInstance02Pair); + faultInstance02res = faultInstance02Object.split("="); + faultInstanceres02.put(faultInstance02res[0], faultInstance02res[1]); + } + Instance02alarmInterfaceA = faultInstanceres02.get("alarmInterfaceA"); + Instance02eventCategory = faultInstanceres02.get("eventCategory"); + Instance02eventSourceType = faultInstanceres02.get("eventSourceType"); + Instance02eventName = faultInstanceres02.get("eventName"); + + //tmp_command + Map.Entry tempcommand02Pair = null; + String tempcommand02Object =""; + Map tempcommand02Parameters = ((Map)faultInstance02Parameters.get("tmp_command")); + Iterator<Map.Entry> itr9 = tempcommand02Parameters.entrySet().iterator(); + while (itr9.hasNext()) { + tempcommand02Pair = itr9.next(); + tempcommand02Object=String.valueOf(tempcommand02Pair); + tempcommand02res = tempcommand02Object.split("="); + faultInstanceres02.put(tempcommand02res[0], tempcommand02res[1]); + } + + + + //tmp_alarmSetParameters + Map.Entry Instance02alarmSetPair = null; + String Instance02alarmSetObject =""; + String[] Instance02alarmSetres; + Map Instance02alarmSetParameters = ((Map)faultInstance02Parameters.get("tmp_alarmSetParameters")); + Iterator<Map.Entry> itr10 = Instance02alarmSetParameters.entrySet().iterator(); + while (itr10.hasNext()) { + Instance02alarmSetPair = itr10.next(); + Instance02alarmSetObject=String.valueOf(Instance02alarmSetPair); + Instance02alarmSetres = Instance02alarmSetObject.split("="); + faultInstanceres02.put(Instance02alarmSetres[0], Instance02alarmSetres[1]); + } + + + setAlarmCondition = faultInstanceres02.get("alarmCondition").toString(); + setSpecificProblem = faultInstanceres02.get("specificProblem").toString(); + setEventSeverity = faultInstanceres02.get("eventSeverity").toString(); + + //tmp_alarmClearParameters + Map.Entry Instanceres02alarmClearPair = null; + String Instanceres02alarmClearObject =""; + String[] Instanceres02alarmClearres; + Map Instanceres02alarmClearParameters = ((Map)faultInstance02Parameters.get("tmp_alarmClearParameters")); + Iterator<Map.Entry> itr11 = Instanceres02alarmClearParameters.entrySet().iterator(); + while (itr11.hasNext()) { + Instanceres02alarmClearPair = itr11.next(); + Instanceres02alarmClearObject=String.valueOf(Instanceres02alarmClearPair); + Instanceres02alarmClearres = Instanceres02alarmClearObject.split("="); + Instanceres02ClearParameter.put(Instanceres02alarmClearres[0], Instanceres02alarmClearres[1]); + } + + ins02alarmConditionClear = Instanceres02ClearParameter.get("alarmCondition").toString(); + ins02specificProblemClear = Instanceres02ClearParameter.get("specificProblem").toString(); + ins02eventSeverityClear = Instanceres02ClearParameter.get("eventSeverity").toString(); + + + + + } catch (ClassCastException ex) { + ex.printStackTrace(); + } + return faultConfig; + } + + + public static HashMap<String, DeviceData> readVppMetrics(String[] linkStart) { + + //t0 + String Bytesin = faultConfigTempInit.get("tmp_t0BytesIn"); + String BytesOut = faultConfigTempInit.get("tmp_t0BytesOut").toString(); + String PacketsIn = faultConfigTempInit.get("tmp_t0PacketsIn"); + String PacketsOut = faultConfigTempInit.get("tmp_t0PacketsOut"); + + + //t1 + String t1BytesIn = faultConfigCommand.get("tmp_t1BytesIn"); + String t1BytesOut = faultConfigCommand.get("tmp_t1BytesOut").toString(); + String t1PacketsIn = faultConfigCommand.get("tmp_t1PacketsIn"); + String t1PacketsOut = faultConfigCommand.get("tmp_t1PacketsOut"); + + + + + String echoFalut = faultInstanceres02.get("tmp_cmd1"); + HashMap<String, DeviceData> vppMetrics = new HashMap<>(); + + for(int i=0;i<linkStart.length;i++) { + String device = linkStart[i]; + + + //t0 + String replaceBytesin =""; + if(Bytesin.contains("$tmp_device")) { + String repString = Bytesin.replace("$tmp_device", device.trim()); + replaceBytesin = repString.replace("sudo", "/bin/sh,-c,"); + } + String[] bytesinArray= replaceBytesin.split(","); + + + String replaceBytesOut =""; + if(BytesOut.contains("$tmp_device")) { + String repString = BytesOut.replace("$tmp_device", device.trim()); + replaceBytesOut = repString.replace("sudo", "/bin/sh,-c,"); + } + String[] bytesoutArray = replaceBytesOut.split(","); + + + String replacePacketsIn =""; + if(PacketsIn.contains("$tmp_device")) { + String repString = PacketsIn.replace("$tmp_device", device.trim()); + replacePacketsIn = repString.replace("sudo", "/bin/sh,-c,"); + } + String[] packetsInArray= replacePacketsIn.split(","); + + String replacePacketsOut =""; + if(PacketsOut.contains("$tmp_device")) { + String repString = PacketsOut.replace("$tmp_device", device.trim()); + replacePacketsOut = repString.replace("sudo", "/bin/sh,-c,"); + } + String[] packetsOutArray= replacePacketsOut.split(","); + + + + //t1 + String replacet1Bytesin =""; + if(t1BytesIn.contains("$tmp_device")) { + String repString = t1BytesIn.replace("$tmp_device", device.trim()); + replacet1Bytesin = repString.replace("sudo", "/bin/sh,-c,"); + } + String[] t1BytesinArray= replacet1Bytesin.split(","); + + String replacet1BytesOut =""; + if(t1BytesOut.contains("$tmp_device")) { + String repString = t1BytesOut.replace("$tmp_device", device.trim()); + replacet1BytesOut = repString.replace("sudo", "/bin/sh,-c,"); + } + String[] t1BytesoutArray = replacet1BytesOut.split(","); + + String replacet1PacketsIn =""; + if(t1PacketsIn.contains("$tmp_device")) { + String repString = t1PacketsIn.replace("$tmp_device", device.trim()); + replacet1PacketsIn = repString.replace("sudo", "/bin/sh,-c,"); + } + String[] t1PacketsInArray= replacet1PacketsIn.split(","); + + String replacet1PacketsOut =""; + if(t1PacketsOut.contains("$tmp_device")) { + String repString = t1PacketsOut.replace("$tmp_device", device.trim()); + replacet1PacketsOut = repString.replace("sudo", "/bin/sh,-c,"); + + } + String[] t1PacketsOutArray= replacet1PacketsOut.split(","); + + try { + //t0 + Runtime rt1 = Runtime.getRuntime(); + Process bytesinchild = rt1.exec(bytesinArray); + BufferedReader readerBytesin = new BufferedReader(new InputStreamReader( + bytesinchild.getInputStream())); + String readMetrics= readerBytesin.readLine(); + + + Runtime rt2 = Runtime.getRuntime(); + Process bytesoutchild = rt2.exec(bytesoutArray); + BufferedReader readerBytesout = new BufferedReader(new InputStreamReader( + bytesoutchild.getInputStream())); + String readMetrics1= readerBytesout.readLine(); + + Runtime rt3 = Runtime.getRuntime(); + Process packetsInchild = rt3.exec(packetsInArray); + BufferedReader readerPacketsIn = new BufferedReader(new InputStreamReader( + packetsInchild.getInputStream())); + String readMetrics2= readerPacketsIn.readLine(); + + Runtime rt4 = Runtime.getRuntime(); + Process packetsOutchild = rt4.exec(packetsOutArray); + BufferedReader readerpacketsOut = new BufferedReader(new InputStreamReader( + packetsOutchild.getInputStream())); + String readMetrics3= readerpacketsOut.readLine(); + + Runtime rt5 = Runtime.getRuntime(); + Process echoFaultchild = rt5.exec(echoFalut); + BufferedReader readerechoFault = new BufferedReader(new InputStreamReader( + echoFaultchild.getInputStream())); + String echoFaultMetric= readerechoFault.readLine(); + DeviceData mddata = new DeviceData(); + + + //t1_Commands run + + Runtime rt6 = Runtime.getRuntime(); + Process t1bytesinchild = rt6.exec(t1BytesinArray); + BufferedReader readert1Bytesin = new BufferedReader(new InputStreamReader( + t1bytesinchild.getInputStream())); + String readMetrics5= readert1Bytesin.readLine(); + + + + Runtime rt7 = Runtime.getRuntime(); + Process t1bytesoutchild = rt7.exec(t1BytesoutArray); + BufferedReader readert1Bytesout = new BufferedReader(new InputStreamReader( + t1bytesoutchild.getInputStream())); + String readMetrics6= readert1Bytesout.readLine(); + + Runtime rt8 = Runtime.getRuntime(); + Process t1packetsInchild = rt8.exec(t1PacketsInArray); + BufferedReader readert1PacketsIn = new BufferedReader(new InputStreamReader( + t1packetsInchild.getInputStream())); + String readMetrics7= readert1PacketsIn.readLine(); + + + Runtime rt9 = Runtime.getRuntime(); + Process t1packetsOutchild = rt9.exec(t1PacketsOutArray); + BufferedReader readert1packetsOut = new BufferedReader(new InputStreamReader( + t1packetsOutchild.getInputStream())); + String readMetrics8= readert1packetsOut.readLine(); + + + mddata.setT0bytesIn(readMetrics); + mddata.setT0bytesOut(readMetrics1); + mddata.setT0packetIn(readMetrics2); + mddata.setT0packetOut(readMetrics3); + + mddata.setT1Bytesin(readMetrics5); + mddata.setT1Bytesout(readMetrics6); + mddata.setT1Packetsin(readMetrics7); + mddata.setT1Packetsout(readMetrics8); + + + mddata.setInstanceres02Command(echoFaultMetric); + + vppMetrics.put("Instanceres02Cmd", mddata); + + if(device.equals("enp0s3")) { + vppMetrics.put("enp0s3", mddata); + }else if(device.equals("lo")) { + vppMetrics.put("lo", mddata); + }else if(device.equals("docker0")) { + vppMetrics.put("docker0", mddata); + } + + }catch (Exception e) { + + } + } + return vppMetrics; + } + +public static void main(String[] args) { + // TODO Auto-generated method stub + + try { + AgentMain.evel_initialize("http://127.0.0.1",30000, + null,null, + "will", + "pill", + null, null, null, + "http://127.0.0.1",30001, "will", + "pill", + Level.TRACE); + }catch(Exception e) { + // e.printStackTrace(); + // return; + } + FaultData flDataThread = new FaultData(); + new Thread(flDataThread.faultInstance01).start(); + new Thread(flDataThread.faultInstance02).start(); + } + +} diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/HeartBeatData.java b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/HeartBeatData.java new file mode 100644 index 0000000..26cccac --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/HeartBeatData.java @@ -0,0 +1,213 @@ +package evel_javalibrary.att.com.loadbalance; +/**************************************************************************//** + * @file + * Heartbeat field class + * + * This file implements the Heartbeat Event class which is intended to provide a + * simple wrapper around the complexity of AT&T's Vendor Event Listener API so + * that VNFs can use it to send Agent status. + * + * License + * ------- + * Unless otherwise specified, all software contained herein is + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *****************************************************************************/ + +import java.io.FileReader; +import java.io.IOException; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + + +import evel_javalibrary.att.com.AgentMain; +import evel_javalibrary.att.com.EvelHeartbeatField; + +import org.apache.log4j.Level; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + + +public class HeartBeatData extends Thread{ + static HashMap<String, String> hbConfig = new HashMap(); + static int gm_event_id = 1; + static String event_id1 = "heartbeatvfs"; + static String event_id = "00000000"; + static String event_id2=null; + + + public void run() { + + Long start_epoch_microsec = 0L; + Long last_epoch_microsec = 0L; + String hostName = hostName(); + try { + readHeartbeatConfig(); + }catch(Exception e) { + } + while(true) { + String heatBeatInterval=""; + long milliseconds = 60000; + + event_id2 = event_id1+ event_id+(gm_event_id++); + if(hbConfig.get("heartbeatInterval") == null) { + heatBeatInterval = Long.toString(milliseconds); + }else { + heatBeatInterval = hbConfig.get("heartbeatInterval"); + } + EvelHeartbeatField evelHb = new EvelHeartbeatField(Integer.parseInt(heatBeatInterval) , + hbConfig.get("eventName"), + event_id2); + + if( hbConfig.get("eventType")!=null) { + start_epoch_microsec = last_epoch_microsec; + last_epoch_microsec = System.nanoTime()/1000; + + evelHb.evel_last_epoch_set(start_epoch_microsec); + evelHb.evel_start_epoch_set(last_epoch_microsec); + + evelHb.evel_header_type_set(hbConfig.get("eventType").toString()); + evelHb.evel_nfcnamingcode_set(hbConfig.get("nfcNamingCode").toString()); + evelHb.evel_nfnamingcode_set(hbConfig.get("nfNamingCode").toString()); + if(hbConfig.get("reportingEntityName") == null) { + evelHb.evel_reporting_entity_name_set(hostName); + }else { + evelHb.evel_reporting_entity_name_set(hbConfig.get("reportingEntityName").toString()); + } + evelHb.evel_reporting_entity_id_set(hbConfig.get("reportingEntityId").toString()); + // evelHb.evel_nfVendorName_set(hbConfig.get("nfVendorName").toString()); + evelHb.evel_header_set_sourceid(true,hbConfig.get("sourceId").toString()); + if(hbConfig.get("sourceName") == null) { + evelHb.evel_header_set_source_name(hostName); + }else { + evelHb.evel_header_set_source_name(hbConfig.get("sourceName").toString()); + } + // evelHb.evel_timeZoneOffset_set(hbConfig.get("timeZoneOffset").toString()); + + } + + try { + Thread.sleep(Integer.parseInt(heatBeatInterval)); + }catch(Exception e) { + + } + AgentMain.evel_post_event(evelHb); + } + } + + + public static HashMap<String, String> readHeartbeatConfig() throws IOException, ParseException { + JSONParser jsonParser = new JSONParser(); + try { + + FileReader reader = new FileReader("./src/main/java/evel_javalibrary/att/com/loadbalance/hb_config.json"); + JSONObject obj = (JSONObject) jsonParser.parse(reader); + Map.Entry pair = null; + String convertObject =""; + String[] res; + Map directParameters = ((Map)obj.get("tmp_directParameters")); + Iterator<Map.Entry> itr1 = directParameters.entrySet().iterator(); + while (itr1.hasNext()) { + pair = itr1.next(); + convertObject=String.valueOf(pair); + res = convertObject.split("="); + hbConfig.put(res[0], res[1]); + } + + } catch (ClassCastException ex) { + ex.printStackTrace(); + } + return hbConfig; + } + +private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); +private static String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for ( int j = 0; j < bytes.length; j++ ) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = hexArray[v >>> 4]; + hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + } + return new String(hexChars); +} + +public static String hostName() { + String hostname = "Unknown"; + String uuid = "Unknown"; + try + { + InetAddress addr; + addr = InetAddress.getLocalHost(); + hostname = addr.getHostName(); + } + catch (UnknownHostException ex) + { + } + try{ + Enumeration<NetworkInterface> networks = + NetworkInterface.getNetworkInterfaces(); + while(networks.hasMoreElements()) { + NetworkInterface network = networks.nextElement(); + byte[] mac = network.getHardwareAddress(); + + if(hostname.equalsIgnoreCase("unknown")) + { + Enumeration inetAddrs = network.getInetAddresses(); + while(inetAddrs.hasMoreElements()){ + InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); + if (!inetAddr.isLoopbackAddress()) { + hostname = inetAddr.getHostAddress(); + break; + } + } + } + if (mac != null) { + uuid = bytesToHex(mac); + } + } + } catch (SocketException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return hostname; +} + +public static void main(String[] args) { + // TODO Auto-generated method stub + + try { + AgentMain.evel_initialize("http://127.0.0.1",30000, + null,null, + "will", + "pill", + null, null, null, + "http://127.0.0.1",30001, "will", + "pill", + Level.TRACE); + }catch(Exception e) { + e.printStackTrace(); + return; + } + HeartBeatData hbDataThread = new HeartBeatData(); + hbDataThread.start(); + } + + + +} diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/MeasureData.java b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/MeasureData.java new file mode 100644 index 0000000..88d99d9 --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/MeasureData.java @@ -0,0 +1,599 @@ +package evel_javalibrary.att.com.loadbalance; +/**************************************************************************//** + * @file + * Measurement class + * + * This file implements the Measurement Event class which is intended to provide a + * simple wrapper around the complexity of AT&T's Vendor Event Listener API so + * that VNFs can use it to send CPU, Memory, Disk Measurements to Collector. + * + * License + * ------- + * Unless otherwise specified, all software contained herein is + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *****************************************************************************/ + + +import java.io.BufferedReader; + +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Level; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import evel_javalibrary.att.com.AgentMain; +import evel_javalibrary.att.com.EvelBatch; +import evel_javalibrary.att.com.EvelScalingMeasurement; + +public class MeasureData extends Thread{ + + + static HashMap<String, String> measConfig = new HashMap<>(); + static String[] resDevice =null; + static String[] tempInitres; + static String[] tempcommandres; + static String[] tempcommandres1; + static HashMap<String, String> vNicPerformanceCommand1 = new HashMap<>(); + static HashMap<String, String> vNicPerformanceArray = new HashMap<>(); + static HashMap<String, String> initTempCommand = new HashMap<>(); + static float bytesInLo; + static float bytesOutLo; + static float packetsInLo; + static float packetsOutLo; + + static float bytesInEnps03; + static float bytesOutEnps03; + static float packetsInEnps03; + static float packetsOutEnps03; + + static float bytesInDocker0; + static float bytesOutDocker0; + static float packetsInDocker0; + static float packetsOutDocker0; + + + static int gmEventId = 1; + static String eventId1 = "mvfs"; + static String eventId = "00000000"; + static String eventId2=null; + + static int requestRate = 0; + static String linkStart = ""; + static int linkCount; + + + Long start_epoch_microsec = 0L; + Long last_epoch_microsec = 0L; + public void run() { + + try { + + readMeasurementConfig(); + //readVppMetrics(resDevice); + } catch (IOException | ParseException e1) { + e1.printStackTrace(); + } + + String[] intFaceMap = resDevice; + + int numOfInterfaces = 0; + if( intFaceMap != null) + numOfInterfaces = intFaceMap.length; + if( numOfInterfaces <= 0) { + + return; + } + + + + + try { + Thread.sleep(1000); + }catch(Exception e) {} + + + while(true) { + HashMap<String, DeviceData> lastMetrics = readVppMetrics(resDevice); + //HashMap<String, DeviceData> currentMetrics = readVppMetrics(resDevice);; + HashMap<String, DeviceData> currentMetrics = lastMetrics; + requestRate =2; + eventId2 = eventId1+ eventId+(gmEventId++); + String measurmentInterval=""; + long milliseconds = 60000; + if(measConfig.get("measurementInterval") == null) { + measurmentInterval = Long.toString(milliseconds); + }else { + measurmentInterval = measConfig.get("measurementInterval"); + } + EvelScalingMeasurement eveMeas = new EvelScalingMeasurement(Integer.parseInt(measurmentInterval) , + measConfig.get("eventName"), + eventId2); + + for( String vNic : intFaceMap) { + + int receivedOctetsDeltaLo = 0; + int receivedTotalPacketsDeltaLo = 0; + int transmittedOctetsDeltaLo = 0; + int transmittedTotalPacketsDeltaLo = 0; + + System.out.println("Data Array T0 "+vNic+" , "+ currentMetrics.get(vNic).getT0bytesIn()+" " + + currentMetrics.get(vNic).getT0bytesOut()+" " + + currentMetrics.get(vNic).getT0packetIn()+" " + + currentMetrics.get(vNic).getT0packetOut()); + System.out.println("Data Array T1 "+vNic+" , "+ currentMetrics.get(vNic).getT1Bytesin()+" " + + currentMetrics.get(vNic).getT1Bytesout()+" " + + currentMetrics.get(vNic).getT1Packetsin()+" " + + currentMetrics.get(vNic).getT1Packetsout()); + + + + if (Integer.parseInt((currentMetrics.get(vNic).getT1Bytesin())) + - Integer.parseInt((lastMetrics.get(vNic).getT0bytesIn()) ) > 0) { + receivedOctetsDeltaLo = (int) (Integer.parseInt((currentMetrics.get(vNic).getT1Bytesin()) ) + - Integer.parseInt((lastMetrics.get(vNic).getT0bytesIn()) )); + } else { + receivedOctetsDeltaLo = 0; + } + + + if (Integer.parseInt((currentMetrics.get(vNic).getT1Packetsin())) + - Integer.parseInt((lastMetrics.get(vNic).getT0packetIn()) ) > 0) { + receivedTotalPacketsDeltaLo = (int) (Integer.parseInt((currentMetrics.get(vNic).getT1Packetsin()) ) + - Integer.parseInt((lastMetrics.get(vNic).getT0packetIn()) )); + } else { + receivedTotalPacketsDeltaLo = 0; + } + + + if (Integer.parseInt((currentMetrics.get(vNic).getT1Bytesout())) + - Integer.parseInt((lastMetrics.get(vNic).getT0bytesOut()) ) > 0) { + transmittedOctetsDeltaLo = (int) (Integer.parseInt((currentMetrics.get(vNic).getT1Bytesout()) ) + - Integer.parseInt((lastMetrics.get(vNic).getT0bytesOut()))); + } else { + transmittedOctetsDeltaLo = 0; + } + + + if (Integer.parseInt((currentMetrics.get(vNic).getT1Packetsout())) + - Integer.parseInt((lastMetrics.get(vNic).getT0packetOut()) ) > 0) { + transmittedTotalPacketsDeltaLo = (int) (Integer.parseInt((currentMetrics.get(vNic).getT1Packetsout()) ) + - Integer.parseInt((lastMetrics.get(vNic).getT0packetOut()))); + } else { + transmittedTotalPacketsDeltaLo = 0; + } + + + EvelScalingMeasurement.MEASUREMENT_VNIC_PERFORMANCE vNicPerf = eveMeas.evel_measurement_new_vnic_performance(vNic.replaceAll("^[\"']+|[\"']+$", ""), "true"); + eveMeas.evel_meas_vnic_performance_add(vNicPerf); + + if( measConfig.get("eventType")!=null) { + String hostName = hostName(); + start_epoch_microsec = last_epoch_microsec; + last_epoch_microsec = System.nanoTime()/1000; + eveMeas.evel_last_epoch_set(start_epoch_microsec); + eveMeas.evel_start_epoch_set(last_epoch_microsec); + eveMeas.evel_measurement_type_set( measConfig.get("eventType").toString()); + + eveMeas.evel_vnic_performance_rx_octets_delta_set( vNicPerf, receivedOctetsDeltaLo); + eveMeas.evel_vnic_performance_rx_total_pkt_delta_set(vNicPerf, receivedTotalPacketsDeltaLo); + eveMeas.evel_vnic_performance_tx_octets_delta_set( vNicPerf, transmittedOctetsDeltaLo); + eveMeas.evel_vnic_performance_tx_total_pkt_delta_set(vNicPerf, transmittedTotalPacketsDeltaLo); + + + eveMeas.evel_nfcnamingcode_set(measConfig.get("nfcNamingCode").toString()); + eveMeas.evel_nfnamingcode_set(measConfig.get("nfNamingCode").toString()); + if(measConfig.get("reportingEntityName") == null) { + eveMeas.evel_reporting_entity_name_set(hostName); + }else { + eveMeas.evel_reporting_entity_name_set(measConfig.get("reportingEntityName").toString()); + } + eveMeas.evel_reporting_entity_id_set(measConfig.get("reportingEntityId").toString()); + + eveMeas.evel_header_set_sourceid(true,measConfig.get("sourceId").toString()); + if(measConfig.get("sourceName") == null) { + eveMeas.evel_header_set_source_name(hostName); + }else { + eveMeas.evel_header_set_source_name(measConfig.get("sourceName").toString()); + } + + } + + } + AgentMain.evel_post_event(eveMeas); + boolean continues = true; + long curr = System.currentTimeMillis(); + while(continues) { + try { + Thread.sleep(100); + }catch (Exception e) { + // TODO: handle exception + } + if(System.currentTimeMillis() >= (curr+Integer.parseInt(measurmentInterval))) { + continues = false; + } + + + } + } + + } + + private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); + private static String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for ( int j = 0; j < bytes.length; j++ ) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = hexArray[v >>> 4]; + hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + } + return new String(hexChars); + } + public static String hostName() { + String hostname = "Unknown"; + String uuid = "Unknown"; + try + { + InetAddress addr; + addr = InetAddress.getLocalHost(); + hostname = addr.getHostName(); + } + catch (UnknownHostException ex) + { + } + try{ + Enumeration<NetworkInterface> networks = + NetworkInterface.getNetworkInterfaces(); + while(networks.hasMoreElements()) { + NetworkInterface network = networks.nextElement(); + byte[] mac = network.getHardwareAddress(); + + if(hostname.equalsIgnoreCase("unknown")) + { + Enumeration inetAddrs = network.getInetAddresses(); + while(inetAddrs.hasMoreElements()){ + InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); + if (!inetAddr.isLoopbackAddress()) { + hostname = inetAddr.getHostAddress(); + break; + } + } + } + if (mac != null) { + uuid = bytesToHex(mac); + } + } + } catch (SocketException e) { + // TODO Auto-generated catch block + + } + + return hostname; + } + + + public static HashMap<String, String> readMeasurementConfig() throws IOException, ParseException { + JSONParser jsonParser = new JSONParser(); + + try { + + FileReader reader = new FileReader("./src/main/java/evel_javalibrary/att/com/loadbalance/meas_config.json"); + JSONObject obj = (JSONObject) jsonParser.parse(reader); + Map.Entry directPair = null; + String directObject =""; + String[] directres; + Map directParameters = ((Map)obj.get("tmp_directParameters")); + Iterator<Map.Entry> itr1 = directParameters.entrySet().iterator(); + while (itr1.hasNext()) { + directPair = itr1.next(); + directObject=String.valueOf(directPair); + directres = directObject.split("="); + measConfig.put(directres[0], directres[1]); + } + + String eventName = measConfig.get("eventName").toString(); + JSONArray arrJson = (JSONArray) directParameters.get("tmp_device"); + resDevice = new String[arrJson.size()]; + for(int i = 0; i < arrJson.size(); i++) + resDevice[i] = (String) arrJson.get(i); + + + //tmp_indirectParameters + Map.Entry indirectPair = null; + String indirectObject =""; + String[] indirectres; + Map indirectParameters = ((Map)obj.get("tmp_indirectParameters")); + Iterator<Map.Entry> itr2 = indirectParameters.entrySet().iterator(); + while (itr2.hasNext()) { + indirectPair = itr2.next(); + indirectObject=String.valueOf(indirectPair); + indirectres = indirectObject.split("="); + measConfig.put(indirectres[0], indirectres[1]); + } + + + + //tmp_init + // Map tempInitParameters = ((Map)indirectParameters.get("tmp_init")); + + //tmp_init + Map.Entry tempcommandPair = null; + String tempcommandObject =""; + Map tempcommandParameters = ((Map)indirectParameters.get("tmp_init")); + Iterator<Map.Entry> itr3 = tempcommandParameters.entrySet().iterator(); + while (itr3.hasNext()) { + tempcommandPair = itr3.next(); + tempcommandObject=String.valueOf(tempcommandPair); + tempcommandres = tempcommandObject.split("="); + initTempCommand.put(tempcommandres[0], tempcommandres[1]); + } + + //tmp_command1 + Map.Entry tempcommand1Pair = null; + String tempcommand1Object =""; + JSONArray nicPerfomenceArray = (JSONArray) indirectParameters.get("vNicPerformance"); + Map vNic = (Map)nicPerfomenceArray.get(0); + Map perf = ((Map)vNic.get("tmp_vnic_command")); + Iterator<Map.Entry> itr5 = perf.entrySet().iterator(); + while (itr5.hasNext()) { + tempcommand1Pair = itr5.next(); + tempcommand1Object=String.valueOf(tempcommand1Pair); + tempcommandres1 = tempcommand1Object.split("="); + vNicPerformanceCommand1.put(tempcommandres1[0], tempcommandres1[1]); + } + Map.Entry vnicPair = null; + String vnicObject =""; + String[] nicPerfomenceArrayRes; + vNic = (Map)nicPerfomenceArray.get(0); + Iterator<Map.Entry> itr6 = vNic.entrySet().iterator(); + while (itr6.hasNext()) { + vnicPair = itr6.next(); + vnicObject=String.valueOf(vnicPair); + nicPerfomenceArrayRes = vnicObject.split("="); + vNicPerformanceArray.put(nicPerfomenceArrayRes[0], nicPerfomenceArrayRes[1]); + } + + String receivedOctetsDelta = vNicPerformanceArray.get("receivedOctetsDelta"); + + } catch (ClassCastException ex) { + + } + return measConfig; + } + + + + + + public static HashMap<String, DeviceData> readVppMetrics(String[] linkStart) { + DeviceData mddata = null; new DeviceData(); + + + //tmp_t0 + String t0BytesIn = initTempCommand.get("tmp_t0BytesIn"); + String t0BytesOut = initTempCommand.get("tmp_t0BytesOut"); + String t0PacketsIn = initTempCommand.get("tmp_t0PacketsIn"); + String t0PacketsOut = initTempCommand.get("tmp_t0PacketsOut"); + + //tmp_t1 + String t1BytesIn = vNicPerformanceCommand1.get("tmp_t1BytesIn"); + String t1BytesOut = vNicPerformanceCommand1.get("tmp_t1BytesOut").toString(); + String t1PacketsIn = vNicPerformanceCommand1.get("tmp_t1PacketsIn"); + String t1PacketsOut = vNicPerformanceCommand1.get("tmp_t1PacketsOut"); + + + HashMap<String, DeviceData> vppMetrics = new HashMap<>(); + for(int i = 0; i < linkStart.length; i++) { + mddata =new DeviceData(); + String device = linkStart[i]; + + //t0_ + String replaceInitBytesint0 =""; + if(t0BytesIn.contains("$tmp_device")) { + String repString = t0BytesIn.replace("$tmp_device", device.trim()); + replaceInitBytesint0 = repString.replace("sudo", "/bin/sh,-c,"); + + } + String[] t0BytesinArray= replaceInitBytesint0.split(","); + + + String replaceInitBytesout=""; + if(t0BytesOut.contains("$tmp_device")) { + String repString = t0BytesOut.replace("$tmp_device", device.trim()); + replaceInitBytesout = repString.replace("sudo", "/bin/sh,-c,"); + + } + String[] t0BytesoutArray= replaceInitBytesout.split(","); + + String replaceInitPacketsin =""; + if(t0PacketsIn.contains("$tmp_device")) { + String repString = t0PacketsIn.replace("$tmp_device", device.trim()); + replaceInitPacketsin = repString.replace("sudo", "/bin/sh,-c,"); + + } + String[] t0PacketsinArray= replaceInitPacketsin.split(","); + + + String replaceInitPacketsout =""; + if(t0PacketsOut.contains("$tmp_device")) { + String repString = t0PacketsOut.replace("$tmp_device", device.trim()); + replaceInitPacketsout = repString.replace("sudo", "/bin/sh,-c,"); + + } + String[] t0PacketsoutArray= replaceInitPacketsout.split(","); + + //t1 + String replaceBytesin =""; + if(t1BytesIn.contains("$tmp_device")) { + String repString = t1BytesIn.replace("$tmp_device", device.trim()); + replaceBytesin = repString.replace("sudo", "/bin/sh,-c,"); + + } + String[] t1BytesinArray= replaceBytesin.split(","); + + String replaceBytesOut =""; + if(t1BytesOut.contains("$tmp_device")) { + String repString = t1BytesOut.replace("$tmp_device", device.trim()); + replaceBytesOut = repString.replace("sudo", "/bin/sh,-c,"); + } + String[] t1BytesoutArray = replaceBytesOut.split(","); + + String replacePacketsIn =""; + if(t1PacketsIn.contains("$tmp_device")) { + String repString = t1PacketsIn.replace("$tmp_device", device.trim()); + replacePacketsIn = repString.replace("sudo", "/bin/sh,-c,"); + } + String[] t1PacketsInArray= replacePacketsIn.split(","); + + String replacePacketsOut =""; + if(t1PacketsOut.contains("$tmp_device")) { + String repString = t1PacketsOut.replace("$tmp_device", device.trim()); + replacePacketsOut = repString.replace("sudo", "/bin/sh,-c,"); + + } + String[] t1PacketsOutArray= replacePacketsOut.split(","); + + try { + //t0_Commands run + Runtime rt5 = Runtime.getRuntime(); + Process initBytesint0child = rt5.exec(t0BytesinArray); + BufferedReader readerinitBytesint0 = new BufferedReader(new InputStreamReader( + initBytesint0child.getInputStream())); + String readinitMetrics= readerinitBytesint0.readLine(); + + Runtime rt6 = Runtime.getRuntime(); + Process initBytesoutchild = rt6.exec(t0BytesoutArray); + BufferedReader readerinitBytesout = new BufferedReader(new InputStreamReader( + initBytesoutchild.getInputStream())); + String readinitMetrics2= readerinitBytesout.readLine(); + + + Runtime rt7 = Runtime.getRuntime(); + Process initPacketsinchild = rt7.exec(t0PacketsinArray); + BufferedReader readerinitPacketsin = new BufferedReader(new InputStreamReader( + initPacketsinchild.getInputStream())); + String readinitMetrics3= readerinitPacketsin.readLine(); + + + + Runtime rt8 = Runtime.getRuntime(); + Process initPacketsoutchild = rt8.exec(t0PacketsoutArray); + BufferedReader readerinitPacketsout = new BufferedReader(new InputStreamReader( + initPacketsoutchild.getInputStream())); + String readinitMetrics4= readerinitPacketsout.readLine(); + + + + //t1_Commands run + Thread.sleep(Integer.parseInt(measConfig.get("measurementInterval"))); + Runtime rt1 = Runtime.getRuntime(); + Process bytesinchild = rt1.exec(t1BytesinArray); + // bytesinchild.waitFor(); + BufferedReader readerBytesin = new BufferedReader(new InputStreamReader( + bytesinchild.getInputStream())); + String readMetrics= readerBytesin.readLine(); + + + + Runtime rt2 = Runtime.getRuntime(); + Process bytesoutchild = rt2.exec(t1BytesoutArray); + BufferedReader readerBytesout = new BufferedReader(new InputStreamReader( + bytesoutchild.getInputStream())); + String readMetrics1= readerBytesout.readLine(); + + Runtime rt3 = Runtime.getRuntime(); + Process packetsInchild = rt3.exec(t1PacketsInArray); + BufferedReader readerPacketsIn = new BufferedReader(new InputStreamReader( + packetsInchild.getInputStream())); + String readMetrics2= readerPacketsIn.readLine(); + + + Runtime rt4 = Runtime.getRuntime(); + Process packetsOutchild = rt4.exec(t1PacketsOutArray); + BufferedReader readerpacketsOut = new BufferedReader(new InputStreamReader( + packetsOutchild.getInputStream())); + String readMetrics3= readerpacketsOut.readLine(); + + // System.out.println(device+" , T1 command data: "+ readMetrics+"," + readMetrics1+"," + readMetrics2+"," + readMetrics3); + // System.out.println(device+" , T0 command data: "+ readinitMetrics+"," + readinitMetrics2+"," + readinitMetrics3+"," + readinitMetrics4); + + //t1 + mddata.setT1Bytesin(readMetrics); + mddata.setT1Bytesout(readMetrics1); + mddata.setT1Packetsin(readMetrics2); + mddata.setT1Packetsout(readMetrics3); + + //t0 + mddata.setT0bytesIn(readinitMetrics); + mddata.setT0bytesOut(readinitMetrics2); + mddata.setT0packetIn(readinitMetrics3); + mddata.setT0packetOut(readinitMetrics4); + + if(device.equals("enp0s3")) { + vppMetrics.put("enp0s3", mddata); + + }else if(device.equals("lo")) { + vppMetrics.put("lo", mddata); + }else if(device.equals("docker0")) { + vppMetrics.put("docker0", mddata); + } + + }catch (Exception e) { + e.printStackTrace(); + } + } + return vppMetrics; + } + + + + + + public static void main(String[] args) { + // TODO Auto-generated method stub + + try { + AgentMain.evel_initialize("http://127.0.0.1",30000, + null,null, + "will", + "pill", + null, null, null, + "http://127.0.0.1",30001, "will", + "pill", + Level.TRACE); + }catch(Exception e) { + e.printStackTrace(); + return; + } + MeasureData mdataThread = new MeasureData(); + mdataThread.start(); + + } + + + +} diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_Fault.md b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_Fault.md new file mode 100644 index 0000000..0151629 --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_Fault.md @@ -0,0 +1,33 @@ + +PROJECT DESCRIPTION + +--- +This project contains the source code and scripts for the generation of fault events. + + - README.md: this file. + + + - FaultData.java and DeviceData.java files: source code that uses the ECOMP Vendor Event Listener Library (VES) to generate the fault events. Fault is generated based on the link status. If number of bytes transmitted/received is less than the low water mark, the fault is generated. The application reads flt_config.json file for parameter values and populate the fault event. If eventName, eventSourceType, vfStatus, specificProblem or alarmCondition parameter value is not given, the application terminates. If reportingEntityName and sourceName parameter values are not given, then it gets the hostname and populates it. If tmp_faultCheckInterval is not given, it defaults to 60 seconds. + + + + - FaultData.java: It reads input parameters like DCAE IP address and port from configuration files contained in /opt/config. Based on the collector configuration, use FaultData.java for use single and 2 collectors configuration. + + +USAGE +----- + +Update the configuration files with proper parameters values so that events generated would contain those values + +To run the FaultData.java in single collector configuration, please execute the following steps: + + -Compile Load Balance VES agent + javac -cp <.:dependent jars> ./evel_javalibrary/att/com/loadbalance + In Eclipse right click on veslibrary/ves_javalibrary/evel_javalib2 application-> click Run As ->and select -> mvn build option then + ->select the configuration mvn clean install. + + + -Run Load Balance VES agent + java -cp <.:dependent jars> evel_javalibrary.att.com.loadbalance.FaultData.java + In Eclipse right click on evel_javalibrary.att.com.loadbalance.FaultData.java class right click -> click Run As -> click Java application. + diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_HeartBeat.md b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_HeartBeat.md new file mode 100644 index 0000000..c9e5792 --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_HeartBeat.md @@ -0,0 +1,33 @@ + +PROJECT DESCRIPTION + +--- +This project contains the source code and scripts for the periodic generation of heartbeat events. + + - README.md: this file. + + + - HeartBeatData.java file: source code that uses the ECOMP Vendor Event Listener Library (VES) to generate the periodic heartbeat events. It reads hb_config.json file for parameter values and populate the heartbeat event. If eventName parameter value is not given, the application terminates. If reportingEntityName and sourceName parameter values are not given, then it gets the hostname and populates it. If heartbeatInterval is not given, it defaults to 60 seconds. + + + + - HeartBeatData.java file: It reads input parameters like DCAE IP address and port from configuration files contained in /opt/config. Based on the collector configuration, use HeartBeatData.java file for single and 2 collectors configuration. + + +USAGE +----- + +Update the configuration files with proper parameters values so that events generated would contain those values + +To run the HeartBeatData.java in single collector configuration, please execute the following steps: + + -Compile Load Balance VES agent + javac -cp <.:dependent jars> ./evel_javalibrary/att/com/loadbalance + In Eclipse right click on veslibrary/ves_javalibrary/evel_javalib2 application-> click Run As ->and select -> mvn build option then + ->select the configuration mvn clean install. + + -Run Load Balance VES agent + java -cp <.:dependent jars> evel_javalibrary.att.com.loadbalance.HeartBeatData.java + In Eclipse right click on evel_javalibrary.att.com.loadbalance.HeartBeatData.java class right click -> click Run As -> click Java application. + + diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_Measurement.md b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_Measurement.md new file mode 100644 index 0000000..f17c9d4 --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_Measurement.md @@ -0,0 +1,32 @@ + +PROJECT DESCRIPTION + +--- +This project contains the source code and scripts for the periodic generation of network measurement reports events. It also generates fault event if the packets/bytes transferred are below the low water mark for the network interface. + + - README.md: this file. + + + - MeasureData.java and DeviceData.java files: source code that uses the ECOMP Vendor Event Listener Library (VES) to read metrics from the network interface and send periodic measurement reports to the VES collector in DCAE. It reads meas_config.json file for parameter values and populate the heartbeat event. If eventName parameter value is not given, the application terminates. If reportingEntityName and sourceName parameter values are not given, then it gets the hostname and populates it. + + + - - MeasureData.java: It reads input parameters like DCAE IP address and port from configuration files contained in /opt/config. Based on the collector configuration, use MeasureData.java for single and 2 collectors configuration. + + +USAGE +----- + +Update the configuration files with proper parameters values so that events generated would contain those values + +To run the MeasureData.java, please execute the following steps: + + -Compile Load Balance VES agent + javac -cp <.:dependent jars> ./evel_javalibrary/att/com/loadbalance + In Eclipse right click on veslibrary/ves_javalibrary/evel_javalib2 application-> click Run As ->and select -> mvn build option then + ->select the configuration mvn clean install. + + -Run Load Balance VES agent + java -cp <.:dependent jars> evel_javalibrary.att.com.loadbalance.MeasureData.java + In Eclipse right click on evel_javalibrary.att.com.loadbalance.MeasureData.java class right click -> click Run As -> click Java application. + + diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_Syslog.md b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_Syslog.md new file mode 100644 index 0000000..8b8ee6d --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/README_Syslog.md @@ -0,0 +1,30 @@ + +PROJECT DESCRIPTION + +--- +This project contains the source code and scripts for the periodic generation of network measurement reports and heartbeat events. It also generates fault event if the packets/bytes transferred are below the low water mark for the network interface. + + + - syslogData.java file: source code that uses the ECOMP Vendor Event Listener Library (VES) to read syslog message from /var/log/syslog and send syslog events to the VES collector in DCAE. It reads syslog_config.json file for parameter values and populate the syslog event. If eventName parameter value is not given, the application terminates. If reportingEntityName and sourceName parameter values are not given. + + + - - syslogData.java: It reads input parameters like DCAE IP address and port from configuration files contained in /opt/config. Based on the collector configuration, use MeasureData.java for single and 2 collectors configuration. + + +USAGE +----- + +Update the configuration files with proper parameters values so that events generated would contain those values + +To run the MeasureData.java, please execute the following steps: + + -Compile Load Balance VES agent + javac -cp <.:dependent jars> ./evel_javalibrary/att/com/loadbalance + In Eclipse right click on veslibrary/ves_javalibrary/evel_javalib2 application-> click Run As ->and select -> mvn build option then + ->select the configuration mvn clean install. + + -Run Load Balance VES agent + java -cp <.:dependent jars> evel_javalibrary.att.com.loadbalance.syslogData.java + In Eclipse right click on evel_javalibrary.att.com.loadbalance.syslogData.java class right click -> click Run As -> click Java application. + + diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/flt_config.json b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/flt_config.json new file mode 100644 index 0000000..5833b2e --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/flt_config.json @@ -0,0 +1,74 @@ +{ + "tmp_directParameters": { + "eventType": "applicationVnf", + "nfcNamingCode": "AFX", + "nfNamingCode": "AFX", + "nfVendorName": "AT&T", + "priority": "Low", + "reportingEntityId": "cc305d54-75b4-431b-adb2-eb6b9e541234", + "reportingEntityName": "ibcx0001vm002oam001", + "sourceId": "de305d54-75b4-431b-adb2-eb6b9e546014", + "sourceName": "scfx0001vm002cap001", + "timeZoneOffset": "UTC-05:30", + "vfStatus": "Idle", + "tmp_device": ["lo", "enp0s3","docker0"] + + }, + "tmp_indirectParameters": { + "tmp_faultInstance01": { + "eventName": "Fault_vLoadbalance-AT&T_linkDownError", + "eventCategory": "link", + "eventSourceType": "router", + "tmp_init":{ + "tmp_t0BytesIn": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f2", + "tmp_t0BytesOut": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f10", + "tmp_t0PacketsIn": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f3", + "tmp_t0PacketsOut": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f11" + }, + "alarmInterfaceA": "$tmp_device", + "tmp_faultCheckInterval": 20, + "tmp_lowWaterMark": 1, + "tmp_command": { + "tmp_t1BytesIn": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f2", + "tmp_t1BytesOut": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f10", + "tmp_t1PacketsIn": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f3", + "tmp_t1PacketsOut": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f11" + }, + "tmp_BytesIn": "$(tmp_t1BytesIn - tmp_t0BytesIn)", + "tmp_PacketsIn": "$(tmp_t1PacketsIn - tmp_t0PacketsIn)", + "tmp_BytesOut": "$(tmp_t1BytesOut - tmp_t0BytesOut)", + "tmp_PacketsOut": "$(tmp_t1PacketsOut - tmp_t0PacketsOut)", + "tmp_alarmSetParameters": { + "specificProblem": "physical or logical connection to a remote router is down", + "eventSeverity": "MAJOR", + "alarmCondition": "link down trap_alarm" + }, + "tmp_alarmClearParameters": { + "specificProblem": "physical or logical connection to a remote router is up", + "eventSeverity": "NORMAL", + "alarmCondition": "link up trap_alarm" + } + }, + "tmp_faultInstance02": { + "eventName": "Fault_vLoadbalance-AT&T_serviceDownError", + "alarmInterfaceA": "afx@input.service", + "eventCategory": "other", + "eventSourceType": "virtualMachine", + "tmp_faultCheckInterval": 10, + "tmp_command": { + + "tmp_cmd1": "echo 1" + }, + "tmp_alarmSetParameters": { + "specificProblem": "service is down", + "eventSeverity": "MAJOR", + "alarmCondition": "service down trap_alarm" + }, + "tmp_alarmClearParameters": { + "specificProblem": "service is up", + "eventSeverity": "NORMAL", + "alarmCondition": "service up trap_alarm" + } + } + } +} diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/hb_config.json b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/hb_config.json new file mode 100644 index 0000000..c1b3a19 --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/hb_config.json @@ -0,0 +1,15 @@ +{ + "tmp_directParameters": { + "eventName": "Heartbeat_vLoadbalance-AT&T_heartbeat", + "eventType": "platform", + "nfcNamingCode": "ssc", + "nfNamingCode": "scfx", + "nfVendorName": "AT&T", + "reportingEntityId": "cc305d54-75b4-431b-adb2-eb6b9e541234", + "reportingEntityName": "ibcx0001vm002oam001", + "sourceId": "de305d54-75b4-431b-adb2-eb6b9e546014", + "sourceName": "scfx0001vm002cap001", + "timeZoneOffset": "UTC-05:30", + "heartbeatInterval": 300 + } +} diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/meas_config.json b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/meas_config.json new file mode 100644 index 0000000..5d1a41e --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/meas_config.json @@ -0,0 +1,51 @@ +{ + "tmp_directParameters": { + "eventName": "Measurement_vFirewall-AT&T_nicPerformance", + "eventType": "applicationVnf", + "nfcNamingCode": "AFX", + "nfNamingCode": "AFX", + "nfVendorName": "AT&T", + "priority": "Low", + "reportingEntityId": "cc305d54-75b4-431b-adb2-eb6b9e541234", + "reportingEntityName": "ibcx0001vm002oam001", + "sourceId": "de305d54-75b4-431b-adb2-eb6b9e546014", + "sourceName": "scfx0001vm002cap001", + "timeZoneOffset": "UTC-05:30", + "measurementInterval": 25000, + "tmp_device": ["lo", "enp0s3","docker0"] + }, + "tmp_indirectParameters": { + "tmp_init":{ + "tmp_t0BytesIn": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f2", + "tmp_t0BytesOut": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f10", + "tmp_t0PacketsIn": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f3", + "tmp_t0PacketsOut": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f11" + }, + "vNicPerformance": [{ + "tmp_vnic_command": { + "tmp_t1BytesIn": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f2", + "tmp_t1BytesOut": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f10", + "tmp_t1PacketsIn": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f3", + "tmp_t1PacketsOut": "sudo cat /proc/net/dev | grep $tmp_device | tr -s ' ' | cut -d ':' -f2 | cut -d ' ' -f11" + }, + "receivedOctetsDelta": "$(tmp_t1BytesIn - tmp_t0BytesIn)", + "receivedTotalPacketsDelta": "$(tmp_t1PacketsIn - tmp_t0PacketsIn)", + "transmittedOctetsDelta": "$(tmp_t1BytesOut - tmp_t0BytesOut)", + "transmittedTotalPacketsDelta": "$(tmp_t1PacketsOut - tmp_t0PacketsOut)", + "valuesAreSuspect": "true", + "vNicIdentifier": "$tmp_device" + }], + "cpuUsage": [{ + "tmp_cpuuse_command": { + "tmp_cpuUseCmd": "/usr/bin/top -bn 2 -d 0.01 | grep '^%Cpu' | tail -n 1 | cut -d ':' -f2", + "tmp_cpuIdle": "/usr/bin/top -bn 2 -d 0.01 | grep '^%Cpu' | tail -n 1 |cut -d ':' -f2 | cut -d ',' -f4 | cut -b 1-5", + "tmp_cpuUsageSystem": "/usr/bin/top -bn 2 -d 0.01 | grep '^%Cpu' | tail -n 1 |cut -d ':' -f2 | cut -d ',' -f2 | cut -b 1-5", + "tmp_cpuUsageUser": "/usr/bin/top -bn 2 -d 0.01 | grep '^%Cpu' | tail -n 1 |cut -d ':' -f2 | cut -d ',' -f1 | cut -b 1-5" + }, + "cpuIdentifier": "Cpu1", + "cpuIdle": "$tmp_cpuIdle", + "cpuUsageSystem": "$tmp_cpuUsageSystem", + "cpuUsageUser": "$tmp_cpuUsageUser" + }] + } +}
\ No newline at end of file diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/syslogData.java b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/syslogData.java new file mode 100644 index 0000000..378a508 --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/syslogData.java @@ -0,0 +1,274 @@ +package evel_javalibrary.att.com.loadbalance; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import org.apache.log4j.Level; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import evel_javalibrary.att.com.AgentMain; +import evel_javalibrary.att.com.EvelFault; +import evel_javalibrary.att.com.EvelSyslog; +import evel_javalibrary.att.com.EvelSyslog.EVEL_SYSLOG_FACILITIES; + +/**************************************************************************//** + * @file + * Syslog class + * + * This file implements the Measurement Event class which is intended to provide a + * simple wrapper around the complexity of AT&T's Vendor Event Listener API so + * that VNFs can use it to send CPU, Memory, Disk Measurements to Collector. + * + * License + * ------- + * Unless otherwise specified, all software contained herein is + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *****************************************************************************/ + +public class syslogData extends Thread{ + + + static HashMap<String, String> syslogConfig = new HashMap<>(); + static String[] interfaceDevice =null; + + static String syslogInterval=""; + static String syslogFile =""; + static String tempCommand = ""; + static int gmEventId = 1; + static String eventId1 = "syslog"; + static String eventId = "00000000"; + static String eventId2=null; + + private static int linesReadFromFile =0; + + public void run() { + try { + readSyslogConfig(); + + } catch (IOException | ParseException e) {} + + while(true) { + String tagToCompare = syslogConfig.get("syslogTag").toString(); + + syslogFileRead(tagToCompare ); + + try { Thread.sleep(500);}catch(Exception e) {} + + } + } + + + public void sendSysLogEvent(String sysTag,String syslogMsg) { + Long start_epoch_microsec = 0L; + Long last_epoch_microsec = 0L; + String hostName = hostName(); + + eventId2 = eventId1+ eventId+(gmEventId++); + EvelSyslog eveSyslog = new EvelSyslog(syslogConfig.get("eventName"), + eventId2, EvelFault.EVEL_SOURCE_TYPES.EVEL_SOURCE_VIRTUAL_MACHINE, + syslogMsg, sysTag); + + if( syslogConfig.get("eventType")!=null) { + start_epoch_microsec = last_epoch_microsec; + last_epoch_microsec = System.nanoTime()/1000; + + eveSyslog.evel_last_epoch_set(start_epoch_microsec); + eveSyslog.evel_start_epoch_set(last_epoch_microsec); + + eveSyslog.evel_header_type_set(syslogConfig.get("eventType").toString()); + eveSyslog.evel_nfcnamingcode_set(syslogConfig.get("nfcNamingCode").toString()); + eveSyslog.evel_nfnamingcode_set(syslogConfig.get("nfNamingCode").toString()); + if(syslogConfig.get("reportingEntityName") == null) { + eveSyslog.evel_reporting_entity_name_set(hostName); + }else { + eveSyslog.evel_reporting_entity_name_set(syslogConfig.get("reportingEntityName").toString()); + } + eveSyslog.evel_reporting_entity_id_set(syslogConfig.get("reportingEntityId").toString()); +// eveSyslog.evel_nfVendorName_set(syslogConfig.get("nfVendorName").toString()); + eveSyslog.evel_header_set_sourceid(true,syslogConfig.get("sourceId").toString()); + if(syslogConfig.get("sourceName") == null) { + eveSyslog.evel_header_set_source_name(hostName); + }else { + eveSyslog.evel_header_set_source_name(syslogConfig.get("sourceName").toString()); + } +// eveSyslog.evel_timeZoneOffset_set(syslogConfig.get("timeZoneOffset").toString()); + } + + eveSyslog.evel_syslog_facility_set(EVEL_SYSLOG_FACILITIES.EVEL_SYSLOG_FACILITY_LOCAL0); + eveSyslog.evel_syslog_proc_set(syslogConfig.get("syslogProc").toString()); + + + + AgentMain.evel_post_event(eveSyslog); + + } + + public String syslogFileRead(String tagToCompare){ + String syslines =""; + int currentIndex = 0; + boolean compare = false; + + try { + + BufferedReader reader = new BufferedReader(new FileReader("/var/log/syslog")); + String line = reader.readLine(); + while (line != null) { + if( currentIndex == linesReadFromFile ) { + compare=true; + } + if( compare ) { + if( line.contains(tagToCompare) ) + sendSysLogEvent( tagToCompare, line); + } + currentIndex ++; + + line = reader.readLine(); + } + + if( compare ) + linesReadFromFile=currentIndex; + + + } catch (Exception ex) { + ex.printStackTrace(); + } + + return null; + } + + private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); + private static String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for ( int j = 0; j < bytes.length; j++ ) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = hexArray[v >>> 4]; + hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + } + return new String(hexChars); + } + + public static String hostName() { + String hostname = "Unknown"; + String uuid = "Unknown"; + try + { + InetAddress addr; + addr = InetAddress.getLocalHost(); + hostname = addr.getHostName(); + } + catch (UnknownHostException ex) + { + + } + try{ + Enumeration<NetworkInterface> networks = + NetworkInterface.getNetworkInterfaces(); + while(networks.hasMoreElements()) { + NetworkInterface network = networks.nextElement(); + byte[] mac = network.getHardwareAddress(); + + if(hostname.equalsIgnoreCase("unknown")) + { + Enumeration inetAddrs = network.getInetAddresses(); + while(inetAddrs.hasMoreElements()){ + InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); + if (!inetAddr.isLoopbackAddress()) { + hostname = inetAddr.getHostAddress(); + break; + } + } + } + if (mac != null) { + uuid = bytesToHex(mac); + } + } + } catch (SocketException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return hostname; + } + + + public static HashMap<String, String> readSyslogConfig() throws IOException, ParseException { + + JSONParser jsonParser = new JSONParser(); + try { + + FileReader reader = new FileReader("./src/main/java/evel_javalibrary/att/com/loadbalance/syslog_config.json"); + JSONObject obj = (JSONObject) jsonParser.parse(reader); + Map.Entry directPair = null; + String directObject =""; + String[] directres; + Map directParameters = ((Map)obj.get("tmp_directParameters")); + Iterator<Map.Entry> itr1 = directParameters.entrySet().iterator(); + while (itr1.hasNext()) { + directPair = itr1.next(); + directObject=String.valueOf(directPair); + directres = directObject.split("="); + syslogConfig.put(directres[0], directres[1]); + + } + //tmp_indirectParameters + Map.Entry indirectPair = null; + String indirectObject =""; + String[] indirectres; + Map indirectParameters = ((Map)obj.get("tmp_indirectParameters")); + Iterator<Map.Entry> itr2 = indirectParameters.entrySet().iterator(); + while (itr2.hasNext()) { + indirectPair = itr2.next(); + indirectObject=String.valueOf(indirectPair); + indirectres = indirectObject.split("="); + syslogConfig.put(indirectres[0], indirectres[1]); + } + syslogFile = syslogConfig.get("tmp_syslogFile").toString(); + } catch (ClassCastException ex) { + ex.printStackTrace(); + } + return syslogConfig; + } + + + public static void main(String[] args) { + // TODO Auto-generated method stub + + try { + AgentMain.evel_initialize("http://127.0.0.1",30000, + null,null, + "will", + "pill", + null, null, null, + "http://127.0.0.1",30001, "will", + "pill", + Level.TRACE); + }catch(Exception e) { + e.printStackTrace(); + return; + } + syslogData syslogDataThread = new syslogData(); + syslogDataThread.start(); + } + + + + +} diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/syslog_config.json b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/syslog_config.json new file mode 100644 index 0000000..6b598b1 --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/loadbalance/syslog_config.json @@ -0,0 +1,20 @@ +{ + "tmp_directParameters": { + "eventName": "syslog_vLoadbalance-AT&T_connectionReset", + "eventType": "applicationVnf", + "nfcNamingCode": "AFX", + "nfNamingCode": "AFX", + "nfVendorName": "AT&T", + "reportingEntityId": "cc305d54-75b4-431b-adb2-eb6b9e541234", + "reportingEntityName": "ibcx0001vm002oam001", + "sourceId": "de305d54-75b4-431b-adb2-eb6b9e546014", + "sourceName": "scfx0001vm002cap001", + "timeZoneOffset": "UTC-05:30", + "eventSourceType": "virtualMachine", + "syslogProc": "vSyslog", + "syslogTag": "INSECURE MODE" + }, + "tmp_indirectParameters": { + "tmp_syslogFile": "/var/log/syslog" + } +}
\ No newline at end of file diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/maindir/Main.java b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/maindir/Main.java new file mode 100644 index 0000000..4c758a6 --- /dev/null +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/main/java/evel_javalibrary/att/com/maindir/Main.java @@ -0,0 +1,271 @@ + +package evel_javalibrary.att.com.maindir; + +/**************************************************************************//** + * @file + * Sample Test Agent for EVEL library + * + * This file implements the Sample Agent which is intended to provide a + * simple wrapper around the complexity of AT&T's Vendor Event Listener API so + * that VNFs can use it without worrying about details of the API transport. + * It also shows how events can be formatted with data for POST + * + * License + * ------- + * Unless otherwise specified, all software contained herein is + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *****************************************************************************/ + + +import org.apache.log4j.Logger; + +import evel_javalibrary.att.com.*; +import evel_javalibrary.att.com.AgentMain.EVEL_ERR_CODES; +import evel_javalibrary.att.com.EvelFault.EVEL_SEVERITIES; +import evel_javalibrary.att.com.EvelFault.EVEL_SOURCE_TYPES; +import evel_javalibrary.att.com.EvelFault.EVEL_VF_STATUSES; +import evel_javalibrary.att.com.EvelHeader.PRIORITIES; +import evel_javalibrary.att.com.EvelMobileFlow.MOBILE_GTP_PER_FLOW_METRICS; +import evel_javalibrary.att.com.EvelScalingMeasurement.MEASUREMENT_CPU_USE; +import evel_javalibrary.att.com.EvelScalingMeasurement.MEASUREMENT_VNIC_PERFORMANCE; +import evel_javalibrary.att.com.EvelStateChange.EVEL_ENTITY_STATE; +import evel_javalibrary.att.com.EvelThresholdCross.EVEL_ALERT_TYPE; +import evel_javalibrary.att.com.EvelThresholdCross.EVEL_EVENT_ACTION; + +import org.apache.log4j.Level; + +import java.io.*; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.util.Date; + +public class Main +{ + + public static void main(String[] args) + { + + try{ + + AgentMain.evel_initialize("http://127.0.0.1",30000, + null,null, + "will", + "pill", + null, null, null, + "http://127.0.0.1",30001, "will", + "pill", + Level.TRACE); + } catch( Exception e ) + { + e.printStackTrace(); + } + + for(int i= 0; i < 30; i++) + { + EvelHeader header = EvelHeader.evel_new_heartbeat("Hearbeat_vAFX","vmname_ip"); + header.evel_nfnamingcode_set("vVNF"); + header.evel_nfcnamingcode_set("vVNF"); + AgentMain.evel_post_event(header); + try { + Thread.sleep(1000); + } catch( Exception e ) + { + e.printStackTrace(); + } + + EvelFault flt = new EvelFault("Fault_vVNF", "vmname_ip", + "NIC error", "Hardware failed", + EvelHeader.PRIORITIES.EVEL_PRIORITY_HIGH, + EVEL_SEVERITIES.EVEL_SEVERITY_MAJOR, + EVEL_SOURCE_TYPES.EVEL_SOURCE_CARD, + EVEL_VF_STATUSES.EVEL_VF_STATUS_ACTIVE); + flt.evel_fault_addl_info_add("nichw", "fail"); + flt.evel_fault_addl_info_add("nicsw", "fail"); + AgentMain.evel_post_event(flt); + + EvelBatch be = new EvelBatch(); + EvelFault flt2 = new EvelFault("Fault_vVNF", "vmname_ip", + "NIC error", "Hardware failed", + EvelHeader.PRIORITIES.EVEL_PRIORITY_HIGH, + EVEL_SEVERITIES.EVEL_SEVERITY_MAJOR, + EVEL_SOURCE_TYPES.EVEL_SOURCE_CARD, + EVEL_VF_STATUSES.EVEL_VF_STATUS_ACTIVE); + flt2.evel_fault_addl_info_add("nichw", "fail"); + flt2.evel_fault_addl_info_add("nicsw", "fail"); + be.addEvent(flt2); + + EvelFault flt3 = new EvelFault("Fault_vVNF", "vmname_ip2", + "NIC error", "Hardware failed", + EvelHeader.PRIORITIES.EVEL_PRIORITY_NORMAL, + EVEL_SEVERITIES.EVEL_SEVERITY_MAJOR, + EVEL_SOURCE_TYPES.EVEL_SOURCE_CARD, + EVEL_VF_STATUSES.EVEL_VF_STATUS_ACTIVE); + flt3.evel_fault_type_set("Interface fault"); + flt3.evel_fault_category_set("Failed category"); + flt3.evel_fault_interface_set("An Interface Card"); + flt3.evel_fault_addl_info_add("nichw", "fail"); + flt3.evel_fault_addl_info_add("nicsw", "fail"); + be.addEvent(flt3); + + + EvelStateChange stc = new EvelStateChange("StateChange_vVNF", "vmname_ip", + EvelStateChange.EVEL_ENTITY_STATE.EVEL_ENTITY_STATE_IN_SERVICE, + EvelStateChange.EVEL_ENTITY_STATE.EVEL_ENTITY_STATE_OUT_OF_SERVICE,"bgp"); + stc.evel_statechange_addl_info_add("bgpa", "fail"); + stc.evel_statechange_addl_info_add("bgpb", "fail"); + //AgentMain.evel_post_event(stc); + + be.addEvent(stc); + AgentMain.evel_post_event(be); + + EvelScalingMeasurement sm = new EvelScalingMeasurement(10.0,"Measurements_vVNF", "vmname_ip"); + sm.evel_measurement_myerrors_set(10,20,30,40); + MEASUREMENT_CPU_USE my1 = sm.evel_measurement_new_cpu_use_add("cpu1", 100.0); + my1.idle.SetValue(20.0); + my1.sys.SetValue(21.0); + MEASUREMENT_CPU_USE my2 = sm.evel_measurement_new_cpu_use_add("cpu2", 10.0); + my2.steal.SetValue(34.0); + my2.user.SetValue(32.0); + sm.evel_measurement_custom_measurement_add("group1","name1","val1"); + sm.evel_measurement_custom_measurement_add("group1","name2","val2"); + sm.evel_measurement_custom_measurement_add("group2","name1","val1"); + sm.evel_measurement_custom_measurement_add("group2","name2","val2"); + + + MEASUREMENT_VNIC_PERFORMANCE vnic_p = sm.evel_measurement_new_vnic_performance("vnic1","true"); + vnic_p.recvd_bcast_packets_acc.SetValue(2400000.0); + vnic_p.recvd_mcast_packets_delta.SetValue(5677888.0); + vnic_p.recvd_mcast_packets_acc.SetValue(5677888.0); + vnic_p.tx_ucast_packets_acc.SetValue(547856576.0); + vnic_p.tx_ucast_packets_delta.SetValue(540000.0); + sm.evel_meas_vnic_performance_add(vnic_p); + + AgentMain.evel_post_event(sm); + + EvelSyslog sysl = new EvelSyslog("Syslog_vVNF", "vmname_ip", + EvelFault.EVEL_SOURCE_TYPES.EVEL_SOURCE_ROUTER, + "Router failed","JUNIPER"); + sysl.evel_syslog_proc_id_set(456); + sysl.evel_syslog_proc_set("routed"); + AgentMain.evel_post_event(sysl); + + EvelHeartbeatField hfld = new EvelHeartbeatField(123,"HeartbeatField_vVNF", "vmname_ip"); + hfld.evel_hrtbt_interval_set(23); + AgentMain.evel_post_event(hfld); + + + EvelSipSignaling sip = new EvelSipSignaling("SipSignaling_vVNF", "vmname_ip","aricent","corlator","127.0.0.1","5647","10.1.1.124","5678"); + AgentMain.evel_post_event(sip); + + EvelVoiceQuality vq = new EvelVoiceQuality("VoiceQuality_vVNF", "vmname_ip", + "calleeSideCodc", + "callerSideCodc", "corlator", + "midCllRtcp", "juniper"); + vq.evel_voice_quality_end_metrics_set("adjname", "Caller", 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 15.1, 160.12, 170, 180, 190); + AgentMain.evel_post_event(vq); + + EvelOther ev = new EvelOther("MyCustomEvent_vVNF", "vmname_ip"); + ev.evel_other_field_add("a1", "b1"); + ev.evel_other_field_add("a1", "b2"); + + ev.evel_other_field_add_namedarray("a1", "b1", "c1"); + ev.evel_other_field_add_namedarray("a1", "b2", "c2"); + ev.evel_other_field_add_namedarray("a2", "b1", "c1"); + ev.evel_other_field_add_namedarray("a2", "b1", "c1"); + AgentMain.evel_post_event(ev); + + String dateStart = "01/14/2012 09:29:58"; + String dateStop = "01/15/2012 10:31:48"; + + //HH converts hour in 24 hours format (0-23), day calculation + SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); + + Date d1 = null; + Date d2 = null; + + try { + d1 = format.parse(dateStart); + d2 = format.parse(dateStop); + }catch (Exception e) { + e.printStackTrace(); + } + + + EvelThresholdCross tca = new EvelThresholdCross("ThresholdCross_vVNF", "vmname_ip", + "CRIT", + "mcast Limit reached", + "mcastRxPackets", + "1250000000", + EvelThresholdCross.EVEL_EVENT_ACTION.EVEL_EVENT_ACTION_SET, + "Mcast Rx breached", + EvelThresholdCross.EVEL_ALERT_TYPE.EVEL_ELEMENT_ANOMALY, + d1, + EvelThresholdCross.EVEL_SEVERITIES.EVEL_SEVERITY_CRITICAL, + d2); + tca.evel_threshold_cross_interfacename_set("ns345"); + tca.evel_thresholdcross_addl_info_add("n1", "v1"); + tca.evel_thresholdcross_addl_info_add("n2", "v2"); + tca.evel_thresholdcross_alertid_add("alert1"); + tca.evel_thresholdcross_alertid_add("alert2"); + + AgentMain.evel_post_event(tca); + + + EvelMobileFlow mf = new EvelMobileFlow("MobileFlow_vVNF", "vmname_ip", + "In", + null, + "GTP", + "v2.3", + "1.2.3.4", + 345556, + "5.6.7.8", + 334344); + MOBILE_GTP_PER_FLOW_METRICS mygtp = mf.new MOBILE_GTP_PER_FLOW_METRICS( + 1.01, + 2.02, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + d1, + "ACTIVE", + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28); + mf.gtp_per_flow_metrics = mygtp; + AgentMain.evel_post_event(mf); + + + } + + } +} + diff --git a/veslibrary/ves_javalibrary/evel_javalib2/src/test/java/TestJunit.java b/veslibrary/ves_javalibrary/evel_javalib2/src/test/java/TestJunit.java index 24ce074..d001731 100644 --- a/veslibrary/ves_javalibrary/evel_javalib2/src/test/java/TestJunit.java +++ b/veslibrary/ves_javalibrary/evel_javalib2/src/test/java/TestJunit.java @@ -78,7 +78,8 @@ public class TestJunit { //evel init try { - mymainmock.evel_initialize( "http://127.0.0.1", 30000, "/vendor_event_listener", "/example_vnf", null, null,null, "pill", "will", Level.DEBUG); + mymainmock.evel_initialize( "http://127.0.0.1", 30000, "/vendor_event_listener", "/example_vnf", null, null,null, "pill", "will", "http://127.0.0.1",30001, "will", + "pill", Level.DEBUG); } catch ( Exception e ) { e.printStackTrace(); |