Search in sources :

Example 11 with NameRecord

use of edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord 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();
        }
    }
}
Also used : JSONArray(org.json.JSONArray) FieldNotFoundException(edu.umass.cs.gnscommon.exceptions.server.FieldNotFoundException) AdminRequestPacket(edu.umass.cs.gnsserver.gnsapp.packet.admin.AdminRequestPacket) JSONException(org.json.JSONException) GuidInfo(edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.commandSupport.GuidInfo) IOException(java.io.IOException) FailedDBOperationException(edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException) DumpRequestPacket(edu.umass.cs.gnsserver.gnsapp.packet.admin.DumpRequestPacket) NameRecord(edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) AbstractRecordCursor(edu.umass.cs.gnsserver.database.AbstractRecordCursor) ParseException(java.text.ParseException) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket)

Example 12 with NameRecord

use of edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord 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;
}
Also used : RecordNotFoundException(edu.umass.cs.gnscommon.exceptions.server.RecordNotFoundException) NameRecord(edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord) FieldNotFoundException(edu.umass.cs.gnscommon.exceptions.server.FieldNotFoundException) FailedDBOperationException(edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException)

Example 13 with NameRecord

use of edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord in project GNS by MobilityFirst.

the class NSUpdateSupport method executeUpdateLocal.

/**
   * Executes a local updateEntireValuesMap operation.
   *
   * @param header
   * @param commandPacket
   * @param guid
   * @param field
   * @param writer
   * @param signature
   * @param message
   * @param timestamp
   * @param operation
   * @param updateValue
   * @param oldValue
   * @param argument
   * @param userJSON
   * @param app
   * @param doNotReplyToClient
   * @return an NSResponseCode
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeySpecException
   * @throws InvalidKeyException
   * @throws SignatureException
   * @throws JSONException
   * @throws IOException
   * @throws FailedDBOperationException
   * @throws RecordNotFoundException
   * @throws FieldNotFoundException
   * @throws edu.umass.cs.gnscommon.exceptions.server.InternalRequestException
   */
public static ResponseCode executeUpdateLocal(InternalRequestHeader header, CommandPacket commandPacket, String guid, String field, String writer, String signature, String message, Date timestamp, UpdateOperation operation, ResultValue updateValue, ResultValue oldValue, int argument, ValuesMap userJSON, GNSApplicationInterface<String> app, boolean doNotReplyToClient) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, JSONException, IOException, FailedDBOperationException, RecordNotFoundException, FieldNotFoundException, InternalRequestException {
    ResponseCode errorCode = ResponseCode.NO_ERROR;
    assert (header != null);
    // No checks for local non-auth commands like verifyAccount or for mutual auth
    if (!GNSProtocol.INTERNAL_QUERIER.toString().equals(writer) && !commandPacket.getCommandType().isMutualAuth()) {
        if (!header.verifyInternal()) {
            // This the standard auth check for most updates
            if (field != null) {
                errorCode = NSAuthentication.signatureAndACLCheck(header, guid, field, null, writer, signature, message, MetaDataTypeName.WRITE_WHITELIST, app);
            } else if (userJSON != null) {
                errorCode = NSAuthentication.signatureAndACLCheck(header, guid, null, userJSON.getKeys(), writer, signature, message, MetaDataTypeName.WRITE_WHITELIST, app);
            } else {
                ClientSupportConfig.getLogger().log(Level.FINE, "Name {0} key={1} : ACCESS_ERROR", new Object[] { guid, field });
                return ResponseCode.ACCESS_ERROR;
            }
        } else {
            // This ACL check will be only used for active code remote query 
            if (field != null) {
                assert (header.getQueryingGUID() != null) : guid + ":" + field + ":" + writer + "::" + header.getOriginatingGUID();
                errorCode = NSAuthentication.aclCheck(header, guid, field, header.getQueryingGUID(), MetaDataTypeName.WRITE_WHITELIST, app).getResponseCode();
            } else if (userJSON != null) {
                List<String> fields = userJSON.getKeys();
                for (String aField : fields) {
                    AclCheckResult aclResult = NSAuthentication.aclCheck(header, guid, aField, header.getQueryingGUID(), MetaDataTypeName.WRITE_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;
        }
    }
    // Return an error code if one of the checks doesn't pass
    if (errorCode.isExceptionOrError()) {
        return errorCode;
    }
    if (!operation.equals(UpdateOperation.CREATE_INDEX)) {
        // Handle usual case
        NameRecord nameRecord = getNameRecord(guid, field, operation, app.getDB());
        updateNameRecord(header, nameRecord, guid, field, operation, updateValue, oldValue, argument, userJSON, app.getDB(), app.getActiveCodeHandler());
        return ResponseCode.NO_ERROR;
    } else // Handle special case of a create index
    if (!updateValue.isEmpty() && updateValue.get(0) instanceof String) {
        ClientSupportConfig.getLogger().log(Level.FINE, "Creating index for {0} {1}", new Object[] { field, updateValue });
        app.getDB().createIndex(field, (String) updateValue.get(0));
        return ResponseCode.NO_ERROR;
    } else {
        ClientSupportConfig.getLogger().log(Level.SEVERE, "Invalid index value:{0}", updateValue);
        return ResponseCode.UPDATE_ERROR;
    }
}
Also used : ResponseCode(edu.umass.cs.gnscommon.ResponseCode) NameRecord(edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord) JSONObject(org.json.JSONObject) List(java.util.List) Date(java.util.Date)

Example 14 with NameRecord

use of edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord in project GNS by MobilityFirst.

the class NSFieldMetaData method fieldExists.

/**
   * Returns true if the ACL field exists.
   * 
   * @param type
   * @param guid
   * @param key
   * @param database
   * @return true if the ACL field exists
   * @throws RecordNotFoundException
   * @throws FieldNotFoundException
   * @throws FailedDBOperationException 
   */
public static boolean fieldExists(MetaDataTypeName type, String guid, String key, BasicRecordMap database) throws RecordNotFoundException, FieldNotFoundException, FailedDBOperationException {
    String field = FieldMetaData.makeFieldMetaDataKey(type, key);
    NameRecord nameRecord = NameRecord.getNameRecordMultiUserFields(database, guid, ColumnFieldType.LIST_STRING, field);
    return nameRecord.containsUserKey(field);
}
Also used : NameRecord(edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord)

Example 15 with NameRecord

use of edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord in project GNS by MobilityFirst.

the class Admintercessor method formatDumpRecords.

@SuppressWarnings("unchecked")
private String formatDumpRecords(Map<String, TreeSet<NameRecord>> recordsMap, ClientRequestHandlerInterface handler) {
    // now process all the records we received
    StringBuilder result = new StringBuilder();
    // are there any NSs that didn't respond?
    Set<String> missingIDs = new HashSet<>(handler.getGnsNodeConfig().getActiveReplicas());
    missingIDs.removeAll(recordsMap.keySet());
    if (missingIDs.size() > 0) {
        result.append("Missing NSs: ");
        result.append(Util.setOfNodeIdToString(missingIDs));
        result.append(LINE_SEPARATOR);
    }
    // process all the entries into a nice string
    for (Map.Entry<String, TreeSet<NameRecord>> entry : recordsMap.entrySet()) {
        ClientCommandProcessorConfig.getLogger().log(Level.FINE, "RECEIVED DUMP RECORD FROM NS: {0}", entry.getKey());
        result.append("========================================================================");
        result.append(LINE_SEPARATOR);
        result.append("Nameserver: ");
        result.append(entry.getKey());
        result.append(" (").append(handler.getGnsNodeConfig().getNodeAddress(entry.getKey()).getHostName());
        result.append(":");
        result.append(handler.getGnsNodeConfig().getNodePort(entry.getKey()));
        result.append(")");
        result.append(LINE_SEPARATOR);
        for (NameRecord record : entry.getValue()) {
            try {
                result.append("  NAME: ");
                result.append(record.getName());
                //          result.append(" P: ");
                //          result.append(Util.setOfNodeIdToString(record.getPrimaryNameservers()));
                result.append(LINE_SEPARATOR);
                result.append("    VALUE: ");
                try {
                    result.append(record.getValuesMap().toString(2));
                } catch (JSONException e) {
                    result.append(record.getValuesMap());
                }
                result.append(LINE_SEPARATOR);
            } catch (FieldNotFoundException e) {
                ClientCommandProcessorConfig.getLogger().log(Level.SEVERE, "FieldNotFoundException. {0}", e.getMessage());
            }
        }
    }
    return result.toString();
}
Also used : NameRecord(edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord) TreeSet(java.util.TreeSet) FieldNotFoundException(edu.umass.cs.gnscommon.exceptions.server.FieldNotFoundException) JSONException(org.json.JSONException) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TreeMap(java.util.TreeMap) HashSet(java.util.HashSet)

Aggregations

NameRecord (edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord)15 JSONObject (org.json.JSONObject)9 FieldNotFoundException (edu.umass.cs.gnscommon.exceptions.server.FieldNotFoundException)8 JSONException (org.json.JSONException)8 FailedDBOperationException (edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException)7 ValuesMap (edu.umass.cs.gnsserver.utils.ValuesMap)6 RecordNotFoundException (edu.umass.cs.gnscommon.exceptions.server.RecordNotFoundException)5 RecordExistsException (edu.umass.cs.gnscommon.exceptions.server.RecordExistsException)3 TreeSet (java.util.TreeSet)3 Test (org.junit.Test)3 DumpRequestPacket (edu.umass.cs.gnsserver.gnsapp.packet.admin.DumpRequestPacket)2 HashSet (java.util.HashSet)2 JSONArray (org.json.JSONArray)2 ResponseCode (edu.umass.cs.gnscommon.ResponseCode)1 InternalRequestException (edu.umass.cs.gnscommon.exceptions.server.InternalRequestException)1 AbstractRecordCursor (edu.umass.cs.gnsserver.database.AbstractRecordCursor)1 GuidInfo (edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.commandSupport.GuidInfo)1 AdminRequestPacket (edu.umass.cs.gnsserver.gnsapp.packet.admin.AdminRequestPacket)1 SentinalPacket (edu.umass.cs.gnsserver.gnsapp.packet.admin.SentinalPacket)1 GNSRecordMap (edu.umass.cs.gnsserver.gnsapp.recordmap.GNSRecordMap)1