estado sist linux interface

parent 7ce330d6
package edu.proygrado.ejb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
......@@ -23,15 +18,12 @@ import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
......@@ -46,6 +38,9 @@ import edu.proygrado.dto.RegistroTareaDTO;
import edu.proygrado.dto.TiempoAccesoDTO;
import edu.proygrado.dto.TipoArchivo;
import edu.proygrado.dto.TipoDestinatario;
import edu.proygrado.ejb.estadoServidor.EstadoServidorLinux;
import edu.proygrado.ejb.estadoServidor.EstadoServidorOSX;
import edu.proygrado.ejb.estadoServidor.IEstadoServidor;
import edu.proygrado.modelo.CentroEducativo;
import edu.proygrado.modelo.RegistroAccesoArchivo;
import edu.proygrado.modelo.RegistroAccesoArchivoPK;
......@@ -302,7 +297,8 @@ public class EstadoSistemaEJB {
return c.getId().equals(1l) || !c.isVisible();
}
private Future<Map<String, Object>> getAllCoursesBasicInfo(ExecutorService executor, CentroEducativo l, CoursesEJB coursesEJB, Map<Long, CentroEducativo> todosLoscentroeducativos) throws Exception{
@SuppressWarnings("serial")
private Future<Map<String, Object>> getAllCoursesBasicInfo(ExecutorService executor, CentroEducativo l, CoursesEJB coursesEJB, Map<Long, CentroEducativo> todosLoscentroeducativos) throws Exception{
return executor.submit(() -> {
boolean multicentroeducativo = (l==null);
ConcurrentLinkedQueue<EstadoSistemaCursoDTO> estadoSistemaCurso = new ConcurrentLinkedQueue<EstadoSistemaCursoDTO>();
......@@ -424,16 +420,12 @@ public class EstadoSistemaEJB {
if (!map.containsKey(key)) {
String keyCantidades = String.format("%d-%d", rt.getcentroeducativo().getCentroEducativoPK().getIdcentroeducativo(), rt.getCursoid());
if (!mapCantidades.containsKey(keyCantidades)) {
//centroeducativosMap
CentroEducativo lic = centroeducativosMap.get(rt.getcentroeducativo().getCentroEducativoPK().getIdcentroeducativo());
mapCantidades.put(keyCantidades, gruposEJB.getCantidadAlumnosCantidadGrupos(rt.getCursoid(),
new StringPair(MoodleConstants.matefunUserCustomServiceToken,
lic.getMoodleapiusertoken()), lic.getMoodleuri()));
}
map.put(key, new RegistroTareaDTO( rt.getNombreTarea(),
rt.getTipoAccion()==TipoAccionRegistroTarea.Entrega ? 1l : 0l,
rt.getTipoAccion()==TipoAccionRegistroTarea.Correccion ? 1l : 0l,
......@@ -489,7 +481,6 @@ public class EstadoSistemaEJB {
public Future<List<RegistroLoginDTO>> getRegistrosLogin(ExecutorService executor, GregorianCalendar inicio, GregorianCalendar fin, Map<Long, CentroEducativo> todosLoscentroeducativos, CentroEducativo ...centroeducativo) {
return executor.submit(() -> {
//MULTIcentroeducativo
CentroEducativo l = centroeducativo!=null && centroeducativo.length > 0 ? centroeducativo[0] : null;
TypedQuery<RegistroLogin> query = em.createQuery(
"select r from RegistroLogin r where " + ( l!=null ? "r.idcentroeducativo = :idcentroeducativo and " : "" ) + "r.fecha >= :inicio and r.fecha <= :fin", RegistroLogin.class)
......@@ -502,141 +493,9 @@ public class EstadoSistemaEJB {
});
}
private String extractHostname(List<String> commandResult) {
String dirtyHostname = commandResult.stream().filter(s -> s.contains("hostname")).findFirst().orElse(null).split(":")[1];
return dirtyHostname.substring(dirtyHostname.indexOf("\"")+1, dirtyHostname.lastIndexOf("\""));
}
private Future<List<String>> executeShellCommand(ExecutorService executor, String command) throws IOException, InterruptedException {
return executor.submit(() -> {
List<String> salida = new ArrayList<String>();
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", command);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
System.out.println((++i) + ": " + command + " -> " + line);
salida.add(line);
}
process.waitFor();
return salida;
});
}
private String getIP() throws IOException {
return (new BufferedReader(new InputStreamReader((new URL("http://checkip.amazonaws.com")).openStream()))).readLine();
}
private List<String> extractTopProcesses(List<String> topResult, String pid) {
List<String> result = new ArrayList<String>();
for (int index = 0; index < topResult.size(); index++) {
if (topResult.get(index).startsWith("PID") || topResult.get(index).startsWith(pid)) {
result.add(topResult.get(index));
}
}
return result;
}
JsonObject extractFieldsFromProcess(List<String> topColumnNameAndProcess){
JsonObjectBuilder builder = Json.createObjectBuilder();
//.add("backend", Json.createObjectBuilder()
// OSX "%CPU" "MEM"
int remaining = 2;
String[] splittedHeader = topColumnNameAndProcess.get(0).split("\\s+");
String[] splittedProcess = topColumnNameAndProcess.get(1).split("\\s+");
for (int index = splittedHeader.length-1; index>=0; index--) {
if (splittedHeader[index].equals("MEM")) {
builder = builder.add("memproceso", splittedProcess[index]);
remaining--;
}else if (splittedHeader[index].equals("%CPU")){
builder = builder.add("cpuproceso", splittedProcess[index]);
remaining--;
}
if (remaining==0)
break;
}
return builder.build();
}
public JsonObject getEstadoServidor(Boolean all) throws IOException, InterruptedException, InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException, ExecutionException {
System.out.print("isUnix: " + isUnix);
ExecutorService executor = Executors.newFixedThreadPool(3);
Future<List<String>> top = executeShellCommand(executor, "top -l 1");
String listenPort = ManagementFactory.getPlatformMBeanServer().getAttribute(new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http"), "port").toString();
Future<List<String>> lsof = executeShellCommand(executor, "lsof -i :"+listenPort+" | grep LISTEN");
Future<List<String>> curl = null;
if (all) {
curl = executeShellCommand(executor, "curl -v https://ipinfo.io");
}
String loadavg = "";
String globalcpuusage = "";
String globalphysmem = "";
int i = 3;
for (String l : top.get()) {
if (l.startsWith("Load Avg")) {
loadavg = l.split("Load Avg: ")[1];
i--;
}else if (l.startsWith("CPU usage")) {
globalcpuusage = l.split("CPU usage: ")[1];
i--;
}else if (l.startsWith("PhysMem")) {
globalphysmem = l.split("PhysMem: ")[1];
i--;
}
if (i==0)
break;
}
String dburl = "";
String schema = "";
String dbSize = "";
try {
userTransaction.begin();
dburl = em.unwrap(java.sql.Connection.class).getMetaData().getURL();
schema = dburl.split("/")[3];
dbSize = ((BigDecimal)em.createNativeQuery("SELECT sum(DATA_LENGTH + INDEX_LENGTH) FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? GROUP BY TABLE_SCHEMA").setParameter(1, schema).getResultList().get(0)).toString();
} catch (Exception e) {
dbSize = "";
} finally {
try {
userTransaction.commit();
} catch (Exception e2) { }
}
String pid = lsof.get().get(0).split("\\s+")[1];
JsonObject cpumem = extractFieldsFromProcess(extractTopProcesses(top.get(), pid));
return Json.createObjectBuilder()
.add("backend", Json.createObjectBuilder()
.add("nombre", all ? extractHostname(curl.get()) : "")
.add("ip", all ? getIP() : "")
.add("carga", loadavg)
.add("pid", pid)
.add("cpuproceso", cpumem.getString("cpuproceso"))
.add("memproceso", cpumem.getString("memproceso"))
.add("cpu", globalcpuusage)
.add("mem", globalphysmem)
.add("puerto", listenPort))
.add("bd", Json.createObjectBuilder()
.add("nombre", all ? dburl.split("/")[2].split(":")[0] : "")
.add("ip", "211.221.111.222")
.add("puerto", all ? dburl.split("/")[2].split(":")[1] : "")
.add("motor", all ? dburl.split(":")[1] : "")
.add("tam", dbSize + " Bytes")
.add("schema", all ? schema : "")).build();
public JsonObject getEstadoServidor(Boolean all) throws InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException, IOException, InterruptedException, ExecutionException {
IEstadoServidor e = isUnix ? new EstadoServidorLinux(em, userTransaction) : new EstadoServidorOSX(em, userTransaction);
return e.getEstadoServidor(all);
}
public List<TiempoAccesoDTO> getTiempos(GregorianCalendar inicio, GregorianCalendar fin, Long idcentroeducativo) {
......
package edu.proygrado.ejb.estadoServidor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.persistence.EntityManager;
import javax.transaction.UserTransaction;
import edu.proygrado.utils.Utils;
public class EstadoServidorLinux implements IEstadoServidor{
private EntityManager em = null;
private UserTransaction userTransaction = null;
public EstadoServidorLinux(EntityManager em, UserTransaction userTransaction) {
this.em = em;
this.userTransaction = userTransaction;
}
private List<String> executeShellCommandSync(String command) throws IOException, InterruptedException {
List<String> salida = new ArrayList<String>();
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", command);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
salida.add(line);
}
process.waitFor();
return salida;
}
private List<String> extractTopProcesses(List<String> topResult, String pid) {
List<String> result = new ArrayList<String>();
for (int index = 0; index < topResult.size(); index++) {
if (topResult.get(index).contains("PID") || topResult.get(index).startsWith(pid)) {
//System.out.println("extractTopProcesses:"+topResult.get(index) + " ADD");
result.add(topResult.get(index));
}else {
//System.out.println("extractTopProcesses:"+topResult.get(index));
}
}
return result;
}
JsonObject extractFieldsFromProcess(List<String> topColumnNameAndProcess){
JsonObjectBuilder builder = Json.createObjectBuilder();
String cpu = "%CPU";
String mem = "%MEM";
//System.out.println("*cpu:"+cpu);
//System.out.println("*mem:"+mem);
int remaining = 2;
String[] splittedHeader = Utils.reverse(topColumnNameAndProcess.get(0).split("\\s+"));
String[] splittedProcess = Utils.reverse(topColumnNameAndProcess.get(1).split("\\s+"));
//System.out.println("*extractFieldsFromProcess:splittedHeader:[" + String.join(",", splittedHeader)+"]");
//System.out.println("*extractFieldsFromProcess:splittedProcess:[" + String.join(",", splittedProcess)+"]");
Integer maxLength = Math.min(splittedHeader.length, splittedProcess.length);
for (int index = 0; index < maxLength; index++) {
//System.out.println("INDEX:"+index+",HEADER:"+splittedHeader[index]+",VALUE:"+splittedProcess[index]);
if (splittedHeader[index].equals(mem)) {
//System.out.println("index:"+index+" es " + mem + ", guarda memproceso="+splittedProcess[index]);
builder = builder.add("memproceso", splittedProcess[index]);
remaining--;
}else if (splittedHeader[index].equals(cpu)) {
//System.out.println("index:"+index+" es " + cpu + ", guarda cpuproceso="+splittedProcess[index]);
builder = builder.add("cpuproceso", splittedProcess[index]);
remaining--;
}
if (remaining==0)
break;
}
return builder.build();
}
private String extractHostname(List<String> commandResult) {
String dirtyHostname = commandResult.stream().filter(s -> s.contains("hostname")).findFirst().orElse(null).split(":")[1];
//System.out.print("extractHostname:dirtyHostname: " + dirtyHostname);
return dirtyHostname.substring(dirtyHostname.indexOf("\"")+1, dirtyHostname.lastIndexOf("\""));
}
private String getIP() throws IOException {
return (new BufferedReader(new InputStreamReader((new URL("http://checkip.amazonaws.com")).openStream()))).readLine();
}
@Override
public JsonObject getEstadoServidor(Boolean all) throws IOException, InterruptedException, InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException, ExecutionException {
String listenPort = ManagementFactory.getPlatformMBeanServer().getAttribute(new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http"), "port").toString();
List<String> lsof = executeShellCommandSync("lsof -i :"+listenPort+" | grep LISTEN");
String pid = lsof.get(0).split("\\s+")[1];
List<String> top = executeShellCommandSync("top -n 1 -b | grep '^"+pid+"\\|load average\\|Mem \\:\\|\\%Cpu\\|PID USER'");
List<String> curl = executeShellCommandSync("curl -v https://ipinfo.io");
String loadavg = "";
String globalcpuusage = "";
String globalphysmem = "";
int i = 3;
for (String l : top) {
if (l.contains("load average:")) {
//System.out.println("linestart:" + l);
loadavg = l.split("load average:")[1];
i--;
}else if (l.startsWith("%Cpu(s)")) {
//System.out.println("linestart:" + l);
globalcpuusage = l.substring(l.indexOf("%Cpu(s)")+9);
i--;
}else if (l.contains("Mem :")) {
//System.out.println("linestart:" + l);
globalphysmem = l.split("Mem : ")[1];
i--;
}
if (i==0)
break;
}
String dburl = "";
String schema = "";
String dbSize = "";
try {
userTransaction.begin();
dburl = em.unwrap(java.sql.Connection.class).getMetaData().getURL();
//System.out.println("dburl:" + dburl);
schema = dburl.split("/")[3];
//System.out.println("schema:" + schema);
dbSize = ((BigDecimal)em.createNativeQuery("SELECT sum(DATA_LENGTH + INDEX_LENGTH) FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? GROUP BY TABLE_SCHEMA").setParameter(1, schema).getResultList().get(0)).toString() + " Bytes";
//System.out.println("dbSize:" + dbSize);
} catch (Exception e) {
} finally {
try {
userTransaction.commit();
} catch (Exception e2) { }
}
JsonObject cpumem = extractFieldsFromProcess(extractTopProcesses(top, pid));
//System.out.println("main:cpumem:" + cpumem.toString());
return Json.createObjectBuilder()
.add("backend", Json.createObjectBuilder()
.add("nombre", extractHostname(curl))
.add("ip", getIP())
.add("carga", loadavg)
.add("pid", pid)
.add("cpuproceso", cpumem.getString("cpuproceso"))
.add("memproceso", cpumem.getString("memproceso"))
.add("cpu", globalcpuusage)
.add("mem", globalphysmem)
.add("puerto", listenPort))
.add("bd", Json.createObjectBuilder()
.add("nombre", dburl.split("/")[2].split(":")[0])
.add("ip", "211.221.111.222")
.add("puerto", dburl.split("/")[2].split(":")[1])
.add("motor", dburl.split(":")[1])
.add("tam", dbSize)
.add("schema", schema)).build();
}
}
package edu.proygrado.ejb.estadoServidor;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import javax.json.JsonObject;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.ReflectionException;
import javax.persistence.EntityManager;
import javax.transaction.UserTransaction;
public class EstadoServidorOSX implements IEstadoServidor {
private EntityManager em = null;
private UserTransaction userTransaction = null;
public EstadoServidorOSX(EntityManager em, UserTransaction userTransaction) {
this.em = em;
this.userTransaction = userTransaction;
}
@Override
public JsonObject getEstadoServidor(Boolean all) throws IOException, InterruptedException, InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException, ExecutionException {
return null;
}
}
package edu.proygrado.ejb.estadoServidor;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import javax.json.JsonObject;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.ReflectionException;
public interface IEstadoServidor {
public JsonObject getEstadoServidor(Boolean all) throws IOException, InterruptedException, InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException, ExecutionException;
}
......@@ -61,8 +61,6 @@ public class ArchivosRS{
Boolean esCompartido = compartido!=null && compartido;
String matefunToken = Utils.getToken(httpServletRequest);
if (!esCompartido) {
startTime = (new Date()).getTime();
ret = MoodleHelper.getMoodleFileContents(invitadoEJB, moodleFilePath, matefunToken, tiempoAccesoEJB);
......
package edu.proygrado.servicios.estadosistema;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.ejb.EJB;
......@@ -51,12 +52,21 @@ public class EstadoSistemaRS {
@EJB
private GruposEJB gruposEJB;
@Inject
private HttpServletRequest httpServletRequest;
@EJB
private EstadoSistemaEJB tiempoAccesoEJB;
@GET
@Path("/servidor")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getEstadoServidor(@QueryParam("all") Boolean all) throws Exception {
return estadoSistemaEJB.getEstadoServidor(all!=null && all);
public JsonObject getEstadoServidor(@QueryParam("all") Boolean all) throws Exception {
Long startTime = (new Date()).getTime();
String matefunToken = Utils.getToken(httpServletRequest);
JsonObject ret = estadoSistemaEJB.getEstadoServidor(all!=null && all);
tiempoAccesoEJB.saveAccessTime(invitadoEJB.getidcentroeducativo(matefunToken), invitadoEJB.getMoodleUserId(matefunToken), "matefun", "GET /estadosistema/servidor", (new Date()).getTime()-startTime);
return ret;
}
@GET
......
......@@ -19,6 +19,16 @@ public class Utils {
public static final int DifferenceFromGMTSeconds = 3 * 60 * 60;
public static String[] reverse(String a[]) {
String[] b = new String[a.length];
int j = a.length;
for (int i = 0; i < a.length; i++) {
b[j - 1] = a[i];
j = j - 1;
}
return b;
}
public static Pair<String,String> extractName(JsonObject user){
return new Pair<String,String> (
user.containsKey("firstname") ? user.getString("firstname") : (user.containsKey("fullname") ? user.getString("fullname").split(" ")[0] : "NO-FIRSTNAME"),
......
#Generated by Maven Integration for Eclipse
#Mon Jul 27 15:40:50 BRT 2020
#Tue Jul 28 16:38:54 BRT 2020
version=0.0.1-SNAPSHOT
groupId=proygrado
m2e.projectName=Servidor JEE
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment