idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
18,000 | private void attemptToExecuteTask ( ApplicationDefinition appDef , Task task , TaskRecord taskRecord ) { Tenant tenant = Tenant . getTenant ( appDef ) ; String taskID = taskRecord . getTaskID ( ) ; String claimID = "_claim/" + taskID ; long claimStamp = System . currentTimeMillis ( ) ; writeTaskClaim ( tenant , claimID , claimStamp ) ; if ( taskClaimedByUs ( tenant , claimID ) ) { startTask ( appDef , task , taskRecord ) ; } else { m_logger . info ( "Will not start task: it was claimed by another service" ) ; } } | Attempt to start the given task by creating claim and see if we win it . |
18,001 | private void startTask ( ApplicationDefinition appDef , Task task , TaskRecord taskRecord ) { try { task . setParams ( m_localHost , taskRecord ) ; m_executor . execute ( task ) ; } catch ( Exception e ) { m_logger . error ( "Failed to start task '" + task . getTaskID ( ) + "'" , e ) ; } } | Execute the given task by handing it to the ExecutorService . |
18,002 | private boolean taskClaimedByUs ( Tenant tenant , String claimID ) { waitForClaim ( ) ; Iterator < DColumn > colIter = DBService . instance ( tenant ) . getAllColumns ( TaskManagerService . TASKS_STORE_NAME , claimID ) . iterator ( ) ; if ( colIter == null ) { m_logger . warn ( "Claim record disappeared: {}" , claimID ) ; return false ; } String claimingHost = m_hostClaimID ; long earliestClaim = Long . MAX_VALUE ; while ( colIter . hasNext ( ) ) { DColumn col = colIter . next ( ) ; try { long claimStamp = Long . parseLong ( col . getValue ( ) ) ; long secondsSinceClaim = ( System . currentTimeMillis ( ) - claimStamp ) / 1000 ; if ( secondsSinceClaim > 600 ) continue ; String claimHost = col . getName ( ) ; if ( claimStamp < earliestClaim ) { claimingHost = claimHost ; earliestClaim = claimStamp ; } else if ( claimStamp == earliestClaim ) { if ( claimHost . compareTo ( claimingHost ) < 0 ) { claimingHost = claimHost ; } } } catch ( NumberFormatException e ) { } } return claimingHost . equals ( m_hostClaimID ) && ! m_bShutdown ; } | Indicate if we won the claim to run the given task . |
18,003 | private void writeTaskClaim ( Tenant tenant , String claimID , long claimStamp ) { DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; dbTran . addColumn ( TaskManagerService . TASKS_STORE_NAME , claimID , m_hostClaimID , claimStamp ) ; DBService . instance ( tenant ) . commit ( dbTran ) ; } | Write a claim record to the Tasks table . |
18,004 | private TaskRecord buildTaskRecord ( String taskID , Iterator < DColumn > colIter ) { TaskRecord taskRecord = new TaskRecord ( taskID ) ; while ( colIter . hasNext ( ) ) { DColumn col = colIter . next ( ) ; taskRecord . setProperty ( col . getName ( ) , col . getValue ( ) ) ; } return taskRecord ; } | Create a TaskRecord from a task status row read from the Tasks table . |
18,005 | private TaskRecord storeTaskRecord ( Tenant tenant , Task task ) { DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; TaskRecord taskRecord = new TaskRecord ( task . getTaskID ( ) ) ; Map < String , String > propMap = taskRecord . getProperties ( ) ; assert propMap . size ( ) > 0 : "Need at least one property to store a row!" ; for ( String propName : propMap . keySet ( ) ) { dbTran . addColumn ( TaskManagerService . TASKS_STORE_NAME , task . getTaskID ( ) , propName , propMap . get ( propName ) ) ; } DBService . instance ( tenant ) . commit ( dbTran ) ; return taskRecord ; } | Create a TaskRecord for the given task and write it to the Tasks table . |
18,006 | private List < Task > getAppTasks ( ApplicationDefinition appDef ) { List < Task > appTasks = new ArrayList < > ( ) ; try { StorageService service = SchemaService . instance ( ) . getStorageService ( appDef ) ; Collection < Task > appTaskColl = service . getAppTasks ( appDef ) ; if ( appTaskColl != null ) { appTasks . addAll ( service . getAppTasks ( appDef ) ) ; } } catch ( IllegalArgumentException e ) { } return appTasks ; } | Ask the storage manager for the given application for its required tasks . |
18,007 | private void checkForDeadTask ( Tenant tenant , TaskRecord taskRecord ) { Calendar lastReport = taskRecord . getTime ( TaskRecord . PROP_PROGRESS_TIME ) ; if ( lastReport == null ) { lastReport = taskRecord . getTime ( TaskRecord . PROP_START_TIME ) ; if ( lastReport == null ) { return ; } } long minsSinceLastActivity = ( System . currentTimeMillis ( ) - lastReport . getTimeInMillis ( ) ) / ( 1000 * 60 ) ; if ( isOurActiveTask ( tenant , taskRecord . getTaskID ( ) ) ) { checkForHungTask ( tenant , taskRecord , minsSinceLastActivity ) ; } else { checkForAbandonedTask ( tenant , taskRecord , minsSinceLastActivity ) ; } } | See if the given in - progress task may be hung or abandoned . |
18,008 | private void checkForHungTask ( Tenant tenant , TaskRecord taskRecord , long minsSinceLastActivity ) { if ( minsSinceLastActivity > HUNG_TASK_THRESHOLD_MINS ) { String taskIdentity = createMapKey ( tenant , taskRecord . getTaskID ( ) ) ; String reason = "No progress reported in " + minsSinceLastActivity + " minutes" ; m_logger . warn ( "Local task {} has not reported progress in {} minutes; " + "restart the server if this continues for too long" , taskIdentity , minsSinceLastActivity ) ; taskRecord . setProperty ( TaskRecord . PROP_PROGRESS_TIME , Long . toString ( System . currentTimeMillis ( ) ) ) ; taskRecord . setProperty ( TaskRecord . PROP_PROGRESS , reason ) ; updateTaskStatus ( tenant , taskRecord , false ) ; } } | potentially harmful second task execution . |
18,009 | private void checkForAbandonedTask ( Tenant tenant , TaskRecord taskRecord , long minsSinceLastActivity ) { if ( minsSinceLastActivity > DEAD_TASK_THRESHOLD_MINS ) { String taskIdentity = createMapKey ( tenant , taskRecord . getTaskID ( ) ) ; String reason = "No progress reported in " + minsSinceLastActivity + " minutes" ; m_logger . error ( "Remote task {} has not reported progress in {} minutes; marking as failed" , taskIdentity , minsSinceLastActivity ) ; taskRecord . setProperty ( TaskRecord . PROP_FINISH_TIME , Long . toString ( System . currentTimeMillis ( ) ) ) ; taskRecord . setProperty ( TaskRecord . PROP_FAIL_REASON , reason ) ; taskRecord . setStatus ( TaskStatus . FAILED ) ; updateTaskStatus ( tenant , taskRecord , true ) ; } } | to restart upon the next check - tasks cycle . |
18,010 | private boolean isOurActiveTask ( Tenant tenant , String taskID ) { synchronized ( m_activeTasks ) { return m_activeTasks . containsKey ( createMapKey ( tenant , taskID ) ) ; } } | Return true if we are currently executing the given task . |
18,011 | private void commitTransaction ( ) { Tenant tenant = Tenant . getTenant ( m_tableDef ) ; DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; m_parentTran . applyUpdates ( dbTran ) ; DBService . instance ( tenant ) . commit ( dbTran ) ; m_parentTran . clear ( ) ; } | Post all updates in the parent transaction to the database . |
18,012 | private boolean updateBatch ( DBObjectBatch dbObjBatch , BatchResult batchResult ) throws IOException { Map < String , Map < String , String > > objCurrScalarMap = getCurrentScalars ( dbObjBatch ) ; Map < String , Map < String , Integer > > targObjShardNos = getLinkTargetShardNumbers ( dbObjBatch ) ; for ( DBObject dbObj : dbObjBatch . getObjects ( ) ) { checkCommit ( ) ; Map < String , String > currScalarMap = objCurrScalarMap . get ( dbObj . getObjectID ( ) ) ; ObjectResult objResult = updateObject ( dbObj , currScalarMap , targObjShardNos ) ; batchResult . addObjectResult ( objResult ) ; } commitTransaction ( ) ; return batchResult . hasUpdates ( ) ; } | Update each object in the given batch updating BatchResult accordingly . |
18,013 | private ObjectResult updateObject ( DBObject dbObj , Map < String , String > currScalarMap , Map < String , Map < String , Integer > > targObjShardNos ) { ObjectResult objResult = null ; if ( Utils . isEmpty ( dbObj . getObjectID ( ) ) ) { objResult = ObjectResult . newErrorResult ( "Object ID is required" , null ) ; } else if ( currScalarMap == null ) { objResult = ObjectResult . newErrorResult ( "No object found" , dbObj . getObjectID ( ) ) ; } else { ObjectUpdater objUpdater = new ObjectUpdater ( m_tableDef ) ; if ( targObjShardNos . size ( ) > 0 ) { objUpdater . setTargetObjectShardNumbers ( targObjShardNos ) ; } objResult = objUpdater . updateObject ( m_parentTran , dbObj , currScalarMap ) ; } return objResult ; } | Update the given object which must exist using the given set of current scalar values . |
18,014 | private ObjectResult addOrUpdateObject ( DBObject dbObj , Map < String , String > currScalarMap , Map < String , Map < String , Integer > > targObjShardNos ) throws IOException { ObjectUpdater objUpdater = new ObjectUpdater ( m_tableDef ) ; if ( targObjShardNos . size ( ) > 0 ) { objUpdater . setTargetObjectShardNumbers ( targObjShardNos ) ; } if ( currScalarMap == null || currScalarMap . size ( ) == 0 ) { return objUpdater . addNewObject ( m_parentTran , dbObj ) ; } else { return objUpdater . updateObject ( m_parentTran , dbObj , currScalarMap ) ; } } | Add the given object if its current - value map is null otherwise update the object . |
18,015 | private void buildErrorStatus ( BatchResult result , Throwable ex ) { result . setStatus ( BatchResult . Status . ERROR ) ; result . setErrorMessage ( ex . getLocalizedMessage ( ) ) ; if ( ex instanceof IllegalArgumentException ) { m_logger . debug ( "Batch update error: {}" , ex . toString ( ) ) ; } else { result . setStackTrace ( Utils . getStackTrace ( ex ) ) ; m_logger . debug ( "Batch update error: {} stacktrace: {}" , ex . toString ( ) , Utils . getStackTrace ( ex ) ) ; } } | Add error fields to the given BatchResult due to the given exception . |
18,016 | private Map < String , Map < String , String > > getCurrentScalars ( DBObjectBatch dbObjBatch ) throws IOException { Set < String > objIDSet = new HashSet < > ( ) ; Set < String > fieldNameSet = new HashSet < String > ( ) ; for ( DBObject dbObj : dbObjBatch . getObjects ( ) ) { if ( ! Utils . isEmpty ( dbObj . getObjectID ( ) ) ) { Utils . require ( objIDSet . add ( dbObj . getObjectID ( ) ) , "Cannot update the same object ID twice: " + dbObj . getObjectID ( ) ) ; fieldNameSet . addAll ( dbObj . getUpdatedScalarFieldNames ( m_tableDef ) ) ; } } if ( m_tableDef . isSharded ( ) ) { fieldNameSet . add ( m_tableDef . getShardingField ( ) . getName ( ) ) ; } return SpiderService . instance ( ) . getObjectScalars ( m_tableDef , objIDSet , fieldNameSet ) ; } | Watch and complain about updates to the same ID . |
18,017 | private Map < String , Map < String , Integer > > getLinkTargetShardNumbers ( DBObjectBatch dbObjBatch ) { Map < String , Map < String , Integer > > result = new HashMap < > ( ) ; Map < String , Set < String > > tableTargetObjIDMap = getAllLinkTargetObjIDs ( dbObjBatch ) ; for ( String targetTableName : tableTargetObjIDMap . keySet ( ) ) { Map < String , Integer > shardNoMap = getShardNumbers ( targetTableName , tableTargetObjIDMap . get ( targetTableName ) ) ; if ( shardNoMap . size ( ) > 0 ) { Map < String , Integer > tableShardNoMap = result . get ( targetTableName ) ; if ( tableShardNoMap == null ) { tableShardNoMap = new HashMap < > ( ) ; result . put ( targetTableName , tableShardNoMap ) ; } tableShardNoMap . putAll ( shardNoMap ) ; } } return result ; } | objects that have no sharding - field value . |
18,018 | private Map < String , Set < String > > getAllLinkTargetObjIDs ( DBObjectBatch dbObjBatch ) { Map < String , Set < String > > resultMap = new HashMap < > ( ) ; for ( FieldDefinition fieldDef : m_tableDef . getFieldDefinitions ( ) ) { if ( ! fieldDef . isLinkField ( ) || ! fieldDef . getInverseTableDef ( ) . isSharded ( ) ) { continue ; } Set < String > targObjIDs = getLinkTargetObjIDs ( fieldDef , dbObjBatch ) ; if ( targObjIDs . size ( ) == 0 ) { continue ; } String targetTableName = fieldDef . getInverseTableDef ( ) . getTableName ( ) ; Set < String > tableObjIDs = resultMap . get ( targetTableName ) ; if ( tableObjIDs == null ) { tableObjIDs = new HashSet < > ( ) ; resultMap . put ( targetTableName , tableObjIDs ) ; } tableObjIDs . addAll ( targObjIDs ) ; } return resultMap ; } | table in the given batch . |
18,019 | private Set < String > getLinkTargetObjIDs ( FieldDefinition linkDef , DBObjectBatch dbObjBatch ) { Set < String > targObjIDs = new HashSet < > ( ) ; for ( DBObject dbObj : dbObjBatch . getObjects ( ) ) { List < String > objIDs = dbObj . getFieldValues ( linkDef . getName ( ) ) ; if ( objIDs != null ) { targObjIDs . addAll ( objIDs ) ; } Set < String > removeIDs = dbObj . getRemoveValues ( linkDef . getName ( ) ) ; if ( removeIDs != null ) { targObjIDs . addAll ( removeIDs ) ; } } return targObjIDs ; } | Target object IDs can be in the add or remove set . |
18,020 | private Map < String , Integer > getShardNumbers ( String tableName , Set < String > targObjIDs ) { TableDefinition tableDef = m_tableDef . getAppDef ( ) . getTableDef ( tableName ) ; FieldDefinition shardField = tableDef . getShardingField ( ) ; Map < String , String > shardFieldMap = SpiderService . instance ( ) . getObjectScalar ( tableDef , targObjIDs , shardField . getName ( ) ) ; Map < String , Integer > shardNoMap = new HashMap < > ( ) ; for ( String objID : shardFieldMap . keySet ( ) ) { Date shardingFieldDate = Utils . dateFromString ( shardFieldMap . get ( objID ) ) ; int shardNo = tableDef . computeShardNumber ( shardingFieldDate ) ; shardNoMap . put ( objID , shardNo ) ; } return shardNoMap ; } | has no value for its sharding - field leave the map empty for that object ID . |
18,021 | public void parse ( UNode userNode ) { m_userID = userNode . getName ( ) ; m_password = null ; m_permissions . clear ( ) ; for ( String childName : userNode . getMemberNames ( ) ) { UNode childNode = userNode . getMember ( childName ) ; switch ( childNode . getName ( ) ) { case "password" : Utils . require ( childNode . isValue ( ) , "'password' must be a simple value: " + childNode ) ; m_password = childNode . getValue ( ) ; break ; case "hash" : Utils . require ( childNode . isValue ( ) , "Invalid 'hash' value" ) ; m_hash = childNode . getValue ( ) ; break ; case "permissions" : Utils . require ( childNode . isValue ( ) , "'permissions' must be a list of values: " + childNode ) ; String [ ] permissions = childNode . getValue ( ) . split ( "," ) ; for ( String permission : permissions ) { String permToken = permission . toUpperCase ( ) . trim ( ) ; try { m_permissions . add ( Permission . valueOf ( permToken ) ) ; } catch ( IllegalArgumentException e ) { Utils . require ( false , "Unrecognized permission: %s; allowed values are: %s" , permToken , Arrays . asList ( Permission . values ( ) ) . toString ( ) ) ; } } break ; default : Utils . require ( false , "Unknown 'user' property: " + childNode ) ; } } } | Parse a user definition expressed as a UNode tree . |
18,022 | public UNode toDoc ( ) { UNode userNode = UNode . createMapNode ( m_userID , "user" ) ; if ( ! Utils . isEmpty ( m_password ) ) { userNode . addValueNode ( "password" , m_password , true ) ; } if ( ! Utils . isEmpty ( m_hash ) ) { userNode . addValueNode ( "hash" , m_hash , true ) ; } String permissions = "ALL" ; if ( m_permissions . size ( ) > 0 ) { permissions = Utils . concatenate ( m_permissions , "," ) ; } userNode . addValueNode ( "permissions" , permissions ) ; return userNode ; } | Serialize this user definition into a UNode tree . |
18,023 | private DBObject parseObject ( TableDefinition tableDef , UNode docNode ) { assert tableDef != null ; assert docNode != null ; assert docNode . getName ( ) . equals ( "doc" ) ; DBObject dbObj = new DBObject ( ) ; for ( UNode childNode : docNode . getMemberList ( ) ) { String fieldName = childNode . getName ( ) ; FieldDefinition fieldDef = tableDef . getFieldDef ( fieldName ) ; boolean isLinkField = fieldDef == null ? false : fieldDef . isLinkField ( ) ; boolean isGroupField = fieldDef == null ? false : fieldDef . isGroupField ( ) ; boolean isCollection = fieldDef == null ? false : fieldDef . isCollection ( ) ; Utils . require ( ! isGroupField , "Unexpected group field in query results: " + fieldName ) ; if ( isLinkField ) { parseLinkValue ( dbObj , childNode , fieldDef ) ; } else if ( isCollection ) { parseMVScalarValue ( dbObj , childNode , fieldDef ) ; } else { Utils . require ( childNode . isValue ( ) , "Value of an SV scalar must be a value: " + childNode ) ; dbObj . addFieldValue ( fieldName , childNode . getValue ( ) ) ; } } return dbObj ; } | than the perspective table of the query . |
18,024 | private void parseLinkValue ( DBObject owningObj , UNode linkNode , FieldDefinition linkFieldDef ) { assert owningObj != null ; assert linkNode != null ; assert linkFieldDef != null ; assert linkFieldDef . isLinkField ( ) ; TableDefinition tableDef = linkFieldDef . getTableDef ( ) ; Utils . require ( linkNode . isCollection ( ) , "Value of link field should be a collection: " + linkNode ) ; TableDefinition extentTableDef = tableDef . getAppDef ( ) . getTableDef ( linkFieldDef . getLinkExtent ( ) ) ; for ( UNode childNode : linkNode . getMemberList ( ) ) { Utils . require ( childNode . getName ( ) . equals ( "doc" ) , "link field array values should be 'doc' objects: " + childNode ) ; DBObject linkedObject = parseObject ( extentTableDef , childNode ) ; String objID = linkedObject . getObjectID ( ) ; cacheLinkedObject ( owningObj . getObjectID ( ) , linkFieldDef . getName ( ) , linkedObject ) ; owningObj . addFieldValues ( linkFieldDef . getName ( ) , Arrays . asList ( objID ) ) ; } } | object and add it to the linked object cache for the owning object and link . |
18,025 | private void cacheLinkedObject ( String owningObjID , String linkFieldName , DBObject linkedObject ) { Map < String , Map < String , DBObject > > objMap = m_linkedObjectMap . get ( owningObjID ) ; if ( objMap == null ) { objMap = new HashMap < String , Map < String , DBObject > > ( ) ; m_linkedObjectMap . put ( owningObjID , objMap ) ; } Map < String , DBObject > linkMap = objMap . get ( linkFieldName ) ; if ( linkMap == null ) { linkMap = new HashMap < String , DBObject > ( ) ; objMap . put ( linkFieldName , linkMap ) ; } linkMap . put ( linkedObject . getObjectID ( ) , linkedObject ) ; } | link field name . |
18,026 | public static RESTParameter fromUNode ( UNode paramNode ) { RESTParameter param = new RESTParameter ( ) ; String name = paramNode . getName ( ) ; Utils . require ( ! Utils . isEmpty ( name ) , "Missing parameter name: " + paramNode ) ; param . setName ( name ) ; for ( UNode childNode : paramNode . getMemberList ( ) ) { switch ( childNode . getName ( ) ) { case "_required" : param . setRequired ( Boolean . parseBoolean ( childNode . getValue ( ) ) ) ; break ; case "_type" : param . setType ( childNode . getValue ( ) ) ; break ; default : if ( childNode . getName ( ) . charAt ( 0 ) != '_' ) { param . add ( RESTParameter . fromUNode ( childNode ) ) ; } break ; } } return param ; } | Create a new RESTParameter object from the given UNode tree . |
18,027 | public UNode toDoc ( ) { UNode paramNode = UNode . createMapNode ( m_name ) ; if ( ! Utils . isEmpty ( m_type ) ) { paramNode . addValueNode ( "_type" , m_type ) ; } if ( m_isRequired ) { paramNode . addValueNode ( "_required" , Boolean . toString ( m_isRequired ) ) ; } if ( m_parameters . size ( ) > 0 ) { for ( RESTParameter param : m_parameters ) { paramNode . addChildNode ( param . toDoc ( ) ) ; } } return paramNode ; } | Serialize this RESTParameter into a UNode tree and return the root node . |
18,028 | public RESTParameter add ( RESTParameter childParam ) { Utils . require ( ! Utils . isEmpty ( childParam . getName ( ) ) , "Child parameter name cannot be empty" ) ; m_parameters . add ( childParam ) ; return this ; } | Add the given RESTParameter as a child of this parameter . This parameter is returned to support builder syntax . |
18,029 | public RESTParameter add ( String childParamName , String childParamType ) { return add ( new RESTParameter ( childParamName , childParamType ) ) ; } | Add a new child parameter with the given name and type to this parameter . The child parameter will not be marked as required . This parameter is returned to support builder syntax . |
18,030 | DBConn getDBConnection ( ) { DBConn dbConn = null ; synchronized ( m_dbConns ) { if ( m_dbConns . size ( ) > 0 ) { dbConn = m_dbConns . poll ( ) ; } else { dbConn = createAndConnectConn ( m_keyspace ) ; } } return dbConn ; } | Get an available database connection from the pool creating a new one if needed . |
18,031 | void connectDBConn ( DBConn dbConn ) throws DBNotAvailableException , RuntimeException { if ( m_bUseSecondaryHosts && ( System . currentTimeMillis ( ) - m_lastPrimaryHostCheckTimeMillis ) > getParamInt ( "primary_host_recheck_millis" , 60000 ) ) { m_bUseSecondaryHosts = false ; } DBNotAvailableException lastException = null ; if ( ! m_bUseSecondaryHosts ) { String [ ] dbHosts = getParamString ( "dbhost" ) . split ( "," ) ; for ( int attempt = 1 ; ! dbConn . isOpen ( ) && attempt <= dbHosts . length ; attempt ++ ) { try { dbConn . connect ( chooseHost ( dbHosts ) ) ; } catch ( DBNotAvailableException ex ) { lastException = ex ; } catch ( RuntimeException ex ) { throw ex ; } } m_lastPrimaryHostCheckTimeMillis = System . currentTimeMillis ( ) ; } if ( ! dbConn . isOpen ( ) && ! Utils . isEmpty ( getParamString ( "secondary_dbhost" ) ) ) { if ( ! m_bUseSecondaryHosts ) { m_logger . info ( "All connections to 'dbhost' failed; trying 'secondary_dbhost'" ) ; } String [ ] dbHosts = getParamString ( "secondary_dbhost" ) . split ( "," ) ; for ( int attempt = 1 ; ! dbConn . isOpen ( ) && attempt <= dbHosts . length ; attempt ++ ) { try { dbConn . connect ( chooseHost ( dbHosts ) ) ; } catch ( DBNotAvailableException e ) { lastException = e ; } catch ( RuntimeException ex ) { throw ex ; } } if ( dbConn . isOpen ( ) ) { m_bUseSecondaryHosts = true ; } } if ( ! dbConn . isOpen ( ) ) { m_logger . error ( "All Thrift connection attempts failed." , lastException ) ; throw lastException ; } } | configured keyspace is not available a RuntimeException is thrown . |
18,032 | private DBConn createAndConnectConn ( String keyspace ) throws DBNotAvailableException , RuntimeException { DBConn dbConn = new DBConn ( this , keyspace ) ; connectDBConn ( dbConn ) ; return dbConn ; } | the given keyspace does not exist . |
18,033 | private String chooseHost ( String [ ] dbHosts ) { String host = null ; synchronized ( m_lastHostLock ) { if ( dbHosts . length == 1 ) { host = dbHosts [ 0 ] ; } else if ( ! Utils . isEmpty ( m_lastHost ) ) { for ( int index = 0 ; host == null && index < dbHosts . length ; index ++ ) { if ( dbHosts [ index ] . equals ( m_lastHost ) ) { host = dbHosts [ ( ++ index ) % dbHosts . length ] ; } } } if ( host == null ) { host = dbHosts [ new Random ( ) . nextInt ( dbHosts . length ) ] ; } m_lastHost = host ; } return host ; } | Choose the next Cassandra host name in the list or a random one . |
18,034 | public void deleteValuesForField ( ) { for ( String targetObjID : m_dbObj . getFieldValues ( m_fieldName ) ) { deleteLinkInverseValue ( targetObjID ) ; } if ( m_linkDef . isSharded ( ) ) { deleteShardedLinkTermRows ( ) ; } } | Clean - up inverses and sharded term rows . |
18,035 | private void addInverseLinkValue ( String targetObjID ) { int shardNo = m_tableDef . getShardNumber ( m_dbObj ) ; if ( shardNo > 0 && m_invLinkDef . isSharded ( ) ) { m_dbTran . addShardedLinkValue ( targetObjID , m_invLinkDef , m_dbObj . getObjectID ( ) , shardNo ) ; } else { m_dbTran . addLinkValue ( targetObjID , m_invLinkDef , m_dbObj . getObjectID ( ) ) ; } m_dbTran . addIDValueColumn ( m_invTableDef , targetObjID ) ; int targetShardNo = getTargetObjectShardNumber ( targetObjID ) ; m_dbTran . addAllObjectsColumn ( m_invTableDef , targetObjID , targetShardNo ) ; } | for the inverse reference . |
18,036 | private void addLinkValue ( String targetObjID ) { int targetShardNo = getTargetObjectShardNumber ( targetObjID ) ; if ( targetShardNo > 0 && m_linkDef . isSharded ( ) ) { m_dbTran . addShardedLinkValue ( m_dbObj . getObjectID ( ) , m_linkDef , targetObjID , targetShardNo ) ; } else { m_dbTran . addLinkValue ( m_dbObj . getObjectID ( ) , m_linkDef , targetObjID ) ; } addInverseLinkValue ( targetObjID ) ; } | Add mutations to add a reference via our link to the given target object ID . |
18,037 | private int getTargetObjectShardNumber ( String targetObjID ) { int targetShardNo = 0 ; if ( m_invTableDef . isSharded ( ) && m_targetObjShardNos != null && m_targetObjShardNos . containsKey ( targetObjID ) ) { targetShardNo = m_targetObjShardNos . get ( targetObjID ) ; } return targetShardNo ; } | Get the shard number of the target object ID if cached . |
18,038 | private void deleteLinkInverseValue ( String targetObjID ) { int shardNo = m_tableDef . getShardNumber ( m_dbObj ) ; if ( shardNo > 0 && m_invLinkDef . isSharded ( ) ) { m_dbTran . deleteShardedLinkValue ( targetObjID , m_invLinkDef , m_dbObj . getObjectID ( ) , shardNo ) ; } else { m_dbTran . deleteLinkValue ( targetObjID , m_invLinkDef , m_dbObj . getObjectID ( ) ) ; } } | Delete the inverse reference to the given target object ID . |
18,039 | private void deleteLinkValue ( String targetObjID ) { int targetShardNo = getTargetObjectShardNumber ( targetObjID ) ; if ( targetShardNo > 0 && m_linkDef . isSharded ( ) ) { m_dbTran . deleteShardedLinkValue ( targetObjID , m_linkDef , m_dbObj . getObjectID ( ) , targetShardNo ) ; } else { m_dbTran . deleteLinkValue ( m_dbObj . getObjectID ( ) , m_linkDef , targetObjID ) ; } deleteLinkInverseValue ( targetObjID ) ; } | Delete the reference via our link to the given target object ID and its inverse . |
18,040 | private void deleteShardedLinkTermRows ( ) { Set < Integer > shardNums = SpiderService . instance ( ) . getShards ( m_invTableDef ) . keySet ( ) ; for ( Integer shardNumber : shardNums ) { m_dbTran . deleteShardedLinkRow ( m_linkDef , m_dbObj . getObjectID ( ) , shardNumber ) ; } } | Delete all possible term rows that might exist for our sharded link . |
18,041 | private boolean updateLinkAddValues ( ) { List < String > linkValues = m_dbObj . getFieldValues ( m_linkDef . getName ( ) ) ; if ( linkValues == null || linkValues . size ( ) == 0 ) { return false ; } Set < String > linkValueSet = new HashSet < > ( linkValues ) ; for ( String targetObjID : linkValueSet ) { addLinkValue ( targetObjID ) ; } return true ; } | Add new values for our link . Return true if at least one update made . |
18,042 | private boolean updateLinkRemoveValues ( ) { Set < String > removeSet = m_dbObj . getRemoveValues ( m_fieldName ) ; List < String > addSet = m_dbObj . getFieldValues ( m_fieldName ) ; if ( removeSet != null && addSet != null ) { removeSet . removeAll ( addSet ) ; } if ( removeSet == null || removeSet . size ( ) == 0 ) { return false ; } for ( String removeObjID : removeSet ) { deleteLinkValue ( removeObjID ) ; } return true ; } | Process removes for our link . Return true if at least one update made . |
18,043 | public synchronized void clear ( ApplicationDefinition appDef ) { String appName = appDef . getAppName ( ) ; for ( TableDefinition tableDef : appDef . getTableDefinitions ( ) . values ( ) ) { m_cacheMap . remove ( appName + "/" + tableDef . getTableName ( ) ) ; } m_appShardMap . remove ( appName ) ; } | Clear all cached shard information for the given application . |
18,044 | public synchronized void verifyShard ( TableDefinition tableDef , int shardNumber ) { assert tableDef != null ; assert tableDef . isSharded ( ) ; assert shardNumber > 0 ; Map < String , Map < Integer , Date > > tableMap = m_appShardMap . get ( tableDef . getAppDef ( ) . getAppName ( ) ) ; if ( tableMap != null ) { Map < Integer , Date > shardMap = tableMap . get ( tableDef . getTableName ( ) ) ; if ( shardMap != null ) { if ( shardMap . containsKey ( shardNumber ) ) { return ; } } } Date shardDate = tableDef . computeShardStart ( shardNumber ) ; addShardStart ( tableDef , shardNumber , shardDate ) ; } | Verify that the shard with the given number has been registered for the given table . If it hasn t the shard s starting date is computed the shard is registered in the _shards row and the start date is cached . |
18,045 | private void addShardStart ( TableDefinition tableDef , int shardNumber , Date shardDate ) { SpiderTransaction spiderTran = new SpiderTransaction ( ) ; spiderTran . addShardStart ( tableDef , shardNumber , shardDate ) ; Tenant tenant = Tenant . getTenant ( tableDef ) ; DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; spiderTran . applyUpdates ( dbTran ) ; DBService . instance ( tenant ) . commit ( dbTran ) ; synchronized ( this ) { cacheShardValue ( tableDef , shardNumber , shardDate ) ; } } | Create a local transaction to add the register the given shard then cache it . |
18,046 | private void cacheShardValue ( TableDefinition tableDef , Integer shardNumber , Date shardStart ) { String appName = tableDef . getAppDef ( ) . getAppName ( ) ; Map < String , Map < Integer , Date > > tableShardNumberMap = m_appShardMap . get ( appName ) ; if ( tableShardNumberMap == null ) { tableShardNumberMap = new HashMap < String , Map < Integer , Date > > ( ) ; m_appShardMap . put ( appName , tableShardNumberMap ) ; } String tableName = tableDef . getTableName ( ) ; Map < Integer , Date > shardNumberMap = tableShardNumberMap . get ( tableName ) ; if ( shardNumberMap == null ) { shardNumberMap = new HashMap < Integer , Date > ( ) ; tableShardNumberMap . put ( tableName , shardNumberMap ) ; } shardNumberMap . put ( shardNumber , shardStart ) ; m_logger . debug ( "Sharding date for {}.{} shard #{} set to: {} ({})" , new Object [ ] { appName , tableName , shardNumber , shardStart . getTime ( ) , Utils . formatDateUTC ( shardStart ) } ) ; } | Cache the given shard . |
18,047 | private void loadShardCache ( TableDefinition tableDef ) { String appName = tableDef . getAppDef ( ) . getAppName ( ) ; String tableName = tableDef . getTableName ( ) ; m_logger . debug ( "Loading shard cache for {}.{}" , appName , tableName ) ; Date cacheDate = new Date ( ) ; String cacheKey = appName + "/" + tableName ; m_cacheMap . put ( cacheKey , cacheDate ) ; Map < String , Map < Integer , Date > > tableMap = m_appShardMap . get ( appName ) ; if ( tableMap == null ) { tableMap = new HashMap < > ( ) ; m_appShardMap . put ( appName , tableMap ) ; } Map < Integer , Date > shardMap = tableMap . get ( tableName ) ; if ( shardMap == null ) { shardMap = new HashMap < > ( ) ; tableMap . put ( tableName , shardMap ) ; } Tenant tenant = Tenant . getTenant ( tableDef ) ; String storeName = SpiderService . termsStoreName ( tableDef ) ; for ( DColumn col : DBService . instance ( tenant ) . getAllColumns ( storeName , SpiderTransaction . SHARDS_ROW_KEY ) ) { Integer shardNum = Integer . parseInt ( col . getName ( ) ) ; Date shardDate = new Date ( Long . parseLong ( col . getValue ( ) ) ) ; shardMap . put ( shardNum , shardDate ) ; } } | worry about concurrency . |
18,048 | private boolean isTooOld ( Date cacheDate ) { Date now = new Date ( ) ; return now . getTime ( ) - cacheDate . getTime ( ) > MAX_CACHE_TIME_MILLIS ; } | Return true if given date has exceeded MAX_CACHE_TIME_MILLIS time . |
18,049 | public ObjectResult addNewObject ( SpiderTransaction parentTran , DBObject dbObj ) { ObjectResult result = new ObjectResult ( ) ; try { addBrandNewObject ( dbObj ) ; result . setObjectID ( dbObj . getObjectID ( ) ) ; result . setUpdated ( true ) ; parentTran . mergeSubTransaction ( m_dbTran ) ; m_logger . trace ( "addNewObject(): Object added/updated for ID={}" , dbObj . getObjectID ( ) ) ; } catch ( Throwable ex ) { buildErrorStatus ( result , dbObj . getObjectID ( ) , ex ) ; } return result ; } | Add the given DBObject to the database as a new object . No check is made to see if an object with the same ID already exists . If the update is successful updates are merged to the given parent SpiderTransaction . |
18,050 | public ObjectResult deleteObject ( SpiderTransaction parentTran , String objID ) { ObjectResult result = new ObjectResult ( objID ) ; try { result . setObjectID ( objID ) ; DBObject dbObj = SpiderService . instance ( ) . getObject ( m_tableDef , objID ) ; if ( dbObj != null ) { deleteObject ( dbObj ) ; result . setUpdated ( true ) ; parentTran . mergeSubTransaction ( m_dbTran ) ; m_logger . trace ( "deleteObject(): object deleted with ID={}" , objID ) ; } else { result . setComment ( "Object not found" ) ; m_logger . trace ( "deleteObject(): no object with ID={}" , objID ) ; } } catch ( Throwable ex ) { buildErrorStatus ( result , objID , ex ) ; } return result ; } | Delete the object with the given object ID . Because of idempotent update semantics it is not an error if the object does not exist . If an object is actually deleted updates are merged to the given parent SpiderTransaction . |
18,051 | public ObjectResult updateObject ( SpiderTransaction parentTran , DBObject dbObj , Map < String , String > currScalarMap ) { ObjectResult result = new ObjectResult ( ) ; try { result . setObjectID ( dbObj . getObjectID ( ) ) ; boolean bUpdated = updateExistingObject ( dbObj , currScalarMap ) ; result . setUpdated ( bUpdated ) ; if ( bUpdated ) { m_logger . trace ( "updateObject(): object updated for ID={}" , dbObj . getObjectID ( ) ) ; parentTran . mergeSubTransaction ( m_dbTran ) ; } else { result . setComment ( "No updates made" ) ; m_logger . trace ( "updateObject(): no updates made for ID={}" , dbObj . getObjectID ( ) ) ; } } catch ( Throwable ex ) { buildErrorStatus ( result , dbObj . getObjectID ( ) , ex ) ; } return result ; } | Update the given object whose current values have been pre - fetched . The object must exist and the values in the given DBObject are compared to the given current values to determine which ones are being added or updated . If an update is actually made updates are merged to the given parent SpiderTransaction . |
18,052 | private boolean addBrandNewObject ( DBObject dbObj ) { if ( Utils . isEmpty ( dbObj . getObjectID ( ) ) ) { dbObj . setObjectID ( Utils . base64FromBinary ( IDGenerator . nextID ( ) ) ) ; } checkForNewShard ( dbObj ) ; for ( String fieldName : dbObj . getUpdatedFieldNames ( ) ) { FieldUpdater fieldUpdater = FieldUpdater . createFieldUpdater ( this , dbObj , fieldName ) ; fieldUpdater . addValuesForField ( ) ; } return true ; } | Add new object to the database . |
18,053 | private void buildErrorStatus ( ObjectResult result , String objID , Throwable ex ) { result . setStatus ( ObjectResult . Status . ERROR ) ; result . setErrorMessage ( ex . getLocalizedMessage ( ) ) ; if ( ! Utils . isEmpty ( objID ) ) { result . setObjectID ( objID ) ; } if ( ex instanceof IllegalArgumentException ) { m_logger . debug ( "Object update error: {}" , ex . toString ( ) ) ; } else { result . setStackTrace ( Utils . getStackTrace ( ex ) ) ; m_logger . debug ( "Object update error: {} stacktrace: {}" , ex . toString ( ) , Utils . getStackTrace ( ex ) ) ; } } | Add error fields to the given ObjectResult due to the given exception . |
18,054 | private void checkForNewShard ( DBObject dbObj ) { int shardNumber = m_tableDef . getShardNumber ( dbObj ) ; if ( shardNumber > 0 ) { SpiderService . instance ( ) . verifyShard ( m_tableDef , shardNumber ) ; } } | If object is sharded see if we need to add a new column to the current shards row . |
18,055 | private void checkNewlySharded ( DBObject dbObj , Map < String , String > currScalarMap ) { if ( ! m_tableDef . isSharded ( ) ) { return ; } String shardingFieldName = m_tableDef . getShardingField ( ) . getName ( ) ; if ( ! currScalarMap . containsKey ( shardingFieldName ) ) { m_dbTran . addAllObjectsColumn ( m_tableDef , dbObj . getObjectID ( ) , m_tableDef . getShardNumber ( dbObj ) ) ; } } | previously undetermined but is not being assigned to a shard . |
18,056 | private void deleteObject ( DBObject dbObj ) { for ( String fieldName : dbObj . getUpdatedFieldNames ( ) ) { FieldUpdater fieldUpdater = FieldUpdater . createFieldUpdater ( this , dbObj , fieldName ) ; fieldUpdater . deleteValuesForField ( ) ; } m_dbTran . deleteObjectRow ( m_tableDef , dbObj . getObjectID ( ) ) ; } | Delete term columns and inverses for field values and the object s primary row . |
18,057 | private boolean updateExistingObject ( DBObject dbObj , Map < String , String > currScalarMap ) { if ( objectIsChangingShards ( dbObj , currScalarMap ) ) { return updateShardedObjectMove ( dbObj ) ; } else { return updateObjectSameShard ( dbObj , currScalarMap ) ; } } | Update the given object using the appropriate strategy . |
18,058 | private boolean updateObjectSameShard ( DBObject dbObj , Map < String , String > currScalarMap ) { boolean bUpdated = false ; checkForNewShard ( dbObj ) ; checkNewlySharded ( dbObj , currScalarMap ) ; for ( String fieldName : dbObj . getUpdatedFieldNames ( ) ) { FieldUpdater fieldUpdater = FieldUpdater . createFieldUpdater ( this , dbObj , fieldName ) ; bUpdated |= fieldUpdater . updateValuesForField ( currScalarMap . get ( fieldName ) ) ; } return bUpdated ; } | through here . |
18,059 | private boolean updateShardedObjectMove ( DBObject dbObj ) { DBObject currDBObj = SpiderService . instance ( ) . getObject ( m_tableDef , dbObj . getObjectID ( ) ) ; m_logger . debug ( "Update forcing move of object {} from shard {} to shard {}" , new Object [ ] { dbObj . getObjectID ( ) , m_tableDef . getShardNumber ( currDBObj ) , m_tableDef . getShardNumber ( dbObj ) } ) ; deleteObject ( currDBObj ) ; mergeAllFieldValues ( dbObj , currDBObj ) ; addBrandNewObject ( currDBObj ) ; return true ; } | delete the current object merge the new fields into it and re - add it . |
18,060 | private boolean objectIsChangingShards ( DBObject dbObj , Map < String , String > currScalarMap ) { if ( ! m_tableDef . isSharded ( ) ) { return false ; } int oldShardNumber = 0 ; String shardingFieldName = m_tableDef . getShardingField ( ) . getName ( ) ; String currShardFieldValue = currScalarMap . get ( shardingFieldName ) ; if ( currShardFieldValue != null ) { oldShardNumber = m_tableDef . computeShardNumber ( Utils . dateFromString ( currShardFieldValue ) ) ; } int newShardNumber = m_tableDef . getShardNumber ( dbObj ) ; String newShardFieldValue = dbObj . getFieldValue ( shardingFieldName ) ; if ( newShardFieldValue == null && currShardFieldValue != null ) { dbObj . addFieldValue ( shardingFieldName , currShardFieldValue ) ; return false ; } return oldShardNumber != newShardNumber ; } | moved to a new shard . |
18,061 | public RESTClient getClient ( SSLTransportParameters sslParams ) { if ( m_cellRing == null ) { throw new IllegalStateException ( "Empty pool" ) ; } Cell currentCell = m_cellRing ; StringBuilder errorMessage = new StringBuilder ( ) ; do { try { RESTClient client = new RESTClient ( sslParams , m_cellRing . m_hostName , m_port ) ; client . setCredentials ( m_credentials ) ; m_cellRing . m_hostStatus = new HostStatus ( ) ; client . setAcceptType ( m_defaultContentType ) ; client . setCompression ( m_defaultCompression ) ; return client ; } catch ( RuntimeException e ) { m_cellRing . m_hostStatus = new HostStatus ( false , e ) ; errorMessage . append ( "Couldn\'t connect to " + m_cellRing . m_hostName ) . append ( "; reason: " + e . getMessage ( ) + "\n" ) ; } finally { m_cellRing = m_cellRing . next ; } } while ( currentCell != m_cellRing ) ; throw new IllegalStateException ( "No active connections found\n" + errorMessage ) ; } | Tries to connect to the next host . If no host is available IllegalStateException will be raised . |
18,062 | public Map < String , HostStatus > getState ( ) { Map < String , HostStatus > map = new HashMap < > ( ) ; if ( m_cellRing != null ) { Cell currentCell = m_cellRing ; do { map . put ( currentCell . m_hostName , currentCell . m_hostStatus ) ; currentCell = currentCell . next ; } while ( currentCell != m_cellRing ) ; } return map ; } | Generates a map of the last state of the attempts of the connections . Useful in a situation when a getClient method ended in exception then this method can show the reasons of refusals . |
18,063 | private void addToRing ( String host ) { Cell newCell = new Cell ( ) ; newCell . m_hostName = host ; if ( m_cellRing == null ) { newCell . next = newCell ; } else { newCell . next = m_cellRing . next ; m_cellRing . next = newCell ; } m_cellRing = newCell ; } | Adds a new host to a cells ring . |
18,064 | private static Mutation createMutation ( byte [ ] colName , byte [ ] colValue , long timestamp ) { if ( colValue == null ) { colValue = EMPTY_BYTES ; } Column col = new Column ( ) ; col . setName ( colName ) ; col . setValue ( colValue ) ; col . setTimestamp ( timestamp ) ; ColumnOrSuperColumn cosc = new ColumnOrSuperColumn ( ) ; cosc . setColumn ( col ) ; Mutation mutation = new Mutation ( ) ; mutation . setColumn_or_supercolumn ( cosc ) ; return mutation ; } | Create a Mutation with the given column name and column value |
18,065 | private static Mutation createDeleteColumnMutation ( byte [ ] colName , long timestamp ) { SlicePredicate slicePred = new SlicePredicate ( ) ; slicePred . addToColumn_names ( ByteBuffer . wrap ( colName ) ) ; Deletion deletion = new Deletion ( ) ; deletion . setPredicate ( slicePred ) ; deletion . setTimestamp ( timestamp ) ; Mutation mutation = new Mutation ( ) ; mutation . setDeletion ( deletion ) ; return mutation ; } | Create a column mutation that deletes the given column name . |
18,066 | public static long gcd ( long x , long y ) { if ( x < 0 ) x = - x ; if ( y < 0 ) y = - y ; if ( x < y ) { long temp = x ; x = y ; y = temp ; } long gcd = 1 ; while ( y > 1 ) { if ( ( x & 1 ) == 0 ) { if ( ( y & 1 ) == 0 ) { gcd <<= 1 ; x >>= 1 ; y >>= 1 ; } else { x >>= 1 ; } } else { if ( ( y & 1 ) == 0 ) { y >>= 1 ; } else { x = ( x - y ) >> 1 ; } } if ( x < y ) { long temp = x ; x = y ; y = temp ; } } return y == 1 ? gcd : gcd * x ; } | greatest common divisor |
18,067 | ColumnOrSuperColumn getColumn ( ByteBuffer key , ColumnPath colPath ) { m_logger . debug ( "Fetching {}.{}" , new Object [ ] { Utils . toString ( key ) , toString ( colPath ) } ) ; ColumnOrSuperColumn column = null ; boolean bSuccess = false ; for ( int attempts = 1 ; ! bSuccess ; attempts ++ ) { try { Date startDate = new Date ( ) ; column = m_client . get ( key , colPath , ConsistencyLevel . ONE ) ; timing ( "get" , startDate ) ; if ( attempts > 1 ) { m_logger . info ( "get() succeeded on attempt #{}" , attempts ) ; } bSuccess = true ; } catch ( NotFoundException ex ) { return null ; } catch ( InvalidRequestException ex ) { String errMsg = "get() failed for table: " + colPath . getColumn_family ( ) ; m_bFailed = true ; m_logger . error ( errMsg , ex ) ; throw new RuntimeException ( errMsg , ex ) ; } catch ( Exception ex ) { if ( attempts >= m_max_read_attempts ) { String errMsg = "All retries exceeded; abandoning get() for table: " + colPath . getColumn_family ( ) ; m_bFailed = true ; m_logger . error ( errMsg , ex ) ; throw new RuntimeException ( errMsg , ex ) ; } m_logger . warn ( "get() attempt #{} failed: {}" , attempts , ex ) ; try { Thread . sleep ( attempts * m_retry_wait_millis ) ; } catch ( InterruptedException e1 ) { } reconnect ( ex ) ; } } return column ; } | Fetch a single column . |
18,068 | private void commitDeletes ( DBTransaction dbTran , long timestamp ) { Map < String , Set < ByteBuffer > > rowDeleteMap = CassandraTransaction . getRowDeletionMap ( dbTran ) ; if ( rowDeleteMap . size ( ) == 0 ) { return ; } for ( String colFamName : rowDeleteMap . keySet ( ) ) { Set < ByteBuffer > rowKeySet = rowDeleteMap . get ( colFamName ) ; for ( ByteBuffer rowKey : rowKeySet ) { removeRow ( timestamp , rowKey , new ColumnPath ( colFamName ) ) ; } } } | Commit all row - deletions in the given MutationMap if any using the given timestamp . |
18,069 | private void commitMutations ( DBTransaction dbTran , long timestamp ) { Map < ByteBuffer , Map < String , List < Mutation > > > colMutMap = CassandraTransaction . getUpdateMap ( dbTran , timestamp ) ; if ( colMutMap . size ( ) == 0 ) { return ; } m_logger . debug ( "Committing {} mutations" , CassandraTransaction . totalColumnMutations ( dbTran ) ) ; boolean bSuccess = false ; for ( int attempts = 1 ; ! bSuccess ; attempts ++ ) { try { Date startDate = new Date ( ) ; m_client . batch_mutate ( colMutMap , ConsistencyLevel . ONE ) ; timing ( "commitMutations" , startDate ) ; if ( attempts > 1 ) { m_logger . info ( "batch_mutate() succeeded on attempt #{}" , attempts ) ; } bSuccess = true ; } catch ( InvalidRequestException ex ) { m_bFailed = true ; m_logger . error ( "batch_mutate() failed" , ex ) ; throw new RuntimeException ( "batch_mutate() failed" , ex ) ; } catch ( Exception ex ) { if ( attempts >= m_max_commit_attempts ) { m_bFailed = true ; m_logger . error ( "All retries exceeded; abandoning batch_mutate()" , ex ) ; throw new RuntimeException ( "All retries exceeded; abandoning batch_mutate()" , ex ) ; } m_logger . warn ( "batch_mutate() attempt #{} failed: {}" , attempts , ex ) ; try { Thread . sleep ( attempts * m_retry_wait_millis ) ; } catch ( InterruptedException e1 ) { } reconnect ( ex ) ; } } } | configured maximum number of retries . |
18,070 | private void reconnect ( Exception reconnectEx ) { m_logger . warn ( "Reconnecting to Cassandra due to error" , reconnectEx ) ; boolean bSuccess = false ; for ( int attempt = 1 ; ! bSuccess ; attempt ++ ) { try { close ( ) ; m_dbService . connectDBConn ( this ) ; m_logger . debug ( "Reconnect successful" ) ; bSuccess = true ; } catch ( Exception ex ) { if ( attempt >= m_max_reconnect_attempts ) { m_logger . error ( "All reconnect attempts failed; abandoning reconnect" , ex ) ; throw new DBNotAvailableException ( "All reconnect attempts failed" , ex ) ; } m_logger . warn ( "Reconnect attempt #" + attempt + " failed" , ex ) ; try { Thread . sleep ( m_retry_wait_millis * attempt ) ; } catch ( InterruptedException e ) { } } } } | an DBNotAvailableException and leave the Thrift connection null . |
18,071 | private void timing ( String metric , Date startDate ) { m_logger . trace ( "Time for '{}': {}" , metric , ( ( new Date ( ) ) . getTime ( ) - startDate . getTime ( ) ) + " millis" ) ; } | milliseconds using the given prefix as a label . |
18,072 | public void startElement ( String elemName , String attrName , String attrValue ) { AttributesImpl attrs = new AttributesImpl ( ) ; attrs . addAttribute ( "" , attrName , "" , "CDATA" , attrValue ) ; writeStartElement ( elemName , attrs ) ; m_tagStack . push ( elemName ) ; } | Start a new XML element using the given start tag and single attribute . |
18,073 | public void startElement ( String elemName , Attributes attrs ) { writeStartElement ( elemName , attrs ) ; m_tagStack . push ( elemName ) ; } | Start a new XML element using the given name and attribute set . |
18,074 | public void addDataElement ( String elemName , String content , Attributes attrs ) { writeDataElement ( elemName , attrs , content ) ; } | Same as above but using an attribute set . |
18,075 | private Attributes toAttributes ( Map < String , String > attrs ) { AttributesImpl impl = new AttributesImpl ( ) ; for ( Map . Entry < String , String > attr : attrs . entrySet ( ) ) { impl . addAttribute ( "" , attr . getKey ( ) , "" , "CDATA" , attr . getValue ( ) ) ; } return impl ; } | Converts attribute map to Attributes class instance . |
18,076 | public static boolean isValidName ( String appName ) { return appName != null && appName . length ( ) > 0 && Utils . isLetter ( appName . charAt ( 0 ) ) && Utils . allAlphaNumUnderscore ( appName ) ; } | Test the given string for validity as an application name . A valid application name must begin with a letter and contain only letters digits and underscores . |
18,077 | public void parse ( UNode appNode ) { assert appNode != null ; setAppName ( appNode . getName ( ) ) ; for ( String childName : appNode . getMemberNames ( ) ) { UNode childNode = appNode . getMember ( childName ) ; if ( childName . equals ( "key" ) ) { Utils . require ( childNode . isValue ( ) , "'key' value must be a string: " + childNode ) ; Utils . require ( m_key == null , "'key' can be specified only once" ) ; m_key = childNode . getValue ( ) ; } else if ( childName . equals ( "options" ) ) { for ( String optName : childNode . getMemberNames ( ) ) { UNode optNode = childNode . getMember ( optName ) ; Utils . require ( optNode . isValue ( ) , "'option' must be a value: " + optNode ) ; setOption ( optNode . getName ( ) , optNode . getValue ( ) ) ; } } else if ( childName . equals ( "tables" ) ) { Utils . require ( m_tableMap . size ( ) == 0 , "'tables' can be specified only once" ) ; for ( UNode tableNode : childNode . getMemberList ( ) ) { TableDefinition tableDef = new TableDefinition ( ) ; tableDef . parse ( tableNode ) ; addTable ( tableDef ) ; } } else { Utils . require ( false , "Unrecognized 'application' element: " + childName ) ; } } verify ( ) ; } | Parse the application definition rooted at given UNode tree and copy its contents into this object . The root node is the application object so its name is the application name and its child nodes are definitions such as key options fields etc . An exception is thrown if the definition contains an error . |
18,078 | public boolean allowsAutoTables ( ) { String optValue = getOption ( CommonDefs . AUTO_TABLES ) ; return optValue != null && optValue . equalsIgnoreCase ( "true" ) ; } | Indicate whether or not this application tables to be implicitly created . |
18,079 | public void setOption ( String optName , String optValue ) { if ( optValue == null ) { m_optionMap . remove ( optName ) ; } else { m_optionMap . put ( optName , optValue . trim ( ) ) ; } } | Set the option with the given name to the given value . If the option value is null the option is unset . If the option has an existing value it is replaced . |
18,080 | public void removeTableDef ( TableDefinition tableDef ) { assert tableDef != null ; assert tableDef . getAppDef ( ) == this ; m_tableMap . remove ( tableDef . getTableName ( ) ) ; } | Remove the given table from this application presumably because it has been deleted . |
18,081 | private void verify ( ) { List < TableDefinition > definedTables = new ArrayList < > ( m_tableMap . values ( ) ) ; for ( TableDefinition tableDef : definedTables ) { List < FieldDefinition > definedFields = new ArrayList < > ( tableDef . getFieldDefinitions ( ) ) ; for ( FieldDefinition fieldDef : definedFields ) { if ( fieldDef . isLinkType ( ) ) { verifyLink ( tableDef , fieldDef ) ; } } } } | complete and in agreement . |
18,082 | private void verifyLink ( TableDefinition tableDef , FieldDefinition linkDef ) { String extent = linkDef . getLinkExtent ( ) ; TableDefinition extentTableDef = getTableDef ( extent ) ; if ( extentTableDef == null ) { extentTableDef = new TableDefinition ( ) ; extentTableDef . setTableName ( extent ) ; tableDef . getAppDef ( ) . addTable ( extentTableDef ) ; } String inverse = linkDef . getLinkInverse ( ) ; FieldDefinition inverseLinkDef = extentTableDef . getFieldDef ( inverse ) ; if ( inverseLinkDef == null ) { inverseLinkDef = new FieldDefinition ( inverse ) ; inverseLinkDef . setType ( linkDef . getType ( ) ) ; inverseLinkDef . setLinkInverse ( linkDef . getName ( ) ) ; inverseLinkDef . setLinkExtent ( tableDef . getTableName ( ) ) ; extentTableDef . addFieldDefinition ( inverseLinkDef ) ; } else { Utils . require ( inverseLinkDef . getType ( ) == linkDef . getType ( ) && inverseLinkDef . getLinkExtent ( ) . equals ( tableDef . getTableName ( ) ) && inverseLinkDef . getLinkInverse ( ) . equals ( linkDef . getName ( ) ) , "Link '%s' in table '%s' conflicts with inverse field '%s' in table '%s'" , linkDef . getName ( ) , tableDef . getTableName ( ) , inverseLinkDef . getName ( ) , extentTableDef . getTableName ( ) ) ; } } | has not been defined add it automatically . |
18,083 | public String replaceAliaces ( String str ) { if ( str == null ) return str ; if ( str . indexOf ( CommonDefs . ALIAS_FIRST_CHAR ) < 0 ) return str ; PriorityQueue < AliasDefinition > aliasQueue = new PriorityQueue < AliasDefinition > ( 11 , new Comparator < AliasDefinition > ( ) { public int compare ( AliasDefinition alias1 , AliasDefinition alias2 ) { return alias2 . getName ( ) . length ( ) - alias1 . getName ( ) . length ( ) ; } } ) ; for ( TableDefinition tableDef : getTableDefinitions ( ) . values ( ) ) { for ( AliasDefinition aliasDef : tableDef . getAliasDefinitions ( ) ) { aliasQueue . add ( aliasDef ) ; } } while ( true ) { String newstring = str ; while ( aliasQueue . size ( ) != 0 ) { AliasDefinition aliasDef = aliasQueue . poll ( ) ; newstring = newstring . replace ( aliasDef . getName ( ) , aliasDef . getExpression ( ) ) ; } if ( newstring . equals ( str ) ) break ; str = newstring ; } return str ; } | Replaces of all occurences of aliases defined with this table by their expressions . Now a simple string . replace is used . |
18,084 | public void register ( ) { try { objectName = consObjectName ( domain , type , keysString ) ; MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; mbs . registerMBean ( this , objectName ) ; } catch ( Exception e ) { objectName = null ; throw new RuntimeException ( e ) ; } } | Registers this bean on platform MBeanServer . |
18,085 | public void deregister ( ) { if ( objectName == null ) { return ; } try { MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; if ( mbs . isRegistered ( objectName ) ) { mbs . unregisterMBean ( objectName ) ; } objectName = null ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Deregisters this bean on platform MBeanServer . |
18,086 | protected ObjectName consObjectName ( String domain , String type , String keysString ) { String d = domain != null && ! "" . equals ( domain ) ? domain : getDefaultDomain ( ) ; String t = type != null && ! "" . equals ( type ) ? type : getDefaultType ( ) ; String k = keysString != null && ! "" . equals ( keysString ) ? "," + keysString : "" ; try { return new ObjectName ( d + ":type=" + t + k ) ; } catch ( MalformedObjectNameException e ) { throw new IllegalArgumentException ( e ) ; } } | Constructs the ObjectName of bean . |
18,087 | private void push ( Construct construct ) { check ( m_stackPos < MAX_STACK_DEPTH , "Too many JSON nested levels (maximum=" + MAX_STACK_DEPTH + ")" ) ; m_stack [ m_stackPos ++ ] = construct ; } | Push the given node onto the node stack . |
18,088 | public RESTResponse call ( RESTClient restClient ) { String methodName = getMethod ( ) ; String uri = getURI ( ) ; StringBuilder uriBuilder = new StringBuilder ( Utils . isEmpty ( restClient . getApiPrefix ( ) ) ? "" : "/" + restClient . getApiPrefix ( ) ) ; uriBuilder . append ( substitute ( uri ) ) ; uri = uriBuilder . toString ( ) ; try { byte [ ] body = getBody ( methodName ) ; RESTResponse response = sendRequest ( restClient , methodName , uri , body ) ; return response ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Call method implementation |
18,089 | public void validate ( RESTClient restClient ) { Utils . require ( this . commandName != null , "missing command name" ) ; this . metadataJson = matchCommand ( restMetadataJson , this . commandName , commandParams . containsKey ( STORAGE_SERVICE ) ? ( String ) commandParams . get ( STORAGE_SERVICE ) : _SYSTEM ) ; if ( this . metadataJson == null ) { if ( commandParams . containsKey ( STORAGE_SERVICE ) ) { this . metadataJson = matchCommand ( restMetadataJson , this . commandName , _SYSTEM ) ; } } if ( this . metadataJson == null ) { throw new RuntimeException ( "unsupported command name: " + this . commandName ) ; } validateRequiredParams ( ) ; } | Validate the command |
18,090 | private void validateRequiredParams ( ) { String [ ] uriStrings = getURI ( ) . split ( "\\?" ) ; if ( uriStrings . length > 0 ) { List < String > requiredParms = extractRequiredParamsInURI ( uriStrings [ 0 ] ) ; for ( String param : requiredParms ) { Utils . require ( commandParams . containsKey ( param ) , "missing param: " + param ) ; } } if ( metadataJson . containsKey ( INPUT_ENTITY ) ) { String paramValue = metadataJson . getString ( INPUT_ENTITY ) ; if ( paramValue != null ) { JsonObject parametersNode = metadataJson . getJsonObject ( PARAMETERS ) ; if ( parametersNode != null ) { if ( parametersNode . keySet ( ) . size ( ) == 1 ) { JsonObject params = parametersNode . getJsonObject ( parametersNode . keySet ( ) . iterator ( ) . next ( ) ) ; for ( String param : params . keySet ( ) ) { JsonObject paramNode = params . getJsonObject ( param ) ; if ( paramNode . keySet ( ) . contains ( _REQUIRED ) ) { setCompound ( true ) ; Utils . require ( commandParams . containsKey ( param ) , "missing param: " + param ) ; } } } } else { Utils . require ( commandParams . containsKey ( paramValue ) , "missing param: " + paramValue ) ; } } } } | Validate Required Params |
18,091 | private List < String > extractRequiredParamsInURI ( String uri ) { List < String > matchList = new ArrayList < String > ( ) ; Pattern regex = Pattern . compile ( "\\{(.*?)\\}" ) ; Matcher regexMatcher = regex . matcher ( uri ) ; while ( regexMatcher . find ( ) ) { matchList . add ( regexMatcher . group ( 1 ) ) ; } return matchList ; } | Extract Required Params In URI |
18,092 | private String substitute ( String uri ) { List < String > params = extractRequiredParamsInURI ( uri ) ; for ( String param : params ) { if ( param . equals ( PARAMS ) ) { uri = uri . replace ( "{" + PARAMS + "}" , Utils . urlEncode ( getParamsURI ( ) ) ) ; } else { uri = uri . replace ( "{" + param + "}" , ( String ) commandParams . get ( param ) ) ; } } return uri ; } | Substitute the params with values submittted via command builder |
18,093 | private byte [ ] getBody ( String method ) { byte [ ] body = null ; String methodsWithInputEntity = HttpMethod . POST . name ( ) + "|" + HttpMethod . PUT . name ( ) + "|" + HttpMethod . DELETE . name ( ) ; if ( method . matches ( methodsWithInputEntity ) ) { if ( isCompound ( ) ) { body = Utils . toBytes ( getQueryInputEntity ( ) ) ; } else { if ( metadataJson . containsKey ( INPUT_ENTITY ) ) { JSONable data = ( JSONable ) commandParams . get ( metadataJson . getString ( INPUT_ENTITY ) ) ; if ( data != null ) { body = Utils . toBytes ( data . toJSON ( ) ) ; } } } } return body ; } | Build the body for request |
18,094 | private RESTResponse sendRequest ( RESTClient restClient , String methodName , String uri , byte [ ] body ) throws IOException { RESTResponse response = restClient . sendRequest ( HttpMethod . methodFromString ( methodName ) , uri , ContentType . APPLICATION_JSON , body ) ; logger . debug ( "response: {}" , response . toString ( ) ) ; return response ; } | Make RESTful calls to Doradus server |
18,095 | public static JsonObject matchCommand ( JsonObject commandsJson , String commandName , String storageService ) { for ( String key : commandsJson . keySet ( ) ) { if ( key . equals ( storageService ) ) { JsonObject commandCats = commandsJson . getJsonObject ( key ) ; if ( commandCats . containsKey ( commandName ) ) { return commandCats . getJsonObject ( commandName ) ; } } } return null ; } | Finds out if a command is supported by Doradus |
18,096 | public void defineApplication ( ApplicationDefinition appDef ) { checkServiceState ( ) ; Tenant tenant = TenantService . instance ( ) . getDefaultTenant ( ) ; defineApplication ( tenant , appDef ) ; } | Create the application with the given name in the default tenant . If the given application already exists the request is treated as an application update . If the update is successfully validated its schema is stored in the database and the appropriate storage service is notified to implement required physical database changes if any . |
18,097 | public void defineApplication ( Tenant tenant , ApplicationDefinition appDef ) { checkServiceState ( ) ; appDef . setTenantName ( tenant . getName ( ) ) ; ApplicationDefinition currAppDef = checkApplicationKey ( appDef ) ; StorageService storageService = verifyStorageServiceOption ( currAppDef , appDef ) ; storageService . validateSchema ( appDef ) ; initializeApplication ( currAppDef , appDef ) ; } | Create the application with the given name in the given Tenant . If the given application already exists the request is treated as an application update . If the update is successfully validated its schema is stored in the database and the appropriate storage service is notified to implement required physical database changes if any . |
18,098 | private void checkTenants ( ) { m_logger . info ( "The following tenants and applications are defined:" ) ; Collection < Tenant > tenantList = TenantService . instance ( ) . getTenants ( ) ; for ( Tenant tenant : tenantList ) { checkTenantApps ( tenant ) ; } if ( tenantList . size ( ) == 0 ) { m_logger . info ( " <no tenants>" ) ; } } | Check to the applications for this tenant . |
18,099 | private void checkTenantApps ( Tenant tenant ) { m_logger . info ( " Tenant: {}" , tenant . getName ( ) ) ; try { Iterator < DRow > rowIter = DBService . instance ( tenant ) . getAllRows ( SchemaService . APPS_STORE_NAME ) . iterator ( ) ; if ( ! rowIter . hasNext ( ) ) { m_logger . info ( " <no applications>" ) ; } while ( rowIter . hasNext ( ) ) { DRow row = rowIter . next ( ) ; ApplicationDefinition appDef = loadAppRow ( tenant , getColumnMap ( row . getAllColumns ( 1024 ) . iterator ( ) ) ) ; if ( appDef != null ) { String appName = appDef . getAppName ( ) ; String ssName = getStorageServiceOption ( appDef ) ; m_logger . info ( " Application '{}': StorageService={}; keyspace={}" , new Object [ ] { appName , ssName , tenant . getName ( ) } ) ; if ( DoradusServer . instance ( ) . findStorageService ( ssName ) == null ) { m_logger . warn ( " >>>Application '{}' uses storage service '{}' which has not been " + "initialized; application will not be accessible via this server" , appDef . getAppName ( ) , ssName ) ; } } } } catch ( Exception e ) { m_logger . warn ( "Could not check tenant '" + tenant . getName ( ) + "'. Applications may be unavailable." , e ) ; } } | Check that this tenant its applications and storage managers are available . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.