use of edu.umass.cs.gnscommon.packets.CommandPacket in project GNS by MobilityFirst.
the class LNSPacketDemultiplexer method handleCommandPacketOld.
/**
* Handles a command packet that has come in from a client.
*
* @param json
* @param header
* @throws JSONException
* @throws IOException
*/
public void handleCommandPacketOld(JSONObject json, NIOHeader header) throws JSONException, IOException {
CommandPacket packet = new CommandPacket(json);
int requestId = random.nextInt();
// packet.setLNSRequestId(requestId);
// Squirrel away the host and port so we know where to send the command return value
LNSRequestInfo requestInfo = new LNSRequestInfo(requestId, packet, null);
handler.addRequestInfo(requestId, requestInfo, header);
// Send it to the client command handler
Set<InetSocketAddress> actives;
if (!disableRequestActives) {
actives = handler.getActivesIfValid(packet.getServiceName());
} else {
// arun
Util.suicide("Should never get here");
actives = handler.getReplicatedActives(packet.getServiceName());
}
if (actives != null) {
if (!disableRequestActives) {
GNSConfig.getLogger().log(Level.FINE, "Found actives in cache for {0}: {1}", new Object[] { packet.getServiceName(), actives });
} else {
GNSConfig.getLogger().log(Level.FINE, "** USING DEFAULT ACTIVES for {0}: {1}", new Object[] { packet.getServiceName(), actives });
}
if (disableCommandRetransmitter) {
handler.sendToClosestReplica(actives, packet.toJSONObject());
} else {
handler.getProtocolExecutor().schedule(new CommandRetransmitter(requestId, packet.toJSONObject(), actives, handler));
}
} else {
handler.getProtocolExecutor().schedule(new RequestActives(requestInfo, handler));
}
}
use of edu.umass.cs.gnscommon.packets.CommandPacket in project GNS by MobilityFirst.
the class GNSHttpServer method processQuery.
/*
* Process queries for the http service. Converts the URI of e the HTTP query into
* the JSON Object format that is used by the CommandModeule class, then finds
* executes the matching command.
*
* @throws InternalRequestException
*/
private CommandResponse processQuery(String host, String commandName, String queryString, boolean secureServer) throws InternalRequestException {
// the signature, and the message signed.
try {
// Note that the commandName is not part of the queryString string here so
// it doesn't end up in the jsonCommand. Also see below where we put the
// command integer into the jsonCommand.
JSONObject jsonCommand = Util.parseURIQueryStringIntoJSONObject(queryString);
// If the signature exists it is Base64 encoded so decode it now.
if (jsonCommand.has(GNSProtocol.SIGNATURE.toString())) {
jsonCommand.put(GNSProtocol.SIGNATURE.toString(), new String(Base64.decode(jsonCommand.getString(GNSProtocol.SIGNATURE.toString())), GNSProtocol.CHARSET.toString()));
}
// getCommandForHttp allows for "dump" as well as "Dump"
CommandType commandType = CommandType.getCommandForHttp(commandName);
if (commandType == null) {
return new CommandResponse(ResponseCode.OPERATION_NOT_SUPPORTED, GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.OPERATION_NOT_SUPPORTED.toString() + " Sorry, don't understand " + commandName + QUERYPREFIX + queryString);
}
//Only allow mutual auth commands if we're on a secure (HTTPS) server
if (commandType.isMutualAuth() && !secureServer) {
return new CommandResponse(ResponseCode.OPERATION_NOT_SUPPORTED, GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.OPERATION_NOT_SUPPORTED.toString() + " Not authorized to execute " + commandName + QUERYPREFIX + queryString);
}
// The client currently just uses the command name (which is not part of the
// query string above) so we need to stuff
// in the Command integer for the signature check and execution.
jsonCommand.put(GNSProtocol.COMMAND_INT.toString(), commandType.getInt());
// Optionally does some sanity checking on the message if that was enabled at the client.
// This makes necessary changes to the jsonCommand so don't remove this call
// unless you know what you're doing and also change the code in the HTTP client.
sanityCheckMessage(jsonCommand);
// is true (or there was a problem).
if (client == null || commandType.isLocallyHandled()) {
// EXECUTE IT LOCALLY
AbstractCommand command;
try {
command = commandModule.lookupCommand(commandType);
// Do some work to get the signature and message into the command for
// signature checking that happens later on.
// This only happens for local execution because remote handling (in the
// other side of the if) already does this.
processSignature(jsonCommand);
if (command != null) {
return CommandHandler.executeCommand(command, new CommandPacket((long) (Math.random() * Long.MAX_VALUE), jsonCommand, false), requestHandler);
}
LOGGER.log(Level.FINE, "lookupCommand returned null for {0}", commandName);
} catch (IllegalArgumentException e) {
LOGGER.log(Level.FINE, "lookupCommand failed for {0}", commandName);
}
return new CommandResponse(ResponseCode.OPERATION_NOT_SUPPORTED, GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.OPERATION_NOT_SUPPORTED.toString() + " Sorry, don't understand " + commandName + QUERYPREFIX + queryString);
} else {
// Send the command remotely using a client
try {
LOGGER.log(Level.FINE, "Sending command out to a remote server: {0}", jsonCommand);
CommandPacket commandResponsePacket = getResponseUsingGNSClient(client, jsonCommand);
return new CommandResponse(ResponseCode.NO_ERROR, // There is similar code to this other places.
specialCaseSingleFieldRead(commandResponsePacket.getResultString(), commandType, jsonCommand));
} catch (IOException | ClientException e) {
return new CommandResponse(ResponseCode.UNSPECIFIED_ERROR, GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.UNSPECIFIED_ERROR.toString() + " " + e.toString());
// } catch (ClientException e) {
// return new CommandResponse(ResponseCode.GNSProtocol.UNSPECIFIED_ERROR.toString(),
// GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.OPERATION_NOT_SUPPORTED.toString()
// + " Sorry, don't understand " + commandName + QUERYPREFIX + queryString);
}
}
} catch (JSONException | UnsupportedEncodingException e) {
return new CommandResponse(ResponseCode.UNSPECIFIED_ERROR, GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.UNSPECIFIED_ERROR.toString() + " " + e.toString());
}
}
use of edu.umass.cs.gnscommon.packets.CommandPacket in project GNS by MobilityFirst.
the class GNSHttpServer method getResponseUsingGNSClient.
private CommandPacket getResponseUsingGNSClient(GNSClient client, JSONObject jsonFormattedArguments) throws ClientException, IOException, JSONException {
LOGGER.log(Level.FINE, "jsonFormattedCommand ={0}", jsonFormattedArguments.toString());
CommandPacket outgoingPacket = new CommandPacket((long) (Math.random() * Long.MAX_VALUE), jsonFormattedArguments, false);
//GNSCommand.createGNSCommandFromJSONObject(jsonFormattedArguments);
LOGGER.log(Level.FINE, "outgoingPacket ={0}", outgoingPacket.toString());
CommandPacket returnPacket = client.execute(outgoingPacket);
LOGGER.log(Level.FINE, "returnPacket ={0}", returnPacket.toString());
/**
* Can also invoke getResponse(), getResponseString(), getResponseJSONObject()
* etc. on {@link CommandPacket} as documented in {@link GNSCommand}.
*/
return returnPacket;
}
use of edu.umass.cs.gnscommon.packets.CommandPacket in project GNS by MobilityFirst.
the class GNSClient method sendSyncInternal.
/**
* All sync sends come here, which in turn calls
* {@link #sendAsync(CommandPacket, Callback)}{@code .get(timeout)}.
*
* @param packet
* @param timeout
* @return
* @throws IOException
* @throws ClientException
*/
private ResponsePacket sendSyncInternal(CommandPacket packet, final long timeout) throws IOException, ClientException {
ResponsePacket[] processed = new ResponsePacket[1];
Callback<Request, CommandPacket> future = new Callback<Request, CommandPacket>() {
@Override
public CommandPacket processResponse(Request response) {
GNSClientConfig.getLogger().log(Level.FINE, "{0} received response {1} for request {2}", new Object[] { GNSClient.this, packet.getSummary(), response.getSummary() });
processed[0] = defaultHandleResponse(response);
return packet;
}
};
try {
this.sendAsync(packet, future).get(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new ClientException(e);
}
return processed[0];
/* We could also simply have used gigapaxos' sync send above, but using
* the async code above avoids the redundancy with sendAsync on checking
* for anycast/proxy/default. */
}
use of edu.umass.cs.gnscommon.packets.CommandPacket in project GNS by MobilityFirst.
the class GNSApp method execute.
/**
*
* @param request
* @param doNotReplyToClient
* @return true if the command is successfully executed
*/
@SuppressWarnings("unchecked")
// we explicitly check type
@Override
public boolean execute(Request request, boolean doNotReplyToClient) {
boolean executed = false;
if (executeNoop(request)) {
return true;
}
try {
Packet.PacketType packetType = request.getRequestType() instanceof Packet.PacketType ? (Packet.PacketType) request.getRequestType() : null;
GNSConfig.getLogger().log(Level.FINE, "{0} starting execute({1}) doNotReplyToClient={2}", new Object[] { this, request.getSummary(), doNotReplyToClient });
Request prev = null;
// arun: enqueue request, dequeue before returning
if (request instanceof RequestIdentifier) {
if (enqueueCommand()) {
prev = this.outstanding.putIfAbsent(((RequestIdentifier) request).getRequestID(), request);
}
} else {
assert (false) : this + " should not be getting requests that do not implement " + RequestIdentifier.class;
}
switch(packetType) {
case SELECT_REQUEST:
Select.handleSelectRequest((SelectRequestPacket) request, this);
break;
case SELECT_RESPONSE:
Select.handleSelectResponse((SelectResponsePacket) request, this);
break;
case COMMAND:
CommandHandler.handleCommandPacket((CommandPacket) request, doNotReplyToClient, this);
break;
case ADMIN_COMMAND:
CommandHandler.handleCommandPacket((AdminCommandPacket) request, doNotReplyToClient, this);
break;
default:
assert (false) : (this + " should not be getting packets of type " + packetType + "; exiting");
GNSConfig.getLogger().log(Level.SEVERE, " Packet type not found: {0}", request.getSummary());
return false;
}
executed = true;
// arun: always clean up all created state upon exiting
if (request instanceof RequestIdentifier && prev == null) {
GNSConfig.getLogger().log(Level.FINE, "{0} finished execute({1}) -> {2}", new Object[] { this, request.getSummary(), request instanceof ClientRequest && ((ClientRequest) request).getResponse() != null ? ((ClientRequest) request).getResponse().getSummary() : null });
this.outstanding.remove(((RequestIdentifier) request).getRequestID());
}
} catch (JSONException | IOException | ClientException | InternalRequestException e) {
e.printStackTrace();
} catch (FailedDBOperationException e) {
// all database operations throw this exception, therefore we keep
// throwing this exception upwards and catch this
// here.
// A database operation error would imply that the application
// hasn't been able to successfully execute
// the request. therefore, this method returns 'false', hoping that
// whoever calls handleDecision would retry
// the request.
GNSConfig.getLogger().log(Level.SEVERE, "Error handling request: {0}", request.toString());
e.printStackTrace();
}
return executed;
}
Aggregations