use of edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException in project GNS by MobilityFirst.
the class FieldAccess method signatureAndACLCheckForRead.
/**
*
* @param header
* @param commandPacket
* @param guid
* @param field
* @param fields
* @param reader
* @param signature
* @param message
* @param timestamp
* @param app
* @param skipSigCheck
* @return the ResponseCode
*/
public static ResponseCode signatureAndACLCheckForRead(InternalRequestHeader header, CommandPacket commandPacket, String guid, String field, List<String> fields, String reader, String signature, String message, Date timestamp, GNSApplicationInterface<String> app, boolean skipSigCheck) {
ResponseCode errorCode = ResponseCode.NO_ERROR;
LOGGER.log(Level.FINE, "signatureAndACLCheckForRead guid: {0} field: {1} reader: {2}", new Object[] { guid, field, reader });
try {
assert (header != null);
// note: reader can also be null here
if (!header.verifyInternal() && !commandPacket.getCommandType().isMutualAuth() && (field != null || fields != null)) {
errorCode = NSAuthentication.signatureAndACLCheck(header, guid, field, fields, reader, signature, message, MetaDataTypeName.READ_WHITELIST, app, skipSigCheck);
} else {
LOGGER.log(Level.FINEST, "reader={0}; internal={1} field={2}; fields={3};", new Object[] { reader, header.verifyInternal(), field, fields });
// internal and mutual auth commands don't need ACL checks
if ((header.verifyInternal() && (GNSProtocol.INTERNAL_QUERIER.toString().equals(reader))) || commandPacket.getCommandType().isMutualAuth()) {
return ResponseCode.NO_ERROR;
}
//Fixme: I'm guessing this case is for active code only.
if (field != null) {
errorCode = NSAuthentication.aclCheck(header, guid, field, header.getQueryingGUID(), MetaDataTypeName.READ_WHITELIST, app).getResponseCode();
} else if (fields != null) {
for (String aField : fields) {
AclCheckResult aclResult = NSAuthentication.aclCheck(header, guid, aField, header.getQueryingGUID(), MetaDataTypeName.READ_WHITELIST, app);
if (aclResult.getResponseCode().isExceptionOrError()) {
errorCode = aclResult.getResponseCode();
}
}
}
}
// Check for stale commands.
if (timestamp != null) {
if (timestamp.before(DateUtils.addMinutes(new Date(), -Config.getGlobalInt(GNSConfig.GNSC.STALE_COMMAND_INTERVAL_IN_MINUTES)))) {
errorCode = ResponseCode.STALE_COMMAND_VALUE;
}
}
} catch (InvalidKeyException | InvalidKeySpecException | SignatureException | NoSuchAlgorithmException | FailedDBOperationException | UnsupportedEncodingException e) {
errorCode = ResponseCode.SIGNATURE_ERROR;
}
return errorCode;
}
use of edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException in project GNS by MobilityFirst.
the class AppAdminServer method run.
/**
* Start executing the thread.
*/
@Override
public void run() {
int numRequest = 0;
GNSConfig.getLogger().log(Level.INFO, "NS Node {0} starting Admin Request Server on port {1}", new Object[] { app.getNodeID(), serverSocket.getLocalPort() });
while (true) {
try {
//Read the packet from the input stream
try (Socket socket = serverSocket.accept()) {
//Read the packet from the input stream
JSONObject incomingJSON = Packet.getJSONObjectFrame(socket);
switch(Packet.getPacketType(incomingJSON)) {
case DUMP_REQUEST:
DumpRequestPacket<String> dumpRequestPacket = new DumpRequestPacket<>(incomingJSON, gnsNodeConfig);
dumpRequestPacket.setPrimaryNameServer(app.getNodeID());
JSONArray jsonArray = new JSONArray();
// if there is an argument it is a TAGNAME we return all the records that have that tag
if (dumpRequestPacket.getArgument() != null) {
String tag = dumpRequestPacket.getArgument();
AbstractRecordCursor cursor = NameRecord.getAllRowsIterator(app.getDB());
while (cursor.hasNext()) {
NameRecord nameRecord = null;
JSONObject json = cursor.nextJSONObject();
try {
nameRecord = new NameRecord(app.getDB(), json);
} catch (JSONException e) {
GNSConfig.getLogger().log(Level.SEVERE, "Problem parsing json into NameRecord: {0} JSON is {1}", new Object[] { e, json.toString() });
}
if (nameRecord != null) {
try {
if (nameRecord.containsUserKey(AccountAccess.GUID_INFO)) {
GuidInfo userInfo = new GuidInfo(nameRecord.getValuesMap().getJSONObject(AccountAccess.GUID_INFO));
//GuidInfo userInfo = new GuidInfo(nameRecord.getUserKeyAsArray(AccountAccess.GUID_INFO).toResultValueString());
if (userInfo.containsTag(tag)) {
jsonArray.put(nameRecord.toJSONObject());
}
}
} catch (FieldNotFoundException e) {
GNSConfig.getLogger().log(Level.SEVERE, "FieldNotFoundException. Field Name = {0}", e.getMessage());
//To change body of catch statement use File | Settings | File Templates.
e.printStackTrace();
}
}
}
// OTHERWISE WE RETURN ALL THE RECORD
} else {
//for (NameRecord nameRecord : NameServer.getAllNameRecords()) {
AbstractRecordCursor cursor = NameRecord.getAllRowsIterator(app.getDB());
while (cursor.hasNext()) {
NameRecord nameRecord = null;
JSONObject json = cursor.nextJSONObject();
try {
nameRecord = new NameRecord(app.getDB(), json);
} catch (JSONException e) {
GNSConfig.getLogger().log(Level.SEVERE, "Problem parsing record cursor into NameRecord: {0} JSON is {1}", new Object[] { e, json.toString() });
}
if (nameRecord != null) {
jsonArray.put(nameRecord.toJSONObject());
}
}
}
GNSConfig.getLogger().log(Level.FINER, "AppAdmin for {0} is {1}", new Object[] { app.getNodeID(), jsonArray.toString() });
dumpRequestPacket.setJsonArray(jsonArray);
Packet.sendTCPPacket(dumpRequestPacket.toJSONObject(), dumpRequestPacket.getReturnAddress());
GNSConfig.getLogger().log(Level.FINEST, "AppAdmin: Response to id:{0} --> {1}", new Object[] { dumpRequestPacket.getId(), dumpRequestPacket.toString() });
break;
case ADMIN_REQUEST:
AdminRequestPacket adminRequestPacket = new AdminRequestPacket(incomingJSON);
switch(adminRequestPacket.getOperation()) {
case CLEARCACHE:
GNSConfig.getLogger().log(Level.WARNING, "NSListenerAdmin ({0}) : Ignoring CLEARCACHE request", app.getNodeID());
break;
case DUMPCACHE:
GNSConfig.getLogger().log(Level.WARNING, "NSListenerAdmin ({0}) : Ignoring DUMPCACHE request", app.getNodeID());
break;
}
break;
}
}
} catch (IOException | JSONException | FailedDBOperationException | ParseException | IllegalArgumentException | SecurityException e) {
if (serverSocket.isClosed()) {
GNSConfig.getLogger().warning("NS Admin shutting down.");
// close this thread
return;
}
e.printStackTrace();
}
}
}
use of edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException 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;
}
use of edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException in project GNS by MobilityFirst.
the class GNSApp method checkpoint.
/**
*
* @param name
* @return the record
*/
@Override
public String checkpoint(String name) {
try {
NameRecord nameRecord = NameRecord.getNameRecord(nameRecordDB, name);
GNSConfig.getLogger().log(Level.FINE, "{0} getting state for {1} : {2} ", new Object[] { this, name, nameRecord.getValuesMap().getSummary() });
return nameRecord.getValuesMap().toString();
} catch (RecordNotFoundException e) {
// the above RecordNotFoundException is a normal result
} catch (FieldNotFoundException e) {
GNSConfig.getLogger().log(Level.SEVERE, "Field not found exception: {0}", e.getMessage());
e.printStackTrace();
} catch (FailedDBOperationException e) {
GNSConfig.getLogger().log(Level.SEVERE, "State not read from DB: {0}", e.getMessage());
e.printStackTrace();
}
return null;
}
use of edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException in project GNS by MobilityFirst.
the class NameResolution method lookupGuidField.
/**
* Lookup the field or fields in the guid.
* Returns a JSONObject containing the fields and values
* or null if the domainName doesn't exist.
* @param addr
* @param id
* @param domain - the HRN of the guid
* @param field - the field to lookup (mutually exclusive with fieldNames)
* @param fields - the fields to lookup (mutually exclusive with fieldNames)
* @param handler
* @return a JSONObject containing the fields and values or null
*/
public static JSONObject lookupGuidField(String addr, int id, String domain, String field, ArrayList<String> fields, ClientRequestHandlerInterface handler) {
/**
* Querying multiple types together is allowed in DNS protocol, but practically not supported.
* Therefore, no need for us to implement support for multi-type query.
*/
/**
* 1. Lookup guid for the domain name
*/
String guid = null;
final ValuesMap result;
try {
result = NSFieldAccess.lookupJSONFieldLocalNoAuth(null, domain, HRN_GUID, handler.getApp(), false);
if (result != null) {
guid = result.getString(HRN_GUID);
}
} catch (FailedDBOperationException | JSONException e) {
NameResolution.getLogger().log(Level.FINE, "No guid for {0}: {1}", new Object[] { domain, e });
return null;
}
/**
* 2. Lookup the record
*/
JSONObject value = null;
if (guid != null) {
// Generate a DNS header for local read
InternalRequestHeader header = new InternalRequestHeader() {
@Override
public long getOriginatingRequestID() {
return id;
}
@Override
public String getOriginatingGUID() {
try {
return result.getString(HRN_GUID);
} catch (JSONException e) {
return null;
}
}
@Override
public int getTTL() {
return InternalRequestHeader.DEFAULT_TTL;
}
@Override
public boolean hasBeenCoordinatedOnce() {
// DNS request does not need coordination
return false;
}
@Override
public String getSourceAddress() {
return addr;
}
};
try {
value = NSFieldAccess.lookupFieldsLocalNoAuth(header, guid, fields, ColumnFieldType.USER_JSON, handler);
} catch (FailedDBOperationException e) {
NameResolution.getLogger().log(Level.FINE, "Fetching record failed for {0}: {1}", new Object[] { domain, e });
}
} else {
NameResolution.getLogger().log(Level.FINE, "No guid for {0} is found", new Object[] { domain });
}
return value;
}
Aggregations