中间件的数据抽取各种运行状态 ,weblogic的 , tomcat 类似 ---朋友的代码

2021-02-25 15:15:59 浏览数 (1)

代码语言:javascript复制
package com.agent.opt.type.weblogic.data;

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
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.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;

import org.apache.commons.lang.StringUtils;

import com.agent.opt.type.tool.model.ConfigConstants;
import com.agent.opt.type.tool.model.ConfigUtil;
import com.agent.opt.type.tool.model.EmptyData;
import com.agent.opt.type.tool.model.IcopLogger;
import com.agent.opt.type.tool.model.IcopLoggerFactory;
import com.agent.opt.type.tool.model.InstallInfoUtil;
import com.agent.opt.type.tool.model.PropertiesUtil;
import com.agent.opt.type.tool.model.StringConstants;
import com.agent.opt.type.weblogic.model.ClusterModel;
import com.agent.opt.type.weblogic.model.CpWeblogicAppData;
import com.agent.opt.type.weblogic.model.CpWeblogicJdbcData;
import com.agent.opt.type.weblogic.model.CpWeblogicJmsData;
import com.agent.opt.type.weblogic.model.CpWeblogicQueueData;
import com.agent.opt.type.weblogic.model.CpWeblogicServerConfig;
import com.agent.opt.type.weblogic.model.CpWeblogicServerData;
import com.agent.opt.type.weblogic.model.WeblogicPackage;
import com.agent.opt.type.weblogic.model.WeblogicRegisterModel;
import com.alibaba.fastjson.JSON;
import com.sun.management.OperatingSystemMXBean;

import weblogic.health.HealthState;

public class WeblogicModule {
   private MBeanServerConnection connection;
   private JMXConnector connector;
   private ObjectName runtimeService;
   private final String RUNTIMESERVICEMBEAN = "com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean";
   private Map clusterlist = new HashMap();
   private static IcopLogger logger = IcopLoggerFactory.getLogger(WeblogicModule.class);

   private static String DEFAULT_PROTOCOL = "t3";

   static {
      String defaultProtocol = ConfigUtil.getConfProperty("default.protocol");
      if (StringUtils.isNotBlank(defaultProtocol)) {
         DEFAULT_PROTOCOL = defaultProtocol;
      }
   }


   private String getSslConfigFile() {
      return InstallInfoUtil.getBinRootInstallFolder()   File.separator   StringConstants.CONFIG_FOLDER
              File.separator   "DemoTrust.jks";
   }

   /**
    * 初始化连接
    *
    * @throws IOException
    * @throws MalformedURLException
    * @throws MalformedObjectNameException
    */
   public void initConnection(String hostname, String portString, String username, String password, String trustFile)
         throws IOException, MalformedURLException, MalformedObjectNameException {
      String protocol = DEFAULT_PROTOCOL;
      if ("https".equals(protocol)) {
         if (StringUtils.isBlank(trustFile)) {
            trustFile = getSslConfigFile();
         }
         System.setProperty("javax.net.ssl.trustStore", trustFile);
      }
      logger.info("jmx initConnection");
      int port = Integer.valueOf(portString);
      String jndiroot = "/jndi/";
      String mserver = "weblogic.management.mbeanservers.domainruntime";
      if (protocol.equals("t3s")) {
         // System.setProperty(Context.PROVIDER_URL,
         // String.format("https://%s:%s", hostname, portString));
         System.setProperty("weblogic.security.allowCryptoJDefaultJCEVerification", "true");
         System.setProperty("weblogic.security.allowCryptoJDefaultPRNG", "true");
         System.setProperty("weblogic.security.SSL.ignoreHostnameVerification", "true");
         System.setProperty("weblogic.security.TrustKeyStore", "CustomTrust");
         if (StringUtils.isBlank(trustFile)) {
            trustFile = getSslConfigFile();
         }
         System.setProperty("weblogic.security.CustomTrustKeyStoreFileName", trustFile);
      }
      Hashtable h = new Hashtable();
      h.put(Context.SECURITY_PRINCIPAL, username);
      h.put(Context.SECURITY_CREDENTIALS, password);
      h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
      JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostname, port, jndiroot   mserver);
      JMXConnector connector = JMXConnectorFactory.connect(serviceURL, h);
      connection = connector.getMBeanServerConnection();
      runtimeService = new ObjectName(RUNTIMESERVICEMBEAN);
      System.out.println("weblogic 连接开启");
   }

   /**
    * weblogic信息管理
    *
    * @throws AttributeNotFoundException
    * @throws InstanceNotFoundException
    * @throws MBeanException
    * @throws ReflectionException
    * @throws IOException
    */
   @SuppressWarnings({ "restriction", "unused" })
   public WeblogicPackage getWeblogicDatas(ObjectName[] serverRuntimes, List serverConfigs,
         WeblogicRegisterModel weblogicRegisterModel, String trustFile) throws AttributeNotFoundException,
         InstanceNotFoundException, MBeanException, ReflectionException, IOException {

      if (weblogicRegisterModel.getIp() != null) {
         logger.info("jmx getWeblogicDatas "   weblogicRegisterModel.getIp());
      } else {
         logger.info("jmx getWeblogicDatas ");
      }

      WeblogicPackage packagedatas = new WeblogicPackage();
      Map serverIDs = new HashMap();
      if (serverConfigs != null && serverConfigs.size() > 0) {
         for (CpWeblogicServerConfig serverConfigModel : serverConfigs) {
            serverIDs.put(serverConfigModel.getServerName(), serverConfigModel.getEntityID());
         }
      } else {
         logger.info("No Weblogic Server found");
         return packagedatas;
      }
      // 获取服务总量
      int length = (int) serverRuntimes.length;
      logger.debug("serverRuntimes "   length   " serverIDs:"   JSON.toJSONString(serverIDs));
      List packageDatas = new ArrayList();
      for (int j = 0; j < length; j  ) {
         CpWeblogicServerData serverDatas = new CpWeblogicServerData();
         // 服务名称 Name
         String name = getAttribute(serverRuntimes[j], "Name");
         // JVM运行时 JVMRuntime
         ObjectName JVMRuntime = getAttribute(serverRuntimes[j], "JVMRuntime");

         // 设置服务ID(突然停服务)
         if ("".equals(serverIDs.get(name)) || serverIDs.get(name) == null) {
            continue;
         }
         serverDatas.setServerID(Integer.parseInt(String.valueOf(serverIDs.get(name))));

         String protocol = DEFAULT_PROTOCOL;
         String jndiroot = "/jndi/";
         String mserver = "weblogic.management.mbeanservers.runtime";
         // 返回当前服务器监听连接的端口 ListenPort
         Integer listenPort = getAttribute(serverRuntimes[j], "ListenPort");
         // 返回当前服务器监听连接的IP地址 ListenAddress
         String listenAddress = getAttribute(serverRuntimes[j], "ListenAddress");

         // TODO jms服务数据
         List cpWeblogicJmsDatas = new ArrayList();
         ObjectName objName = (ObjectName) connection.getAttribute(serverRuntimes[j], "JMSRuntime");
         ObjectName[] jmsServers = (ObjectName[]) getAttribute(objName, "JMSServers");
         for (int i = 0; i < jmsServers.length; i  ) {
            CpWeblogicJmsData cpWeblogicJmsData = new CpWeblogicJmsData();
            String jmsServerName = getAttribute(jmsServers[i], "Name");
            Long messagesPendingCount = getAttribute(jmsServers[i], "MessagesPendingCount");
            HealthState healthState = getAttribute(objName, "HealthState");
            cpWeblogicJmsData.setServerID(serverDatas.getServerID());
            cpWeblogicJmsData.setJmsName(jmsServerName);
            cpWeblogicJmsData.setMessagesPendingCount(messagesPendingCount);
            cpWeblogicJmsData.setJmsServerStatus(healthState.getState());
            cpWeblogicJmsDatas.add(cpWeblogicJmsData);
         }
         serverDatas.setCpWeblogicJmsData(cpWeblogicJmsDatas);

         if (listenAddress.indexOf("/") != -1) {
            String[] tempAddr = listenAddress.split("/");
            if (tempAddr.length == 1) {
               listenAddress = tempAddr[0];
            } else if (tempAddr[tempAddr.length - 1].trim().length() != 0) {
               listenAddress = tempAddr[tempAddr.length - 1];
            } else if (tempAddr.length > 2) {
               listenAddress = tempAddr[tempAddr.length - 2];
            }
            // listenAddress = listenAddress.split("/")[1];
         }
         if (!isIPAddress(listenAddress)) {
            String ip = hostToIp(listenAddress);
            if (!"".equals(ip)) {
               listenAddress = ip;
            } else {
               continue;
            }
         }
         JMXConnector connector1 = null;
         try {
            String javaVersion = getAttribute(JVMRuntime, "JavaVersion");
            if (IsJavaVersionSupported(javaVersion)) {
               logger.debug("jmx getServerData :"   listenAddress   " port:"   listenPort
                       " Supported JDK version: "   javaVersion);
               if ("https".equals(protocol)) {
                  if (StringUtils.isBlank(trustFile)) {
                     trustFile = getSslConfigFile();
                  }
                  System.setProperty("javax.net.ssl.trustStore", trustFile);
               }
               // get AdministrationPort
               ObjectName domainConfig = (ObjectName) connection.getAttribute(runtimeService,
                     "DomainConfiguration");
               Integer administrationPort = getAttribute(domainConfig, "AdministrationPort");
               if (protocol.equals("t3s")) {
                  listenPort = administrationPort;
                  serverDatas.setServicePortState(telnet(listenAddress, listenPort) ? 0 : 1);
                  // System.setProperty(Context.PROVIDER_URL,
                  // String.format("https://%s:%s", hostname,
                  // portString));
                  System.setProperty("weblogic.security.allowCryptoJDefaultJCEVerification", "true");
                  System.setProperty("weblogic.security.allowCryptoJDefaultPRNG", "true");
                  System.setProperty("weblogic.security.SSL.ignoreHostnameVerification", "true");
                  System.setProperty("weblogic.security.TrustKeyStore", "CustomTrust");
                  if (StringUtils.isBlank(trustFile)) {
                     trustFile = getSslConfigFile();
                  }
                  System.setProperty("weblogic.security.CustomTrustKeyStoreFileName", trustFile);
               }
               JMXServiceURL serviceURL = new JMXServiceURL(protocol, listenAddress, listenPort,
                     jndiroot   mserver);
               Hashtable h = new Hashtable();
               h.put(Context.SECURITY_PRINCIPAL, weblogicRegisterModel.getUser());
               h.put(Context.SECURITY_CREDENTIALS, weblogicRegisterModel.getPassword());
               h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
               connector1 = JMXConnectorFactory.connect(serviceURL, h);

               MBeanServerConnection msc = connector1.getMBeanServerConnection();
               OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(msc,
                     ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
               // TODO 端口状态
               serverDatas.setServicePortState(telnet(listenAddress, listenPort) ? 0 : 1);
               // 获取cpu使用
               serverDatas.setCpuUsed(operatingSystemMXBean.getProcessCpuLoad());
               // 获取内存使用
               serverDatas.setMemoryUsed(operatingSystemMXBean.getFreePhysicalMemorySize() * 1.0
                     / operatingSystemMXBean.getTotalPhysicalMemorySize());
               connector1.close();
               connector1 = null;
            } else {
               logger.debug("jmx getServerData :"   listenAddress   " port:"   listenPort
                       " Unsupported JDK version: "   javaVersion);
               serverDatas.setCpuUsed(EmptyData.EMPTY_DOUBLE);
               serverDatas.setMemoryUsed(EmptyData.EMPTY_DOUBLE);
            }
         } catch (Exception e) {
            logger.error(e);
            if (connector1 != null) {
               try {
                  connector1.close();
               } catch (Exception ex) {
                  logger.error(ex);
               }
               connector1 = null;
            }
         }

         // 获取jvm空闲 <核实和api一样>
         Long heapFreePercent = getAttribute(JVMRuntime, "HeapFreeCurrent");
         serverDatas.setJvmFreeSize(heapFreePercent);
         // 获取jvm使用 <核实和api一样>
         Long heapFreeCurrent = getAttribute(JVMRuntime, "HeapSizeCurrent");
         serverDatas.setJvmUseSize(heapFreeCurrent - heapFreePercent);
         // 获取线程池运行时
         ObjectName threadPoolRuntime = getAttribute(serverRuntimes[j], "ThreadPoolRuntime");
         // 线程总数
         Integer executeThreadTotalCount = getAttribute(threadPoolRuntime, "ExecuteThreadTotalCount");
         // 空闲线程数 *
         Integer executeThreadIdleCount = getAttribute(threadPoolRuntime, "ExecuteThreadIdleCount");
         // 备用线程数
         Integer standbyThreadCount = getAttribute(threadPoolRuntime, "StandbyThreadCount");
         // 获取线程活动数
         Integer activeExeThreadCount = executeThreadTotalCount - standbyThreadCount;
         serverDatas.setActiveExeThreadCount(activeExeThreadCount);
         // 获取线程池执行线程数 <修改>
         Integer executeThreads = getAttribute(threadPoolRuntime, "ExecuteThreadTotalCount");
         serverDatas.setExecuteThreads(executeThreads);
         // 获取线程池空闲数
         serverDatas.setExecuteThreadIdleCount(executeThreadIdleCount);
         // 获取线程池等待数
         // 待处理用户请求计数 PendingUserRequestCount *
         Integer pendingUserRequestCount = getAttribute(threadPoolRuntime, "PendingUserRequestCount");
         serverDatas.setPendingUserRequestCount(pendingUserRequestCount);
         // TODO 占用的线程数
         Integer hoggingThreadCount = getAttribute(threadPoolRuntime, "HoggingThreadCount");
         serverDatas.setHoggingThreadCount(hoggingThreadCount);
         // 获取健康状态
         // 健康状态
         HealthState healthState = getAttribute(threadPoolRuntime, "HealthState");
         serverDatas.setHealthState(healthState.getState());
         // 状态 State xiachunbo add
         String state = getAttribute(serverRuntimes[j], "State");
         int runState = returnState(state);
         // 设置运行状态
         serverDatas.setRunState(runState);
         logger.debug("jmx getJDBCDataSourceRuntime "   listenAddress   " port:"   listenPort);
         // JDBC运行时 JDBCServiceRuntime
         ObjectName jdbcServiceRuntime = getAttribute(serverRuntimes[j], "JDBCServiceRuntime");
         ObjectName[] jdbcDataSourceRuntimeMBeans = getAttribute(jdbcServiceRuntime, "JDBCDataSourceRuntimeMBeans");
         List jdbcDatas = new ArrayList();
         for (int i = 0; i < jdbcDataSourceRuntimeMBeans.length; i  ) {
            ObjectName jdbcDataSourceRuntimeMBean = jdbcDataSourceRuntimeMBeans[i];
            CpWeblogicJdbcData jbdcData = new CpWeblogicJdbcData();
            // 服务ID
            jbdcData.setServerID(Integer.parseInt(String.valueOf(serverIDs.get(name))));
            // 队列名称
            // 数据源名称 Name
            String jbbcName = getAttribute(jdbcDataSourceRuntimeMBean, "Name");
            jbdcData.setJdbcName(jbbcName);
            // 连接数
            Integer currCapacity = getAttribute(jdbcDataSourceRuntimeMBean, "CurrCapacity");
            jbdcData.setCurrCapacity(currCapacity);
            // 使用数
            Integer activeConnectionsCurrentCount = getAttribute(jdbcDataSourceRuntimeMBean,
                  "ActiveConnectionsCurrentCount");
            jbdcData.setConnectionUsedCount(activeConnectionsCurrentCount);
            // 等待数
            Integer waitingForConnectionCurrentCount = getAttribute(jdbcDataSourceRuntimeMBean,
                  "WaitingForConnectionCurrentCount");
            jbdcData.setConnectionWaitingCount(waitingForConnectionCurrentCount);
            // 最大连接数
            Integer maxCapacity = getAttribute(jdbcDataSourceRuntimeMBean, "ConnectionsTotalCount");
            jbdcData.setMaxConnectionCount(maxCapacity);
            // TODO 数据源泄漏的连接数
            Integer leakedConnectionCount = getAttribute(jdbcDataSourceRuntimeMBean, "LeakedConnectionCount");
            jbdcData.setLeakedConnectionCount(leakedConnectionCount);
             // 数据源状态  
               Integer dataSourceState = getAttribute(jdbcDataSourceRuntimeMBean, "State");
               jbdcData.setDataSourceState(dataSourceState);
            jdbcDatas.add(jbdcData);
         }
         serverDatas.setCpWeblogicJdbcData(jdbcDatas);
         logger.debug("jmx getExecuteQueueRuntimes "   listenAddress   " port:"   listenPort);
         ObjectName[] executeQueueRuntimes = getAttribute(serverRuntimes[j], "ExecuteQueueRuntimes");
         List queueDatas = new ArrayList();
         for (int i = 0; i < executeQueueRuntimes.length; i  ) {
            CpWeblogicQueueData queueData = new CpWeblogicQueueData();
            ObjectName executeQueueRuntime = executeQueueRuntimes[i];
            queueData.setServerID(Integer.parseInt(String.valueOf(serverIDs.get(name))));
            // 队列的名称 Name
            String queueName = getAttribute(executeQueueRuntime, "Name");
            queueData.setQueueName(queueName);
            // 队列长度 **
            Integer queueLength = getAttribute(executeQueueRuntime, "ExecuteThreadTotalCount");
            // Long queueLength = (Long)
            // connection.getAttribute(executeQueueRuntime,"QueueLength");
            queueData.setQueueLength(queueLength.intValue());
            // 等待请求数
            Integer pendingRequestCurrentCount = getAttribute(executeQueueRuntime, "PendingRequestCurrentCount");
            queueData.setPendingRequestCurrentCount(pendingRequestCurrentCount);
            // 队列中最长的等待时间
            Long pendingTime = getAttribute(executeQueueRuntime, "PendingRequestOldestTime");
            queueData.setPendingRequestOldestTime(pendingTime.longValue() / 1000);
            // 空闲线程数
            Integer executeThreadCurrentIdleCount = getAttribute(executeQueueRuntime,
                  "ExecuteThreadCurrentIdleCount");
            queueData.setExecuteThreadCurrentIdleCount(executeThreadCurrentIdleCount);
            queueDatas.add(queueData);
         }
         serverDatas.setCpWeblogicQueueData(queueDatas);
         logger.debug("jmx getWebAppComponentRuntime -> AppDeployments"   listenAddress   " port:"   listenPort);
         ObjectName domainConfig = (ObjectName) connection.getAttribute(runtimeService, "DomainConfiguration");
         Integer administrationPort = getAttribute(domainConfig, "AdministrationPort");
         // 获得并显示当前部署的所有应用
         ObjectName[] applicationRuntimes = (ObjectName[]) connection.getAttribute(domainConfig, "AppDeployments");
         Map dataMap = new HashMap();
         List appDatas = new ArrayList();
         for (int i = 0; i < applicationRuntimes.length; i  ) {
            ObjectName applicationRuntime = applicationRuntimes[i];
            CpWeblogicAppData appData = new CpWeblogicAppData();
            appData.setServerID(Integer.parseInt(String.valueOf(serverIDs.get(name))));
            // 单元名 Name
            String appName = getAttribute(applicationRuntime, "Name").toString();
            appData.setName(appName);
            dataMap.put(appName, appData);
         }
         logger.debug(
               "jmx getWebAppComponentRuntime -> ApplicationRuntimes"   listenAddress   " port:"   listenPort);
         ObjectName[] applicationRuntime = getAttribute(serverRuntimes[j], "ApplicationRuntimes");
         for (int i = 0; i < applicationRuntime.length; i  ) {
            ObjectName application = applicationRuntime[i];
            ObjectName[] componentRuntimes = getAttribute(application, "ComponentRuntimes");
            for (int z = 0; z < componentRuntimes.length; z  ) {
               ObjectName componentRuntime = componentRuntimes[z];
               String componentType = getAttribute(componentRuntime, "Type");
               // web应用程序运行时组件 WebAppComponentRuntime
               if (componentType.equals("WebAppComponentRuntime")) {
                  // 单元名 Name
                  String appName = getAttribute(componentRuntime, "Name");
                  // Iterator keys = dataMap.keySet().iterator();
                  // while (keys.hasNext()) {
                  // String key = (String) keys.next();
                  if (!appName.contains(name   "_/"   "console") && !appName.contains(name   "_/"   "management")
                        && !appName.contains(name   "_/"   "bea_wls_internal")) {
                     logger.info("jmx getWebAppComponentRuntime -> ApplicationRuntimes"   listenAddress
                             " port:"   listenPort   "Oh my god. AppName "   appName);
                     CpWeblogicAppData appData = new CpWeblogicAppData();
                     appData.setName(appName);
                     appData.setServerID(Integer.parseInt(String.valueOf(serverIDs.get(name))));
                     // 部署状态 DeploymentState
                     Integer deploymentState = getAttribute(componentRuntime, "DeploymentState");
                     appData.setStatus(deploymentState);
                     // 应用健康状态 Status ***
                     String status = getAttribute(componentRuntime, "Status");
                     appData.setHealthStatus(deployedState(status));
                     // 应用类型 ***
                     appData.setType(0);
                     appDatas.add(appData);
                  }
                  // }
               }
            }
         }
         serverDatas.setCpWeblogicAppData(appDatas);
         packageDatas.add(serverDatas);
         // 在此处添加停止server状态
         List stopList = getServerStopConfig(serverRuntimes, false);
         for (int y = 0; y < stopList.size(); y  ) {
            if (!"".equals(serverIDs.get(stopList.get(y).getServerName()))
                  && serverIDs.get(stopList.get(y).getServerName()) != null) {
               CpWeblogicServerData serverStopDatas = new CpWeblogicServerData();
               serverStopDatas.setServerID(
                     Integer.parseInt(String.valueOf(serverIDs.get(stopList.get(y).getServerName()))));
               serverStopDatas.setRunState(returnState("SHUTTING_DOWN"));
               boolean ishave = false;
               for (int i = 0; i < packageDatas.size(); i  ) {
                  if (packageDatas.get(i).getServerID().equals(serverStopDatas.getServerID())) {
                     ishave = true;
                  }
               }
               if (!ishave) {
                  packageDatas.add(serverStopDatas);
               }
            }
         }
         logger.debug("jmx getServerData complete:"   listenAddress   " port:"   listenPort);
      }

      // 添加发送包根据serverId 进行去重逻辑
      packagedatas.setCpWeblogicServerData(packageDatas);
      if (weblogicRegisterModel.getIp() != null) {
         logger.info("jmx getWeblogicDatas Complete "   weblogicRegisterModel.getIp());
      } else {
         logger.info("jmx getWeblogicDatas Complete ");
      }
      return packagedatas;
   }

   private boolean IsJavaVersionSupported(String javaVersion) {
      if (StringUtils.isBlank(javaVersion)) {
         logger.debug("Unknown java version");
         return false;
      }
      String[] versionSplits = javaVersion.trim().split("\.");
      if (versionSplits.length < 3) {
         logger.error("Invalid Java version "   javaVersion   " expect x.x.x_");
         return false;
      }
      try {
         Integer mainVersion = Integer.parseInt(versionSplits[0]);
         Integer majorVersion = Integer.parseInt(versionSplits[1]);
         if (mainVersion.intValue() >= 1 && majorVersion.intValue() > 6) {
            return true;
         }
         logger.debug("Unsupported Java version "   javaVersion);
         return false;
      } catch (Exception ex) {
         logger.error(ex);
         return false;
      }
   }

   /**
    * queue 信息管理
    *
    * @throws AttributeNotFoundException
    * @throws InstanceNotFoundException
    * @throws MBeanException
    * @throws ReflectionException
    * @throws IOException
    */
   public Map>> getQueues(ObjectName[] serverRuntimes) {
      int length = (int) serverRuntimes.length;
      Map>> serversQueues = new HashMap>>();
      for (int j = 0; j < length; j  ) {
         List> dataList = new ArrayList>();
         Map queueMap = new HashMap();
         ObjectName[] executeQueueRuntimes = getAttribute(serverRuntimes[j], "ExecuteQueueRuntimes");
         // 队列的名称 Name
         String serverName = getAttribute(serverRuntimes[j], "Name");
         // 队列的名称 Name
         for (int i = 0; i < executeQueueRuntimes.length; i  ) {
            ObjectName executeQueueRuntime = executeQueueRuntimes[i];
            String queueName = getAttribute(executeQueueRuntime, "Name");
            queueMap.put("n", serverName   "."   queueName);
            dataList.add(queueMap);
         }
         serversQueues.put(serverName, dataList);
      }
      return serversQueues;
   }

   /**
    * 服务器运行时
    *
    * @param serverRuntime
    * @throws AttributeNotFoundException
    * @throws InstanceNotFoundException
    * @throws MBeanException
    * @throws ReflectionException
    * @throws IOException
    */
   public CpWeblogicServerConfig getServerConfig(ObjectName serverRuntime) throws AttributeNotFoundException,
         InstanceNotFoundException, MBeanException, ReflectionException, IOException {
      logger.info("jmx getServerRuntime");

      // 服务名称 Name
      String name = getAttribute(serverRuntime, "Name");
      ObjectName cluster = (ObjectName) connection.getAttribute(serverRuntime, "ClusterRuntime");
      String clusterName = "single";
      if (cluster != null) {
         clusterName = getAttribute(cluster, "Name");
      }
      clusterlist.put(name, clusterName);
      // 返回当前服务器监听连接的端口 ListenPort
      Integer listenPort = getAttribute(serverRuntime, "ListenPort");
      // 返回当前服务器监听连接的IP地址 ListenAddress <已修改 去掉host部分>
      String listenAddress = getAttribute(serverRuntime, "ListenAddress");
      if (listenAddress.indexOf("/") != -1) {
         String[] tempAddr = listenAddress.split("/");
         if (tempAddr.length == 1) {
            listenAddress = tempAddr[0];
         } else if (tempAddr[tempAddr.length - 1].trim().length() != 0) {
            listenAddress = tempAddr[tempAddr.length - 1];
         } else if (tempAddr.length > 2) {
            listenAddress = tempAddr[tempAddr.length - 2];
         }
         // listenAddress = listenAddress.split("/")[1];
      }
      // 状态 State
      String state = getAttribute(serverRuntime, "State");
      // 应用服务器的健康状态 HealthState
      CpWeblogicServerConfig serverConfigModel = new CpWeblogicServerConfig();
      if (!isIPAddress(listenAddress)) {
         String ip = hostToIp(listenAddress);
         if (!"".equals(ip)) {
            listenAddress = ip;
         }
      }
      // JVM运行时 JVMRuntime
      ObjectName JVMRuntime = getAttribute(serverRuntime, "JVMRuntime");
      // JavaVersion
      String javaVersion = getAttribute(JVMRuntime, "JavaVersion");
      // OSName
      String OSName = getAttribute(JVMRuntime, "OSName");
      serverConfigModel.setIsDeleted(0);
      serverConfigModel.setClusterName(clusterName);
      serverConfigModel.setJdkVersion(javaVersion);
      serverConfigModel.setServerIP(listenAddress);
      serverConfigModel.setServerName(name);
      serverConfigModel.setServerOS(OSName);
      serverConfigModel.setServerPort(listenPort);
      serverConfigModel.setServerType(name.contains("Admin") ? 0 : 1);
      serverConfigModel.setStatus(returnState(state));
      return serverConfigModel;
   }

   /**
    * domain 信息管理
    *
    * @throws AttributeNotFoundException
    * @throws InstanceNotFoundException
    * @throws MBeanException
    * @throws ReflectionException
    * @throws IOException
    */
   public String getdomain() {
      ObjectName domainConfiguration = getAttribute(runtimeService, "DomainConfiguration");
      String domain = (String) domainConfiguration.getKeyProperty("Location");
      return domain;
   }

   /**
    * 集群信息管理
    *
    * @throws AttributeNotFoundException
    * @throws InstanceNotFoundException
    * @throws MBeanException
    * @throws ReflectionException
    * @throws IOException
    */
   public List getClusterRuntime() throws AttributeNotFoundException, InstanceNotFoundException,
         MBeanException, ReflectionException, IOException {
      List clusterModelList = new ArrayList();
      logger.info("jmx getClusterRuntime");
      ObjectName domainConfig = (ObjectName) getAttribute(runtimeService, "DomainConfiguration");
      ObjectName[] clusterList = (ObjectName[]) getAttribute(domainConfig, "Clusters");
      int compLength = (int) clusterList.length;
      for (int y = 0; y < compLength; y  ) {
         try {
            ClusterModel clusterModel = new ClusterModel();
            clusterModel.setClusterName((String) connection.getAttribute(clusterList[y], "Name"));
            clusterModel.setClusterAddress((String) connection.getAttribute(clusterList[y], "ClusterAddress"));
            clusterModel.setClusterType((String) connection.getAttribute(clusterList[y], "ClusterType"));
            clusterModel.setDomainName((String) domainConfig.getKeyProperty("Location"));
            clusterModelList.add(clusterModel);
         } catch (Exception e) {
            e.printStackTrace();
         }
      }
      return clusterModelList;
   }

   public ObjectName[] getServerRuntimes() throws Exception {
      return (ObjectName[]) connection.getAttribute(runtimeService, "ServerRuntimes");
   }

   /**
    * 获取weblogic属性参数
    *
    * @param objectName
    * @param name
    * @return
    */
   @SuppressWarnings("unchecked")
   public  T getAttribute(ObjectName objectName, String name) {
      Object obj = null;
      try {
         obj = connection.getAttribute(objectName, name);
      } catch (Exception e) {

         e.printStackTrace();
      }
      return (T) obj;
   }

   /**
    * ObjName Mbean服务器实例 return 返回状态名
    */
   @SuppressWarnings("unused")
   private String returnState(int i) {
      String states = "";
      switch (i) {
      case 0:
         states = "OK";
         break;
      case 1:
         states = "Warning";
         break;
      case 2:
         states = "CRITICAL";
         break;
      case 3:
         states = "FAILED";
         break;
      case 4:
         states = "OVERLOADED";
         break;
      }
      return states;
   }

   /**
    * weblogic 地址
    *
    * @throws AttributeNotFoundException
    * @throws InstanceNotFoundException
    * @throws MBeanException
    * @throws ReflectionException
    * @throws IOException
    */
   public String getDomainPath(ObjectName serverRuntime) {
      String domainPath = getAttribute(serverRuntime, "MiddlewareHome");
      return domainPath;
   }

   /**
    * weblogic 版本
    *
    * @throws AttributeNotFoundException
    * @throws InstanceNotFoundException
    * @throws MBeanException
    * @throws ReflectionException
    * @throws IOException
    */
   public String getWeblogicVersion(ObjectName serverRuntime) {
      String weblogicVersion = getAttribute(serverRuntime, "WeblogicVersion");
      return weblogicVersion;
   }

   /**
    * weblogic 地址
    *
    * @throws AttributeNotFoundException
    * @throws InstanceNotFoundException
    * @throws MBeanException
    * @throws ReflectionException
    * @throws IOException
    */
   public String getWeblogicPath(ObjectName serverRuntime) {
      String weblogicPath = getAttribute(serverRuntime, "WeblogicHome");
      return weblogicPath;
   }

   /**
    * ObjName Mbean服务器实例 return 返回运行状态编号
    */
   @SuppressWarnings("unused")
   public int returnState(String str) {
      int states = 0;
      if (str.equals("ACTIVATE_LATER"))
         states = 1;
      if (str.equals("ADMIN"))
         states = 2;
      if (str.equals("FAILED"))
         states = 3;
      if (str.equals("FAILED_NOT_RESTARTABLE"))
         states = 4;
      if (str.equals("FAILED_RESTARTING"))
         states = 5;
      if (str.equals("FORCE_SHUTTING_DOWN"))
         states = 6;
      if (str.equals("FORCE_SUSPENDING"))
         states = 7;
      if (str.equals("RUNNING"))
         states = 8;
      if (str.equals("SHUTDOWN_IN_PROCESS"))
         states = 9;
      if (str.equals("SHUTDOWN_PENDING"))
         states = 10;
      if (str.equals("SHUTTING_DOWN"))
         states = 11;
      if (str.equals("STANDBY"))
         states = 12;
      if (str.equals("STARTING"))
         states = 13;
      if (str.equals("SUSPENDING"))
         states = 14;
      if (str.equals("UNKNOWN"))
         states = 15;
      return states;
   }

   /**
    * ObjName Mbean服务器实例 return 返回运行状态编号
    */
   @SuppressWarnings("unused")
   private int deployedState(String str) {
      int states = 0;
      if (str.equals("UNKNOWN"))
         states = 0;
      if (str.equals("DEPLOYED"))
         states = 1;
      if (str.equals("UNDEPLOYED"))
         states = 2;
      if (str.equals("ERROR"))
         states = 3;
      return states;
   }

   /**
    * 停止状态的主机数据比对 获取停止列表
    *
    * @param serverRT
    * @return
    */
   public List getServerStopConfig(ObjectName[] serverRT, boolean checkip) {
      List configs = new ArrayList();
      // 获取服务总量
      int length = (int) serverRT.length;
      Map map = new HashMap();
      for (int j = 0; j < length; j  ) {
         // 服务名称 Name
         String name = getAttribute(serverRT[j], "Name");
         map.put(name, name);
      }
      ObjectName domainConfig = (ObjectName) getAttribute(runtimeService, "DomainConfiguration");
      ObjectName[] serviceList = (ObjectName[]) getAttribute(domainConfig, "Servers");
      int compLength1 = (int) serviceList.length;
      for (int y = 0; y < compLength1; y  ) {
         // 服务名称 Name
         String name = getAttribute(serviceList[y], "Name");
         Integer serverPort = getAttribute(serviceList[y], "ListenPort");
         // 返回当前服务器监听连接的IP地址 ListenAddress <已修改 去掉host部分>
         String serverIP = getAttribute(serviceList[y], "ListenAddress");
         if (checkip) {
            if (!"".equals(serverIP) && serverIP != null) {
               if (serverIP.contains("/")) {
                  String[] tempAddr = serverIP.split("/");
                  if (tempAddr.length == 1) {
                     serverIP = tempAddr[0];
                  } else if (tempAddr[tempAddr.length - 1].trim().length() != 0) {
                     serverIP = tempAddr[tempAddr.length - 1];
                  } else if (tempAddr.length > 2) {
                     serverIP = tempAddr[tempAddr.length - 2];
                  }
                  // serverIP = serverIP.split("/")[1];
               }
               if (!isIPAddress(serverIP)) {
                  String ip = hostToIp(serverIP);
                  if (!"".equals(ip)) {
                     serverIP = ip;
                  } else {
                     continue;
                  }
               }
               if ("".equals(map.get(name)) || map.get(name) == null) {
                  CpWeblogicServerConfig config = new CpWeblogicServerConfig();
                  config.setServerName(name);
                  config.setServerIP(serverIP);
                  config.setServerPort(serverPort);
                  config.setServerType(1);
                  config.setStatus(returnState("SHUTTING_DOWN"));
                  configs.add(config);
               }
            }
         } else {
            if ("".equals(map.get(name)) || map.get(name) == null) {
               CpWeblogicServerConfig config = new CpWeblogicServerConfig();
               config.setServerName(name);
               config.setServerIP(serverIP);
               config.setServerPort(serverPort);
               config.setServerType(1);
               config.setStatus(returnState("SHUTTING_DOWN"));
               configs.add(config);
            }
         }
      }
      return configs;
   }

   private boolean isIPAddress(String ipaddr) {
      boolean flag = false;
      Pattern pattern = Pattern.compile(
            "\b((?!\d\d\d)\d |1\d\d|2[0-4]\d|25[0-5])\.((?!\d\d\d)\d |1\d\d|2[0-4]\d|25[0-5])\.((?!\d\d\d)\d |1\d\d|2[0-4]\d|25[0-5])\.((?!\d\d\d)\d |1\d\d|2[0-4]\d|25[0-5])\b");
      Matcher m = pattern.matcher(ipaddr);
      flag = m.matches();
      return flag;
   }

   public String hostToIp(String hostName) {
      String ip = "";
      InetAddress address = null;
      try {
         address = InetAddress.getByName(hostName);
         ip = address.getHostAddress();
         logger.info(address.getHostName()   " IP is = "   address.getHostAddress());
         return ip;
      } catch (Exception e) {
         ip = "";
         logger.info("hosts: "   e.getMessage()   "!");
         String masterPath = ConfigConstants.getMasterPrPath();
         masterPath = masterPath.replace(ConfigConstants.MASTER_PROPERTIES, "hosts.properties");
         Properties loadProperties = PropertiesUtil.LoadProperties(masterPath);
         if (loadProperties != null) {
            String serverIp = loadProperties.getProperty(hostName).trim();
            if ("".equals(serverIp) || serverIp == null) {
               serverIp = "";
               logger.info(hostName   " from host config result ip  is not find!");
            } else {
               logger.info(hostName   " from host config result ip is "   serverIp   "!");
            }
            ip = serverIp;
         }
      }
      return ip;
   }

   public void close() {
      if (connector != null) {
         try {
            connector.close();
         } catch (IOException e) {
            logger.error(e);
         }
      }
   }

   /** Check server host & port whether normal. */
   public boolean telnet(String host, int port) {
      Socket socket = new Socket();
      try {
         socket.setReceiveBufferSize(8049);
         socket.setSoTimeout(3000);
      } catch (Exception ex) {
         logger.error("Socket create failed.");
      }
      SocketAddress address = new InetSocketAddress(host, port);
      try {
         socket.connect(address, 3000);
         return true;
      } catch (IOException e) {
         logger.error("Telnet ["   host   ":"   port   "] has crash,please check it.");
         return false;
      } finally {
         if (socket != null) {
            try {
               socket.close();
               System.out.println("weblogic 连接关闭");
            } catch (IOException e) {
               logger.error("Close socket ["   host   ":"   port   "] has error.");
            }
         }
      }
   }

}

0 人点赞