name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
shardingsphere-elasticjob_JobNodePath_getInstancesNodePath_rdh
/** * Get instances node path. * * @return instances node path */ public String getInstancesNodePath() { return String.format("/%s/%s", jobName, INSTANCES_NODE); }
3.26
shardingsphere-elasticjob_JobNodePath_getFullPath_rdh
/** * Get full path. * * @param node * node * @return full path */ public String getFullPath(final String node) { return String.format("/%s/%s", jobName, node); }
3.26
shardingsphere-elasticjob_JobNodePath_getServerNodePath_rdh
/** * Get server node path. * * @param serverIp * server IP address * @return server node path */ public String getServerNodePath(final String serverIp) { return String.format("%s/%s", getServerNodePath(), serverIp); }
3.26
shardingsphere-elasticjob_ConfigurationService_load_rdh
/** * Load job configuration. * * @param fromCache * load from cache or not * @return job configuration */ public JobConfiguration load(final boolean fromCache) { String result; if (fromCache) { result = jobNodeStorage.getJobNodeData(ConfigurationNode.ROOT); if (null == result) { result = jobNodeStorage.getJobNodeDataDirectly(ConfigurationNode.ROOT); } } else { result = jobNodeStorage.getJobNodeDataDirectly(ConfigurationNode.ROOT); } if (result != null) { return YamlEngine.unmarshal(result, JobConfigurationPOJO.class).toJobConfiguration(); } else { throw new JobConfigurationException("JobConfiguration was not found. It maybe has been removed or has not been configured correctly."); } }
3.26
shardingsphere-elasticjob_ConfigurationService_checkMaxTimeDiffSecondsTolerable_rdh
/** * Check max time different seconds tolerable between job server and registry center. * * @throws JobExecutionEnvironmentException * throe JobExecutionEnvironmentException if exceed max time different seconds */ public void checkMaxTimeDiffSecondsTolerable() throws JobExecutionEnvironmentException { int maxTimeDiffSeconds = load(true).getMaxTimeDiffSeconds(); if (0 > maxTimeDiffSeconds) { return; } long timeDiff = Math.abs(f0.getCurrentMillis() - jobNodeStorage.getRegistryCenterTime()); if (timeDiff > (maxTimeDiffSeconds * 1000L)) { throw new JobExecutionEnvironmentException("Time different between job server and register center exceed '%s' seconds, max time different is '%s' seconds.", timeDiff / 1000, maxTimeDiffSeconds); } }
3.26
shardingsphere-elasticjob_ConfigurationService_setUpJobConfiguration_rdh
/** * Set up job configuration. * * @param jobClassName * job class name * @param jobConfig * job configuration to be updated * @return accepted job configuration */ public JobConfiguration setUpJobConfiguration(final String jobClassName, final JobConfiguration jobConfig) { checkConflictJob(jobClassName, jobConfig); if ((!jobNodeStorage.isJobNodeExisted(ConfigurationNode.ROOT)) || jobConfig.isOverwrite()) { jobNodeStorage.replaceJobNode(ConfigurationNode.ROOT, YamlEngine.marshal(JobConfigurationPOJO.fromJobConfiguration(jobConfig))); jobNodeStorage.replaceJobRootNode(jobClassName); return jobConfig; } return load(false); }
3.26
shardingsphere-elasticjob_ElasticJobListener_order_rdh
/** * Listener order, default is the lowest. * * @return order */ default int order() { return LOWEST; }
3.26
shardingsphere-elasticjob_RDBTracingStorageConfiguration_getDataSourceConfiguration_rdh
/** * Get data source configuration. * * @param dataSource * data source * @return data source configuration */ public static RDBTracingStorageConfiguration getDataSourceConfiguration(final DataSource dataSource) { RDBTracingStorageConfiguration result = new RDBTracingStorageConfiguration(dataSource.getClass().getName()); result.props.putAll(findAllGetterProperties(dataSource)); return result; }
3.26
shardingsphere-elasticjob_RDBTracingStorageConfiguration_createDataSource_rdh
/** * Create data source. * * @return data source */@SuppressWarnings({ "unchecked", "rawtypes" }) @SneakyThrows(ReflectiveOperationException.class) public DataSource createDataSource() { DataSource result = ((DataSource) (Class.forName(dataSourceClassName).getConstructor().newInstance())); Method[] methods = result.getClass().getMethods(); for (Entry<String, Object> entry : props.entrySet()) { if (SKIPPED_PROPERTY_NAMES.contains(entry.getKey())) { continue; } Optional<Method> setterMethod = findSetterMethod(methods, entry.getKey()); if (setterMethod.isPresent()) { setterMethod.get().invoke(result, entry.getValue()); } } Optional<JDBCParameterDecorator> decorator = TypedSPILoader.findService(JDBCParameterDecorator.class, result.getClass()); return decorator.isPresent() ? decorator.get().decorate(result) : result; }
3.26
shardingsphere-elasticjob_DataflowJobExecutor_process_rdh
/** * Dataflow job executor. */public final class DataflowJobExecutor implements ClassedJobItemExecutor<DataflowJob> { @Override public void process(final DataflowJob elasticJob, final JobConfiguration jobConfig, final JobRuntimeService jobRuntimeService, final ShardingContext shardingContext) { if (Boolean.parseBoolean(jobConfig.getProps().getOrDefault(DataflowJobProperties.STREAM_PROCESS_KEY, false).toString())) { streamingExecute(elasticJob, jobConfig, jobRuntimeService, shardingContext); } else { oneOffExecute(elasticJob, shardingContext); } }
3.26
shardingsphere-elasticjob_SetUpFacade_registerStartUpInfo_rdh
/** * Register start up info. * * @param enabled * enable job on startup */ public void registerStartUpInfo(final boolean enabled) { listenerManager.startAllListeners(); leaderService.electLeader(); serverService.persistOnline(enabled); instanceService.persistOnline(); if (!reconcileService.isRunning()) { reconcileService.startAsync(); } serverService.removeOfflineServers(); }
3.26
shardingsphere-elasticjob_SetUpFacade_tearDown_rdh
/** * Tear down. */ public void tearDown() { f0.removeConnStateListener("/" + this.jobName); f0.removeDataListeners("/" + this.jobName); if (reconcileService.isRunning()) { reconcileService.stopAsync(); } }
3.26
shardingsphere-elasticjob_RegistryCenterFactory_createCoordinatorRegistryCenter_rdh
/** * Create a {@link CoordinatorRegistryCenter} or return the existing one if there is one set up with the same {@code connectionString}, {@code namespace} and {@code digest} already. * * @param connectString * registry center connect string * @param namespace * registry center namespace * @param digest * registry center digest * @return registry center */ public static CoordinatorRegistryCenter createCoordinatorRegistryCenter(final String connectString, final String namespace, final String digest) { Hasher hasher = Hashing.sha256().newHasher().putString(connectString, StandardCharsets.UTF_8).putString(namespace, StandardCharsets.UTF_8); if (!Strings.isNullOrEmpty(digest)) { hasher.putString(digest, StandardCharsets.UTF_8); } HashCode hashCode = hasher.hash(); return REG_CENTER_REGISTRY.computeIfAbsent(hashCode, unused -> { CoordinatorRegistryCenter result = newCoordinatorRegistryCenter(connectString, namespace, digest); result.init(); return result; }); }
3.26
shardingsphere-elasticjob_DataSourceRegistry_registerDataSource_rdh
/** * Register data source. * * @param dataSourceConfig * data source configuration * @param dataSource * data source */ public void registerDataSource(final RDBTracingStorageConfiguration dataSourceConfig, final DataSource dataSource) { dataSources.putIfAbsent(dataSourceConfig, dataSource); }
3.26
shardingsphere-elasticjob_DataSourceRegistry_getDataSource_rdh
/** * Get {@link DataSource} by {@link RDBTracingStorageConfiguration}. * * @param dataSourceConfig * data source configuration * @return instance of {@link DataSource} */ public DataSource getDataSource(final RDBTracingStorageConfiguration dataSourceConfig) { return dataSources.computeIfAbsent(dataSourceConfig, RDBTracingStorageConfiguration::createDataSource); }
3.26
shardingsphere-elasticjob_DataSourceRegistry_getInstance_rdh
/** * Get instance of {@link DataSourceRegistry}. * * @return {@link DataSourceRegistry} singleton */ public static DataSourceRegistry getInstance() { if (null == f0) { synchronized(DataSourceRegistry.class) { if (null == f0) { f0 = new DataSourceRegistry(); } } } return f0; }
3.26
shardingsphere-elasticjob_ExecutorServiceReloader_reloadIfNecessary_rdh
/** * Reload if necessary. * * @param jobConfig * job configuration */ public synchronized void reloadIfNecessary(final JobConfiguration jobConfig) { if (jobExecutorThreadPoolSizeProviderType.equals(jobConfig.getJobExecutorThreadPoolSizeProviderType())) { return; } executorService.shutdown(); init(jobConfig); }
3.26
shardingsphere-elasticjob_JobAnnotationBuilder_generateJobConfiguration_rdh
/** * Generate job configuration from @ElasticJobConfiguration. * * @param type * The job of @ElasticJobConfiguration annotation class * @return job configuration */ public static JobConfiguration generateJobConfiguration(final Class<?> type) { ElasticJobConfiguration annotation = type.getAnnotation(ElasticJobConfiguration.class); Preconditions.checkArgument(null != annotation, "@ElasticJobConfiguration not found by class '%s'.", type); Preconditions.checkArgument(!Strings.isNullOrEmpty(annotation.jobName()), "@ElasticJobConfiguration jobName could not be empty by class '%s'.", type); JobConfiguration.Builder jobConfigurationBuilder = JobConfiguration.newBuilder(annotation.jobName(), annotation.shardingTotalCount()).shardingItemParameters(annotation.shardingItemParameters()).cron(Strings.isNullOrEmpty(annotation.cron()) ? null : annotation.cron()).timeZone(Strings.isNullOrEmpty(annotation.timeZone()) ? null : annotation.timeZone()).jobParameter(annotation.jobParameter()).monitorExecution(annotation.monitorExecution()).failover(annotation.failover()).misfire(annotation.misfire()).maxTimeDiffSeconds(annotation.maxTimeDiffSeconds()).reconcileIntervalMinutes(annotation.reconcileIntervalMinutes()).jobShardingStrategyType(Strings.isNullOrEmpty(annotation.jobShardingStrategyType()) ? null : annotation.jobShardingStrategyType()).jobExecutorThreadPoolSizeProviderType(Strings.isNullOrEmpty(annotation.jobExecutorThreadPoolSizeProviderType()) ? null : annotation.jobExecutorThreadPoolSizeProviderType()).jobErrorHandlerType(Strings.isNullOrEmpty(annotation.jobErrorHandlerType()) ? null : annotation.jobErrorHandlerType()).jobListenerTypes(annotation.jobListenerTypes()).description(annotation.description()).disabled(annotation.disabled()).overwrite(annotation.overwrite()); for (Class<? extends JobExtraConfigurationFactory> clazz : annotation.extraConfigurations()) { try { Optional<JobExtraConfiguration> jobExtraConfig = clazz.newInstance().getJobExtraConfiguration(); jobExtraConfig.ifPresent(jobConfigurationBuilder::addExtraConfigurations); } catch (IllegalAccessException | InstantiationException exception) { throw ((JobConfigurationException) (new JobConfigurationException("new JobExtraConfigurationFactory instance by class '%s' failure", clazz).initCause(exception))); } } for (ElasticJobProp prop : annotation.props()) { jobConfigurationBuilder.setProperty(prop.key(), prop.value());} return jobConfigurationBuilder.build();}
3.26
shardingsphere-elasticjob_TimeService_getCurrentMillis_rdh
/** * Get current millis. * * @return current millis */ public long getCurrentMillis() { return System.currentTimeMillis(); }
3.26
shardingsphere-elasticjob_JobScheduler_shutdown_rdh
/** * Shutdown job. */ public void shutdown() { setUpFacade.tearDown();schedulerFacade.shutdownInstance(); jobExecutor.shutdown(); }
3.26
shardingsphere-elasticjob_SQLPropertiesFactory_getProperties_rdh
/** * Get SQL properties. * * @param type * tracing storage database type * @return SQL properties */ public static Properties getProperties(final TracingStorageDatabaseType type) { return loadProps(String.format("%s.properties", type.getType())); }
3.26
shardingsphere-elasticjob_AbstractDistributeOnceElasticJobListener_notifyWaitingTaskStart_rdh
/** * Notify waiting task start. */ public void notifyWaitingTaskStart() { synchronized(startedWait) {startedWait.notifyAll(); } }
3.26
shardingsphere-elasticjob_AbstractDistributeOnceElasticJobListener_notifyWaitingTaskComplete_rdh
/** * Notify waiting task complete. */ public void notifyWaitingTaskComplete() { synchronized(completedWait) { completedWait.notifyAll(); } }
3.26
shardingsphere-elasticjob_JobItemExecutorFactory_m0_rdh
/** * Get executor. * * @param elasticJobClass * elastic job class * @return job item executor */ @SuppressWarnings("unchecked") public static JobItemExecutor m0(final Class<? extends ElasticJob> elasticJobClass) { for (ClassedJobItemExecutor each : ShardingSphereServiceLoader.getServiceInstances(ClassedJobItemExecutor.class)) { if (each.getElasticJobClass().isAssignableFrom(elasticJobClass)) { return each; } } throw new JobConfigurationException("Can not find executor for elastic job class `%s`", elasticJobClass.getName()); }
3.26
shardingsphere-elasticjob_JobExecutionEvent_m0_rdh
/** * Execution success. * * @return job execution event */ public JobExecutionEvent m0() { JobExecutionEvent result = new JobExecutionEvent(id, hostname, ip, taskId, f0, source, f1, startTime, completeTime, f2, failureCause); result.setCompleteTime(new Date()); result.setSuccess(true); return result; }
3.26
shardingsphere-elasticjob_ElasticJobExecutor_execute_rdh
/** * Execute job. */ public void execute() { JobConfiguration jobConfig = jobFacade.loadJobConfiguration(true); executorServiceReloader.reloadIfNecessary(jobConfig);jobErrorHandlerReloader.reloadIfNecessary(jobConfig); JobErrorHandler jobErrorHandler = jobErrorHandlerReloader.getJobErrorHandler(); try { jobFacade.checkJobExecutionEnvironment(); } catch (final JobExecutionEnvironmentException cause) { jobErrorHandler.handleException(jobConfig.getJobName(), cause);} ShardingContexts shardingContexts = jobFacade.getShardingContexts(); jobFacade.postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_STAGING, String.format("Job '%s' execute begin.", jobConfig.getJobName())); if (jobFacade.misfireIfRunning(shardingContexts.getShardingItemParameters().keySet())) { jobFacade.postJobStatusTraceEvent(shardingContexts.getTaskId(), State.TASK_FINISHED, String.format("Previous job '%s' - shardingItems '%s' is still running, misfired job will start after previous job completed.", jobConfig.getJobName(), shardingContexts.getShardingItemParameters().keySet())); return; } try { jobFacade.beforeJobExecuted(shardingContexts); // CHECKSTYLE:OFF } catch (final Throwable cause) { // CHECKSTYLE:ON jobErrorHandler.handleException(jobConfig.getJobName(), cause); } execute(jobConfig, shardingContexts, ExecutionSource.NORMAL_TRIGGER); while (jobFacade.isExecuteMisfired(shardingContexts.getShardingItemParameters().keySet())) { jobFacade.clearMisfire(shardingContexts.getShardingItemParameters().keySet()); execute(jobConfig, shardingContexts, ExecutionSource.MISFIRE); } jobFacade.failoverIfNecessary(); try { jobFacade.afterJobExecuted(shardingContexts); // CHECKSTYLE:OFF } catch (final Throwable cause) { // CHECKSTYLE:ON jobErrorHandler.handleException(jobConfig.getJobName(), cause); } }
3.26
shardingsphere-elasticjob_ElasticJobExecutor_shutdown_rdh
/** * Shutdown executor. */ public void shutdown() {executorServiceReloader.close(); jobErrorHandlerReloader.close(); }
3.26
shardingsphere-elasticjob_TriggerService_removeTriggerFlag_rdh
/** * Remove trigger flag. */ public void removeTriggerFlag() { f0.removeJobNodeIfExisted(triggerNode.getLocalTriggerPath()); }
3.26
shardingsphere-elasticjob_JobRegistry_setJobRunning_rdh
/** * Set job running status. * * @param jobName * job name * @param isRunning * job running status */ public void setJobRunning(final String jobName, final boolean isRunning) { jobRunningMap.put(jobName, isRunning); }
3.26
shardingsphere-elasticjob_JobRegistry_getJobInstance_rdh
/** * Get job instance. * * @param jobName * job name * @return job instance */ public JobInstance getJobInstance(final String jobName) { return jobInstanceMap.get(jobName); }
3.26
shardingsphere-elasticjob_JobRegistry_shutdown_rdh
/** * Shutdown job schedule. * * @param jobName * job name */ public void shutdown(final String jobName) {Optional.ofNullable(schedulerMap.remove(jobName)).ifPresent(JobScheduleController::shutdown); Optional.ofNullable(regCenterMap.remove(jobName)).ifPresent(regCenter -> regCenter.evictCacheData("/" + jobName)); ListenerNotifierManager.getInstance().removeJobNotifyExecutor(jobName); jobInstanceMap.remove(jobName);jobRunningMap.remove(jobName); currentShardingTotalCountMap.remove(jobName); }
3.26
shardingsphere-elasticjob_JobRegistry_getInstance_rdh
/** * Get instance of job registry. * * @return instance of job registry */ public static JobRegistry getInstance() { if (null == instance) { synchronized(JobRegistry.class) { if (null == instance) { instance = new JobRegistry(); } } } return instance; }
3.26
shardingsphere-elasticjob_JobRegistry_registerJob_rdh
/** * Register job. * * @param jobName * job name * @param jobScheduleController * job schedule controller */ public void registerJob(final String jobName, final JobScheduleController jobScheduleController) { schedulerMap.put(jobName, jobScheduleController); }
3.26
shardingsphere-elasticjob_JobRegistry_addJobInstance_rdh
/** * Add job instance. * * @param jobName * job name * @param jobInstance * job instance */ public void addJobInstance(final String jobName, final JobInstance jobInstance) { jobInstanceMap.put(jobName, jobInstance); }
3.26
shardingsphere-elasticjob_JobRegistry_isJobRunning_rdh
/** * Judge job is running or not. * * @param jobName * job name * @return job is running or not */public boolean isJobRunning(final String jobName) { return jobRunningMap.getOrDefault(jobName, false); }
3.26
shardingsphere-elasticjob_JobRegistry_getCurrentShardingTotalCount_rdh
/** * Get sharding total count which running on current job server. * * @param jobName * job name * @return sharding total count which running on current job server */ public int getCurrentShardingTotalCount(final String jobName) { return currentShardingTotalCountMap.getOrDefault(jobName, 0); }
3.26
shardingsphere-elasticjob_JobRegistry_setCurrentShardingTotalCount_rdh
/** * Set sharding total count which running on current job server. * * @param jobName * job name * @param currentShardingTotalCount * sharding total count which running on current job server */ public void setCurrentShardingTotalCount(final String jobName, final int currentShardingTotalCount) { currentShardingTotalCountMap.put(jobName, currentShardingTotalCount); }
3.26
shardingsphere-elasticjob_JobRegistry_getJobScheduleController_rdh
/** * Get job schedule controller. * * @param jobName * job name * @return job schedule controller */ public JobScheduleController getJobScheduleController(final String jobName) { return schedulerMap.get(jobName); }
3.26
shardingsphere-elasticjob_JobRegistry_registerRegistryCenter_rdh
/** * Register registry center. * * @param jobName * job name * @param regCenter * registry center */ public void registerRegistryCenter(final String jobName, final CoordinatorRegistryCenter regCenter) { regCenterMap.put(jobName, regCenter); regCenter.addCacheData("/" + jobName); }
3.26
shardingsphere-elasticjob_JobRegistry_isShutdown_rdh
/** * Judge job is shutdown or not. * * @param jobName * job name * @return job is shutdown or not */ public boolean isShutdown(final String jobName) { return (!schedulerMap.containsKey(jobName)) || (!jobInstanceMap.containsKey(jobName)); }
3.26
shardingsphere-elasticjob_ShardingNode_getRunningNode_rdh
/** * Get job running node. * * @param item * sharding item * @return job running node */ public static String getRunningNode(final int item) { return String.format(f0, item); }
3.26
shardingsphere-elasticjob_ShardingNode_getInstanceNode_rdh
/** * Get the path of instance node. * * @param item * sharding item * @return the path of instance node */ public static String getInstanceNode(final int item) { return String.format(INSTANCE, item); }
3.26
shardingsphere-elasticjob_ShardingNode_getItemByRunningItemPath_rdh
/** * Get item by running item path. * * @param path * running item path * @return running item, return null if sharding item is not running */ public Integer getItemByRunningItemPath(final String path) { if (!isRunningItemPath(path)) { return null; } return Integer.parseInt(path.substring(jobNodePath.getFullPath(ROOT).length() + 1, path.lastIndexOf(RUNNING_APPENDIX) - 1)); }
3.26
shardingsphere-elasticjob_ZookeeperElectionService_start_rdh
/** * Start election. */ public void start() { log.debug("Elastic job: {} start to elect leadership", leaderSelector.getId()); leaderSelector.start(); }
3.26
shardingsphere-elasticjob_ZookeeperElectionService_stop_rdh
/** * Stop election. */ public void stop() { log.info("Elastic job: stop leadership election"); leaderLatch.countDown(); try { leaderSelector.close(); // CHECKSTYLE:OFF } catch (final Exception ignore) { }// CHECKSTYLE:ON }
3.26
shardingsphere-elasticjob_DefaultYamlTupleProcessor_process_rdh
/** * Process node tuple. * * @param nodeTuple * node tuple * @return processed node tuple */ public NodeTuple process(final NodeTuple nodeTuple) { return isUnsetNodeTuple(nodeTuple.getValueNode()) ? null : nodeTuple; }
3.26
shardingsphere-elasticjob_TaskContext_setSlaveId_rdh
/** * Set job server ID. * * @param slaveId * job server ID */ public void setSlaveId(final String slaveId) { id = id.replaceAll(this.slaveId, slaveId); this.slaveId = slaveId; }
3.26
shardingsphere-elasticjob_TaskContext_getIdForUnassignedSlave_rdh
/** * Get unassigned task ID before job execute. * * @param id * task ID * @return unassigned task ID before job execute */public static String getIdForUnassignedSlave(final String id) { return id.replaceAll(TaskContext.from(id).getSlaveId(), UNASSIGNED_SLAVE_ID); }
3.26
shardingsphere-elasticjob_TaskContext_from_rdh
/** * Get task meta data info via string. * * @param value * task meta data info string * @return task meta data info */ public static MetaInfo from(final String value) { String[] v1 = value.split(DELIMITER); Preconditions.checkState(((1 == v1.length) || (2 == v1.length)) || (5 == v1.length)); return new MetaInfo(v1[0], (1 == v1.length) || "".equals(v1[1]) ? Collections.emptyList() : Splitter.on(",").splitToList(v1[1]).stream().map(Integer::parseInt).collect(Collectors.toList())); }
3.26
shardingsphere-elasticjob_TaskContext_getTaskName_rdh
/** * Get task name. * * @return task name */ public String getTaskName() { return String.join(DELIMITER, metaInfo.m0(), type.toString(), slaveId); }
3.26
shardingsphere-elasticjob_TaskContext_getExecutorId_rdh
/** * Get executor ID. * * @param appName * application name * @return executor ID */ public String getExecutorId(final String appName) { return String.join(DELIMITER, appName, slaveId); }
3.26
shardingsphere-elasticjob_SnapshotService_listen_rdh
/** * Start to listen. */ public void listen() {try { log.info("ElasticJob: Snapshot service is running on port '{}'", m0(port)); } catch (final IOException ex) { log.error("ElasticJob: Snapshot service listen failure, error is: ", ex); } }
3.26
shardingsphere-elasticjob_SnapshotService_dumpJobDirectly_rdh
/** * Dump job. * * @param jobName * job's name * @return dump job's info */ public String dumpJobDirectly(final String jobName) {String path = "/" + jobName; final List<String> result = new ArrayList<>(); dumpDirectly(path, jobName, result); return String.join("\n", SensitiveInfoUtils.filterSensitiveIps(result)) + "\n"; }
3.26
shardingsphere-elasticjob_SnapshotService_close_rdh
/** * Close listener. */ public void close() { closed = true; if ((null != serverSocket) && (!serverSocket.isClosed())) { try { serverSocket.close(); } catch (final IOException ex) {log.error("ElasticJob: Snapshot service close failure, error is: ", ex); } } }
3.26
shardingsphere-elasticjob_SnapshotService_dumpJob_rdh
/** * Dump job. * * @param instanceIp * job instance ip addr * @param dumpPort * dump port * @param jobName * job's name * @return dump job's info * @throws IOException * i/o exception */ public static String dumpJob(final String instanceIp, final int dumpPort, final String jobName) throws IOException { try (Socket socket = new Socket(instanceIp, dumpPort);BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) { writer.write(DUMP_COMMAND + jobName); writer.newLine(); writer.flush(); StringBuilder sb = new StringBuilder(); String line; while (null != (line = reader.readLine())) { sb.append(line).append("\n"); } return sb.toString(); } }
3.26
shardingsphere-elasticjob_RegExceptionHandler_handleException_rdh
/** * Handle exception. * * @param cause * exception to be handled */ public static void handleException(final Exception cause) { if (null == cause) { return; }if (isIgnoredException(cause) || ((null != cause.getCause()) && isIgnoredException(cause.getCause()))) { log.debug("Elastic job: ignored exception for: {}", cause.getMessage()); } else if (cause instanceof InterruptedException) { Thread.currentThread().interrupt(); } else { throw new RegException(cause); } }
3.26
shardingsphere-elasticjob_ExecutionContextService_m0_rdh
/** * Get job sharding context. * * @param shardingItems * sharding items * @return job sharding context */ public ShardingContexts m0(final List<Integer> shardingItems) { JobConfiguration jobConfig = configService.load(false); removeRunningIfMonitorExecution(jobConfig.isMonitorExecution(), shardingItems); if (shardingItems.isEmpty()) { return new ShardingContexts(buildTaskId(jobConfig, shardingItems), jobConfig.getJobName(), jobConfig.getShardingTotalCount(), jobConfig.getJobParameter(), Collections.emptyMap()); } Map<Integer, String> shardingItemParameterMap = new ShardingItemParameters(jobConfig.getShardingItemParameters()).getMap();return new ShardingContexts(buildTaskId(jobConfig, shardingItems), jobConfig.getJobName(), jobConfig.getShardingTotalCount(), jobConfig.getJobParameter(), getAssignedShardingItemParameterMap(shardingItems, shardingItemParameterMap)); }
3.26
shardingsphere-elasticjob_ExecutionService_setMisfire_rdh
/** * Set misfire flag if sharding items still running. * * @param items * sharding items need to be set misfire flag */ public void setMisfire(final Collection<Integer> items) { for (int each : items) {jobNodeStorage.createJobNodeIfNeeded(ShardingNode.getMisfireNode(each)); } }
3.26
shardingsphere-elasticjob_ExecutionService_misfireIfHasRunningItems_rdh
/** * Set misfire flag if sharding items still running. * * @param items * sharding items need to be set misfire flag * @return is misfired for this schedule time or not */ public boolean misfireIfHasRunningItems(final Collection<Integer> items) { if (!hasRunningItems(items)) { return false; } setMisfire(items); return true;}
3.26
shardingsphere-elasticjob_ExecutionService_clearMisfire_rdh
/** * Clear misfire flag. * * @param items * sharding items need to be cleared */ public void clearMisfire(final Collection<Integer> items) { for (int each : items) { jobNodeStorage.removeJobNodeIfExisted(ShardingNode.getMisfireNode(each)); } }
3.26
shardingsphere-elasticjob_ExecutionService_clearRunningInfo_rdh
/** * Clear running info. * * @param items * sharding items which need to be cleared */ public void clearRunningInfo(final List<Integer> items) { for (int v4 : items) { jobNodeStorage.removeJobNodeIfExisted(ShardingNode.getRunningNode(v4)); } }
3.26
shardingsphere-elasticjob_ExecutionService_getAllRunningItems_rdh
/** * Get all running items with instance. * * @return running items with instance. */ public Map<Integer, JobInstance> getAllRunningItems() { int shardingTotalCount = configService.load(true).getShardingTotalCount();Map<Integer, JobInstance> result = new LinkedHashMap<>(shardingTotalCount, 1); for (int i = 0; i < shardingTotalCount; i++) { String data = jobNodeStorage.getJobNodeData(ShardingNode.getRunningNode(i)); if (!Strings.isNullOrEmpty(data)) { result.put(i, new JobInstance(data)); } } return result; }
3.26
shardingsphere-elasticjob_ExecutionService_getMisfiredJobItems_rdh
/** * Get misfired job sharding items. * * @param items * sharding items need to be judged * @return misfired job sharding items */ public List<Integer> getMisfiredJobItems(final Collection<Integer> items) { List<Integer> result = new ArrayList<>(items.size()); for (int each : items) { if (jobNodeStorage.isJobNodeExisted(ShardingNode.getMisfireNode(each))) { result.add(each); } } return result; }
3.26
shardingsphere-elasticjob_ExecutionService_registerJobBegin_rdh
/** * Register job begin. * * @param shardingContexts * sharding contexts */ public void registerJobBegin(final ShardingContexts shardingContexts) { JobRegistry.getInstance().setJobRunning(jobName, true); JobConfiguration jobConfig = configService.load(true); if (!jobConfig.isMonitorExecution()) { return; } String jobInstanceId = JobRegistry.getInstance().getJobInstance(jobName).getJobInstanceId(); for (int each : shardingContexts.getShardingItemParameters().keySet()) { if (jobConfig.isFailover()) { jobNodeStorage.fillJobNode(ShardingNode.getRunningNode(each), jobInstanceId); } else { jobNodeStorage.fillEphemeralJobNode(ShardingNode.getRunningNode(each), jobInstanceId); } } }
3.26
shardingsphere-elasticjob_ExecutionService_getDisabledItems_rdh
/** * Get disabled sharding items. * * @param items * sharding items need to be got * @return disabled sharding items */ public List<Integer> getDisabledItems(final List<Integer> items) { List<Integer> result = new ArrayList<>(items.size()); for (int each : items) { if (jobNodeStorage.isJobNodeExisted(ShardingNode.getDisabledNode(each))) {result.add(each); } } return result; }
3.26
shardingsphere-elasticjob_ElasticJobBootstrapConfiguration_createJobBootstrapBeans_rdh
/** * Create job bootstrap instances and register them into container. */ public void createJobBootstrapBeans() { ElasticJobProperties elasticJobProperties = applicationContext.getBean(ElasticJobProperties.class); SingletonBeanRegistry singletonBeanRegistry = ((ConfigurableApplicationContext) (applicationContext)).getBeanFactory(); CoordinatorRegistryCenter registryCenter = applicationContext.getBean(CoordinatorRegistryCenter.class); TracingConfiguration<?> tracingConfig = getTracingConfiguration(); constructJobBootstraps(elasticJobProperties, singletonBeanRegistry, registryCenter, tracingConfig); }
3.26
hbase_DelayedUtil_getRemainingTime_rdh
/** * Returns Time remaining as milliseconds. */public static long getRemainingTime(final TimeUnit resultUnit, final long timeout) { final long currentTime = EnvironmentEdgeManager.currentTime(); if (currentTime >= timeout) { return 0; } return resultUnit.convert(timeout - currentTime, TimeUnit.MILLISECONDS); }
3.26
hbase_DelayedUtil_takeWithoutInterrupt_rdh
/** * Returns null (if an interrupt) or an instance of E; resets interrupt on calling thread. */ public static <E extends Delayed> E takeWithoutInterrupt(final DelayQueue<E> queue, final long timeout, final TimeUnit timeUnit) { try { return queue.poll(timeout, timeUnit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; } }
3.26
hbase_CellVisibility_getExpression_rdh
/** * Returns The visibility expression */ public String getExpression() { return this.expression; }
3.26
hbase_CellVisibility_quote_rdh
/** * Helps in quoting authentication Strings. Use this if unicode characters to be used in * expression or special characters like '(', ')', '"','\','&amp;','|','!' */public static String quote(byte[] auth) { int escapeChars = 0; for (int i = 0; i < auth.length; i++) if ((auth[i] == '"') || (auth[i] == '\\')) escapeChars++; byte[] escapedAuth = new byte[(auth.length + escapeChars) + 2]; int index = 1; for (int i = 0; i < auth.length; i++) { if ((auth[i] == '"') || (auth[i] == '\\')) { escapedAuth[index++] = '\\'; } escapedAuth[index++] = auth[i];} escapedAuth[0] = '"'; escapedAuth[escapedAuth.length - 1] = '"'; return Bytes.toString(escapedAuth); }
3.26
hbase_ProcedureTree_checkReady_rdh
// In this method first we will check whether the given root procedure and all its sub procedures // are valid, through the procedure stack. And we will also remove all these procedures from the // remainingProcMap, so at last, if there are still procedures in the map, we know that there are // orphan procedures. private void checkReady(Entry rootEntry, Map<Long, Entry> remainingProcMap) { if (ProcedureUtil.isFinished(rootEntry.proc)) { if (!rootEntry.subProcs.isEmpty()) { LOG.error("unexpected active children for root-procedure: {}", rootEntry); rootEntry.subProcs.forEach(e -> LOG.error("unexpected active children: {}", e)); addAllToCorruptedAndRemoveFromProcMap(rootEntry, remainingProcMap);} else {addAllToValidAndRemoveFromProcMap(rootEntry, remainingProcMap); } return; } Map<Integer, List<Entry>> stackId2Proc = new HashMap<>(); MutableInt maxStackId = new MutableInt(Integer.MIN_VALUE);collectStackId(rootEntry, stackId2Proc, maxStackId);// the stack ids should start from 0 and increase by one every time boolean valid = true; for (int i = 0; i <= maxStackId.intValue(); i++) { List<Entry> entries = stackId2Proc.get(i); if (entries == null) { LOG.error("Missing stack id {}, max stack id is {}, root procedure is {}", i, maxStackId, rootEntry); valid = false; } else if (entries.size() > 1) { LOG.error("Multiple procedures {} have the same stack id {}, max stack id is {}," + " root procedure is {}", entries, i, maxStackId, rootEntry); valid = false; } }if (valid) { addAllToValidAndRemoveFromProcMap(rootEntry, remainingProcMap); } else { addAllToCorruptedAndRemoveFromProcMap(rootEntry, remainingProcMap); } }
3.26
hbase_IdentityTableReducer_reduce_rdh
/** * Writes each given record, consisting of the row key and the given values, to the configured * {@link org.apache.hadoop.mapreduce.OutputFormat}. It is emitting the row key and each * {@link org.apache.hadoop.hbase.client.Put Put} or {@link org.apache.hadoop.hbase.client.Delete * Delete} as separate pairs. * * @param key * The current row key. * @param values * The {@link org.apache.hadoop.hbase.client.Put Put} or * {@link org.apache.hadoop.hbase.client.Delete Delete} list for the given row. * @param context * The context of the reduce. * @throws IOException * When writing the record fails. * @throws InterruptedException * When the job gets interrupted. */ @Override public void reduce(Writable key, Iterable<Mutation> values, Context context) throws IOException, InterruptedException { for (Mutation putOrDelete : values) { context.write(key, putOrDelete); } }
3.26
hbase_MetricsRegionServerSourceImpl_getMetrics_rdh
/** * Yes this is a get function that doesn't return anything. Thanks Hadoop for breaking all * expectations of java programmers. Instead of returning anything Hadoop metrics expects * getMetrics to push the metrics into the collector. * * @param metricsCollector * Collector to accept metrics * @param all * push all or only changed? */ @Override public void getMetrics(MetricsCollector metricsCollector, boolean all) {MetricsRecordBuilder mrb = metricsCollector.addRecord(metricsName); // rsWrap can be null because this function is called inside of init. if (rsWrap != null) { addGaugesToMetricsRecordBuilder(mrb).addCounter(Interns.info(TOTAL_REQUEST_COUNT, TOTAL_REQUEST_COUNT_DESC), rsWrap.getTotalRequestCount()).addCounter(Interns.info(TOTAL_ROW_ACTION_REQUEST_COUNT, TOTAL_ROW_ACTION_REQUEST_COUNT_DESC), rsWrap.getTotalRowActionRequestCount()).addCounter(Interns.info(READ_REQUEST_COUNT, READ_REQUEST_COUNT_DESC), rsWrap.getReadRequestsCount()).addCounter(Interns.info(CP_REQUEST_COUNT, CP_REQUEST_COUNT_DESC), rsWrap.getCpRequestsCount()).addCounter(Interns.info(FILTERED_READ_REQUEST_COUNT, FILTERED_READ_REQUEST_COUNT_DESC), rsWrap.getFilteredReadRequestsCount()).addCounter(Interns.info(WRITE_REQUEST_COUNT, WRITE_REQUEST_COUNT_DESC), rsWrap.getWriteRequestsCount()).addCounter(Interns.info(RPC_GET_REQUEST_COUNT, RPC_GET_REQUEST_COUNT_DESC), rsWrap.getRpcGetRequestsCount()).addCounter(Interns.info(RPC_FULL_SCAN_REQUEST_COUNT, RPC_FULL_SCAN_REQUEST_COUNT_DESC), rsWrap.getRpcFullScanRequestsCount()).addCounter(Interns.info(RPC_SCAN_REQUEST_COUNT, RPC_SCAN_REQUEST_COUNT_DESC), rsWrap.getRpcScanRequestsCount()).addCounter(Interns.info(RPC_MULTI_REQUEST_COUNT, RPC_MULTI_REQUEST_COUNT_DESC), rsWrap.getRpcMultiRequestsCount()).addCounter(Interns.info(RPC_MUTATE_REQUEST_COUNT, RPC_MUTATE_REQUEST_COUNT_DESC), rsWrap.getRpcMutateRequestsCount()).addCounter(Interns.info(CHECK_MUTATE_FAILED_COUNT, CHECK_MUTATE_FAILED_COUNT_DESC), rsWrap.getCheckAndMutateChecksFailed()).addCounter(Interns.info(CHECK_MUTATE_PASSED_COUNT, CHECK_MUTATE_PASSED_COUNT_DESC), rsWrap.getCheckAndMutateChecksPassed()).addCounter(Interns.info(BLOCK_CACHE_HIT_COUNT, BLOCK_CACHE_HIT_COUNT_DESC), rsWrap.getBlockCacheHitCount()).addCounter(Interns.info(BLOCK_CACHE_PRIMARY_HIT_COUNT, BLOCK_CACHE_PRIMARY_HIT_COUNT_DESC), rsWrap.getBlockCachePrimaryHitCount()).addCounter(Interns.info(BLOCK_CACHE_HIT_CACHING_COUNT, BLOCK_CACHE_HIT_CACHING_COUNT_DESC), rsWrap.getBlockCacheHitCachingCount()).addCounter(Interns.info(BLOCK_CACHE_MISS_COUNT, BLOCK_COUNT_MISS_COUNT_DESC), rsWrap.getBlockCacheMissCount()).addCounter(Interns.info(BLOCK_CACHE_PRIMARY_MISS_COUNT, BLOCK_COUNT_PRIMARY_MISS_COUNT_DESC), rsWrap.getBlockCachePrimaryMissCount()).addCounter(Interns.info(BLOCK_CACHE_MISS_CACHING_COUNT, BLOCK_COUNT_MISS_CACHING_COUNT_DESC), rsWrap.getBlockCacheMissCachingCount()).addCounter(Interns.info(BLOCK_CACHE_EVICTION_COUNT, BLOCK_CACHE_EVICTION_COUNT_DESC), rsWrap.getBlockCacheEvictedCount()).addCounter(Interns.info(BLOCK_CACHE_PRIMARY_EVICTION_COUNT, BLOCK_CACHE_PRIMARY_EVICTION_COUNT_DESC), rsWrap.getBlockCachePrimaryEvictedCount()).addCounter(Interns.info(BLOCK_CACHE_FAILED_INSERTION_COUNT, BLOCK_CACHE_FAILED_INSERTION_COUNT_DESC), rsWrap.getBlockCacheFailedInsertions()).addCounter(Interns.info(BLOCK_CACHE_DATA_MISS_COUNT, ""), rsWrap.getDataMissCount()).addCounter(Interns.info(BLOCK_CACHE_LEAF_INDEX_MISS_COUNT, ""), rsWrap.getLeafIndexMissCount()).addCounter(Interns.info(BLOCK_CACHE_BLOOM_CHUNK_MISS_COUNT, ""), rsWrap.getBloomChunkMissCount()).addCounter(Interns.info(BLOCK_CACHE_META_MISS_COUNT, ""), rsWrap.getMetaMissCount()).addCounter(Interns.info(BLOCK_CACHE_ROOT_INDEX_MISS_COUNT, ""), rsWrap.getRootIndexMissCount()).addCounter(Interns.info(BLOCK_CACHE_INTERMEDIATE_INDEX_MISS_COUNT, ""), rsWrap.getIntermediateIndexMissCount()).addCounter(Interns.info(BLOCK_CACHE_FILE_INFO_MISS_COUNT, ""), rsWrap.getFileInfoMissCount()).addCounter(Interns.info(BLOCK_CACHE_GENERAL_BLOOM_META_MISS_COUNT, ""), rsWrap.getGeneralBloomMetaMissCount()).addCounter(Interns.info(BLOCK_CACHE_DELETE_FAMILY_BLOOM_MISS_COUNT, ""), rsWrap.getDeleteFamilyBloomMissCount()).addCounter(Interns.info(BLOCK_CACHE_TRAILER_MISS_COUNT, ""), rsWrap.getTrailerMissCount()).addCounter(Interns.info(BLOCK_CACHE_DATA_HIT_COUNT, ""), rsWrap.getDataHitCount()).addCounter(Interns.info(BLOCK_CACHE_LEAF_INDEX_HIT_COUNT, ""), rsWrap.getLeafIndexHitCount()).addCounter(Interns.info(BLOCK_CACHE_BLOOM_CHUNK_HIT_COUNT, ""), rsWrap.getBloomChunkHitCount()).addCounter(Interns.info(BLOCK_CACHE_META_HIT_COUNT, ""), rsWrap.getMetaHitCount()).addCounter(Interns.info(BLOCK_CACHE_ROOT_INDEX_HIT_COUNT, ""), rsWrap.getRootIndexHitCount()).addCounter(Interns.info(BLOCK_CACHE_INTERMEDIATE_INDEX_HIT_COUNT, ""), rsWrap.getIntermediateIndexHitCount()).addCounter(Interns.info(BLOCK_CACHE_FILE_INFO_HIT_COUNT, ""), rsWrap.getFileInfoHitCount()).addCounter(Interns.info(BLOCK_CACHE_GENERAL_BLOOM_META_HIT_COUNT, ""), rsWrap.getGeneralBloomMetaHitCount()).addCounter(Interns.info(BLOCK_CACHE_DELETE_FAMILY_BLOOM_HIT_COUNT, ""), rsWrap.getDeleteFamilyBloomHitCount()).addCounter(Interns.info(BLOCK_CACHE_TRAILER_HIT_COUNT, ""), rsWrap.getTrailerHitCount()).addCounter(Interns.info(UPDATES_BLOCKED_TIME, UPDATES_BLOCKED_DESC), rsWrap.getUpdatesBlockedTime()).addCounter(Interns.info(FLUSHED_CELLS, FLUSHED_CELLS_DESC), rsWrap.getFlushedCellsCount()).addCounter(Interns.info(COMPACTED_CELLS, COMPACTED_CELLS_DESC), rsWrap.getCompactedCellsCount()).addCounter(Interns.info(MAJOR_COMPACTED_CELLS, MAJOR_COMPACTED_CELLS_DESC), rsWrap.getMajorCompactedCellsCount()).addCounter(Interns.info(FLUSHED_CELLS_SIZE, FLUSHED_CELLS_SIZE_DESC), rsWrap.getFlushedCellsSize()).addCounter(Interns.info(COMPACTED_CELLS_SIZE, COMPACTED_CELLS_SIZE_DESC), rsWrap.getCompactedCellsSize()).addCounter(Interns.info(MAJOR_COMPACTED_CELLS_SIZE, MAJOR_COMPACTED_CELLS_SIZE_DESC), rsWrap.getMajorCompactedCellsSize()).addCounter(Interns.info(CELLS_COUNT_COMPACTED_FROM_MOB, CELLS_COUNT_COMPACTED_FROM_MOB_DESC), rsWrap.getCellsCountCompactedFromMob()).addCounter(Interns.info(CELLS_COUNT_COMPACTED_TO_MOB, CELLS_COUNT_COMPACTED_TO_MOB_DESC), rsWrap.getCellsCountCompactedToMob()).addCounter(Interns.info(CELLS_SIZE_COMPACTED_FROM_MOB, CELLS_SIZE_COMPACTED_FROM_MOB_DESC), rsWrap.getCellsSizeCompactedFromMob()).addCounter(Interns.info(CELLS_SIZE_COMPACTED_TO_MOB, CELLS_SIZE_COMPACTED_TO_MOB_DESC), rsWrap.getCellsSizeCompactedToMob()).addCounter(Interns.info(MOB_FLUSH_COUNT, MOB_FLUSH_COUNT_DESC), rsWrap.getMobFlushCount()).addCounter(Interns.info(MOB_FLUSHED_CELLS_COUNT, MOB_FLUSHED_CELLS_COUNT_DESC), rsWrap.getMobFlushedCellsCount()).addCounter(Interns.info(MOB_FLUSHED_CELLS_SIZE, MOB_FLUSHED_CELLS_SIZE_DESC), rsWrap.getMobFlushedCellsSize()).addCounter(Interns.info(MOB_SCAN_CELLS_COUNT, MOB_SCAN_CELLS_COUNT_DESC), rsWrap.getMobScanCellsCount()).addCounter(Interns.info(MOB_SCAN_CELLS_SIZE, MOB_SCAN_CELLS_SIZE_DESC), rsWrap.getMobScanCellsSize()).addCounter(Interns.info(MOB_FILE_CACHE_ACCESS_COUNT, MOB_FILE_CACHE_ACCESS_COUNT_DESC), rsWrap.getMobFileCacheAccessCount()).addCounter(Interns.info(MOB_FILE_CACHE_MISS_COUNT, MOB_FILE_CACHE_MISS_COUNT_DESC), rsWrap.getMobFileCacheMissCount()).addCounter(Interns.info(MOB_FILE_CACHE_EVICTED_COUNT, MOB_FILE_CACHE_EVICTED_COUNT_DESC), rsWrap.getMobFileCacheEvictedCount()).addCounter(Interns.info(HEDGED_READS, HEDGED_READS_DESC), rsWrap.getHedgedReadOps()).addCounter(Interns.info(HEDGED_READ_WINS, HEDGED_READ_WINS_DESC), rsWrap.getHedgedReadWins()).addCounter(Interns.info(HEDGED_READ_IN_CUR_THREAD, HEDGED_READ_IN_CUR_THREAD_DESC), rsWrap.getHedgedReadOpsInCurThread()).addCounter(Interns.info(BLOCKED_REQUESTS_COUNT, BLOCKED_REQUESTS_COUNT_DESC), rsWrap.getBlockedRequestsCount()).tag(Interns.info(ZOOKEEPER_QUORUM_NAME, ZOOKEEPER_QUORUM_DESC), rsWrap.getZookeeperQuorum()).tag(Interns.info(SERVER_NAME_NAME, SERVER_NAME_DESC), rsWrap.getServerName()).tag(Interns.info(CLUSTER_ID_NAME, CLUSTER_ID_DESC), rsWrap.getClusterId()); } metricsRegistry.snapshot(mrb, all); // source is registered in supers constructor, sometimes called before the whole initialization. if (metricsAdapter != null) { // snapshot MetricRegistry as well metricsAdapter.snapshotAllMetrics(registry, mrb); } }
3.26
hbase_SimpleRegionNormalizer_skipForMerge_rdh
/** * Determine if a {@link RegionInfo} should be considered for a merge operation. * </p> * Callers beware: for safe concurrency, be sure to pass in the local instance of * {@link NormalizerConfiguration}, don't use {@code this}'s instance. */ private boolean skipForMerge(final NormalizerConfiguration normalizerConfiguration, final NormalizeContext ctx, final RegionInfo regionInfo) { final RegionState state = ctx.getRegionStates().getRegionState(regionInfo); final String name = regionInfo.getEncodedName(); return ((logTraceReason(() -> state == null, "skipping merge of region {} because no state information is available.", name) || logTraceReason(() -> !Objects.equals(state.getState(), State.OPEN), "skipping merge of region {} because it is not open.", name)) || logTraceReason(() -> !isOldEnoughForMerge(normalizerConfiguration, ctx, regionInfo), "skipping merge of region {} because it is not old enough.", name)) || logTraceReason(() -> !isLargeEnoughForMerge(normalizerConfiguration, ctx, regionInfo), "skipping merge region {} because it is not large enough.", name); }
3.26
hbase_SimpleRegionNormalizer_computeMergeNormalizationPlans_rdh
/** * Computes the merge plans that should be executed for this table to converge average region * towards target average or target region count. */ private List<NormalizationPlan> computeMergeNormalizationPlans(final NormalizeContext ctx) { final NormalizerConfiguration configuration = normalizerConfiguration; if (ctx.getTableRegions().size() < configuration.getMergeMinRegionCount(ctx)) { LOG.debug("Table {} has {} regions, required min number of regions for normalizer to run" + " is {}, not computing merge plans.", ctx.getTableName(), ctx.getTableRegions().size(), configuration.getMergeMinRegionCount()); return Collections.emptyList(); } final long avgRegionSizeMb = ((long) (ctx.getAverageRegionSizeMb())); if (avgRegionSizeMb < configuration.getMergeMinRegionSizeMb(ctx)) { return Collections.emptyList(); } LOG.debug("Computing normalization plan for table {}. average region size: {} MB, number of" + " regions: {}.", ctx.getTableName(), avgRegionSizeMb, ctx.getTableRegions().size()); // this nested loop walks the table's region chain once, looking for contiguous sequences of // regions that meet the criteria for merge. The outer loop tracks the starting point of the // next sequence, the inner loop looks for the end of that sequence. A single sequence becomes // an instance of MergeNormalizationPlan. final List<NormalizationPlan> plans = new LinkedList<>(); final List<NormalizationTarget> rangeMembers = new LinkedList<>(); long sumRangeMembersSizeMb; int current = 0; for (int rangeStart = 0; (rangeStart < (ctx.getTableRegions().size() - 1)) && (current < ctx.getTableRegions().size());) { // walk the region chain looking for contiguous sequences of regions that can be merged. rangeMembers.clear(); sumRangeMembersSizeMb = 0; for (current = rangeStart; current < ctx.getTableRegions().size(); current++) { final RegionInfo regionInfo = ctx.getTableRegions().get(current); final long regionSizeMb = getRegionSizeMB(regionInfo); if (skipForMerge(configuration, ctx, regionInfo)) { // this region cannot participate in a range. resume the outer loop. rangeStart = Math.max(current, rangeStart + 1); break; } // when there are no range members, seed the range with whatever we have. this way we're // prepared in case the next region is 0-size. if (((rangeMembers.isEmpty() || // when there is only one region and the size is 0, seed the range with whatever we // have. ((rangeMembers.size() == 1) && (sumRangeMembersSizeMb == 0))) || // add an empty region to the current range only if it doesn't exceed max merge request // region count ((regionSizeMb == 0) && (rangeMembers.size() < getMergeRequestMaxNumberOfRegionsCount()))) || // add region if current range region size is less than avg region size of table // and current range doesn't exceed max merge request region count (((regionSizeMb + sumRangeMembersSizeMb) <= avgRegionSizeMb) && (rangeMembers.size() < getMergeRequestMaxNumberOfRegionsCount()))) { // add the current region to the range when there's capacity remaining. rangeMembers.add(new NormalizationTarget(regionInfo, regionSizeMb)); sumRangeMembersSizeMb += regionSizeMb; continue; } // we have accumulated enough regions to fill a range. resume the outer loop. rangeStart = Math.max(current, rangeStart + 1); break; } if (rangeMembers.size() > 1) { plans.add(new MergeNormalizationPlan.Builder().setTargets(rangeMembers).build()); } } return plans; }
3.26
hbase_SimpleRegionNormalizer_computeSplitNormalizationPlans_rdh
/** * Computes the split plans that should be executed for this table to converge average region size * towards target average or target region count. <br /> * if the region is > 2 times larger than average, we split it. split is more high priority * normalization action than merge. */ private List<NormalizationPlan> computeSplitNormalizationPlans(final NormalizeContext ctx) { final double avgRegionSize = ctx.getAverageRegionSizeMb(); LOG.debug("Table {}, average region size: {} MB", ctx.getTableName(), String.format("%.3f", avgRegionSize)); final List<NormalizationPlan> plans = new ArrayList<>(); for (final RegionInfo hri : ctx.getTableRegions()) { if (skipForSplit(ctx.getRegionStates().getRegionState(hri), hri)) { continue; } final long regionSizeMb = getRegionSizeMB(hri); if (regionSizeMb > (2 * avgRegionSize)) { LOG.info("Table {}, large region {} has size {} MB, more than twice avg size {} MB, " + "splitting", ctx.getTableName(), hri.getRegionNameAsString(), regionSizeMb, String.format("%.3f", avgRegionSize)); plans.add(new SplitNormalizationPlan(hri, regionSizeMb)); } } return plans; }
3.26
hbase_SimpleRegionNormalizer_skipForSplit_rdh
/** * Determine if a region in {@link RegionState} should be considered for a split operation. */ private static boolean skipForSplit(final RegionState state, final RegionInfo regionInfo) { final String name = regionInfo.getEncodedName(); return logTraceReason(() -> state == null, "skipping split of region {} because no state information is available.", name) || logTraceReason(() -> !Objects.equals(state.getState(), State.OPEN), "skipping merge of region {} because it is not open.", name); }
3.26
hbase_SimpleRegionNormalizer_isOldEnoughForMerge_rdh
/** * Return {@code true} when {@code regionInfo} has a creation date that is old enough to be * considered for a merge operation, {@code false} otherwise. */ private static boolean isOldEnoughForMerge(final NormalizerConfiguration normalizerConfiguration, final NormalizeContext ctx, final RegionInfo regionInfo) { final Instant currentTime = Instant.ofEpochMilli(EnvironmentEdgeManager.currentTime()); final Instant regionCreateTime = Instant.ofEpochMilli(regionInfo.getRegionId()); return currentTime.isAfter(regionCreateTime.plus(normalizerConfiguration.getMergeMinRegionAge(ctx))); }
3.26
hbase_SimpleRegionNormalizer_getMergeMinRegionCount_rdh
/** * Return this instance's configured value for {@value #MERGE_MIN_REGION_COUNT_KEY}. */ public int getMergeMinRegionCount() { return normalizerConfiguration.getMergeMinRegionCount(); }
3.26
hbase_SimpleRegionNormalizer_getMergeMinRegionAge_rdh
/** * Return this instance's configured value for {@value #MERGE_MIN_REGION_AGE_DAYS_KEY}. */ public Period getMergeMinRegionAge() { return normalizerConfiguration.getMergeMinRegionAge(); } /** * Return this instance's configured value for {@value #MERGE_MIN_REGION_SIZE_MB_KEY}
3.26
hbase_SimpleRegionNormalizer_shuffleNormalizationPlans_rdh
/** * This very simple method exists so we can verify it was called in a unit test. Visible for * testing. */ void shuffleNormalizationPlans(List<NormalizationPlan> plans) { Collections.shuffle(plans); }
3.26
hbase_SimpleRegionNormalizer_isSplitEnabled_rdh
/** * Return this instance's configured value for {@value #SPLIT_ENABLED_KEY}. */ public boolean isSplitEnabled() { return normalizerConfiguration.isSplitEnabled(); }
3.26
hbase_SimpleRegionNormalizer_getRegionSizeMB_rdh
/** * Returns size of region in MB and if region is not found than -1 */ private long getRegionSizeMB(RegionInfo hri) { ServerName sn = masterServices.getAssignmentManager().getRegionStates().getRegionServerOfRegion(hri); if (sn == null) { LOG.debug("{} region was not found on any Server", hri.getRegionNameAsString()); return -1; } ServerMetrics serverMetrics = masterServices.getServerManager().getLoad(sn); if (serverMetrics == null) { LOG.debug("server {} was not found in ServerManager", sn.getServerName()); return -1; } RegionMetrics regionLoad = serverMetrics.getRegionMetrics().get(hri.getRegionName()); if (regionLoad == null) { LOG.debug("{} was not found in RegionsLoad", hri.getRegionNameAsString()); return -1; } return ((long) (regionLoad.getStoreFileSize().get(Unit.MEGABYTE))); }
3.26
hbase_SimpleRegionNormalizer_isMergeEnabled_rdh
/** * Return this instance's configured value for {@value #MERGE_ENABLED_KEY}. */ public boolean isMergeEnabled() { return normalizerConfiguration.isMergeEnabled(); }
3.26
hbase_SimpleRegionNormalizer_isLargeEnoughForMerge_rdh
/** * Return {@code true} when {@code regionInfo} has a size that is sufficient to be considered for * a merge operation, {@code false} otherwise. * </p> * Callers beware: for safe concurrency, be sure to pass in the local instance of * {@link NormalizerConfiguration}, don't use {@code this}'s instance. */ private boolean isLargeEnoughForMerge(final NormalizerConfiguration normalizerConfiguration, final NormalizeContext ctx, final RegionInfo regionInfo) { return getRegionSizeMB(regionInfo) >= normalizerConfiguration.getMergeMinRegionSizeMb(ctx); }
3.26
hbase_ReversedMobStoreScanner_next_rdh
/** * Firstly reads the cells from the HBase. If the cell is a reference cell (which has the * reference tag), the scanner need seek this cell from the mob file, and use the cell found from * the mob file as the result. */ @Override public boolean next(List<Cell> outResult, ScannerContext ctx) throws IOException { boolean v0 = super.next(outResult, ctx); if (!rawMobScan) { // retrieve the mob data if (outResult.isEmpty()) { return v0; } long mobKVCount = 0; long mobKVSize = 0; for (int i = 0; i < outResult.size(); i++) { Cell cell = outResult.get(i); if (MobUtils.isMobReferenceCell(cell)) { MobCell mobCell = mobStore.resolve(cell, cacheMobBlocks, readPt, readEmptyValueOnMobCellMiss); mobKVCount++; mobKVSize += mobCell.getCell().getValueLength(); outResult.set(i, mobCell.getCell()); // Keep the MobCell here unless we shipped the RPC or close the scanner. referencedMobCells.add(mobCell); } } mobStore.updateMobScanCellsCount(mobKVCount); mobStore.updateMobScanCellsSize(mobKVSize); } return v0; }
3.26
hbase_DeadServer_copyDeadServersSince_rdh
/** * Extract all the servers dead since a given time, and sort them. * * @param ts * the time, 0 for all * @return a sorted array list, by death time, lowest values first. */ synchronized List<Pair<ServerName, Long>> copyDeadServersSince(long ts) { List<Pair<ServerName, Long>> res = new ArrayList<>(size()); for (Map.Entry<ServerName, Long> entry : deadServers.entrySet()) { if (entry.getValue() >= ts) { res.add(new Pair<>(entry.getKey(), entry.getValue())); } } Collections.sort(res, (o1, o2) -> o1.getSecond().compareTo(o2.getSecond())); return res; }
3.26
hbase_DeadServer_m0_rdh
/** * Handles restart of a server. The new server instance has a different start code. The new start * code should be greater than the old one. We don't check that here. Removes the old server from * deadserver list. * * @param newServerName * Servername as either <code>host:port</code> or * <code>host,port,startcode</code>. * @return true if this server was dead before and coming back alive again */ synchronized boolean m0(final ServerName newServerName) { Iterator<ServerName> it = deadServers.keySet().iterator(); while (it.hasNext()) { if (cleanOldServerName(newServerName, it)) { return true; } } return false; }
3.26
hbase_DeadServer_isDeadServer_rdh
/** * * @param serverName * server name. * @return true if this server is on the dead servers list false otherwise */public synchronized boolean isDeadServer(final ServerName serverName) { return deadServers.containsKey(serverName); }
3.26
hbase_DeadServer_putIfAbsent_rdh
/** * Adds the server to the dead server list if it's not there already. */ synchronized void putIfAbsent(ServerName sn) { this.deadServers.putIfAbsent(sn, EnvironmentEdgeManager.currentTime()); }
3.26
hbase_DeadServer_getTimeOfDeath_rdh
/** * Get the time when a server died * * @param deadServerName * the dead server name * @return the date when the server died */ public synchronized Date getTimeOfDeath(final ServerName deadServerName) { Long time = deadServers.get(deadServerName); return time == null ? null : new Date(time); }
3.26
hbase_DeadServer_removeDeadServer_rdh
/** * Called from rpc by operator cleaning up deadserver list. * * @param deadServerName * the dead server name * @return true if this server was removed */ public synchronized boolean removeDeadServer(final ServerName deadServerName) { return this.deadServers.remove(deadServerName) != null; }
3.26
hbase_TransitRegionStateProcedure_execute_rdh
// Override to lock RegionStateNode @SuppressWarnings("rawtypes") @Override protected Procedure[] execute(MasterProcedureEnv env) throws ProcedureSuspendedException, ProcedureYieldException, InterruptedException {RegionStateNode regionNode = env.getAssignmentManager().getRegionStates().getOrCreateRegionStateNode(getRegion()); regionNode.lock(); try { return super.execute(env); } finally { regionNode.unlock(); } }
3.26
hbase_TransitRegionStateProcedure_serverCrashed_rdh
// Should be called with RegionStateNode locked public void serverCrashed(MasterProcedureEnv env, RegionStateNode regionNode, ServerName serverName, boolean forceNewPlan) throws IOException { this.forceNewPlan = forceNewPlan; if (remoteProc != null) { // this means we are waiting for the sub procedure, so wake it up remoteProc.serverCrashed(env, regionNode, serverName); } else { // we are in RUNNING state, just update the region state, and we will process it later. env.getAssignmentManager().regionClosedAbnormally(regionNode); } }
3.26
hbase_TransitRegionStateProcedure_m0_rdh
/** * At end of timeout, wake ourselves up so we run again. */ @Override protected synchronized boolean m0(MasterProcedureEnv env) { setState(ProcedureState.RUNNABLE); env.getProcedureScheduler().addFront(this); return false;// 'false' means that this procedure handled the timeout }
3.26
hbase_TransitRegionStateProcedure_assign_rdh
// Be careful that, when you call these 4 methods below, you need to manually attach the returned // procedure with the RegionStateNode, otherwise the procedure will quit immediately without doing // anything. See the comment in executeFromState to find out why we need this assumption. public static TransitRegionStateProcedure assign(MasterProcedureEnv env, RegionInfo region, @Nullable ServerName targetServer) { return assign(env, region, false, targetServer); }
3.26
hbase_TransitRegionStateProcedure_reportTransition_rdh
// Should be called with RegionStateNode locked public void reportTransition(MasterProcedureEnv env, RegionStateNode regionNode, ServerName serverName, TransitionCode code, long seqId, long procId) throws IOException { if (remoteProc == null) { LOG.warn("There is no outstanding remote region procedure for {}, serverName={}, code={}," + " seqId={}, proc={}, should be a retry, ignore", regionNode, serverName, code, seqId, this); return; } // The procId could be -1 if it is from an old region server, we need to deal with it so that we // can do rolling upgraing. if ((procId >= 0) && (remoteProc.getProcId() != procId)) { LOG.warn("The pid of remote region procedure for {} is {}, the reported pid={}, serverName={}," + " code={}, seqId={}, proc={}, should be a retry, ignore", regionNode, remoteProc.getProcId(), procId, serverName, code, seqId, this); return; } remoteProc.reportTransition(env, regionNode, serverName, code, seqId); }
3.26
hbase_TransitRegionStateProcedure_stateLoaded_rdh
// the state to meta yet. See the code in RegionRemoteProcedureBase.execute for more details. void stateLoaded(AssignmentManager am, RegionStateNode regionNode) { if (remoteProc != null) { remoteProc.stateLoaded(am, regionNode); } }
3.26
hbase_MetaTableLocator_setMetaLocation_rdh
/** * Sets the location of <code>hbase:meta</code> in ZooKeeper to the specified server address. * * @param zookeeper * reference to the {@link ZKWatcher} which also contains configuration and * operation * @param serverName * the name of the server * @param replicaId * the ID of the replica * @param state * the state of the region * @throws KeeperException * if a ZooKeeper operation fails */ public static void setMetaLocation(ZKWatcher zookeeper, ServerName serverName, int replicaId, RegionState.State state) throws KeeperException { if (serverName == null) { LOG.warn("Tried to set null ServerName in hbase:meta; skipping -- ServerName required"); return; } LOG.info("Setting hbase:meta replicaId={} location in ZooKeeper as {}, state={}", replicaId, serverName, state); // Make the MetaRegionServer pb and then get its bytes and save this as // the znode content. MetaRegionServer pbrsr = MetaRegionServer.newBuilder().setServer(ProtobufUtil.toServerName(serverName)).setRpcVersion(HConstants.RPC_CURRENT_VERSION).setState(state.convert()).build();byte[] data = ProtobufUtil.prependPBMagic(pbrsr.toByteArray()); try { ZKUtil.setData(zookeeper, zookeeper.getZNodePaths().getZNodeForReplica(replicaId), data); } catch (KeeperException.NoNodeException nne) { if (replicaId == RegionInfo.DEFAULT_REPLICA_ID) { LOG.debug("hbase:meta region location doesn't exist, create it"); } else { LOG.debug(("hbase:meta region location doesn't exist for replicaId=" + replicaId) + ", create it");} ZKUtil.createAndWatch(zookeeper, zookeeper.getZNodePaths().getZNodeForReplica(replicaId), data); } }
3.26
hbase_MetaTableLocator_blockUntilAvailable_rdh
/** * Wait until the meta region is available and is not in transition. * * @param zkw * reference to the {@link ZKWatcher} which also contains configuration and * constants * @param replicaId * the ID of the replica * @param timeout * maximum time to wait in millis * @return ServerName or null if we timed out. * @throws InterruptedException * if waiting for the socket operation fails */ private static ServerName blockUntilAvailable(final ZKWatcher zkw, int replicaId, final long timeout) throws InterruptedException { if (timeout < 0) { throw new IllegalArgumentException(); } if (zkw == null) { throw new IllegalArgumentException(); } long startTime = EnvironmentEdgeManager.currentTime(); ServerName sn = null; while (true) { sn = getMetaRegionLocation(zkw, replicaId); if ((sn != null) || ((EnvironmentEdgeManager.currentTime() - startTime) > (timeout - HConstants.SOCKET_RETRY_WAIT_MS))) { break; } Thread.sleep(HConstants.SOCKET_RETRY_WAIT_MS); } return sn; }
3.26