diff options
author | 2017-09-26 21:57:03 +0530 | |
---|---|---|
committer | 2017-10-16 17:12:45 +0530 | |
commit | e4a8fb1d9a9106a03cf2c30b8165966567339a11 (patch) | |
tree | 272ccfda5393e797705795ade21bda1d9aafde77 /vesagent/src/main/java/org | |
parent | 3406b48e1526dd7723f534d8d36ad183b01cbd06 (diff) |
VMWare vesagent for FCAPS
Fix python verify job fail issue
Change-Id: If4b7f82fe7175a4d018cd5c5232217e98824c0bd
Issue-ID: MULTICLOUD-8
Signed-off-by: Arun Arora <aroraarun@vmware.com>
Diffstat (limited to 'vesagent/src/main/java/org')
10 files changed, 1070 insertions, 0 deletions
diff --git a/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/JsonAlarmStorage.java b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/JsonAlarmStorage.java new file mode 100644 index 0000000..b38330e --- /dev/null +++ b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/JsonAlarmStorage.java @@ -0,0 +1,26 @@ + /* Copyright (c) 2017 VMware, Inc. + * + * 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. + */ + +package org.onap.multicloud.openstack.vmware; + +import org.json.simple.JSONObject; + +/*JsonAlarmStorage class include + * fields to stote to list + * which will be the value of Map*/ + +public class JsonAlarmStorage { + JSONObject json; + String alarm; + String vesSendStatus; +} diff --git a/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/JsonStoreMap.java b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/JsonStoreMap.java new file mode 100644 index 0000000..deecfd8 --- /dev/null +++ b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/JsonStoreMap.java @@ -0,0 +1,176 @@ + /* Copyright (c) 2017 VMware, Inc. + * + * 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. + */ + +package org.onap.multicloud.openstack.vmware; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +/*JsonStoreMap class having all methods + * related with HashMap + * Map taking UUID of VM as key + * Value is List Contain encoded json, alarm condition + * and ves send status + * If need to add any values --> add to JsonStoreMap */ + +public class JsonStoreMap { + protected static final Map<String, List<JsonAlarmStorage>> map = new HashMap<String, List<JsonAlarmStorage>>(); + private final Logger log = LoggerFactory.getLogger(JsonStoreMap.class); + private String line = "......................"; + public Map<String, List<JsonAlarmStorage>> addToMap(String key,List<JsonAlarmStorage> value){ + log.info ("adding to map"); + map.put(key, value); + return map; + } + public Map<String, List<JsonAlarmStorage>> updateMap(String key,List<JsonAlarmStorage> value){ + log.info("updating map"); + map.put(key, value); + return map; + } + public Map<String, List<JsonAlarmStorage>> updateMapBatch(String vesSendStatus){ + log.info("updating map for batch"); + Iterator i = map.keySet().iterator(); + while(i.hasNext()) + { + String key = i.next().toString(); + List<JsonAlarmStorage> value = map.get(key); + value.get(0).vesSendStatus = vesSendStatus; + } + log.info("updated total batch with vesSendStatus = 'failed'"); + return map; + } + public String retrieveAlarmConditionFromMap(String key){ + List<JsonAlarmStorage> value; + System.out.println("retriving alarm condition from map"); + if (map.containsKey(key)) { + value = map.get(key); + //System.out.println("Key : " + key +" value :"+ value); + return value.get(0).alarm; + } + return "uuid not found"; + } + + public String retrieveVesSendStatusFromMap(String key){ + List<JsonAlarmStorage> value; + log.info("retriving alarm condition from map"); + if (map.containsKey(key)) { + value = map.get(key); + //System.out.println("Key : " + key +" value :"+ value); + return value.get(0).vesSendStatus; + } + return "uuid not found"; + } + + public JSONObject retrieveJsonFromMap(String key){ + List<JsonAlarmStorage> value; + log.info("retriving json from map"); + if (map.containsKey(key)) { + value = map.get(key); + //System.out.println("Key : " + key +" value :"+ value); + return value.get(0).json; + } + return null; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public JSONObject retrieveALLFromMapBatch(){ + log.info("Encoding and retriving json for batch"); + JSONObject eventList = new JSONObject(); + JSONArray list = new JSONArray(); + Iterator i = map.keySet().iterator(); + while(i.hasNext()) + { + String key = i.next().toString(); + List<JsonAlarmStorage> value = map.get(key); + String value1=value.get(0).alarm+""+value.get(0).json.toString() ; + log.info("Key : " + key +" value :"+ value.get(0).alarm+""+value.get(0).json); + JSONObject json = value.get(0).json; + log.info(line); + log.info(json.get("event").toString()); + JSONObject obj = (JSONObject) json.get("event"); + list.add(obj); + } + log.info(line); + eventList.put("eventList", list); + log.info(eventList.toString()); + log.info(line); + return eventList; + } + + + @SuppressWarnings("rawtypes") + public void displayAllEntriesInMap(){ + log.info("retrive all from map"); + Iterator i = map.keySet().iterator(); + String mapValues; + while(i.hasNext()){ + String key = i.next().toString(); + List<JsonAlarmStorage> value = map.get(key); + mapValues = "uuid: "+key+" jsonStructure: "+value.get(0).json.toString()+" AlarmCondition: "+value.get(0).alarm+": VesSend status: "+value.get(0).vesSendStatus; + log.info(mapValues); + } + } + + public void deleteFromMap(String key){ + log.info("deleting json from map"); + map.remove(key); + log.info("values of key "+key+" deleted successfully"); + } + + @SuppressWarnings("rawtypes") +public void deleteUsingAlarmCondition(String alarm){ + Iterator it = map.entrySet().iterator(); + while (it.hasNext()) + { + Entry item = (Entry) it.next(); + System.out.println(item.getKey());; + List<JsonAlarmStorage> value = map.get(item.getKey()); + if(value.get(0).alarm == alarm) + { + it.remove(); + log.info("removed.."); + } + } + log.info("removed"); +} + + + + + public void deleteAllFromMap(){ + log.info("clearing map"); + map.clear(); + log.info("map cleared.."); + log.info(map.toString()); + } + + public int totalEntriesInMap(){ + log.info("Total entries in map", map.size()); + return map.size(); + } + + public boolean isJsonFound(String key){ + log.info("checking uuid in map"); + if(map.containsKey(key)) + { + return true; + } + return false; + } +} diff --git a/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/ReadPropertiesFile.java b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/ReadPropertiesFile.java new file mode 100644 index 0000000..9a96c2c --- /dev/null +++ b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/ReadPropertiesFile.java @@ -0,0 +1,49 @@ + /* Copyright (c) 2017 VMware, Inc. + * + * 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. + */ + +package org.onap.multicloud.openstack.vmware; + + +import java.io.File; +import java.io.FileInputStream; +import java.util.Properties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ReadPropertiesFile { + private final Logger log = LoggerFactory.getLogger(ReadPropertiesFile.class); + public boolean readProperties(VsphereEntity vsphereEntity,String filePath){ + try { + File file = new File(filePath); + FileInputStream fileInput = new FileInputStream(file); + Properties properties = new Properties(); + properties.load(fileInput); + fileInput.close(); + if( properties.getProperty("Path_VspherePython").isEmpty() || properties.getProperty("Python_Output_Json").isEmpty()){ + log.info("Provide python path and json path in Agent.properties file"); + return false; + }else{ + vsphereEntity.setPathVspherePython(properties.getProperty("Path_VspherePython")); + vsphereEntity.setPythonOutputJson(properties.getProperty("Python_Output_Json")); + return true; + } + } + catch(Exception e){ + log.info("Agent.properties file doen't have appropriate values or the file is empty Please modify Agent.properties!"); + log.error("error",e); + + } + + return false; + } +} diff --git a/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VESRestAPI.java b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VESRestAPI.java new file mode 100644 index 0000000..db8e580 --- /dev/null +++ b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VESRestAPI.java @@ -0,0 +1,188 @@ + /* Copyright (c) 2017 VMware, Inc. + * + * 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. + */ + +package org.onap.multicloud.openstack.vmware; + +import java.io.IOException; +import java.net.Socket; +import java.util.List; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.json.simple.JSONObject; +import org.json.simple.parser.ParseException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/*Contain all methods for rest api calls*/ +@SuppressWarnings("deprecation") +public class VESRestAPI{ + String eventType; + int counter_connectionRefused = 0; + private StringEntity entity; + private HttpPost post; + private Socket sock; + private DefaultHttpClient client; + private final Logger log = LoggerFactory.getLogger(VESRestAPI.class); + private String applicationJson = "application/json"; + private String anyEvent = "any"; + private String batchEvent = "batch"; + private String vesSendStatusSuccess="success"; + @SuppressWarnings({ "resource" }) + public boolean publishAnyEventToVES(VesEntity ves ,JsonStoreMap map, VesTimer timer,String uuidKey,List<JsonAlarmStorage> list, Integer duration,String vesSendStatus) throws IOException{ + try{ + eventType = anyEvent; + log.info("inside publish any event method"); + sock = new Socket(ves.getVesip(), ves.getPort()); + log.info(String.valueOf(sock.isConnected())); + if(sock.isConnected()){ + log.info("list "+list.get(0).json.toString()); + client = new DefaultHttpClient(); + /* check the vesStructure whether each of the variable like ip address , portnumber , user name and password contains something or is null */ + if(vesEntitycredentialCheckSuccess(ves)){ + post = new HttpPost("http://"+ves.getVesip()+":"+ves.getPort()+"/eventListener/v5"); + log.info(ves.getPort().toString()); + }else{ + log.info("Null"); + } + entity = new StringEntity(list.get(0).json.toString()); + post.setEntity(entity); + post.setHeader("Content-type", applicationJson); + HttpResponse response = client.execute(post); + log.info(response.getStatusLine().toString()); + if(vESCollectorSendStatus(response,map,uuidKey,list,timer,vesSendStatus)){ + return true; + } + sock.close(); + client.close(); + } + }catch(Exception e){ + log.info("VES Collector connection refused exception error occured"); + log.error("error",e); + list.get(0).vesSendStatus = "failed"; + map.updateMap(uuidKey, list); + if (!timer.isTimerRunning()){ + timer.startTimer(duration); + } + else log.info("VES Collector Connection Refushed Timer is running "); +} + return false; + +} + + @SuppressWarnings("resource") + public boolean publishBatchEventToVES(VesEntity ves, JSONObject alarmJsonConstructArray,JsonStoreMap map, VesTimer timer,String uuidKey,List<JsonAlarmStorage> list, Integer duration,String vesSendStatus) throws IOException{ + try { + eventType = batchEvent; + log.info("inside publish batch event method"); + sock = new Socket(ves.getVesip(), ves.getPort()); + if(sock.isConnected()){ + log.info("Sending batch"); + client = new DefaultHttpClient(); + if(vesEntitycredentialCheckSuccess(ves)) + { + post = new HttpPost("http://"+ves.getVesip()+":"+ves.getPort()+"/eventListener/v5/eventBatch"); + }else{ + log.info("Null"); + } + entity = new StringEntity(alarmJsonConstructArray.toJSONString()); + post.setEntity(entity); + post.setHeader("Content-type", applicationJson); + post.addHeader("Accept", applicationJson); + HttpResponse response = client.execute(post); + log.info(response.getStatusLine().toString()); + if(!connectionRefused(response)){ + return true; + } + + if(vESCollectorSendStatus(response,map,uuidKey,list,timer,vesSendStatus)){ + return true; + } + } + sock.close(); + client.close(); + }catch(Exception e){ + log.info("connection refused exception error occured"); + log.error("error",e); + list.get(0).vesSendStatus = "failed"; + map.updateMap(uuidKey, list); //modifying map with vesSendStatus as failed + log.info("..."); + if (!timer.isTimerRunning()){ + log.info("timer started...."); + timer.startTimer(duration); + } + else{ + log.info("Connection refused timer is running"); + } + } + return false; + } + public boolean vesEntitycredentialCheckSuccess(VesEntity ves){ + if(ves.getPort()==null || ves.getVesip()==null || ves.getVesPassword()==null || ves.getVesUsername()==null){ + return false; + } + return true; + } + +public boolean vESCollectorSendStatus ( HttpResponse response,JsonStoreMap map,String uuidKey, List<JsonAlarmStorage> list,VesTimer timer,String vesSendStatus) throws ParseException { + + JsonAlarmStorage store = list.get(0); + log.info(String.valueOf(list.size())); + log.info(store.alarm); + String alarmStatus = store.alarm; + log.info("insiide ves collector method"); + if(response.getStatusLine().getStatusCode()>=200 && response.getStatusLine().getStatusCode()<300){ + log.info("..........."); + if(alarmStatus == "ON" && eventType==anyEvent){ + log.info("alarm on ,event type is any and connection is 200 ok"); + log.info("Test list for satus"+list.get(0).vesSendStatus); + log.info("total entrie sin map: ",map.totalEntriesInMap()); + map.displayAllEntriesInMap(); + list.get(0).vesSendStatus = vesSendStatusSuccess; + map.updateMap(uuidKey, list); + }else if(alarmStatus == "ON" && eventType==batchEvent){ + log.info("alarm on ,event type is any and connection is 200 ok"); + log.info("Test list for satus"+list.get(0).vesSendStatus); + log.info("total entrie:",map.totalEntriesInMap()); + map.displayAllEntriesInMap(); + map.updateMapBatch("success"); + }else if (alarmStatus == "OFF" && (vesSendStatus=="new" || vesSendStatus ==vesSendStatusSuccess) && eventType==anyEvent){ + log.info("alarm off and connection ok"); + map.deleteFromMap(uuidKey); + } else if(alarmStatus == "OFF" && (vesSendStatus=="new" || vesSendStatus ==vesSendStatusSuccess) && eventType==batchEvent){ + log.info("alarm off and connection ok"); + map.deleteUsingAlarmCondition(alarmStatus); + } + + if(timer.isTimerRunning()){ + timer.stopTimer(); + } + else{ + log.info("timer is not running...."); + } + return true; + } + else + { + log.info("connection error !200"); + return false; + } + } + public boolean connectionRefused(HttpResponse response){ + if(response.getStatusLine().getStatusCode()!=200){ + return true; + } + return false; + } +} diff --git a/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VesAgent.java b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VesAgent.java new file mode 100644 index 0000000..e5ad34f --- /dev/null +++ b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VesAgent.java @@ -0,0 +1,226 @@ + /* Copyright (c) 2017 VMware, Inc. + * + * 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. + */ + +package org.onap.multicloud.openstack.vmware; + +import java.io.FileReader; +import java.util.List; +import java.text.DateFormat; +import java.util.Date; +import java.util.Locale; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import java.io.IOException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.log4j.BasicConfigurator; +public class VesAgent { + private static final Logger log = LoggerFactory.getLogger(VesAgent.class); + private static final String ERROR = "error"; + private VesAgent(){ + + } + public static void main (String[] args ) throws InterruptedException { + BasicConfigurator.configure(); + + if (args.length < 1 ) + { + log.info("Invalid Number of Arugments , provide the agent properties file path! " ); + return; + } + else + { + try { + /* in the VShpere Entity we are storing the VCentre IP Address + * , user name , + * password , vmname + */ + + int count = 0; + VsphereDataEntity vsphereDataEntity = new VsphereDataEntity(); + JsonStoreMap map = new JsonStoreMap(); + List<JsonAlarmStorage> list; + JSONParser parser = new JSONParser(); + Integer duration = 120000; + log.info("inside main method"); + String alarmCondition; // for checking alarm is raised or not + String vesSendStatus = "new"; //vesSendStatus + String filePath=args[0]; + /* VSphereData contains all method to connect , + * retrieve and + * fetch data using VShpere API + */ + VsphereData vsphereData = new VsphereData(); + VsphereEntity vsphereEntity = new VsphereEntity(); + VesEntity vesEntity = new VesEntity(); + ReadPropertiesFile file = new ReadPropertiesFile(); + if(file.readProperties(vsphereEntity,filePath) && getEnv(vsphereEntity, vesEntity)) + { + VESRestAPI vesRestAPI= new VESRestAPI(); + JSONObject eventObj = new JSONObject(); + JSONObject event = new JSONObject(); + JSONObject commonEventHeader = new JSONObject(); + JSONObject faultFields = new JSONObject(); + VesTimer timer = new VesTimer(map); + int i=0; + while(true) + { + /* In this we are calling pyvmomi sdk via python to get the list of VM + * containing instanceUUID and heartbeatstatus for each VM into a JSON File */ + log.info("timer before running python"+getDateTime()); + Runtime rt = Runtime.getRuntime(); + log.info("Execute Python File: " + vsphereEntity.getPathVspherePython()); + Process p = rt.exec("python "+vsphereEntity.getPathVspherePython()+" -s "+vsphereEntity.getVsphereServerName()+" -u "+vsphereEntity.getVsphereUsername()+" -p "+vsphereEntity.getVsperePassword()); + int result=p.waitFor(); + if(result == 0){ + System.out.println("......done..json..."); + Thread.sleep(5000); + log.info("JSON File Path: " + vsphereEntity.getPythonOutputJson()); + /* Here we are opening the JSON File + * and iterating and fetching the indivudal VM details and deciding the logic of raising the alarm on/off */ + Object obj = parser.parse(new FileReader(vsphereEntity.getPythonOutputJson())); + JSONArray jsonObject = (JSONArray) obj; + log.info(jsonObject.toJSONString()); + log.info("inside while loop"); + for(int j = 0;j<=jsonObject.size()-1;j++){ + log.info("timer is running or not: "+timer.isTimerRunning()); + log.info("Is timed out happn: "+timer.isTimeout()); + JSONObject js = (JSONObject) jsonObject.get(j); + log.info(""); + log.info(js.toJSONString()); + count++; + log.info("////////////////////////////////////////////////////////////////////////////"); + log.info("map entries in total"+map.totalEntriesInMap()); + log.info("Count:"+count); + VsphereDataEntity entity = vsphereData.gettingVMInfo(js,vsphereDataEntity,vsphereEntity); + String heartBeatStatus = vsphereDataEntity.getStatus(); + log.info(heartBeatStatus); + + String uuid_key = vsphereDataEntity.getSourceId(); + if(heartBeatStatus!="green"){ + //encode json + if(map.isJsonFound(uuid_key) && map.retrieveAlarmConditionFromMap(uuid_key) == "ON"){ + log.info("alarm ON already raised"); + } + else if(!map.isJsonFound(uuid_key)){ + alarmCondition = "ON"; + vsphereData.encodeJson(entity, event, eventObj, commonEventHeader, faultFields,map); + list = vsphereData.listJsonAlarm2(event, alarmCondition,vesSendStatus); + log.info(list.get(0).json+" :"+list.get(0).alarm+" :"+list.get(0).vesSendStatus); + map.addToMap(uuid_key, list); + + if(map.totalEntriesInMap()>1) + { + JSONObject alarmJsonConstructArray = map.retrieveALLFromMapBatch(); + vesRestAPI.publishBatchEventToVES(vesEntity, alarmJsonConstructArray, map, timer, uuid_key, list, duration , vesSendStatus); + } + else + { + //map.addToMap(uuid_key, list); + //vesRestAPI.publishAnyEventToVES(vesEntity, event,null,map, timer); + vesRestAPI.publishAnyEventToVES(vesEntity,map, timer,uuid_key, list,duration,vesSendStatus); + log.info("published "); + + } + } + } + else if(heartBeatStatus == "green"){ + /* if the alarm on entry is found in Map then check for the vesSendStatus + * IF the VesSendStatus ==failed for Alarm On + * in the case remove the entries from MAP and + * donot encode the alarm off and donot send it to VESCollector */ + if((map.isJsonFound(uuid_key) && map.retrieveAlarmConditionFromMap(uuid_key) == "ON") && map.retrieveVesSendStatusFromMap(uuid_key)!="failed"){ + alarmCondition = "OFF"; + vsphereData.encodeJson(entity, event, eventObj, commonEventHeader, faultFields,map); + list = vsphereData.listJsonAlarm2(event, alarmCondition,vesSendStatus); + String json = event.toJSONString(); + log.info(json); + map.addToMap(uuid_key, list); + + if(map.totalEntriesInMap()>1){ + //sending only entry having vesSendStatus = failed + JSONObject alarmJsonConstructArray = map.retrieveALLFromMapBatch(); + vesRestAPI.publishBatchEventToVES(vesEntity, alarmJsonConstructArray, map, timer, json, list, duration,vesSendStatus); + } + else{ + vesRestAPI.publishAnyEventToVES(vesEntity,map, timer,uuid_key,list,duration,vesSendStatus); + } + } + else{ + log.info("ALarm ON not found, ves Send status is failed"); + } + } + Thread.sleep(2000); + log.info("for loop end..."); + } + log.info(String.valueOf(count)); + + }else if(result!=0){ + log.info("Something went wrong on fetching info using python script!! Check the python script and credentials"); + break; + } + i++; + if (i == Integer.MIN_VALUE) { // true at Integer.MAX_VALUE +1 + break; + } + } + }else{ + log.info("Missing values for python files - Env Variabl es "); + + } + } catch(java.io.FileNotFoundException e){ + log.info("File not found exception. Check the json file path"); + log.error(ERROR,e); + } + catch (IOException e) { + log.info("Something went wrong with python in runtime"); + log.error(ERROR,e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + log.info("Interupted exception occured. Python script execution taking more time"); + log.error(ERROR,e); + } catch (ParseException e) { + log.info("Something went wrong with json created by python! Parse exception occured"); + log.error(ERROR,e); + }catch (Exception e) { + log.info("Exception Occured!!"); + log.error(ERROR,e); + } } + } + public static String getDateTime(){ + DateFormat df = DateFormat.getDateTimeInstance (DateFormat.MEDIUM, DateFormat.MEDIUM, new Locale ("en", "EN")); + return df.format (new Date ()); + } +public static boolean getEnv(VsphereEntity vsphereEntity, VesEntity vesEntity){ + try{ + if(System.getenv("Vsphere_Ip").isEmpty() || System.getenv("Vsphere_Username").isEmpty() || System.getenv("Vsphere_Password")==null || System.getenv("VesCollector_Ip").isEmpty() || System.getenv("VesCollector_Port").isEmpty()){ + log.info("Null values"); + return false; + } + else{ + vsphereEntity.setVsphereServerName(System.getenv("Vsphere_Ip")); + vsphereEntity.setVsphereUsername(System.getenv("Vsphere_Username")); + vsphereEntity.setVsperePassword(System.getenv("Vsphere_Password")); + vesEntity.setVesip(System.getenv("VesCollector_Ip")); + vesEntity.setVesPassword(System.getenv("VesCollector_Port")); + return true; + + } + }catch(NullPointerException e){ + log.error("Missing values - env var",e); + } + return false; + } +} diff --git a/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VesEntity.java b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VesEntity.java new file mode 100644 index 0000000..1f3e863 --- /dev/null +++ b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VesEntity.java @@ -0,0 +1,48 @@ + /* Copyright (c) 2017 VMware, Inc. + * + * 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. + */ + +package org.onap.multicloud.openstack.vmware; +/*Entity class for ves ip + * port + * username + * password*/ +public class VesEntity { + private String vesip; + private Integer port; + private String vesUsername; + private String vesPassword; + public String getVesip() { + return vesip; + } + public void setVesip(String vesip) { + this.vesip = vesip; + } + public Integer getPort() { + return port; + } + public void setPort(Integer port) { + this.port = port; + } + public String getVesUsername() { + return vesUsername; + } + public void setVesUsername(String vesUsername) { + this.vesUsername = vesUsername; + } + public String getVesPassword() { + return vesPassword; + } + public void setVesPassword(String vesPassword) { + this.vesPassword = vesPassword; + } +} diff --git a/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VesTimer.java b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VesTimer.java new file mode 100644 index 0000000..acdca74 --- /dev/null +++ b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VesTimer.java @@ -0,0 +1,95 @@ + /* Copyright (c) 2017 VMware, Inc. + * + * 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. + */ + +package org.onap.multicloud.openstack.vmware; + +import java.util.Timer; +import java.util.TimerTask; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +class TimerExtend extends Timer{ + + public TimerExtend(){ + VesTimer.hasStarted = true; + } + + public boolean hasRunStarted() { + return VesTimer.hasStarted; + } +} + +class TaskTimeout extends TimerTask{ + private static JsonStoreMap map; + private final Logger log = LoggerFactory.getLogger(TaskTimeout.class); + @SuppressWarnings("static-access") + public TaskTimeout(JsonStoreMap map) { + TaskTimeout.map = map; + } + + public static void run1(){ + VesTimer.timeoutCheck = true; + map.deleteAllFromMap(); + VesTimer.hasStarted=false; + } + @SuppressWarnings("resource") + @Override + public void run() { + run1(); + log.info("In Time out before deleting the entries from Map"); + + } +} + +public class VesTimer { + TimerExtend tt = null; + TaskTimeout timeout = null; + static boolean hasStarted = false; + static boolean timeoutCheck = false; + private JsonStoreMap map; + private final Logger log = LoggerFactory.getLogger(VesTimer.class); + public VesTimer(JsonStoreMap map){ + this.map = map; + } + + public void startTimer(Integer duration){ + tt = new TimerExtend(); + timeout= new TaskTimeout(this.map); + log.info("timer started................."); + tt.schedule(timeout, duration); + } + + public void stopTimer(){ + tt.cancel(); + log.info("timer stopped"); + } + + public boolean isTimerRunning(){ + if(VesTimer.hasStarted == true){ + log.info("timer started...."); + return true; + } + else { + log.info("timer is not running"); + return false; + } +} + public String isTimeout(){ + if(VesTimer.timeoutCheck){ + log.info("expired"); + return "expired"; + } + return "not expired"; + } +} diff --git a/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VsphereData.java b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VsphereData.java new file mode 100644 index 0000000..0c56c2d --- /dev/null +++ b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VsphereData.java @@ -0,0 +1,158 @@ + /* Copyright (c) 2017 VMware, Inc. + * + * 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. + */ + +package org.onap.multicloud.openstack.vmware; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.json.simple.JSONObject; + +public class VsphereData { + private final Logger log = LoggerFactory.getLogger(VsphereData.class); + public VsphereDataEntity gettingVMInfo(JSONObject js,VsphereDataEntity vsphereDataEntity,VsphereEntity vsphereEntity){ + String vsphereVMname = (String) js.get("Name"); + vsphereEntity.setVsphereVMname(vsphereVMname); + vsphereDataEntity.setSourceName(vsphereVMname); + String status = (String) js.get("Heartbeatstatus"); + vsphereDataEntity.setStatus(status.toString()); + + String instance_uuid=(String) js.get("Instance UUID"); + vsphereDataEntity.setSourceId(instance_uuid); + + String sourceType="VirtualMachine"; + vsphereDataEntity.setSourceType(sourceType); + + log.info(vsphereDataEntity.getSourceName()); + log.info(vsphereDataEntity.getSourceId()); + + log.info(vsphereDataEntity.getStatus()); + log.info(vsphereDataEntity.getSourceType()); + + return vsphereDataEntity; + } + + + @SuppressWarnings("unchecked") + public void encodeJson(VsphereDataEntity vsphereDataEntity,JSONObject event, JSONObject eventObj,JSONObject commonEventHeader,JSONObject faultFields, JsonStoreMap map) { + log.info("encoding to json......."); + Double version = 3.0; + String domain="fault"; + + UUID uuid = UUID.randomUUID(); + + + //String eventId = "ab305d54-85b4-a31b-7db2-fb6b9e546015"; + String sourceName=vsphereDataEntity.getSourceName(); + String reportingEntityName = "Multi-Cloud"; + Integer sequence=0; + //String eventType="GuestOS"; + String eventName=""; + String priority=""; + String eventSeverity=""; + String alarmCondition=""; + String vfStatus=""; + String specificProblem=""; + long unixTime = (System.currentTimeMillis() / 1000L)*1000000 ; + Long startEpochMicrosec = null; + Long lastEpochMicrosec = null; + String eventId=""; + String sourceId =vsphereDataEntity.getSourceId().toString(); + Double faultFieldsVersion=2.0; + if (vsphereDataEntity.getStatus() !="green") { + eventName="Fault_MultiCloud_VMFailure"; + priority="High"; + eventSeverity="CRITICAL" ; //it should be in caps + alarmCondition="Guest_Os_Failure"; + vfStatus="Active"; + specificProblem="AlarmOn"; + startEpochMicrosec = unixTime; + lastEpochMicrosec = unixTime; + eventId = uuid.toString(); + } + else { + eventName="Fault_MultiCloud_VMFailureCleared"; + priority="Normal"; + eventSeverity="Normal" ; + alarmCondition="Vm_Restart"; + vfStatus="Active"; + specificProblem="AlarmOff"; + + JSONObject json = map.retrieveJsonFromMap(sourceId); + JSONObject e1 = (JSONObject) json.get("event"); + JSONObject c1 =(JSONObject) e1.get("commonEventHeader"); + String eventIdRetrieved = (String) c1.get("eventId"); + Long startEpochMicrosecRetrieved = (Long) c1.get("startEpochMicrosec"); + + startEpochMicrosec = startEpochMicrosecRetrieved; + lastEpochMicrosec = unixTime; + eventId=eventIdRetrieved; + } + /* Point to be noted for start and last epoch time - + for alarm on case both will be the same value + but for alarm off case the lastEpochMicroSec will be current System/Date/Time */ + + + //here we have to create jsonobjects + //JSONObject commonEventHeader = new JSONObject(); + commonEventHeader.put("version", version); + commonEventHeader.put("domain",domain); + commonEventHeader.put("eventName",eventName); + commonEventHeader.put("eventId",eventId); + commonEventHeader.put("sequence",sequence); + commonEventHeader.put("priority",priority); + commonEventHeader.put("reportingEntityName",reportingEntityName); + commonEventHeader.put("sourceId",sourceId); + commonEventHeader.put("sourceName",sourceName); + commonEventHeader.put("startEpochMicrosec",startEpochMicrosec); + commonEventHeader.put("lastEpochMicrosec",lastEpochMicrosec); + + //JSONObject faultFields = new JSONObject(); + faultFields.put("faultFieldsVersion",faultFieldsVersion ); + faultFields.put("eventSeverity",eventSeverity ); + faultFields.put("alarmCondition",alarmCondition ); + faultFields.put("specificProblem",specificProblem ); + faultFields.put("vfStatus",vfStatus ); + faultFields.put("alarmInterfaceA", "aaaa"); + faultFields.put("eventSourceType", "other"); + + //JSONObject eventObj = new JSONObject(); + eventObj.put("commonEventHeader", commonEventHeader); + eventObj.put("faultFields",faultFields); + + //JSONObject event = new JSONObject(); + event.put("event", eventObj); + } + + public List<String> listJsonAlarm(String Json,String alarmCondition){ + System.out.println("adding to list- json and alarm"); + List<String> list = new ArrayList<String>(); + list.add(Json); + list.add(alarmCondition); + return list; + } + + public List<JsonAlarmStorage> listJsonAlarm2(JSONObject json,String alarmCondition, String vesSendStatus){ + log.info("adding to list- json and alarm"); + JsonAlarmStorage store = new JsonAlarmStorage(); + List<JsonAlarmStorage> list = new ArrayList<JsonAlarmStorage>(); + store.json = json; + store.alarm=alarmCondition; + store.vesSendStatus = vesSendStatus; + list.add(store); + return list; + } +} diff --git a/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VsphereDataEntity.java b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VsphereDataEntity.java new file mode 100644 index 0000000..2e747ba --- /dev/null +++ b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VsphereDataEntity.java @@ -0,0 +1,45 @@ + /* Copyright (c) 2017 VMware, Inc. + * + * 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. + */ + +package org.onap.multicloud.openstack.vmware; + +public class VsphereDataEntity { + private String sourceName; + private String sourceType; + private String sourceId; + private String status; + public String getSourceName() { + return sourceName; + } + public void setSourceName(String sourceName) { + this.sourceName = sourceName; + } + public String getSourceType() { + return sourceType; + } + public void setSourceType(String sourceType) { + this.sourceType = sourceType; + } + public String getSourceId() { + return sourceId; + } + public void setSourceId(String sourceId) { + this.sourceId = sourceId; + } + public String getStatus() { + return status; + } + public void setStatus(String status) { + this.status = status; + } +} diff --git a/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VsphereEntity.java b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VsphereEntity.java new file mode 100644 index 0000000..809fd78 --- /dev/null +++ b/vesagent/src/main/java/org/onap/multicloud/openstack/vmware/VsphereEntity.java @@ -0,0 +1,59 @@ + /* Copyright (c) 2017 VMware, Inc. + * + * 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. + */ + +package org.onap.multicloud.openstack.vmware; + +public class VsphereEntity { + private String VsphereServerName; + private String VsphereUsername; + private String VsperePassword; + private String VsphereVMname; + private String PathVspherePython; + private String PythonOutputJson; + + public String getVsphereUsername() { + return VsphereUsername; + } + + public void setVsphereUsername(String vsphereUsername) { + this.VsphereUsername = vsphereUsername; + } + + public String getPythonOutputJson() { + return PythonOutputJson; + } + public void setPythonOutputJson(String pythonOutputJson) { + PythonOutputJson = pythonOutputJson; + } + public String getPathVspherePython() { + return PathVspherePython; + } + public void setPathVspherePython(String pathVspherePython) { + PathVspherePython = pathVspherePython; + } + public String getVsperePassword() { + return VsperePassword; + } + public void setVsperePassword(String vsperePassword) { + VsperePassword = vsperePassword; + } + public void setVsphereVMname(String vsphereVMname) { + VsphereVMname = vsphereVMname; + } + public String getVsphereServerName() { + return VsphereServerName; + } + public void setVsphereServerName(String vsphereServerName) { + VsphereServerName = vsphereServerName; + } +} |