CSC to provide a view of DPN re-sync
[openflowplugin.git] / openflowjava / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / util / JMXOperationsUtil.java
1 /*
2  * Copyright (c) 2019 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.openflowjava.protocol.impl.util;
10
11 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
12 import java.lang.management.ManagementFactory;
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17 import javax.management.InstanceNotFoundException;
18 import javax.management.MBeanException;
19 import javax.management.MBeanServer;
20 import javax.management.MalformedObjectNameException;
21 import javax.management.ObjectName;
22 import javax.management.ReflectionException;
23 import org.apache.commons.codec.binary.Base64;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * Created by efiijjp on 10/19/2014.
29  */
30 @SuppressWarnings("IllegalCatch")
31 public class JMXOperationsUtil {
32
33     private static final Logger LOG = LoggerFactory.getLogger(JMXOperationsUtil.class);
34     private static final String JMX_REST_HTTP_OPERATION = "GET";
35     //private static final String JMX_REST_HTTP_JOLOKIA_BASE_URI = "/controller/nb/v2/jolokia/exec/";
36     private static final String JMX_REST_HTTP_JOL_OKIA_BASE_URI = "/jolokia/exec/";
37     private static final String JMX_REST_HTTP_AUTH_UNAME_PWD = "admin:admin";
38     private static final String JMX_REST_HTTP_PORT = "8181";
39     private static final int TIME_OUT = 5000;
40
41     protected JMXOperationsUtil(){
42     }
43
44     public static String invokeLocalJMXOperation(String objectName, String operationToExec) {
45         LOG.debug("invokeLocalJMXOperation - ObjectName : {} , operation : {}", objectName, operationToExec);
46         MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
47         LOG.debug("invokeLocalJMXOperation - MBS instance retrieved ! ");
48         Object result = null;
49         String resultStr = "JMX ERROR";
50         if (mbs != null) {
51             try {
52                 result = mbs.invoke(new ObjectName(objectName), operationToExec, null, null);
53                 if (result != null) {
54                     resultStr = (String)result;
55                     LOG.debug("invokeLocalJMXOperation - result is {}", resultStr);
56                 }
57                 else {
58                     LOG.debug("invokeLocalJMXOperation - result is NULL");
59                 }
60             }
61             catch (MalformedObjectNameException monEx) {
62                 LOG.error("Error accesing Local MBean {} and Service {}", objectName, operationToExec, monEx);
63                 resultStr = "CRITICAL EXCEPTION : Malformed Object Name Exception";
64             }
65             catch (MBeanException mbEx) {
66                 LOG.error("Error accesing Local MBean {} and Service {}", objectName, operationToExec, mbEx);
67                 resultStr = "CRITICAL EXCEPTION : MBean Exception";
68             }
69             catch (InstanceNotFoundException infEx) {
70                 resultStr = "Diag Status Service Down";
71             }
72             catch (ReflectionException rEx) {
73                 LOG.error("Error accesing Local MBean {} and Service {}", objectName, operationToExec, rEx);
74                 resultStr = "CRITICAL EXCEPTION : Reflection Exception";
75             }
76         }
77         return resultStr;
78     }
79
80     @SuppressFBWarnings("DM_DEFAULT_ENCODING")
81     public static String invokeRemoteJMXOperationREST(String host, String mbeanName,
82                                                       String operation) throws Exception {
83         int httpResponseCode = 400;
84         String restUrl = buildRemoteJMXReSTUrl(host, mbeanName, operation);
85         String respStr = "ERROR accessing JMX URL - " + restUrl;
86         LOG.info("invokeRemoteJMXOperationREST : REST JMX URL - {}", restUrl);
87         try {
88             HTTPRequest request = new HTTPRequest();
89             request.setUri(restUrl);
90             request.setMethod(JMX_REST_HTTP_OPERATION);
91             request.setTimeout(TIME_OUT);
92             // To compensate for respond
93             // within default timeout during
94             // IT so setting an indefinite
95             // timeout till the issue is
96             // sorted out
97
98             Map<String, List<String>> headers = new HashMap<String, List<String>>();
99             String authString = JMX_REST_HTTP_AUTH_UNAME_PWD;
100             byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
101             String authStringEnc = new String(authEncBytes);
102             List<String> header = new ArrayList<String>();
103             header.add("Basic " + authStringEnc);
104             headers.put("Authorization", header);
105             header = new ArrayList<String>();
106             header.add("application/json");
107             headers.put("Accept", header);
108             request.setHeaders(headers);
109             request.setContentType("application/json");
110             LOG.debug("invokeRemoteJMXOperationREST : sending request ... ");
111             HTTPResponse response = HTTPClient.sendRequest(request);
112             LOG.debug("invokeRemoteJMXOperationREST : response received ... ");
113             // Response code for success should be 2xx
114             httpResponseCode = response.getStatus();
115             LOG.debug("invokeRemoteJMXOperationREST : HTTP Response code is - {}", httpResponseCode);
116             if (httpResponseCode > 299) {
117                 LOG.error("invokeRemoteJMXOperationREST : Non-200 HTTP Response code is  {} for URL {}",
118                         httpResponseCode, restUrl);
119                 return respStr + " HTTP Response Code : " + Integer.toString(httpResponseCode);
120             }
121             LOG.debug("invokeRemoteJMXOperationREST : HTTP Response is - {} for URL {}", response.getEntity(), restUrl);
122             respStr = response.getEntity();
123         } catch (Exception e) {
124             LOG.error("Error accesing URL {}", restUrl, e);
125             throw e;
126         }
127         return respStr;
128     }
129
130     @SuppressFBWarnings("DM_DEFAULT_ENCODING")
131     public static String invokeRemoteJMXOperationREST(String host, String mbeanName, String operation,
132                                                       List<String> operationArgs) throws Exception {
133         // initialize response code to indicate error
134         int httpResponseCode = 400;
135         String restUrl = buildRemoteJMXReSTUrlWithMultipleArg(host, mbeanName, operation, operationArgs);
136         String respStr = "ERROR accessing JMX URL - " + restUrl;
137         LOG.info("invokeRemoteJMXOperationRESTWithArg : REST JMX URL - {}", restUrl);
138         try {
139             HTTPRequest request = new HTTPRequest();
140             request.setUri(restUrl);
141             request.setMethod(JMX_REST_HTTP_OPERATION);
142             request.setTimeout(TIME_OUT);
143             // To compensate for respond
144             // within default timeout during
145             // IT so setting an indefinite
146             // timeout till the issue is
147             // sorted out
148             Map<String, List<String>> headers = new HashMap<String, List<String>>();
149             String authString = JMX_REST_HTTP_AUTH_UNAME_PWD;
150             byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
151             String authStringEnc = new String(authEncBytes);
152             List<String> header = new ArrayList<String>();
153             header.add("Basic " + authStringEnc);
154             headers.put("Authorization", header);
155             header = new ArrayList<String>();
156             header.add("application/json");
157             headers.put("Accept", header);
158             request.setHeaders(headers);
159             request.setContentType("application/json");
160             LOG.debug("invokeRemoteJMXOperationRESTWithArg : sending request ... ");
161             HTTPResponse response = HTTPClient.sendRequest(request);
162             LOG.debug("invokeRemoteJMXOperationREST : response received ... ");
163             // Response code for success should be 2xx
164             httpResponseCode = response.getStatus();
165             LOG.debug("invokeRemoteJMXOperationRESTWithArg : HTTP Response code is - {}", httpResponseCode);
166             if (httpResponseCode > 299) {
167                 LOG.error("invokeRemoteJMXOperationRESTWithArg : Non-200 HTTP Response code is  {} for URL {}",
168                         httpResponseCode, restUrl);
169                 return respStr + " HTTP Response Code : " + Integer.toString(httpResponseCode);
170             }
171             LOG.debug("invokeRemoteJMXOperationRESTWithArg : HTTP Response is - {} for URL {}",
172                     response.getEntity(), restUrl);
173             respStr = response.getEntity();
174         } catch (Exception e) {
175             LOG.error("Error accesing URL {}", restUrl, e);
176             throw e;
177         }
178         return respStr;
179     }
180
181     private static String buildRemoteJMXReSTUrl(String host, String mbeanName, String operation) {
182         return "http:/" + host + ":" + JMX_REST_HTTP_PORT + JMX_REST_HTTP_JOL_OKIA_BASE_URI + mbeanName + "/"
183                 + operation;
184     }
185
186     private static String buildRemoteJMXReSTUrlWithMultipleArg(String host, String mbeanName, String operation,
187                                                                List<String> args) {
188         StringBuilder jmxUrl = new StringBuilder();
189         jmxUrl.append("http:/" + host + ":" + JMX_REST_HTTP_PORT + JMX_REST_HTTP_JOL_OKIA_BASE_URI + mbeanName + "/"
190                 + operation);
191         for (String str : args) {
192             jmxUrl.append("/").append(str);
193         }
194         return jmxUrl.toString();
195     }
196
197     public static String execRemoteJMXOperation(String jmxServiceObjectName, String invokeCommand, String ipAddress,
198                                                 List args) throws Exception {
199         String operationResult;
200         try {
201             LOG.debug("runClusterwideCommand : Peer cluster address : {}", ipAddress);
202             if (args != null && !args.isEmpty()) {
203                 operationResult = JMXOperationsUtil.invokeRemoteJMXOperationREST(ipAddress, jmxServiceObjectName,
204                         invokeCommand, args);
205             }
206             else {
207                 operationResult = JMXOperationsUtil.invokeRemoteJMXOperationREST(ipAddress, jmxServiceObjectName,
208                         invokeCommand);
209             }
210             LOG.debug("runClusterwideCommand : Remote JMX Response successful: {}", operationResult);
211         }
212         catch (Exception ex) {
213             LOG.error("runClusterwideCommand : Error Invoking REST on Remote Node ", ex);
214             throw ex;
215         }
216         return operationResult;
217     }
218 }