method2testcases
stringlengths
118
6.63k
### Question: Counters extends AbstractCounters<Counters.Counter, Counters.Group> { public void incrCounter(Enum<?> key, long amount) { findCounter(key).increment(amount); } Counters(); Counters(org.apache.hadoop.mapreduce.Counters newCounters); synchronized Group getGroup(String groupName); @SuppressWarnings("unchecked") synchronized Collection<String> getGroupNames(); synchronized String makeCompactString(); synchronized Counter findCounter(String group, String name); @Deprecated Counter findCounter(String group, int id, String name); void incrCounter(Enum<?> key, long amount); void incrCounter(String group, String counter, long amount); synchronized long getCounter(Enum<?> key); synchronized void incrAllCounters(Counters other); int size(); static Counters sum(Counters a, Counters b); void log(Log log); String makeEscapedCompactString(); static Counters fromEscapedCompactString(String compactString); static int MAX_COUNTER_LIMIT; }### Answer: @SuppressWarnings("deprecation") @Test public void testCounterIteratorConcurrency() { Counters counters = new Counters(); counters.incrCounter("group1", "counter1", 1); Iterator<Group> iterator = counters.iterator(); counters.incrCounter("group2", "counter2", 1); iterator.next(); }
### Question: Counters extends AbstractCounters<Counters.Counter, Counters.Group> { public synchronized String makeCompactString() { StringBuilder builder = new StringBuilder(); boolean first = true; for(Group group: this){ for(Counter counter: group) { if (first) { first = false; } else { builder.append(','); } builder.append(group.getDisplayName()); builder.append('.'); builder.append(counter.getDisplayName()); builder.append(':'); builder.append(counter.getCounter()); } } return builder.toString(); } Counters(); Counters(org.apache.hadoop.mapreduce.Counters newCounters); synchronized Group getGroup(String groupName); @SuppressWarnings("unchecked") synchronized Collection<String> getGroupNames(); synchronized String makeCompactString(); synchronized Counter findCounter(String group, String name); @Deprecated Counter findCounter(String group, int id, String name); void incrCounter(Enum<?> key, long amount); void incrCounter(String group, String counter, long amount); synchronized long getCounter(Enum<?> key); synchronized void incrAllCounters(Counters other); int size(); static Counters sum(Counters a, Counters b); void log(Log log); String makeEscapedCompactString(); static Counters fromEscapedCompactString(String compactString); static int MAX_COUNTER_LIMIT; }### Answer: @Test public void testMakeCompactString() { final String GC1 = "group1.counter1:1"; final String GC2 = "group2.counter2:3"; Counters counters = new Counters(); counters.incrCounter("group1", "counter1", 1); assertEquals("group1.counter1:1", counters.makeCompactString()); counters.incrCounter("group2", "counter2", 3); String cs = counters.makeCompactString(); assertTrue("Bad compact string", cs.equals(GC1 + ',' + GC2) || cs.equals(GC2 + ',' + GC1)); }
### Question: ResourceMgrDelegate extends YarnClientImpl { public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return TypeConverter.fromYarnQueueInfo(super.getRootQueueInfos(), this.conf); } ResourceMgrDelegate(YarnConfiguration conf); void cancelDelegationToken(Token<DelegationTokenIdentifier> arg0); TaskTrackerInfo[] getActiveTrackers(); JobStatus[] getAllJobs(); TaskTrackerInfo[] getBlacklistedTrackers(); ClusterMetrics getClusterMetrics(); @SuppressWarnings("rawtypes") Token getDelegationToken(Text renewer); String getFilesystemName(); JobID getNewJobID(); QueueInfo getQueue(String queueName); QueueAclsInfo[] getQueueAclsForCurrentUser(); QueueInfo[] getQueues(); QueueInfo[] getRootQueues(); QueueInfo[] getChildQueues(String parent); String getStagingAreaDir(); String getSystemDir(); long getTaskTrackerExpiryInterval(); void setJobPriority(JobID arg0, String arg1); long getProtocolVersion(String arg0, long arg1); long renewDelegationToken(Token<DelegationTokenIdentifier> arg0); ApplicationId getApplicationId(); }### Answer: @Test public void testGetRootQueues() throws IOException, InterruptedException { final ClientRMProtocol applicationsManager = Mockito.mock(ClientRMProtocol.class); GetQueueInfoResponse response = Mockito.mock(GetQueueInfoResponse.class); org.apache.hadoop.yarn.api.records.QueueInfo queueInfo = Mockito.mock(org.apache.hadoop.yarn.api.records.QueueInfo.class); Mockito.when(response.getQueueInfo()).thenReturn(queueInfo); Mockito.when(applicationsManager.getQueueInfo(Mockito.any( GetQueueInfoRequest.class))).thenReturn(response); ResourceMgrDelegate delegate = new ResourceMgrDelegate( new YarnConfiguration()) { @Override public synchronized void start() { this.rmClient = applicationsManager; } }; delegate.getRootQueues(); ArgumentCaptor<GetQueueInfoRequest> argument = ArgumentCaptor.forClass(GetQueueInfoRequest.class); Mockito.verify(applicationsManager).getQueueInfo( argument.capture()); Assert.assertTrue("Children of root queue not requested", argument.getValue().getIncludeChildQueues()); Assert.assertTrue("Request wasn't to recurse through children", argument.getValue().getRecursive()); }
### Question: ResourceMgrDelegate extends YarnClientImpl { public JobStatus[] getAllJobs() throws IOException, InterruptedException { return TypeConverter.fromYarnApps(super.getApplicationList(), this.conf); } ResourceMgrDelegate(YarnConfiguration conf); void cancelDelegationToken(Token<DelegationTokenIdentifier> arg0); TaskTrackerInfo[] getActiveTrackers(); JobStatus[] getAllJobs(); TaskTrackerInfo[] getBlacklistedTrackers(); ClusterMetrics getClusterMetrics(); @SuppressWarnings("rawtypes") Token getDelegationToken(Text renewer); String getFilesystemName(); JobID getNewJobID(); QueueInfo getQueue(String queueName); QueueAclsInfo[] getQueueAclsForCurrentUser(); QueueInfo[] getQueues(); QueueInfo[] getRootQueues(); QueueInfo[] getChildQueues(String parent); String getStagingAreaDir(); String getSystemDir(); long getTaskTrackerExpiryInterval(); void setJobPriority(JobID arg0, String arg1); long getProtocolVersion(String arg0, long arg1); long renewDelegationToken(Token<DelegationTokenIdentifier> arg0); ApplicationId getApplicationId(); }### Answer: @Test public void tesAllJobs() throws Exception { final ClientRMProtocol applicationsManager = Mockito.mock(ClientRMProtocol.class); GetAllApplicationsResponse allApplicationsResponse = Records .newRecord(GetAllApplicationsResponse.class); List<ApplicationReport> applications = new ArrayList<ApplicationReport>(); applications.add(getApplicationReport(YarnApplicationState.FINISHED, FinalApplicationStatus.FAILED)); applications.add(getApplicationReport(YarnApplicationState.FINISHED, FinalApplicationStatus.SUCCEEDED)); applications.add(getApplicationReport(YarnApplicationState.FINISHED, FinalApplicationStatus.KILLED)); applications.add(getApplicationReport(YarnApplicationState.FAILED, FinalApplicationStatus.FAILED)); allApplicationsResponse.setApplicationList(applications); Mockito.when( applicationsManager.getAllApplications(Mockito .any(GetAllApplicationsRequest.class))).thenReturn( allApplicationsResponse); ResourceMgrDelegate resourceMgrDelegate = new ResourceMgrDelegate( new YarnConfiguration()) { @Override public synchronized void start() { this.rmClient = applicationsManager; } }; JobStatus[] allJobs = resourceMgrDelegate.getAllJobs(); Assert.assertEquals(State.FAILED, allJobs[0].getState()); Assert.assertEquals(State.SUCCEEDED, allJobs[1].getState()); Assert.assertEquals(State.KILLED, allJobs[2].getState()); Assert.assertEquals(State.FAILED, allJobs[3].getState()); }
### Question: ClientServiceDelegate { public org.apache.hadoop.mapreduce.Counters getJobCounters(JobID arg0) throws IOException, InterruptedException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobID = TypeConverter.toYarn(arg0); GetCountersRequest request = recordFactory.newRecordInstance(GetCountersRequest.class); request.setJobId(jobID); Counters cnt = ((GetCountersResponse) invoke("getCounters", GetCountersRequest.class, request)).getCounters(); return TypeConverter.fromYarn(cnt); } ClientServiceDelegate(Configuration conf, ResourceMgrDelegate rm, JobID jobId, MRClientProtocol historyServerProxy); org.apache.hadoop.mapreduce.Counters getJobCounters(JobID arg0); TaskCompletionEvent[] getTaskCompletionEvents(JobID arg0, int arg1, int arg2); String[] getTaskDiagnostics(org.apache.hadoop.mapreduce.TaskAttemptID arg0); JobStatus getJobStatus(JobID oldJobID); org.apache.hadoop.mapreduce.TaskReport[] getTaskReports(JobID oldJobID, TaskType taskType); boolean killTask(TaskAttemptID taskAttemptID, boolean fail); boolean killJob(JobID oldJobID); LogParams getLogFilePath(JobID oldJobID, TaskAttemptID oldTaskAttemptID); }### Answer: @Test public void testCountersFromHistoryServer() throws Exception { MRClientProtocol historyServerProxy = mock(MRClientProtocol.class); when(historyServerProxy.getCounters(getCountersRequest())).thenReturn( getCountersResponseFromHistoryServer()); ResourceMgrDelegate rm = mock(ResourceMgrDelegate.class); when(rm.getApplicationReport(TypeConverter.toYarn(oldJobId).getAppId())) .thenReturn(null); ClientServiceDelegate clientServiceDelegate = getClientServiceDelegate( historyServerProxy, rm); Counters counters = TypeConverter.toYarn(clientServiceDelegate.getJobCounters(oldJobId)); Assert.assertNotNull(counters); Assert.assertEquals(1001, counters.getCounterGroup("dummyCounters").getCounter("dummyCounter").getValue()); }
### Question: ContainerLauncherImpl extends AbstractService implements ContainerLauncher { @Override public void handle(ContainerLauncherEvent event) { try { eventQueue.put(event); this.allNodes.add(event.getContainerMgrAddress()); } catch (InterruptedException e) { throw new YarnException(e); } } ContainerLauncherImpl(AppContext context); @Override synchronized void init(Configuration config); void start(); void stop(); @Override void handle(ContainerLauncherEvent event); }### Answer: @Test public void testHandle() throws Exception { LOG.info("STARTING testHandle"); YarnRPC mockRpc = mock(YarnRPC.class); AppContext mockContext = mock(AppContext.class); @SuppressWarnings("rawtypes") EventHandler mockEventHandler = mock(EventHandler.class); when(mockContext.getEventHandler()).thenReturn(mockEventHandler); ContainerManager mockCM = mock(ContainerManager.class); when(mockRpc.getProxy(eq(ContainerManager.class), any(InetSocketAddress.class), any(Configuration.class))) .thenReturn(mockCM); ContainerLauncherImplUnderTest ut = new ContainerLauncherImplUnderTest(mockContext, mockRpc); Configuration conf = new Configuration(); ut.init(conf); ut.start(); try { ContainerId contId = makeContainerId(0l, 0, 0, 1); TaskAttemptId taskAttemptId = makeTaskAttemptId(0l, 0, 0, TaskType.MAP, 0); String cmAddress = "127.0.0.1:8000"; StartContainerResponse startResp = recordFactory.newRecordInstance(StartContainerResponse.class); startResp.setServiceResponse(ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID, ShuffleHandler.serializeMetaData(80)); LOG.info("inserting launch event"); ContainerRemoteLaunchEvent mockLaunchEvent = mock(ContainerRemoteLaunchEvent.class); when(mockLaunchEvent.getType()) .thenReturn(EventType.CONTAINER_REMOTE_LAUNCH); when(mockLaunchEvent.getContainerID()) .thenReturn(contId); when(mockLaunchEvent.getTaskAttemptID()).thenReturn(taskAttemptId); when(mockLaunchEvent.getContainerMgrAddress()).thenReturn(cmAddress); when(mockCM.startContainer(any(StartContainerRequest.class))).thenReturn(startResp); ut.handle(mockLaunchEvent); ut.waitForPoolToIdle(); verify(mockCM).startContainer(any(StartContainerRequest.class)); LOG.info("inserting cleanup event"); ContainerLauncherEvent mockCleanupEvent = mock(ContainerLauncherEvent.class); when(mockCleanupEvent.getType()) .thenReturn(EventType.CONTAINER_REMOTE_CLEANUP); when(mockCleanupEvent.getContainerID()) .thenReturn(contId); when(mockCleanupEvent.getTaskAttemptID()).thenReturn(taskAttemptId); when(mockCleanupEvent.getContainerMgrAddress()).thenReturn(cmAddress); ut.handle(mockCleanupEvent); ut.waitForPoolToIdle(); verify(mockCM).stopContainer(any(StopContainerRequest.class)); } finally { ut.stop(); } }
### Question: Constraints { public static void remove(HTableDescriptor desc) { disable(desc); List<ImmutableBytesWritable> keys = new ArrayList<ImmutableBytesWritable>(); for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e : desc .getValues().entrySet()) { String key = Bytes.toString((e.getKey().get())); String[] className = CONSTRAINT_HTD_ATTR_KEY_PATTERN.split(key); if (className.length == 2) { keys.add(e.getKey()); } } for (ImmutableBytesWritable key : keys) { desc.remove(key.get()); } } private Constraints(); static void enable(HTableDescriptor desc); static void disable(HTableDescriptor desc); static void remove(HTableDescriptor desc); static boolean has(HTableDescriptor desc, Class<? extends Constraint> clazz); static void add(HTableDescriptor desc, Class<? extends Constraint>... constraints); static void add(HTableDescriptor desc, Pair<Class<? extends Constraint>, Configuration>... constraints); static void add(HTableDescriptor desc, Class<? extends Constraint> constraint, Configuration conf); static void setConfiguration(HTableDescriptor desc, Class<? extends Constraint> clazz, Configuration configuration); static void remove(HTableDescriptor desc, Class<? extends Constraint> clazz); static void enableConstraint(HTableDescriptor desc, Class<? extends Constraint> clazz); static void disableConstraint(HTableDescriptor desc, Class<? extends Constraint> clazz); static boolean enabled(HTableDescriptor desc, Class<? extends Constraint> clazz); }### Answer: @Test public void testRemoveUnsetConstraint() throws Throwable { HTableDescriptor desc = new HTableDescriptor("table"); Constraints.remove(desc); Constraints.remove(desc, AlsoWorks.class); }
### Question: MRAppMaster extends CompositeService { protected static void initAndStartAppMaster(final MRAppMaster appMaster, final JobConf conf, String jobUserName) throws IOException, InterruptedException { UserGroupInformation.setConfiguration(conf); Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials(); UserGroupInformation appMasterUgi = UserGroupInformation .createRemoteUser(jobUserName); appMasterUgi.addCredentials(credentials); conf.getCredentials().addAll(credentials); appMasterUgi.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { appMaster.init(conf); appMaster.start(); return null; } }); } MRAppMaster(ApplicationAttemptId applicationAttemptId, ContainerId containerId, String nmHost, int nmPort, int nmHttpPort, long appSubmitTime); MRAppMaster(ApplicationAttemptId applicationAttemptId, ContainerId containerId, String nmHost, int nmPort, int nmHttpPort, Clock clock, long appSubmitTime); @Override void init(final Configuration conf); void cleanupStagingDir(); @VisibleForTesting void shutDownJob(); ApplicationId getAppID(); ApplicationAttemptId getAttemptID(); JobId getJobId(); OutputCommitter getCommitter(); boolean isNewApiCommitter(); int getStartCount(); AppContext getContext(); Dispatcher getDispatcher(); Map<TaskId, TaskInfo> getCompletedTaskFromPreviousRun(); List<AMInfo> getAllAMInfos(); ContainerAllocator getContainerAllocator(); ContainerLauncher getContainerLauncher(); TaskAttemptListener getTaskAttemptListener(); @SuppressWarnings("unchecked") @Override void start(); static void main(String[] args); static final int SHUTDOWN_HOOK_PRIORITY; }### Answer: @Test public void testMRAppMasterForDifferentUser() throws IOException, InterruptedException { String applicationAttemptIdStr = "appattempt_1317529182569_0004_000001"; String containerIdStr = "container_1317529182569_0004_000001_1"; String stagingDir = "/tmp/staging"; String userName = "TestAppMasterUser"; ApplicationAttemptId applicationAttemptId = ConverterUtils .toApplicationAttemptId(applicationAttemptIdStr); ContainerId containerId = ConverterUtils.toContainerId(containerIdStr); MRAppMasterTest appMaster = new MRAppMasterTest(applicationAttemptId, containerId, "host", -1, -1, System.currentTimeMillis()); JobConf conf = new JobConf(new YarnConfiguration()); conf.set(MRJobConfig.MR_AM_STAGING_DIR, stagingDir); MRAppMaster.initAndStartAppMaster(appMaster, conf, userName); Assert.assertEquals(stagingDir + Path.SEPARATOR + userName + Path.SEPARATOR + ".staging", appMaster.stagingDirPath.toString()); }
### Question: TaskImpl implements Task, EventHandler<TaskEvent> { @Override public void handle(TaskEvent event) { if (LOG.isDebugEnabled()) { LOG.debug("Processing " + event.getTaskID() + " of type " + event.getType()); } try { writeLock.lock(); TaskStateInternal oldState = getInternalState(); try { stateMachine.doTransition(event.getType(), event); } catch (InvalidStateTransitonException e) { LOG.error("Can't handle this event at current state for " + this.taskId, e); internalError(event.getType()); } if (oldState != getInternalState()) { LOG.info(taskId + " Task Transitioned from " + oldState + " to " + getInternalState()); } } finally { writeLock.unlock(); } } TaskImpl(JobId jobId, TaskType taskType, int partition, EventHandler eventHandler, Path remoteJobConfFile, JobConf conf, TaskAttemptListener taskAttemptListener, Token<JobTokenIdentifier> jobToken, Credentials credentials, Clock clock, Map<TaskId, TaskInfo> completedTasksFromPreviousRun, int startCount, MRAppMetrics metrics, AppContext appContext); @Override TaskState getState(); @Override Map<TaskAttemptId, TaskAttempt> getAttempts(); @Override TaskAttempt getAttempt(TaskAttemptId attemptID); @Override TaskId getID(); @Override boolean isFinished(); @Override TaskReport getReport(); @Override Counters getCounters(); @Override float getProgress(); @VisibleForTesting TaskStateInternal getInternalState(); @Override boolean canCommit(TaskAttemptId taskAttemptID); @Override void handle(TaskEvent event); }### Answer: @Test public void testKillSuccessfulTask() { LOG.info("--- START: testKillSuccesfulTask ---"); mockTask = createMockTask(TaskType.MAP); TaskId taskId = getNewTaskID(); scheduleTaskAttempt(taskId); launchTaskAttempt(getLastAttempt().getAttemptId()); commitTaskAttempt(getLastAttempt().getAttemptId()); mockTask.handle(new TaskTAttemptEvent(getLastAttempt().getAttemptId(), TaskEventType.T_ATTEMPT_SUCCEEDED)); assertTaskSucceededState(); mockTask.handle(new TaskEvent(taskId, TaskEventType.T_KILL)); assertTaskSucceededState(); } @Test public void testSpeculativeMapFetchFailure() { mockTask = createMockTask(TaskType.MAP); runSpeculativeTaskAttemptSucceeds(TaskEventType.T_ATTEMPT_KILLED); assertEquals(2, taskAttempts.size()); mockTask.handle(new TaskTAttemptEvent(taskAttempts.get(1).getAttemptId(), TaskEventType.T_ATTEMPT_FAILED)); assertTaskScheduledState(); assertEquals(3, taskAttempts.size()); } @Test public void testSpeculativeMapMultipleSucceedFetchFailure() { mockTask = createMockTask(TaskType.MAP); runSpeculativeTaskAttemptSucceeds(TaskEventType.T_ATTEMPT_SUCCEEDED); assertEquals(2, taskAttempts.size()); mockTask.handle(new TaskTAttemptEvent(taskAttempts.get(1).getAttemptId(), TaskEventType.T_ATTEMPT_FAILED)); assertTaskScheduledState(); assertEquals(3, taskAttempts.size()); } @Test public void testSpeculativeMapFailedFetchFailure() { mockTask = createMockTask(TaskType.MAP); runSpeculativeTaskAttemptSucceeds(TaskEventType.T_ATTEMPT_FAILED); assertEquals(2, taskAttempts.size()); mockTask.handle(new TaskTAttemptEvent(taskAttempts.get(1).getAttemptId(), TaskEventType.T_ATTEMPT_FAILED)); assertTaskScheduledState(); assertEquals(3, taskAttempts.size()); }
### Question: TaskImpl implements Task, EventHandler<TaskEvent> { @Override public float getProgress() { readLock.lock(); try { TaskAttempt bestAttempt = selectBestAttempt(); if (bestAttempt == null) { return 0f; } return bestAttempt.getProgress(); } finally { readLock.unlock(); } } TaskImpl(JobId jobId, TaskType taskType, int partition, EventHandler eventHandler, Path remoteJobConfFile, JobConf conf, TaskAttemptListener taskAttemptListener, Token<JobTokenIdentifier> jobToken, Credentials credentials, Clock clock, Map<TaskId, TaskInfo> completedTasksFromPreviousRun, int startCount, MRAppMetrics metrics, AppContext appContext); @Override TaskState getState(); @Override Map<TaskAttemptId, TaskAttempt> getAttempts(); @Override TaskAttempt getAttempt(TaskAttemptId attemptID); @Override TaskId getID(); @Override boolean isFinished(); @Override TaskReport getReport(); @Override Counters getCounters(); @Override float getProgress(); @VisibleForTesting TaskStateInternal getInternalState(); @Override boolean canCommit(TaskAttemptId taskAttemptID); @Override void handle(TaskEvent event); }### Answer: @Test public void testTaskProgress() { LOG.info("--- START: testTaskProgress ---"); mockTask = createMockTask(TaskType.MAP); TaskId taskId = getNewTaskID(); scheduleTaskAttempt(taskId); float progress = 0f; assert(mockTask.getProgress() == progress); launchTaskAttempt(getLastAttempt().getAttemptId()); progress = 50f; updateLastAttemptProgress(progress); assert(mockTask.getProgress() == progress); progress = 100f; updateLastAttemptProgress(progress); assert(mockTask.getProgress() == progress); progress = 0f; updateLastAttemptState(TaskAttemptState.KILLED); assert(mockTask.getProgress() == progress); killRunningTaskAttempt(getLastAttempt().getAttemptId()); assert(taskAttempts.size() == 2); assert(mockTask.getProgress() == 0f); launchTaskAttempt(getLastAttempt().getAttemptId()); progress = 50f; updateLastAttemptProgress(progress); assert(mockTask.getProgress() == progress); }
### Question: LoadTypedBytes implements Tool { public int run(String[] args) throws Exception { if (args.length == 0) { System.err.println("Too few arguments!"); printUsage(); return 1; } Path path = new Path(args[0]); FileSystem fs = path.getFileSystem(getConf()); if (fs.exists(path)) { System.err.println("given path exists already!"); return -1; } TypedBytesInput tbinput = new TypedBytesInput(new DataInputStream(System.in)); SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, path, TypedBytesWritable.class, TypedBytesWritable.class); try { TypedBytesWritable key = new TypedBytesWritable(); TypedBytesWritable value = new TypedBytesWritable(); byte[] rawKey = tbinput.readRaw(); while (rawKey != null) { byte[] rawValue = tbinput.readRaw(); key.set(rawKey, 0, rawKey.length); value.set(rawValue, 0, rawValue.length); writer.append(key, value); rawKey = tbinput.readRaw(); } } finally { writer.close(); } return 0; } LoadTypedBytes(Configuration conf); LoadTypedBytes(); Configuration getConf(); void setConf(Configuration conf); int run(String[] args); static void main(String[] args); }### Answer: @Test public void testLoading() throws Exception { Configuration conf = new Configuration(); MiniDFSCluster cluster = new MiniDFSCluster(conf, 2, true, null); FileSystem fs = cluster.getFileSystem(); ByteArrayOutputStream out = new ByteArrayOutputStream(); TypedBytesOutput tboutput = new TypedBytesOutput(new DataOutputStream(out)); for (int i = 0; i < 100; i++) { tboutput.write(new Long(i)); tboutput.write("" + (10 * i)); } InputStream isBackup = System.in; ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); System.setIn(in); LoadTypedBytes loadtb = new LoadTypedBytes(conf); try { Path root = new Path("/typedbytestest"); assertTrue(fs.mkdirs(root)); assertTrue(fs.exists(root)); String[] args = new String[1]; args[0] = "/typedbytestest/test.seq"; int ret = loadtb.run(args); assertEquals("Return value != 0.", 0, ret); Path file = new Path(root, "test.seq"); assertTrue(fs.exists(file)); SequenceFile.Reader reader = new SequenceFile.Reader(fs, file, conf); int counter = 0; TypedBytesWritable key = new TypedBytesWritable(); TypedBytesWritable value = new TypedBytesWritable(); while (reader.next(key, value)) { assertEquals(Long.class, key.getValue().getClass()); assertEquals(String.class, value.getValue().getClass()); assertTrue("Invalid record.", Integer.parseInt(value.toString()) % 10 == 0); counter++; } assertEquals("Wrong number of records.", 100, counter); } finally { try { fs.close(); } catch (Exception e) { } System.setIn(isBackup); cluster.shutdown(); } }
### Question: DumpTypedBytes implements Tool { public int run(String[] args) throws Exception { if (args.length == 0) { System.err.println("Too few arguments!"); printUsage(); return 1; } Path pattern = new Path(args[0]); FileSystem fs = pattern.getFileSystem(getConf()); fs.setVerifyChecksum(true); for (Path p : FileUtil.stat2Paths(fs.globStatus(pattern), pattern)) { List<FileStatus> inputFiles = new ArrayList<FileStatus>(); FileStatus status = fs.getFileStatus(p); if (status.isDirectory()) { FileStatus[] files = fs.listStatus(p); Collections.addAll(inputFiles, files); } else { inputFiles.add(status); } return dumpTypedBytes(inputFiles); } return -1; } DumpTypedBytes(Configuration conf); DumpTypedBytes(); Configuration getConf(); void setConf(Configuration conf); int run(String[] args); static void main(String[] args); }### Answer: @Test public void testDumping() throws Exception { Configuration conf = new Configuration(); MiniDFSCluster cluster = new MiniDFSCluster(conf, 2, true, null); FileSystem fs = cluster.getFileSystem(); PrintStream psBackup = System.out; ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream psOut = new PrintStream(out); System.setOut(psOut); DumpTypedBytes dumptb = new DumpTypedBytes(conf); try { Path root = new Path("/typedbytestest"); assertTrue(fs.mkdirs(root)); assertTrue(fs.exists(root)); OutputStreamWriter writer = new OutputStreamWriter(fs.create(new Path( root, "test.txt"))); try { for (int i = 0; i < 100; i++) { writer.write("" + (10 * i) + "\n"); } } finally { writer.close(); } String[] args = new String[1]; args[0] = "/typedbytestest"; int ret = dumptb.run(args); assertEquals("Return value != 0.", 0, ret); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); TypedBytesInput tbinput = new TypedBytesInput(new DataInputStream(in)); int counter = 0; Object key = tbinput.read(); while (key != null) { assertEquals(Long.class, key.getClass()); Object value = tbinput.read(); assertEquals(String.class, value.getClass()); assertTrue("Invalid output.", Integer.parseInt(value.toString()) % 10 == 0); counter++; key = tbinput.read(); } assertEquals("Wrong number of outputs.", 100, counter); } finally { try { fs.close(); } catch (Exception e) { } System.setOut(psBackup); cluster.shutdown(); } }
### Question: DistCpUtils { public static void preserve(FileSystem targetFS, Path path, FileStatus srcFileStatus, EnumSet<FileAttribute> attributes) throws IOException { FileStatus targetFileStatus = targetFS.getFileStatus(path); String group = targetFileStatus.getGroup(); String user = targetFileStatus.getOwner(); boolean chown = false; if (attributes.contains(FileAttribute.PERMISSION) && !srcFileStatus.getPermission().equals(targetFileStatus.getPermission())) { targetFS.setPermission(path, srcFileStatus.getPermission()); } if (attributes.contains(FileAttribute.REPLICATION) && ! targetFileStatus.isDirectory() && srcFileStatus.getReplication() != targetFileStatus.getReplication()) { targetFS.setReplication(path, srcFileStatus.getReplication()); } if (attributes.contains(FileAttribute.GROUP) && !group.equals(srcFileStatus.getGroup())) { group = srcFileStatus.getGroup(); chown = true; } if (attributes.contains(FileAttribute.USER) && !user.equals(srcFileStatus.getOwner())) { user = srcFileStatus.getOwner(); chown = true; } if (chown) { targetFS.setOwner(path, user, group); } } static long getFileSize(Path path, Configuration configuration); static void publish(Configuration configuration, String label, T value); static int getInt(Configuration configuration, String label); static long getLong(Configuration configuration, String label); static Class<? extends InputFormat> getStrategy(Configuration conf, DistCpOptions options); static String getRelativePath(Path sourceRootPath, Path childPath); static String packAttributes(EnumSet<FileAttribute> attributes); static EnumSet<FileAttribute> unpackAttributes(String attributes); static void preserve(FileSystem targetFS, Path path, FileStatus srcFileStatus, EnumSet<FileAttribute> attributes); static Path sortListing(FileSystem fs, Configuration conf, Path sourceListing); static DecimalFormat getFormatter(); static String getStringDescriptionFor(long nBytes); static boolean checksumsAreEqual(FileSystem sourceFS, Path source, FileSystem targetFS, Path target); static boolean compareFs(FileSystem srcFs, FileSystem destFs); }### Answer: @Test public void testPreserve() { try { FileSystem fs = FileSystem.get(config); EnumSet<FileAttribute> attributes = EnumSet.noneOf(FileAttribute.class); Path path = new Path("/tmp/abc"); Path src = new Path("/tmp/src"); fs.mkdirs(path); fs.mkdirs(src); FileStatus srcStatus = fs.getFileStatus(src); FsPermission noPerm = new FsPermission((short) 0); fs.setPermission(path, noPerm); fs.setOwner(path, "nobody", "nobody"); DistCpUtils.preserve(fs, path, srcStatus, attributes); FileStatus target = fs.getFileStatus(path); Assert.assertEquals(target.getPermission(), noPerm); Assert.assertEquals(target.getOwner(), "nobody"); Assert.assertEquals(target.getGroup(), "nobody"); attributes.add(FileAttribute.PERMISSION); DistCpUtils.preserve(fs, path, srcStatus, attributes); target = fs.getFileStatus(path); Assert.assertEquals(target.getPermission(), srcStatus.getPermission()); Assert.assertEquals(target.getOwner(), "nobody"); Assert.assertEquals(target.getGroup(), "nobody"); attributes.add(FileAttribute.GROUP); attributes.add(FileAttribute.USER); DistCpUtils.preserve(fs, path, srcStatus, attributes); target = fs.getFileStatus(path); Assert.assertEquals(target.getPermission(), srcStatus.getPermission()); Assert.assertEquals(target.getOwner(), srcStatus.getOwner()); Assert.assertEquals(target.getGroup(), srcStatus.getGroup()); fs.delete(path, true); fs.delete(src, true); } catch (IOException e) { LOG.error("Exception encountered ", e); Assert.fail("Preserve test failure"); } }
### Question: ThrottledInputStream extends InputStream { @Override public int read() throws IOException { throttle(); int data = rawStream.read(); if (data != -1) { bytesRead++; } return data; } ThrottledInputStream(InputStream rawStream); ThrottledInputStream(InputStream rawStream, long maxBytesPerSec); @Override int read(); @Override int read(byte[] b); @Override int read(byte[] b, int off, int len); long getTotalBytesRead(); long getBytesPerSec(); long getTotalSleepTime(); @Override String toString(); }### Answer: @Test public void testRead() { File tmpFile; File outFile; try { tmpFile = createFile(1024); outFile = createFile(); tmpFile.deleteOnExit(); outFile.deleteOnExit(); long maxBandwidth = copyAndAssert(tmpFile, outFile, 0, 1, -1, CB.BUFFER); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.BUFFER); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.BUFF_OFFSET); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.ONE_C); } catch (IOException e) { LOG.error("Exception encountered ", e); } }
### Question: ResourceCalculatorProcessTree extends Configured { public static ResourceCalculatorProcessTree getResourceCalculatorProcessTree( String pid, Class<? extends ResourceCalculatorProcessTree> clazz, Configuration conf) { if (clazz != null) { try { Constructor <? extends ResourceCalculatorProcessTree> c = clazz.getConstructor(String.class); ResourceCalculatorProcessTree rctree = c.newInstance(pid); rctree.setConf(conf); return rctree; } catch(Exception e) { throw new RuntimeException(e); } } try { String osName = System.getProperty("os.name"); if (osName.startsWith("Linux")) { return new ProcfsBasedProcessTree(pid); } } catch (SecurityException se) { return null; } return null; } ResourceCalculatorProcessTree(String root); abstract void updateProcessTree(); abstract String getProcessTreeDump(); long getCumulativeVmem(); long getCumulativeRssmem(); abstract long getCumulativeVmem(int olderThanAge); abstract long getCumulativeRssmem(int olderThanAge); abstract long getCumulativeCpuTime(); abstract boolean checkPidPgrpidForMatch(); static ResourceCalculatorProcessTree getResourceCalculatorProcessTree( String pid, Class<? extends ResourceCalculatorProcessTree> clazz, Configuration conf); }### Answer: @Test public void testCreateInstance() { ResourceCalculatorProcessTree tree; tree = ResourceCalculatorProcessTree.getResourceCalculatorProcessTree("1", EmptyProcessTree.class, new Configuration()); assertNotNull(tree); assertThat(tree, instanceOf(EmptyProcessTree.class)); } @Test public void testCreatedInstanceConfigured() { ResourceCalculatorProcessTree tree; Configuration conf = new Configuration(); tree = ResourceCalculatorProcessTree.getResourceCalculatorProcessTree("1", EmptyProcessTree.class, conf); assertNotNull(tree); assertThat(tree.getConf(), sameInstance(conf)); }
### Question: ProcfsBasedProcessTree extends ResourceCalculatorProcessTree { @Override public boolean checkPidPgrpidForMatch() { return checkPidPgrpidForMatch(pid, PROCFS); } ProcfsBasedProcessTree(String pid); ProcfsBasedProcessTree(String pid, String procfsDir); static boolean isAvailable(); @Override void updateProcessTree(); @Override boolean checkPidPgrpidForMatch(); static boolean checkPidPgrpidForMatch(String _pid, String procfs); List<String> getCurrentProcessIDs(); @Override String getProcessTreeDump(); @Override long getCumulativeVmem(int olderThanAge); @Override long getCumulativeRssmem(int olderThanAge); @Override long getCumulativeCpuTime(); @Override String toString(); static final String PROCFS_STAT_FILE; static final String PROCFS_CMDLINE_FILE; static final long PAGE_SIZE; static final long JIFFY_LENGTH_IN_MILLIS; }### Answer: @Test public void testDestroyProcessTree() throws IOException { String pid = "100"; File procfsRootDir = new File(TEST_ROOT_DIR, "proc"); try { setupProcfsRootDir(procfsRootDir); createProcessTree(pid, procfsRootDir.getAbsolutePath()); Assert.assertTrue(ProcfsBasedProcessTree.checkPidPgrpidForMatch( pid, procfsRootDir.getAbsolutePath())); } finally { FileUtil.fullyDelete(procfsRootDir); } }
### Question: ConverterUtils { public static String toString(ApplicationId appId) { return appId.toString(); } static Path getPathFromYarnURL(URL url); static Map<String, String> convertToString( Map<CharSequence, CharSequence> env); static URL getYarnUrlFromPath(Path path); static URL getYarnUrlFromURI(URI uri); static String toString(ApplicationId appId); static ApplicationId toApplicationId(RecordFactory recordFactory, String appIdStr); static String toString(ContainerId cId); static NodeId toNodeId(String nodeIdStr); static ContainerId toContainerId(String containerIdStr); static ApplicationAttemptId toApplicationAttemptId( String applicationAttmeptIdStr); static ApplicationId toApplicationId( String appIdStr); static final String APPLICATION_PREFIX; static final String CONTAINER_PREFIX; static final String APPLICATION_ATTEMPT_PREFIX; }### Answer: @Test public void testContainerIdNull() throws URISyntaxException { assertNull(ConverterUtils.toString((ContainerId)null)); }
### Question: ApplicationClassLoader extends URLClassLoader { @VisibleForTesting static URL[] constructUrlsFromClasspath(String classpath) throws MalformedURLException { List<URL> urls = new ArrayList<URL>(); for (String element : Splitter.on(File.pathSeparator).split(classpath)) { if (element.endsWith("/*")) { String dir = element.substring(0, element.length() - 1); File[] files = new File(dir).listFiles(JAR_FILENAME_FILTER); if (files != null) { for (File file : files) { urls.add(file.toURI().toURL()); } } } else { File file = new File(element); if (file.exists()) { urls.add(new File(element).toURI().toURL()); } } } return urls.toArray(new URL[urls.size()]); } ApplicationClassLoader(URL[] urls, ClassLoader parent, List<String> systemClasses); ApplicationClassLoader(String classpath, ClassLoader parent, List<String> systemClasses); @Override URL getResource(String name); @Override Class<?> loadClass(String name); }### Answer: @Test public void testConstructUrlsFromClasspath() throws Exception { File file = new File(testDir, "file"); assertTrue("Create file", file.createNewFile()); File dir = new File(testDir, "dir"); assertTrue("Make dir", dir.mkdir()); File jarsDir = new File(testDir, "jarsdir"); assertTrue("Make jarsDir", jarsDir.mkdir()); File nonJarFile = new File(jarsDir, "nonjar"); assertTrue("Create non-jar file", nonJarFile.createNewFile()); File jarFile = new File(jarsDir, "a.jar"); assertTrue("Create jar file", jarFile.createNewFile()); File nofile = new File(testDir, "nofile"); StringBuilder cp = new StringBuilder(); cp.append(file.getAbsolutePath()).append(File.pathSeparator) .append(dir.getAbsolutePath()).append(File.pathSeparator) .append(jarsDir.getAbsolutePath() + "/*").append(File.pathSeparator) .append(nofile.getAbsolutePath()).append(File.pathSeparator) .append(nofile.getAbsolutePath() + "/*").append(File.pathSeparator); URL[] urls = constructUrlsFromClasspath(cp.toString()); assertEquals(3, urls.length); assertEquals(file.toURI().toURL(), urls[0]); assertEquals(dir.toURI().toURL(), urls[1]); assertEquals(jarFile.toURI().toURL(), urls[2]); }
### Question: ApplicationClassLoader extends URLClassLoader { @VisibleForTesting static boolean isSystemClass(String name, List<String> systemClasses) { if (systemClasses != null) { String canonicalName = name.replace('/', '.'); while (canonicalName.startsWith(".")) { canonicalName=canonicalName.substring(1); } for (String c : systemClasses) { boolean result = true; if (c.startsWith("-")) { c = c.substring(1); result = false; } if (c.endsWith(".") && canonicalName.startsWith(c)) { return result; } else if (canonicalName.equals(c)) { return result; } } } return false; } ApplicationClassLoader(URL[] urls, ClassLoader parent, List<String> systemClasses); ApplicationClassLoader(String classpath, ClassLoader parent, List<String> systemClasses); @Override URL getResource(String name); @Override Class<?> loadClass(String name); }### Answer: @Test public void testIsSystemClass() { assertFalse(isSystemClass("org.example.Foo", null)); assertTrue(isSystemClass("org.example.Foo", classes("org.example.Foo"))); assertTrue(isSystemClass("/org.example.Foo", classes("org.example.Foo"))); assertTrue(isSystemClass("org.example.Foo", classes("org.example."))); assertTrue(isSystemClass("net.example.Foo", classes("org.example.,net.example."))); assertFalse(isSystemClass("org.example.Foo", classes("-org.example.Foo,org.example."))); assertTrue(isSystemClass("org.example.Bar", classes("-org.example.Foo.,org.example."))); }
### Question: ApplicationClassLoader extends URLClassLoader { @Override public URL getResource(String name) { URL url = null; if (!isSystemClass(name, systemClasses)) { url= findResource(name); if (url == null && name.startsWith("/")) { if (LOG.isDebugEnabled()) { LOG.debug("Remove leading / off " + name); } url= findResource(name.substring(1)); } } if (url == null) { url= parent.getResource(name); } if (url != null) { if (LOG.isDebugEnabled()) { LOG.debug("getResource("+name+")=" + url); } } return url; } ApplicationClassLoader(URL[] urls, ClassLoader parent, List<String> systemClasses); ApplicationClassLoader(String classpath, ClassLoader parent, List<String> systemClasses); @Override URL getResource(String name); @Override Class<?> loadClass(String name); }### Answer: @Test public void testGetResource() throws IOException { URL testJar = makeTestJar().toURI().toURL(); ClassLoader currentClassLoader = getClass().getClassLoader(); ClassLoader appClassloader = new ApplicationClassLoader( new URL[] { testJar }, currentClassLoader, null); assertNull("Resource should be null for current classloader", currentClassLoader.getResourceAsStream("resource.txt")); InputStream in = appClassloader.getResourceAsStream("resource.txt"); assertNotNull("Resource should not be null for app classloader", in); assertEquals("hello", IOUtils.toString(in)); }
### Question: HFileArchiveUtil { public static Path getTableArchivePath(Path tabledir) { Path root = tabledir.getParent(); return getTableArchivePath(root, tabledir.getName()); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final String tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegion region, byte [] family); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Configuration conf, Path tabledir, Path regiondir); static Path getRegionArchiveDir(Path rootdir, Path tabledir, Path regiondir); static Path getTableArchivePath(Path tabledir); static Path getTableArchivePath(final Path rootdir, final String tableName); static Path getTableArchivePath(final Configuration conf, final String tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testGetTableArchivePath() { assertNotNull(HFileArchiveUtil.getTableArchivePath(new Path("table"))); assertNotNull(HFileArchiveUtil.getTableArchivePath(new Path("root", new Path("table")))); }
### Question: WebApp extends ServletModule { public void stop() { try { checkNotNull(httpServer, "httpServer").stop(); checkNotNull(guiceFilter, "guiceFilter").destroy(); } catch (Exception e) { throw new WebAppException(e); } } @Provides HttpServer httpServer(); InetSocketAddress getListenerAddress(); int port(); void stop(); void joinThread(); @Provides Configuration conf(); String name(); String[] getServePathSpecs(); String getRedirectPath(); @Override void configureServlets(); void route(HTTP method, String pathSpec, Class<? extends Controller> cls, String action); void route(String pathSpec, Class<? extends Controller> cls, String action); void route(String pathSpec, Class<? extends Controller> cls); abstract void setup(); }### Answer: @Test public void testCreate() { WebApp app = WebApps.$for(this).start(); app.stop(); } @Test public void testDefaultRoutes() throws Exception { WebApp app = WebApps.$for("test", this).start(); String baseUrl = baseUrl(app); try { assertEquals("foo", getContent(baseUrl +"test/foo").trim()); assertEquals("foo", getContent(baseUrl +"test/foo/index").trim()); assertEquals("bar", getContent(baseUrl +"test/foo/bar").trim()); assertEquals("default", getContent(baseUrl +"test").trim()); assertEquals("default", getContent(baseUrl +"test/").trim()); assertEquals("default", getContent(baseUrl).trim()); } finally { app.stop(); } }
### Question: ServiceOperations { public static void init(Service service, Configuration configuration) { Service.STATE state = service.getServiceState(); ensureCurrentState(state, Service.STATE.NOTINITED); service.init(configuration); } private ServiceOperations(); static void ensureCurrentState(Service.STATE state, Service.STATE expectedState); static void init(Service service, Configuration configuration); static void start(Service service); static void deploy(Service service, Configuration configuration); static void stop(Service service); static Exception stopQuietly(Service service); }### Answer: @Test public void testInitTwice() throws Throwable { BreakableService svc = new BreakableService(); Configuration conf = new Configuration(); conf.set("test.init", "t"); ServiceOperations.init(svc, conf); try { ServiceOperations.init(svc, new Configuration()); fail("Expected a failure, got " + svc); } catch (IllegalStateException e) { } assertStateCount(svc, Service.STATE.INITED, 1); assertServiceConfigurationContains(svc, "test.init"); }
### Question: ServiceOperations { public static void deploy(Service service, Configuration configuration) { init(service, configuration); start(service); } private ServiceOperations(); static void ensureCurrentState(Service.STATE state, Service.STATE expectedState); static void init(Service service, Configuration configuration); static void start(Service service); static void deploy(Service service, Configuration configuration); static void stop(Service service); static Exception stopQuietly(Service service); }### Answer: @Test public void testDeploy() throws Throwable { BreakableService svc = new BreakableService(); assertServiceStateCreated(svc); ServiceOperations.deploy(svc, new Configuration()); assertServiceStateStarted(svc); assertStateCount(svc, Service.STATE.INITED, 1); assertStateCount(svc, Service.STATE.STARTED, 1); ServiceOperations.stop(svc); assertServiceStateStopped(svc); assertStateCount(svc, Service.STATE.STOPPED, 1); } @Test public void testDeployNotAtomic() throws Throwable { BreakableService svc = new BreakableService(false, true, false); try { ServiceOperations.deploy(svc, new Configuration()); fail("Expected a failure, got " + svc); } catch (BreakableService.BrokenLifecycleEvent expected) { } assertServiceStateInited(svc); assertStateCount(svc, Service.STATE.INITED, 1); assertStateCount(svc, Service.STATE.STARTED, 1); try { ServiceOperations.deploy(svc, new Configuration()); fail("Expected a failure, got " + svc); } catch (IllegalStateException e) { } }
### Question: ServiceOperations { public static void stop(Service service) { if (service != null) { Service.STATE state = service.getServiceState(); if (state == Service.STATE.STARTED) { service.stop(); } } } private ServiceOperations(); static void ensureCurrentState(Service.STATE state, Service.STATE expectedState); static void init(Service service, Configuration configuration); static void start(Service service); static void deploy(Service service, Configuration configuration); static void stop(Service service); static Exception stopQuietly(Service service); }### Answer: @Test public void testStopInit() throws Throwable { BreakableService svc = new BreakableService(); ServiceOperations.stop(svc); assertServiceStateCreated(svc); assertStateCount(svc, Service.STATE.STOPPED, 0); ServiceOperations.stop(svc); assertStateCount(svc, Service.STATE.STOPPED, 0); }
### Question: HFileArchiveUtil { public static Path getArchivePath(Configuration conf) throws IOException { return getArchivePath(FSUtils.getRootDir(conf)); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final String tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegion region, byte [] family); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Configuration conf, Path tabledir, Path regiondir); static Path getRegionArchiveDir(Path rootdir, Path tabledir, Path regiondir); static Path getTableArchivePath(Path tabledir); static Path getTableArchivePath(final Path rootdir, final String tableName); static Path getTableArchivePath(final Configuration conf, final String tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testGetArchivePath() throws Exception { Configuration conf = new Configuration(); FSUtils.setRootDir(conf, new Path("root")); assertNotNull(HFileArchiveUtil.getArchivePath(conf)); }
### Question: LinuxContainerExecutor extends ContainerExecutor { @Override public boolean signalContainer(String user, String pid, Signal signal) throws IOException { String[] command = new String[] { containerExecutorExe, user, Integer.toString(Commands.SIGNAL_CONTAINER.getValue()), pid, Integer.toString(signal.getValue()) }; ShellCommandExecutor shExec = new ShellCommandExecutor(command); if (LOG.isDebugEnabled()) { LOG.debug("signalContainer: " + Arrays.toString(command)); } try { shExec.execute(); } catch (ExitCodeException e) { int ret_code = shExec.getExitCode(); if (ret_code == ResultCode.INVALID_CONTAINER_PID.getValue()) { return false; } logOutput(shExec.getOutput()); throw new IOException("Problem signalling container " + pid + " with " + signal + "; exit = " + ret_code); } return true; } @Override void setConf(Configuration conf); @Override void init(); @Override void startLocalizer(Path nmPrivateContainerTokensPath, InetSocketAddress nmAddr, String user, String appId, String locId, List<String> localDirs, List<String> logDirs); @Override int launchContainer(Container container, Path nmPrivateCotainerScriptPath, Path nmPrivateTokensPath, String user, String appId, Path containerWorkDir, List<String> localDirs, List<String> logDirs); @Override boolean signalContainer(String user, String pid, Signal signal); @Override void deleteAsUser(String user, Path dir, Path... baseDirs); }### Answer: @Test public void testContainerKill() throws Exception { if (!shouldRun()) { return; } final ContainerId sleepId = getNextContainerId(); Thread t = new Thread() { public void run() { try { runAndBlock(sleepId, "sleep", "100"); } catch (IOException e) { LOG.warn("Caught exception while running sleep",e); } }; }; t.setDaemon(true); t.start(); assertTrue(t.isAlive()); String pid = null; int count = 10; while ((pid = exec.getProcessId(sleepId)) == null && count > 0) { LOG.info("Sleeping for 200 ms before checking for pid "); Thread.sleep(200); count--; } assertNotNull(pid); LOG.info("Going to killing the process."); exec.signalContainer(appSubmitter, pid, Signal.TERM); LOG.info("sleeping for 100ms to let the sleep be killed"); Thread.sleep(100); assertFalse(t.isAlive()); }
### Question: ProcessIdFileReader { public static String getProcessId(Path path) throws IOException { if (path == null) { throw new IOException("Trying to access process id from a null path"); } LOG.debug("Accessing pid from pid file " + path); String processId = null; FileReader fileReader = null; BufferedReader bufReader = null; try { File file = new File(path.toString()); if (file.exists()) { fileReader = new FileReader(file); bufReader = new BufferedReader(fileReader); while (true) { String line = bufReader.readLine(); if (line == null) { break; } String temp = line.trim(); if (!temp.isEmpty()) { try { Long pid = Long.valueOf(temp); if (pid > 0) { processId = temp; break; } } catch (Exception e) { } } } } } finally { if (fileReader != null) { fileReader.close(); } if (bufReader != null) { bufReader.close(); } } LOG.debug("Got pid " + (processId != null? processId : "null") + " from path " + path); return processId; } static String getProcessId(Path path); }### Answer: @Test public void testNullPath() { String pid = null; try { pid = ProcessIdFileReader.getProcessId(null); fail("Expected an error to be thrown for null path"); } catch (Exception e) { } assert(pid == null); } @Test public void testSimpleGet() throws IOException { String rootDir = new File(System.getProperty( "test.build.data", "/tmp")).getAbsolutePath(); File testFile = null; try { testFile = new File(rootDir, "temp.txt"); PrintWriter fileWriter = new PrintWriter(testFile); fileWriter.println("56789"); fileWriter.close(); String processId = null; processId = ProcessIdFileReader.getProcessId( new Path(rootDir + Path.SEPARATOR + "temp.txt")); Assert.assertEquals("56789", processId); } finally { if (testFile != null && testFile.exists()) { testFile.delete(); } } } @Test public void testComplexGet() throws IOException { String rootDir = new File(System.getProperty( "test.build.data", "/tmp")).getAbsolutePath(); File testFile = null; try { testFile = new File(rootDir, "temp.txt"); PrintWriter fileWriter = new PrintWriter(testFile); fileWriter.println(" "); fileWriter.println(""); fileWriter.println("abc"); fileWriter.println("-123"); fileWriter.println("-123 "); fileWriter.println(" 23 "); fileWriter.println("6236"); fileWriter.close(); String processId = null; processId = ProcessIdFileReader.getProcessId( new Path(rootDir + Path.SEPARATOR + "temp.txt")); Assert.assertEquals("23", processId); } finally { if (testFile != null && testFile.exists()) { testFile.delete(); } } }
### Question: HFileArchiveUtil { public static Path getRegionArchiveDir(Configuration conf, Path tabledir, Path regiondir) { Path archiveDir = getTableArchivePath(tabledir); String encodedRegionName = regiondir.getName(); return HRegion.getRegionDir(archiveDir, encodedRegionName); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final String tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegion region, byte [] family); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Configuration conf, Path tabledir, Path regiondir); static Path getRegionArchiveDir(Path rootdir, Path tabledir, Path regiondir); static Path getTableArchivePath(Path tabledir); static Path getTableArchivePath(final Path rootdir, final String tableName); static Path getTableArchivePath(final Configuration conf, final String tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testRegionArchiveDir() { Configuration conf = null; Path tableDir = new Path("table"); Path regionDir = new Path("region"); assertNotNull(HFileArchiveUtil.getRegionArchiveDir(conf, tableDir, regionDir)); }
### Question: NMAuditLogger { static void start(Keys key, String value, StringBuilder b) { b.append(key.name()).append(AuditConstants.KEY_VAL_SEPARATOR).append(value); } static void logSuccess(String user, String operation, String target, ApplicationId appId, ContainerId containerId); static void logSuccess(String user, String operation, String target); static void logFailure(String user, String operation, String target, String description, ApplicationId appId, ContainerId containerId); static void logFailure(String user, String operation, String target, String description); }### Answer: @Test public void testNMAuditLoggerWithIP() throws Exception { Configuration conf = new Configuration(); Server server = RPC.getServer(TestProtocol.class, new MyTestRPCServer(), "0.0.0.0", 0, 5, true, conf, null); server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); TestProtocol proxy = (TestProtocol)RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); proxy.ping(); server.stop(); } @Test public void testNMAuditLoggerWithIP() throws Exception { Configuration conf = new Configuration(); Server server = RPC.getServer(new MyTestRPCServer(), "0.0.0.0", 0, conf); server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); TestProtocol proxy = (TestProtocol)RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); proxy.ping(); server.stop(); } @Test public void testNMAuditLoggerWithIP() throws Exception { Configuration conf = new Configuration(); RPC.setProtocolEngine(conf, TestRpcService.class, ProtobufRpcEngine.class); MyTestRPCServer serverImpl = new MyTestRPCServer(); BlockingService service = TestRpcServiceProtos.TestProtobufRpcProto .newReflectiveBlockingService(serverImpl); Server server = new RPC.Builder(conf) .setProtocol(TestRpcBase.TestRpcService.class) .setInstance(service).setBindAddress("0.0.0.0") .setPort(0).setNumHandlers(5).setVerbose(true).build(); server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); TestRpcService proxy = RPC.getProxy(TestRpcService.class, TestProtocol.versionID, addr, conf); TestProtos.EmptyRequestProto pingRequest = TestProtos.EmptyRequestProto.newBuilder().build(); proxy.ping(null, pingRequest); server.stop(); RPC.stopProxy(proxy); }
### Question: NodeManager extends CompositeService implements ServiceStateChangeListener { @Override public void init(Configuration conf) { conf.setBoolean(Dispatcher.DISPATCHER_EXIT_ON_ERROR_KEY, true); NMContainerTokenSecretManager containerTokenSecretManager = null; if (UserGroupInformation.isSecurityEnabled()) { LOG.info("Security is enabled on NodeManager. " + "Creating ContainerTokenSecretManager"); containerTokenSecretManager = new NMContainerTokenSecretManager(conf); } this.context = new NMContext(containerTokenSecretManager); this.aclsManager = new ApplicationACLsManager(conf); ContainerExecutor exec = ReflectionUtils.newInstance( conf.getClass(YarnConfiguration.NM_CONTAINER_EXECUTOR, DefaultContainerExecutor.class, ContainerExecutor.class), conf); try { exec.init(); } catch (IOException e) { throw new YarnException("Failed to initialize container executor", e); } DeletionService del = new DeletionService(exec); addService(del); this.dispatcher = new AsyncDispatcher(); nodeHealthChecker = new NodeHealthCheckerService(); addService(nodeHealthChecker); dirsHandler = nodeHealthChecker.getDiskHandler(); NodeStatusUpdater nodeStatusUpdater = createNodeStatusUpdater(context, dispatcher, nodeHealthChecker); nodeStatusUpdater.register(this); NodeResourceMonitor nodeResourceMonitor = createNodeResourceMonitor(); addService(nodeResourceMonitor); containerManager = createContainerManager(context, exec, del, nodeStatusUpdater, this.aclsManager, dirsHandler); addService(containerManager); Service webServer = createWebServer(context, containerManager .getContainersMonitor(), this.aclsManager, dirsHandler); addService(webServer); dispatcher.register(ContainerManagerEventType.class, containerManager); addService(dispatcher); DefaultMetricsSystem.initialize("NodeManager"); addService(nodeStatusUpdater); waitForContainersOnShutdownMillis = conf.getLong(YarnConfiguration.NM_SLEEP_DELAY_BEFORE_SIGKILL_MS, YarnConfiguration.DEFAULT_NM_SLEEP_DELAY_BEFORE_SIGKILL_MS) + conf.getLong(YarnConfiguration.NM_PROCESS_KILL_WAIT_MS, YarnConfiguration.DEFAULT_NM_PROCESS_KILL_WAIT_MS) + SHUTDOWN_CLEANUP_SLOP_MS; super.init(conf); } NodeManager(); @Override void init(Configuration conf); @Override void start(); @Override void stop(); NodeHealthCheckerService getNodeHealthChecker(); @Override void stateChanged(Service service); static void main(String[] args); static final int SHUTDOWN_HOOK_PRIORITY; }### Answer: @Test public void testContainerExecutorInitCall() { NodeManager nm = new NodeManager(); YarnConfiguration conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.NM_CONTAINER_EXECUTOR, InvalidContainerExecutor.class, ContainerExecutor.class); try { nm.init(conf); fail("Init should fail"); } catch (YarnException e) { assert(e.getCause().getMessage().contains("dummy executor init called")); } }
### Question: DirectoryCollection { synchronized boolean createNonExistentDirs(FileContext localFs, FsPermission perm) { boolean failed = false; for (final String dir : localDirs) { try { createDir(localFs, new Path(dir), perm); } catch (IOException e) { LOG.warn("Unable to create directory " + dir + " error " + e.getMessage() + ", removing from the list of valid directories."); localDirs.remove(dir); failedDirs.add(dir); numFailures++; failed = true; } } return !failed; } DirectoryCollection(String[] dirs); }### Answer: @Test public void testCreateDirectories() throws IOException { Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077"); FileContext localFs = FileContext.getLocalFSFileContext(conf); String dirA = new File(testDir, "dirA").getPath(); String dirB = new File(dirA, "dirB").getPath(); String dirC = new File(testDir, "dirC").getPath(); Path pathC = new Path(dirC); FsPermission permDirC = new FsPermission((short)0710); localFs.mkdir(pathC, null, true); localFs.setPermission(pathC, permDirC); String[] dirs = { dirA, dirB, dirC }; DirectoryCollection dc = new DirectoryCollection(dirs); FsPermission defaultPerm = FsPermission.getDefault() .applyUMask(new FsPermission((short)FsPermission.DEFAULT_UMASK)); boolean createResult = dc.createNonExistentDirs(localFs, defaultPerm); Assert.assertTrue(createResult); FileStatus status = localFs.getFileStatus(new Path(dirA)); Assert.assertEquals("local dir parent not created with proper permissions", defaultPerm, status.getPermission()); status = localFs.getFileStatus(new Path(dirB)); Assert.assertEquals("local dir not created with proper permissions", defaultPerm, status.getPermission()); status = localFs.getFileStatus(pathC); Assert.assertEquals("existing local directory permissions modified", permDirC, status.getPermission()); }
### Question: LocalDirsHandlerService extends AbstractService { @Override public void init(Configuration config) { Configuration conf = new Configuration(config); diskHealthCheckInterval = conf.getLong( YarnConfiguration.NM_DISK_HEALTH_CHECK_INTERVAL_MS, YarnConfiguration.DEFAULT_NM_DISK_HEALTH_CHECK_INTERVAL_MS); monitoringTimerTask = new MonitoringTimerTask(conf); isDiskHealthCheckerEnabled = conf.getBoolean( YarnConfiguration.NM_DISK_HEALTH_CHECK_ENABLE, true); minNeededHealthyDisksFactor = conf.getFloat( YarnConfiguration.NM_MIN_HEALTHY_DISKS_FRACTION, YarnConfiguration.DEFAULT_NM_MIN_HEALTHY_DISKS_FRACTION); lastDisksCheckTime = System.currentTimeMillis(); super.init(conf); FileContext localFs; try { localFs = FileContext.getLocalFSFileContext(config); } catch (IOException e) { throw new YarnException("Unable to get the local filesystem", e); } FsPermission perm = new FsPermission((short)0755); boolean createSucceeded = localDirs.createNonExistentDirs(localFs, perm); createSucceeded &= logDirs.createNonExistentDirs(localFs, perm); if (!createSucceeded) { updateDirsAfterFailure(); } checkDirs(); } LocalDirsHandlerService(); @Override void init(Configuration config); @Override void start(); @Override void stop(); List<String> getLocalDirs(); List<String> getLogDirs(); String getDisksHealthReport(); boolean areDisksHealthy(); long getLastDisksCheckTime(); Path getLocalPathForWrite(String pathStr); Path getLocalPathForWrite(String pathStr, long size, boolean checkWrite); Path getLogPathForWrite(String pathStr, boolean checkWrite); Path getLogPathToRead(String pathStr); static String[] validatePaths(String[] paths); }### Answer: @Test public void testValidPathsDirHandlerService() { Configuration conf = new YarnConfiguration(); String localDir1 = new File("file: String localDir2 = new File("hdfs: conf.set(YarnConfiguration.NM_LOCAL_DIRS, localDir1 + "," + localDir2); String logDir1 = new File("file: conf.set(YarnConfiguration.NM_LOG_DIRS, logDir1); LocalDirsHandlerService dirSvc = new LocalDirsHandlerService(); try { dirSvc.init(conf); Assert.fail("Service should have thrown an exception due to wrong URI"); } catch (YarnException e) { } Assert.assertTrue("Service should not be inited", dirSvc.getServiceState() .compareTo(STATE.NOTINITED) == 0); }
### Question: NonAggregatingLogHandler extends AbstractService implements LogHandler { @Override public void stop() { if (sched != null) { sched.shutdown(); boolean isShutdown = false; try { isShutdown = sched.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { sched.shutdownNow(); isShutdown = true; } if (!isShutdown) { sched.shutdownNow(); } } super.stop(); } NonAggregatingLogHandler(Dispatcher dispatcher, DeletionService delService, LocalDirsHandlerService dirsHandler); @Override void init(Configuration conf); @Override void stop(); @SuppressWarnings("unchecked") @Override void handle(LogHandlerEvent event); }### Answer: @Test public void testStop() throws Exception { NonAggregatingLogHandler aggregatingLogHandler = new NonAggregatingLogHandler(null, null, null); aggregatingLogHandler.stop(); NonAggregatingLogHandlerWithMockExecutor logHandler = new NonAggregatingLogHandlerWithMockExecutor(null, null, null); logHandler.init(new Configuration()); logHandler.stop(); verify(logHandler.mockSched).shutdown(); verify(logHandler.mockSched) .awaitTermination(eq(10l), eq(TimeUnit.SECONDS)); verify(logHandler.mockSched).shutdownNow(); }
### Question: HFileArchiveUtil { public static Path getStoreArchivePath(final Configuration conf, final String tableName, final String regionName, final String familyName) throws IOException { Path tableArchiveDir = getTableArchivePath(conf, tableName); return Store.getStoreHomedir(tableArchiveDir, regionName, familyName); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final String tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegion region, byte [] family); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Configuration conf, Path tabledir, Path regiondir); static Path getRegionArchiveDir(Path rootdir, Path tabledir, Path regiondir); static Path getTableArchivePath(Path tabledir); static Path getTableArchivePath(final Path rootdir, final String tableName); static Path getTableArchivePath(final Configuration conf, final String tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testGetStoreArchivePath(){ byte[] family = Bytes.toBytes("Family"); Path tabledir = new Path("table"); HRegionInfo region = new HRegionInfo(Bytes.toBytes("table")); Configuration conf = null; assertNotNull(HFileArchiveUtil.getStoreArchivePath(conf, region, tabledir, family)); conf = new Configuration(); assertNotNull(HFileArchiveUtil.getStoreArchivePath(conf, region, tabledir, family)); HRegion mockRegion = Mockito.mock(HRegion.class); Mockito.when(mockRegion.getRegionInfo()).thenReturn(region); Mockito.when(mockRegion.getTableDir()).thenReturn(tabledir); assertNotNull(HFileArchiveUtil.getStoreArchivePath(null, mockRegion, family)); conf = new Configuration(); assertNotNull(HFileArchiveUtil.getStoreArchivePath(conf, mockRegion, family)); }
### Question: ContainerLaunch implements Callable<Integer> { static void writeLaunchEnv(OutputStream out, Map<String,String> environment, Map<Path,List<String>> resources, List<String> command) throws IOException { ShellScriptBuilder sb = new ShellScriptBuilder(); if (environment != null) { for (Map.Entry<String,String> env : environment.entrySet()) { sb.env(env.getKey().toString(), env.getValue().toString()); } } if (resources != null) { for (Map.Entry<Path,List<String>> entry : resources.entrySet()) { for (String linkName : entry.getValue()) { sb.symlink(entry.getKey(), linkName); } } } ArrayList<String> cmd = new ArrayList<String>(2 * command.size() + 5); cmd.add("exec /bin/bash "); cmd.add("-c "); cmd.add("\""); for (String cs : command) { cmd.add(cs.toString()); cmd.add(" "); } cmd.add("\""); sb.line(cmd.toArray(new String[cmd.size()])); PrintStream pout = null; try { pout = new PrintStream(out); sb.write(pout); } finally { if (out != null) { out.close(); } } } ContainerLaunch(Configuration configuration, Dispatcher dispatcher, ContainerExecutor exec, Application app, Container container, LocalDirsHandlerService dirsHandler); @Override @SuppressWarnings("unchecked") // dispatcher not typed Integer call(); void cleanupContainer(); static String getRelativeContainerLogDir(String appIdStr, String containerIdStr); void sanitizeEnv(Map<String, String> environment, Path pwd, List<Path> appDirs); static final String CONTAINER_SCRIPT; static final String FINAL_CONTAINER_TOKENS_FILE; }### Answer: @Test public void testSpecialCharSymlinks() throws IOException { File shellFile = null; File tempFile = null; String badSymlink = "foo@zz%_#*&!-+= bar()"; File symLinkFile = null; try { shellFile = new File(tmpDir, "hello.sh"); tempFile = new File(tmpDir, "temp.sh"); String timeoutCommand = "echo \"hello\""; PrintWriter writer = new PrintWriter(new FileOutputStream(shellFile)); shellFile.setExecutable(true); writer.println(timeoutCommand); writer.close(); Map<Path, List<String>> resources = new HashMap<Path, List<String>>(); Path path = new Path(shellFile.getAbsolutePath()); resources.put(path, Arrays.asList(badSymlink)); FileOutputStream fos = new FileOutputStream(tempFile); Map<String, String> env = new HashMap<String, String>(); List<String> commands = new ArrayList<String>(); commands.add("/bin/sh ./\\\"" + badSymlink + "\\\""); ContainerLaunch.writeLaunchEnv(fos, env, resources, commands); fos.flush(); fos.close(); tempFile.setExecutable(true); Shell.ShellCommandExecutor shexc = new Shell.ShellCommandExecutor(new String[]{tempFile.getAbsolutePath()}, tmpDir); shexc.execute(); assertEquals(shexc.getExitCode(), 0); assert(shexc.getOutput().contains("hello")); symLinkFile = new File(tmpDir, badSymlink); } finally { if (shellFile != null && shellFile.exists()) { shellFile.delete(); } if (tempFile != null && tempFile.exists()) { tempFile.delete(); } if (symLinkFile != null && symLinkFile.exists()) { symLinkFile.delete(); } } }
### Question: AuxServices extends AbstractService implements ServiceStateChangeListener, EventHandler<AuxServicesEvent> { public AuxServices() { super(AuxServices.class.getName()); serviceMap = Collections.synchronizedMap(new HashMap<String,AuxiliaryService>()); serviceMeta = Collections.synchronizedMap(new HashMap<String,ByteBuffer>()); } AuxServices(); Map<String, ByteBuffer> getMeta(); @Override void init(Configuration conf); @Override void start(); @Override void stop(); @Override void stateChanged(Service service); @Override void handle(AuxServicesEvent event); }### Answer: @Test public void testAuxServices() { Configuration conf = new Configuration(); conf.setStrings(YarnConfiguration.NM_AUX_SERVICES, new String[] { "Asrv", "Bsrv" }); conf.setClass(String.format(YarnConfiguration.NM_AUX_SERVICE_FMT, "Asrv"), ServiceA.class, Service.class); conf.setClass(String.format(YarnConfiguration.NM_AUX_SERVICE_FMT, "Bsrv"), ServiceB.class, Service.class); final AuxServices aux = new AuxServices(); aux.init(conf); int latch = 1; for (Service s : aux.getServices()) { assertEquals(INITED, s.getServiceState()); if (s instanceof ServiceA) { latch *= 2; } else if (s instanceof ServiceB) { latch *= 3; } else fail("Unexpected service type " + s.getClass()); } assertEquals("Invalid mix of services", 6, latch); aux.start(); for (Service s : aux.getServices()) { assertEquals(STARTED, s.getServiceState()); } aux.stop(); for (Service s : aux.getServices()) { assertEquals(STOPPED, s.getServiceState()); } }
### Question: 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; } timeMillis = System.currentTimeMillis(); } if (interrupted) { Thread.currentThread().interrupt(); } } static Thread setDaemonThreadRunning(final Thread t); static Thread setDaemonThreadRunning(final Thread t, final String name); static Thread setDaemonThreadRunning(final Thread t, final String name, final UncaughtExceptionHandler handler); static void shutdown(final Thread t); static void shutdown(final Thread t, final long joinwait); static void threadDumpingIsAlive(final Thread t); static void sleep(long millis); static void sleepWithoutInterrupt(final long msToWait); static ThreadPoolExecutor getBoundedCachedThreadPool( int maxCachedThread, long timeout, TimeUnit unit, ThreadFactory threadFactory); static ThreadFactory getNamedThreadFactory(final String prefix); static ThreadFactory newDaemonThreadFactory(final String prefix); }### Answer: @Test(timeout=6000) 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"); wasInterrupted = Thread.currentThread().isInterrupted(); } }); LOG.debug("Starting sleeper thread (" + SLEEP_TIME_MS + " ms)"); sleeper.start(); long startTime = System.currentTimeMillis(); LOG.debug("Main thread: sleeping for 500 ms"); Threads.sleep(500); LOG.debug("Interrupting the sleeper thread and sleeping for 2000 ms"); sleeper.interrupt(); Threads.sleep(2000); LOG.debug("Interrupting the sleeper thread and sleeping for 1000 ms"); sleeper.interrupt(); Threads.sleep(1000); LOG.debug("Interrupting the sleeper thread again"); sleeper.interrupt(); sleeper.join(); assertTrue("sleepWithoutInterrupt did not preserve the thread's " + "interrupted status", wasInterrupted); long timeElapsed = System.currentTimeMillis() - startTime; assertTrue("Elapsed time " + timeElapsed + " ms is out of the expected " + "range of the sleep time " + SLEEP_TIME_MS, Math.abs(timeElapsed - SLEEP_TIME_MS) < TOLERANCE_MS); LOG.debug("Target sleep time: " + SLEEP_TIME_MS + ", time elapsed: " + timeElapsed); }
### Question: ResourceManager extends CompositeService implements Recoverable { public RMContext getRMContext() { return this.rmContext; } ResourceManager(); RMContext getRMContext(); @Override synchronized void init(Configuration conf); @Override void start(); @Override void stop(); @Private ClientRMService getClientRMService(); @Private ResourceScheduler getResourceScheduler(); @Private ResourceTrackerService getResourceTrackerService(); @Private ApplicationMasterService getApplicationMasterService(); @Private ApplicationACLsManager getApplicationACLsManager(); @Private RMContainerTokenSecretManager getRMContainerTokenSecretManager(); @Private ApplicationTokenSecretManager getApplicationTokenSecretManager(); @Override void recover(RMState state); static void main(String argv[]); static final int SHUTDOWN_HOOK_PRIORITY; static final long clusterTimeStamp; }### Answer: @Test public void testNodeHealthReportIsNotNull() throws Exception{ String host1 = "host1"; final int memory = 4 * 1024; org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm1 = registerNode(host1, 1234, 2345, NetworkTopology.DEFAULT_RACK, memory); nm1.heartbeat(); nm1.heartbeat(); Collection<RMNode> values = resourceManager.getRMContext().getRMNodes().values(); for (RMNode ni : values) { NodeHealthStatus nodeHealthStatus = ni.getNodeHealthStatus(); String healthReport = nodeHealthStatus.getHealthReport(); assertNotNull(healthReport); } }
### Question: RMAuditLogger { static void start(Keys key, String value, StringBuilder b) { b.append(key.name()).append(AuditConstants.KEY_VAL_SEPARATOR).append(value); } static void logSuccess(String user, String operation, String target, ApplicationId appId, ContainerId containerId); static void logSuccess(String user, String operation, String target, ApplicationId appId, ApplicationAttemptId attemptId); static void logSuccess(String user, String operation, String target, ApplicationId appId); static void logSuccess(String user, String operation, String target); static void logFailure(String user, String operation, String perm, String target, String description, ApplicationId appId, ContainerId containerId); static void logFailure(String user, String operation, String perm, String target, String description, ApplicationId appId, ApplicationAttemptId attemptId); static void logFailure(String user, String operation, String perm, String target, String description, ApplicationId appId); static void logFailure(String user, String operation, String perm, String target, String description); }### Answer: @Test public void testRMAuditLoggerWithIP() throws Exception { Configuration conf = new Configuration(); Server server = RPC.getServer(TestProtocol.class, new MyTestRPCServer(), "0.0.0.0", 0, 5, true, conf, null); server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); TestProtocol proxy = (TestProtocol)RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); proxy.ping(); server.stop(); } @Test public void testRMAuditLoggerWithIP() throws Exception { Configuration conf = new Configuration(); Server server = RPC.getServer(new MyTestRPCServer(), "0.0.0.0", 0, conf); server.start(); InetSocketAddress addr = NetUtils.getConnectAddress(server); TestProtocol proxy = (TestProtocol)RPC.getProxy(TestProtocol.class, TestProtocol.versionID, addr, conf); proxy.ping(); server.stop(); }
### Question: ClientRMService extends AbstractService implements ClientRMProtocol { @Override public GetClusterNodesResponse getClusterNodes(GetClusterNodesRequest request) throws YarnRemoteException { GetClusterNodesResponse response = recordFactory.newRecordInstance(GetClusterNodesResponse.class); Collection<RMNode> nodes = this.rmContext.getRMNodes().values(); List<NodeReport> nodeReports = new ArrayList<NodeReport>(nodes.size()); for (RMNode nodeInfo : nodes) { nodeReports.add(createNodeReports(nodeInfo)); } response.setNodeReports(nodeReports); return response; } ClientRMService(RMContext rmContext, YarnScheduler scheduler, RMAppManager rmAppManager, ApplicationACLsManager applicationACLsManager, RMDelegationTokenSecretManager rmDTSecretManager); @Override void init(Configuration conf); @Override void start(); @Private InetSocketAddress getBindAddress(); @Override GetNewApplicationResponse getNewApplication( GetNewApplicationRequest request); @Override GetApplicationReportResponse getApplicationReport( GetApplicationReportRequest request); @Override SubmitApplicationResponse submitApplication( SubmitApplicationRequest request); @SuppressWarnings("unchecked") @Override KillApplicationResponse forceKillApplication( KillApplicationRequest request); @Override GetClusterMetricsResponse getClusterMetrics( GetClusterMetricsRequest request); @Override GetAllApplicationsResponse getAllApplications( GetAllApplicationsRequest request); @Override GetClusterNodesResponse getClusterNodes(GetClusterNodesRequest request); @Override GetQueueInfoResponse getQueueInfo(GetQueueInfoRequest request); @Override GetQueueUserAclsInfoResponse getQueueUserAcls( GetQueueUserAclsInfoRequest request); @Override GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request); @Override void stop(); }### Answer: @Test public void testGetClusterNodes() throws Exception { MockRM rm = new MockRM() { protected ClientRMService createClientRMService() { return new ClientRMService(this.rmContext, scheduler, this.rmAppManager, this.applicationACLsManager, this.rmDTSecretManager); }; }; rm.start(); MockNM node = rm.registerNode("host:1234", 1024); node.nodeHeartbeat(true); Configuration conf = new Configuration(); YarnRPC rpc = YarnRPC.create(conf); InetSocketAddress rmAddress = rm.getClientRMService().getBindAddress(); LOG.info("Connecting to ResourceManager at " + rmAddress); ClientRMProtocol client = (ClientRMProtocol) rpc .getProxy(ClientRMProtocol.class, rmAddress, conf); GetClusterNodesRequest request = Records.newRecord(GetClusterNodesRequest.class); List<NodeReport> nodeReports = client.getClusterNodes(request).getNodeReports(); Assert.assertEquals(1, nodeReports.size()); Assert.assertTrue("Node is expected to be healthy!", nodeReports.get(0) .getNodeHealthStatus().getIsNodeHealthy()); node.nodeHeartbeat(false); nodeReports = client.getClusterNodes(request).getNodeReports(); Assert.assertEquals(1, nodeReports.size()); Assert.assertFalse("Node is expected to be unhealthy!", nodeReports.get(0) .getNodeHealthStatus().getIsNodeHealthy()); }
### Question: ClientRMService extends AbstractService implements ClientRMProtocol { @Override public GetApplicationReportResponse getApplicationReport( GetApplicationReportRequest request) throws YarnRemoteException { ApplicationId applicationId = request.getApplicationId(); UserGroupInformation callerUGI; try { callerUGI = UserGroupInformation.getCurrentUser(); } catch (IOException ie) { LOG.info("Error getting UGI ", ie); throw RPCUtil.getRemoteException(ie); } RMApp application = this.rmContext.getRMApps().get(applicationId); if (application == null) { return recordFactory .newRecordInstance(GetApplicationReportResponse.class); } boolean allowAccess = checkAccess(callerUGI, application.getUser(), ApplicationAccessType.VIEW_APP, applicationId); ApplicationReport report = application.createAndGetApplicationReport(allowAccess); GetApplicationReportResponse response = recordFactory .newRecordInstance(GetApplicationReportResponse.class); response.setApplicationReport(report); return response; } ClientRMService(RMContext rmContext, YarnScheduler scheduler, RMAppManager rmAppManager, ApplicationACLsManager applicationACLsManager, RMDelegationTokenSecretManager rmDTSecretManager); @Override void init(Configuration conf); @Override void start(); @Private InetSocketAddress getBindAddress(); @Override GetNewApplicationResponse getNewApplication( GetNewApplicationRequest request); @Override GetApplicationReportResponse getApplicationReport( GetApplicationReportRequest request); @Override SubmitApplicationResponse submitApplication( SubmitApplicationRequest request); @SuppressWarnings("unchecked") @Override KillApplicationResponse forceKillApplication( KillApplicationRequest request); @Override GetClusterMetricsResponse getClusterMetrics( GetClusterMetricsRequest request); @Override GetAllApplicationsResponse getAllApplications( GetAllApplicationsRequest request); @Override GetClusterNodesResponse getClusterNodes(GetClusterNodesRequest request); @Override GetQueueInfoResponse getQueueInfo(GetQueueInfoRequest request); @Override GetQueueUserAclsInfoResponse getQueueUserAcls( GetQueueUserAclsInfoRequest request); @Override GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request); @Override void stop(); }### Answer: @Test public void testGetApplicationReport() throws YarnRemoteException { RMContext rmContext = mock(RMContext.class); when(rmContext.getRMApps()).thenReturn( new ConcurrentHashMap<ApplicationId, RMApp>()); ClientRMService rmService = new ClientRMService(rmContext, null, null, null, null); RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); GetApplicationReportRequest request = recordFactory .newRecordInstance(GetApplicationReportRequest.class); request.setApplicationId(recordFactory .newRecordInstance(ApplicationId.class)); GetApplicationReportResponse applicationReport = rmService .getApplicationReport(request); Assert.assertNull("It should return null as application report for absent application.", applicationReport.getApplicationReport()); }
### Question: ClientRMService extends AbstractService implements ClientRMProtocol { @Override public GetQueueInfoResponse getQueueInfo(GetQueueInfoRequest request) throws YarnRemoteException { GetQueueInfoResponse response = recordFactory.newRecordInstance(GetQueueInfoResponse.class); try { QueueInfo queueInfo = scheduler.getQueueInfo(request.getQueueName(), request.getIncludeChildQueues(), request.getRecursive()); List<ApplicationReport> appReports = EMPTY_APPS_REPORT; if (request.getIncludeApplications()) { Collection<RMApp> apps = this.rmContext.getRMApps().values(); appReports = new ArrayList<ApplicationReport>( apps.size()); for (RMApp app : apps) { if (app.getQueue().equals(queueInfo.getQueueName())) { appReports.add(app.createAndGetApplicationReport(true)); } } } queueInfo.setApplications(appReports); response.setQueueInfo(queueInfo); } catch (IOException ioe) { LOG.info("Failed to getQueueInfo for " + request.getQueueName(), ioe); } return response; } ClientRMService(RMContext rmContext, YarnScheduler scheduler, RMAppManager rmAppManager, ApplicationACLsManager applicationACLsManager, RMDelegationTokenSecretManager rmDTSecretManager); @Override void init(Configuration conf); @Override void start(); @Private InetSocketAddress getBindAddress(); @Override GetNewApplicationResponse getNewApplication( GetNewApplicationRequest request); @Override GetApplicationReportResponse getApplicationReport( GetApplicationReportRequest request); @Override SubmitApplicationResponse submitApplication( SubmitApplicationRequest request); @SuppressWarnings("unchecked") @Override KillApplicationResponse forceKillApplication( KillApplicationRequest request); @Override GetClusterMetricsResponse getClusterMetrics( GetClusterMetricsRequest request); @Override GetAllApplicationsResponse getAllApplications( GetAllApplicationsRequest request); @Override GetClusterNodesResponse getClusterNodes(GetClusterNodesRequest request); @Override GetQueueInfoResponse getQueueInfo(GetQueueInfoRequest request); @Override GetQueueUserAclsInfoResponse getQueueUserAcls( GetQueueUserAclsInfoRequest request); @Override GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request); @Override void stop(); }### Answer: @Test public void testGetQueueInfo() throws Exception { YarnScheduler yarnScheduler = mock(YarnScheduler.class); RMContext rmContext = mock(RMContext.class); mockRMContext(yarnScheduler, rmContext); ClientRMService rmService = new ClientRMService(rmContext, yarnScheduler, null, null, null); GetQueueInfoRequest request = recordFactory .newRecordInstance(GetQueueInfoRequest.class); request.setQueueName("testqueue"); request.setIncludeApplications(true); GetQueueInfoResponse queueInfo = rmService.getQueueInfo(request); List<ApplicationReport> applications = queueInfo.getQueueInfo() .getApplications(); Assert.assertEquals(2, applications.size()); request.setQueueName("nonexistentqueue"); request.setIncludeApplications(true); queueInfo = rmService.getQueueInfo(request); }
### Question: FifoScheduler implements ResourceScheduler, Configurable { @Override public QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive) { return DEFAULT_QUEUE.getQueueInfo(false, false); } @Override synchronized void setConf(Configuration conf); @Override synchronized Configuration getConf(); @Override Resource getMinimumResourceCapability(); @Override int getNumClusterNodes(); @Override Resource getMaximumResourceCapability(); @Override synchronized void reinitialize(Configuration conf, RMContext rmContext); @Override Allocation allocate( ApplicationAttemptId applicationAttemptId, List<ResourceRequest> ask, List<ContainerId> release); @Override SchedulerAppReport getSchedulerAppInfo( ApplicationAttemptId applicationAttemptId); @Override void handle(SchedulerEvent event); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override void recover(RMState state); @Override synchronized SchedulerNodeReport getNodeReport(NodeId nodeId); @Override QueueMetrics getRootQueueMetrics(); }### Answer: @Test public void testFifoSchedulerCapacityWhenNoNMs() { FifoScheduler scheduler = new FifoScheduler(); QueueInfo queueInfo = scheduler.getQueueInfo(null, false, false); Assert.assertEquals(0.0f, queueInfo.getCurrentCapacity()); }
### Question: SchedulerUtils { public static void normalizeRequest(ResourceRequest ask, int minMemory) { int memory = Math.max(ask.getCapability().getMemory(), minMemory); ask.getCapability().setMemory( minMemory * ((memory / minMemory) + (memory % minMemory > 0 ? 1 : 0))); } static ContainerStatus createAbnormalContainerStatus( ContainerId containerId, String diagnostics); static void normalizeRequests(List<ResourceRequest> asks, int minMemory); static void normalizeRequest(ResourceRequest ask, int minMemory); static final String RELEASED_CONTAINER; static final String LOST_CONTAINER; static final String PREEMPTED_CONTAINER; static final String COMPLETED_APPLICATION; static final String EXPIRED_CONTAINER; static final String UNRESERVED_CONTAINER; }### Answer: @Test public void testNormalizeRequest() { int minMemory = 1024; ResourceRequest ask = new ResourceRequestPBImpl(); ask.setCapability(Resource.createResource(-1024)); SchedulerUtils.normalizeRequest(ask, minMemory); assertEquals(minMemory, ask.getCapability().getMemory()); ask.setCapability(Resource.createResource(0)); SchedulerUtils.normalizeRequest(ask, minMemory); assertEquals(minMemory, ask.getCapability().getMemory()); ask.setCapability(Resource.createResource(2 * minMemory)); SchedulerUtils.normalizeRequest(ask, minMemory); assertEquals(2 * minMemory, ask.getCapability().getMemory()); ask.setCapability(Resource.createResource(minMemory + 10)); SchedulerUtils.normalizeRequest(ask, minMemory); assertEquals(2 * minMemory, ask.getCapability().getMemory()); }
### Question: FairScheduler implements ResourceScheduler { public QueueManager getQueueManager() { return queueMgr; } FairScheduler(); FairSchedulerConfiguration getConf(); QueueManager getQueueManager(); RMContainerTokenSecretManager getContainerTokenSecretManager(); synchronized double getAppWeight(AppSchedulable app); @Override Resource getMinimumResourceCapability(); @Override Resource getMaximumResourceCapability(); double getNodeLocalityThreshold(); double getRackLocalityThreshold(); Resource getClusterCapacity(); Clock getClock(); FairSchedulerEventLog getEventLog(); @Override Allocation allocate(ApplicationAttemptId appAttemptId, List<ResourceRequest> ask, List<ContainerId> release); @Override SchedulerNodeReport getNodeReport(NodeId nodeId); FSSchedulerApp getSchedulerApp(ApplicationAttemptId appAttemptId); @Override SchedulerAppReport getSchedulerAppInfo( ApplicationAttemptId appAttemptId); @Override QueueMetrics getRootQueueMetrics(); @Override void handle(SchedulerEvent event); @Override void recover(RMState state); @Override synchronized void reinitialize(Configuration conf, RMContext rmContext); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override int getNumClusterNodes(); static final Resource CONTAINER_RESERVED; }### Answer: @Test public void testHierarchicalQueuesSimilarParents() { QueueManager queueManager = scheduler.getQueueManager(); FSLeafQueue leafQueue = queueManager.getLeafQueue("parent.child"); Assert.assertEquals(2, queueManager.getLeafQueues().size()); Assert.assertNotNull(leafQueue); Assert.assertEquals("root.parent.child", leafQueue.getName()); FSLeafQueue leafQueue2 = queueManager.getLeafQueue("parent"); Assert.assertNull(leafQueue2); Assert.assertEquals(2, queueManager.getLeafQueues().size()); FSLeafQueue leafQueue3 = queueManager.getLeafQueue("parent.child.grandchild"); Assert.assertNull(leafQueue3); Assert.assertEquals(2, queueManager.getLeafQueues().size()); FSLeafQueue leafQueue4 = queueManager.getLeafQueue("parent.sister"); Assert.assertNotNull(leafQueue4); Assert.assertEquals("root.parent.sister", leafQueue4.getName()); Assert.assertEquals(3, queueManager.getLeafQueues().size()); }
### Question: FairScheduler implements ResourceScheduler { boolean isStarvedForMinShare(FSLeafQueue sched) { Resource desiredShare = Resources.min(sched.getMinShare(), sched.getDemand()); return Resources.lessThan(sched.getResourceUsage(), desiredShare); } FairScheduler(); FairSchedulerConfiguration getConf(); QueueManager getQueueManager(); RMContainerTokenSecretManager getContainerTokenSecretManager(); synchronized double getAppWeight(AppSchedulable app); @Override Resource getMinimumResourceCapability(); @Override Resource getMaximumResourceCapability(); double getNodeLocalityThreshold(); double getRackLocalityThreshold(); Resource getClusterCapacity(); Clock getClock(); FairSchedulerEventLog getEventLog(); @Override Allocation allocate(ApplicationAttemptId appAttemptId, List<ResourceRequest> ask, List<ContainerId> release); @Override SchedulerNodeReport getNodeReport(NodeId nodeId); FSSchedulerApp getSchedulerApp(ApplicationAttemptId appAttemptId); @Override SchedulerAppReport getSchedulerAppInfo( ApplicationAttemptId appAttemptId); @Override QueueMetrics getRootQueueMetrics(); @Override void handle(SchedulerEvent event); @Override void recover(RMState state); @Override synchronized void reinitialize(Configuration conf, RMContext rmContext); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override int getNumClusterNodes(); static final Resource CONTAINER_RESERVED; }### Answer: @Test public void testIsStarvedForMinShare() throws Exception { Configuration conf = createConfiguration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); scheduler.reinitialize(conf, resourceManager.getRMContext()); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<minResources>2048</minResources>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<minResources>2048</minResources>"); out.println("</queue>"); out.println("</allocations>"); out.close(); QueueManager queueManager = scheduler.getQueueManager(); queueManager.initialize(); RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024)); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); createSchedulingRequest(3 * 1024, "queueA", "user1"); scheduler.update(); NodeUpdateSchedulerEvent nodeEvent2 = new NodeUpdateSchedulerEvent(node1, new LinkedList<ContainerStatus>(), new LinkedList<ContainerStatus>()); scheduler.handle(nodeEvent2); createSchedulingRequest(1 * 1024, "queueB", "user1"); scheduler.update(); Collection<FSLeafQueue> queues = scheduler.getQueueManager().getLeafQueues(); assertEquals(3, queues.size()); for (FSLeafQueue p : queues) { if (p.getName().equals("root.queueA")) { assertEquals(false, scheduler.isStarvedForMinShare(p)); } else if (p.getName().equals("root.queueB")) { assertEquals(true, scheduler.isStarvedForMinShare(p)); } } scheduler.handle(nodeEvent2); for (FSLeafQueue p : queues) { if (p.getName().equals("root.queueB")) { assertEquals(false, scheduler.isStarvedForMinShare(p)); } } }
### Question: FairScheduler implements ResourceScheduler { boolean isStarvedForFairShare(FSLeafQueue sched) { Resource desiredFairShare = Resources.max( Resources.multiply(sched.getFairShare(), .5), sched.getDemand()); return Resources.lessThan(sched.getResourceUsage(), desiredFairShare); } FairScheduler(); FairSchedulerConfiguration getConf(); QueueManager getQueueManager(); RMContainerTokenSecretManager getContainerTokenSecretManager(); synchronized double getAppWeight(AppSchedulable app); @Override Resource getMinimumResourceCapability(); @Override Resource getMaximumResourceCapability(); double getNodeLocalityThreshold(); double getRackLocalityThreshold(); Resource getClusterCapacity(); Clock getClock(); FairSchedulerEventLog getEventLog(); @Override Allocation allocate(ApplicationAttemptId appAttemptId, List<ResourceRequest> ask, List<ContainerId> release); @Override SchedulerNodeReport getNodeReport(NodeId nodeId); FSSchedulerApp getSchedulerApp(ApplicationAttemptId appAttemptId); @Override SchedulerAppReport getSchedulerAppInfo( ApplicationAttemptId appAttemptId); @Override QueueMetrics getRootQueueMetrics(); @Override void handle(SchedulerEvent event); @Override void recover(RMState state); @Override synchronized void reinitialize(Configuration conf, RMContext rmContext); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override int getNumClusterNodes(); static final Resource CONTAINER_RESERVED; }### Answer: @Test public void testIsStarvedForFairShare() throws Exception { Configuration conf = createConfiguration(); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); scheduler.reinitialize(conf, resourceManager.getRMContext()); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("<queue name=\"queueA\">"); out.println("<weight>.25</weight>"); out.println("</queue>"); out.println("<queue name=\"queueB\">"); out.println("<weight>.75</weight>"); out.println("</queue>"); out.println("</allocations>"); out.close(); QueueManager queueManager = scheduler.getQueueManager(); queueManager.initialize(); RMNode node1 = MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024)); NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1); scheduler.handle(nodeEvent1); createSchedulingRequest(3 * 1024, "queueA", "user1"); scheduler.update(); NodeUpdateSchedulerEvent nodeEvent2 = new NodeUpdateSchedulerEvent(node1, new LinkedList<ContainerStatus>(), new LinkedList<ContainerStatus>()); scheduler.handle(nodeEvent2); createSchedulingRequest(1 * 1024, "queueB", "user1"); scheduler.update(); Collection<FSLeafQueue> queues = scheduler.getQueueManager().getLeafQueues(); assertEquals(3, queues.size()); for (FSLeafQueue p : queues) { if (p.getName().equals("root.queueA")) { assertEquals(false, scheduler.isStarvedForFairShare(p)); } else if (p.getName().equals("root.queueB")) { assertEquals(true, scheduler.isStarvedForFairShare(p)); } } scheduler.handle(nodeEvent2); for (FSLeafQueue p : queues) { if (p.getName().equals("root.queueB")) { assertEquals(false, scheduler.isStarvedForFairShare(p)); } } }
### Question: FSLeafQueue extends FSQueue { @Override public void updateDemand() { Resource maxRes = queueMgr.getMaxResources(getName()); demand = Resources.createResource(0); for (AppSchedulable sched : appScheds) { sched.updateDemand(); Resource toAdd = sched.getDemand(); if (LOG.isDebugEnabled()) { LOG.debug("Counting resource from " + sched.getName() + " " + toAdd + "; Total resource consumption for " + getName() + " now " + demand); } demand = Resources.add(demand, toAdd); if (Resources.greaterThanOrEqual(demand, maxRes)) { demand = maxRes; break; } } if (LOG.isDebugEnabled()) { LOG.debug("The updated demand for " + getName() + " is " + demand + "; the max is " + maxRes); } } FSLeafQueue(String name, QueueManager queueMgr, FairScheduler scheduler, FSParentQueue parent); void addApp(FSSchedulerApp app); void removeApp(FSSchedulerApp app); Collection<AppSchedulable> getAppSchedulables(); void setSchedulingMode(SchedulingMode mode); @Override void recomputeFairShares(); @Override Resource getDemand(); @Override Resource getResourceUsage(); @Override void updateDemand(); @Override Resource assignContainer(FSSchedulerNode node, boolean reserved); @Override Collection<FSQueue> getChildQueues(); @Override List<QueueUserACLInfo> getQueueUserAclInfo(UserGroupInformation user); long getLastTimeAtMinShare(); void setLastTimeAtMinShare(long lastTimeAtMinShare); long getLastTimeAtHalfFairShare(); void setLastTimeAtHalfFairShare(long lastTimeAtHalfFairShare); }### Answer: @Test public void testUpdateDemand() { AppSchedulable app = mock(AppSchedulable.class); Mockito.when(app.getDemand()).thenReturn(maxResource); schedulable.addAppSchedulable(app); schedulable.addAppSchedulable(app); schedulable.updateDemand(); assertTrue("Demand is greater than max allowed ", Resources.equals(schedulable.getDemand(), maxResource)); }
### Question: CapacityScheduler implements ResourceScheduler, CapacitySchedulerContext, Configurable { @Lock(CapacityScheduler.class) static CSQueue parseQueue( CapacitySchedulerContext csContext, CapacitySchedulerConfiguration conf, CSQueue parent, String queueName, Map<String, CSQueue> queues, Map<String, CSQueue> oldQueues, Comparator<CSQueue> queueComparator, Comparator<FiCaSchedulerApp> applicationComparator, QueueHook hook) throws IOException { CSQueue queue; String[] childQueueNames = conf.getQueues((parent == null) ? queueName : (parent.getQueuePath()+"."+queueName)); if (childQueueNames == null || childQueueNames.length == 0) { if (null == parent) { throw new IllegalStateException( "Queue configuration missing child queue names for " + queueName); } queue = new LeafQueue(csContext, queueName, parent, applicationComparator, oldQueues.get(queueName)); queue = hook.hook(queue); } else { ParentQueue parentQueue = new ParentQueue(csContext, queueName, queueComparator, parent, oldQueues.get(queueName)); queue = hook.hook(parentQueue); List<CSQueue> childQueues = new ArrayList<CSQueue>(); for (String childQueueName : childQueueNames) { CSQueue childQueue = parseQueue(csContext, conf, queue, childQueueName, queues, oldQueues, queueComparator, applicationComparator, hook); childQueues.add(childQueue); } parentQueue.setChildQueues(childQueues); } if(queue instanceof LeafQueue == true && queues.containsKey(queueName) && queues.get(queueName) instanceof LeafQueue == true) { throw new IOException("Two leaf queues were named " + queueName + ". Leaf queue names must be distinct"); } queues.put(queueName, queue); LOG.info("Initialized queue: " + queue); return queue; } CapacityScheduler(); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override QueueMetrics getRootQueueMetrics(); CSQueue getRootQueue(); @Override CapacitySchedulerConfiguration getConfiguration(); @Override RMContainerTokenSecretManager getContainerTokenSecretManager(); @Override Resource getMinimumResourceCapability(); @Override Resource getMaximumResourceCapability(); @Override synchronized int getNumClusterNodes(); @Override RMContext getRMContext(); @Override Resource getClusterResources(); @Override synchronized void reinitialize(Configuration conf, RMContext rmContext); @Override @Lock(Lock.NoLock.class) Allocation allocate(ApplicationAttemptId applicationAttemptId, List<ResourceRequest> ask, List<ContainerId> release); @Override @Lock(Lock.NoLock.class) QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override @Lock(Lock.NoLock.class) List<QueueUserACLInfo> getQueueUserAclInfo(); @Override void handle(SchedulerEvent event); @Override SchedulerAppReport getSchedulerAppInfo( ApplicationAttemptId applicationAttemptId); @Override @Lock(Lock.NoLock.class) void recover(RMState state); @Override SchedulerNodeReport getNodeReport(NodeId nodeId); @Private static final String ROOT_QUEUE; }### Answer: @Test(expected=IOException.class) public void testParseQueue() throws IOException { CapacityScheduler cs = new CapacityScheduler(); cs.setConf(new YarnConfiguration()); CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); conf.setQueues(CapacitySchedulerConfiguration.ROOT + ".a.a1", new String[] {"b1"} ); conf.setCapacity(CapacitySchedulerConfiguration.ROOT + ".a.a1.b1", 100.0f); conf.setUserLimitFactor(CapacitySchedulerConfiguration.ROOT + ".a.a1.b1", 100.0f); cs.reinitialize(conf, new RMContextImpl(null, null, null, null, null, null, new RMContainerTokenSecretManager(conf), new ClientToAMTokenSecretManagerInRM())); }
### Question: ProxyUriUtils { public static String getPath(ApplicationId id) { if(id == null) { throw new IllegalArgumentException("Application id cannot be null "); } return ujoin(PROXY_BASE, uriEncode(id)); } static String getPath(ApplicationId id); static String getPath(ApplicationId id, String path); static String getPathAndQuery(ApplicationId id, String path, String query, boolean approved); static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id); static URI getUriFromAMUrl(String noSchemeUrl); static URI getUriFromTrackingPlugins(ApplicationId id, List<TrackingUriPlugin> trackingUriPlugins); static final String PROXY_SERVLET_NAME; static final String PROXY_BASE; static final String PROXY_PATH_SPEC; static final String PROXY_APPROVAL_PARAM; }### Answer: @Test public void testGetPathApplicationId() { assertEquals("/proxy/application_100_0001", ProxyUriUtils.getPath(BuilderUtils.newApplicationId(100l, 1))); assertEquals("/proxy/application_6384623_0005", ProxyUriUtils.getPath(BuilderUtils.newApplicationId(6384623l, 5))); } @Test(expected = IllegalArgumentException.class) public void testGetPathApplicationIdBad() { ProxyUriUtils.getPath(null); } @Test public void testGetPathApplicationIdString() { assertEquals("/proxy/application_6384623_0005", ProxyUriUtils.getPath(BuilderUtils.newApplicationId(6384623l, 5), null)); assertEquals("/proxy/application_6384623_0005/static/app", ProxyUriUtils.getPath(BuilderUtils.newApplicationId(6384623l, 5), "/static/app")); assertEquals("/proxy/application_6384623_0005/", ProxyUriUtils.getPath(BuilderUtils.newApplicationId(6384623l, 5), "/")); assertEquals("/proxy/application_6384623_0005/some/path", ProxyUriUtils.getPath(BuilderUtils.newApplicationId(6384623l, 5), "some/path")); }
### Question: ByteBufferUtils { public static void writeVLong(ByteBuffer out, long i) { if (i >= -112 && i <= 127) { out.put((byte) i); return; } int len = -112; if (i < 0) { i ^= -1L; len = -120; } long tmp = i; while (tmp != 0) { tmp = tmp >> 8; len--; } out.put((byte) len); len = (len < -120) ? -(len + 120) : -(len + 112); for (int idx = len; idx != 0; idx--) { int shiftbits = (idx - 1) * 8; long mask = 0xFFL << shiftbits; out.put((byte) ((i & mask) >> shiftbits)); } } private ByteBufferUtils(); static void writeVLong(ByteBuffer out, long i); static long readVLong(ByteBuffer in); static int putCompressedInt(OutputStream out, final int value); static void putInt(OutputStream out, final int value); static void moveBufferToStream(OutputStream out, ByteBuffer in, int length); static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length); static int putLong(OutputStream out, final long value, final int fitInBytes); static int longFitsIn(final long value); static int intFitsIn(final int value); static int readCompressedInt(InputStream input); static int readCompressedInt(ByteBuffer buffer); static long readLong(InputStream in, final int fitInBytes); static long readLong(ByteBuffer in, final int fitInBytes); static void ensureSpace(ByteBuffer out, int length); static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length); static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length); static int findCommonPrefix(ByteBuffer buffer, int offsetLeft, int offsetRight, int limit); static int findCommonPrefix( byte[] left, int leftOffset, int leftLength, byte[] right, int rightOffset, int rightLength); static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight); static void skip(ByteBuffer buffer, int length); }### Answer: @Test public void testConsistencyWithHadoopVLong() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); for (long l : testNumbers) { baos.reset(); ByteBuffer b = ByteBuffer.allocate(MAX_VLONG_LENGTH); ByteBufferUtils.writeVLong(b, l); String bufStr = Bytes.toStringBinary(b.array(), b.arrayOffset(), b.position()); WritableUtils.writeVLong(dos, l); String baosStr = Bytes.toStringBinary(baos.toByteArray()); assertEquals(baosStr, bufStr); } }
### Question: ProxyUriUtils { public static String getPathAndQuery(ApplicationId id, String path, String query, boolean approved) { StringBuilder newp = new StringBuilder(); newp.append(getPath(id, path)); boolean first = appendQuery(newp, query, true); if(approved) { appendQuery(newp, PROXY_APPROVAL_PARAM+"=true", first); } return newp.toString(); } static String getPath(ApplicationId id); static String getPath(ApplicationId id, String path); static String getPathAndQuery(ApplicationId id, String path, String query, boolean approved); static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id); static URI getUriFromAMUrl(String noSchemeUrl); static URI getUriFromTrackingPlugins(ApplicationId id, List<TrackingUriPlugin> trackingUriPlugins); static final String PROXY_SERVLET_NAME; static final String PROXY_BASE; static final String PROXY_PATH_SPEC; static final String PROXY_APPROVAL_PARAM; }### Answer: @Test public void testGetPathAndQuery() { assertEquals("/proxy/application_6384623_0005/static/app?foo=bar", ProxyUriUtils.getPathAndQuery(BuilderUtils.newApplicationId(6384623l, 5), "/static/app", "?foo=bar", false)); assertEquals("/proxy/application_6384623_0005/static/app?foo=bar&bad=good&proxyapproved=true", ProxyUriUtils.getPathAndQuery(BuilderUtils.newApplicationId(6384623l, 5), "/static/app", "foo=bar&bad=good", true)); }
### Question: ProxyUriUtils { public static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id) { try { String path = getPath(id, originalUri == null ? "/" : originalUri.getPath()); return new URI(proxyUri.getScheme(), proxyUri.getAuthority(), path, originalUri == null ? null : originalUri.getQuery(), originalUri == null ? null : originalUri.getFragment()); } catch (URISyntaxException e) { throw new RuntimeException("Could not proxify "+originalUri,e); } } static String getPath(ApplicationId id); static String getPath(ApplicationId id, String path); static String getPathAndQuery(ApplicationId id, String path, String query, boolean approved); static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id); static URI getUriFromAMUrl(String noSchemeUrl); static URI getUriFromTrackingPlugins(ApplicationId id, List<TrackingUriPlugin> trackingUriPlugins); static final String PROXY_SERVLET_NAME; static final String PROXY_BASE; static final String PROXY_PATH_SPEC; static final String PROXY_APPROVAL_PARAM; }### Answer: @Test public void testGetProxyUri() throws Exception { URI originalUri = new URI("http: URI proxyUri = new URI("http: ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); URI expected = new URI("http: URI result = ProxyUriUtils.getProxyUri(originalUri, proxyUri, id); assertEquals(expected, result); } @Test public void testGetProxyUriNull() throws Exception { URI originalUri = null; URI proxyUri = new URI("http: ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); URI expected = new URI("http: URI result = ProxyUriUtils.getProxyUri(originalUri, proxyUri, id); assertEquals(expected, result); }
### Question: ProxyUriUtils { public static URI getUriFromTrackingPlugins(ApplicationId id, List<TrackingUriPlugin> trackingUriPlugins) throws URISyntaxException { URI toRet = null; for(TrackingUriPlugin plugin : trackingUriPlugins) { toRet = plugin.getTrackingUri(id); if (toRet != null) { return toRet; } } return null; } static String getPath(ApplicationId id); static String getPath(ApplicationId id, String path); static String getPathAndQuery(ApplicationId id, String path, String query, boolean approved); static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id); static URI getUriFromAMUrl(String noSchemeUrl); static URI getUriFromTrackingPlugins(ApplicationId id, List<TrackingUriPlugin> trackingUriPlugins); static final String PROXY_SERVLET_NAME; static final String PROXY_BASE; static final String PROXY_PATH_SPEC; static final String PROXY_APPROVAL_PARAM; }### Answer: @Test public void testGetProxyUriFromPluginsReturnsNullIfNoPlugins() throws URISyntaxException { ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); List<TrackingUriPlugin> list = Lists.newArrayListWithExpectedSize(0); assertNull(ProxyUriUtils.getUriFromTrackingPlugins(id, list)); } @Test public void testGetProxyUriFromPluginsReturnsValidUriWhenAble() throws URISyntaxException { ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); List<TrackingUriPlugin> list = Lists.newArrayListWithExpectedSize(2); list.add(new TrackingUriPlugin() { public URI getTrackingUri(ApplicationId id) throws URISyntaxException { return null; } }); list.add(new TrackingUriPlugin() { public URI getTrackingUri(ApplicationId id) throws URISyntaxException { return new URI("http: } }); URI result = ProxyUriUtils.getUriFromTrackingPlugins(id, list); assertNotNull(result); }
### Question: KerberosName { public String getRealm() { return realm; } KerberosName(String name); String getDefaultRealm(); @Override String toString(); String getServiceName(); String getHostName(); String getRealm(); String getShortName(); static void setRules(String ruleString); static boolean hasRulesBeenSet(); }### Answer: @Test public void testRules() throws Exception { checkTranslation("omalley@" + KerberosTestUtils.getRealm(), "omalley"); checkTranslation("hdfs/10.0.0.1@" + KerberosTestUtils.getRealm(), "hdfs"); checkTranslation("[email protected]", "oom"); checkTranslation("johndoe/[email protected]", "guest"); checkTranslation("joe/[email protected]", "joe"); checkTranslation("joe/[email protected]", "root"); }
### Question: ByteBufferUtils { public static void moveBufferToStream(OutputStream out, ByteBuffer in, int length) throws IOException { copyBufferToStream(out, in, in.position(), length); skip(in, length); } private ByteBufferUtils(); static void writeVLong(ByteBuffer out, long i); static long readVLong(ByteBuffer in); static int putCompressedInt(OutputStream out, final int value); static void putInt(OutputStream out, final int value); static void moveBufferToStream(OutputStream out, ByteBuffer in, int length); static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length); static int putLong(OutputStream out, final long value, final int fitInBytes); static int longFitsIn(final long value); static int intFitsIn(final int value); static int readCompressedInt(InputStream input); static int readCompressedInt(ByteBuffer buffer); static long readLong(InputStream in, final int fitInBytes); static long readLong(ByteBuffer in, final int fitInBytes); static void ensureSpace(ByteBuffer out, int length); static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length); static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length); static int findCommonPrefix(ByteBuffer buffer, int offsetLeft, int offsetRight, int limit); static int findCommonPrefix( byte[] left, int leftOffset, int leftLength, byte[] right, int rightOffset, int rightLength); static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight); static void skip(ByteBuffer buffer, int length); }### Answer: @Test public void testMoveBufferToStream() { final int arrayOffset = 7; final int initialPosition = 10; final int endPadding = 5; byte[] arrayWrapper = new byte[arrayOffset + initialPosition + array.length + endPadding]; System.arraycopy(array, 0, arrayWrapper, arrayOffset + initialPosition, array.length); ByteBuffer buffer = ByteBuffer.wrap(arrayWrapper, arrayOffset, initialPosition + array.length).slice(); assertEquals(initialPosition + array.length, buffer.limit()); assertEquals(0, buffer.position()); buffer.position(initialPosition); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ByteBufferUtils.moveBufferToStream(bos, buffer, array.length); } catch (IOException e) { fail("IOException in testCopyToStream()"); } assertArrayEquals(array, bos.toByteArray()); assertEquals(initialPosition + array.length, buffer.position()); }
### Question: HttpServer implements FilterContainer { @Override public String toString() { return listener != null ? ("HttpServer at http: + (isAlive() ? STATE_DESCRIPTION_ALIVE : STATE_DESCRIPTION_NOT_LIVE)) : "Inactive HttpServer"; } HttpServer(String name, String bindAddress, int port, boolean findPort ); HttpServer(String name, String bindAddress, int port, boolean findPort, Configuration conf, Connector connector); HttpServer(String name, String bindAddress, int port, boolean findPort, Configuration conf, String[] pathSpecs); HttpServer(String name, String bindAddress, int port, boolean findPort, Configuration conf); HttpServer(String name, String bindAddress, int port, boolean findPort, Configuration conf, AccessControlList adminsAcl); HttpServer(String name, String bindAddress, int port, boolean findPort, Configuration conf, AccessControlList adminsAcl, Connector connector); HttpServer(String name, String bindAddress, int port, boolean findPort, Configuration conf, AccessControlList adminsAcl, Connector connector, String[] pathSpecs); Connector createBaseListener(Configuration conf); @InterfaceAudience.Private static Connector createDefaultChannelConnector(); void addContext(Context ctxt, boolean isFiltered); void setAttribute(String name, Object value); void addJerseyResourcePackage(final String packageName, final String pathSpec); void addServlet(String name, String pathSpec, Class<? extends HttpServlet> clazz); void addInternalServlet(String name, String pathSpec, Class<? extends HttpServlet> clazz); void addInternalServlet(String name, String pathSpec, Class<? extends HttpServlet> clazz, boolean requireAuth); void addFilter(String name, String classname, Map<String, String> parameters); void addGlobalFilter(String name, String classname, Map<String, String> parameters); Object getAttribute(String name); int getPort(); void setThreads(int min, int max); @Deprecated void addSslListener(InetSocketAddress addr, String keystore, String storPass, String keyPass); void addSslListener(InetSocketAddress addr, Configuration sslConf, boolean needCertsAuth); void start(); InetSocketAddress getListenerAddress(); void stop(); void join(); boolean isAlive(); @Override String toString(); static boolean isInstrumentationAccessAllowed( ServletContext servletContext, HttpServletRequest request, HttpServletResponse response); static boolean hasAdministratorAccess( ServletContext servletContext, HttpServletRequest request, HttpServletResponse response); static boolean userHasAdministratorAccess(ServletContext servletContext, String remoteUser); static final Log LOG; static final String CONF_CONTEXT_ATTRIBUTE; static final String ADMINS_ACL; static final String SPNEGO_FILTER; static final String NO_CACHE_FILTER; static final String BIND_ADDRESS; }### Answer: @Test public void testLongHeader() throws Exception { URL url = new URL(baseUrl, "/longheader"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); StringBuilder sb = new StringBuilder(); for (int i = 0 ; i < 63 * 1024; i++) { sb.append("a"); } conn.setRequestProperty("longheader", sb.toString()); assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); }
### Question: DataChecksum implements Checksum { public static DataChecksum newDataChecksum( int type, int bytesPerChecksum ) { if ( bytesPerChecksum <= 0 ) { return null; } switch ( type ) { case CHECKSUM_NULL : return new DataChecksum( CHECKSUM_NULL, new ChecksumNull(), CHECKSUM_NULL_SIZE, bytesPerChecksum ); case CHECKSUM_CRC32 : return new DataChecksum( CHECKSUM_CRC32, new PureJavaCrc32(), CHECKSUM_CRC32_SIZE, bytesPerChecksum ); case CHECKSUM_CRC32C: return new DataChecksum( CHECKSUM_CRC32C, new PureJavaCrc32C(), CHECKSUM_CRC32C_SIZE, bytesPerChecksum); default: return null; } } private DataChecksum( int checksumType, Checksum checksum, int sumSize, int chunkSize ); static DataChecksum newDataChecksum( int type, int bytesPerChecksum ); static DataChecksum newDataChecksum( byte bytes[], int offset ); static DataChecksum newDataChecksum( DataInputStream in ); void writeHeader( DataOutputStream out ); byte[] getHeader(); int writeValue( DataOutputStream out, boolean reset ); int writeValue( byte[] buf, int offset, boolean reset ); boolean compare( byte buf[], int offset ); int getChecksumType(); int getChecksumSize(); int getBytesPerChecksum(); int getNumBytesInSum(); static int getChecksumHeaderSize(); long getValue(); void reset(); void update( byte[] b, int off, int len ); void update( int b ); void verifyChunkedSums(ByteBuffer data, ByteBuffer checksums, String fileName, long basePos); void calculateChunkedSums(ByteBuffer data, ByteBuffer checksums); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); static String getNameOfType(int checksumType); static int getTypeFromName(String checksumName); static final int HEADER_LEN; static final int CHECKSUM_NULL; static final int CHECKSUM_CRC32; static final int CHECKSUM_CRC32C; static final int CHECKSUM_DEFAULT; static final int CHECKSUM_MIXED; static final int SIZE_OF_INTEGER; }### Answer: @Test public void testBulkOps() throws Exception { for (int type : CHECKSUM_TYPES) { System.err.println( "---- beginning tests with checksum type " + type + "----"); DataChecksum checksum = DataChecksum.newDataChecksum( type, BYTES_PER_CHUNK); for (boolean useDirect : new boolean[]{false, true}) { doBulkTest(checksum, 1023, useDirect); doBulkTest(checksum, 1024, useDirect); doBulkTest(checksum, 1025, useDirect); } } }
### Question: DataChecksum implements Checksum { @Override public String toString() { String strType = getNameOfType(type); return "DataChecksum(type=" + strType + ", chunkSize=" + bytesPerChecksum + ")"; } private DataChecksum( int checksumType, Checksum checksum, int sumSize, int chunkSize ); static DataChecksum newDataChecksum( int type, int bytesPerChecksum ); static DataChecksum newDataChecksum( byte bytes[], int offset ); static DataChecksum newDataChecksum( DataInputStream in ); void writeHeader( DataOutputStream out ); byte[] getHeader(); int writeValue( DataOutputStream out, boolean reset ); int writeValue( byte[] buf, int offset, boolean reset ); boolean compare( byte buf[], int offset ); int getChecksumType(); int getChecksumSize(); int getBytesPerChecksum(); int getNumBytesInSum(); static int getChecksumHeaderSize(); long getValue(); void reset(); void update( byte[] b, int off, int len ); void update( int b ); void verifyChunkedSums(ByteBuffer data, ByteBuffer checksums, String fileName, long basePos); void calculateChunkedSums(ByteBuffer data, ByteBuffer checksums); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); static String getNameOfType(int checksumType); static int getTypeFromName(String checksumName); static final int HEADER_LEN; static final int CHECKSUM_NULL; static final int CHECKSUM_CRC32; static final int CHECKSUM_CRC32C; static final int CHECKSUM_DEFAULT; static final int CHECKSUM_MIXED; static final int SIZE_OF_INTEGER; }### Answer: @Test public void testToString() { assertEquals("DataChecksum(type=CRC32, chunkSize=512)", DataChecksum.newDataChecksum(DataChecksum.CHECKSUM_CRC32, 512) .toString()); }
### Question: HostsFileReader { public synchronized void refresh() throws IOException { LOG.info("Refreshing hosts (include/exclude) list"); if (!includesFile.equals("")) { Set<String> newIncludes = new HashSet<String>(); readFileToSet(includesFile, newIncludes); includes = newIncludes; } if (!excludesFile.equals("")) { Set<String> newExcludes = new HashSet<String>(); readFileToSet(excludesFile, newExcludes); excludes = newExcludes; } } HostsFileReader(String inFile, String exFile); synchronized void refresh(); synchronized Set<String> getHosts(); synchronized Set<String> getExcludedHosts(); synchronized void setIncludesFile(String includesFile); synchronized void setExcludesFile(String excludesFile); synchronized void updateFileNames(String includesFile, String excludesFile); }### Answer: @Test public void testRefreshHostFileReaderWithNonexistentFile() throws Exception { FileWriter efw = new FileWriter(excludesFile); FileWriter ifw = new FileWriter(includesFile); efw.close(); ifw.close(); HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile); assertTrue(INCLUDES_FILE.delete()); try { hfp.refresh(); Assert.fail("Should throw FileNotFoundException"); } catch (FileNotFoundException ex) { } }
### Question: ByteBufferUtils { public static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length) throws IOException { if (in.hasArray()) { out.write(in.array(), in.arrayOffset() + offset, length); } else { for (int i = 0; i < length; ++i) { out.write(in.get(offset + i)); } } } private ByteBufferUtils(); static void writeVLong(ByteBuffer out, long i); static long readVLong(ByteBuffer in); static int putCompressedInt(OutputStream out, final int value); static void putInt(OutputStream out, final int value); static void moveBufferToStream(OutputStream out, ByteBuffer in, int length); static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length); static int putLong(OutputStream out, final long value, final int fitInBytes); static int longFitsIn(final long value); static int intFitsIn(final int value); static int readCompressedInt(InputStream input); static int readCompressedInt(ByteBuffer buffer); static long readLong(InputStream in, final int fitInBytes); static long readLong(ByteBuffer in, final int fitInBytes); static void ensureSpace(ByteBuffer out, int length); static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length); static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length); static int findCommonPrefix(ByteBuffer buffer, int offsetLeft, int offsetRight, int limit); static int findCommonPrefix( byte[] left, int leftOffset, int leftLength, byte[] right, int rightOffset, int rightLength); static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight); static void skip(ByteBuffer buffer, int length); }### Answer: @Test public void testCopyToStreamWithOffset() throws IOException { ByteBuffer buffer = ByteBuffer.wrap(array); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteBufferUtils.copyBufferToStream(bos, buffer, array.length / 2, array.length / 2); byte[] returnedArray = bos.toByteArray(); for (int i = 0; i < array.length / 2; ++i) { int pos = array.length / 2 + i; assertEquals(returnedArray[i], array[pos]); } }
### Question: StringUtils { public static String escapeString(String str) { return escapeString(str, ESCAPE_CHAR, COMMA); } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String camelize(String s); static final int SHUTDOWN_HOOK_PRIORITY; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test public void testEscapeString() throws Exception { assertEquals(NULL_STR, StringUtils.escapeString(NULL_STR)); assertEquals(EMPTY_STR, StringUtils.escapeString(EMPTY_STR)); assertEquals(STR_WO_SPECIAL_CHARS, StringUtils.escapeString(STR_WO_SPECIAL_CHARS)); assertEquals(ESCAPED_STR_WITH_COMMA, StringUtils.escapeString(STR_WITH_COMMA)); assertEquals(ESCAPED_STR_WITH_ESCAPE, StringUtils.escapeString(STR_WITH_ESCAPE)); assertEquals(ESCAPED_STR_WITH_BOTH2, StringUtils.escapeString(STR_WITH_BOTH2)); }
### Question: StringUtils { public static String[] split(String str) { return split(str, ESCAPE_CHAR, COMMA); } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String camelize(String s); static final int SHUTDOWN_HOOK_PRIORITY; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test public void testSplit() throws Exception { assertEquals(NULL_STR, StringUtils.split(NULL_STR)); String[] splits = StringUtils.split(EMPTY_STR); assertEquals(0, splits.length); splits = StringUtils.split(",,"); assertEquals(0, splits.length); splits = StringUtils.split(STR_WO_SPECIAL_CHARS); assertEquals(1, splits.length); assertEquals(STR_WO_SPECIAL_CHARS, splits[0]); splits = StringUtils.split(STR_WITH_COMMA); assertEquals(2, splits.length); assertEquals("A", splits[0]); assertEquals("B", splits[1]); splits = StringUtils.split(ESCAPED_STR_WITH_COMMA); assertEquals(1, splits.length); assertEquals(ESCAPED_STR_WITH_COMMA, splits[0]); splits = StringUtils.split(STR_WITH_ESCAPE); assertEquals(1, splits.length); assertEquals(STR_WITH_ESCAPE, splits[0]); splits = StringUtils.split(STR_WITH_BOTH2); assertEquals(3, splits.length); assertEquals(EMPTY_STR, splits[0]); assertEquals("A\\,", splits[1]); assertEquals("B\\\\", splits[2]); splits = StringUtils.split(ESCAPED_STR_WITH_BOTH2); assertEquals(1, splits.length); assertEquals(ESCAPED_STR_WITH_BOTH2, splits[0]); } @Test public void testSimpleSplit() throws Exception { final String[] TO_TEST = { "a/b/c", "a/b/c " "", "/", " for (String testSubject : TO_TEST) { assertArrayEquals("Testing '" + testSubject + "'", testSubject.split("/"), StringUtils.split(testSubject, '/')); } }
### Question: StringUtils { public static String unEscapeString(String str) { return unEscapeString(str, ESCAPE_CHAR, COMMA); } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String camelize(String s); static final int SHUTDOWN_HOOK_PRIORITY; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test public void testUnescapeString() throws Exception { assertEquals(NULL_STR, StringUtils.unEscapeString(NULL_STR)); assertEquals(EMPTY_STR, StringUtils.unEscapeString(EMPTY_STR)); assertEquals(STR_WO_SPECIAL_CHARS, StringUtils.unEscapeString(STR_WO_SPECIAL_CHARS)); try { StringUtils.unEscapeString(STR_WITH_COMMA); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { } assertEquals(STR_WITH_COMMA, StringUtils.unEscapeString(ESCAPED_STR_WITH_COMMA)); try { StringUtils.unEscapeString(STR_WITH_ESCAPE); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { } assertEquals(STR_WITH_ESCAPE, StringUtils.unEscapeString(ESCAPED_STR_WITH_ESCAPE)); try { StringUtils.unEscapeString(STR_WITH_BOTH2); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { } assertEquals(STR_WITH_BOTH2, StringUtils.unEscapeString(ESCAPED_STR_WITH_BOTH2)); }
### Question: StringUtils { public static String join(CharSequence separator, Iterable<?> strings) { Iterator<?> i = strings.iterator(); if (!i.hasNext()) { return ""; } StringBuilder sb = new StringBuilder(i.next().toString()); while (i.hasNext()) { sb.append(separator); sb.append(i.next().toString()); } return sb.toString(); } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String camelize(String s); static final int SHUTDOWN_HOOK_PRIORITY; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test public void testJoin() { List<String> s = new ArrayList<String>(); s.add("a"); s.add("b"); s.add("c"); assertEquals("", StringUtils.join(":", s.subList(0, 0))); assertEquals("a", StringUtils.join(":", s.subList(0, 1))); assertEquals("a:b", StringUtils.join(":", s.subList(0, 2))); assertEquals("a:b:c", StringUtils.join(":", s.subList(0, 3))); }
### Question: StringUtils { public static String[] getTrimmedStrings(String str){ if (null == str || "".equals(str.trim())) { return emptyStringArray; } return str.trim().split("\\s*,\\s*"); } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String camelize(String s); static final int SHUTDOWN_HOOK_PRIORITY; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test public void testGetTrimmedStrings() throws Exception { String compactDirList = "/spindle1/hdfs,/spindle2/hdfs,/spindle3/hdfs"; String spacedDirList = "/spindle1/hdfs, /spindle2/hdfs, /spindle3/hdfs"; String pathologicalDirList1 = " /spindle1/hdfs , /spindle2/hdfs ,/spindle3/hdfs "; String pathologicalDirList2 = " /spindle1/hdfs , /spindle2/hdfs ,/spindle3/hdfs , "; String emptyList1 = ""; String emptyList2 = " "; String[] expectedArray = {"/spindle1/hdfs", "/spindle2/hdfs", "/spindle3/hdfs"}; String[] emptyArray = {}; assertArrayEquals(expectedArray, StringUtils.getTrimmedStrings(compactDirList)); assertArrayEquals(expectedArray, StringUtils.getTrimmedStrings(spacedDirList)); assertArrayEquals(expectedArray, StringUtils.getTrimmedStrings(pathologicalDirList1)); assertArrayEquals(expectedArray, StringUtils.getTrimmedStrings(pathologicalDirList2)); assertArrayEquals(emptyArray, StringUtils.getTrimmedStrings(emptyList1)); assertArrayEquals(emptyArray, StringUtils.getTrimmedStrings(emptyList2)); }
### Question: StringUtils { public static URI[] stringToURI(String[] str){ if (str == null) return null; URI[] uris = new URI[str.length]; for (int i = 0; i < str.length;i++){ try{ uris[i] = new URI(str[i]); }catch(URISyntaxException ur){ throw new IllegalArgumentException( "Failed to create uri for " + str[i], ur); } } return uris; } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String camelize(String s); static final int SHUTDOWN_HOOK_PRIORITY; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test public void testStringToURI() { String[] str = new String[] { "file: try { StringUtils.stringToURI(str); fail("Ignoring URISyntaxException while creating URI from string file: } catch (IllegalArgumentException iae) { assertEquals("Failed to create uri for file: } }
### Question: ByteBufferUtils { public static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length) throws IOException { if (out.hasArray()) { in.readFully(out.array(), out.position() + out.arrayOffset(), length); skip(out, length); } else { for (int i = 0; i < length; ++i) { out.put(in.readByte()); } } } private ByteBufferUtils(); static void writeVLong(ByteBuffer out, long i); static long readVLong(ByteBuffer in); static int putCompressedInt(OutputStream out, final int value); static void putInt(OutputStream out, final int value); static void moveBufferToStream(OutputStream out, ByteBuffer in, int length); static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length); static int putLong(OutputStream out, final long value, final int fitInBytes); static int longFitsIn(final long value); static int intFitsIn(final int value); static int readCompressedInt(InputStream input); static int readCompressedInt(ByteBuffer buffer); static long readLong(InputStream in, final int fitInBytes); static long readLong(ByteBuffer in, final int fitInBytes); static void ensureSpace(ByteBuffer out, int length); static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length); static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length); static int findCommonPrefix(ByteBuffer buffer, int offsetLeft, int offsetRight, int limit); static int findCommonPrefix( byte[] left, int leftOffset, int leftLength, byte[] right, int rightOffset, int rightLength); static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight); static void skip(ByteBuffer buffer, int length); }### Answer: @Test public void testCopyFromStream() throws IOException { ByteBuffer buffer = ByteBuffer.allocate(array.length); ByteArrayInputStream bis = new ByteArrayInputStream(array); DataInputStream dis = new DataInputStream(bis); ByteBufferUtils.copyFromStreamToBuffer(buffer, dis, array.length / 2); ByteBufferUtils.copyFromStreamToBuffer(buffer, dis, array.length - array.length / 2); for (int i = 0; i < array.length; ++i) { assertEquals(array[i], buffer.get(i)); } }
### Question: StringUtils { public static String simpleHostname(String fullHostname) { if (InetAddresses.isInetAddress(fullHostname)) { return fullHostname; } int offset = fullHostname.indexOf('.'); if (offset != -1) { return fullHostname.substring(0, offset); } return fullHostname; } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String camelize(String s); static final int SHUTDOWN_HOOK_PRIORITY; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test public void testSimpleHostName() { assertEquals("Should return hostname when FQDN is specified", "hadoop01", StringUtils.simpleHostname("hadoop01.domain.com")); assertEquals("Should return hostname when only hostname is specified", "hadoop01", StringUtils.simpleHostname("hadoop01")); assertEquals("Should not truncate when IP address is passed", "10.10.5.68", StringUtils.simpleHostname("10.10.5.68")); }
### Question: VersionUtil { public static int compareVersions(String version1, String version2) { boolean isSnapshot1 = version1.endsWith(SNAPSHOT_SUFFIX); boolean isSnapshot2 = version2.endsWith(SNAPSHOT_SUFFIX); version1 = stripSnapshotSuffix(version1); version2 = stripSnapshotSuffix(version2); String[] version1Parts = version1.split("\\."); String[] version2Parts = version2.split("\\."); for (int i = 0; i < version1Parts.length && i < version2Parts.length; i++) { String component1 = version1Parts[i]; String component2 = version2Parts[i]; if (!component1.equals(component2)) { Matcher matcher1 = COMPONENT_GROUPS.matcher(component1); Matcher matcher2 = COMPONENT_GROUPS.matcher(component2); while (matcher1.find() && matcher2.find()) { String group1 = matcher1.group(); String group2 = matcher2.group(); if (!group1.equals(group2)) { if (isNumeric(group1) && isNumeric(group2)) { return Integer.parseInt(group1) - Integer.parseInt(group2); } else if (!isNumeric(group1) && !isNumeric(group2)) { return group1.compareTo(group2); } else { return isNumeric(group1) ? -1 : 1; } } } return component1.length() - component2.length(); } } return ComparisonChain.start() .compare(version1Parts.length, version2Parts.length) .compare(isSnapshot2, isSnapshot1) .result(); } static int compareVersions(String version1, String version2); }### Answer: @Test public void testCompareVersions() { assertEquals(0, VersionUtil.compareVersions("2.0.0", "2.0.0")); assertEquals(0, VersionUtil.compareVersions("2.0.0a", "2.0.0a")); assertEquals(0, VersionUtil.compareVersions("1", "1")); assertEquals(0, VersionUtil.compareVersions( "2.0.0-SNAPSHOT", "2.0.0-SNAPSHOT")); assertExpectedValues("1", "2.0.0"); assertExpectedValues("1.0.0", "2"); assertExpectedValues("1.0.0", "2.0.0"); assertExpectedValues("1.0", "2.0.0"); assertExpectedValues("1.0.0", "2.0.0"); assertExpectedValues("1.0.0", "1.0.0a"); assertExpectedValues("1.0.0.0", "2.0.0"); assertExpectedValues("1.0.0", "1.0.0-dev"); assertExpectedValues("1.0.0", "1.0.1"); assertExpectedValues("1.0.0", "1.0.2"); assertExpectedValues("1.0.0", "1.1.0"); assertExpectedValues("2.0.0", "10.0.0"); assertExpectedValues("1.0.0", "1.0.0a"); assertExpectedValues("1.0.2a", "1.0.10"); assertExpectedValues("1.0.2a", "1.0.2b"); assertExpectedValues("1.0.2a", "1.0.2ab"); assertExpectedValues("1.0.0a1", "1.0.0a2"); assertExpectedValues("1.0.0a2", "1.0.0a10"); assertExpectedValues("1.0", "1.a"); assertExpectedValues("1.0", "1.a0"); assertExpectedValues("1.0-SNAPSHOT", "1.0"); assertExpectedValues("1.0", "1.0.0-SNAPSHOT"); assertExpectedValues("1.0.0-SNAPSHOT", "1.0.0"); assertExpectedValues("1.0.0", "1.0.1-SNAPSHOT"); assertExpectedValues("1.0.1-SNAPSHOT", "1.0.1"); }
### Question: NativeLibraryChecker { public static void main(String[] args) { String usage = "NativeLibraryChecker [-a|-h]\n" + " -a use -a to check all libraries are available\n" + " by default just check hadoop library is available\n" + " exit with error code if check failed\n" + " -h print this message\n"; if (args.length > 1 || (args.length == 1 && !(args[0].equals("-a") || args[0].equals("-h")))) { System.err.println(usage); ExitUtil.terminate(1); } boolean checkAll = false; if (args.length == 1) { if (args[0].equals("-h")) { System.out.println(usage); return; } checkAll = true; } boolean nativeHadoopLoaded = NativeCodeLoader.isNativeCodeLoaded(); boolean zlibLoaded = false; boolean snappyLoaded = false; boolean lz4Loaded = nativeHadoopLoaded; if (nativeHadoopLoaded) { zlibLoaded = ZlibFactory.isNativeZlibLoaded(new Configuration()); snappyLoaded = NativeCodeLoader.buildSupportsSnappy() && SnappyCodec.isNativeCodeLoaded(); } System.out.println("Native library checking:"); System.out.printf("hadoop: %b\n", nativeHadoopLoaded); System.out.printf("zlib: %b\n", zlibLoaded); System.out.printf("snappy: %b\n", snappyLoaded); System.out.printf("lz4: %b\n", lz4Loaded); if ((!nativeHadoopLoaded) || (checkAll && !(zlibLoaded && snappyLoaded && lz4Loaded))) { ExitUtil.terminate(1); } } static void main(String[] args); }### Answer: @Test public void testNativeLibraryChecker() { ExitUtil.disableSystemExit(); NativeLibraryChecker.main(new String[] {"-h"}); expectExit(new String[] {"-a", "-h"}); expectExit(new String[] {"aaa"}); if (NativeCodeLoader.isNativeCodeLoaded()) { NativeLibraryChecker.main(new String[0]); } else { expectExit(new String[0]); } }
### Question: NativeCodeLoader { public static boolean isNativeCodeLoaded() { return nativeCodeLoaded; } static boolean isNativeCodeLoaded(); static native boolean buildSupportsSnappy(); boolean getLoadNativeLibraries(Configuration conf); void setLoadNativeLibraries(Configuration conf, boolean loadNativeLibraries); }### Answer: @Test public void testNativeCodeLoaded() { if (requireTestJni() == false) { LOG.info("TestNativeCodeLoader: libhadoop.so testing is not required."); return; } if (!NativeCodeLoader.isNativeCodeLoaded()) { fail("TestNativeCodeLoader: libhadoop.so testing was required, but " + "libhadoop.so was not loaded."); } LOG.info("TestNativeCodeLoader: libhadoop.so is loaded."); }
### Question: ClassUtil { public static String findContainingJar(Class clazz) { ClassLoader loader = clazz.getClassLoader(); String classFile = clazz.getName().replaceAll("\\.", "/") + ".class"; try { for (Enumeration itr = loader.getResources(classFile); itr.hasMoreElements();) { URL url = (URL) itr.nextElement(); if ("jar".equals(url.getProtocol())) { String toReturn = url.getPath(); if (toReturn.startsWith("file:")) { toReturn = toReturn.substring("file:".length()); } toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } return null; } static String findContainingJar(Class clazz); }### Answer: @Test(timeout=1000) public void testFindContainingJar() { String containingJar = ClassUtil.findContainingJar(Logger.class); Assert.assertNotNull("Containing jar not found for Logger", containingJar); File jarFile = new File(containingJar); Assert.assertTrue("Containing jar does not exist on file system", jarFile.exists()); Assert.assertTrue("Incorrect jar file" + containingJar, jarFile.getName().matches("log4j.+[.]jar")); }
### Question: ByteBufferUtils { public static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length) { if (in.hasArray() && out.hasArray()) { System.arraycopy(in.array(), sourceOffset + in.arrayOffset(), out.array(), out.position() + out.arrayOffset(), length); skip(out, length); } else { for (int i = 0; i < length; ++i) { out.put(in.get(sourceOffset + i)); } } } private ByteBufferUtils(); static void writeVLong(ByteBuffer out, long i); static long readVLong(ByteBuffer in); static int putCompressedInt(OutputStream out, final int value); static void putInt(OutputStream out, final int value); static void moveBufferToStream(OutputStream out, ByteBuffer in, int length); static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length); static int putLong(OutputStream out, final long value, final int fitInBytes); static int longFitsIn(final long value); static int intFitsIn(final int value); static int readCompressedInt(InputStream input); static int readCompressedInt(ByteBuffer buffer); static long readLong(InputStream in, final int fitInBytes); static long readLong(ByteBuffer in, final int fitInBytes); static void ensureSpace(ByteBuffer out, int length); static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length); static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length); static int findCommonPrefix(ByteBuffer buffer, int offsetLeft, int offsetRight, int limit); static int findCommonPrefix( byte[] left, int leftOffset, int leftLength, byte[] right, int rightOffset, int rightLength); static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight); static void skip(ByteBuffer buffer, int length); }### Answer: @Test public void testCopyFromBuffer() { ByteBuffer srcBuffer = ByteBuffer.allocate(array.length); ByteBuffer dstBuffer = ByteBuffer.allocate(array.length); srcBuffer.put(array); ByteBufferUtils.copyFromBufferToBuffer(dstBuffer, srcBuffer, array.length / 2, array.length / 4); for (int i = 0; i < array.length / 4; ++i) { assertEquals(srcBuffer.get(i + array.length / 2), dstBuffer.get(i)); } }
### Question: NodeFencer { public boolean fence(HAServiceTarget fromSvc) { LOG.info("====== Beginning Service Fencing Process... ======"); int i = 0; for (FenceMethodWithArg method : methods) { LOG.info("Trying method " + (++i) + "/" + methods.size() +": " + method); try { if (method.method.tryFence(fromSvc, method.arg)) { LOG.info("====== Fencing successful by method " + method + " ======"); return true; } } catch (BadFencingConfigurationException e) { LOG.error("Fencing method " + method + " misconfigured", e); continue; } catch (Throwable t) { LOG.error("Fencing method " + method + " failed with an unexpected error.", t); continue; } LOG.warn("Fencing method " + method + " was unsuccessful."); } LOG.error("Unable to fence service by any configured method."); return false; } NodeFencer(Configuration conf, String spec); static NodeFencer create(Configuration conf, String confKey); boolean fence(HAServiceTarget fromSvc); }### Answer: @Test public void testShortNameShell() throws BadFencingConfigurationException { NodeFencer fencer = setupFencer("shell(true)"); assertTrue(fencer.fence(MOCK_TARGET)); }
### Question: ShellCommandFencer extends Configured implements FenceMethod { @Override public boolean tryFence(HAServiceTarget target, String cmd) { ProcessBuilder builder = new ProcessBuilder( "bash", "-e", "-c", cmd); setConfAsEnvVars(builder.environment()); addTargetInfoAsEnvVars(target, builder.environment()); Process p; try { p = builder.start(); p.getOutputStream().close(); } catch (IOException e) { LOG.warn("Unable to execute " + cmd, e); return false; } String pid = tryGetPid(p); LOG.info("Launched fencing command '" + cmd + "' with " + ((pid != null) ? ("pid " + pid) : "unknown pid")); String logPrefix = abbreviate(cmd, ABBREV_LENGTH); if (pid != null) { logPrefix = "[PID " + pid + "] " + logPrefix; } StreamPumper errPumper = new StreamPumper( LOG, logPrefix, p.getErrorStream(), StreamPumper.StreamType.STDERR); errPumper.start(); StreamPumper outPumper = new StreamPumper( LOG, logPrefix, p.getInputStream(), StreamPumper.StreamType.STDOUT); outPumper.start(); int rc; try { rc = p.waitFor(); errPumper.join(); outPumper.join(); } catch (InterruptedException ie) { LOG.warn("Interrupted while waiting for fencing command: " + cmd); return false; } return rc == 0; } @Override void checkArgs(String args); @Override boolean tryFence(HAServiceTarget target, String cmd); }### Answer: @Test public void testBasicSuccessFailure() { assertTrue(fencer.tryFence(TEST_TARGET, "echo")); assertFalse(fencer.tryFence(TEST_TARGET, "exit 1")); assertFalse(fencer.tryFence(TEST_TARGET, "xxxxxxxxxxxx")); } @Test public void testStdoutLogging() { assertTrue(fencer.tryFence(TEST_TARGET, "echo hello")); Mockito.verify(ShellCommandFencer.LOG).info( Mockito.endsWith("echo hello: hello")); } @Test public void testStderrLogging() { assertTrue(fencer.tryFence(TEST_TARGET, "echo hello >&2")); Mockito.verify(ShellCommandFencer.LOG).warn( Mockito.endsWith("echo hello >&2: hello")); } @Test public void testConfAsEnvironment() { fencer.tryFence(TEST_TARGET, "echo $in_fencing_tests"); Mockito.verify(ShellCommandFencer.LOG).info( Mockito.endsWith("echo $in...ing_tests: yessir")); } @Test public void testTargetAsEnvironment() { fencer.tryFence(TEST_TARGET, "echo $target_host $target_port $target_address"); Mockito.verify(ShellCommandFencer.LOG).info( Mockito.endsWith("echo $ta...t_address: host 1234 host:1234")); } @Test(timeout=10000) public void testSubprocessInputIsClosed() { assertFalse(fencer.tryFence(TEST_TARGET, "read")); }
### Question: ByteBufferUtils { public static int intFitsIn(final int value) { if (value < 0) { return 4; } if (value < (1 << 2 * 8)) { if (value < (1 << 1 * 8)) { return 1; } return 2; } if (value <= (1 << 3 * 8)) { return 3; } return 4; } private ByteBufferUtils(); static void writeVLong(ByteBuffer out, long i); static long readVLong(ByteBuffer in); static int putCompressedInt(OutputStream out, final int value); static void putInt(OutputStream out, final int value); static void moveBufferToStream(OutputStream out, ByteBuffer in, int length); static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length); static int putLong(OutputStream out, final long value, final int fitInBytes); static int longFitsIn(final long value); static int intFitsIn(final int value); static int readCompressedInt(InputStream input); static int readCompressedInt(ByteBuffer buffer); static long readLong(InputStream in, final int fitInBytes); static long readLong(ByteBuffer in, final int fitInBytes); static void ensureSpace(ByteBuffer out, int length); static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length); static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length); static int findCommonPrefix(ByteBuffer buffer, int offsetLeft, int offsetRight, int limit); static int findCommonPrefix( byte[] left, int leftOffset, int leftLength, byte[] right, int rightOffset, int rightLength); static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight); static void skip(ByteBuffer buffer, int length); }### Answer: @Test public void testIntFitsIn() { assertEquals(1, ByteBufferUtils.intFitsIn(0)); assertEquals(1, ByteBufferUtils.intFitsIn(1)); assertEquals(2, ByteBufferUtils.intFitsIn(1 << 8)); assertEquals(3, ByteBufferUtils.intFitsIn(1 << 16)); assertEquals(4, ByteBufferUtils.intFitsIn(-1)); assertEquals(4, ByteBufferUtils.intFitsIn(Integer.MAX_VALUE)); assertEquals(4, ByteBufferUtils.intFitsIn(Integer.MIN_VALUE)); }
### Question: HAZKUtil { public static List<ACL> parseACLs(String aclString) { List<ACL> acl = Lists.newArrayList(); if (aclString == null) { return acl; } List<String> aclComps = Lists.newArrayList( Splitter.on(',').omitEmptyStrings().trimResults() .split(aclString)); for (String a : aclComps) { int firstColon = a.indexOf(':'); int lastColon = a.lastIndexOf(':'); if (firstColon == -1 || lastColon == -1 || firstColon == lastColon) { throw new BadAclFormatException( "ACL '" + a + "' not of expected form scheme:id:perm"); } ACL newAcl = new ACL(); newAcl.setId(new Id(a.substring(0, firstColon), a.substring( firstColon + 1, lastColon))); newAcl.setPerms(getPermFromString(a.substring(lastColon + 1))); acl.add(newAcl); } return acl; } static List<ACL> parseACLs(String aclString); static List<ZKAuthInfo> parseAuth(String authString); static String resolveConfIndirection(String valInConf); }### Answer: @Test public void testEmptyACL() { List<ACL> result = HAZKUtil.parseACLs(""); assertTrue(result.isEmpty()); } @Test public void testNullACL() { List<ACL> result = HAZKUtil.parseACLs(null); assertTrue(result.isEmpty()); } @Test public void testGoodACLs() { List<ACL> result = HAZKUtil.parseACLs( "sasl:hdfs/[email protected]:cdrwa, sasl:hdfs/[email protected]:ca"); ACL acl0 = result.get(0); assertEquals(Perms.CREATE | Perms.DELETE | Perms.READ | Perms.WRITE | Perms.ADMIN, acl0.getPerms()); assertEquals("sasl", acl0.getId().getScheme()); assertEquals("hdfs/[email protected]", acl0.getId().getId()); ACL acl1 = result.get(1); assertEquals(Perms.CREATE | Perms.ADMIN, acl1.getPerms()); assertEquals("sasl", acl1.getId().getScheme()); assertEquals("hdfs/[email protected]", acl1.getId().getId()); }
### Question: HAZKUtil { public static List<ZKAuthInfo> parseAuth(String authString) { List<ZKAuthInfo> ret = Lists.newArrayList(); if (authString == null) { return ret; } List<String> authComps = Lists.newArrayList( Splitter.on(',').omitEmptyStrings().trimResults() .split(authString)); for (String comp : authComps) { String parts[] = comp.split(":", 2); if (parts.length != 2) { throw new BadAuthFormatException( "Auth '" + comp + "' not of expected form scheme:auth"); } ret.add(new ZKAuthInfo(parts[0], parts[1].getBytes(Charsets.UTF_8))); } return ret; } static List<ACL> parseACLs(String aclString); static List<ZKAuthInfo> parseAuth(String authString); static String resolveConfIndirection(String valInConf); }### Answer: @Test public void testEmptyAuth() { List<ZKAuthInfo> result = HAZKUtil.parseAuth(""); assertTrue(result.isEmpty()); } @Test public void testNullAuth() { List<ZKAuthInfo> result = HAZKUtil.parseAuth(null); assertTrue(result.isEmpty()); } @Test public void testGoodAuths() { List<ZKAuthInfo> result = HAZKUtil.parseAuth( "scheme:data,\n scheme2:user:pass"); assertEquals(2, result.size()); ZKAuthInfo auth0 = result.get(0); assertEquals("scheme", auth0.getScheme()); assertEquals("data", new String(auth0.getAuth())); ZKAuthInfo auth1 = result.get(1); assertEquals("scheme2", auth1.getScheme()); assertEquals("user:pass", new String(auth1.getAuth())); }
### Question: ByteBufferUtils { public static int longFitsIn(final long value) { if (value < 0) { return 8; } if (value < (1l << 4 * 8)) { if (value < (1l << 2 * 8)) { if (value < (1l << 1 * 8)) { return 1; } return 2; } if (value < (1l << 3 * 8)) { return 3; } return 4; } if (value < (1l << 6 * 8)) { if (value < (1l << 5 * 8)) { return 5; } return 6; } if (value < (1l << 7 * 8)) { return 7; } return 8; } private ByteBufferUtils(); static void writeVLong(ByteBuffer out, long i); static long readVLong(ByteBuffer in); static int putCompressedInt(OutputStream out, final int value); static void putInt(OutputStream out, final int value); static void moveBufferToStream(OutputStream out, ByteBuffer in, int length); static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length); static int putLong(OutputStream out, final long value, final int fitInBytes); static int longFitsIn(final long value); static int intFitsIn(final int value); static int readCompressedInt(InputStream input); static int readCompressedInt(ByteBuffer buffer); static long readLong(InputStream in, final int fitInBytes); static long readLong(ByteBuffer in, final int fitInBytes); static void ensureSpace(ByteBuffer out, int length); static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length); static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length); static int findCommonPrefix(ByteBuffer buffer, int offsetLeft, int offsetRight, int limit); static int findCommonPrefix( byte[] left, int leftOffset, int leftLength, byte[] right, int rightOffset, int rightLength); static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight); static void skip(ByteBuffer buffer, int length); }### Answer: @Test public void testLongFitsIn() { assertEquals(1, ByteBufferUtils.longFitsIn(0)); assertEquals(1, ByteBufferUtils.longFitsIn(1)); assertEquals(3, ByteBufferUtils.longFitsIn(1l << 16)); assertEquals(5, ByteBufferUtils.longFitsIn(1l << 32)); assertEquals(8, ByteBufferUtils.longFitsIn(-1)); assertEquals(8, ByteBufferUtils.longFitsIn(Long.MIN_VALUE)); assertEquals(8, ByteBufferUtils.longFitsIn(Long.MAX_VALUE)); }
### Question: HAZKUtil { public static String resolveConfIndirection(String valInConf) throws IOException { if (valInConf == null) return null; if (!valInConf.startsWith("@")) { return valInConf; } String path = valInConf.substring(1).trim(); return Files.toString(new File(path), Charsets.UTF_8).trim(); } static List<ACL> parseACLs(String aclString); static List<ZKAuthInfo> parseAuth(String authString); static String resolveConfIndirection(String valInConf); }### Answer: @Test public void testConfIndirection() throws IOException { assertNull(HAZKUtil.resolveConfIndirection(null)); assertEquals("x", HAZKUtil.resolveConfIndirection("x")); TEST_FILE.getParentFile().mkdirs(); Files.write("hello world", TEST_FILE, Charsets.UTF_8); assertEquals("hello world", HAZKUtil.resolveConfIndirection( "@" + TEST_FILE.getAbsolutePath())); try { HAZKUtil.resolveConfIndirection("@" + BOGUS_FILE); fail("Did not throw for non-existent file reference"); } catch (FileNotFoundException fnfe) { assertTrue(fnfe.getMessage().startsWith(BOGUS_FILE)); } }
### Question: ActiveStandbyElector implements StatCallback, StringCallback { public synchronized void joinElection(byte[] data) throws HadoopIllegalArgumentException { if (data == null) { throw new HadoopIllegalArgumentException("data cannot be null"); } if (wantToBeInElection) { LOG.info("Already in election. Not re-connecting."); return; } appData = new byte[data.length]; System.arraycopy(data, 0, appData, 0, data.length); LOG.debug("Attempting active election for " + this); joinElectionInternal(); } ActiveStandbyElector(String zookeeperHostPorts, int zookeeperSessionTimeout, String parentZnodeName, List<ACL> acl, List<ZKAuthInfo> authInfo, ActiveStandbyElectorCallback app); synchronized void joinElection(byte[] data); synchronized boolean parentZNodeExists(); synchronized void ensureParentZNode(); synchronized void clearParentZNode(); synchronized void quitElection(boolean needFence); synchronized byte[] getActiveData(); @Override synchronized void processResult(int rc, String path, Object ctx, String name); @Override synchronized void processResult(int rc, String path, Object ctx, Stat stat); @Override String toString(); static final Log LOG; }### Answer: @Test(expected = HadoopIllegalArgumentException.class) public void testJoinElectionException() { elector.joinElection(null); } @Test public void testJoinElection() { elector.joinElection(data); Mockito.verify(mockZK, Mockito.times(1)).create(ZK_LOCK_NAME, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK); }
### Question: ActiveStandbyElector implements StatCallback, StringCallback { public synchronized void quitElection(boolean needFence) { LOG.info("Yielding from election"); if (!needFence && state == State.ACTIVE) { tryDeleteOwnBreadCrumbNode(); } reset(); wantToBeInElection = false; } ActiveStandbyElector(String zookeeperHostPorts, int zookeeperSessionTimeout, String parentZnodeName, List<ACL> acl, List<ZKAuthInfo> authInfo, ActiveStandbyElectorCallback app); synchronized void joinElection(byte[] data); synchronized boolean parentZNodeExists(); synchronized void ensureParentZNode(); synchronized void clearParentZNode(); synchronized void quitElection(boolean needFence); synchronized byte[] getActiveData(); @Override synchronized void processResult(int rc, String path, Object ctx, String name); @Override synchronized void processResult(int rc, String path, Object ctx, Stat stat); @Override String toString(); static final Log LOG; }### Answer: @Test public void testQuitElection() throws Exception { elector.joinElection(data); Mockito.verify(mockZK, Mockito.times(0)).close(); elector.quitElection(true); Mockito.verify(mockZK, Mockito.times(1)).close(); verifyExistCall(0); byte[] data = new byte[8]; elector.joinElection(data); Assert.assertEquals(2, count); elector.processResult(Code.NODEEXISTS.intValue(), ZK_LOCK_NAME, mockZK, ZK_LOCK_NAME); Mockito.verify(mockApp, Mockito.times(1)).becomeStandby(); verifyExistCall(1); }
### Question: ActiveStandbyElector implements StatCallback, StringCallback { public synchronized byte[] getActiveData() throws ActiveNotFoundException, KeeperException, InterruptedException, IOException { try { if (zkClient == null) { createConnection(); } Stat stat = new Stat(); return getDataWithRetries(zkLockFilePath, false, stat); } catch(KeeperException e) { Code code = e.code(); if (isNodeDoesNotExist(code)) { throw new ActiveNotFoundException(); } else { throw e; } } } ActiveStandbyElector(String zookeeperHostPorts, int zookeeperSessionTimeout, String parentZnodeName, List<ACL> acl, List<ZKAuthInfo> authInfo, ActiveStandbyElectorCallback app); synchronized void joinElection(byte[] data); synchronized boolean parentZNodeExists(); synchronized void ensureParentZNode(); synchronized void clearParentZNode(); synchronized void quitElection(boolean needFence); synchronized byte[] getActiveData(); @Override synchronized void processResult(int rc, String path, Object ctx, String name); @Override synchronized void processResult(int rc, String path, Object ctx, Stat stat); @Override String toString(); static final Log LOG; }### Answer: @Test public void testGetActiveData() throws ActiveNotFoundException, KeeperException, InterruptedException, IOException { byte[] data = new byte[8]; Mockito.when( mockZK.getData(Mockito.eq(ZK_LOCK_NAME), Mockito.eq(false), Mockito.<Stat> anyObject())).thenReturn(data); Assert.assertEquals(data, elector.getActiveData()); Mockito.verify(mockZK, Mockito.times(1)).getData( Mockito.eq(ZK_LOCK_NAME), Mockito.eq(false), Mockito.<Stat> anyObject()); Mockito.when( mockZK.getData(Mockito.eq(ZK_LOCK_NAME), Mockito.eq(false), Mockito.<Stat> anyObject())).thenThrow( new KeeperException.NoNodeException()); try { elector.getActiveData(); Assert.fail("ActiveNotFoundException expected"); } catch(ActiveNotFoundException e) { Mockito.verify(mockZK, Mockito.times(2)).getData( Mockito.eq(ZK_LOCK_NAME), Mockito.eq(false), Mockito.<Stat> anyObject()); } try { Mockito.when( mockZK.getData(Mockito.eq(ZK_LOCK_NAME), Mockito.eq(false), Mockito.<Stat> anyObject())).thenThrow( new KeeperException.AuthFailedException()); elector.getActiveData(); Assert.fail("KeeperException.AuthFailedException expected"); } catch(KeeperException.AuthFailedException ke) { Mockito.verify(mockZK, Mockito.times(3)).getData( Mockito.eq(ZK_LOCK_NAME), Mockito.eq(false), Mockito.<Stat> anyObject()); } }
### Question: ActiveStandbyElector implements StatCallback, StringCallback { public synchronized void ensureParentZNode() throws IOException, InterruptedException { Preconditions.checkState(!wantToBeInElection, "ensureParentZNode() may not be called while in the election"); String pathParts[] = znodeWorkingDir.split("/"); Preconditions.checkArgument(pathParts.length >= 1 && "".equals(pathParts[0]), "Invalid path: %s", znodeWorkingDir); StringBuilder sb = new StringBuilder(); for (int i = 1; i < pathParts.length; i++) { sb.append("/").append(pathParts[i]); String prefixPath = sb.toString(); LOG.debug("Ensuring existence of " + prefixPath); try { createWithRetries(prefixPath, new byte[]{}, zkAcl, CreateMode.PERSISTENT); } catch (KeeperException e) { if (isNodeExists(e.code())) { continue; } else { throw new IOException("Couldn't create " + prefixPath, e); } } } LOG.info("Successfully created " + znodeWorkingDir + " in ZK."); } ActiveStandbyElector(String zookeeperHostPorts, int zookeeperSessionTimeout, String parentZnodeName, List<ACL> acl, List<ZKAuthInfo> authInfo, ActiveStandbyElectorCallback app); synchronized void joinElection(byte[] data); synchronized boolean parentZNodeExists(); synchronized void ensureParentZNode(); synchronized void clearParentZNode(); synchronized void quitElection(boolean needFence); synchronized byte[] getActiveData(); @Override synchronized void processResult(int rc, String path, Object ctx, String name); @Override synchronized void processResult(int rc, String path, Object ctx, Stat stat); @Override String toString(); static final Log LOG; }### Answer: @Test public void testEnsureBaseNodeFails() throws Exception { Mockito.doThrow(new KeeperException.ConnectionLossException()) .when(mockZK).create( Mockito.eq(ZK_PARENT_NAME), Mockito.<byte[]>any(), Mockito.eq(Ids.OPEN_ACL_UNSAFE), Mockito.eq(CreateMode.PERSISTENT)); try { elector.ensureParentZNode(); Assert.fail("Did not throw!"); } catch (IOException ioe) { if (!(ioe.getCause() instanceof KeeperException.ConnectionLossException)) { throw ioe; } } Mockito.verify(mockZK, Mockito.times(3)).create( Mockito.eq(ZK_PARENT_NAME), Mockito.<byte[]>any(), Mockito.eq(Ids.OPEN_ACL_UNSAFE), Mockito.eq(CreateMode.PERSISTENT)); }
### Question: ActiveStandbyElector implements StatCallback, StringCallback { synchronized void processWatchEvent(ZooKeeper zk, WatchedEvent event) { Event.EventType eventType = event.getType(); if (isStaleClient(zk)) return; LOG.debug("Watcher event type: " + eventType + " with state:" + event.getState() + " for path:" + event.getPath() + " connectionState: " + zkConnectionState + " for " + this); if (eventType == Event.EventType.None) { switch (event.getState()) { case SyncConnected: LOG.info("Session connected."); ConnectionState prevConnectionState = zkConnectionState; zkConnectionState = ConnectionState.CONNECTED; if (prevConnectionState == ConnectionState.DISCONNECTED && wantToBeInElection) { monitorActiveStatus(); } break; case Disconnected: LOG.info("Session disconnected. Entering neutral mode..."); zkConnectionState = ConnectionState.DISCONNECTED; enterNeutralMode(); break; case Expired: LOG.info("Session expired. Entering neutral mode and rejoining..."); enterNeutralMode(); reJoinElection(0); break; default: fatalError("Unexpected Zookeeper watch event state: " + event.getState()); break; } return; } String path = event.getPath(); if (path != null) { switch (eventType) { case NodeDeleted: if (state == State.ACTIVE) { enterNeutralMode(); } joinElectionInternal(); break; case NodeDataChanged: monitorActiveStatus(); break; default: LOG.debug("Unexpected node event: " + eventType + " for path: " + path); monitorActiveStatus(); } return; } fatalError("Unexpected watch error from Zookeeper"); } ActiveStandbyElector(String zookeeperHostPorts, int zookeeperSessionTimeout, String parentZnodeName, List<ACL> acl, List<ZKAuthInfo> authInfo, ActiveStandbyElectorCallback app); synchronized void joinElection(byte[] data); synchronized boolean parentZNodeExists(); synchronized void ensureParentZNode(); synchronized void clearParentZNode(); synchronized void quitElection(boolean needFence); synchronized byte[] getActiveData(); @Override synchronized void processResult(int rc, String path, Object ctx, String name); @Override synchronized void processResult(int rc, String path, Object ctx, Stat stat); @Override String toString(); static final Log LOG; }### Answer: @Test public void testBecomeActiveBeforeServiceHealthy() throws Exception { mockNoPriorActive(); WatchedEvent mockEvent = Mockito.mock(WatchedEvent.class); Mockito.when(mockEvent.getType()).thenReturn(Event.EventType.None); Mockito.when(mockEvent.getState()).thenReturn(Event.KeeperState.Expired); elector.processWatchEvent(mockZK, mockEvent); Mockito.verify(mockZK, Mockito.times(0)).create(ZK_LOCK_NAME, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK); }
### Question: ByteBufferUtils { public static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight) { if (lengthLeft != lengthRight) { return false; } if (buffer.hasArray()) { return 0 == Bytes.compareTo( buffer.array(), buffer.arrayOffset() + offsetLeft, lengthLeft, buffer.array(), buffer.arrayOffset() + offsetRight, lengthRight); } for (int i = 0; i < lengthRight; ++i) { if (buffer.get(offsetLeft + i) != buffer.get(offsetRight + i)) { return false; } } return true; } private ByteBufferUtils(); static void writeVLong(ByteBuffer out, long i); static long readVLong(ByteBuffer in); static int putCompressedInt(OutputStream out, final int value); static void putInt(OutputStream out, final int value); static void moveBufferToStream(OutputStream out, ByteBuffer in, int length); static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length); static int putLong(OutputStream out, final long value, final int fitInBytes); static int longFitsIn(final long value); static int intFitsIn(final int value); static int readCompressedInt(InputStream input); static int readCompressedInt(ByteBuffer buffer); static long readLong(InputStream in, final int fitInBytes); static long readLong(ByteBuffer in, final int fitInBytes); static void ensureSpace(ByteBuffer out, int length); static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length); static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length); static int findCommonPrefix(ByteBuffer buffer, int offsetLeft, int offsetRight, int limit); static int findCommonPrefix( byte[] left, int leftOffset, int leftLength, byte[] right, int rightOffset, int rightLength); static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight); static void skip(ByteBuffer buffer, int length); }### Answer: @Test public void testArePartEqual() { byte[] array = new byte[] { 1, 2, 3, 4, 5, 1, 2, 3, 4 }; ByteBuffer buffer = ByteBuffer.wrap(array); assertTrue(ByteBufferUtils.arePartsEqual(buffer, 0, 4, 5, 4)); assertTrue(ByteBufferUtils.arePartsEqual(buffer, 1, 2, 6, 2)); assertFalse(ByteBufferUtils.arePartsEqual(buffer, 1, 2, 6, 3)); assertFalse(ByteBufferUtils.arePartsEqual(buffer, 1, 3, 6, 2)); assertFalse(ByteBufferUtils.arePartsEqual(buffer, 0, 3, 6, 3)); }
### Question: HAAdmin extends Configured implements Tool { private int help(String[] argv) { if (argv.length == 1) { printUsage(out); return 0; } else if (argv.length != 2) { printUsage(errOut, "-help"); return -1; } String cmd = argv[1]; if (!cmd.startsWith("-")) { cmd = "-" + cmd; } UsageInfo usageInfo = USAGE.get(cmd); if (usageInfo == null) { errOut.println(cmd + ": Unknown command"); printUsage(errOut); return -1; } out.println(cmd + " [" + usageInfo.args + "]: " + usageInfo.help); return 0; } @Override void setConf(Configuration conf); @Override int run(String[] argv); }### Answer: @Test public void testHelp() throws Exception { assertEquals(0, runTool("-help")); assertEquals(0, runTool("-help", "transitionToActive")); assertOutputContains("Transitions the service into Active"); }
### Question: HealthMonitor { public void addCallback(Callback cb) { this.callbacks.add(cb); } HealthMonitor(Configuration conf, HAServiceTarget target); void addCallback(Callback cb); void removeCallback(Callback cb); void shutdown(); synchronized HAServiceProtocol getProxy(); }### Answer: @Test(timeout=15000) public void testCallbackThrowsRTE() throws Exception { hm.addCallback(new Callback() { @Override public void enteredState(State newState) { throw new RuntimeException("Injected RTE"); } }); LOG.info("Mocking bad health check, waiting for UNHEALTHY"); svc.isHealthy = false; waitForState(hm, HealthMonitor.State.HEALTH_MONITOR_FAILED); }
### Question: ByteBufferUtils { public static void putInt(OutputStream out, final int value) throws IOException { for (int i = Bytes.SIZEOF_INT - 1; i >= 0; --i) { out.write((byte) (value >>> (i * 8))); } } private ByteBufferUtils(); static void writeVLong(ByteBuffer out, long i); static long readVLong(ByteBuffer in); static int putCompressedInt(OutputStream out, final int value); static void putInt(OutputStream out, final int value); static void moveBufferToStream(OutputStream out, ByteBuffer in, int length); static void copyBufferToStream(OutputStream out, ByteBuffer in, int offset, int length); static int putLong(OutputStream out, final long value, final int fitInBytes); static int longFitsIn(final long value); static int intFitsIn(final int value); static int readCompressedInt(InputStream input); static int readCompressedInt(ByteBuffer buffer); static long readLong(InputStream in, final int fitInBytes); static long readLong(ByteBuffer in, final int fitInBytes); static void ensureSpace(ByteBuffer out, int length); static void copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length); static void copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length); static int findCommonPrefix(ByteBuffer buffer, int offsetLeft, int offsetRight, int limit); static int findCommonPrefix( byte[] left, int leftOffset, int leftLength, byte[] right, int rightOffset, int rightLength); static boolean arePartsEqual(ByteBuffer buffer, int offsetLeft, int lengthLeft, int offsetRight, int lengthRight); static void skip(ByteBuffer buffer, int length); }### Answer: @Test public void testPutInt() { testPutInt(0); testPutInt(Integer.MAX_VALUE); for (int i = 0; i < 3; i++) { testPutInt((128 << i) - 1); } for (int i = 0; i < 3; i++) { testPutInt((128 << i)); } }
### Question: IOUtils { public static void writeFully(WritableByteChannel bc, ByteBuffer buf) throws IOException { do { bc.write(buf); } while (buf.remaining() > 0); } static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close); static void copyBytes(InputStream in, OutputStream out, int buffSize); static void copyBytes(InputStream in, OutputStream out, Configuration conf); static void copyBytes(InputStream in, OutputStream out, Configuration conf, boolean close); static void copyBytes(InputStream in, OutputStream out, long count, boolean close); static int wrappedReadForCompressedData(InputStream is, byte[] buf, int off, int len); static void readFully(InputStream in, byte buf[], int off, int len); static void skipFully(InputStream in, long len); static void cleanup(Log log, java.io.Closeable... closeables); static void closeStream(java.io.Closeable stream); static void closeSocket(Socket sock); static void writeFully(WritableByteChannel bc, ByteBuffer buf); static void writeFully(FileChannel fc, ByteBuffer buf, long offset); }### Answer: @Test public void testWriteFully() throws IOException { final int INPUT_BUFFER_LEN = 10000; final int HALFWAY = 1 + (INPUT_BUFFER_LEN / 2); byte[] input = new byte[INPUT_BUFFER_LEN]; for (int i = 0; i < input.length; i++) { input[i] = (byte)(i & 0xff); } byte[] output = new byte[input.length]; try { RandomAccessFile raf = new RandomAccessFile(TEST_FILE_NAME, "rw"); FileChannel fc = raf.getChannel(); ByteBuffer buf = ByteBuffer.wrap(input); IOUtils.writeFully(fc, buf); raf.seek(0); raf.read(output); for (int i = 0; i < input.length; i++) { assertEquals(input[i], output[i]); } buf.rewind(); IOUtils.writeFully(fc, buf, HALFWAY); for (int i = 0; i < HALFWAY; i++) { assertEquals(input[i], output[i]); } raf.seek(0); raf.read(output); for (int i = HALFWAY; i < input.length; i++) { assertEquals(input[i - HALFWAY], output[i]); } } finally { File f = new File(TEST_FILE_NAME); if (f.exists()) { f.delete(); } } }
### Question: IOUtils { public static int wrappedReadForCompressedData(InputStream is, byte[] buf, int off, int len) throws IOException { try { return is.read(buf, off, len); } catch (IOException ie) { throw ie; } catch (Throwable t) { throw new IOException("Error while reading compressed data", t); } } static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close); static void copyBytes(InputStream in, OutputStream out, int buffSize); static void copyBytes(InputStream in, OutputStream out, Configuration conf); static void copyBytes(InputStream in, OutputStream out, Configuration conf, boolean close); static void copyBytes(InputStream in, OutputStream out, long count, boolean close); static int wrappedReadForCompressedData(InputStream is, byte[] buf, int off, int len); static void readFully(InputStream in, byte buf[], int off, int len); static void skipFully(InputStream in, long len); static void cleanup(Log log, java.io.Closeable... closeables); static void closeStream(java.io.Closeable stream); static void closeSocket(Socket sock); static void writeFully(WritableByteChannel bc, ByteBuffer buf); static void writeFully(FileChannel fc, ByteBuffer buf, long offset); }### Answer: @Test public void testWrappedReadForCompressedData() throws IOException { byte[] buf = new byte[2]; InputStream mockStream = Mockito.mock(InputStream.class); Mockito.when(mockStream.read(buf, 0, 1)).thenReturn(1); Mockito.when(mockStream.read(buf, 0, 2)).thenThrow( new java.lang.InternalError()); try { assertEquals("Check expected value", 1, IOUtils.wrappedReadForCompressedData(mockStream, buf, 0, 1)); } catch (IOException ioe) { fail("Unexpected error while reading"); } try { IOUtils.wrappedReadForCompressedData(mockStream, buf, 0, 2); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains( "Error while reading compressed data", ioe); } }
### Question: IOUtils { public static void skipFully(InputStream in, long len) throws IOException { long amt = len; while (amt > 0) { long ret = in.skip(amt); if (ret == 0) { int b = in.read(); if (b == -1) { throw new EOFException( "Premature EOF from inputStream after " + "skipping " + (len - amt) + " byte(s)."); } ret = 1; } amt -= ret; } } static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close); static void copyBytes(InputStream in, OutputStream out, int buffSize); static void copyBytes(InputStream in, OutputStream out, Configuration conf); static void copyBytes(InputStream in, OutputStream out, Configuration conf, boolean close); static void copyBytes(InputStream in, OutputStream out, long count, boolean close); static int wrappedReadForCompressedData(InputStream is, byte[] buf, int off, int len); static void readFully(InputStream in, byte buf[], int off, int len); static void skipFully(InputStream in, long len); static void cleanup(Log log, java.io.Closeable... closeables); static void closeStream(java.io.Closeable stream); static void closeSocket(Socket sock); static void writeFully(WritableByteChannel bc, ByteBuffer buf); static void writeFully(FileChannel fc, ByteBuffer buf, long offset); }### Answer: @Test public void testSkipFully() throws IOException { byte inArray[] = new byte[] {0, 1, 2, 3, 4}; ByteArrayInputStream in = new ByteArrayInputStream(inArray); try { in.mark(inArray.length); IOUtils.skipFully(in, 2); IOUtils.skipFully(in, 2); try { IOUtils.skipFully(in, 2); fail("expected to get a PrematureEOFException"); } catch (EOFException e) { assertEquals(e.getMessage(), "Premature EOF from inputStream " + "after skipping 1 byte(s)."); } in.reset(); try { IOUtils.skipFully(in, 20); fail("expected to get a PrematureEOFException"); } catch (EOFException e) { assertEquals(e.getMessage(), "Premature EOF from inputStream " + "after skipping 5 byte(s)."); } in.reset(); IOUtils.skipFully(in, 5); try { IOUtils.skipFully(in, 10); fail("expected to get a PrematureEOFException"); } catch (EOFException e) { assertEquals(e.getMessage(), "Premature EOF from inputStream " + "after skipping 0 byte(s)."); } } finally { in.close(); } }
### Question: SecureIOUtils { static FileInputStream forceSecureOpenForRead(File f, String expectedOwner, String expectedGroup) throws IOException { FileInputStream fis = new FileInputStream(f); boolean success = false; try { Stat stat = NativeIO.getFstat(fis.getFD()); checkStat(f, stat.getOwner(), stat.getGroup(), expectedOwner, expectedGroup); success = true; return fis; } finally { if (!success) { fis.close(); } } } static FileInputStream openForRead(File f, String expectedOwner, String expectedGroup); static FileOutputStream createForWrite(File f, int permissions); }### Answer: @Test public void testReadIncorrectlyRestrictedWithSecurity() throws IOException { assumeTrue(NativeIO.isAvailable()); System.out.println("Running test with native libs..."); try { SecureIOUtils .forceSecureOpenForRead(testFilePath, "invalidUser", null).close(); fail("Didn't throw expection for wrong ownership!"); } catch (IOException ioe) { } }
### Question: FSVisitor { public static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor) throws IOException { FileStatus[] regions = FSUtils.listStatus(fs, tableDir, new FSUtils.RegionDirFilter(fs)); if (regions == null) { LOG.info("No regions under directory:" + tableDir); return; } for (FileStatus region: regions) { visitRegionStoreFiles(fs, region.getPath(), visitor); } } private FSVisitor(); static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor); static void visitRegionStoreFiles(final FileSystem fs, final Path regionDir, final StoreFileVisitor visitor); static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitRegionRecoveredEdits(final FileSystem fs, final Path regionDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor); }### Answer: @Test public void testVisitStoreFiles() throws IOException { final Set<String> regions = new HashSet<String>(); final Set<String> families = new HashSet<String>(); final Set<String> hfiles = new HashSet<String>(); FSVisitor.visitTableStoreFiles(fs, tableDir, new FSVisitor.StoreFileVisitor() { public void storeFile(final String region, final String family, final String hfileName) throws IOException { regions.add(region); families.add(family); hfiles.add(hfileName); } }); assertEquals(tableRegions, regions); assertEquals(tableFamilies, families); assertEquals(tableHFiles, hfiles); }
### Question: NativeIO { private static native Stat fstat(FileDescriptor fd) throws IOException; static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testFstat() throws Exception { FileOutputStream fos = new FileOutputStream( new File(TEST_DIR, "testfstat")); NativeIO.Stat stat = NativeIO.getFstat(fos.getFD()); fos.close(); LOG.info("Stat: " + String.valueOf(stat)); assertEquals(System.getProperty("user.name"), stat.getOwner()); assertNotNull(stat.getGroup()); assertTrue(!"".equals(stat.getGroup())); assertEquals("Stat mode field should indicate a regular file", NativeIO.Stat.S_IFREG, stat.getMode() & NativeIO.Stat.S_IFMT); }
### Question: NativeIO { public static Stat getFstat(FileDescriptor fd) throws IOException { Stat stat = fstat(fd); stat.owner = getName(IdCache.USER, stat.ownerId); stat.group = getName(IdCache.GROUP, stat.groupId); return stat; } static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testMultiThreadedFstat() throws Exception { final FileOutputStream fos = new FileOutputStream( new File(TEST_DIR, "testfstat")); final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>(); List<Thread> statters = new ArrayList<Thread>(); for (int i = 0; i < 10; i++) { Thread statter = new Thread() { public void run() { long et = Time.now() + 5000; while (Time.now() < et) { try { NativeIO.Stat stat = NativeIO.getFstat(fos.getFD()); assertEquals(System.getProperty("user.name"), stat.getOwner()); assertNotNull(stat.getGroup()); assertTrue(!"".equals(stat.getGroup())); assertEquals("Stat mode field should indicate a regular file", NativeIO.Stat.S_IFREG, stat.getMode() & NativeIO.Stat.S_IFMT); } catch (Throwable t) { thrown.set(t); } } } }; statters.add(statter); statter.start(); } for (Thread t : statters) { t.join(); } fos.close(); if (thrown.get() != null) { throw new RuntimeException(thrown.get()); } } @Test public void testFstatClosedFd() throws Exception { FileOutputStream fos = new FileOutputStream( new File(TEST_DIR, "testfstat2")); fos.close(); try { NativeIO.Stat stat = NativeIO.getFstat(fos.getFD()); } catch (NativeIOException nioe) { LOG.info("Got expected exception", nioe); assertEquals(Errno.EBADF, nioe.getErrno()); } }
### Question: NativeIO { public static native FileDescriptor open(String path, int flags, int mode) throws IOException; static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testOpenMissingWithoutCreate() throws Exception { LOG.info("Open a missing file without O_CREAT and it should fail"); try { FileDescriptor fd = NativeIO.open( new File(TEST_DIR, "doesntexist").getAbsolutePath(), NativeIO.O_WRONLY, 0700); fail("Able to open a new file without O_CREAT"); } catch (NativeIOException nioe) { LOG.info("Got expected exception", nioe); assertEquals(Errno.ENOENT, nioe.getErrno()); } } @Test public void testOpenWithCreate() throws Exception { LOG.info("Test creating a file with O_CREAT"); FileDescriptor fd = NativeIO.open( new File(TEST_DIR, "testWorkingOpen").getAbsolutePath(), NativeIO.O_WRONLY | NativeIO.O_CREAT, 0700); assertNotNull(true); assertTrue(fd.valid()); FileOutputStream fos = new FileOutputStream(fd); fos.write("foo".getBytes()); fos.close(); assertFalse(fd.valid()); LOG.info("Test exclusive create"); try { fd = NativeIO.open( new File(TEST_DIR, "testWorkingOpen").getAbsolutePath(), NativeIO.O_WRONLY | NativeIO.O_CREAT | NativeIO.O_EXCL, 0700); fail("Was able to create existing file with O_EXCL"); } catch (NativeIOException nioe) { LOG.info("Got expected exception for failed exclusive create", nioe); assertEquals(Errno.EEXIST, nioe.getErrno()); } } @Test public void testFDDoesntLeak() throws IOException { for (int i = 0; i < 10000; i++) { FileDescriptor fd = NativeIO.open( new File(TEST_DIR, "testNoFdLeak").getAbsolutePath(), NativeIO.O_WRONLY | NativeIO.O_CREAT, 0700); assertNotNull(true); assertTrue(fd.valid()); FileOutputStream fos = new FileOutputStream(fd); fos.write("foo".getBytes()); fos.close(); } }
### Question: NativeIO { public static native void chmod(String path, int mode) throws IOException; static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testChmod() throws Exception { try { NativeIO.chmod("/this/file/doesnt/exist", 777); fail("Chmod of non-existent file didn't fail"); } catch (NativeIOException nioe) { assertEquals(Errno.ENOENT, nioe.getErrno()); } File toChmod = new File(TEST_DIR, "testChmod"); assertTrue("Create test subject", toChmod.exists() || toChmod.mkdir()); NativeIO.chmod(toChmod.getAbsolutePath(), 0777); assertPermissions(toChmod, 0777); NativeIO.chmod(toChmod.getAbsolutePath(), 0000); assertPermissions(toChmod, 0000); NativeIO.chmod(toChmod.getAbsolutePath(), 0644); assertPermissions(toChmod, 0644); }