_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q160600
HttpImageUploadStream.flushBuffer
train
private void flushBuffer(boolean close) { for (HttpImageUploadChannel ch : uploadChannels) { ch.send(buffer); } if (!close) { // allocate new buffer, since the old one is used by the channels for // reading buffer = new ByteArrayOutputStream((int) (1.2 * flushSize)); } }
java
{ "resource": "" }
q160601
JobClient.getFs
train
public synchronized FileSystem getFs() throws IOException { if (this.fs == null) { Path sysDir = getSystemDir(); this.fs = sysDir.getFileSystem(getConf()); } return fs; }
java
{ "resource": "" }
q160602
JobClient.copyRemoteFiles
train
private Path copyRemoteFiles(FileSystem jtFs, Path parentDir, Path originalPath, JobConf job, short replication, String md5) throws IOException { //check if we do not need to copy the files // is jt using the same file system. // just checking for uri strings... doing no dns lookups // to see if the filesystems are the same. This is not optimal. // but avoids name resolution. FileSystem remoteFs = null; remoteFs = originalPath.getFileSystem(job); if (compareFs(remoteFs, jtFs)) { return originalPath; } // This function is overloaded to support cache sharing when enabled if (md5 != null) { // Check if file already exists in cache Path basePath = parentDir; Path realPath = new Path(basePath, md5 + "_" + originalPath.getName()); Path qualifiedRealPath = realPath.makeQualified(jtFs); if (filesInCache.contains(qualifiedRealPath)) { // We "touch" the file to update its access time // This is done only 10% of the time to reduce load on the namenode if (r.nextLong() % 10 == 0) { try { jtFs.setTimes(realPath, -1, System.currentTimeMillis()); } catch (RemoteException e){ LOG.warn("Error in setTimes", e); } } return qualifiedRealPath; } // This loop should not even loop most of the time Path newPath; do { newPath = new Path(basePath, "tmp_" + originalPath.getName() + r.nextLong()); } while (jtFs.exists(newPath)); FileUtil.copy(remoteFs, originalPath, jtFs, newPath, false, job); jtFs.setReplication(newPath, replication); jtFs.setPermission(newPath, new FsPermission(JOB_DIR_PERMISSION)); LOG.info ("Uploading new shared jar: " + realPath.toString()); if (!jtFs.rename(newPath, realPath)) { // if there are multiple clients racing to upload the new jar - only // one of them will succeed. Check if we failed because the file already // exists. if so, ignore and move on if (!jtFs.exists(realPath)) throw new IOException ("Unable to upload or find shared jar: " + realPath.toString()); } // Update the list filesInCache.add(qualifiedRealPath); return qualifiedRealPath; } // this might have name collisions. copy will throw an exception // parse the original path to create new path Path newPath = new Path(parentDir, originalPath.getName()); FileUtil.copy(remoteFs, originalPath, jtFs, newPath, false, job); jtFs.setReplication(newPath, replication); return jtFs.makeQualified(newPath); }
java
{ "resource": "" }
q160603
JobClient.symLinkAndConfigureFiles
train
private void symLinkAndConfigureFiles(JobConf job) throws IOException { if (!(job.getBoolean("mapred.used.genericoptionsparser", false))) { LOG.warn("Use GenericOptionsParser for parsing the arguments. " + "Applications should implement Tool for the same."); } // get all the command line arguments into the // jobconf passed in by the user conf String files = job.get("tmpfiles"); String archives = job.get("tmparchives"); // "tmpjars" are not needed because its in the classpath List<String> filesToSymLink = new ArrayList<String>(); splitAndAdd(files, filesToSymLink); splitAndAdd(archives, filesToSymLink); for (String file : filesToSymLink) { String target = new Path(file).toUri().getPath(); String basename = new File(target).getName(); String linkName = new File(".").getAbsolutePath() + File.separator + basename; File toLink = new File(linkName); if (toLink.exists()) { LOG.info("Symlink " + linkName + " already exists. Delete it."); toLink.delete(); } int ret = FileUtil.symLink(target, linkName); LOG.info("Creating symlink " + linkName + " -> " + target + " returns " + ret + "."); } // Configure job name String originalJar = job.getJar(); if (originalJar != null) { // use jar name if job is not named. if ("".equals(job.getJobName())) { job.setJobName(new Path(originalJar).getName()); } } // Configure username configureUserName(job); }
java
{ "resource": "" }
q160604
JobClient.configureUserName
train
private void configureUserName(JobConf job) throws IOException { UnixUserGroupInformation ugi = getUGI(job); // Set the user's name, group and working directory job.setUser(ugi.getUserName()); if (ugi.getGroupNames() != null && ugi.getGroupNames().length > 0) { job.set("group.name", ugi.getGroupNames()[0]); } if (job.getWorkingDirectory() == null) { job.setWorkingDirectory(fs.getWorkingDirectory()); } }
java
{ "resource": "" }
q160605
JobClient.submitJob
train
public RunningJob submitJob(String jobFile) throws FileNotFoundException, InvalidJobConfException, IOException { // Load in the submitted job details JobConf job = new JobConf(jobFile); return submitJob(job); }
java
{ "resource": "" }
q160606
JobClient.submitJobInternal
train
public RunningJob submitJobInternal(JobConf job ) throws FileNotFoundException, ClassNotFoundException, InterruptedException, IOException { /* * configure the command line options correctly on the submitting dfs */ boolean shared = job.getBoolean("mapred.cache.shared.enabled", false); JobID jobId = jobSubmitClient.getNewJobId(); Path submitJobDir = new Path(getSystemDir(), jobId.toString()); Path sharedFilesDir = new Path(getSystemDir(), jobSubmitClient.CAR); Path submitSplitFile = new Path(submitJobDir, "job.split"); getFs(); if (jobSubmitClient instanceof LocalJobRunner) { symLinkAndConfigureFiles(job); } else { copyAndConfigureFiles(job, (shared) ? sharedFilesDir : submitJobDir, shared); } Path submitJobFile = new Path(submitJobDir, "job.xml"); int reduces = job.getNumReduceTasks(); JobContext context = new JobContext(job, jobId); // Check the output specification if (reduces == 0 ? job.getUseNewMapper() : job.getUseNewReducer()) { org.apache.hadoop.mapreduce.OutputFormat<?,?> output = ReflectionUtils.newInstance(context.getOutputFormatClass(), job); output.checkOutputSpecs(context); } else { job.getOutputFormat().checkOutputSpecs(fs, job); } // Create the splits for the job LOG.debug("Creating splits at " + fs.makeQualified(submitSplitFile)); List<RawSplit> maps; if (job.getUseNewMapper()) { maps = computeNewSplits(context); } else { maps = computeOldSplits(job); } job.setNumMapTasks(maps.size()); if (!isJobTrackerInProc) { JobConf conf = null; if (job.getUseNewMapper()) { conf = context.getJobConf(); } else { conf = job; } writeComputedSplits(conf, maps, submitSplitFile); job.set("mapred.job.split.file", submitSplitFile.toString()); } else { synchronized(JobClient.jobSplitCache) { if (JobClient.jobSplitCache.containsKey(jobId)) { throw new IOException("Job split already cached " + jobId); } JobClient.jobSplitCache.put(jobId, maps); } synchronized(JobClient.jobConfCache) { if (JobClient.jobConfCache.containsKey(jobId)) { throw new IOException("Job conf already cached " + jobId); } jobConfCache.put(jobId, job); } } // Write job file to JobTracker's fs FSDataOutputStream out = FileSystem.create(fs, submitJobFile, new FsPermission(JOB_FILE_PERMISSION)); try { job.writeXml(out); } finally { out.close(); } // // Now, actually submit the job (using the submit name) // JobStatus status = jobSubmitClient.submitJob(jobId); if (status != null) { return new NetworkedJob(status); } else { throw new IOException("Could not launch job"); } }
java
{ "resource": "" }
q160607
JobClient.validateNumberOfTasks
train
private void validateNumberOfTasks(int splits, int reduceTasks, JobConf conf) throws IOException { int maxTasks = conf.getInt("mapred.jobtracker.maxtasks.per.job", -1); int totalTasks = splits + reduceTasks; if ((maxTasks!= -1) && (totalTasks > maxTasks)) { throw new IOException( "The number of tasks for this job " + totalTasks + " exceeds the configured limit " + maxTasks); } }
java
{ "resource": "" }
q160608
JobClient.readSplitFile
train
static RawSplit[] readSplitFile(DataInput in) throws IOException { byte[] header = new byte[SPLIT_FILE_HEADER.length]; in.readFully(header); if (!Arrays.equals(SPLIT_FILE_HEADER, header)) { throw new IOException("Invalid header on split file"); } int vers = WritableUtils.readVInt(in); if (vers != CURRENT_SPLIT_FILE_VERSION) { throw new IOException("Unsupported split version " + vers); } int len = WritableUtils.readVInt(in); RawSplit[] result = new RawSplit[len]; for(int i=0; i < len; ++i) { result[i] = new RawSplit(); result[i].readFields(in); } return result; }
java
{ "resource": "" }
q160609
JobClient.displayTasks
train
public void displayTasks(JobID jobId, String type, String state) throws IOException { TaskReport[] reports = new TaskReport[0]; if (type.equals("map")) { reports = getMapTaskReports(jobId); } else if (type.equals("reduce")) { reports = getReduceTaskReports(jobId); } else if (type.equals("setup")) { reports = getSetupTaskReports(jobId); } else if (type.equals("cleanup")) { reports = getCleanupTaskReports(jobId); } for (TaskReport report : reports) { TIPStatus status = report.getCurrentStatus(); if ((state.equals("pending") && status ==TIPStatus.PENDING) || (state.equals("running") && status ==TIPStatus.RUNNING) || (state.equals("completed") && status == TIPStatus.COMPLETE) || (state.equals("failed") && status == TIPStatus.FAILED) || (state.equals("killed") && status == TIPStatus.KILLED)) { printTaskAttempts(report); } } }
java
{ "resource": "" }
q160610
JobClient.runJob
train
public static RunningJob runJob(JobConf job) throws IOException { JobClient jc = new JobClient(job); RunningJob rj = jc.submitJob(job); try { if (!jc.monitorAndPrintJob(job, rj)) { throw new IOException("Job failed!"); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } return rj; }
java
{ "resource": "" }
q160611
JobClient.monitorAndPrintJob
train
public boolean monitorAndPrintJob(JobConf conf, RunningJob job ) throws IOException, InterruptedException { String lastReport = null; TaskStatusFilter filter; filter = getTaskOutputFilter(conf); JobID jobId = job.getID(); LOG.info("Running job: " + jobId); int eventCounter = 0; boolean profiling = conf.getProfileEnabled(); Configuration.IntegerRanges mapRanges = conf.getProfileTaskRange(true); Configuration.IntegerRanges reduceRanges = conf.getProfileTaskRange(false); while (!job.isComplete()) { Thread.sleep(MAX_JOBPROFILE_AGE); String report = (" map " + StringUtils.formatPercent(job.mapProgress(), 0)+ " reduce " + StringUtils.formatPercent(job.reduceProgress(), 0)); if (!report.equals(lastReport)) { LOG.info(report); lastReport = report; } TaskCompletionEvent[] events = job.getTaskCompletionEvents(eventCounter); eventCounter += events.length; for(TaskCompletionEvent event : events){ TaskCompletionEvent.Status status = event.getTaskStatus(); if (profiling && (status == TaskCompletionEvent.Status.SUCCEEDED || status == TaskCompletionEvent.Status.FAILED) && (event.isMap ? mapRanges : reduceRanges). isIncluded(event.idWithinJob())) { downloadProfile(event); } switch(filter){ case NONE: break; case SUCCEEDED: if (event.getTaskStatus() == TaskCompletionEvent.Status.SUCCEEDED){ LOG.info(event.toString()); displayTaskLogs(event.getTaskAttemptId(), event.getTaskTrackerHttp()); } break; case FAILED: if (event.getTaskStatus() == TaskCompletionEvent.Status.FAILED){ LOG.info(event.toString()); // Displaying the task diagnostic information TaskAttemptID taskId = event.getTaskAttemptId(); String[] taskDiagnostics = jobSubmitClient.getTaskDiagnostics(taskId); if (taskDiagnostics != null) { for(String diagnostics : taskDiagnostics){ System.err.println(diagnostics); } } // Displaying the task logs displayTaskLogs(event.getTaskAttemptId(), event.getTaskTrackerHttp()); } break; case KILLED: if (event.getTaskStatus() == TaskCompletionEvent.Status.KILLED){ LOG.info(event.toString()); } break; case ALL: LOG.info(event.toString()); displayTaskLogs(event.getTaskAttemptId(), event.getTaskTrackerHttp()); break; } } } LOG.info("Job complete: " + jobId); Counters counters = job.getCounters(); if (counters != null) { counters.log(LOG); } return job.isSuccessful(); }
java
{ "resource": "" }
q160612
JobClient.listEvents
train
private void listEvents(JobID jobId, int fromEventId, int numEvents) throws IOException { TaskCompletionEvent[] events = jobSubmitClient.getTaskCompletionEvents(jobId, fromEventId, numEvents); System.out.println("Task completion events for " + jobId); System.out.println("Number of events (from " + fromEventId + ") are: " + events.length); for(TaskCompletionEvent event: events) { System.out.println(event.getTaskStatus() + " " + event.getTaskAttemptId() + " " + getTaskLogURL(event.getTaskAttemptId(), event.getTaskTrackerHttp())); } }
java
{ "resource": "" }
q160613
JobClient.listJobs
train
private void listJobs() throws IOException { JobStatus[] jobs = jobsToComplete(); if (jobs == null) jobs = new JobStatus[0]; System.out.printf("%d jobs currently running\n", jobs.length); displayJobList(jobs); }
java
{ "resource": "" }
q160614
JobClient.listAllJobs
train
private void listAllJobs() throws IOException { JobStatus[] jobs = getAllJobs(); if (jobs == null) jobs = new JobStatus[0]; System.out.printf("%d jobs submitted\n", jobs.length); System.out.printf("States are:\n\tRunning : 1\tSucceded : 2" + "\tFailed : 3\tPrep : 4\n"); displayJobList(jobs); }
java
{ "resource": "" }
q160615
JobClient.listActiveTrackers
train
private void listActiveTrackers() throws IOException { ClusterStatus c = jobSubmitClient.getClusterStatus(true); Collection<String> trackers = c.getActiveTrackerNames(); for (String trackerName : trackers) { System.out.println(trackerName); } }
java
{ "resource": "" }
q160616
JobClient.listBlacklistedTrackers
train
private void listBlacklistedTrackers() throws IOException { ClusterStatus c = jobSubmitClient.getClusterStatus(true); Collection<String> trackers = c.getBlacklistedTrackerNames(); for (String trackerName : trackers) { System.out.println(trackerName); } }
java
{ "resource": "" }
q160617
JobClient.listTrackers
train
private void listTrackers() throws IOException { ClusterStatus fullStatus = jobSubmitClient.getClusterStatus(true); Collection<TaskTrackerStatus> trackers = fullStatus.getTaskTrackersDetails(); Set<String> activeTrackers = new HashSet<String>(fullStatus.getActiveTrackerNames()); List<Float> mapsProgress = new ArrayList<Float>(); List<Float> reducesProgress = new ArrayList<Float>(); int finishedMapsFromRunningJobs = 0; int finishedReducesFromRunningJobs = 0; System.out.println("Total Map Tasks in Running Jobs: " + fullStatus.getTotalMapTasks()); System.out.println("Total Reduce Tasks in Running Jobs: " + fullStatus.getTotalReduceTasks()); for (TaskTrackerStatus tracker : trackers) { System.out.println(tracker.getTrackerName()); //List<TaskStatus> tasks = tracker.getTaskReports(); Collection<TaskStatus> tasks = fullStatus.getTaskTrackerTasksStatuses(tracker.getTrackerName()); for (TaskStatus task : tasks) { TaskStatus.State state = task.getRunState(); if (task.getIsMap() && (state == TaskStatus.State.RUNNING || state == TaskStatus.State.UNASSIGNED)) { mapsProgress.add(task.getProgress()); } else if (!task.getIsMap() && (state == TaskStatus.State.RUNNING || state == TaskStatus.State.UNASSIGNED)) { reducesProgress.add(task.getProgress()); } else if (task.getIsMap() && state == TaskStatus.State.SUCCEEDED) { finishedMapsFromRunningJobs++; } else if (!task.getIsMap() && state == TaskStatus.State.SUCCEEDED) { finishedReducesFromRunningJobs++; } } if (activeTrackers.contains(tracker.getTrackerName())) { System.out.println("\tActive"); } else { System.out.println("\tBlacklisted"); } System.out.println("\tLast Seen: " + tracker.getLastSeen()); System.out.println("\tMap Tasks Running: " + tracker.countMapTasks() + "/" + tracker.getMaxMapSlots()); System.out.println("\tMap Tasks Progress: " + mapsProgress.toString()); System.out.println("\tFinished Map Tasks From Running Jobs: " + finishedMapsFromRunningJobs); System.out.println("\tReduce Tasks Running: " + tracker.countReduceTasks() + "/" + tracker.getMaxReduceSlots()); System.out.println("\tReduce Tasks Progress: " + reducesProgress.toString()); System.out.println("\tTask Tracker Failures: " + tracker.getFailures()); mapsProgress.clear(); reducesProgress.clear(); } }
java
{ "resource": "" }
q160618
PathFinder.getAbsolutePath
train
public File getAbsolutePath(String filename) { if (pathenv == null || pathSep == null || fileSep == null) { return null; } int val = -1; String classvalue = pathenv + pathSep; while (((val = classvalue.indexOf(pathSep)) >= 0) && classvalue.length() > 0) { // // Extract each entry from the pathenv // String entry = classvalue.substring(0, val).trim(); File f = new File(entry); try { if (f.isDirectory()) { // // this entry in the pathenv is a directory. // see if the required file is in this directory // f = new File(entry + fileSep + filename); } // // see if the filename matches and we can read it // if (f.isFile() && f.canRead()) { return f; } } catch (Exception exp){ } classvalue = classvalue.substring(val+1).trim(); } return null; }
java
{ "resource": "" }
q160619
PathFinder.printSystemProperties
train
private static void printSystemProperties() { System.out.println("System properties: "); java.util.Properties p = System.getProperties(); java.util.Enumeration keys = p.keys(); while(keys.hasMoreElements()) { String thiskey = (String)keys.nextElement(); String value = p.getProperty(thiskey); System.out.println(thiskey + " = " + value); } }
java
{ "resource": "" }
q160620
DFSFile.downloadToLocalFile
train
public void downloadToLocalFile(final File file) throws InvocationTargetException, InterruptedException { PlatformUI.getWorkbench().getProgressService().busyCursorWhile( new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { DFSFile.this.downloadToLocalFile(monitor, file); } }); }
java
{ "resource": "" }
q160621
DFSFile.toDetailedString
train
public String toDetailedString() { final String[] units = { "b", "Kb", "Mb", "Gb", "Tb" }; int unit = 0; double l = this.length; while ((l >= 1024.0) && (unit < units.length)) { unit += 1; l /= 1024.0; } return String.format("%s (%.1f %s, r%d)", super.toString(), l, units[unit], this.replication); }
java
{ "resource": "" }
q160622
DFSFile.downloadToLocalFile
train
public void downloadToLocalFile(IProgressMonitor monitor, File file) throws InvocationTargetException { final int taskSize = 1024; monitor.setTaskName("Download file " + this.path); BufferedOutputStream ostream = null; DataInputStream istream = null; try { istream = getDFS().open(this.path); ostream = new BufferedOutputStream(new FileOutputStream(file)); int bytes; byte[] buffer = new byte[taskSize]; while ((bytes = istream.read(buffer)) >= 0) { if (monitor.isCanceled()) return; ostream.write(buffer, 0, bytes); monitor.worked(1); } } catch (Exception e) { throw new InvocationTargetException(e); } finally { // Clean all opened resources if (istream != null) { try { istream.close(); } catch (IOException e) { e.printStackTrace(); // nothing we can do here } } try { ostream.close(); } catch (IOException e) { e.printStackTrace(); // nothing we can do here } } }
java
{ "resource": "" }
q160623
DFSFile.upload
train
public void upload(IProgressMonitor monitor, File file) { final int taskSize = 1024; monitor.setTaskName("Upload file " + this.path); BufferedInputStream istream = null; DataOutputStream ostream = null; try { istream = new BufferedInputStream(new FileInputStream(file)); ostream = getDFS().create(this.path); int bytes; byte[] buffer = new byte[taskSize]; while ((bytes = istream.read(buffer)) >= 0) { if (monitor.isCanceled()) return; ostream.write(buffer, 0, bytes); monitor.worked(1); } } catch (Exception e) { ErrorMessageDialog.display(String.format( "Unable to uploade file %s to %s", file, this.path), e .getLocalizedMessage()); } finally { try { if (istream != null) istream.close(); } catch (IOException e) { e.printStackTrace(); // nothing we can do here } try { if (ostream != null) ostream.close(); } catch (IOException e) { e.printStackTrace(); // nothing we can do here } } }
java
{ "resource": "" }
q160624
FSNamesystemDatanodeHelper.getDatanodeStats
train
public static DatanodeStatus getDatanodeStats(FSNamesystem ns, ArrayList<DatanodeDescriptor> live, ArrayList<DatanodeDescriptor> dead) { ns.DFSNodesStatus(live, dead); ArrayList<DatanodeDescriptor> decommissioning = ns .getDecommissioningNodesList(live); // live nodes int numLive = live.size(); int numLiveExcluded = 0; int numLiveDecommissioningInProgress = decommissioning.size(); int numLiveDecommissioned = 0; for (DatanodeDescriptor d : live) { numLiveDecommissioned += d.isDecommissioned() ? 1 : 0; numLiveExcluded += ns.inExcludedHostsList(d, null) ? 1 : 0; } // dead nodes int numDead = dead.size(); int numDeadExcluded = 0; int numDeadDecommissioningNotCompleted = 0; int numDeadDecommissioned = 0; for (DatanodeDescriptor d : dead) { numDeadDecommissioned += d.isDecommissioned() ? 1 : 0; numDeadExcluded += ns.inExcludedHostsList(d, null) ? 1 : 0; } numDeadDecommissioningNotCompleted = numDeadExcluded - numDeadDecommissioned; return new DatanodeStatus(numLive, numLiveExcluded, numLiveDecommissioningInProgress, numLiveDecommissioned, numDead, numDeadExcluded, numDeadDecommissioningNotCompleted, numDeadDecommissioned); }
java
{ "resource": "" }
q160625
IFileOutputStream.finish
train
public void finish() throws IOException { if (finished) { return; } finished = true; sum.writeValue(barray, 0, false); out.write (barray, 0, sum.getChecksumSize()); out.flush(); }
java
{ "resource": "" }
q160626
FilterFileSystem.hardLink
train
public boolean hardLink(Path src, Path dst) throws IOException { return fs.hardLink(src, dst); }
java
{ "resource": "" }
q160627
FilterFileSystem.rename
train
public boolean rename(Path src, Path dst) throws IOException { return fs.rename(src, dst); }
java
{ "resource": "" }
q160628
FilterFileSystem.copyFromLocalFile
train
public void copyFromLocalFile(boolean delSrc, boolean overwrite, Path[] srcs, Path dst) throws IOException { fs.copyFromLocalFile(delSrc, overwrite, srcs, dst); }
java
{ "resource": "" }
q160629
FilterFileSystem.copyToLocalFile
train
public void copyToLocalFile(boolean delSrc, Path src, Path dst) throws IOException { fs.copyToLocalFile(delSrc, src, dst); }
java
{ "resource": "" }
q160630
FilterFileSystem.startLocalOutput
train
public Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile) throws IOException { return fs.startLocalOutput(fsOutputFile, tmpLocalFile); }
java
{ "resource": "" }
q160631
FilterFileSystem.completeLocalOutput
train
public void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile) throws IOException { fs.completeLocalOutput(fsOutputFile, tmpLocalFile); }
java
{ "resource": "" }
q160632
LocalStore.insert
train
public void insert(EventRecord er) { SerializedRecord sr = new SerializedRecord(er); try { Anonymizer.anonymize(sr); } catch (Exception e) { e.printStackTrace(); } append(sr); }
java
{ "resource": "" }
q160633
LocalStore.pack
train
public static StringBuffer pack(SerializedRecord sr) { StringBuffer sb = new StringBuffer(); ArrayList<String> keys = new ArrayList<String>(sr.fields.keySet()); if (sr.isValid()) SerializedRecord.arrangeKeys(keys); for (int i = 0; i < keys.size(); i++) { String value = sr.fields.get(keys.get(i)); sb.append(keys.get(i) + ":" + value); sb.append(FIELD_SEPARATOR); } return sb; }
java
{ "resource": "" }
q160634
LocalStore.upload
train
public void upload() { try { writer.flush(); if (compress) zipCompress(filename); String remoteName = "failmon-"; if ("true".equalsIgnoreCase(Environment.getProperty("anonymizer.hash.hostnames"))) remoteName += Anonymizer.getMD5Hash(InetAddress.getLocalHost().getCanonicalHostName()) + "-"; else remoteName += InetAddress.getLocalHost().getCanonicalHostName() + "-"; remoteName += Calendar.getInstance().getTimeInMillis();//.toString(); if (compress) copyToHDFS(filename + COMPRESSION_SUFFIX, hdfsDir + "/" + remoteName + COMPRESSION_SUFFIX); else copyToHDFS(filename, hdfsDir + "/" + remoteName); } catch (IOException e) { e.printStackTrace(); } // delete and re-open try { fw.close(); fw = new FileWriter(filename); writer = new BufferedWriter(fw); } catch (IOException e) { e.printStackTrace(); } }
java
{ "resource": "" }
q160635
LocalStore.zipCompress
train
public static void zipCompress(String filename) throws IOException { FileOutputStream fos = new FileOutputStream(filename + COMPRESSION_SUFFIX); CheckedOutputStream csum = new CheckedOutputStream(fos, new CRC32()); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(csum)); out.setComment("Failmon records."); BufferedReader in = new BufferedReader(new FileReader(filename)); out.putNextEntry(new ZipEntry(new File(filename).getName())); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.finish(); out.close(); }
java
{ "resource": "" }
q160636
LocalStore.copyToHDFS
train
public static void copyToHDFS(String localFile, String hdfsFile) throws IOException { String hadoopConfPath; if (Environment.getProperty("hadoop.conf.path") == null) hadoopConfPath = "../../../conf"; else hadoopConfPath = Environment.getProperty("hadoop.conf.path"); // Read the configuration for the Hadoop environment Configuration hadoopConf = new Configuration(); hadoopConf.addResource(new Path(hadoopConfPath + "/hadoop-default.xml")); hadoopConf.addResource(new Path(hadoopConfPath + "/hadoop-site.xml")); // System.out.println(hadoopConf.get("hadoop.tmp.dir")); // System.out.println(hadoopConf.get("fs.default.name")); FileSystem fs = FileSystem.get(hadoopConf); // HadoopDFS deals with Path Path inFile = new Path("file://" + localFile); Path outFile = new Path(hadoopConf.get("fs.default.name") + hdfsFile); // Read from and write to new file Environment.logInfo("Uploading to HDFS (file " + outFile + ") ..."); fs.copyFromLocalFile(false, inFile, outFile); }
java
{ "resource": "" }
q160637
Anonymizer.getMD5Hash
train
public static String getMD5Hash(String text) { MessageDigest md; byte[] md5hash = new byte[32]; try { md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return convertToHex(md5hash); }
java
{ "resource": "" }
q160638
ListPathsServlet.writeInfo
train
static void writeInfo(String parent, HdfsFileStatus i, XMLOutputter doc) throws IOException { final SimpleDateFormat ldf = df.get(); doc.startTag(i.isDir() ? "directory" : "file"); doc.attribute("path", i.getFullPath(new Path(parent)).toUri().getPath()); doc.attribute("modified", ldf.format(new Date(i.getModificationTime()))); doc.attribute("accesstime", ldf.format(new Date(i.getAccessTime()))); if (!i.isDir()) { doc.attribute("size", String.valueOf(i.getLen())); doc.attribute("replication", String.valueOf(i.getReplication())); doc.attribute("blocksize", String.valueOf(i.getBlockSize())); } doc.attribute("permission", (i.isDir()? "d": "-") + i.getPermission()); doc.attribute("owner", i.getOwner()); doc.attribute("group", i.getGroup()); doc.endTag(); }
java
{ "resource": "" }
q160639
ListPathsServlet.buildRoot
train
protected Map<String,String> buildRoot(HttpServletRequest request, XMLOutputter doc) { final String path = request.getPathInfo() != null ? request.getPathInfo() : "/"; final String exclude = request.getParameter("exclude") != null ? request.getParameter("exclude") : "\\..*\\.crc"; final String filter = request.getParameter("filter") != null ? request.getParameter("filter") : ".*"; final boolean recur = request.getParameter("recursive") != null && "yes".equals(request.getParameter("recursive")); Map<String, String> root = new HashMap<String, String>(); root.put("path", path); root.put("recursive", recur ? "yes" : "no"); root.put("filter", filter); root.put("exclude", exclude); root.put("time", df.get().format(new Date())); root.put("version", VersionInfo.getVersion()); return root; }
java
{ "resource": "" }
q160640
PlacementMonitor.shouldSubmitMove
train
private boolean shouldSubmitMove(PolicyInfo policy, Map<String, Integer> nodeToNumBlocks, List<BlockInfo> stripeBlocks) { if (policy == null) { return true; } int targetRepl = Integer.parseInt(policy.getProperty("targetReplication")); int parityRepl = Integer.parseInt(policy.getProperty("metaReplication")); Codec codec = Codec.getCodec(policy.getCodecId()); int numParityBlks = codec.parityLength; int numSrcBlks = stripeBlocks.size() - numParityBlks; int expectNumReplicas = numSrcBlks * targetRepl + numParityBlks * parityRepl; int actualNumReplicas = 0; for (int num : nodeToNumBlocks.values()) { actualNumReplicas += num; } if (actualNumReplicas != expectNumReplicas) { String msg = "Expected number of replicas in the stripe: " + expectNumReplicas + ", but actual number is: " + actualNumReplicas + ". "; if (stripeBlocks.size() > 0) { msg += "filePath: " + stripeBlocks.get(0).file.getPath(); } LOG.warn(msg); } return actualNumReplicas == expectNumReplicas; }
java
{ "resource": "" }
q160641
BlockIntegrityMonitor.incrNumBlockFixSimulationSuccess
train
protected synchronized void incrNumBlockFixSimulationSuccess(long incr) { if (incr < 0) { throw new IllegalArgumentException("Cannot increment by negative value " + incr); } RaidNodeMetrics.getInstance(RaidNodeMetrics.DEFAULT_NAMESPACE_ID). blockFixSimulationSuccess.inc(incr); numBlockFixSimulationSuccess += incr; }
java
{ "resource": "" }
q160642
BlockIntegrityMonitor.incrNumBlockFixSimulationFailures
train
protected synchronized void incrNumBlockFixSimulationFailures(long incr) { if (incr < 0) { throw new IllegalArgumentException("Cannot increment by negative value " + incr); } RaidNodeMetrics.getInstance(RaidNodeMetrics.DEFAULT_NAMESPACE_ID). blockFixSimulationFailures.inc(incr); numBlockFixSimulationFailures += incr; }
java
{ "resource": "" }
q160643
BlockIntegrityMonitor.incrFileFixFailures
train
protected synchronized void incrFileFixFailures(long incr) { if (incr < 0) { throw new IllegalArgumentException("Cannot increment by negative value " + incr); } RaidNodeMetrics.getInstance(RaidNodeMetrics.DEFAULT_NAMESPACE_ID).fileFixFailures.inc(incr); numFileFixFailures += incr; }
java
{ "resource": "" }
q160644
BlockIntegrityMonitor.incrFilesFixed
train
protected synchronized void incrFilesFixed(long incr) { if (incr < 0) { throw new IllegalArgumentException("Cannot increment by negative value " + incr); } RaidNodeMetrics.getInstance(RaidNodeMetrics.DEFAULT_NAMESPACE_ID).filesFixed.inc(incr); numFilesFixed += incr; }
java
{ "resource": "" }
q160645
BlockIntegrityMonitor.incrFileFixReadBytesRemoteRack
train
protected synchronized void incrFileFixReadBytesRemoteRack(long incr) { if (incr < 0) { throw new IllegalArgumentException("Cannot increment by negative value " + incr); } RaidNodeMetrics.getInstance(RaidNodeMetrics.DEFAULT_NAMESPACE_ID).numFileFixReadBytesRemoteRack.inc(incr); numfileFixBytesReadRemoteRack += incr; }
java
{ "resource": "" }
q160646
BlockIntegrityMonitor.incrFileCopyFailures
train
protected synchronized void incrFileCopyFailures(long incr) { if (incr < 0) { throw new IllegalArgumentException("Cannot increment by negative value " + incr); } RaidNodeMetrics.getInstance(RaidNodeMetrics.DEFAULT_NAMESPACE_ID).fileCopyFailures.inc(incr); numFileCopyFailures += incr; }
java
{ "resource": "" }
q160647
BlockIntegrityMonitor.incrFilesCopied
train
protected synchronized void incrFilesCopied(long incr) { if (incr < 0) { throw new IllegalArgumentException("Cannot increment by negative value " + incr); } RaidNodeMetrics.getInstance(RaidNodeMetrics.DEFAULT_NAMESPACE_ID).filesCopied.inc(incr); numFilesCopied += incr; }
java
{ "resource": "" }
q160648
FSEditLog.open
train
synchronized void open() throws IOException { if (syncer == null) { syncer = new SyncThread(); syncThread = new Thread(syncer); syncThread.start(); } if (state != State.BETWEEN_LOG_SEGMENTS) throw new IOException("Bad state: " + state); startLogSegment(getLastWrittenTxId() + 1, true); if (state != State.IN_SEGMENT) throw new IOException("Bad state: " + state); }
java
{ "resource": "" }
q160649
FSEditLog.logSyncAll
train
public void logSyncAll() throws IOException { // Record the most recent transaction ID as our own id synchronized (this) { TransactionId id = myTransactionId.get(); id.txid = txid; } // Then make sure we're synced up to this point logSync(); }
java
{ "resource": "" }
q160650
FSEditLog.logSyncIfNeeded
train
public void logSyncIfNeeded() { boolean doSync = false; synchronized (this) { if (txid > synctxid + maxBufferedTransactions) { FSNamesystem.LOG.info("Out of band log sync triggered " + " because there are " + (txid-synctxid) + " buffered transactions which " + " is more than the configured limit of " + maxBufferedTransactions); doSync = true; } if (shouldForceSync()) { FSNamesystem.LOG.info("Log sync triggered by the output stream"); doSync = true; } } if (doSync) { logSync(); } }
java
{ "resource": "" }
q160651
FSEditLog.logSync
train
public void logSync(boolean doWait) { long syncStart = 0; boolean thisThreadSuccess = false; boolean thisThreadSyncing = false; EditLogOutputStream logStream = null; try { synchronized (this) { long mytxid = myTransactionId.get().txid; myTransactionId.get().txid = -1L; if (mytxid == -1) { mytxid = txid; } printStatistics(false); // if somebody is already syncing, then wait while (mytxid > synctxid && isSyncRunning) { if (!doWait) { long delayedId = Server.delayResponse(); List<Long> responses = delayedSyncs.get(mytxid); if (responses == null) { responses = new LinkedList<Long>(); delayedSyncs.put(mytxid, responses); } responses.add(delayedId); return; } try { wait(1000); } catch (InterruptedException ie) { } } // // If this transaction was already flushed, then nothing to do // if (mytxid <= synctxid) { numTransactionsBatchedInSync++; if (metrics != null) // Metrics is non-null only when used inside name // node metrics.transactionsBatchedInSync.inc(); return; } // now, this thread will do the sync syncStart = txid; isSyncRunning = true; thisThreadSyncing = true; // swap buffers try { if (journalSet.isEmpty()) { throw new IOException( "No journals available to flush, journalset is empty"); } if (editLogStream == null) { throw new IOException( "No journals available to flush, editlogstream is null"); } editLogStream.setReadyToFlush(); } catch (IOException e) { LOG.fatal("Could not sync enough journals to persistent storage. " + "Unsynced transactions: " + (txid - synctxid), new Exception(e)); runtime.exit(1); } // editLogStream may become null, // so store a local variable for flush. logStream = editLogStream; } // do the sync sync(logStream, syncStart); thisThreadSuccess = true; } finally { synchronized (this) { if (thisThreadSyncing) { if(thisThreadSuccess) { // only set this if the sync succeeded synctxid = syncStart; } // if this thread was syncing, clear isSyncRunning isSyncRunning = false; } this.notifyAll(); } } endDelay(syncStart); }
java
{ "resource": "" }
q160652
FSEditLog.logOpenFile
train
public void logOpenFile(String path, INodeFileUnderConstruction newNode) throws IOException { AddOp op = AddOp.getInstance(); op.set(newNode.getId(), path, newNode.getReplication(), newNode.getModificationTime(), newNode.getAccessTime(), newNode.getPreferredBlockSize(), newNode.getBlocks(), newNode.getPermissionStatus(), newNode.getClientName(), newNode.getClientMachine()); logEdit(op); }
java
{ "resource": "" }
q160653
FSEditLog.logCloseFile
train
public void logCloseFile(String path, INodeFile newNode) { CloseOp op = CloseOp.getInstance(); op.set(newNode.getId(), path, newNode.getReplication(), newNode.getModificationTime(), newNode.getAccessTime(), newNode.getPreferredBlockSize(), newNode.getBlocks(), newNode.getPermissionStatus(), null, null); logEdit(op); }
java
{ "resource": "" }
q160654
FSEditLog.logAppendFile
train
public void logAppendFile(String path, INodeFileUnderConstruction newNode) throws IOException { AppendOp op = AppendOp.getInstance(); op.set(path, newNode.getBlocks(), newNode.getClientName(), newNode.getClientMachine()); logEdit(op); }
java
{ "resource": "" }
q160655
FSEditLog.logMkDir
train
public void logMkDir(String path, INode newNode) { MkdirOp op = MkdirOp.getInstance(); op.set(newNode.getId(), path, newNode.getModificationTime(), newNode.getPermissionStatus()); logEdit(op); }
java
{ "resource": "" }
q160656
FSEditLog.logHardLink
train
public void logHardLink(String src, String dst, long timestamp) { HardLinkOp op = HardLinkOp.getInstance(); op.set(src, dst, timestamp); logEdit(op); }
java
{ "resource": "" }
q160657
FSEditLog.logRename
train
public void logRename(String src, String dst, long timestamp) { RenameOp op = RenameOp.getInstance(); op.set(src, dst, timestamp); logEdit(op); }
java
{ "resource": "" }
q160658
FSEditLog.logSetReplication
train
public void logSetReplication(String src, short replication) { SetReplicationOp op = SetReplicationOp.getInstance(); op.set(src, replication); logEdit(op); }
java
{ "resource": "" }
q160659
FSEditLog.logSetQuota
train
public void logSetQuota(String src, long nsQuota, long dsQuota) { SetQuotaOp op = SetQuotaOp.getInstance(); op.set(src, nsQuota, dsQuota); logEdit(op); }
java
{ "resource": "" }
q160660
FSEditLog.logSetPermissions
train
public void logSetPermissions(String src, FsPermission permissions) { SetPermissionsOp op = SetPermissionsOp.getInstance(); op.set(src, permissions); logEdit(op); }
java
{ "resource": "" }
q160661
FSEditLog.logSetOwner
train
public void logSetOwner(String src, String username, String groupname) { SetOwnerOp op = SetOwnerOp.getInstance(); op.set(src, username, groupname); logEdit(op); }
java
{ "resource": "" }
q160662
FSEditLog.logDelete
train
public void logDelete(String src, long timestamp) { DeleteOp op = DeleteOp.getInstance(); op.set(src, timestamp); logEdit(op); }
java
{ "resource": "" }
q160663
FSEditLog.logGenerationStamp
train
public void logGenerationStamp(long genstamp) { SetGenstampOp op = SetGenstampOp.getInstance(); op.set(genstamp); logEdit(op); }
java
{ "resource": "" }
q160664
FSEditLog.logTimes
train
public void logTimes(String src, long mtime, long atime) { TimesOp op = TimesOp.getInstance(); op.set(src, mtime, atime); logEdit(op); }
java
{ "resource": "" }
q160665
FSEditLog.rollEditLog
train
synchronized long rollEditLog() throws IOException { LOG.info("Rolling edit logs."); long start = System.nanoTime(); endCurrentLogSegment(true); long nextTxId = getLastWrittenTxId() + 1; startLogSegment(nextTxId, true); assert curSegmentTxId == nextTxId; long rollTime = DFSUtil.getElapsedTimeMicroSeconds(start); if (metrics != null) { metrics.rollEditLogTime.inc(rollTime); metrics.tsLastEditsRoll.set(System.currentTimeMillis()); } return nextTxId; }
java
{ "resource": "" }
q160666
FSEditLog.startLogSegment
train
synchronized void startLogSegment(final long segmentTxId, boolean writeHeaderTxn) throws IOException { LOG.info("Starting log segment at " + segmentTxId); if (segmentTxId < 0) { throw new IOException("Bad txid: " + segmentTxId); } if (state != State.BETWEEN_LOG_SEGMENTS) { throw new IOException("Bad state: " + state); } if (segmentTxId <= curSegmentTxId) { throw new IOException("Cannot start writing to log segment " + segmentTxId + " when previous log segment started at " + curSegmentTxId); } if (segmentTxId != txid + 1) { throw new IOException("Cannot start log segment at txid " + segmentTxId + " when next expected " + (txid + 1)); } numTransactions = totalTimeTransactions = numTransactionsBatchedInSync = 0; // TODO no need to link this back to storage anymore! // See HDFS-2174. storage.attemptRestoreRemovedStorage(); try { editLogStream = journalSet.startLogSegment(segmentTxId); } catch (IOException ex) { throw new IOException("Unable to start log segment " + segmentTxId + ": no journals successfully started."); } curSegmentTxId = segmentTxId; state = State.IN_SEGMENT; if (writeHeaderTxn) { logEdit(LogSegmentOp.getInstance(FSEditLogOpCodes.OP_START_LOG_SEGMENT)); logSync(); } // force update of journal and image metrics journalSet.updateJournalMetrics(); // If it is configured, we want to schedule an automatic edits roll if (timeoutRollEdits > 0) { FSNamesystem fsn = this.journalSet.getImage().getFSNamesystem(); if (fsn != null) { // In some test cases fsn is NULL in images. Simply skip the feature. AutomaticEditsRoller aer = fsn.automaticEditsRoller; if (aer != null) { aer.setNextRollTime(System.currentTimeMillis() + timeoutRollEdits); } else { LOG.warn("Automatic edits roll is enabled but the roller thread " + "is not enabled. Should only happen in unit tests."); } } else { LOG.warn("FSNamesystem is NULL in FSEditLog."); } } }
java
{ "resource": "" }
q160667
FSEditLog.endCurrentLogSegment
train
synchronized void endCurrentLogSegment(boolean writeEndTxn) throws IOException { LOG.info("Ending log segment " + curSegmentTxId); if (state != State.IN_SEGMENT) { throw new IllegalStateException("Bad state: " + state); } waitForSyncToFinish(); if (writeEndTxn) { logEdit(LogSegmentOp.getInstance(FSEditLogOpCodes.OP_END_LOG_SEGMENT)); } logSyncAll(); printStatistics(true); final long lastTxId = getLastWrittenTxId(); try { journalSet.finalizeLogSegment(curSegmentTxId, lastTxId); editLogStream = null; } catch (IOException e) { // All journals have failed, it will be handled in logSync. FSNamesystem.LOG.info("Cannot finalize log segment: " + e.toString()); } state = State.BETWEEN_LOG_SEGMENTS; }
java
{ "resource": "" }
q160668
FSEditLog.purgeLogsOlderThan
train
public void purgeLogsOlderThan(final long minTxIdToKeep) { synchronized (this) { // synchronized to prevent findbugs warning about inconsistent // synchronization. This will be JIT-ed out if asserts are // off. assert curSegmentTxId == HdfsConstants.INVALID_TXID || // on format this // is no-op minTxIdToKeep <= curSegmentTxId : "cannot purge logs older than txid " + minTxIdToKeep + " when current segment starts at " + curSegmentTxId; try { journalSet.purgeLogsOlderThan(minTxIdToKeep); } catch (IOException ex) { // All journals have failed, it will be handled in logSync. } } }
java
{ "resource": "" }
q160669
FSEditLog.selectInputStreams
train
public synchronized boolean selectInputStreams( Collection<EditLogInputStream> streams, long fromTxId, long toAtLeastTxId, int minRedundancy) throws IOException { // at this point we should not have any non-finalized segments // this function is called at startup, and must be invoked after // recovering all in progress segments if (journalSet.hasUnfinalizedSegments(fromTxId)) { LOG.fatal("All streams should be finalized"); throw new IOException("All streams should be finalized at startup"); } // get all finalized streams boolean redundancyViolated = journalSet.selectInputStreams(streams, fromTxId, false, false, minRedundancy); try { checkForGaps(streams, fromTxId, toAtLeastTxId, true); } catch (IOException e) { closeAllStreams(streams); throw e; } return redundancyViolated; }
java
{ "resource": "" }
q160670
FSEditLog.closeAllStreams
train
static void closeAllStreams(Iterable<EditLogInputStream> streams) { for (EditLogInputStream s : streams) { IOUtils.closeStream(s); } }
java
{ "resource": "" }
q160671
FSEditLog.getJournalClass
train
static Class<? extends JournalManager> getJournalClass(Configuration conf, String uriScheme) { String key = "dfs.name.edits.journal-plugin" + "." + uriScheme; Class<? extends JournalManager> clazz = null; try { clazz = conf.getClass(key, null, JournalManager.class); } catch (RuntimeException re) { throw new IllegalArgumentException("Invalid class specified for " + uriScheme, re); } if (clazz == null) { LOG.warn("No class configured for " + uriScheme + ", " + key + " is empty"); throw new IllegalArgumentException("No class configured for " + uriScheme); } return clazz; }
java
{ "resource": "" }
q160672
FSEditLog.createJournal
train
public static JournalManager createJournal(Configuration conf, URI uri, NamespaceInfo nsInfo, NameNodeMetrics metrics) { Class<? extends JournalManager> clazz = getJournalClass(conf, uri.getScheme()); try { Constructor<? extends JournalManager> cons = clazz.getConstructor( Configuration.class, URI.class, NamespaceInfo.class, NameNodeMetrics.class); return cons.newInstance(conf, uri, nsInfo, metrics); } catch (Exception e) { throw new IllegalArgumentException("Unable to construct journal, " + uri, e); } }
java
{ "resource": "" }
q160673
CombineFileRecordReader.getProgress
train
public float getProgress() throws IOException { long subprogress = 0; // bytes processed in current split if (null != curReader) { // idx is always one past the current subsplit's true index. subprogress = (long)(curReader.getProgress() * split.getLength(idx - 1)); } return Math.min(1.0f, (progress + subprogress)/(float)(split.getLength())); }
java
{ "resource": "" }
q160674
CombineFileRecordReader.initNextRecordReader
train
protected boolean initNextRecordReader() throws IOException { if (curReader != null) { curReader.close(); curReader = null; if (idx > 0) { progress += split.getLength(idx-1); // done processing so far } } // if all chunks have been processed, nothing more to do. if (idx == split.getNumPaths()) { return false; } // get a record reader for the idx-th chunk try { curReader = rrConstructor.newInstance(new Object [] {split, jc, reporter, Integer.valueOf(idx)}); // setup some helper config variables. jc.set("map.input.file", split.getPath(idx).toString()); jc.setLong("map.input.start", split.getOffset(idx)); jc.setLong("map.input.length", split.getLength(idx)); } catch (Exception e) { throw new RuntimeException (e); } idx++; return true; }
java
{ "resource": "" }
q160675
FileOutputCommitter.setupJob
train
public void setupJob(JobContext context) throws IOException { if (outputPath != null) { Path tmpDir = new Path(outputPath, FileOutputCommitter.TEMP_DIR_NAME); FileSystem fileSys = tmpDir.getFileSystem(context.getConfiguration()); if (!fileSys.mkdirs(tmpDir)) { LOG.error("Mkdirs failed to create " + tmpDir.toString()); } } }
java
{ "resource": "" }
q160676
FileOutputCommitter.commitJob
train
public void commitJob(JobContext context) throws IOException { // delete the _temporary folder cleanupJob(context); // check if the o/p dir should be marked if (shouldMarkOutputDir(context.getConfiguration())) { // create a _success file in the o/p folder markOutputDirSuccessful(context); } }
java
{ "resource": "" }
q160677
FileOutputCommitter.abortJob
train
@Override public void abortJob(JobContext context, JobStatus.State state) throws IOException { cleanupJob(context); }
java
{ "resource": "" }
q160678
FileOutputCommitter.commitTask
train
public void commitTask(TaskAttemptContext context) throws IOException { TaskAttemptID attemptId = context.getTaskAttemptID(); if (workPath != null) { context.progress(); if (outputFileSystem.exists(workPath)) { // Move the task outputs to their final place moveTaskOutputs(context, outputFileSystem, outputPath, workPath); // Delete the temporary task-specific output directory if (!outputFileSystem.delete(workPath, true)) { LOG.warn("Failed to delete the temporary output" + " directory of task: " + attemptId + " - " + workPath); } LOG.info("Saved output of task '" + attemptId + "' to " + outputPath); } } }
java
{ "resource": "" }
q160679
FileOutputCommitter.moveTaskOutputs
train
private void moveTaskOutputs(TaskAttemptContext context, FileSystem fs, Path jobOutputDir, Path taskOutput) throws IOException { TaskAttemptID attemptId = context.getTaskAttemptID(); context.progress(); if (fs.isFile(taskOutput)) { Path finalOutputPath = getFinalPath(jobOutputDir, taskOutput, workPath); if (!fs.rename(taskOutput, finalOutputPath)) { if (!fs.delete(finalOutputPath, true)) { throw new IOException("Failed to delete earlier output of task: " + attemptId); } if (!fs.rename(taskOutput, finalOutputPath)) { throw new IOException("Failed to save output of task: " + attemptId); } } LOG.debug("Moved " + taskOutput + " to " + finalOutputPath); } else if(fs.getFileStatus(taskOutput).isDir()) { FileStatus[] paths = fs.listStatus(taskOutput); Path finalOutputPath = getFinalPath(jobOutputDir, taskOutput, workPath); fs.mkdirs(finalOutputPath); if (paths != null) { for (FileStatus path : paths) { moveTaskOutputs(context, fs, jobOutputDir, path.getPath()); } } } }
java
{ "resource": "" }
q160680
FileOutputCommitter.abortTask
train
@Override public void abortTask(TaskAttemptContext context) throws IOException { try { if (workPath != null) { context.progress(); if (!outputFileSystem.delete(workPath, true)) { LOG.warn("Deleting output in " + workPath + " returns false"); } } } catch (IOException ie) { LOG.warn("Error discarding output in " + workPath, ie); throw ie; } }
java
{ "resource": "" }
q160681
FileOutputCommitter.getFinalPath
train
private Path getFinalPath(Path jobOutputDir, Path taskOutput, Path taskOutputPath) throws IOException { URI taskOutputUri = taskOutput.toUri(); URI relativePath = taskOutputPath.toUri().relativize(taskOutputUri); if (taskOutputUri == relativePath) { throw new IOException("Can not get the relative path: base = " + taskOutputPath + " child = " + taskOutput); } if (relativePath.getPath().length() > 0) { return new Path(jobOutputDir, relativePath.getPath()); } else { return jobOutputDir; } }
java
{ "resource": "" }
q160682
FileOutputCommitter.needsTaskCommit
train
@Override public boolean needsTaskCommit(TaskAttemptContext context ) throws IOException { return workPath != null && outputFileSystem.exists(workPath); }
java
{ "resource": "" }
q160683
NodeManager.readNameToNode
train
private void readNameToNode(CoronaSerializer coronaSerializer) throws IOException { coronaSerializer.readField("nameToNode"); // Expecting the START_OBJECT token for nameToNode coronaSerializer.readStartObjectToken("nameToNode"); JsonToken current = coronaSerializer.nextToken(); while (current != JsonToken.END_OBJECT) { // nodeName is the key, and the ClusterNode is the value here String nodeName = coronaSerializer.getFieldName(); ClusterNode clusterNode = new ClusterNode(coronaSerializer); if (!nameToNode.containsKey(nodeName)) { nameToNode.put(nodeName, clusterNode); } current = coronaSerializer.nextToken(); } // Done with reading the END_OBJECT token for nameToNode }
java
{ "resource": "" }
q160684
NodeManager.readHostsToSessions
train
private void readHostsToSessions(CoronaSerializer coronaSerializer) throws IOException { coronaSerializer.readField("hostsToSessions"); // Expecting the START_OBJECT token for hostsToSessions coronaSerializer.readStartObjectToken("hostsToSessions"); JsonToken current = coronaSerializer.nextToken(); while (current != JsonToken.END_OBJECT) { String host = coronaSerializer.getFieldName(); Set<String> sessionsSet = coronaSerializer.readValueAs(Set.class); hostsToSessions.put(nameToNode.get(host), sessionsSet); current = coronaSerializer.nextToken(); } }
java
{ "resource": "" }
q160685
NodeManager.readNameToApps
train
private void readNameToApps(CoronaSerializer coronaSerializer) throws IOException { coronaSerializer.readField("nameToApps"); // Expecting the START_OBJECT token for nameToApps coronaSerializer.readStartObjectToken("nameToApps"); JsonToken current = coronaSerializer.nextToken(); while (current != JsonToken.END_OBJECT) { String nodeName = coronaSerializer.getFieldName(); // Expecting the START_OBJECT token for the Apps coronaSerializer.readStartObjectToken(nodeName); Map<String, String> appMap = coronaSerializer.readValueAs(Map.class); Map<ResourceType, String> appsOnNode = new HashMap<ResourceType, String>(); for (Map.Entry<String, String> entry : appMap.entrySet()) { appsOnNode.put(ResourceType.valueOf(entry.getKey()), entry.getValue()); } nameToApps.put(nodeName, appsOnNode); current = coronaSerializer.nextToken(); } }
java
{ "resource": "" }
q160686
NodeManager.existRunnableNodes
train
public boolean existRunnableNodes(ResourceType type) { RunnableIndices r = typeToIndices.get(type); return r.existRunnableNodes(); }
java
{ "resource": "" }
q160687
NodeManager.getRunnableNode
train
public ClusterNode getRunnableNode(String host, LocalityLevel maxLevel, ResourceType type, Set<String> excluded) { if (host == null) { RunnableIndices r = typeToIndices.get(type); return r.getRunnableNodeForAny(excluded); } RequestedNode node = resolve(host, type); return getRunnableNode(node, maxLevel, type, excluded); }
java
{ "resource": "" }
q160688
NodeManager.getRunnableNode
train
public ClusterNode getRunnableNode(RequestedNode requestedNode, LocalityLevel maxLevel, ResourceType type, Set<String> excluded) { ClusterNode node = null; RunnableIndices r = typeToIndices.get(type); // find host local node = r.getRunnableNodeForHost(requestedNode); if (maxLevel == LocalityLevel.NODE || node != null) { return node; } node = r.getRunnableNodeForRack(requestedNode, excluded); if (maxLevel == LocalityLevel.RACK || node != null) { return node; } // find any node node = r.getRunnableNodeForAny(excluded); return node; }
java
{ "resource": "" }
q160689
NodeManager.addNode
train
protected void addNode(ClusterNode node, Map<ResourceType, String> resourceInfos) { synchronized (node) { // 1: primary nameToNode.put(node.getName(), node); faultManager.addNode(node.getName(), resourceInfos.keySet()); nameToApps.put(node.getName(), resourceInfos); hostsToSessions.put(node, new HashSet<String>()); clusterManager.getMetrics().restartTaskTracker(1); setAliveDeadMetrics(); // 2: update runnable indices for (Map.Entry<ResourceType, RunnableIndices> entry : typeToIndices.entrySet()) { ResourceType type = entry.getKey(); if (resourceInfos.containsKey(type)) { if (node.checkForGrant(Utilities.getUnitResourceRequest(type), resourceLimit)) { RunnableIndices r = entry.getValue(); r.addRunnable(node); } } } } }
java
{ "resource": "" }
q160690
NodeManager.updateRunnability
train
private void updateRunnability(ClusterNode node) { synchronized (node) { for (Map.Entry<ResourceType, RunnableIndices> entry : typeToIndices.entrySet()) { ResourceType type = entry.getKey(); RunnableIndices r = entry.getValue(); ResourceRequest unitReq = Utilities.getUnitResourceRequest(type); boolean currentlyRunnable = r.hasRunnable(node); boolean shouldBeRunnable = node.checkForGrant(unitReq, resourceLimit); if (currentlyRunnable && !shouldBeRunnable) { LOG.info("Node " + node.getName() + " is no longer " + type + " runnable"); r.deleteRunnable(node); } else if (!currentlyRunnable && shouldBeRunnable) { LOG.info("Node " + node.getName() + " is now " + type + " runnable"); r.addRunnable(node); } } } }
java
{ "resource": "" }
q160691
NodeManager.addAppToNode
train
protected void addAppToNode( ClusterNode node, ResourceType type, String appInfo) { synchronized (node) { // Update primary index. Map<ResourceType, String> apps = nameToApps.get(node.getName()); apps.put(type, appInfo); // Update runnable indices. for (Map.Entry<ResourceType, RunnableIndices> entry : typeToIndices.entrySet()) { if (type.equals(entry.getKey())) { if (node.checkForGrant(Utilities.getUnitResourceRequest(type), resourceLimit)) { RunnableIndices r = entry.getValue(); r.addRunnable(node); } } } } }
java
{ "resource": "" }
q160692
NodeManager.getNodeSessions
train
public Set<String> getNodeSessions(String nodeName) { ClusterNode node = nameToNode.get(nodeName); if (node == null) { LOG.warn("Trying to get the sessions for a non-existent node " + nodeName); return new HashSet<String>(); } synchronized (node) { return new HashSet<String>(hostsToSessions.get(node)); } }
java
{ "resource": "" }
q160693
NodeManager.deleteSession
train
public void deleteSession(String session) { for (Set<String> sessions : hostsToSessions.values()) { sessions.remove(session); } }
java
{ "resource": "" }
q160694
NodeManager.cancelGrant
train
public void cancelGrant(String nodeName, String sessionId, int requestId) { ClusterNode node = nameToNode.get(nodeName); if (node == null) { LOG.warn("Canceling grant for non-existent node: " + nodeName); return; } synchronized (node) { if (node.deleted) { LOG.warn("Canceling grant for deleted node: " + nodeName); return; } String hoststr = node.getClusterNodeInfo().getAddress().getHost(); if (!canAllowNode(hoststr)) { LOG.warn("Canceling grant for excluded node: " + hoststr); return; } ResourceRequestInfo req = node.getRequestForGrant(sessionId, requestId); if (req != null) { ResourceRequest unitReq = Utilities.getUnitResourceRequest( req.getType()); boolean previouslyRunnable = node.checkForGrant(unitReq, resourceLimit); node.cancelGrant(sessionId, requestId); loadManager.decrementLoad(req.getType()); if (!previouslyRunnable && node.checkForGrant(unitReq, resourceLimit)) { RunnableIndices r = typeToIndices.get(req.getType()); if (!faultManager.isBlacklisted(node.getName(), req.getType())) { r.addRunnable(node); } } } } }
java
{ "resource": "" }
q160695
NodeManager.addGrant
train
public boolean addGrant( ClusterNode node, String sessionId, ResourceRequestInfo req) { synchronized (node) { if (node.deleted) { return false; } if (!node.checkForGrant(Utilities.getUnitResourceRequest( req.getType()), resourceLimit)) { return false; } node.addGrant(sessionId, req); loadManager.incrementLoad(req.getType()); hostsToSessions.get(node).add(sessionId); if (!node.checkForGrant(Utilities.getUnitResourceRequest( req.getType()), resourceLimit)) { RunnableIndices r = typeToIndices.get(req.getType()); r.deleteRunnable(node); } } return true; }
java
{ "resource": "" }
q160696
NodeManager.restoreAfterSafeModeRestart
train
public void restoreAfterSafeModeRestart() throws IOException { if (!clusterManager.safeMode) { throw new IOException("restoreAfterSafeModeRestart() called while the " + "Cluster Manager was not in Safe Mode"); } // Restoring all the ClusterNode(s) for (ClusterNode clusterNode : nameToNode.values()) { restoreClusterNode(clusterNode); } // Restoring all the RequestedNodes(s) for (ClusterNode clusterNode : nameToNode.values()) { for (ResourceRequestInfo resourceRequestInfo : clusterNode.grants.values()) { // Fix the RequestedNode(s) restoreResourceRequestInfo(resourceRequestInfo); loadManager.incrementLoad(resourceRequestInfo.getType()); } } }
java
{ "resource": "" }
q160697
NodeManager.restoreResourceRequestInfo
train
public void restoreResourceRequestInfo(ResourceRequestInfo resourceRequestInfo) { List<RequestedNode> requestedNodes = null; List<String> hosts = resourceRequestInfo.getHosts(); if (hosts != null && hosts.size() > 0) { requestedNodes = new ArrayList<RequestedNode>(hosts.size()); for (String host : hosts) { requestedNodes.add(resolve(host, resourceRequestInfo.getType())); } } resourceRequestInfo.nodes = requestedNodes; }
java
{ "resource": "" }
q160698
NodeManager.heartbeat
train
public boolean heartbeat(ClusterNodeInfo clusterNodeInfo) throws DisallowedNode { ClusterNode node = nameToNode.get(clusterNodeInfo.name); if (!canAllowNode(clusterNodeInfo.getAddress().getHost())) { if (node != null) { node.heartbeat(clusterNodeInfo); } else { throw new DisallowedNode(clusterNodeInfo.getAddress().getHost()); } return false; } boolean newNode = false; Map<ResourceType, String> currentResources = clusterNodeInfo.getResourceInfos(); if (currentResources == null) { currentResources = new EnumMap<ResourceType, String>(ResourceType.class); } if (node == null) { LOG.info("Adding node with heartbeat: " + clusterNodeInfo.toString()); node = new ClusterNode(clusterNodeInfo, topologyCache.getNode(clusterNodeInfo.address.host), cpuToResourcePartitioning); addNode(node, currentResources); newNode = true; } node.heartbeat(clusterNodeInfo); boolean appsChanged = false; Map<ResourceType, String> prevResources = nameToApps.get(clusterNodeInfo.name); Set<ResourceType> deletedApps = null; for (Map.Entry<ResourceType, String> entry : prevResources.entrySet()) { String newAppInfo = currentResources.get(entry.getKey()); String oldAppInfo = entry.getValue(); if (newAppInfo == null || !newAppInfo.equals(oldAppInfo)) { if (deletedApps == null) { deletedApps = EnumSet.noneOf(ResourceType.class); } deletedApps.add(entry.getKey()); appsChanged = true; } } Map<ResourceType, String> addedApps = null; for (Map.Entry<ResourceType, String> entry : currentResources.entrySet()) { String newAppInfo = entry.getValue(); String oldAppInfo = prevResources.get(entry.getKey()); if (oldAppInfo == null || !oldAppInfo.equals(newAppInfo)) { if (addedApps == null) { addedApps = new EnumMap<ResourceType, String>(ResourceType.class); } addedApps.put(entry.getKey(), entry.getValue()); appsChanged = true; } } if (deletedApps != null) { for (ResourceType deleted : deletedApps) { clusterManager.nodeAppRemoved(clusterNodeInfo.name, deleted); } } if (addedApps != null) { for (Map.Entry<ResourceType, String> added: addedApps.entrySet()) { addAppToNode(node, added.getKey(), added.getValue()); } } updateRunnability(node); return newNode || appsChanged; }
java
{ "resource": "" }
q160699
NodeManager.getAppInfo
train
public String getAppInfo(ClusterNode node, ResourceType type) { Map<ResourceType, String> resourceInfos = nameToApps.get(node.getName()); if (resourceInfos == null) { return null; } else { return resourceInfos.get(type); } }
java
{ "resource": "" }