use of com.vmware.vim25.mo.ManagedEntity in project opennms by OpenNMS.
the class VmwareConfigBuilder method lookupMetrics.
private void lookupMetrics(String collectionName, String managedObjectId) throws Exception {
ManagedObjectReference managedObjectReference = new ManagedObjectReference();
managedObjectReference.setType("ManagedEntity");
managedObjectReference.setVal(managedObjectId);
ManagedEntity managedEntity = MorUtil.createExactManagedEntity(serviceInstance.getServerConnection(), managedObjectReference);
int refreshRate = performanceManager.queryPerfProviderSummary(managedEntity).getRefreshRate();
PerfQuerySpec perfQuerySpec = new PerfQuerySpec();
perfQuerySpec.setEntity(managedEntity.getMOR());
perfQuerySpec.setMaxSample(Integer.valueOf(1));
perfQuerySpec.setIntervalId(refreshRate);
PerfEntityMetricBase[] perfEntityMetricBases = performanceManager.queryPerf(new PerfQuerySpec[] { perfQuerySpec });
HashMap<String, TreeSet<VMwareConfigMetric>> groupMap = new HashMap<String, TreeSet<VMwareConfigMetric>>();
HashMap<String, Boolean> multiInstance = new HashMap<String, Boolean>();
if (perfEntityMetricBases != null) {
for (int i = 0; i < perfEntityMetricBases.length; i++) {
PerfMetricSeries[] perfMetricSeries = ((PerfEntityMetric) perfEntityMetricBases[i]).getValue();
for (int j = 0; perfMetricSeries != null && j < perfMetricSeries.length; j++) {
if (perfMetricSeries[j] instanceof PerfMetricIntSeries) {
long[] longs = ((PerfMetricIntSeries) perfMetricSeries[j]).getValue();
if (longs.length == 1) {
PerfCounterInfo perfCounterInfo = perfCounterInfoMap.get(perfMetricSeries[j].getId().getCounterId());
String instanceName = perfMetricSeries[j].getId().getInstance();
String humanReadableName = getHumanReadableName(perfCounterInfo);
String aliasName = getAliasName(perfCounterInfo);
String groupName = perfCounterInfo.getGroupInfo().getKey();
String normalizedGroupName = normalizeGroupName(groupName);
Boolean b = multiInstance.get(getHumanReadableName(perfCounterInfo));
if (b == null) {
b = Boolean.valueOf(instanceName != null && !"".equals(instanceName));
} else {
b = Boolean.valueOf(b.booleanValue() || (instanceName != null && !"".equals(instanceName)));
}
if (!b) {
groupName = "Node";
normalizedGroupName = "Node";
}
if (!groupMap.containsKey(normalizedGroupName)) {
groupMap.put(normalizedGroupName, new TreeSet<VMwareConfigMetric>());
}
TreeSet<VMwareConfigMetric> counterSet = groupMap.get(normalizedGroupName);
multiInstance.put(getHumanReadableName(perfCounterInfo), b);
counterSet.add(new VMwareConfigMetric(perfCounterInfo, humanReadableName, aliasName, b, normalizedGroupName));
}
}
}
}
}
collections.put(collectionName, groupMap);
}
use of com.vmware.vim25.mo.ManagedEntity in project CloudStack-archive by CloudStack-extras.
the class VmwareContext method getHostMorByPath.
public ManagedObjectReference getHostMorByPath(String inventoryPath) throws Exception {
assert (inventoryPath != null);
String[] tokens;
if (inventoryPath.startsWith("/"))
tokens = inventoryPath.substring(1).split("/");
else
tokens = inventoryPath.split("/");
ManagedObjectReference mor = getRootFolder();
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
ObjectContent[] ocs;
if (mor.getType().equalsIgnoreCase("Datacenter")) {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("ManagedEntity");
pSpec.setPathSet(new String[] { "name" });
TraversalSpec dcHostFolderTraversal = new TraversalSpec();
dcHostFolderTraversal.setType("Datacenter");
dcHostFolderTraversal.setPath("hostFolder");
dcHostFolderTraversal.setName("dcHostFolderTraversal");
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(mor);
oSpec.setSkip(Boolean.TRUE);
oSpec.setSelectSet(new SelectionSpec[] { dcHostFolderTraversal });
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setPropSet(new PropertySpec[] { pSpec });
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
ocs = getService().retrieveProperties(getServiceContent().getPropertyCollector(), new PropertyFilterSpec[] { pfSpec });
} else if (mor.getType().equalsIgnoreCase("Folder")) {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("ManagedEntity");
pSpec.setPathSet(new String[] { "name" });
TraversalSpec folderChildrenTraversal = new TraversalSpec();
folderChildrenTraversal.setType("Folder");
folderChildrenTraversal.setPath("childEntity");
folderChildrenTraversal.setName("folderChildrenTraversal");
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(mor);
oSpec.setSkip(Boolean.TRUE);
oSpec.setSelectSet(new SelectionSpec[] { folderChildrenTraversal });
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setPropSet(new PropertySpec[] { pSpec });
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
ocs = getService().retrieveProperties(getServiceContent().getPropertyCollector(), new PropertyFilterSpec[] { pfSpec });
} else if (mor.getType().equalsIgnoreCase("ClusterComputeResource")) {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("ManagedEntity");
pSpec.setPathSet(new String[] { "name" });
TraversalSpec clusterHostTraversal = new TraversalSpec();
clusterHostTraversal.setType("ClusterComputeResource");
clusterHostTraversal.setPath("host");
clusterHostTraversal.setName("folderChildrenTraversal");
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(mor);
oSpec.setSkip(Boolean.TRUE);
oSpec.setSelectSet(new SelectionSpec[] { clusterHostTraversal });
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setPropSet(new PropertySpec[] { pSpec });
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
ocs = getService().retrieveProperties(getServiceContent().getPropertyCollector(), new PropertyFilterSpec[] { pfSpec });
} else {
s_logger.error("Invalid inventory path, path element can only be datacenter and folder");
return null;
}
if (ocs != null && ocs.length > 0) {
boolean found = false;
for (ObjectContent oc : ocs) {
String name = oc.getPropSet()[0].getVal().toString();
if (name.equalsIgnoreCase(token) || name.equalsIgnoreCase("host")) {
mor = oc.getObj();
found = true;
if (name.equalsIgnoreCase("host"))
i--;
break;
}
}
if (!found) {
s_logger.error("Path element points to an un-existing inventory entity");
return null;
}
} else {
s_logger.error("Path element points to an un-existing inventory entity");
return null;
}
}
return mor;
}
use of com.vmware.vim25.mo.ManagedEntity in project CloudStack-archive by CloudStack-extras.
the class DatacenterMO method getOwnerDatacenter.
public static Pair<DatacenterMO, String> getOwnerDatacenter(VmwareContext context, ManagedObjectReference morEntity) throws Exception {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Datacenter");
pSpec.setPathSet(new String[] { "name" });
TraversalSpec entityParentTraversal = new TraversalSpec();
entityParentTraversal.setType("ManagedEntity");
entityParentTraversal.setPath("parent");
entityParentTraversal.setName("entityParentTraversal");
entityParentTraversal.setSelectSet(new SelectionSpec[] { new SelectionSpec(null, null, "entityParentTraversal") });
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(morEntity);
oSpec.setSkip(Boolean.TRUE);
oSpec.setSelectSet(new SelectionSpec[] { entityParentTraversal });
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setPropSet(new PropertySpec[] { pSpec });
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
ObjectContent[] ocs = context.getService().retrieveProperties(context.getServiceContent().getPropertyCollector(), new PropertyFilterSpec[] { pfSpec });
assert (ocs != null);
assert (ocs[0].getObj() != null);
assert (ocs[0].getPropSet(0) != null);
assert (ocs[0].getPropSet(0).getVal() != null);
String dcName = ocs[0].getPropSet(0).getVal().toString();
return new Pair<DatacenterMO, String>(new DatacenterMO(context, ocs[0].getObj()), dcName);
}
use of com.vmware.vim25.mo.ManagedEntity in project opennms by OpenNMS.
the class VmwareImporter method createRequisitionNode.
/**
* Creates a requisition node for the given managed entity and type.
*
* @param ipAddresses the set of Ip addresses
* @param managedEntity the managed entity
* @return the generated requisition node
*/
private RequisitionNode createRequisitionNode(Set<String> ipAddresses, ManagedEntity managedEntity, int apiVersion, VmwareViJavaAccess vmwareViJavaAccess) {
RequisitionNode requisitionNode = new RequisitionNode();
// Setting the node label
requisitionNode.setNodeLabel(managedEntity.getName());
// Foreign Id consisting of managed entity Id
requisitionNode.setForeignId(managedEntity.getMOR().getVal());
if (managedEntity instanceof VirtualMachine) {
boolean firstInterface = true;
// add all given interfaces
for (String ipAddress : ipAddresses) {
try {
if ((request.isPersistIPv4() && InetAddressUtils.isIPv4Address(ipAddress)) || (request.isPersistIPv6() && InetAddressUtils.isIPv6Address(ipAddress))) {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
if (!inetAddress.isLoopbackAddress()) {
RequisitionInterface requisitionInterface = new RequisitionInterface();
requisitionInterface.setIpAddr(ipAddress);
// the first one will be primary
if (firstInterface) {
requisitionInterface.setSnmpPrimary(PrimaryType.PRIMARY);
for (String service : request.getVirtualMachineServices()) {
requisitionInterface.insertMonitoredService(new RequisitionMonitoredService(service.trim()));
}
firstInterface = false;
} else {
requisitionInterface.setSnmpPrimary(PrimaryType.SECONDARY);
}
requisitionInterface.setManaged(Boolean.TRUE);
requisitionInterface.setStatus(Integer.valueOf(1));
requisitionNode.putInterface(requisitionInterface);
}
}
} catch (UnknownHostException unknownHostException) {
logger.warn("Invalid IP address '{}'", unknownHostException.getMessage());
}
}
} else {
if (managedEntity instanceof HostSystem) {
boolean reachableInterfaceFound = false, firstInterface = true;
List<RequisitionInterface> requisitionInterfaceList = new ArrayList<RequisitionInterface>();
RequisitionInterface primaryInterfaceCandidate = null;
// add all given interfaces
for (String ipAddress : ipAddresses) {
try {
if ((request.isPersistIPv4() && InetAddressUtils.isIPv4Address(ipAddress)) || (request.isPersistIPv6() && InetAddressUtils.isIPv6Address(ipAddress))) {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
if (!inetAddress.isLoopbackAddress()) {
RequisitionInterface requisitionInterface = new RequisitionInterface();
requisitionInterface.setIpAddr(ipAddress);
if (firstInterface) {
primaryInterfaceCandidate = requisitionInterface;
firstInterface = false;
}
if (!reachableInterfaceFound && reachableCimService(vmwareViJavaAccess, (HostSystem) managedEntity, ipAddress)) {
primaryInterfaceCandidate = requisitionInterface;
reachableInterfaceFound = true;
}
requisitionInterface.setManaged(Boolean.TRUE);
requisitionInterface.setStatus(Integer.valueOf(1));
requisitionInterface.setSnmpPrimary(PrimaryType.SECONDARY);
requisitionInterfaceList.add(requisitionInterface);
}
}
} catch (UnknownHostException unknownHostException) {
logger.warn("Invalid IP address '{}'", unknownHostException.getMessage());
}
}
if (primaryInterfaceCandidate != null) {
if (reachableInterfaceFound) {
logger.warn("Found reachable primary interface '{}'", primaryInterfaceCandidate.getIpAddr());
} else {
logger.warn("Only non-reachable interfaces found, using first one for primary interface '{}'", primaryInterfaceCandidate.getIpAddr());
}
primaryInterfaceCandidate.setSnmpPrimary(PrimaryType.PRIMARY);
for (String service : request.getHostSystemServices()) {
if (reachableInterfaceFound || !"VMwareCim-HostSystem".equals(service)) {
primaryInterfaceCandidate.insertMonitoredService(new RequisitionMonitoredService(service.trim()));
}
}
} else {
logger.warn("No primary interface found");
}
for (RequisitionInterface requisitionInterface : requisitionInterfaceList) {
requisitionNode.putInterface(requisitionInterface);
}
} else {
logger.error("Undefined type of managedEntity '{}'", managedEntity.getMOR().getType());
return null;
}
}
/*
* For now we use displaycategory, notifycategory and pollercategory for storing
* the vcenter Ip address, the username and the password
*/
String powerState = "unknown";
StringBuffer vmwareTopologyInfo = new StringBuffer();
// putting parents to topology information
ManagedEntity parentEntity = managedEntity.getParent();
do {
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
if (parentEntity != null && parentEntity.getMOR() != null) {
vmwareTopologyInfo.append(parentEntity.getMOR().getVal() + "/" + URLEncoder.encode(parentEntity.getName(), StandardCharsets.UTF_8.name()));
} else {
logger.warn("Can't add topologyInformation because either the parentEntity or the MOR is null for " + managedEntity.getName());
}
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
parentEntity = parentEntity == null ? null : parentEntity.getParent();
} while (parentEntity != null);
if (managedEntity instanceof HostSystem) {
HostSystem hostSystem = (HostSystem) managedEntity;
HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime();
if (hostRuntimeInfo == null) {
logger.debug("hostRuntimeInfo=null");
} else {
HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState();
if (hostSystemPowerState == null) {
logger.debug("hostSystemPowerState=null");
} else {
powerState = hostSystemPowerState.toString();
}
}
try {
if (request.isTopologyDatastores()) {
for (Datastore datastore : hostSystem.getDatastores()) {
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
vmwareTopologyInfo.append(datastore.getMOR().getVal() + "/" + URLEncoder.encode(datastore.getSummary().getName(), StandardCharsets.UTF_8.name()));
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
}
}
} catch (RemoteException e) {
logger.warn("Cannot retrieve datastores for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage());
}
try {
if (request.isTopologyNetworks()) {
for (Network network : hostSystem.getNetworks()) {
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
if (network instanceof DistributedVirtualPortgroup ? request.isTopologyPortGroups() : true) {
vmwareTopologyInfo.append(network.getMOR().getVal() + "/" + URLEncoder.encode(network.getSummary().getName(), StandardCharsets.UTF_8.name()));
}
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
}
}
} catch (RemoteException e) {
logger.warn("Cannot retrieve networks for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage());
}
} else {
if (managedEntity instanceof VirtualMachine) {
VirtualMachine virtualMachine = (VirtualMachine) managedEntity;
VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime();
if (virtualMachineRuntimeInfo == null) {
logger.debug("virtualMachineRuntimeInfo=null");
} else {
VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState();
if (virtualMachinePowerState == null) {
logger.debug("virtualMachinePowerState=null");
} else {
powerState = virtualMachinePowerState.toString();
}
}
try {
if (request.isTopologyDatastores()) {
for (Datastore datastore : virtualMachine.getDatastores()) {
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
vmwareTopologyInfo.append(datastore.getMOR().getVal() + "/" + URLEncoder.encode(datastore.getSummary().getName(), StandardCharsets.UTF_8.name()));
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
}
}
} catch (RemoteException e) {
logger.warn("Cannot retrieve datastores for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage());
}
try {
if (request.isTopologyNetworks()) {
for (Network network : virtualMachine.getNetworks()) {
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
if (network instanceof DistributedVirtualPortgroup ? request.isTopologyPortGroups() : true) {
vmwareTopologyInfo.append(network.getMOR().getVal() + "/" + URLEncoder.encode(network.getSummary().getName(), StandardCharsets.UTF_8.name()));
}
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
}
}
} catch (RemoteException e) {
logger.warn("Cannot retrieve networks for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage());
}
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
if (m_hostSystemMap.get(virtualMachine.getRuntime().getHost().getVal()) != null) {
vmwareTopologyInfo.append(virtualMachine.getRuntime().getHost().getVal() + "/" + URLEncoder.encode(m_hostSystemMap.get(virtualMachine.getRuntime().getHost().getVal()), StandardCharsets.UTF_8.name()));
} else {
logger.warn("Problem building topology information for virtual machine '{}' with power state '{}' running on host system '{}'", virtualMachine.getMOR().getVal(), powerState, virtualMachine.getRuntime().getHost().getVal());
}
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
} else {
logger.error("Undefined type of managedEntity '{}'", managedEntity.getMOR().getType());
return null;
}
}
RequisitionAsset requisitionAssetHostname = new RequisitionAsset("vmwareManagementServer", request.getHostname());
requisitionNode.putAsset(requisitionAssetHostname);
RequisitionAsset requisitionAssetType = new RequisitionAsset("vmwareManagedEntityType", (managedEntity instanceof HostSystem ? "HostSystem" : "VirtualMachine"));
requisitionNode.putAsset(requisitionAssetType);
RequisitionAsset requisitionAssetId = new RequisitionAsset("vmwareManagedObjectId", managedEntity.getMOR().getVal());
requisitionNode.putAsset(requisitionAssetId);
RequisitionAsset requisitionAssetTopologyInfo = new RequisitionAsset("vmwareTopologyInfo", vmwareTopologyInfo.toString());
requisitionNode.putAsset(requisitionAssetTopologyInfo);
RequisitionAsset requisitionAssetState = new RequisitionAsset("vmwareState", powerState);
requisitionNode.putAsset(requisitionAssetState);
requisitionNode.putCategory(new RequisitionCategory("VMware" + apiVersion));
return requisitionNode;
}
use of com.vmware.vim25.mo.ManagedEntity in project opennms by OpenNMS.
the class VmwareImporter method iterateVirtualMachines.
/**
* Iterates through the virtual machines and adds them to the requisition object.
*
* @param vmwareViJavaAccess the access/connection to use
* @throws RemoteException
*/
private void iterateVirtualMachines(VmwareViJavaAccess vmwareViJavaAccess, int apiVersion) throws RemoteException {
ManagedEntity[] virtualMachines;
// search for all virtual machines
virtualMachines = vmwareViJavaAccess.searchManagedEntities("VirtualMachine");
if (virtualMachines != null) {
// check for correct key/value-pair
for (ManagedEntity managedEntity : virtualMachines) {
VirtualMachine virtualMachine = (VirtualMachine) managedEntity;
logger.debug("Iterating host systems on VMware management server {} : {} (ID: {})", request.getHostname(), virtualMachine.getName(), virtualMachine.getMOR().getVal());
// import only when the specified attributes is set
if (checkVMPowerState(virtualMachine) && checkForAttribute(virtualMachine)) {
logger.debug("Adding Virtual Machine '{}' (ID: {})", virtualMachine.getName(), virtualMachine.getMOR().getVal());
// iterate over all interfaces
TreeSet<String> ipAddresses = vmwareViJavaAccess.getVirtualMachineIpAddresses(virtualMachine);
// create the new node...
RequisitionNode node = createRequisitionNode(ipAddresses, virtualMachine, apiVersion, vmwareViJavaAccess);
// add the operating system
if (virtualMachine.getGuest().getGuestFullName() != null) {
node.putAsset(new RequisitionAsset("operatingSystem", virtualMachine.getGuest().getGuestFullName()));
}
// add cpu
try {
node.putAsset(new RequisitionAsset("cpu", virtualMachine.getConfig().getHardware().getNumCPU() + " vCPU"));
} catch (Exception e) {
logger.debug("Can't find CPU information for {} (ID: {})", virtualMachine.getName(), virtualMachine.getMOR().getVal());
}
// add memory
try {
node.putAsset(new RequisitionAsset("ram", virtualMachine.getConfig().getHardware().getMemoryMB() + " MB"));
} catch (Exception e) {
logger.debug("Can't find Memory information for {} (ID: {})", virtualMachine.getName(), virtualMachine.getMOR().getVal());
}
// set the location
node.setLocation(request.getLocation());
// ...and add it to the requisition
if (node != null && request.isPersistVMs()) {
m_requisition.insertNode(node);
}
}
}
}
}
Aggregations