Search in sources :

Example 1 with J4pException

use of org.jolokia.client.exception.J4pException in project opennms by OpenNMS.

the class JolokiaBeanMonitor method poll.

/**
 * {@inheritDoc}
 *
 * Poll the specified address for service availability.
 *
 * During the poll an attempt is made to execute the named method (with
 * optional input) connect on the specified port. If the exec on request is
 * successful, the banner line generated by the interface is parsed and if
 * the banner text indicates that we are talking to Provided that the
 * interface's response is valid we set the service status to
 * SERVICE_AVAILABLE and return.
 */
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // 
    // Process parameters
    // 
    // 
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Port
    int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
    // URL
    String strURL = ParameterMap.getKeyedString(parameters, PARAMETER_URL, DEFAULT_URL);
    // Username
    String strUser = ParameterMap.getKeyedString(parameters, PARAMETER_USERNAME, null);
    // Password
    String strPasswd = ParameterMap.getKeyedString(parameters, PARAMETER_PASSWORD, null);
    // AttrName
    String strAttrName = ParameterMap.getKeyedString(parameters, PARAMETER_ATTRNAME, null);
    // AttrPath
    String strAttrPath = ParameterMap.getKeyedString(parameters, PARAMETER_ATTRPATH, null);
    // BeanName
    String strBeanName = ParameterMap.getKeyedString(parameters, PARAMETER_BEANNAME, null);
    // MethodName
    String strMethodName = ParameterMap.getKeyedString(parameters, PARAMETER_METHODNAME, null);
    // Optional Inputs
    String strInput1 = ParameterMap.getKeyedString(parameters, PARAMETER_METHODINPUT1, null);
    String strInput2 = ParameterMap.getKeyedString(parameters, PARAMETER_METHODINPUT2, null);
    // BannerMatch
    String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);
    // Get the address instance.
    InetAddress ipAddr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOGGER.debug("poll: address = " + hostAddress + ", port = " + port + ", " + tracker);
    strURL = strURL.replace("${ipaddr}", hostAddress);
    strURL = strURL.replace("${port}", ((Integer) port).toString());
    LOGGER.debug("poll: final URL address = " + strURL);
    // Give it a whirl
    PollStatus serviceStatus = PollStatus.unknown("Initialized");
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        try {
            tracker.startAttempt();
            J4pClientBuilder j4pClientBuilder = new J4pClientBuilder();
            j4pClientBuilder.url(strURL).connectionTimeout(tracker.getConnectionTimeout()).socketTimeout(tracker.getSoTimeout());
            if (strUser != null && strPasswd != null) {
                j4pClientBuilder.user(strUser).password(strPasswd);
            }
            J4pClient j4pClient = j4pClientBuilder.build();
            LOGGER.debug("JolokiaBeanMonitor: connected to URLhost: " + strURL);
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            if (strBannerMatch == null || strBannerMatch.length() == 0 || strBannerMatch.equals("*")) {
                serviceStatus = PollStatus.available(tracker.elapsedTimeInMillis());
                break;
            }
            // Exec a method or poll an attribute?
            String response;
            if (strAttrName != null) {
                J4pReadRequest readReq = new J4pReadRequest(strBeanName, strAttrName);
                readReq.setPreferredHttpMethod("POST");
                if (strAttrPath != null) {
                    readReq.setPath(strAttrPath);
                }
                J4pReadResponse resp = j4pClient.execute(readReq);
                response = resp.getValue().toString();
            } else {
                J4pExecRequest execReq;
                // Default Inputs
                if (strInput1 == null && strInput2 == null) {
                    LOGGER.debug("JolokiaBeanMonitor - execute bean: " + strBeanName + " method: " + strMethodName);
                    execReq = new J4pExecRequest(strBeanName, strMethodName);
                } else if (strInput1 != null && strInput2 == null) {
                    // Single Input
                    LOGGER.debug("JolokiaBeanMonitor - execute bean: " + strBeanName + " method: " + strMethodName + " args: " + strInput1);
                    execReq = new J4pExecRequest(strBeanName, strMethodName, strInput1);
                } else {
                    // Double Input
                    LOGGER.debug("JolokiaBeanMonitor - execute bean: " + strBeanName + " method: " + strMethodName + " args: " + strInput1 + " " + strInput2);
                    execReq = new J4pExecRequest(strBeanName, strMethodName, strInput1, strInput2);
                }
                execReq.setPreferredHttpMethod("POST");
                J4pExecResponse resp = j4pClient.execute(execReq);
                response = resp.getValue().toString();
            }
            double responseTime = tracker.elapsedTimeInMillis();
            if (response == null) {
                continue;
            }
            LOGGER.debug("poll: banner = " + response);
            LOGGER.debug("poll: responseTime = " + responseTime + "ms");
            // Could it be a regex?
            if (strBannerMatch.charAt(0) == '~') {
                if (!response.matches(strBannerMatch.substring(1))) {
                    serviceStatus = PollStatus.unavailable("Banner does not match Regex '" + strBannerMatch + "'");
                } else {
                    serviceStatus = PollStatus.available(responseTime);
                }
            } else {
                if (response.contains(strBannerMatch)) {
                    serviceStatus = PollStatus.available(responseTime);
                } else {
                    serviceStatus = PollStatus.unavailable("Did not find expected Text '" + strBannerMatch + "'");
                }
            }
        } catch (J4pConnectException e) {
            String reason = "Connection exception for address: " + ipAddr + ":" + port + " " + e.getMessage();
            LOGGER.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } catch (J4pRemoteException e) {
            String reason = "Remote exception from J4pRemote: " + e.getMessage();
            LOGGER.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (MalformedObjectNameException e) {
            String reason = "Parameters for Jolokia are malformed: " + e.getMessage();
            LOGGER.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (J4pException e) {
            String reason = J4pException.class.getSimpleName() + " during Jolokia monitor call: " + e.getMessage();
            LOGGER.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        }
    }
    return serviceStatus;
}
Also used : MalformedObjectNameException(javax.management.MalformedObjectNameException) PollStatus(org.opennms.netmgt.poller.PollStatus) J4pReadRequest(org.jolokia.client.request.J4pReadRequest) J4pExecRequest(org.jolokia.client.request.J4pExecRequest) J4pConnectException(org.jolokia.client.exception.J4pConnectException) J4pClient(org.jolokia.client.J4pClient) J4pRemoteException(org.jolokia.client.exception.J4pRemoteException) J4pReadResponse(org.jolokia.client.request.J4pReadResponse) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) J4pException(org.jolokia.client.exception.J4pException) J4pClientBuilder(org.jolokia.client.J4pClientBuilder) J4pExecResponse(org.jolokia.client.request.J4pExecResponse) InetAddress(java.net.InetAddress)

Example 2 with J4pException

use of org.jolokia.client.exception.J4pException in project fabric8 by jboss-fuse.

the class DeployToProfileMojo method uploadProfileConfigFile.

protected void uploadProfileConfigFile(J4pClient client, DeployResults results, File rootDir, File configFile) throws MojoExecutionException, J4pException, IOException, MalformedObjectNameException {
    String profileId = results.getProfileId();
    String versionId = results.getVersionId();
    if (Strings.isNullOrBlank(profileId)) {
        throw new MojoExecutionException("Cannot upload configuration file " + configFile + " to profile as the profileId was not returned");
    }
    if (Strings.isNullOrBlank(versionId)) {
        throw new MojoExecutionException("Cannot upload configuration file " + configFile + " to profile as the versionId was not returned");
    }
    String relativePath = Files.getRelativePath(rootDir, configFile);
    if (relativePath.startsWith("/"))
        relativePath = relativePath.substring(1);
    // the path should use forward slash only as we use forward slashes in fabric profiles
    relativePath = Files.normalizePath(relativePath, '\\', '/');
    String configFileContents = loadFilteredConfigFile(configFile);
    if (configFileContents == null) {
        getLog().debug(String.format("Filtered copy of the config file %s not found. Using the original file.", configFile));
        configFileContents = Files.toString(configFile);
    }
    String expandedConfig = expandPlaceholders(configFileContents);
    String data = Base64Encoder.encode(expandedConfig);
    String mbeanName = "io.fabric8:type=Fabric";
    getLog().info("Uploading file " + relativePath + " to invoke mbean " + mbeanName + " on jolokia URL: " + jolokiaUrl + " with user: " + fabricServer.getUsername());
    try {
        J4pExecRequest request = new J4pExecRequest(mbeanName, "setConfigurationFile", versionId, profileId, relativePath, data);
        J4pResponse<J4pExecRequest> response = client.execute(request, "POST");
        Object value = response.getValue();
        if (value != null) {
            getLog().info("Upload returned result: " + value);
        }
    } catch (J4pException e) {
        if (e.getMessage().contains(".InstanceNotFoundException")) {
            throw new MojoExecutionException("Could not find the mbean " + mbeanName + " in the JVM for " + jolokiaUrl + ". Are you sure this JVM is running the Fabric8 console?");
        } else {
            throw e;
        }
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) J4pExecRequest(org.jolokia.client.request.J4pExecRequest) J4pException(org.jolokia.client.exception.J4pException)

Example 3 with J4pException

use of org.jolokia.client.exception.J4pException in project fabric8 by jboss-fuse.

the class DeployToProfileMojo method getMavenUploadUri.

protected String getMavenUploadUri(J4pClient client) throws MalformedObjectNameException, J4pException, MojoExecutionException {
    Exception exception = null;
    try {
        J4pSearchResponse searchResponse = client.execute(new J4pSearchRequest(FABRIC_MBEAN));
        List<String> mbeanNames = searchResponse.getMBeanNames();
        if (mbeanNames == null || mbeanNames.isEmpty()) {
            getLog().warn("No MBean " + FABRIC_MBEAN + " found, are you sure you have created a fabric in this JVM?");
            return null;
        }
        J4pResponse<J4pReadRequest> request = client.execute(new J4pReadRequest(FABRIC_MBEAN, "MavenRepoUploadURI"));
        Object value = request.getValue();
        if (value != null) {
            String uri = value.toString();
            if (uri.startsWith("http")) {
                return uri;
            } else {
                getLog().warn("Could not find the Maven upload URI. Got: " + value);
            }
        } else {
            getLog().warn("Could not find the Maven upload URI");
        }
    } catch (J4pConnectException e) {
        String message = "Could not connect to jolokia on " + jolokiaUrl + " using user: " + fabricServer.getUsername() + ".\nAre you sure you are running a fabric8 container?";
        getLog().error(message);
        throw new MojoExecutionException(message, e);
    } catch (J4pRemoteException e) {
        int status = e.getStatus();
        if (status == 401) {
            String message = "Status 401: Unauthorized to access: " + jolokiaUrl + " using user: " + fabricServer.getUsername();
            if (!customUsernameAndPassword) {
                message += ".\nHave you created a Fabric?\nHave you setup your ~/.m2/settings.xml with the correct user and password for server ID: " + serverId + " and do the user/password match the server " + jolokiaUrl + "?";
            }
            getLog().error(message);
            throw new MojoExecutionException(message, e);
        } else if (status == 404) {
            String message = "Status 404: Resource not found: " + jolokiaUrl + ".\nHave you created a Fabric?";
            getLog().error(message);
            throw new MojoExecutionException(message, e);
        } else {
            exception = e;
        }
    } catch (J4pException e) {
        // it may be an empty response which is like a 404
        boolean is404 = "Could not parse answer: Unexpected token END OF FILE at position 0.".equals(e.getMessage());
        if (is404) {
            String message = "Status 404: Resource not found: " + jolokiaUrl + ".\nHave you created a Fabric?";
            getLog().error(message);
            throw new MojoExecutionException(message, e);
        } else {
            exception = e;
        }
    }
    if (exception != null) {
        getLog().error("Failed to get maven repository URI from " + jolokiaUrl + ". " + exception, exception);
        throw new MojoExecutionException("Could not find the Maven Upload Repository URI");
    } else {
        throw new MojoExecutionException("Could not find the Maven Upload Repository URI");
    }
}
Also used : J4pRemoteException(org.jolokia.client.exception.J4pRemoteException) J4pReadRequest(org.jolokia.client.request.J4pReadRequest) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) J4pConnectException(org.jolokia.client.exception.J4pConnectException) J4pException(org.jolokia.client.exception.J4pException) J4pSearchRequest(org.jolokia.client.request.J4pSearchRequest) MalformedObjectNameException(javax.management.MalformedObjectNameException) J4pRemoteException(org.jolokia.client.exception.J4pRemoteException) ArtifactDeploymentException(org.apache.maven.artifact.deployer.ArtifactDeploymentException) J4pConnectException(org.jolokia.client.exception.J4pConnectException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) J4pException(org.jolokia.client.exception.J4pException) J4pSearchResponse(org.jolokia.client.request.J4pSearchResponse)

Example 4 with J4pException

use of org.jolokia.client.exception.J4pException in project fabric8 by jboss-fuse.

the class ProfileFacade method getFieldValue.

@SuppressWarnings("unchecked")
private static <T extends Object> T getFieldValue(J4pClient j4p, String operation, String versionId, String id, String field) {
    T rc = null;
    try {
        J4pExecRequest request = Helpers.createExecRequest(operation, versionId, id, Helpers.toList(field));
        J4pExecResponse response = j4p.execute(request);
        Map<String, Object> value = response.getValue();
        rc = (T) value.get(field);
    } catch (MalformedObjectNameException e) {
        throw new RuntimeException("Failed to get container field", e);
    } catch (J4pException e) {
        throw new RuntimeException("Failed to get container field", e);
    }
    return rc;
}
Also used : MalformedObjectNameException(javax.management.MalformedObjectNameException) J4pExecRequest(org.jolokia.client.request.J4pExecRequest) J4pException(org.jolokia.client.exception.J4pException) J4pExecResponse(org.jolokia.client.request.J4pExecResponse)

Example 5 with J4pException

use of org.jolokia.client.exception.J4pException in project fabric8 by jboss-fuse.

the class JolokiaInvocationHandler method invoke.

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String name = method.getName();
    String attribute;
    AbtractJ4pMBeanRequest request;
    if ((attribute = getterAttributeName(method)) != null) {
        request = new J4pReadRequest(objectName, attribute);
    } else if ((attribute = setterAttributeName(method)) != null) {
        request = new J4pWriteRequest(objectName, attribute, args[0]);
    } else {
        name = executeMethodName(method);
        if (args == null | method.getParameterTypes().length == 0) {
            request = new J4pExecRequest(objectName, name);
        } else {
            request = new J4pExecRequest(objectName, name, args);
        }
    }
    try {
        request.setPreferredHttpMethod("POST");
        J4pResponse response = jolokia.execute(request);
        Object value = response.getValue();
        return JolokiaClients.convertJolokiaToJavaType(method.getReturnType(), value);
    } catch (J4pException e) {
        List<Object> argsList = args == null ? null : Arrays.asList(args);
        LOG.warn("Failed to invoke " + objectName + " method: " + name + " with arguments: " + argsList + ". " + e, e);
        throw e;
    }
}
Also used : J4pReadRequest(org.jolokia.client.request.J4pReadRequest) J4pWriteRequest(org.jolokia.client.request.J4pWriteRequest) J4pExecRequest(org.jolokia.client.request.J4pExecRequest) J4pException(org.jolokia.client.exception.J4pException) List(java.util.List) AbtractJ4pMBeanRequest(org.jolokia.client.request.AbtractJ4pMBeanRequest) J4pResponse(org.jolokia.client.request.J4pResponse)

Aggregations

J4pException (org.jolokia.client.exception.J4pException)6 J4pExecRequest (org.jolokia.client.request.J4pExecRequest)5 J4pReadRequest (org.jolokia.client.request.J4pReadRequest)4 MalformedObjectNameException (javax.management.MalformedObjectNameException)3 List (java.util.List)2 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 J4pConnectException (org.jolokia.client.exception.J4pConnectException)2 J4pRemoteException (org.jolokia.client.exception.J4pRemoteException)2 AbtractJ4pMBeanRequest (org.jolokia.client.request.AbtractJ4pMBeanRequest)2 J4pExecResponse (org.jolokia.client.request.J4pExecResponse)2 J4pResponse (org.jolokia.client.request.J4pResponse)2 J4pWriteRequest (org.jolokia.client.request.J4pWriteRequest)2 IOException (java.io.IOException)1 InetAddress (java.net.InetAddress)1 MalformedURLException (java.net.MalformedURLException)1 ArtifactDeploymentException (org.apache.maven.artifact.deployer.ArtifactDeploymentException)1 MojoFailureException (org.apache.maven.plugin.MojoFailureException)1 J4pClient (org.jolokia.client.J4pClient)1 J4pClientBuilder (org.jolokia.client.J4pClientBuilder)1 J4pReadResponse (org.jolokia.client.request.J4pReadResponse)1