Search in sources :

Example 1 with DeviceCommandOutput

use of org.eclipse.kapua.service.device.management.command.DeviceCommandOutput in project kapua by eclipse.

the class UploadRequest method doPostCommand.

private void doPostCommand(KapuaFormFields kapuaFormFields, HttpServletResponse resp) throws ServletException, IOException {
    try {
        List<FileItem> fileItems = kapuaFormFields.getFileItems();
        final String scopeIdString = kapuaFormFields.get("scopeIdString");
        final String deviceIdString = kapuaFormFields.get("deviceIdString");
        final String command = kapuaFormFields.get("command");
        final String password = kapuaFormFields.get("password");
        final String timeoutString = kapuaFormFields.get("timeout");
        if (scopeIdString == null || scopeIdString.isEmpty()) {
            throw new IllegalArgumentException("scopeId");
        }
        if (deviceIdString == null || deviceIdString.isEmpty()) {
            throw new IllegalArgumentException("deviceId");
        }
        if (command == null || command.isEmpty()) {
            throw new IllegalArgumentException("command");
        }
        if (fileItems.size() > 1) {
            throw new IllegalArgumentException("file");
        }
        Integer timeout = null;
        if (timeoutString != null && !timeoutString.isEmpty()) {
            try {
                timeout = Integer.parseInt(timeoutString);
            } catch (NumberFormatException nfe) {
                throw new IllegalArgumentException("timeout");
            }
        }
        KapuaLocator locator = KapuaLocator.getInstance();
        DeviceCommandManagementService deviceService = locator.getService(DeviceCommandManagementService.class);
        // FIXME: set a max size on the MQtt payload
        byte[] data = fileItems.size() == 0 ? null : fileItems.get(0).get();
        DeviceCommandFactory deviceCommandFactory = locator.getFactory(DeviceCommandFactory.class);
        DeviceCommandInput commandInput = deviceCommandFactory.newCommandInput();
        StringTokenizer st = new StringTokenizer(command);
        int count = st.countTokens();
        String cmd = count > 0 ? st.nextToken() : null;
        String[] args = count > 1 ? new String[count - 1] : null;
        int i = 0;
        while (st.hasMoreTokens()) {
            args[i++] = st.nextToken();
        }
        commandInput.setCommand(cmd);
        commandInput.setPassword((password == null || password.isEmpty()) ? null : password);
        commandInput.setArguments(args);
        commandInput.setTimeout(timeout);
        commandInput.setWorkingDir("/tmp/");
        commandInput.setBody(data);
        DeviceCommandOutput deviceCommandOutput = deviceService.exec(KapuaEid.parseShortId(scopeIdString), KapuaEid.parseShortId(deviceIdString), commandInput, null);
        resp.setContentType("text/plain");
        if (deviceCommandOutput.getStderr() != null && deviceCommandOutput.getStderr().length() > 0) {
            resp.getWriter().println(deviceCommandOutput.getStderr());
        }
        if (deviceCommandOutput.getStdout() != null && deviceCommandOutput.getStdout().length() > 0) {
            resp.getWriter().println(deviceCommandOutput.getStdout());
        }
        if (deviceCommandOutput.getExceptionMessage() != null && deviceCommandOutput.getExceptionMessage().length() > 0) {
            resp.getWriter().println(deviceCommandOutput.getExceptionMessage());
        }
    } catch (IllegalArgumentException iae) {
        resp.sendError(400, "Illegal value for query parameter: " + iae.getMessage());
        return;
    } catch (KapuaEntityNotFoundException eenfe) {
        resp.sendError(400, eenfe.getMessage());
        return;
    } catch (KapuaUnauthenticatedException eiae) {
        resp.sendError(401, eiae.getMessage());
        return;
    } catch (KapuaIllegalAccessException eiae) {
        resp.sendError(403, eiae.getMessage());
        return;
    } catch (Exception e) {
        s_logger.error("Error sending command", e);
        throw new ServletException(e);
    }
}
Also used : DeviceCommandOutput(org.eclipse.kapua.service.device.management.command.DeviceCommandOutput) KapuaLocator(org.eclipse.kapua.locator.KapuaLocator) DeviceCommandManagementService(org.eclipse.kapua.service.device.management.command.DeviceCommandManagementService) KapuaIllegalAccessException(org.eclipse.kapua.KapuaIllegalAccessException) ServletException(javax.servlet.ServletException) KapuaUnauthenticatedException(org.eclipse.kapua.KapuaUnauthenticatedException) KapuaEntityNotFoundException(org.eclipse.kapua.KapuaEntityNotFoundException) IOException(java.io.IOException) KapuaIllegalAccessException(org.eclipse.kapua.KapuaIllegalAccessException) FileUploadException(org.apache.commons.fileupload.FileUploadException) ServletException(javax.servlet.ServletException) FileItem(org.apache.commons.fileupload.FileItem) StringTokenizer(java.util.StringTokenizer) DeviceCommandInput(org.eclipse.kapua.service.device.management.command.DeviceCommandInput) DeviceCommandFactory(org.eclipse.kapua.service.device.management.command.DeviceCommandFactory) KapuaEntityNotFoundException(org.eclipse.kapua.KapuaEntityNotFoundException) KapuaUnauthenticatedException(org.eclipse.kapua.KapuaUnauthenticatedException)

Example 2 with DeviceCommandOutput

use of org.eclipse.kapua.service.device.management.command.DeviceCommandOutput in project kapua by eclipse.

the class GwtDeviceManagementServiceImpl method executeCommand.

// 
// Command
// 
@Override
public GwtDeviceCommandOutput executeCommand(GwtXSRFToken xsrfToken, GwtDevice gwtDevice, GwtDeviceCommandInput gwtCommandInput) throws GwtKapuaException {
    // 
    // Checking validity of the given XSRF Token
    checkXSRFToken(xsrfToken);
    GwtDeviceCommandOutput gwtCommandOutput = new GwtDeviceCommandOutput();
    try {
        // execute the command
        KapuaLocator locator = KapuaLocator.getInstance();
        DeviceCommandManagementService deviceCommandManagementService = locator.getService(DeviceCommandManagementService.class);
        DeviceCommandFactory deviceCommandFactory = locator.getFactory(DeviceCommandFactory.class);
        StringTokenizer st = new StringTokenizer(gwtCommandInput.getCommand());
        int count = st.countTokens();
        String command = count > 0 ? st.nextToken() : null;
        String[] args = count > 1 ? new String[count - 1] : null;
        int i = 0;
        while (st.hasMoreTokens()) {
            args[i++] = st.nextToken();
        }
        DeviceCommandInput commandInput = deviceCommandFactory.newCommandInput();
        // commandInput.setArguments(gwtCommandInput.getArguments());
        commandInput.setArguments(args);
        // commandInput.setCommand(gwtCommandInput.getCommand());
        commandInput.setCommand(command);
        commandInput.setEnvironment(gwtCommandInput.getEnvironment());
        commandInput.setRunAsynch(gwtCommandInput.isRunAsynch() != null ? gwtCommandInput.isRunAsynch().booleanValue() : false);
        commandInput.setStdin(gwtCommandInput.getStdin());
        commandInput.setTimeout(gwtCommandInput.getTimeout() != null ? gwtCommandInput.getTimeout().intValue() : 0);
        commandInput.setWorkingDir(gwtCommandInput.getWorkingDir());
        commandInput.setBody(gwtCommandInput.getZipBytes());
        KapuaId scopeId = KapuaEid.parseShortId(gwtDevice.getScopeId());
        KapuaId deviceId = KapuaEid.parseShortId(gwtDevice.getId());
        DeviceCommandOutput commandOutput = deviceCommandManagementService.exec(scopeId, deviceId, commandInput, null);
        if (commandOutput.getExceptionMessage() != null) {
            gwtCommandOutput.setExceptionMessage(commandOutput.getExceptionMessage().replace("\n", "<br>"));
        }
        if (commandOutput.getExceptionStack() != null) {
            gwtCommandOutput.setExceptionStack(commandOutput.getExceptionStack().replace("\n", "<br>"));
        }
        gwtCommandOutput.setExitCode(commandOutput.getExitCode());
        if (commandOutput.getStderr() != null) {
            gwtCommandOutput.setStderr(commandOutput.getStderr().replace("\n", "<br>"));
        }
        gwtCommandOutput.setStdout(commandOutput.getStdout());
        gwtCommandOutput.setTimedout(commandOutput.getHasTimedout());
    } catch (Throwable t) {
        KapuaExceptionHandler.handle(t);
    }
    return gwtCommandOutput;
}
Also used : GwtDeviceCommandOutput(org.eclipse.kapua.app.console.shared.model.GwtDeviceCommandOutput) DeviceCommandOutput(org.eclipse.kapua.service.device.management.command.DeviceCommandOutput) KapuaLocator(org.eclipse.kapua.locator.KapuaLocator) StringTokenizer(java.util.StringTokenizer) GwtDeviceCommandInput(org.eclipse.kapua.app.console.shared.model.GwtDeviceCommandInput) DeviceCommandInput(org.eclipse.kapua.service.device.management.command.DeviceCommandInput) DeviceCommandFactory(org.eclipse.kapua.service.device.management.command.DeviceCommandFactory) DeviceCommandManagementService(org.eclipse.kapua.service.device.management.command.DeviceCommandManagementService) KapuaId(org.eclipse.kapua.model.id.KapuaId) GwtDeviceCommandOutput(org.eclipse.kapua.app.console.shared.model.GwtDeviceCommandOutput)

Example 3 with DeviceCommandOutput

use of org.eclipse.kapua.service.device.management.command.DeviceCommandOutput in project kapua by eclipse.

the class DeviceCommandManagementServiceImpl method exec.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public DeviceCommandOutput exec(KapuaId scopeId, KapuaId deviceId, DeviceCommandInput commandInput, Long timeout) throws KapuaException {
    // 
    // Argument Validation
    ArgumentValidator.notNull(scopeId, "scopeId");
    ArgumentValidator.notNull(deviceId, "deviceId");
    ArgumentValidator.notNull(commandInput, "commandInput");
    // 
    // Check Access
    KapuaLocator locator = KapuaLocator.getInstance();
    AuthorizationService authorizationService = locator.getService(AuthorizationService.class);
    PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class);
    authorizationService.checkPermission(permissionFactory.newPermission(DeviceManagementDomain.DEVICE_MANAGEMENT, Actions.execute, scopeId));
    // 
    // Prepare the request
    CommandRequestChannel commandRequestChannel = new CommandRequestChannel();
    commandRequestChannel.setAppName(CommandAppProperties.APP_NAME);
    commandRequestChannel.setVersion(CommandAppProperties.APP_VERSION);
    commandRequestChannel.setMethod(KapuaMethod.EXECUTE);
    CommandRequestPayload commandRequestPayload = new CommandRequestPayload();
    commandRequestPayload.setCommand(commandInput.getCommand());
    commandRequestPayload.setArguments(commandInput.getArguments());
    commandRequestPayload.setStdin(commandInput.getStdin());
    commandRequestPayload.setTimeout(commandInput.getTimeout());
    commandRequestPayload.setWorkingDir(commandInput.getWorkingDir());
    commandRequestPayload.setEnvironmentPairs(commandInput.getEnvironment());
    commandRequestPayload.setRunAsync(commandInput.isRunAsynch());
    commandRequestPayload.setPassword(commandInput.getPassword());
    commandRequestPayload.setBody(commandInput.getBody());
    CommandRequestMessage commandRequestMessage = new CommandRequestMessage();
    commandRequestMessage.setScopeId(scopeId);
    commandRequestMessage.setDeviceId(deviceId);
    commandRequestMessage.setCapturedOn(new Date());
    commandRequestMessage.setPayload(commandRequestPayload);
    commandRequestMessage.setChannel(commandRequestChannel);
    // 
    // Do exec
    DeviceCallExecutor deviceApplicationCall = new DeviceCallExecutor(commandRequestMessage, timeout);
    CommandResponseMessage responseMessage = (CommandResponseMessage) deviceApplicationCall.send();
    // 
    // Create event
    DeviceEventService deviceEventService = locator.getService(DeviceEventService.class);
    DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class);
    DeviceEventCreator deviceEventCreator = deviceEventFactory.newCreator(scopeId, deviceId, responseMessage.getReceivedOn(), CommandAppProperties.APP_NAME.getValue());
    deviceEventCreator.setPosition(responseMessage.getPosition());
    deviceEventCreator.setSentOn(responseMessage.getSentOn());
    deviceEventCreator.setAction(KapuaMethod.EXECUTE);
    deviceEventCreator.setResponseCode(responseMessage.getResponseCode());
    deviceEventCreator.setEventMessage(responseMessage.getPayload().toDisplayString());
    deviceEventService.create(deviceEventCreator);
    // 
    // Parse the response
    CommandResponsePayload responsePayload = responseMessage.getPayload();
    DeviceCommandOutput deviceCommandOutput = new DeviceCommandOutputImpl();
    deviceCommandOutput.setExceptionMessage(responsePayload.getExceptionMessage());
    deviceCommandOutput.setExceptionStack(responsePayload.getExceptionStack());
    deviceCommandOutput.setExitCode(responsePayload.getExitCode());
    // FIXME: implement track of timeout!!!
    deviceCommandOutput.setHasTimedout(false);
    deviceCommandOutput.setStderr(responsePayload.getStderr());
    deviceCommandOutput.setStdout(responsePayload.getStdout());
    return deviceCommandOutput;
}
Also used : CommandResponsePayload(org.eclipse.kapua.service.device.management.command.message.internal.CommandResponsePayload) DeviceCommandOutput(org.eclipse.kapua.service.device.management.command.DeviceCommandOutput) KapuaLocator(org.eclipse.kapua.locator.KapuaLocator) PermissionFactory(org.eclipse.kapua.service.authorization.permission.PermissionFactory) CommandResponseMessage(org.eclipse.kapua.service.device.management.command.message.internal.CommandResponseMessage) DeviceEventFactory(org.eclipse.kapua.service.device.registry.event.DeviceEventFactory) Date(java.util.Date) CommandRequestMessage(org.eclipse.kapua.service.device.management.command.message.internal.CommandRequestMessage) DeviceCallExecutor(org.eclipse.kapua.service.device.management.commons.call.DeviceCallExecutor) CommandRequestChannel(org.eclipse.kapua.service.device.management.command.message.internal.CommandRequestChannel) AuthorizationService(org.eclipse.kapua.service.authorization.AuthorizationService) CommandRequestPayload(org.eclipse.kapua.service.device.management.command.message.internal.CommandRequestPayload) DeviceEventService(org.eclipse.kapua.service.device.registry.event.DeviceEventService) DeviceEventCreator(org.eclipse.kapua.service.device.registry.event.DeviceEventCreator)

Aggregations

KapuaLocator (org.eclipse.kapua.locator.KapuaLocator)3 DeviceCommandOutput (org.eclipse.kapua.service.device.management.command.DeviceCommandOutput)3 StringTokenizer (java.util.StringTokenizer)2 DeviceCommandFactory (org.eclipse.kapua.service.device.management.command.DeviceCommandFactory)2 DeviceCommandInput (org.eclipse.kapua.service.device.management.command.DeviceCommandInput)2 DeviceCommandManagementService (org.eclipse.kapua.service.device.management.command.DeviceCommandManagementService)2 IOException (java.io.IOException)1 Date (java.util.Date)1 ServletException (javax.servlet.ServletException)1 FileItem (org.apache.commons.fileupload.FileItem)1 FileUploadException (org.apache.commons.fileupload.FileUploadException)1 KapuaEntityNotFoundException (org.eclipse.kapua.KapuaEntityNotFoundException)1 KapuaIllegalAccessException (org.eclipse.kapua.KapuaIllegalAccessException)1 KapuaUnauthenticatedException (org.eclipse.kapua.KapuaUnauthenticatedException)1 GwtDeviceCommandInput (org.eclipse.kapua.app.console.shared.model.GwtDeviceCommandInput)1 GwtDeviceCommandOutput (org.eclipse.kapua.app.console.shared.model.GwtDeviceCommandOutput)1 KapuaId (org.eclipse.kapua.model.id.KapuaId)1 AuthorizationService (org.eclipse.kapua.service.authorization.AuthorizationService)1 PermissionFactory (org.eclipse.kapua.service.authorization.permission.PermissionFactory)1 CommandRequestChannel (org.eclipse.kapua.service.device.management.command.message.internal.CommandRequestChannel)1