src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
StochasticLoadBalancer extends BaseLoadBalancer { @Override public synchronized void setClusterStatus(ClusterStatus st) { super.setClusterStatus(st); updateRegionLoad(); for(CostFromRegionLoadFunction cost : regionLoadFunctions) { cost.setClusterStatus(st); } } @Override void onConfigurationChange(Configuration conf);... | @Test public void testKeepRegionLoad() throws Exception { ServerName sn = ServerName.valueOf("test:8080", 100); int numClusterStatusToAdd = 20000; for (int i = 0; i < numClusterStatusToAdd; i++) { ServerLoad sl = mock(ServerLoad.class); RegionLoad rl = mock(RegionLoad.class); when(rl.getStores()).thenReturn(i); Map<byt... |
StochasticLoadBalancer extends BaseLoadBalancer { @Override public synchronized List<RegionPlan> balanceCluster(Map<ServerName, List<HRegionInfo>> clusterState) { List<RegionPlan> plans = balanceMasterRegions(clusterState); if (plans != null || clusterState == null || clusterState.size() <= 1) { return plans; } if (mas... | @Test public void testBalanceCluster() throws Exception { for (int[] mockCluster : clusterStateMocks) { Map<ServerName, List<HRegionInfo>> servers = mockClusterServers(mockCluster); List<ServerAndLoad> list = convertToList(servers); LOG.info("Mock Cluster : " + printMock(list) + " " + printStats(list)); List<RegionPlan... |
StochasticLoadBalancer extends BaseLoadBalancer { @Override public synchronized void setConf(Configuration conf) { super.setConf(conf); LOG.info("loading config"); maxSteps = conf.getInt(MAX_STEPS_KEY, maxSteps); stepsPerRegion = conf.getInt(STEPS_PER_REGION_KEY, stepsPerRegion); maxRunningTime = conf.getLong(MAX_RUNNI... | @Ignore @Test (timeout = 800000) public void testRegionReplicationOnMidClusterSameHosts() { conf.setLong(StochasticLoadBalancer.MAX_STEPS_KEY, 2000000L); conf.setLong("hbase.master.balancer.stochastic.maxRunningTime", 90 * 1000); conf.setFloat("hbase.master.balancer.stochastic.maxMovePercent", 1.0f); loadBalancer.setCo... |
FSTableDescriptors implements TableDescriptors { @Override public HTableDescriptor get(final TableName tablename) throws IOException { invocations++; if (TableName.META_TABLE_NAME.equals(tablename)) { cachehits++; return metaTableDescriptor; } if (HConstants.HBASE_NON_USER_TABLE_DIRS.contains(tablename.getNameAsString(... | @Test public void testNoSuchTable() throws IOException { final String name = "testNoSuchTable"; FileSystem fs = FileSystem.get(UTIL.getConfiguration()); Path rootdir = new Path(UTIL.getDataTestDir(), name); TableDescriptors htds = new FSTableDescriptors(UTIL.getConfiguration(), fs, rootdir); assertNull("There shouldn't... |
DeadServer { public synchronized boolean areDeadServersInProgress() { return processing; } synchronized boolean cleanPreviousInstance(final ServerName newServerName); synchronized boolean isDeadServer(final ServerName serverName); synchronized boolean areDeadServersInProgress(); synchronized Set<ServerName> copyServer... | @Test(timeout = 15000) public void testCrashProcedureReplay() { HMaster master = TEST_UTIL.getHBaseCluster().getMaster(); ProcedureExecutor pExecutor = master.getMasterProcedureExecutor(); ServerCrashProcedure proc = new ServerCrashProcedure(hostname123, false, false); ProcedureTestingUtility.submitAndWait(pExecutor, p... |
ClusterStatusPublisher extends ScheduledChore { protected List<ServerName> generateDeadServersListToSend() { long since = EnvironmentEdgeManager.currentTime() - messagePeriod * 2; for (Pair<ServerName, Long> dead : getDeadServers(since)) { lastSent.putIfAbsent(dead.getFirst(), 0); } List<Map.Entry<ServerName, Integer>>... | @Test public void testEmpty() { ClusterStatusPublisher csp = new ClusterStatusPublisher() { @Override protected List<Pair<ServerName, Long>> getDeadServers(long since) { return new ArrayList<Pair<ServerName, Long>>(); } }; Assert.assertTrue(csp.generateDeadServersListToSend().isEmpty()); }
@Test public void testMaxSend... |
CatalogJanitor extends ScheduledChore { boolean cleanParent(final HRegionInfo parent, Result rowContent) throws IOException { boolean result = false; if (rowContent.getValue(HConstants.CATALOG_FAMILY, HConstants.MERGEA_QUALIFIER) != null) { return result; } PairOfSameType<HRegionInfo> daughters = HRegionInfo.getDaughte... | @Test public void testCleanParent() throws IOException, InterruptedException { HBaseTestingUtility htu = new HBaseTestingUtility(); setRootDirAndCleanIt(htu, "testCleanParent"); Server server = new MockServer(htu); try { MasterServices services = new MockMasterServices(server); CatalogJanitor janitor = new CatalogJanit... |
SplitLogManager { Task findOrCreateOrphanTask(String path) { Task orphanTask = new Task(); Task task; task = tasks.putIfAbsent(path, orphanTask); if (task == null) { LOG.info("creating orphan task " + path); SplitLogCounters.tot_mgr_orphan_task_acquired.incrementAndGet(); task = orphanTask; } return task; } SplitLogMan... | @Test (timeout=180000) public void testOrphanTaskAcquisition() throws Exception { LOG.info("TestOrphanTaskAcquisition"); String tasknode = ZKSplitLog.getEncodedNodeName(zkw, "orphan/test/slash"); SplitLogTask slt = new SplitLogTask.Owned(DUMMY_MASTER, this.mode); zkw.getRecoverableZooKeeper().create(tasknode, slt.toByt... |
SplitLogManager { void handleDeadWorker(ServerName workerName) { synchronized (deadWorkersLock) { if (deadWorkers == null) { deadWorkers = new HashSet<ServerName>(100); } deadWorkers.add(workerName); } LOG.info("dead splitlog worker " + workerName); } SplitLogManager(Server server, Configuration conf, Stoppable stopper... | @Test (timeout=180000) public void testDeadWorker() throws Exception { LOG.info("testDeadWorker"); conf.setLong("hbase.splitlog.max.resubmit", 0); slm = new SplitLogManager(ds, conf, stopper, master, DUMMY_MASTER); TaskBatch batch = new TaskBatch(); String tasknode = submitTaskAndWait(batch, "foo/1"); int version = ZKU... |
SplitLogManager { public long splitLogDistributed(final Path logDir) throws IOException { List<Path> logDirs = new ArrayList<Path>(); logDirs.add(logDir); return splitLogDistributed(logDirs); } SplitLogManager(Server server, Configuration conf, Stoppable stopper,
MasterServices master, ServerName serverName); @Vi... | @Test (timeout=180000) public void testEmptyLogDir() throws Exception { LOG.info("testEmptyLogDir"); slm = new SplitLogManager(ds, conf, stopper, master, DUMMY_MASTER); FileSystem fs = TEST_UTIL.getTestFileSystem(); Path emptyLogDirPath = new Path(fs.getWorkingDirectory(), UUID.randomUUID().toString()); fs.mkdirs(empty... |
SplitLogManager { void removeStaleRecoveringRegions(final Set<ServerName> failedServers) throws IOException, InterruptedIOException { Set<String> knownFailedServers = new HashSet<String>(); if (failedServers != null) { for (ServerName tmpServerName : failedServers) { knownFailedServers.add(tmpServerName.getServerName()... | @Test(timeout = 300000) public void testRecoveryRegionRemovedFromZK() throws Exception { LOG.info("testRecoveryRegionRemovedFromZK"); conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, false); String nodePath = ZKUtil.joinZNode(zkw.recoveringRegionsZNode, HRegionInfo.FIRST_META_REGIONINFO.getEncodedName()); ZKUtil.... |
SimpleRegionNormalizer implements RegionNormalizer { @Override public List<NormalizationPlan> computePlanForTable(TableName table) throws HBaseIOException { if (table == null || table.isSystemTable()) { LOG.debug("Normalization of system table " + table + " isn't allowed"); return null; } List<NormalizationPlan> plans ... | @Test public void testNoNormalizationForMetaTable() throws HBaseIOException { TableName testTable = TableName.META_TABLE_NAME; List<HRegionInfo> hris = new ArrayList<>(); Map<byte[], Integer> regionSizes = new HashMap<>(); setupMocksForNormalizer(regionSizes, hris); List<NormalizationPlan> plans = normalizer.computePla... |
StealJobQueue extends PriorityBlockingQueue<T> { @Override public T take() throws InterruptedException { lock.lockInterruptibly(); try { while (true) { T retVal = this.poll(); if (retVal == null) { retVal = stealFromQueue.poll(); } if (retVal == null) { notEmpty.await(); } else { return retVal; } } } finally { lock.unl... | @Test public void testTake() throws InterruptedException { stealJobQueue.offer(3); stealFromQueue.offer(10); stealJobQueue.offer(15); stealJobQueue.offer(4); assertEquals(3, stealJobQueue.take().intValue()); assertEquals(4, stealJobQueue.take().intValue()); assertEquals("always take from the main queue before trying to... |
CleanerChore extends ScheduledChore { @Override protected void chore() { try { FileStatus[] files = FSUtils.listStatus(this.fs, this.oldFileDir); checkAndDeleteEntries(files); } catch (IOException e) { e = RemoteExceptionHandler.checkIOException(e); LOG.warn("Error while cleaning the logs", e); } } CleanerChore(String ... | @Test public void testSavesFilesOnRequest() throws Exception { Stoppable stop = new StoppableImplementation(); Configuration conf = UTIL.getConfiguration(); Path testDir = UTIL.getDataTestDir(); FileSystem fs = UTIL.getTestFileSystem(); String confKey = "hbase.test.cleaner.delegates"; conf.set(confKey, NeverDelete.clas... |
CleanerChore extends ScheduledChore { @VisibleForTesting boolean checkAndDeleteDirectory(Path dir) { if (LOG.isTraceEnabled()) { LOG.trace("Checking directory: " + dir); } try { FileStatus[] children = FSUtils.listStatus(fs, dir); boolean allChildrenDeleted = checkAndDeleteEntries(children); if (!allChildrenDeleted) re... | @Test public void testNoExceptionFromDirectoryWithRacyChildren() throws Exception { Stoppable stop = new StoppableImplementation(); HBaseTestingUtility localUtil = new HBaseTestingUtility(); Configuration conf = localUtil.getConfiguration(); final Path testDir = UTIL.getDataTestDir(); final FileSystem fs = UTIL.getTest... |
SnapshotLogCleaner extends BaseLogCleanerDelegate { @Override public void setConf(Configuration conf) { super.setConf(conf); try { long cacheRefreshPeriod = conf.getLong( WAL_CACHE_REFRESH_PERIOD_CONF_KEY, DEFAULT_WAL_CACHE_REFRESH_PERIOD); final FileSystem fs = FSUtils.getCurrentFileSystem(conf); Path rootDir = FSUtil... | @Test public void testFindsSnapshotFilesWhenCleaning() throws IOException { Configuration conf = TEST_UTIL.getConfiguration(); FSUtils.setRootDir(conf, TEST_UTIL.getDataTestDir()); Path rootDir = FSUtils.getRootDir(conf); FileSystem fs = FileSystem.get(conf); SnapshotLogCleaner cleaner = new SnapshotLogCleaner(); clean... |
ServerCrashProcedure extends StateMachineProcedure<MasterProcedureEnv, ServerCrashState> implements ServerProcedureInterface { @Override public ServerName getServerName() { return this.serverName; } ServerCrashProcedure(final ServerName serverName,
final boolean shouldSplitWal, final boolean carryingMeta); Serve... | @Test(timeout = 300000) public void testRecoveryAndDoubleExecutionOnline() throws Exception { final TableName tableName = TableName.valueOf("testRecoveryAndDoubleExecutionOnline"); this.util.createTable(tableName, HBaseTestingUtility.COLUMNS, HBaseTestingUtility.KEYS_FOR_HBA_CREATE_TABLE); try (Table t = this.util.getC... |
StorefileRefresherChore extends ScheduledChore { @Override protected void chore() { for (Region r : regionServer.getOnlineRegionsLocalContext()) { if (!r.isReadOnly()) { continue; } if (onlyMetaRefresh && !r.getRegionInfo().isMetaTable()) continue; String encodedName = r.getRegionInfo().getEncodedName(); long time = En... | @Test public void testIsStale() throws IOException { int period = 0; byte[][] families = new byte[][] {Bytes.toBytes("cf")}; byte[] qf = Bytes.toBytes("cq"); HRegionServer regionServer = mock(HRegionServer.class); List<Region> regions = new ArrayList<Region>(); when(regionServer.getOnlineRegionsLocalContext()).thenRetu... |
StripeStoreFileManager implements StoreFileManager, StripeCompactionPolicy.StripeInformationProvider { @Override public ImmutableCollection<StoreFile> clearFiles() { ImmutableCollection<StoreFile> result = state.allFilesCached; this.state = new State(); this.fileStarts.clear(); this.fileEnds.clear(); return result; } S... | @Test public void testClearFiles() throws Exception { StripeStoreFileManager manager = createManager(); manager.insertNewFiles(al(createFile())); manager.insertNewFiles(al(createFile())); manager.addCompactionResults(al(), al(createFile(OPEN_KEY, KEY_B), createFile(KEY_B, OPEN_KEY))); assertEquals(4, manager.getStorefi... |
StealJobQueue extends PriorityBlockingQueue<T> { @Override public T poll(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); lock.lockInterruptibly(); try { while (true) { T retVal = this.poll(); if (retVal == null) { retVal = stealFromQueue.poll(); } if (retVal == null) { if ... | @Test public void testPoll() throws InterruptedException { stealJobQueue.offer(3); stealFromQueue.offer(10); stealJobQueue.offer(15); stealJobQueue.offer(4); assertEquals(3, stealJobQueue.poll(1, TimeUnit.SECONDS).intValue()); assertEquals(4, stealJobQueue.poll(1, TimeUnit.SECONDS).intValue()); assertEquals("always tak... |
StripeStoreFileManager implements StoreFileManager, StripeCompactionPolicy.StripeInformationProvider { @Override public List<StoreFile> getLevel0Files() { return this.state.level0Files; } StripeStoreFileManager(
KVComparator kvComparator, Configuration conf, StripeStoreConfig config); @Override void loadFiles(Lis... | @Test @SuppressWarnings("unchecked") public void testLoadFilesWithRecoverableBadFiles() throws Exception { ArrayList<StoreFile> validStripeFiles = al(createFile(OPEN_KEY, KEY_B), createFile(KEY_B, KEY_C), createFile(KEY_C, OPEN_KEY), createFile(KEY_C, OPEN_KEY)); ArrayList<StoreFile> filesToGoToL0 = al(createFile(), cr... |
StoreFileInfo { @Override public int hashCode() { int hash = 17; hash = hash * 31 + ((reference == null) ? 0 : reference.hashCode()); hash = hash * 31 + ((initialPath == null) ? 0 : initialPath.hashCode()); hash = hash * 31 + ((link == null) ? 0 : link.hashCode()); return hash; } StoreFileInfo(final Configuration conf,... | @Test public void testEqualsWithLink() throws IOException { Path origin = new Path("/origin"); Path tmp = new Path("/tmp"); Path archive = new Path("/archive"); HFileLink link1 = new HFileLink(new Path(origin, "f1"), new Path(tmp, "f1"), new Path(archive, "f1")); HFileLink link2 = new HFileLink(new Path(origin, "f1"), ... |
ServerNonceManager { public void endOperation(long group, long nonce, boolean success) { if (nonce == HConstants.NO_NONCE) return; NonceKey nk = new NonceKey(group, nonce); OperationContext newResult = nonces.get(nk); assert newResult != null; synchronized (newResult) { assert newResult.getState() == OperationContext.W... | @Test public void testNoEndWithoutStart() { ServerNonceManager nm = createManager(); try { nm.endOperation(NO_NONCE, 1, true); fail("Should have thrown"); } catch (AssertionError err) {} } |
OpenRegionHandler extends EventHandler { @Override public void process() throws IOException { boolean openSuccessful = false; boolean transitionedToOpening = false; final String regionName = regionInfo.getRegionNameAsString(); HRegion region = null; try { if (this.server.isStopped() || this.rsServices.isStopping()) { r... | @Test public void testRegionServerAbortionDueToFailureTransitioningToOpened() throws IOException, NodeExistsException, KeeperException { final Server server = new MockServer(HTU); final RegionServerServices rss = HTU.createMockRegionServerService(); HTableDescriptor htd = TEST_HTD; final HRegionInfo hri = TEST_HRI; HRe... |
CloseRegionHandler extends EventHandler { @Override public void process() { try { String name = regionInfo.getRegionNameAsString(); LOG.debug("Processing close of " + name); String encodedRegionName = regionInfo.getEncodedName(); HRegion region = (HRegion)rsServices.getFromOnlineRegions(encodedRegionName); if (region =... | @Test public void testFailedFlushAborts() throws IOException, NodeExistsException, KeeperException { final Server server = new MockServer(HTU, false); final RegionServerServices rss = HTU.createMockRegionServerService(); HTableDescriptor htd = TEST_HTD; final HRegionInfo hri = new HRegionInfo(htd.getTableName(), HConst... |
RegionSplitPolicy extends Configured { protected byte[] getSplitPoint() { byte[] explicitSplitPoint = this.region.getExplicitSplitPoint(); if (explicitSplitPoint != null) { return explicitSplitPoint; } List<Store> stores = region.getStores(); byte[] splitPointFromLargestStore = null; long largestStoreSize = 0; for (Sto... | @Test public void testGetSplitPoint() throws IOException { ConstantSizeRegionSplitPolicy policy = (ConstantSizeRegionSplitPolicy)RegionSplitPolicy.create(mockRegion, conf); assertFalse(policy.shouldSplit()); assertNull(policy.getSplitPoint()); HStore mockStore = Mockito.mock(HStore.class); Mockito.doReturn(2000L).when(... |
HeapMemoryManager { public static HeapMemoryManager create(Configuration conf, FlushRequester memStoreFlusher, Server server, RegionServerAccounting regionServerAccounting) { BlockCache blockCache = CacheConfig.instantiateBlockCache(conf); if (blockCache instanceof ResizableBlockCache) { return new HeapMemoryManager((R... | @Test public void testWhenMemstoreAndBlockCacheMaxMinChecksFails() throws Exception { BlockCacheStub blockCache = new BlockCacheStub(0); MemstoreFlusherStub memStoreFlusher = new MemstoreFlusherStub(0); Configuration conf = HBaseConfiguration.create(); conf.setFloat(HeapMemoryManager.MEMSTORE_SIZE_MAX_RANGE_KEY, 0.75f)... |
MetricsWAL extends WALActionsListener.Base { @Override public void logRollRequested(boolean underReplicated) { source.incrementLogRollRequested(); if (underReplicated) { source.incrementLowReplicationLogRoll(); } } MetricsWAL(); @VisibleForTesting MetricsWAL(MetricsWALSource s); @Override void postSync(final long time... | @Test public void testLogRollRequested() throws Exception { MetricsWALSource source = mock(MetricsWALSourceImpl.class); MetricsWAL metricsWAL = new MetricsWAL(source); metricsWAL.logRollRequested(false); metricsWAL.logRollRequested(true); verify(source, times(2)).incrementLogRollRequested(); verify(source, times(1)).in... |
MetricsWAL extends WALActionsListener.Base { @Override public void postSync(final long timeInNanos, final int handlerSyncs) { source.incrementSyncTime(timeInNanos/1000000L); } MetricsWAL(); @VisibleForTesting MetricsWAL(MetricsWALSource s); @Override void postSync(final long timeInNanos, final int handlerSyncs); @Over... | @Test public void testPostSync() throws Exception { long nanos = TimeUnit.MILLISECONDS.toNanos(145); MetricsWALSource source = mock(MetricsWALSourceImpl.class); MetricsWAL metricsWAL = new MetricsWAL(source); metricsWAL.postSync(nanos, 1); verify(source, times(1)).incrementSyncTime(145); } |
FSHLog implements WAL { @Override public void close() throws IOException { shutdown(); final FileStatus[] files = getFiles(); if (null != files && 0 != files.length) { for (FileStatus file : files) { Path p = getWALArchivePath(this.fullPathArchiveDir, file.getPath()); if (!this.listeners.isEmpty()) { for (WALActionsLis... | @Test public void testSyncRunnerIndexOverflow() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { final String name = "testSyncRunnerIndexOverflow"; FSHLog log = new FSHLog(fs, FSUtils.getRootDir(conf), name, HConstants.HREGION_OLDLOGDIR_NAME, conf, null, tr... |
SequenceIdAccounting { Long startCacheFlush(final byte[] encodedRegionName, final Set<byte[]> families) { Map<byte[], Long> oldSequenceIds = null; Long lowestUnflushedInRegion = HConstants.NO_SEQNUM; synchronized (tieLock) { Map<byte[], Long> m = this.lowestUnflushedSequenceIds.get(encodedRegionName); if (m != null) { ... | @Test public void testStartCacheFlush() { SequenceIdAccounting sida = new SequenceIdAccounting(); sida.getOrCreateLowestSequenceIds(ENCODED_REGION_NAME); Map<byte[], Long> m = new HashMap<byte[], Long>(); m.put(ENCODED_REGION_NAME, HConstants.NO_SEQNUM); assertEquals(HConstants.NO_SEQNUM, (long)sida.startCacheFlush(ENC... |
SequenceIdAccounting { boolean areAllLower(Map<byte[], Long> sequenceids) { Map<byte[], Long> flushing = null; Map<byte[], Long> unflushed = null; synchronized (this.tieLock) { flushing = flattenToLowestSequenceId(this.flushingSequenceIds); unflushed = flattenToLowestSequenceId(this.lowestUnflushedSequenceIds); } for (... | @Test public void testAreAllLower() { SequenceIdAccounting sida = new SequenceIdAccounting(); sida.getOrCreateLowestSequenceIds(ENCODED_REGION_NAME); Map<byte[], Long> m = new HashMap<byte[], Long>(); m.put(ENCODED_REGION_NAME, HConstants.NO_SEQNUM); assertTrue(sida.areAllLower(m)); long sequenceid = 1; sida.update(ENC... |
StealJobQueue extends PriorityBlockingQueue<T> { public BlockingQueue<T> getStealFromQueue() { return stealFromQueue; } StealJobQueue(); BlockingQueue<T> getStealFromQueue(); @Override boolean offer(T t); @Override T take(); @Override T poll(long timeout, TimeUnit unit); } | @Test public void testInteractWithThreadPool() throws InterruptedException { StealJobQueue<Runnable> stealTasksQueue = new StealJobQueue<>(); final CountDownLatch stealJobCountDown = new CountDownLatch(3); final CountDownLatch stealFromCountDown = new CountDownLatch(3); ThreadPoolExecutor stealPool = new ThreadPoolExec... |
SequenceIdAccounting { byte[][] findLower(Map<byte[], Long> sequenceids) { List<byte[]> toFlush = null; synchronized (tieLock) { for (Map.Entry<byte[], Long> e: sequenceids.entrySet()) { Map<byte[], Long> m = this.lowestUnflushedSequenceIds.get(e.getKey()); if (m == null) continue; long lowest = getLowestSequenceId(m);... | @Test public void testFindLower() { SequenceIdAccounting sida = new SequenceIdAccounting(); sida.getOrCreateLowestSequenceIds(ENCODED_REGION_NAME); Map<byte[], Long> m = new HashMap<byte[], Long>(); m.put(ENCODED_REGION_NAME, HConstants.NO_SEQNUM); long sequenceid = 1; sida.update(ENCODED_REGION_NAME, FAMILIES, sequenc... |
SplitLogWorker implements Runnable { public void start() { worker = new Thread(null, this, "SplitLogWorker-" + server.getServerName().toShortString()); worker.start(); } SplitLogWorker(Server hserver, Configuration conf, RegionServerServices server,
TaskExecutor splitTaskExecutor); SplitLogWorker(final Server hs... | @Test(timeout=60000) public void testAcquireTaskAtStartup() throws Exception { LOG.info("testAcquireTaskAtStartup"); SplitLogCounters.resetCounters(); final String TATAS = "tatas"; final ServerName RS = ServerName.valueOf("rs,1,1"); RegionServerServices mockedRS = getRegionServer(RS); zkw.getRecoverableZooKeeper().crea... |
HRegion implements HeapSize, PropagatingConfigurationObserver, Region { public static void closeHRegion(final HRegion r) throws IOException { if (r == null) return; r.close(); if (r.getWAL() == null) return; r.getWAL().close(); } @Deprecated @VisibleForTesting HRegion(final Path tableDir, final WAL wal,
final Fi... | @Test public void testGetWhileRegionClose() throws IOException { TableName tableName = TableName.valueOf(name.getMethodName()); Configuration hc = initSplit(); int numRows = 100; byte[][] families = { fam1, fam2, fam3 }; String method = name.getMethodName(); this.region = initHRegion(tableName, method, hc, families); t... |
HRegion implements HeapSize, PropagatingConfigurationObserver, Region { public static HRegion merge(final HRegion a, final HRegion b) throws IOException { if (!a.getRegionInfo().getTable().equals(b.getRegionInfo().getTable())) { throw new IOException("Regions do not belong to the same table"); } FileSystem fs = a.getRe... | @Test public void testMerge() throws IOException { byte[][] families = { fam1, fam2, fam3 }; Configuration hc = initSplit(); String method = this.getName(); this.region = initHRegion(tableName, method, hc, families); try { LOG.info("" + HBaseTestCase.addContent(region, fam3)); region.flush(true); region.compactStores()... |
HRegion implements HeapSize, PropagatingConfigurationObserver, Region { @Override public HDFSBlocksDistribution getHDFSBlocksDistribution() { HDFSBlocksDistribution hdfsBlocksDistribution = new HDFSBlocksDistribution(); synchronized (this.stores) { for (Store store : this.stores.values()) { Collection<StoreFile> storeF... | @Test public void testgetHDFSBlocksDistribution() throws Exception { HBaseTestingUtility htu = new HBaseTestingUtility(); htu.getConfiguration().setInt("dfs.replication", 2); MiniHBaseCluster cluster = null; String dataNodeHosts[] = new String[] { "host1", "host2", "host3" }; int regionServersCount = 3; try { cluster =... |
IdLock { void assertMapEmpty() { assert map.size() == 0; } Entry getLockEntry(long id); void releaseLockEntry(Entry entry); @VisibleForTesting void waitForWaiters(long id, int numWaiters); } | @Test public void testMultipleClients() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); try { ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(exec); for (int i = 0; i < NUM_THREADS; ++i) ecs.submit(new IdLockTestThread("client_" + i)); for (int i = 0;... |
SnapshotManifest { public static SnapshotManifest open(final Configuration conf, final FileSystem fs, final Path workingDir, final SnapshotDescription desc) throws IOException { SnapshotManifest manifest = new SnapshotManifest(conf, fs, workingDir, desc, null); manifest.load(); return manifest; } private SnapshotManif... | @Test public void testReadSnapshotManifest() throws IOException { try { SnapshotManifest.open(conf, fs, snapshotDir, snapshotDesc); fail("fail to test snapshot manifest because message size is too small."); } catch (InvalidProtocolBufferException ipbe) { try { conf.setInt(SnapshotManifest.SNAPSHOT_MANIFEST_SIZE_LIMIT_C... |
ExportSnapshot extends Configured implements Tool { static List<List<Pair<SnapshotFileInfo, Long>>> getBalancedSplits( final List<Pair<SnapshotFileInfo, Long>> files, final int ngroups) { Collections.sort(files, new Comparator<Pair<SnapshotFileInfo, Long>>() { public int compare(Pair<SnapshotFileInfo, Long> a, Pair<Sna... | @Test public void testBalanceSplit() throws Exception { List<Pair<SnapshotFileInfo, Long>> files = new ArrayList<Pair<SnapshotFileInfo, Long>>(); for (long i = 0; i <= 20; i++) { SnapshotFileInfo fileInfo = SnapshotFileInfo.newBuilder() .setType(SnapshotFileInfo.Type.HFILE) .setHfile("file-" + i) .build(); files.add(ne... |
SnapshotDescriptionUtils { public static SnapshotDescription validate(SnapshotDescription snapshot, Configuration conf) throws IllegalArgumentException { if (!snapshot.hasTable()) { throw new IllegalArgumentException( "Descriptor doesn't apply to a table, so we can't build it."); } long time = snapshot.getCreationTime(... | @Test public void testValidateMissingTableName() { Configuration conf = new Configuration(false); try { SnapshotDescriptionUtils.validate(SnapshotDescription.newBuilder().setName("fail").build(), conf); fail("Snapshot was considered valid without a table name"); } catch (IllegalArgumentException e) { LOG.debug("Correct... |
SnapshotDescriptionUtils { public static void completeSnapshot(SnapshotDescription snapshot, Path rootdir, Path workingDir, FileSystem fs) throws SnapshotCreationException, IOException { Path finishedDir = getCompletedSnapshotDir(snapshot, rootdir); LOG.debug("Snapshot is done, just moving the snapshot from " + working... | @Test public void testCompleteSnapshotWithNoSnapshotDirectoryFailure() throws Exception { Path snapshotDir = new Path(root, HConstants.SNAPSHOT_DIR_NAME); Path tmpDir = new Path(snapshotDir, ".tmp"); Path workingDir = new Path(tmpDir, "not_a_snapshot"); assertFalse("Already have working snapshot dir: " + workingDir + "... |
JMXListener implements Coprocessor { @Override public void start(CoprocessorEnvironment env) throws IOException { int rmiRegistryPort = -1; int rmiConnectorPort = -1; Configuration conf = env.getConfiguration(); if (env instanceof MasterCoprocessorEnvironment) { rmiRegistryPort = conf.getInt("master" + RMI_REGISTRY_POR... | @Test public void testStart() throws Exception { JMXConnector connector = JMXConnectorFactory.connect( JMXListener.buildJMXServiceURL(connectorPort,connectorPort)); MBeanServerConnection mb = connector.getMBeanServerConnection(); String domain = mb.getDefaultDomain(); Assert.assertTrue("default domain is not correct", ... |
JMXListener implements Coprocessor { @Override public void stop(CoprocessorEnvironment env) throws IOException { stopConnectorServer(); } static JMXServiceURL buildJMXServiceURL(int rmiRegistryPort,
int rmiConnectorPort); void startConnectorServer(int rmiRegistryPort, int rmiConnectorPort); void stopConnectorSer... | @Test public void testStop() throws Exception { MiniHBaseCluster cluster = UTIL.getHBaseCluster(); LOG.info("shutdown hbase cluster..."); cluster.shutdown(); LOG.info("wait for the hbase cluster shutdown..."); cluster.waitUntilShutDown(); JMXConnector connector = JMXConnectorFactory.newJMXConnector( JMXListener.buildJM... |
TagRewriteCell implements Cell, SettableSequenceId, SettableTimestamp, HeapSize { @Override public long heapSize() { long sum = CellUtil.estimatedHeapSizeOf(cell) - cell.getTagsLength(); sum += ClassSize.OBJECT; sum += (2 * ClassSize.REFERENCE); if (this.tags != null) { sum += ClassSize.align(ClassSize.ARRAY); sum += t... | @Test public void testHeapSize() { Cell originalCell = CellUtil.createCell(Bytes.toBytes("row"), Bytes.toBytes("value")); final int fakeTagArrayLength = 10; TagRewriteCell trCell = new TagRewriteCell(originalCell, new byte[fakeTagArrayLength]); long trCellHeapSize = trCell.heapSize(); TagRewriteCell trCell2 = new TagRe... |
KeyLocker { public ReentrantLock acquireLock(K key) { if (key == null) throw new IllegalArgumentException("key must not be null"); lockPool.purge(); ReentrantLock lock = lockPool.get(key); lock.lock(); return lock; } ReentrantLock acquireLock(K key); Map<K, Lock> acquireLocks(Set<? extends K> keys); } | @Test public void testLocker(){ KeyLocker<String> locker = new KeyLocker<String>(); ReentrantLock lock1 = locker.acquireLock("l1"); Assert.assertTrue(lock1.isHeldByCurrentThread()); ReentrantLock lock2 = locker.acquireLock("l2"); Assert.assertTrue(lock2.isHeldByCurrentThread()); Assert.assertTrue(lock1 != lock2); Reent... |
DynamicClassLoader extends ClassLoaderBase { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { try { return parent.loadClass(name); } catch (ClassNotFoundException e) { if (LOG.isDebugEnabled()) { LOG.debug("Class " + name + " not found - using dynamical class loader"); } if (useDynamicJa... | @Test public void testLoadClassFromLocalPath() throws Exception { ClassLoader parent = TestDynamicClassLoader.class.getClassLoader(); DynamicClassLoader classLoader = new DynamicClassLoader(conf, parent); String className = "TestLoadClassFromLocalPath"; deleteClass(className); try { classLoader.loadClass(className); fa... |
HBaseFsck extends Configured implements Closeable { public HBaseFsck(Configuration conf) throws MasterNotRunningException, ZooKeeperConnectionException, IOException, ClassNotFoundException { this(conf, createThreadPool(conf)); } HBaseFsck(Configuration conf); HBaseFsck(Configuration conf, ExecutorService exec); void c... | @Test (timeout=180000) public void testHBaseFsck() throws Exception { assertNoErrors(doFsck(conf, false)); TableName table = TableName.valueOf("tableBadMetaAssign"); HTableDescriptor desc = new HTableDescriptor(table); HColumnDescriptor hcd = new HColumnDescriptor(Bytes.toString(FAM)); desc.addFamily(hcd); createTable(... |
Threads { public static void sleepWithoutInterrupt(final long msToWait) { long timeMillis = System.currentTimeMillis(); long endTime = timeMillis + msToWait; boolean interrupted = false; while (timeMillis < endTime) { try { Thread.sleep(endTime - timeMillis); } catch (InterruptedException ex) { interrupted = true; } ti... | @Test(timeout=60000) public void testSleepWithoutInterrupt() throws InterruptedException { Thread sleeper = new Thread(new Runnable() { @Override public void run() { LOG.debug("Sleeper thread: sleeping for " + SLEEP_TIME_MS); Threads.sleepWithoutInterrupt(SLEEP_TIME_MS); LOG.debug("Sleeper thread: finished sleeping"); ... |
OrderedBytes { public static int encodeString(PositionedByteRange dst, String val, Order ord) { if (null == val) { return encodeNull(dst, ord); } if (val.contains("\u0000")) throw new IllegalArgumentException("Cannot encode String values containing '\\u0000'"); final int offset = dst.getOffset(), start = dst.getPositio... | @Test(expected = IllegalArgumentException.class) public void testStringNoNullChars() { PositionedByteRange buff = new SimplePositionedMutableByteRange(3); OrderedBytes.encodeString(buff, "\u0000", Order.ASCENDING); } |
OrderedBytes { public static int encodeBlobCopy(PositionedByteRange dst, byte[] val, int voff, int vlen, Order ord) { if (null == val) { encodeNull(dst, ord); if (ASCENDING == ord) return 1; else { dst.put(ord.apply(TERM)); return 2; } } assert dst.getRemaining() >= vlen + (ASCENDING == ord ? 1 : 2); if (DESCENDING == ... | @Test(expected = IllegalArgumentException.class) public void testBlobCopyNoZeroBytes() { byte[] val = { 0x01, 0x02, 0x00, 0x03 }; byte[] ascExpected = { 0x38, 0x01, 0x02, 0x00, 0x03 }; PositionedByteRange buf = new SimplePositionedMutableByteRange(val.length + 1); OrderedBytes.encodeBlobCopy(buf, val, Order.ASCENDING);... |
OrderedBytes { public static int skip(PositionedByteRange src) { final int start = src.getPosition(); byte header = src.get(); Order ord = (-1 == Integer.signum(header)) ? DESCENDING : ASCENDING; header = ord.apply(header); switch (header) { case NULL: case NEG_INF: return 1; case NEG_LARGE: skipVaruint64(src, DESCENDI... | @Test public void testSkip() { BigDecimal longMax = BigDecimal.valueOf(Long.MAX_VALUE); double negInf = Double.NEGATIVE_INFINITY; BigDecimal negLarge = longMax.multiply(longMax).negate(); BigDecimal negMed = new BigDecimal("-10.0"); BigDecimal negSmall = new BigDecimal("-0.0010"); long zero = 0l; BigDecimal posSmall = ... |
HBaseFsck extends Configured implements Closeable { private void closeRegion(HbckInfo hi) throws IOException, InterruptedException { if (hi.metaEntry == null && hi.hdfsEntry == null) { undeployRegions(hi); return; } Get get = new Get(hi.getRegionName()); get.addColumn(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QU... | @Test(timeout=180000) public void testFixAssignmentsWhenMETAinTransition() throws Exception { MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); admin.closeRegion(cluster.getServerHoldingMeta(), HRegionInfo.FIRST_META_REGIONINFO); regionStates.regionOffline(HRegionInfo.FIRST_META_REGIONINFO); new MetaTableLocator(... |
SimpleMutableByteRange extends AbstractByteRange { @Override public boolean equals(Object thatObject) { if (thatObject == null) { return false; } if (this == thatObject) { return true; } if (hashCode() != thatObject.hashCode()) { return false; } if (!(thatObject instanceof SimpleMutableByteRange)) { return false; } Sim... | @Test public void testEmpty(){ Assert.assertTrue(SimpleMutableByteRange.isEmpty(null)); ByteRange r = new SimpleMutableByteRange(); Assert.assertTrue(SimpleMutableByteRange.isEmpty(r)); Assert.assertTrue(r.isEmpty()); r.set(new byte[0]); Assert.assertEquals(0, r.getBytes().length); Assert.assertEquals(0, r.getOffset())... |
WeakObjectPool { public V get(K key) { ObjectReference ref = referenceCache.get(key); if (ref != null) { V obj = ref.get(); if (obj != null) { return obj; } referenceCache.remove(key, ref); } V newObj = objectFactory.createObject(key); ObjectReference newRef = new ObjectReference(key, newObj); while (true) { ObjectRefe... | @Test public void testKeys() { Object obj1 = pool.get("a"); Object obj2 = pool.get(new String("a")); Assert.assertSame(obj1, obj2); Object obj3 = pool.get("b"); Assert.assertNotSame(obj1, obj3); }
@Test(timeout=1000) public void testCongestion() throws Exception { final int THREAD_COUNT = 100; final AtomicBoolean asser... |
AES extends Cipher { @VisibleForTesting SecureRandom getRNG() { return rng; } AES(CipherProvider provider); @Override String getName(); @Override int getKeyLength(); @Override int getIvLength(); @Override Key getRandomKey(); @Override Encryptor getEncryptor(); @Override Decryptor getDecryptor(); @Override OutputStream ... | @Test public void testAlternateRNG() throws Exception { Security.addProvider(new TestProvider()); Configuration conf = new Configuration(); conf.set(AES.RNG_ALGORITHM_KEY, "TestRNG"); conf.set(AES.RNG_PROVIDER_KEY, "TEST"); DefaultCipherProvider.getInstance().setConf(conf); AES aes = new AES(DefaultCipherProvider.getIn... |
BoundedByteBufferPool { public void putBuffer(ByteBuffer bb) { if (bb.capacity() > this.maxByteBufferSizeToCache) return; boolean success = false; int average = 0; lock.lock(); try { success = this.buffers.offer(bb); if (success) { this.totalReservoirCapacity += bb.capacity(); average = this.totalReservoirCapacity / th... | @Test public void testEquivalence() { ByteBuffer bb = ByteBuffer.allocate(1); this.reservoir.putBuffer(bb); this.reservoir.putBuffer(bb); this.reservoir.putBuffer(bb); assertEquals(3, this.reservoir.buffers.size()); } |
ChoreService implements ChoreServicer { @Override public synchronized void cancelChore(ScheduledChore chore) { cancelChore(chore, true); } @VisibleForTesting ChoreService(final String coreThreadPoolPrefix); ChoreService(final String coreThreadPoolPrefix, final boolean jitter); ChoreService(final String coreThreadPoo... | @Test (timeout=20000) public void testCancelChore() throws InterruptedException { final int period = 100; ScheduledChore chore1 = new DoNothingChore("chore1", period); ChoreService service = ChoreService.getInstance("testCancelChore"); try { service.scheduleChore(chore1); assertTrue(chore1.isScheduled()); chore1.cancel... |
ChoreService implements ChoreServicer { int getCorePoolSize() { return scheduler.getCorePoolSize(); } @VisibleForTesting ChoreService(final String coreThreadPoolPrefix); ChoreService(final String coreThreadPoolPrefix, final boolean jitter); ChoreService(final String coreThreadPoolPrefix, int corePoolSize, boolean ji... | @Test (timeout=20000) public void testChoreServiceConstruction() throws InterruptedException { final int corePoolSize = 10; final int defaultCorePoolSize = ChoreService.MIN_CORE_POOL_SIZE; ChoreService customInit = new ChoreService("testChoreServiceConstruction_custom", corePoolSize, false); try { assertEquals(corePool... |
HBaseFsck extends Configured implements Closeable { public Multimap<byte[], HbckInfo> getOverlapGroups( TableName table) { TableInfo ti = tablesInfo.get(table); return ti.overlapGroups; } HBaseFsck(Configuration conf); HBaseFsck(Configuration conf, ExecutorService exec); void connect(); void offlineHdfsIntegrityRepair... | @Test (timeout=180000) public void testHBaseFsckClean() throws Exception { assertNoErrors(doFsck(conf, false)); TableName table = TableName.valueOf("tableClean"); try { HBaseFsck hbck = doFsck(conf, false); assertNoErrors(hbck); setupTable(table); assertEquals(ROWKEYS.length, countRows()); hbck = doFsck(conf, false); a... |
ChoreService implements ChoreServicer { public synchronized boolean scheduleChore(ScheduledChore chore) { if (chore == null) { return false; } try { chore.setChoreServicer(this); ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(chore, chore.getInitialDelay(), chore.getPeriod(), chore.getTimeUnit()); scheduledC... | @Test (timeout=20000) public void testShutdownCancelsScheduledChores() throws InterruptedException { final int period = 100; ChoreService service = new ChoreService("testShutdownCancelsScheduledChores"); ScheduledChore successChore1 = new DoNothingChore("sc1", period); ScheduledChore successChore2 = new DoNothingChore(... |
ZKConfig { public static Properties makeZKProps(Configuration conf) { Properties zkProperties = makeZKPropsFromZooCfg(conf); if (zkProperties == null) { zkProperties = makeZKPropsFromHbaseConfig(conf); } return zkProperties; } private ZKConfig(); static Properties makeZKProps(Configuration conf); @Deprecated static Pr... | @Test public void testZKConfigLoading() throws Exception { Configuration conf = HBaseConfiguration.create(); conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, 2181); Properties props = ZKConfig.makeZKProps(conf); assertEquals("Property client port should have been default from the HBase config", "2181", props.getProperty("... |
ZKConfig { public static String getZooKeeperClusterKey(Configuration conf) { return getZooKeeperClusterKey(conf, null); } private ZKConfig(); static Properties makeZKProps(Configuration conf); @Deprecated static Properties parseZooCfg(Configuration conf,
InputStream inputStream); static String getZKQuorumServers... | @Test public void testGetZooKeeperClusterKey() { Configuration conf = HBaseConfiguration.create(); conf.set(HConstants.ZOOKEEPER_QUORUM, "\tlocalhost\n"); conf.set(HConstants.ZOOKEEPER_CLIENT_PORT, "3333"); conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "hbase"); String clusterKey = ZKConfig.getZooKeeperClusterKey(conf, "... |
ZKConfig { public static void validateClusterKey(String key) throws IOException { transformClusterKey(key); } private ZKConfig(); static Properties makeZKProps(Configuration conf); @Deprecated static Properties parseZooCfg(Configuration conf,
InputStream inputStream); static String getZKQuorumServersString(Confi... | @Test public void testClusterKey() throws Exception { testKey("server", 2181, "hbase"); testKey("server1,server2,server3", 2181, "hbase"); try { ZKConfig.validateClusterKey("2181:hbase"); } catch (IOException ex) { } } |
CellUtil { public static CellScanner createCellScanner(final List<? extends CellScannable> cellScannerables) { return new CellScanner() { private final Iterator<? extends CellScannable> iterator = cellScannerables.iterator(); private CellScanner cellScanner = null; @Override public Cell current() { return this.cellScan... | @Test public void testCreateCellScannerOverflow() throws IOException { consume(doCreateCellScanner(1, 1), 1 * 1); consume(doCreateCellScanner(3, 0), 3 * 0); consume(doCreateCellScanner(3, 3), 3 * 3); consume(doCreateCellScanner(0, 1), 0 * 1); final int hundredK = 100000; consume(doCreateCellScanner(hundredK, 0), hundre... |
CellUtil { public static boolean overlappingKeys(final byte[] start1, final byte[] end1, final byte[] start2, final byte[] end2) { return (end2.length == 0 || start1.length == 0 || Bytes.compareTo(start1, end2) < 0) && (end1.length == 0 || start2.length == 0 || Bytes.compareTo(start2, end1) < 0); } static ByteRange fi... | @Test public void testOverlappingKeys() { byte[] empty = HConstants.EMPTY_BYTE_ARRAY; byte[] a = Bytes.toBytes("a"); byte[] b = Bytes.toBytes("b"); byte[] c = Bytes.toBytes("c"); byte[] d = Bytes.toBytes("d"); Assert.assertTrue(CellUtil.overlappingKeys(a, b, a, b)); Assert.assertTrue(CellUtil.overlappingKeys(a, c, a, b... |
CellUtil { public static int findCommonPrefixInFlatKey(Cell c1, Cell c2, boolean bypassFamilyCheck, boolean withTsType) { short rLen1 = c1.getRowLength(); short rLen2 = c2.getRowLength(); int commonPrefix = KeyValue.ROW_LENGTH_SIZE; if (rLen1 != rLen2) { return ByteBufferUtils.findCommonPrefix(Bytes.toBytes(rLen1), 0, ... | @Test public void testFindCommonPrefixInFlatKey() { KeyValue kv1 = new KeyValue("r1".getBytes(), "f1".getBytes(), "q1".getBytes(), null); Assert.assertEquals(kv1.getKeyLength(), CellUtil.findCommonPrefixInFlatKey(kv1, kv1, true, true)); Assert.assertEquals(kv1.getKeyLength(), CellUtil.findCommonPrefixInFlatKey(kv1, kv1... |
CellUtil { public static String toString(Cell cell, boolean verbose) { if (cell == null) { return ""; } StringBuilder builder = new StringBuilder(); String keyStr = getCellKeyAsString(cell); String tag = null; String value = null; if (verbose) { tag = Bytes.toStringBinary(cell.getTagsArray(), cell.getTagsOffset(), cell... | @Test public void testToString() { byte [] row = Bytes.toBytes("row"); long ts = 123l; KeyValue kv = new KeyValue(row, HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY, ts, KeyValue.Type.Minimum, HConstants.EMPTY_BYTE_ARRAY); Cell cell = CellUtil.createCell(row, HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYT... |
HBaseFsck extends Configured implements Closeable { public int getRetCode() { return retcode; } HBaseFsck(Configuration conf); HBaseFsck(Configuration conf, ExecutorService exec); void connect(); void offlineHdfsIntegrityRepair(); int onlineConsistencyRepair(); int onlineHbck(); static byte[] keyOnly(byte[] b); @Overr... | @Test (timeout=180000) public void testParallelHbck() throws Exception { final ExecutorService service; final Future<HBaseFsck> hbck1,hbck2; class RunHbck implements Callable<HBaseFsck>{ boolean fail = true; @Override public HBaseFsck call(){ Configuration c = new Configuration(conf); c.setInt("hbase.hbck.lockfile.atte... |
FixedLengthWrapper implements DataType<T> { @Override public T decode(PositionedByteRange src) { if (src.getRemaining() < length) { throw new IllegalArgumentException("Not enough buffer remaining. src.offset: " + src.getOffset() + " src.length: " + src.getLength() + " src.position: " + src.getPosition() + " max length:... | @Test(expected = IllegalArgumentException.class) public void testInsufficientRemainingRead() { PositionedByteRange buff = new SimplePositionedMutableByteRange(0); DataType<byte[]> type = new FixedLengthWrapper<byte[]>(new RawBytes(), 3); type.decode(buff); } |
HBaseConfiguration extends Configuration { public static Configuration subset(Configuration srcConf, String prefix) { Configuration newConf = new Configuration(false); for (Map.Entry<String, String> entry : srcConf) { if (entry.getKey().startsWith(prefix)) { String newKey = entry.getKey().substring(prefix.length()); if... | @Test public void testSubset() throws Exception { Configuration conf = HBaseConfiguration.create(); String prefix = "hbase.mapred.output."; conf.set("hbase.security.authentication", "kerberos"); conf.set("hbase.regionserver.kerberos.principal", "hbasesource"); HBaseConfiguration.setWithPrefix(conf, prefix, ImmutableMap... |
HBaseConfiguration extends Configuration { public static String getPassword(Configuration conf, String alias, String defPass) throws IOException { String passwd = null; try { Method m = Configuration.class.getMethod("getPassword", String.class); char[] p = (char[]) m.invoke(conf, alias); if (p != null) { LOG.debug(Stri... | @Test public void testGetPassword() throws Exception { Configuration conf = HBaseConfiguration.create(); conf.set(ReflectiveCredentialProviderClient.CREDENTIAL_PROVIDER_PATH, "jceks: + new File(UTIL.getDataTestDir().toUri().getPath(), "foo.jks").getCanonicalPath()); ReflectiveCredentialProviderClient client = new Refle... |
TimeoutBlockingQueue { public TimeoutBlockingQueue(TimeoutRetriever<? super E> timeoutRetriever) { this(32, timeoutRetriever); } TimeoutBlockingQueue(TimeoutRetriever<? super E> timeoutRetriever); @SuppressWarnings("unchecked") TimeoutBlockingQueue(int capacity, TimeoutRetriever<? super E> timeoutRetriever); void dump... | @Test public void testTimeoutBlockingQueue() { TimeoutBlockingQueue<TestObject> queue; int[][] testArray = new int[][] { {200, 400, 600}, {200, 400, 100}, {200, 400, 300}, }; for (int i = 0; i < testArray.length; ++i) { int[] sortedArray = Arrays.copyOf(testArray[i], testArray[i].length); Arrays.sort(sortedArray); queu... |
ProcedureStoreTracker { public boolean isTracking(long minId, long maxId) { return map.floorEntry(minId) != null || map.floorEntry(maxId) != null; } void insert(long procId); void insert(final long procId, final long[] subProcIds); void update(long procId); void delete(long procId); long getUpdatedMinProcId(); long ge... | @Test public void testIsTracking() { long[][] procIds = new long[][] {{4, 7}, {1024, 1027}, {8192, 8194}}; long[][] checkIds = new long[][] {{2, 8}, {1023, 1025}, {8193, 8191}}; ProcedureStoreTracker tracker = new ProcedureStoreTracker(); for (int i = 0; i < procIds.length; ++i) { long[] seq = procIds[i]; tracker.inser... |
ProcedureStoreTracker { public void delete(long procId) { Map.Entry<Long, BitSetNode> entry = map.floorEntry(procId); assert entry != null : "expected node to delete procId=" + procId; BitSetNode node = entry.getValue(); assert node.contains(procId) : "expected procId in the node"; node.delete(procId); if (!keepDeletes... | @Test public void testDelete() { final ProcedureStoreTracker tracker = new ProcedureStoreTracker(); long[] procIds = new long[] { 65, 1, 193 }; for (int i = 0; i < procIds.length; ++i) { tracker.insert(procIds[i]); tracker.dump(); } for (int i = 0; i < (64 * 4); ++i) { boolean hasProc = false; for (int j = 0; j < procI... |
WALProcedureStore extends ProcedureStoreBase { @VisibleForTesting protected void periodicRollForTesting() throws IOException { lock.lock(); try { periodicRoll(); } finally { lock.unlock(); } } WALProcedureStore(final Configuration conf, final FileSystem fs, final Path logDir,
final LeaseRecovery leaseRecovery); @... | @Test public void testEmptyRoll() throws Exception { for (int i = 0; i < 10; ++i) { procStore.periodicRollForTesting(); } FileStatus[] status = fs.listStatus(logDir); assertEquals(1, status.length); } |
WALProcedureStore extends ProcedureStoreBase { @Override public void load(final ProcedureLoader loader) throws IOException { if (logs.isEmpty()) { throw new RuntimeException("recoverLease() must be called before loading data"); } if (logs.size() == 1) { if (LOG.isDebugEnabled()) { LOG.debug("No state logs to replay.");... | @Test public void testLoad() throws Exception { Set<Long> procIds = new HashSet<>(); Procedure proc1 = new TestSequentialProcedure(); procIds.add(proc1.getProcId()); procStore.insert(proc1, null); Procedure proc2 = new TestSequentialProcedure(); Procedure[] child2 = new Procedure[2]; child2[0] = new TestSequentialProce... |
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public boolean exists(ByteBuffer table, TGet get) throws TIOError, TException { Table htable = getTable(table); try { return htable.exists(getFromThrift(get)); } catch (IOException e) { throw getTIOError(e); } finally { closeTable(htable); } } ThriftH... | @Test public void testExists() throws TIOError, TException { ThriftHBaseServiceHandler handler = createHandler(); byte[] rowName = "testExists".getBytes(); ByteBuffer table = wrap(tableAname); TGet get = new TGet(wrap(rowName)); assertFalse(handler.exists(table, get)); List<TColumnValue> columnValues = new ArrayList<TC... |
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public List<TDelete> deleteMultiple(ByteBuffer table, List<TDelete> deletes) throws TIOError, TException { Table htable = getTable(table); try { htable.delete(deletesFromThrift(deletes)); } catch (IOException e) { throw getTIOError(e); } finally { clo... | @Test public void testDeleteMultiple() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); ByteBuffer table = wrap(tableAname); byte[] rowName1 = "testDeleteMultiple1".getBytes(); byte[] rowName2 = "testDeleteMultiple2".getBytes(); List<TColumnValue> columnValues = new ArrayList<TColumnValue>(); col... |
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public TResult increment(ByteBuffer table, TIncrement increment) throws TIOError, TException { Table htable = getTable(table); try { return resultFromHBase(htable.increment(incrementFromThrift(increment))); } catch (IOException e) { throw getTIOError(... | @Test public void testIncrement() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); byte[] rowName = "testIncrement".getBytes(); ByteBuffer table = wrap(tableAname); List<TColumnValue> columnValues = new ArrayList<TColumnValue>(); columnValues.add(new TColumnValue(wrap(familyAname), wrap(qualifier... |
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public TResult append(ByteBuffer table, TAppend append) throws TIOError, TException { Table htable = getTable(table); try { return resultFromHBase(htable.append(appendFromThrift(append))); } catch (IOException e) { throw getTIOError(e); } finally { cl... | @Test public void testAppend() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); byte[] rowName = "testAppend".getBytes(); ByteBuffer table = wrap(tableAname); byte[] v1 = Bytes.toBytes("42"); byte[] v2 = Bytes.toBytes("23"); List<TColumnValue> columnValues = new ArrayList<TColumnValue>(); columnV... |
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public boolean checkAndPut(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value, TPut put) throws TIOError, TException { Table htable = getTable(table); try { return htable.checkAndPut(byteBufferToByteArray(row),... | @Test public void testCheckAndPut() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); byte[] rowName = "testCheckAndPut".getBytes(); ByteBuffer table = wrap(tableAname); List<TColumnValue> columnValuesA = new ArrayList<TColumnValue>(); TColumnValue columnValueA = new TColumnValue(wrap(familyAname)... |
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public boolean checkAndDelete(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value, TDelete deleteSingle) throws TIOError, TException { Table htable = getTable(table); try { if (value == null) { return htable.che... | @Test public void testCheckAndDelete() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); byte[] rowName = "testCheckAndDelete".getBytes(); ByteBuffer table = wrap(tableAname); List<TColumnValue> columnValuesA = new ArrayList<TColumnValue>(); TColumnValue columnValueA = new TColumnValue(wrap(family... |
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public List<TResult> getScannerResults(ByteBuffer table, TScan scan, int numRows) throws TIOError, TException { Table htable = getTable(table); List<TResult> results = null; ResultScanner scanner = null; try { scanner = htable.getScanner(scanFromThrif... | @Test public void testGetScannerResults() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); ByteBuffer table = wrap(tableAname); TColumnValue columnValue = new TColumnValue(wrap(familyAname), wrap(qualifierAname), wrap(valueAname)); List<TColumnValue> columnValues = new ArrayList<TColumnValue>(); ... |
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public TResult get(ByteBuffer table, TGet get) throws TIOError, TException { Table htable = getTable(table); try { return resultFromHBase(htable.get(getFromThrift(get))); } catch (IOException e) { throw getTIOError(e); } finally { closeTable(htable); ... | @Test public void testFilterRegistration() throws Exception { Configuration conf = UTIL.getConfiguration(); conf.set("hbase.thrift.filters", "MyFilter:filterclass"); ThriftServer.registerFilters(conf); Map<String, String> registeredFilters = ParseFilter.getAllFilters(); assertEquals("filterclass", registeredFilters.get... |
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public void put(ByteBuffer table, TPut put) throws TIOError, TException { Table htable = getTable(table); try { htable.put(putFromThrift(put)); } catch (IOException e) { throw getTIOError(e); } finally { closeTable(htable); } } ThriftHBaseServiceHandl... | @Test public void testAttribute() throws Exception { byte[] rowName = "testAttribute".getBytes(); byte[] attributeKey = "attribute1".getBytes(); byte[] attributeValue = "value1".getBytes(); Map<ByteBuffer, ByteBuffer> attributes = new HashMap<ByteBuffer, ByteBuffer>(); attributes.put(wrap(attributeKey), wrap(attributeV... |
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public void mutateRow(ByteBuffer table, TRowMutations rowMutations) throws TIOError, TException { Table htable = getTable(table); try { htable.mutateRow(rowMutationsFromThrift(rowMutations)); } catch (IOException e) { throw getTIOError(e); } finally {... | @Test public void testMutateRow() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); byte[] rowName = "testMutateRow".getBytes(); ByteBuffer table = wrap(tableAname); List<TColumnValue> columnValuesA = new ArrayList<TColumnValue>(); TColumnValue columnValueA = new TColumnValue(wrap(familyAname), wr... |
ClientExceptionsUtil { public static Throwable findException(Object exception) { if (exception == null || !(exception instanceof Throwable)) { return null; } Throwable cur = (Throwable) exception; while (cur != null) { if (isSpecialException(cur)) { return cur; } if (cur instanceof RemoteException) { RemoteException re... | @Test public void testFindException() throws Exception { IOException ioe = new IOException("Tesst"); ServiceException se = new ServiceException(ioe); assertEquals(ioe, ClientExceptionsUtil.findException(se)); } |
LongComparator extends ByteArrayComparable { @Override public int compareTo(byte[] value, int offset, int length) { Long that = Bytes.toLong(value, offset, length); return this.longValue.compareTo(that); } LongComparator(long value); @Override int compareTo(byte[] value, int offset, int length); @Override byte [] toByt... | @Test public void testSimple() { for (int i = 1; i < values.length ; i++) { for (int j = 0; j < i; j++) { LongComparator cp = new LongComparator(values[i]); assertEquals(1, cp.compareTo(Bytes.toBytes(values[j]))); } } } |
RegionLocations { public RegionLocations removeByServer(ServerName serverName) { HRegionLocation[] newLocations = null; for (int i = 0; i < locations.length; i++) { if (locations[i] != null && serverName.equals(locations[i].getServerName())) { if (newLocations == null) { newLocations = new HRegionLocation[locations.len... | @Test public void testRemoveByServer() { RegionLocations list; list = new RegionLocations(); assertTrue(list == list.removeByServer(sn0)); list = hrll(hrl(info0, sn0)); assertTrue(list == list.removeByServer(sn1)); list = list.removeByServer(sn0); assertEquals(0, list.numNonNullElements()); list = hrll(hrl(info0, sn0),... |
RegionLocations { public RegionLocations remove(HRegionLocation location) { if (location == null) return this; if (location.getRegionInfo() == null) return this; int replicaId = location.getRegionInfo().getReplicaId(); if (replicaId >= locations.length) return this; if (locations[replicaId] == null || !location.getRegi... | @Test public void testRemove() { RegionLocations list; list = new RegionLocations(); assertTrue(list == list.remove(hrl(info0, sn0))); list = hrll(hrl(info0, sn0)); assertTrue(list == list.remove(hrl(info0, sn1))); list = list.remove(hrl(info0, sn0)); assertTrue(list.isEmpty()); list = hrll(hrl(info0, sn0), hrl(info1, ... |
RegionLocations { public RegionLocations updateLocation(HRegionLocation location, boolean checkForEquals, boolean force) { assert location != null; int replicaId = location.getRegionInfo().getReplicaId(); HRegionLocation oldLoc = getRegionLocation(location.getRegionInfo().getReplicaId()); HRegionLocation selectedLoc = ... | @Test public void testUpdateLocation() { RegionLocations list; list = new RegionLocations(); list = list.updateLocation(hrl(info0, sn1), false, false); assertEquals(sn1, list.getRegionLocation(0).getServerName()); list = list.updateLocation(hrl(info9, sn3, 10), false, false); assertEquals(sn3, list.getRegionLocation(9)... |
HBaseFsck extends Configured implements Closeable { @Override public void close() throws IOException { IOUtils.closeQuietly(admin); IOUtils.closeQuietly(meta); IOUtils.closeQuietly(connection); } HBaseFsck(Configuration conf); HBaseFsck(Configuration conf, ExecutorService exec); void connect(); void offlineHdfsIntegri... | @Test public void testHbckWithExcessReplica() throws Exception { TableName table = TableName.valueOf("testHbckWithExcessReplica"); try { setupTableWithRegionReplica(table, 2); TEST_UTIL.getHBaseAdmin().flush(table.getName()); assertNoErrors(doFsck(conf, false)); assertEquals(ROWKEYS.length, countRows()); HTable meta = ... |
RegionLocations { public RegionLocations mergeLocations(RegionLocations other) { assert other != null; HRegionLocation[] newLocations = null; int max = other.locations.length; HRegionInfo regionInfo = null; for (int i = 0; i < max; i++) { HRegionLocation thisLoc = this.getRegionLocation(i); HRegionLocation otherLoc = o... | @Test public void testMergeLocations() { RegionLocations list1, list2; list1 = new RegionLocations(); list2 = new RegionLocations(); assertTrue(list1 == list1.mergeLocations(list2)); list2 = hrll(hrl(info0, sn0)); list1 = list1.mergeLocations(list2); assertEquals(sn0, list1.getRegionLocation(0).getServerName()); list1 ... |
IPCUtil { @SuppressWarnings("resource") public ByteBuffer buildCellBlock(final Codec codec, final CompressionCodec compressor, final CellScanner cellScanner) throws IOException { return buildCellBlock(codec, compressor, cellScanner, null); } IPCUtil(final Configuration conf); @SuppressWarnings("resource") ByteBuffer bu... | @Test public void testBuildCellBlock() throws IOException { doBuildCellBlockUndoCellBlock(this.util, new KeyValueCodec(), null); doBuildCellBlockUndoCellBlock(this.util, new KeyValueCodec(), new DefaultCodec()); doBuildCellBlockUndoCellBlock(this.util, new KeyValueCodec(), new GzipCodec()); } |
PayloadCarryingRpcController extends TimeLimitedRpcController implements CellScannable { public CellScanner cellScanner() { return cellScanner; } PayloadCarryingRpcController(); PayloadCarryingRpcController(final CellScanner cellScanner); PayloadCarryingRpcController(final List<CellScannable> cellIterables); CellScan... | @Test public void testListOfCellScannerables() throws IOException { List<CellScannable> cells = new ArrayList<CellScannable>(); final int count = 10; for (int i = 0; i < count; i++) { cells.add(createCell(i)); } PayloadCarryingRpcController controller = new PayloadCarryingRpcController(cells); CellScanner cellScanner =... |
AsyncProcess { public <CResult> AsyncRequestFuture submit(TableName tableName, List<? extends Row> rows, boolean atLeastOne, Batch.Callback<CResult> callback, boolean needResults) throws InterruptedIOException { return submit(null, tableName, rows, atLeastOne, callback, needResults); } AsyncProcess(ClusterConnection hc... | @Test public void testSubmit() throws Exception { ClusterConnection hc = createHConnection(); AsyncProcess ap = new MyAsyncProcess(hc, conf); List<Put> puts = new ArrayList<Put>(); puts.add(createPut(1, true)); ap.submit(DUMMY_TABLE, puts, false, null, false); Assert.assertTrue(puts.isEmpty()); }
@Test public void test... |
AsyncProcess { @VisibleForTesting void waitUntilDone() throws InterruptedIOException { waitForMaximumCurrentTasks(0); } AsyncProcess(ClusterConnection hc, Configuration conf, ExecutorService pool,
RpcRetryingCallerFactory rpcCaller, boolean useGlobalErrors, RpcControllerFactory rpcFactory); AsyncRequestFuture sub... | @Test public void testHTableFailedPutAndNewPut() throws Exception { ClusterConnection conn = createHConnection(); BufferedMutatorImpl mutator = new BufferedMutatorImpl(conn, null, null, new BufferedMutatorParams(DUMMY_TABLE).writeBufferSize(0)); MyAsyncProcess ap = new MyAsyncProcess(conn, conf, true); mutator.ap = ap;... |
AsyncProcess { protected ConnectionManager.ServerErrorTracker createServerErrorTracker() { return new ConnectionManager.ServerErrorTracker( this.serverTrackerTimeout, this.numTries); } AsyncProcess(ClusterConnection hc, Configuration conf, ExecutorService pool,
RpcRetryingCallerFactory rpcCaller, boolean useGloba... | @Test public void testErrorsServers() throws IOException { Configuration configuration = new Configuration(conf); ClusterConnection conn = new MyConnectionImpl(configuration); BufferedMutatorImpl mutator = new BufferedMutatorImpl(conn, null, null, new BufferedMutatorParams(DUMMY_TABLE)); configuration.setBoolean(Connec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.