Search in sources :

Example 6 with ClusterNode

use of com.openmeap.model.dto.ClusterNode in project OpenMEAP by OpenMEAP.

the class ApplicationManagementServlet method handleArchiveDownload.

private Result handleArchiveDownload(HttpServletRequest request, HttpServletResponse response) {
    Result res = new Result();
    Error err = new Error();
    res.setError(err);
    GlobalSettings settings = modelManager.getGlobalSettings();
    Map properties = this.getServicesWebProperties();
    String nodeKey = (String) properties.get("clusterNodeUrlPrefix");
    ClusterNode clusterNode = settings.getClusterNode(nodeKey);
    if (nodeKey == null || clusterNode == null) {
        // TODO: create a configuration error code
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage("A configuration is missing.  Please consult the error logs.");
        logger.error("For each node in the cluster, the property or environment variable OPENMEAP_CLUSTER_NODE_URL_PREFIX must match the \"Service Url Prefix\" value configured in the administrative interface.  This value is currently " + nodeKey + ".");
        return res;
    }
    String pathValidation = clusterNode.validateFileSystemStoragePathPrefix();
    if (pathValidation != null) {
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage("A configuration is missing.  Please consult the error logs.");
        logger.error("There is an issue with the location at \"File-system Storage Prefix\".  " + pathValidation);
        return res;
    }
    String hash = request.getParameter(UrlParamConstants.APPARCH_HASH);
    String hashAlg = request.getParameter(UrlParamConstants.APPARCH_HASH_ALG);
    String fileName = null;
    if (hash == null || hashAlg == null) {
        // look in the apps directory for the archive specified
        String appName = request.getParameter(UrlParamConstants.APP_NAME);
        String versionId = request.getParameter(UrlParamConstants.APP_VERSION);
        ApplicationVersion appVersion = modelManager.getModelService().findAppVersionByNameAndId(appName, versionId);
        if (appVersion == null) {
            String mesg = "The application version " + versionId + " was not found for application " + appName;
            err.setCode(ErrorCode.APPLICATION_VERSION_NOTFOUND);
            err.setMessage(mesg);
            logger.warn(mesg);
            return res;
        }
        String auth = request.getParameter(UrlParamConstants.AUTH_TOKEN);
        com.openmeap.model.dto.Application app = appVersion.getApplication();
        try {
            if (auth == null || !AuthTokenProvider.validateAuthToken(app.getProxyAuthSalt(), auth)) {
                err.setCode(ErrorCode.AUTHENTICATION_FAILURE);
                err.setMessage("The \"auth\" token presented is not recognized, missing, or empty.");
                return res;
            }
        } catch (DigestException e) {
            throw new GenericRuntimeException(e);
        }
        hash = appVersion.getArchive().getHash();
        hashAlg = appVersion.getArchive().getHashAlgorithm();
        fileName = app.getName() + " - " + appVersion.getIdentifier();
    } else {
        fileName = hashAlg + "-" + hash;
    }
    File file = ApplicationArchive.getFile(clusterNode.getFileSystemStoragePathPrefix(), hashAlg, hash);
    if (!file.exists()) {
        String mesg = "The application archive with " + hashAlg + " hash " + hash + " was not found.";
        // TODO: create an enumeration for this error
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage(mesg);
        logger.warn(mesg);
        return res;
    }
    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(file.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(file.length()).intValue());
        URLCodec codec = new URLCodec();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".zip\";");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        //if(outputStream!=null) {outputStream.close();}
        }
        response.flushBuffer();
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
    }
    return null;
}
Also used : ClusterNode(com.openmeap.model.dto.ClusterNode) ApplicationVersion(com.openmeap.model.dto.ApplicationVersion) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileNotFoundException(java.io.FileNotFoundException) Error(com.openmeap.protocol.dto.Error) GlobalSettings(com.openmeap.model.dto.GlobalSettings) IOException(java.io.IOException) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) FileNameMap(java.net.FileNameMap) FileInputStream(java.io.FileInputStream) Result(com.openmeap.protocol.dto.Result) URLCodec(org.apache.commons.codec.net.URLCodec) BufferedInputStream(java.io.BufferedInputStream) DigestException(com.openmeap.digest.DigestException) FileNameMap(java.net.FileNameMap) Map(java.util.Map) File(java.io.File)

Example 7 with ClusterNode

use of com.openmeap.model.dto.ClusterNode in project OpenMEAP by OpenMEAP.

the class AdminTest method testUpdateGlobalSettings.

public void testUpdateGlobalSettings() throws Exception {
    // correct location of storage path prefix
    GlobalSettings originalSettings = new GlobalSettings();
    originalSettings.setExternalServiceUrlPrefix(AdminTestHelper.SERVICES_WEB_URL);
    originalSettings.setMaxFileUploadSize(1234550);
    originalSettings.setServiceManagementAuthSalt(AdminTestHelper.SERVICES_WEB_AUTH_SALT);
    originalSettings.setTemporaryStoragePath(AdminTestHelper.ADMIN_WEB_STORAGE);
    // correct cluster node location and path prefix
    ClusterNode node = new ClusterNode();
    node.setServiceWebUrlPrefix(AdminTestHelper.NODE_01_SERVICES_URL);
    node.setFileSystemStoragePathPrefix(AdminTestHelper.NODE_01_STORAGE);
    originalSettings.addClusterNode(node);
    // validate settings stored in database
    String returnBody = Utils.readInputStream(helper.postGlobalSettings(originalSettings).getResponseBody(), FormConstants.CHAR_ENC_DEFAULT);
    logger.info(returnBody);
    modelManager.getModelService().clearPersistenceContext();
    GlobalSettings insertedSettings = modelManager.getGlobalSettings();
    JSONObjectBuilder job = new JSONObjectBuilder();
    String originalSettingsJSON = job.toJSON(originalSettings).toString(3);
    String insertedSettingsJSON = job.toJSON(insertedSettings).toString(3);
    logger.info("original: {}", originalSettingsJSON);
    logger.info("inserted: {}", insertedSettingsJSON);
    Assert.assertEquals(originalSettingsJSON, insertedSettingsJSON);
}
Also used : ClusterNode(com.openmeap.model.dto.ClusterNode) JSONObjectBuilder(com.openmeap.json.JSONObjectBuilder) GlobalSettings(com.openmeap.model.dto.GlobalSettings)

Example 8 with ClusterNode

use of com.openmeap.model.dto.ClusterNode in project OpenMEAP by OpenMEAP.

the class ClusterNodeHealthCheckThread method _run.

private void _run() {
    settings = modelManager.getGlobalSettings();
    JSONObjectBuilder builder = new JSONObjectBuilder();
    ClusterNodeRequest request = new ClusterNodeRequest();
    request.setSubject(ClusterNodeRequest.HEALTH_CHECK);
    lastCheckExceptions = new Vector<Exception>();
    while (true) {
        synchronized (this) {
            lastCheckExceptions.clear();
            if (settings.getClusterNodes() != null) {
                for (ClusterNode clusterNode : settings.getClusterNodes()) {
                    try {
                        request.setClusterNode(clusterNode);
                        HttpResponse response = null;
                        try {
                            response = httpRequestExecuter.postContent(clusterNode.getServiceWebUrlPrefix() + "/service-management/?action=" + ClusterNodeRequest.HEALTH_CHECK + "&auth=" + AuthTokenProvider.newAuthToken(settings.getServiceManagementAuthSalt()), builder.toJSON(request).toString(3), FormConstants.CONT_TYPE_JSON);
                        } catch (Exception e) {
                            logger.error(clusterNode.getServiceWebUrlPrefix() + " health check returned exception", e);
                            Throwable t = ExceptionUtils.getRootCause(e);
                            ClusterNode.Status err = null;
                            if (t instanceof ConnectException) {
                                err = ClusterNode.Status.CONNECT_ERROR;
                            } else {
                                err = ClusterNode.Status.ERROR;
                            }
                            synchronized (clusterNode) {
                                clusterNode.setLastStatus(err);
                                clusterNode.setLastStatusMessage(t.getMessage());
                                clusterNode.setLastStatusCheck(new Date());
                            }
                            if (response != null && response.getResponseBody() != null) {
                                Utils.consumeInputStream(response.getResponseBody());
                                response.getResponseBody().close();
                            }
                            continue;
                        }
                        if (response != null && response.getStatusCode() == 200) {
                            String json = Utils.readInputStream(response.getResponseBody(), FormConstants.CHAR_ENC_DEFAULT);
                            JSONObject jsonObj = new JSONObject(json);
                            Result result = (Result) builder.fromJSON(jsonObj, new Result());
                            response.getResponseBody().close();
                            synchronized (clusterNode) {
                                clusterNode.setLastStatus(result.getStatus() == Result.Status.SUCCESS ? ClusterNode.Status.GOOD : ClusterNode.Status.ERROR);
                                clusterNode.setLastStatusMessage(result.getMessage());
                                clusterNode.setLastStatusCheck(new Date());
                            }
                        } else {
                            synchronized (clusterNode) {
                                clusterNode.setLastStatus(ClusterNode.Status.ERROR);
                                String msg = "Service node " + clusterNode.getServiceWebUrlPrefix() + " returned a non-200 status code " + response.getStatusCode() + " " + Utils.readInputStream(response.getResponseBody(), FormConstants.CHAR_ENC_DEFAULT);
                                logger.error(msg);
                                clusterNode.setLastStatusMessage(msg);
                                response.getResponseBody().close();
                                clusterNode.setLastStatusCheck(new Date());
                            }
                        }
                    } catch (Exception e) {
                        logger.error("Exception performing health check", e);
                        lastCheckExceptions.add(e);
                    }
                }
            }
        }
        synchronized (lastCheckExceptions) {
            lastCheckExceptions.notifyAll();
        }
        try {
            Thread.sleep(checkInterval);
        } catch (InterruptedException e) {
            logger.error("Nap interrupted!", e);
        }
    }
}
Also used : ClusterNode(com.openmeap.model.dto.ClusterNode) HttpResponse(com.openmeap.http.HttpResponse) ClusterNodeRequest(com.openmeap.cluster.dto.ClusterNodeRequest) ConnectException(java.net.ConnectException) Date(java.util.Date) Result(com.openmeap.services.dto.Result) JSONObjectBuilder(com.openmeap.json.JSONObjectBuilder) JSONObject(com.openmeap.thirdparty.org.json.me.JSONObject) ConnectException(java.net.ConnectException)

Example 9 with ClusterNode

use of com.openmeap.model.dto.ClusterNode in project OpenMEAP by OpenMEAP.

the class ModelServiceRefreshNotifierTest method testHandlePostSaveOrUpdate.

@Test
public void testHandlePostSaveOrUpdate() throws Exception {
    try {
        new NonStrictExpectations() {

            {
            }
        };
    } catch (Exception e) {
    }
    ;
    MockHttpRequestExecuter.setResponseCode(200);
    MockHttpRequestExecuter.setResponseText("");
    MockHttpRequestExecuter httpExecuter = new MockHttpRequestExecuter();
    final ModelManager modelManager = new MockModelManager();
    final GlobalSettings globalSettings = new GlobalSettings();
    globalSettings.setServiceManagementAuthSalt(UUID.randomUUID().toString());
    ClusterNode clusterNode = new ClusterNode();
    clusterNode.setServiceWebUrlPrefix("http://www.openmeap.com/openmeap-services-web");
    globalSettings.addClusterNode(clusterNode);
    new NonStrictExpectations(globalSettings, modelManager) {

        {
            modelManager.getGlobalSettings();
            result = globalSettings;
        }
    };
    Application app = new Application();
    app.setName("Happy Name");
    app.setId(1L);
    ModelServiceRefreshNotifier notifier = new ModelServiceRefreshNotifier();
    notifier.setModelManager(modelManager);
    notifier.setHttpRequestExecuter(httpExecuter);
    notifier.notify(new ModelEntityModifyEvent(app), null);
    String lastPostUrl = MockHttpRequestExecuter.getLastPostUrl();
    Map<String, Object> lastPostData = MockHttpRequestExecuter.getLastPostData();
    String uri = lastPostUrl;
    String type = (String) lastPostData.get("type");
    String auth = (String) lastPostData.get("auth");
    String id = (String) lastPostData.get("id").toString();
    Assert.assertTrue(uri.equals("http://www.openmeap.com/openmeap-services-web/service-management/"));
    Assert.assertTrue(id.equals("1"));
    Assert.assertTrue(type.equals("Application"));
    Assert.assertTrue(AuthTokenProvider.validateAuthToken(globalSettings.getServiceManagementAuthSalt(), auth));
}
Also used : ClusterNode(com.openmeap.model.dto.ClusterNode) GlobalSettings(com.openmeap.model.dto.GlobalSettings) ModelManager(com.openmeap.model.ModelManager) MockHttpRequestExecuter(com.openmeap.util.MockHttpRequestExecuter) NonStrictExpectations(mockit.NonStrictExpectations) Application(com.openmeap.model.dto.Application) ModelEntityModifyEvent(com.openmeap.model.event.ModelEntityModifyEvent) Test(org.junit.Test)

Aggregations

ClusterNode (com.openmeap.model.dto.ClusterNode)9 GlobalSettings (com.openmeap.model.dto.GlobalSettings)7 JSONObject (com.openmeap.thirdparty.org.json.me.JSONObject)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 JSONObjectBuilder (com.openmeap.json.JSONObjectBuilder)2 InvalidPropertiesException (com.openmeap.model.InvalidPropertiesException)2 Result (com.openmeap.services.dto.Result)2 GenericRuntimeException (com.openmeap.util.GenericRuntimeException)2 Date (java.util.Date)2 PersistenceException (javax.persistence.PersistenceException)2 Test (org.junit.Test)2 ClusterNodeRequest (com.openmeap.cluster.dto.ClusterNodeRequest)1 DigestException (com.openmeap.digest.DigestException)1 EventNotificationException (com.openmeap.event.EventNotificationException)1 MessagesEvent (com.openmeap.event.MessagesEvent)1 ProcessingEvent (com.openmeap.event.ProcessingEvent)1 HttpResponse (com.openmeap.http.HttpResponse)1 ModelManager (com.openmeap.model.ModelManager)1 Application (com.openmeap.model.dto.Application)1