663 lines
25 KiB
Java
663 lines
25 KiB
Java
package org.gcube.smartgears.connector.resourceregistry.resourcemanager;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.File;
|
|
import java.io.FileReader;
|
|
import java.io.IOException;
|
|
import java.lang.management.ManagementFactory;
|
|
import java.lang.management.OperatingSystemMXBean;
|
|
import java.net.InetAddress;
|
|
import java.net.UnknownHostException;
|
|
import java.nio.file.FileStore;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Paths;
|
|
import java.util.ArrayList;
|
|
import java.util.Calendar;
|
|
import java.util.Date;
|
|
import java.util.HashMap;
|
|
import java.util.Iterator;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Set;
|
|
import java.util.TreeSet;
|
|
import java.util.UUID;
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
|
|
import javax.management.AttributeNotFoundException;
|
|
import javax.management.InstanceNotFoundException;
|
|
import javax.management.MBeanException;
|
|
import javax.management.MBeanServer;
|
|
import javax.management.MalformedObjectNameException;
|
|
import javax.management.ObjectName;
|
|
import javax.management.ReflectionException;
|
|
|
|
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
|
|
import org.gcube.common.security.providers.SecretManagerProvider;
|
|
import org.gcube.common.security.secrets.Secret;
|
|
import org.gcube.informationsystem.model.reference.entities.Facet;
|
|
import org.gcube.informationsystem.model.reference.entities.Resource;
|
|
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
|
|
import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache;
|
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException;
|
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException;
|
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
|
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException;
|
|
import org.gcube.informationsystem.resourceregistry.api.exceptions.entities.resource.ResourceNotFoundException;
|
|
import org.gcube.informationsystem.resourceregistry.client.ResourceRegistryClient;
|
|
import org.gcube.informationsystem.resourceregistry.client.ResourceRegistryClientFactory;
|
|
import org.gcube.informationsystem.resourceregistry.publisher.ResourceRegistryPublisher;
|
|
import org.gcube.informationsystem.resourceregistry.publisher.ResourceRegistryPublisherFactory;
|
|
import org.gcube.informationsystem.serialization.ElementMapper;
|
|
import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl;
|
|
import org.gcube.resourcemanagement.model.impl.entities.facets.EventFacetImpl;
|
|
import org.gcube.resourcemanagement.model.impl.entities.facets.LocationFacetImpl;
|
|
import org.gcube.resourcemanagement.model.impl.entities.facets.MemoryFacetImpl;
|
|
import org.gcube.resourcemanagement.model.impl.entities.facets.NetworkingFacetImpl;
|
|
import org.gcube.resourcemanagement.model.impl.entities.facets.SimplePropertyFacetImpl;
|
|
import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl;
|
|
import org.gcube.resourcemanagement.model.impl.entities.facets.StateFacetImpl;
|
|
import org.gcube.resourcemanagement.model.impl.entities.resources.HostingNodeImpl;
|
|
import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasPersistentMemoryImpl;
|
|
import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasVolatileMemoryImpl;
|
|
import org.gcube.resourcemanagement.model.impl.relations.consistsof.IsIdentifiedByImpl;
|
|
import org.gcube.resourcemanagement.model.reference.entities.facets.CPUFacet;
|
|
import org.gcube.resourcemanagement.model.reference.entities.facets.EventFacet;
|
|
import org.gcube.resourcemanagement.model.reference.entities.facets.LocationFacet;
|
|
import org.gcube.resourcemanagement.model.reference.entities.facets.MemoryFacet;
|
|
import org.gcube.resourcemanagement.model.reference.entities.facets.MemoryFacet.MemoryUnit;
|
|
import org.gcube.resourcemanagement.model.reference.entities.facets.NetworkingFacet;
|
|
import org.gcube.resourcemanagement.model.reference.entities.facets.SimplePropertyFacet;
|
|
import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet;
|
|
import org.gcube.resourcemanagement.model.reference.entities.facets.StateFacet;
|
|
import org.gcube.resourcemanagement.model.reference.entities.resources.HostingNode;
|
|
import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasPersistentMemory;
|
|
import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasVolatileMemory;
|
|
import org.gcube.resourcemanagement.model.reference.relations.consistsof.IsIdentifiedBy;
|
|
import org.gcube.smartgears.configuration.PersistenceConfiguration;
|
|
import org.gcube.smartgears.configuration.SmartgearsConfiguration;
|
|
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
|
|
import org.gcube.smartgears.configuration.container.Site;
|
|
import org.gcube.smartgears.connector.resourceregistry.ContextUtility;
|
|
import org.gcube.smartgears.connector.resourceregistry.FacetBasedPublisher;
|
|
import org.gcube.smartgears.context.container.ContainerContext;
|
|
import org.gcube.smartgears.provider.ProviderFactory;
|
|
import org.gcube.smartgears.security.AuthorizationProvider;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
/**
|
|
* @author Luca Frosini (ISTI-CNR)
|
|
*/
|
|
public class HostingNodeManager {
|
|
|
|
private static Logger logger = LoggerFactory.getLogger(HostingNodeManager.class);
|
|
|
|
public static final String MEMORY_TYPE = "memoryType";
|
|
public static final String MEMORY_TYPE_RAM = "RAM";
|
|
public static final String MEMORY_TYPE_JVM = "JVM";
|
|
public static final String JVM_MAX_MEMORY = "jvmMaxMemory";
|
|
|
|
public static final String MESSAGE = "message";
|
|
|
|
private ContainerContext containerContext;
|
|
private ResourceRegistryPublisher resourceRegistryPublisher;
|
|
private HostingNode hostingNode;
|
|
|
|
public HostingNodeManager(ContainerContext containerContext) {
|
|
this.containerContext = containerContext;
|
|
this.resourceRegistryPublisher = ResourceRegistryPublisherFactory.create();
|
|
}
|
|
|
|
public HostingNode getHostingNode() {
|
|
return hostingNode;
|
|
}
|
|
|
|
public void addToCurrentContext() throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
|
Secret secret = SecretManagerProvider.instance.get();
|
|
String context = secret.getContext();
|
|
UUID contextUUID = ContextUtility.getContextUUID(context);
|
|
|
|
/* Trying to get a context which is not the current to properly invoke the addToContext without forcing the operation using addResourceToCurrentContext */
|
|
AuthorizationProvider authorizationProvider = FacetBasedPublisher.getAuthorizationProvider(containerContext);
|
|
Set<String> contexts = authorizationProvider.getContexts();
|
|
boolean anotherContextSet = false;
|
|
for (String c : contexts) {
|
|
if(c.compareTo(context)!=0) {
|
|
Secret s = authorizationProvider.getSecretForContext(c);
|
|
SecretManagerProvider.instance.set(s);
|
|
anotherContextSet = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
UUID uuid = UUID.fromString(containerContext.id());
|
|
try {
|
|
if(anotherContextSet) {
|
|
resourceRegistryPublisher.addToContext(HostingNode.NAME, uuid, contextUUID, false);
|
|
}else {
|
|
resourceRegistryPublisher.addResourceToCurrentContext(HostingNode.NAME, uuid, false);
|
|
}
|
|
logger.info("{} with UUID {} successfully added to context ({})", HostingNode.NAME, uuid, context);
|
|
} catch (Exception e) {
|
|
logger.error("Unable to add {} with UUID {} to context ({})", HostingNode.NAME, uuid, context, e);
|
|
}
|
|
}
|
|
|
|
public void addToContext(UUID contextUUID) throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
|
String context = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
|
|
UUID uuid = UUID.fromString(containerContext.id());
|
|
try {
|
|
resourceRegistryPublisher.addToContext(HostingNode.NAME, uuid, contextUUID, false);
|
|
logger.info("{} with UUID {} successfully added to context ({})", HostingNode.NAME, uuid, context);
|
|
} catch (Exception e) {
|
|
logger.error("Unable to add {} with UUID {} to context ({})", HostingNode.NAME, uuid, context, e);
|
|
}
|
|
}
|
|
|
|
public void removeFromCurrentContext()
|
|
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
|
Secret secret = SecretManagerProvider.instance.get();
|
|
String context = secret.getContext();
|
|
UUID uuid = UUID.fromString(containerContext.id());
|
|
try {
|
|
resourceRegistryPublisher.removeResourceFromCurrentContext(HostingNode.NAME, uuid, false);
|
|
logger.info("{} with UUID {} successfully removed from context ({})", HostingNode.NAME, uuid, context);
|
|
} catch (Exception e) {
|
|
logger.error("Unable to remove {} with UUID {} from context ({})", HostingNode.NAME, uuid, context, e);
|
|
}
|
|
}
|
|
|
|
public void removeFromContext(UUID contextUUID)
|
|
throws ResourceNotFoundException, ContextNotFoundException, ResourceRegistryException {
|
|
String context = ContextCache.getInstance().getContextFullNameByUUID(contextUUID);
|
|
UUID uuid = UUID.fromString(containerContext.id());
|
|
try {
|
|
resourceRegistryPublisher.removeResourceFromContext(HostingNode.NAME, uuid, contextUUID, false);
|
|
logger.info("{} with UUID {} successfully removed from context ({})", HostingNode.NAME, uuid, context);
|
|
} catch (Exception e) {
|
|
logger.error("Unable to remove {} from context ({})", HostingNode.NAME, uuid, context, e);
|
|
}
|
|
}
|
|
|
|
public HostingNode updateFacets() throws ResourceRegistryException {
|
|
logger.debug("Updating {}", HostingNode.NAME);
|
|
|
|
MemoryFacet ramFacet = null;
|
|
MemoryFacet jvmMemoryFacet = null;
|
|
MemoryFacet disk = null;
|
|
StateFacet stateFacet = null;
|
|
EventFacet eventFacet = null;
|
|
|
|
Date date = Calendar.getInstance().getTime();
|
|
|
|
List<ConsistsOf<? extends Resource, ? extends Facet>> consistsOfToRemove = new ArrayList<>();
|
|
|
|
List<ConsistsOf<? extends Resource, ? extends Facet>> consistsOfList = hostingNode.getConsistsOf();
|
|
for (ConsistsOf<? extends Resource, ? extends Facet> c : consistsOfList) {
|
|
if (c.getTarget() instanceof StateFacet) {
|
|
stateFacet = (StateFacet) c.getTarget();
|
|
stateFacet = getStateFacet(stateFacet, date);
|
|
continue;
|
|
}
|
|
|
|
if (c instanceof HasVolatileMemory) {
|
|
String memoryType = (String) c.getAdditionalProperty(MEMORY_TYPE);
|
|
if (memoryType.compareTo(MEMORY_TYPE_RAM) == 0) {
|
|
ramFacet = (MemoryFacet) c.getTarget();
|
|
ramFacet = getRamInfo(ramFacet);
|
|
continue;
|
|
}
|
|
|
|
if (memoryType.compareTo(MEMORY_TYPE_JVM) == 0) {
|
|
jvmMemoryFacet = (MemoryFacet) c.getTarget();
|
|
jvmMemoryFacet = getJVMMemoryInfo(jvmMemoryFacet);
|
|
continue;
|
|
}
|
|
|
|
}
|
|
|
|
if (c instanceof HasPersistentMemory) {
|
|
disk = (MemoryFacet) c.getTarget();
|
|
disk = getDiskSpace(disk);
|
|
continue;
|
|
}
|
|
|
|
if(c.getTarget() instanceof EventFacet) {
|
|
EventFacet foundEventFacet = (EventFacet) c.getTarget();
|
|
String value = foundEventFacet.getEvent();
|
|
if(value.compareTo(getState())==0) {
|
|
// This facet must be updated (the date must be updated) so it must not be removed from update
|
|
foundEventFacet.setDate(date);
|
|
eventFacet = foundEventFacet;
|
|
continue;
|
|
}
|
|
}
|
|
|
|
consistsOfToRemove.add(c);
|
|
|
|
}
|
|
|
|
// Resource Update has effect only on specified facets.
|
|
// Removing the ones that have not to be changed.
|
|
consistsOfList.removeAll(consistsOfToRemove);
|
|
|
|
/* The eventFacet for the event does not exists. Going to create it */
|
|
if(eventFacet == null) {
|
|
eventFacet = getEventFacet(date);
|
|
hostingNode.addFacet(eventFacet);
|
|
}
|
|
|
|
try {
|
|
hostingNode = resourceRegistryPublisher.updateResource(hostingNode);
|
|
} catch (ResourceRegistryException e) {
|
|
logger.error("error trying to publish hosting node", e);
|
|
}
|
|
|
|
return hostingNode;
|
|
}
|
|
|
|
public static SoftwareFacet getOperativeSystem() {
|
|
SoftwareFacet osSoftwareFacet = new SoftwareFacetImpl();
|
|
OperatingSystemMXBean mxbean = ManagementFactory.getOperatingSystemMXBean();
|
|
String osName = mxbean.getName();
|
|
osSoftwareFacet.setGroup(osName); // softwareFacet.setGroup(System.getProperty("os.name"));
|
|
osSoftwareFacet.setName(mxbean.getArch()); // softwareFacet.setName(System.getProperty("os.arch"));
|
|
osSoftwareFacet.setVersion(mxbean.getVersion()); // softwareFacet.setVersion(System.getProperty("os.version"));
|
|
|
|
JsonNode jsonNode = ElementMapper.getObjectMapper().valueToTree(osSoftwareFacet);
|
|
Set<String> fieldNames = new TreeSet<>();
|
|
Iterator<String> it = jsonNode.fieldNames();
|
|
while (it.hasNext()) fieldNames.add(it.next());
|
|
|
|
if(osName.compareTo("Linux")==0) {
|
|
// Adding Linux Distribution Info
|
|
LinuxDistributionInfo linuxDistributionInfo = new LinuxDistributionInfo();
|
|
Map<String, String> map = linuxDistributionInfo.getInfo();
|
|
Set<String> keys = map.keySet();
|
|
for(String key : keys) {
|
|
String k = key;
|
|
if(fieldNames.contains(key)) {
|
|
k = "linuxDistribution-" + k;
|
|
}
|
|
osSoftwareFacet.setAdditionalProperty(k, map.get(key));
|
|
}
|
|
}
|
|
|
|
return osSoftwareFacet;
|
|
}
|
|
|
|
private HostingNode instantiateHostingNode() {
|
|
logger.info("Creating {}", HostingNode.NAME);
|
|
|
|
ContainerConfiguration containerConfiguration = containerContext.configuration();
|
|
String id = containerContext.id();
|
|
|
|
UUID uuid = UUID.fromString(id);
|
|
HostingNode hostingNode = new HostingNodeImpl();
|
|
hostingNode.setID(uuid);
|
|
|
|
NetworkingFacet networkingFacet = new NetworkingFacetImpl();
|
|
try {
|
|
networkingFacet.setIPAddress(InetAddress.getLocalHost().getHostAddress());
|
|
} catch (UnknownHostException e) {
|
|
logger.warn("unable to detect the IP address of the host");
|
|
}
|
|
String hostname = containerConfiguration.hostname();
|
|
networkingFacet.setHostName(hostname);
|
|
networkingFacet.setDomainName(getDomain(hostname));
|
|
|
|
networkingFacet.setAdditionalProperty("Port", containerConfiguration.port());
|
|
IsIdentifiedBy<HostingNode, NetworkingFacet> isIdentifiedBy = new IsIdentifiedByImpl<>(hostingNode,
|
|
networkingFacet, null);
|
|
hostingNode.addFacet(isIdentifiedBy);
|
|
|
|
List<CPUFacet> cpuFacets = getCPUFacets();
|
|
for (CPUFacet cpuFacet : cpuFacets) {
|
|
hostingNode.addFacet(cpuFacet);
|
|
}
|
|
|
|
SoftwareFacet osSoftwareFacet = getOperativeSystem();
|
|
hostingNode.addFacet(osSoftwareFacet);
|
|
|
|
|
|
SmartgearsConfiguration config = ProviderFactory.provider().smartgearsConfiguration();
|
|
SoftwareFacet smartgearsSoftwareFacet = new SoftwareFacetImpl();
|
|
smartgearsSoftwareFacet.setGroup("gCube");
|
|
smartgearsSoftwareFacet.setName("SmartGears");
|
|
smartgearsSoftwareFacet.setVersion(config.getVersion());
|
|
hostingNode.addFacet(smartgearsSoftwareFacet);
|
|
|
|
SoftwareFacet smartgearsDistributionSoftwareFacet = new SoftwareFacetImpl();
|
|
smartgearsDistributionSoftwareFacet.setGroup("gCube");
|
|
smartgearsDistributionSoftwareFacet.setName("SmartGearsDistribution");
|
|
String smartgearsDistributionVersion = containerConfiguration.properties().get("SmartGearsDistribution");
|
|
smartgearsDistributionSoftwareFacet.setVersion(smartgearsDistributionVersion);
|
|
smartgearsDistributionSoftwareFacet.setAdditionalProperty("publication-frequency",
|
|
String.valueOf(containerConfiguration.publicationFrequency()));
|
|
hostingNode.addFacet(smartgearsDistributionSoftwareFacet);
|
|
|
|
|
|
SoftwareFacet javaSoftwareFacet = new SoftwareFacetImpl();
|
|
javaSoftwareFacet.setGroup(System.getProperty("java.vendor"));
|
|
javaSoftwareFacet.setName("Java");
|
|
javaSoftwareFacet.setVersion(System.getProperty("java.version"));
|
|
javaSoftwareFacet.setAdditionalProperty("java.vendor.url", System.getProperty("java.vendor.url"));
|
|
javaSoftwareFacet.setAdditionalProperty("java.specification.version", System.getProperty("java.specification.version"));
|
|
hostingNode.addFacet(javaSoftwareFacet);
|
|
|
|
SimplePropertyFacet simplePropertyFacet = addEnvironmentVariables(containerConfiguration);
|
|
hostingNode.addFacet(simplePropertyFacet);
|
|
|
|
Date date = Calendar.getInstance().getTime();
|
|
|
|
StateFacet stateFacet = getStateFacet(null, date);
|
|
hostingNode.addFacet(stateFacet);
|
|
|
|
EventFacet eventFacet = getEventFacet(date);
|
|
hostingNode.addFacet(eventFacet);
|
|
|
|
MemoryFacet ramFacet = getRamInfo(null);
|
|
HasVolatileMemory<HostingNode, MemoryFacet> hasVolatileRAMMemory = new HasVolatileMemoryImpl<HostingNode, MemoryFacet>(
|
|
hostingNode, ramFacet, null);
|
|
hasVolatileRAMMemory.setAdditionalProperty(MEMORY_TYPE, MEMORY_TYPE_RAM);
|
|
hostingNode.addFacet(hasVolatileRAMMemory);
|
|
|
|
MemoryFacet jvmMemoryFacet = getJVMMemoryInfo(null);
|
|
HasVolatileMemory<HostingNode, MemoryFacet> hasVolatileJVMMemory = new HasVolatileMemoryImpl<HostingNode, MemoryFacet>(
|
|
hostingNode, jvmMemoryFacet, null);
|
|
hasVolatileJVMMemory.setAdditionalProperty(MEMORY_TYPE, MEMORY_TYPE_JVM);
|
|
hostingNode.addFacet(hasVolatileJVMMemory);
|
|
|
|
MemoryFacet diskFacet = getDiskSpace(null);
|
|
HasPersistentMemory<HostingNode, MemoryFacet> hasPersistentMemory = new HasPersistentMemoryImpl<HostingNode, MemoryFacet>(
|
|
hostingNode, diskFacet, null);
|
|
hostingNode.addFacet(hasPersistentMemory);
|
|
|
|
LocationFacet locationFacet = new LocationFacetImpl();
|
|
Site site = containerConfiguration.site();
|
|
locationFacet.setCountry(site.getCountry());
|
|
locationFacet.setLocation(site.getLocation());
|
|
// locationFacet.setLatitude(site.getLatitude());
|
|
// locationFacet.setLongitude(site.getLongitude());
|
|
hostingNode.addFacet(locationFacet);
|
|
|
|
logger.info("{} with UUID {} instantiated", HostingNode.NAME, uuid);
|
|
return hostingNode;
|
|
}
|
|
|
|
public HostingNode createHostingNode() throws ResourceRegistryException {
|
|
ResourceRegistryClient resourceRegistryClient = ResourceRegistryClientFactory.create();
|
|
UUID uuid = UUID.fromString(containerContext.id());
|
|
try {
|
|
hostingNode = resourceRegistryClient.getInstance(HostingNode.class, uuid);
|
|
hostingNode = updateFacets();
|
|
} catch (NotFoundException e) {
|
|
hostingNode = instantiateHostingNode();
|
|
hostingNode = resourceRegistryPublisher.createResource(hostingNode);
|
|
} catch (AvailableInAnotherContextException e) {
|
|
addToCurrentContext();
|
|
hostingNode = resourceRegistryClient.getInstance(HostingNode.class, uuid);
|
|
} catch (ResourceRegistryException e) {
|
|
logger.error("", e);
|
|
}
|
|
return hostingNode;
|
|
}
|
|
|
|
public String getState() {
|
|
return containerContext.lifecycle().state().remoteForm().toLowerCase();
|
|
}
|
|
|
|
|
|
private StateFacet getStateFacet(StateFacet stateFacet, Date date) {
|
|
if (stateFacet == null) {
|
|
stateFacet = new StateFacetImpl();
|
|
}
|
|
String state = getState();
|
|
stateFacet.setValue(state);
|
|
stateFacet.setAdditionalProperty("date", date);
|
|
return stateFacet;
|
|
}
|
|
|
|
private EventFacet getEventFacet(Date date) {
|
|
EventFacet eventFacet = new EventFacetImpl();
|
|
eventFacet.setDate(date);
|
|
String state = getState();
|
|
eventFacet.setEvent(state);
|
|
return eventFacet;
|
|
}
|
|
|
|
private MemoryFacet getDiskSpace(MemoryFacet memoryFacet) {
|
|
if (memoryFacet == null) {
|
|
memoryFacet = new MemoryFacetImpl();
|
|
}
|
|
|
|
long free = 0;
|
|
long total = 0;
|
|
try {
|
|
PersistenceConfiguration persistenceConfiguration = containerContext.configuration().persistenceConfiguration();
|
|
FileStore fileStore = Files
|
|
.getFileStore(Paths.get(persistenceConfiguration.getImplementationClass().newInstance().getLocation()));
|
|
free = fileStore.getUsableSpace() / 1048576; // 1048576 = 1024*1024
|
|
// user to convert
|
|
// bytes in MByte
|
|
total = fileStore.getTotalSpace() / 1048576; // 1048576 = 1024*1024
|
|
// user to convert
|
|
// bytes in MByte
|
|
} catch (Exception ioe) {
|
|
logger.warn("Unable to detect disk space information", ioe);
|
|
memoryFacet.setAdditionalProperty(MESSAGE, "Unable to detect disk space information.");
|
|
}
|
|
|
|
memoryFacet.setUnit(MemoryUnit.MB);
|
|
memoryFacet.setSize(total);
|
|
memoryFacet.setUsed(total - free);
|
|
|
|
return memoryFacet;
|
|
}
|
|
|
|
private static final long BYTE_TO_MB = 1024 * 1024;
|
|
|
|
private MemoryFacet getRamInfo(MemoryFacet memoryFacet) {
|
|
if (memoryFacet == null) {
|
|
memoryFacet = new MemoryFacetImpl();
|
|
}
|
|
|
|
/*
|
|
* OperatingSystemMXBean mxbean = ManagementFactory.getOperatingSystemMXBean();
|
|
* com.sun.management.OperatingSystemMXBean sunmxbean =
|
|
* (com.sun.management.OperatingSystemMXBean) mxbean; long freeMemory =
|
|
* sunmxbean.getFreePhysicalMemorySize() / 1048576; // in MB long totalMemory =
|
|
* sunmxbean.getTotalPhysicalMemorySize() / 1048576; // in MB
|
|
*/
|
|
|
|
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
|
|
long freeMemory;
|
|
try {
|
|
freeMemory = Long.parseLong(mBeanServer
|
|
.getAttribute(new ObjectName("java.lang", "type", "OperatingSystem"), "FreePhysicalMemorySize")
|
|
.toString()) / BYTE_TO_MB;
|
|
} catch (NumberFormatException | InstanceNotFoundException | AttributeNotFoundException
|
|
| MalformedObjectNameException | ReflectionException | MBeanException e) {
|
|
logger.warn(
|
|
"Unable to get free memory from Operating System. Going to get JVM Memory. Better than nothing");
|
|
long allocatedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
|
|
freeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory;
|
|
}
|
|
long totalMemory;
|
|
try {
|
|
totalMemory = Long.parseLong(mBeanServer
|
|
.getAttribute(new ObjectName("java.lang", "type", "OperatingSystem"), "TotalPhysicalMemorySize")
|
|
.toString()) / BYTE_TO_MB;
|
|
} catch (NumberFormatException | InstanceNotFoundException | AttributeNotFoundException
|
|
| MalformedObjectNameException | ReflectionException | MBeanException e) {
|
|
logger.warn("Unable to total memory from Operating System. Going to get JVM Memory. Better than nothing");
|
|
totalMemory = Runtime.getRuntime().maxMemory();
|
|
}
|
|
|
|
memoryFacet.setUnit(MemoryUnit.MB);
|
|
memoryFacet.setSize(totalMemory);
|
|
memoryFacet.setUsed(totalMemory - freeMemory);
|
|
|
|
return memoryFacet;
|
|
}
|
|
|
|
private MemoryFacet getJVMMemoryInfo(MemoryFacet memoryFacet) {
|
|
if (memoryFacet == null) {
|
|
memoryFacet = new MemoryFacetImpl();
|
|
}
|
|
|
|
/* 1048576 = 1024*1024 used to convert bytes in MByte */
|
|
long jvmFreeMemory = Runtime.getRuntime().freeMemory() / 1048576;
|
|
long jvmTotalMemory = Runtime.getRuntime().totalMemory() / 1048576;
|
|
long jvmMaxMemory = Runtime.getRuntime().maxMemory() / 1048576;
|
|
|
|
memoryFacet.setUnit(MemoryUnit.MB);
|
|
memoryFacet.setSize(jvmTotalMemory);
|
|
memoryFacet.setUsed(jvmTotalMemory - jvmFreeMemory);
|
|
memoryFacet.setAdditionalProperty(JVM_MAX_MEMORY, jvmMaxMemory);
|
|
|
|
return memoryFacet;
|
|
}
|
|
|
|
private static String sanitizeKey(String key) {
|
|
return key.trim().replace(" ", "_");
|
|
}
|
|
|
|
private SimplePropertyFacet addEnvironmentVariables(ContainerConfiguration containerConfiguration) {
|
|
|
|
Map<String, String> map = new HashMap<String, String>();
|
|
map.putAll(containerConfiguration.properties());
|
|
map.putAll(System.getenv());
|
|
|
|
SimplePropertyFacet simplePropertyFacet = new SimplePropertyFacetImpl();
|
|
simplePropertyFacet.setName("ENVIRONMENT_VARIABLES");
|
|
simplePropertyFacet.setValue("");
|
|
|
|
for (Map.Entry<String, String> entry : map.entrySet()) {
|
|
String varname = entry.getKey();
|
|
if ((varname.compareToIgnoreCase("CLASSPATH") == 0) || (varname.compareToIgnoreCase("PATH") == 0)
|
|
|| (varname.contains("SSH")) || (varname.contains("MAIL"))
|
|
|| (varname.compareToIgnoreCase("LS_COLORS") == 0)) {
|
|
continue;
|
|
}
|
|
simplePropertyFacet.setAdditionalProperty(sanitizeKey(entry.getKey()), entry.getValue());
|
|
}
|
|
|
|
return simplePropertyFacet;
|
|
}
|
|
|
|
private static String getDomain(String hostname) {
|
|
try {
|
|
Pattern pattern = Pattern.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})");
|
|
Matcher regexMatcher = pattern.matcher(hostname);
|
|
if (regexMatcher.matches()) { // it's an IP address, nothing to trim
|
|
return hostname;
|
|
}
|
|
return hostname.substring(hostname.indexOf(".") + 1);
|
|
} catch (Exception e) {
|
|
logger.warn("Error while getting domain from hostname");
|
|
return hostname;
|
|
}
|
|
}
|
|
|
|
public static final String CPU_PROCESSOR = "processor";
|
|
public static final String CPU_VENDOR_ID = "vendor_id";
|
|
public static final String CPU_MODEL_NAME = "model name";
|
|
public static final String CPU_CPU_MHZ = "cpu MHz";
|
|
public static final String CPU_MODEL_T = "model\t";
|
|
public static final String CPU_MODEL_B = "model\b";
|
|
public static final String CPU_MODEL_NUMBER = "modelNumber";
|
|
|
|
public static List<CPUFacet> getCPUFacets() {
|
|
|
|
List<CPUFacet> cpuFacets = new ArrayList<>();
|
|
|
|
File file = new File("/proc/cpuinfo");
|
|
|
|
if (!file.exists()) {
|
|
logger.warn("cannot acquire CPU info (no /proc/cpuinfo)");
|
|
return cpuFacets;
|
|
}
|
|
|
|
BufferedReader input = null;
|
|
|
|
try {
|
|
input = new BufferedReader(new FileReader(file));
|
|
|
|
String line = null;
|
|
|
|
CPUFacet cpuFacet = null;
|
|
|
|
while ((line = input.readLine()) != null) {
|
|
|
|
if ((line.startsWith(CPU_PROCESSOR))) { // add the current
|
|
// processor to the map
|
|
cpuFacet = new CPUFacetImpl();
|
|
cpuFacets.add(cpuFacet);
|
|
}
|
|
|
|
try {
|
|
if (line.contains(CPU_VENDOR_ID)) {
|
|
cpuFacet.setVendor(line.split(":")[1].trim());
|
|
continue;
|
|
}
|
|
} catch (Exception e) {
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
if (line.contains(CPU_MODEL_NAME)) {
|
|
cpuFacet.setModel(line.split(":")[1].trim());
|
|
continue;
|
|
}
|
|
} catch (Exception e) {
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
if (line.contains(CPU_CPU_MHZ)) {
|
|
cpuFacet.setClockSpeed(line.split(":")[1].trim());
|
|
continue;
|
|
}
|
|
} catch (Exception e) {
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
if ((line.contains(CPU_MODEL_T)) || (line.contains(CPU_MODEL_B))) {
|
|
cpuFacet.setAdditionalProperty(CPU_MODEL_NUMBER, line.split(":")[1].trim());
|
|
continue;
|
|
}
|
|
} catch (Exception e) {
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
String[] nameValue = line.split(":");
|
|
cpuFacet.setAdditionalProperty(sanitizeKey(nameValue[0]), line.split(":")[1].trim());
|
|
} catch (Exception e) {
|
|
|
|
}
|
|
|
|
}
|
|
} catch (Exception e) {
|
|
logger.warn("unable to acquire CPU info", e);
|
|
} finally {
|
|
if (input != null) {
|
|
try {
|
|
input.close();
|
|
} catch (IOException e) {
|
|
logger.warn("unable to close stream", e);
|
|
}
|
|
}
|
|
}
|
|
return cpuFacets;
|
|
}
|
|
|
|
public Map<UUID,String> getContextsUUID() throws Exception {
|
|
return resourceRegistryPublisher.getResourceContexts(hostingNode);
|
|
}
|
|
|
|
}
|