public void configure(JobConf conf) { numberOfCenters = Integer.valueOf(conf.get("numberOfCenters")); centersDirectory = conf.get("centersReadDirectory"); try { Configuration c = new Configuration(); FileSystem fs = FileSystem.get(c); for (int index = 0; index < numberOfCenters; ++index) { SequenceFile.Reader reader = new SequenceFile.Reader(fs, new Path(centersDirectory + "/centers/" + index), c); LongWritable key = new LongWritable(); Point value = new Point(); reader.next(key, value); Point center = (Point) value; centers.add(center); reader.close(); } } catch (IOException e) { // do nothing // I hope this doesn't happen System.out.println("well, damn."); e.printStackTrace(); } }
public Writable call(Class<?> protocol, Writable param, long receivedTime) throws IOException { try { Invocation call = (Invocation) param; if (verbose) log("Call: " + call); Method method = protocol.getMethod(call.getMethodName(), call.getParameterClasses()); method.setAccessible(true); int qTime = (int) (System.currentTimeMillis() - receivedTime); long startNanoTime = System.nanoTime(); Object value = method.invoke(instance, call.getParameters()); long processingMicroTime = (System.nanoTime() - startNanoTime) / 1000; if (LOG.isDebugEnabled()) { LOG.debug( "Served: " + call.getMethodName() + " queueTime (millisec)= " + qTime + " procesingTime (microsec)= " + processingMicroTime); } rpcMetrics.rpcQueueTime.inc(qTime); rpcMetrics.rpcProcessingTime.inc(processingMicroTime); MetricsTimeVaryingRate m = (MetricsTimeVaryingRate) rpcMetrics.registry.get(call.getMethodName()); if (m == null) { try { m = new MetricsTimeVaryingRate(call.getMethodName(), rpcMetrics.registry); } catch (IllegalArgumentException iae) { // the metrics has been registered; re-fetch the handle LOG.debug("Error register " + call.getMethodName(), iae); m = (MetricsTimeVaryingRate) rpcMetrics.registry.get(call.getMethodName()); } } // record call time in microseconds m.inc(processingMicroTime); if (verbose) log("Return: " + value); return new ObjectWritable(method.getReturnType(), value); } catch (InvocationTargetException e) { Throwable target = e.getTargetException(); if (target instanceof IOException) { throw (IOException) target; } else { IOException ioe = new IOException(target.toString()); ioe.setStackTrace(target.getStackTrace()); throw ioe; } } catch (Throwable e) { if (!(e instanceof IOException)) { LOG.error("Unexpected throwable object ", e); } IOException ioe = new IOException(e.toString()); ioe.setStackTrace(e.getStackTrace()); throw ioe; } }
/** * Get the cause of an I/O exception if caused by a possible disk error * * @param ioe an I/O exception * @return cause if the I/O exception is caused by a possible disk error; null otherwise. */ static IOException getCauseIfDiskError(IOException ioe) { if (ioe.getMessage() != null && ioe.getMessage().startsWith(DISK_ERROR)) { return (IOException) ioe.getCause(); } else { return null; } }
// // The main work loop // public void run() { // // Poll the Namenode (once every 5 minutes) to find the size of the // pending edit log. // long period = 5 * 60; // 5 minutes long lastCheckpointTime = 0; if (checkpointPeriod < period) { period = checkpointPeriod; } while (shouldRun) { try { Thread.sleep(1000 * period); } catch (InterruptedException ie) { // do nothing } if (!shouldRun) { break; } try { long now = System.currentTimeMillis(); long size = namenode.getEditLogSize(); if (size >= checkpointSize || now >= lastCheckpointTime + 1000 * checkpointPeriod) { doCheckpoint(); lastCheckpointTime = now; } } catch (IOException e) { LOG.error("Exception in doCheckpoint: "); LOG.error(StringUtils.stringifyException(e)); e.printStackTrace(); checkpointImage.imageDigest = null; } catch (Throwable e) { LOG.error("Throwable Exception in doCheckpoint: "); LOG.error(StringUtils.stringifyException(e)); e.printStackTrace(); Runtime.getRuntime().exit(-1); } } }
/** * Construct a client-side proxy that implements the named protocol, talking to a server at the * named address. * * @param protocol protocol * @param clientVersion client's version * @param addr server address * @param ticket security ticket * @param conf configuration * @param factory socket factory * @param rpcTimeout max time for each rpc; 0 means no timeout * @return the proxy * @throws IOException if any error occurs */ @SuppressWarnings("unchecked") public static <T extends VersionedProtocol> ProtocolProxy<T> getProtocolProxy( Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout) throws IOException { T proxy = (T) Proxy.newProxyInstance( protocol.getClassLoader(), new Class[] {protocol}, new Invoker(addr, ticket, conf, factory, rpcTimeout, protocol)); String protocolName = protocol.getName(); try { ProtocolSignature serverInfo = proxy.getProtocolSignature( protocolName, clientVersion, ProtocolSignature.getFingerprint(protocol.getMethods())); return new ProtocolProxy<T>(protocol, proxy, serverInfo.getMethods()); } catch (RemoteException re) { IOException ioe = re.unwrapRemoteException(IOException.class); if (ioe.getMessage() .startsWith(IOException.class.getName() + ": " + NoSuchMethodException.class.getName())) { // Method getProtocolSignature not supported long serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion); if (serverVersion == clientVersion) { return new ProtocolProxy<T>(protocol, proxy, null); } throw new VersionMismatch(protocolName, clientVersion, serverVersion, proxy); } throw re; } }
public BufferedReader loadDataFromFile(String filepath, long offset) { try { Path pt = new Path(filepath); FileSystem fs = FileSystem.get(fsConf); InputStreamReader isr; if (fs.isDirectory(pt)) { // multiple parts isr = new InputStreamReader(OpenMultiplePartsWithOffset(fs, pt, offset)); } else { // single file FSDataInputStream fileHandler = fs.open(pt); if (offset > 0) fileHandler.seek(offset); isr = new InputStreamReader(fileHandler); } BufferedReader reader = new BufferedReader(isr); if (offset > 0) reader.readLine(); // skip first line in case of seek return reader; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } assert false : "Should not reach here!"; return null; }
public void generateFileChunks(JspWriter out, HttpServletRequest req) throws IOException { long startOffset = 0; int chunkSizeToView = 0; String referrer = req.getParameter("referrer"); boolean noLink = false; if (referrer == null) { noLink = true; } String filename = req.getParameter("filename"); if (filename == null) { out.print("Invalid input (file name absent)"); return; } String namenodeInfoPortStr = req.getParameter("namenodeInfoPort"); int namenodeInfoPort = -1; if (namenodeInfoPortStr != null) namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr); String chunkSizeToViewStr = req.getParameter("chunkSizeToView"); if (chunkSizeToViewStr != null && Integer.parseInt(chunkSizeToViewStr) > 0) chunkSizeToView = Integer.parseInt(chunkSizeToViewStr); else chunkSizeToView = jspHelper.defaultChunkSizeToView; if (!noLink) { out.print("<h3>Tail of File: "); JspHelper.printPathWithLinks(filename, out, namenodeInfoPort); out.print("</h3><hr>"); out.print("<a href=\"" + referrer + "\">Go Back to File View</a><hr>"); } else { out.print("<h3>" + filename + "</h3>"); } out.print("<b>Chunk size to view (in bytes, up to file's DFS block size): </b>"); out.print( "<input type=\"text\" name=\"chunkSizeToView\" value=" + chunkSizeToView + " size=10 maxlength=10>"); out.print(" <input type=\"submit\" name=\"submit\" value=\"Refresh\"><hr>"); out.print("<input type=\"hidden\" name=\"filename\" value=\"" + filename + "\">"); out.print( "<input type=\"hidden\" name=\"namenodeInfoPort\" value=\"" + namenodeInfoPort + "\">"); if (!noLink) out.print("<input type=\"hidden\" name=\"referrer\" value=\"" + referrer + "\">"); // fetch the block from the datanode that has the last block for this file DFSClient dfs = new DFSClient(jspHelper.nameNodeAddr, jspHelper.conf); List<LocatedBlock> blocks = dfs.namenode.getBlockLocations(filename, 0, Long.MAX_VALUE).getLocatedBlocks(); if (blocks == null || blocks.size() == 0) { out.print("No datanodes contain blocks of file " + filename); dfs.close(); return; } LocatedBlock lastBlk = blocks.get(blocks.size() - 1); long blockSize = lastBlk.getBlock().getNumBytes(); long blockId = lastBlk.getBlock().getBlockId(); long genStamp = lastBlk.getBlock().getGenerationStamp(); DatanodeInfo chosenNode; try { chosenNode = jspHelper.bestNode(lastBlk); } catch (IOException e) { out.print(e.toString()); dfs.close(); return; } InetSocketAddress addr = NetUtils.createSocketAddr(chosenNode.getName()); // view the last chunkSizeToView bytes while Tailing if (blockSize >= chunkSizeToView) startOffset = blockSize - chunkSizeToView; else startOffset = 0; out.print("<textarea cols=\"100\" rows=\"25\" wrap=\"virtual\" style=\"width:100%\" READONLY>"); jspHelper.streamBlockInAscii( addr, blockId, genStamp, blockSize, startOffset, chunkSizeToView, out); out.print("</textarea>"); dfs.close(); }
@Override public Writable call( org.apache.hadoop.ipc.RPC.Server server, String protocolName, Writable rpcRequest, long receivedTime) throws IOException { try { Invocation call = (Invocation) rpcRequest; if (server.verbose) log("Call: " + call); // Verify rpc version if (call.getRpcVersion() != writableRpcVersion) { // Client is using a different version of WritableRpc throw new IOException( "WritableRpc version mismatch, client side version=" + call.getRpcVersion() + ", server side version=" + writableRpcVersion); } long clientVersion = call.getProtocolVersion(); final String protoName; ProtoClassProtoImpl protocolImpl; if (call.declaringClassProtocolName.equals(VersionedProtocol.class.getName())) { // VersionProtocol methods are often used by client to figure out // which version of protocol to use. // // Versioned protocol methods should go the protocolName protocol // rather than the declaring class of the method since the // the declaring class is VersionedProtocol which is not // registered directly. // Send the call to the highest protocol version VerProtocolImpl highest = server.getHighestSupportedProtocol(RPC.RpcKind.RPC_WRITABLE, protocolName); if (highest == null) { throw new IOException("Unknown protocol: " + protocolName); } protocolImpl = highest.protocolTarget; } else { protoName = call.declaringClassProtocolName; // Find the right impl for the protocol based on client version. ProtoNameVer pv = new ProtoNameVer(call.declaringClassProtocolName, clientVersion); protocolImpl = server.getProtocolImplMap(RPC.RpcKind.RPC_WRITABLE).get(pv); if (protocolImpl == null) { // no match for Protocol AND Version VerProtocolImpl highest = server.getHighestSupportedProtocol(RPC.RpcKind.RPC_WRITABLE, protoName); if (highest == null) { throw new IOException("Unknown protocol: " + protoName); } else { // protocol supported but not the version that client wants throw new RPC.VersionMismatch(protoName, clientVersion, highest.version); } } } // Invoke the protocol method long startTime = Time.now(); Method method = protocolImpl.protocolClass.getMethod( call.getMethodName(), call.getParameterClasses()); method.setAccessible(true); server.rpcDetailedMetrics.init(protocolImpl.protocolClass); Object value = method.invoke(protocolImpl.protocolImpl, call.getParameters()); int processingTime = (int) (Time.now() - startTime); int qTime = (int) (startTime - receivedTime); if (LOG.isDebugEnabled()) { LOG.debug( "Served: " + call.getMethodName() + " queueTime= " + qTime + " procesingTime= " + processingTime); } server.rpcMetrics.addRpcQueueTime(qTime); server.rpcMetrics.addRpcProcessingTime(processingTime); server.rpcDetailedMetrics.addProcessingTime(call.getMethodName(), processingTime); if (server.verbose) log("Return: " + value); return new ObjectWritable(method.getReturnType(), value); } catch (InvocationTargetException e) { Throwable target = e.getTargetException(); if (target instanceof IOException) { throw (IOException) target; } else { IOException ioe = new IOException(target.toString()); ioe.setStackTrace(target.getStackTrace()); throw ioe; } } catch (Throwable e) { if (!(e instanceof IOException)) { LOG.error("Unexpected throwable object ", e); } IOException ioe = new IOException(e.toString()); ioe.setStackTrace(e.getStackTrace()); throw ioe; } }
/** * @param argv The parameters passed to this program. * @exception Exception if the filesystem does not exist. * @return 0 on success, non zero on error. */ private int processArgs(String[] argv) throws Exception { if (argv.length < 1) { printUsage(""); return -1; } int exitCode = -1; int i = 0; String cmd = argv[i++]; // // verify that we have enough command line parameters // if ("-geteditsize".equals(cmd)) { if (argv.length != 1) { printUsage(cmd); return exitCode; } } else if ("-checkpoint".equals(cmd)) { if (argv.length != 1 && argv.length != 2) { printUsage(cmd); return exitCode; } if (argv.length == 2 && !"force".equals(argv[i])) { printUsage(cmd); return exitCode; } } exitCode = 0; try { if ("-checkpoint".equals(cmd)) { long size = namenode.getEditLogSize(); if (size >= checkpointSize || argv.length == 2 && "force".equals(argv[i])) { doCheckpoint(); } else { System.err.println( "EditLog size " + size + " bytes is " + "smaller than configured checkpoint " + "size " + checkpointSize + " bytes."); System.err.println("Skipping checkpoint."); } } else if ("-geteditsize".equals(cmd)) { long size = namenode.getEditLogSize(); System.out.println("EditLog size is " + size + " bytes"); } else { exitCode = -1; LOG.error(cmd.substring(1) + ": Unknown command"); printUsage(""); } } catch (RemoteException e) { // // This is a error returned by hadoop server. Print // out the first line of the error mesage, ignore the stack trace. exitCode = -1; try { String[] content; content = e.getLocalizedMessage().split("\n"); LOG.error(cmd.substring(1) + ": " + content[0]); } catch (Exception ex) { LOG.error(cmd.substring(1) + ": " + ex.getLocalizedMessage()); } } catch (IOException e) { // // IO exception encountered locally. // exitCode = -1; LOG.error(cmd.substring(1) + ": " + e.getLocalizedMessage()); } finally { // Does the RPC connection need to be closed? } return exitCode; }
public void generateFileDetails(JspWriter out, HttpServletRequest req, Configuration conf) throws IOException, InterruptedException { int chunkSizeToView = 0; long startOffset = 0; int datanodePort; String blockIdStr = null; long currBlockId = 0; blockIdStr = req.getParameter("blockId"); if (blockIdStr == null) { out.print("Invalid input (blockId absent)"); return; } currBlockId = Long.parseLong(blockIdStr); String datanodePortStr = req.getParameter("datanodePort"); if (datanodePortStr == null) { out.print("Invalid input (datanodePort absent)"); return; } datanodePort = Integer.parseInt(datanodePortStr); String namenodeInfoPortStr = req.getParameter("namenodeInfoPort"); int namenodeInfoPort = -1; if (namenodeInfoPortStr != null) namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr); String chunkSizeToViewStr = req.getParameter("chunkSizeToView"); if (chunkSizeToViewStr != null && Integer.parseInt(chunkSizeToViewStr) > 0) { chunkSizeToView = Integer.parseInt(chunkSizeToViewStr); } else { chunkSizeToView = JspHelper.getDefaultChunkSize(conf); } String startOffsetStr = req.getParameter("startOffset"); if (startOffsetStr == null || Long.parseLong(startOffsetStr) < 0) startOffset = 0; else startOffset = Long.parseLong(startOffsetStr); String filename = HtmlQuoting.unquoteHtmlChars(req.getParameter("filename")); if (filename == null || filename.length() == 0) { out.print("Invalid input"); return; } String blockSizeStr = req.getParameter("blockSize"); long blockSize = 0; if (blockSizeStr == null || blockSizeStr.length() == 0) { out.print("Invalid input"); return; } blockSize = Long.parseLong(blockSizeStr); String tokenString = req.getParameter(JspHelper.DELEGATION_PARAMETER_NAME); UserGroupInformation ugi = JspHelper.getUGI(req, conf); DFSClient dfs = JspHelper.getDFSClient(ugi, jspHelper.nameNodeAddr, conf); List<LocatedBlock> blocks = dfs.namenode.getBlockLocations(filename, 0, Long.MAX_VALUE).getLocatedBlocks(); // Add the various links for looking at the file contents // URL for downloading the full file String downloadUrl = "http://" + req.getServerName() + ":" + +req.getServerPort() + "/streamFile" + URLEncoder.encode(filename, "UTF-8") + "?" + JspHelper.DELEGATION_PARAMETER_NAME + "=" + tokenString; out.print("<a name=\"viewOptions\"></a>"); out.print("<a href=\"" + downloadUrl + "\">Download this file</a><br>"); DatanodeInfo chosenNode; // URL for TAIL LocatedBlock lastBlk = blocks.get(blocks.size() - 1); long blockId = lastBlk.getBlock().getBlockId(); try { chosenNode = jspHelper.bestNode(lastBlk); } catch (IOException e) { out.print(e.toString()); dfs.close(); return; } String fqdn = InetAddress.getByName(chosenNode.getHost()).getCanonicalHostName(); String tailUrl = "http://" + fqdn + ":" + chosenNode.getInfoPort() + "/tail.jsp?filename=" + URLEncoder.encode(filename, "UTF-8") + "&namenodeInfoPort=" + namenodeInfoPort + "&chunkSizeToView=" + chunkSizeToView + "&referrer=" + URLEncoder.encode(req.getRequestURL() + "?" + req.getQueryString(), "UTF-8") + JspHelper.getDelegationTokenUrlParam(tokenString); out.print("<a href=\"" + tailUrl + "\">Tail this file</a><br>"); out.print("<form action=\"/browseBlock.jsp\" method=GET>"); out.print("<b>Chunk size to view (in bytes, up to file's DFS block size): </b>"); out.print("<input type=\"hidden\" name=\"blockId\" value=\"" + currBlockId + "\">"); out.print("<input type=\"hidden\" name=\"blockSize\" value=\"" + blockSize + "\">"); out.print("<input type=\"hidden\" name=\"startOffset\" value=\"" + startOffset + "\">"); out.print("<input type=\"hidden\" name=\"filename\" value=\"" + filename + "\">"); out.print("<input type=\"hidden\" name=\"datanodePort\" value=\"" + datanodePort + "\">"); out.print( "<input type=\"hidden\" name=\"namenodeInfoPort\" value=\"" + namenodeInfoPort + "\">"); out.print( "<input type=\"text\" name=\"chunkSizeToView\" value=" + chunkSizeToView + " size=10 maxlength=10>"); out.print(" <input type=\"submit\" name=\"submit\" value=\"Refresh\">"); out.print("</form>"); out.print("<hr>"); out.print("<a name=\"blockDetails\"></a>"); out.print("<B>Total number of blocks: " + blocks.size() + "</B><br>"); // generate a table and dump the info out.println("\n<table>"); for (LocatedBlock cur : blocks) { out.print("<tr>"); blockId = cur.getBlock().getBlockId(); blockSize = cur.getBlock().getNumBytes(); String blk = "blk_" + Long.toString(blockId); out.print("<td>" + Long.toString(blockId) + ":</td>"); DatanodeInfo[] locs = cur.getLocations(); for (int j = 0; j < locs.length; j++) { String datanodeAddr = locs[j].getName(); datanodePort = Integer.parseInt( datanodeAddr.substring(datanodeAddr.indexOf(':') + 1, datanodeAddr.length())); fqdn = InetAddress.getByName(locs[j].getHost()).getCanonicalHostName(); String blockUrl = "http://" + fqdn + ":" + locs[j].getInfoPort() + "/browseBlock.jsp?blockId=" + Long.toString(blockId) + "&blockSize=" + blockSize + "&filename=" + URLEncoder.encode(filename, "UTF-8") + "&datanodePort=" + datanodePort + "&genstamp=" + cur.getBlock().getGenerationStamp() + "&namenodeInfoPort=" + namenodeInfoPort + "&chunkSizeToView=" + chunkSizeToView; out.print( "<td> </td>" + "<td><a href=\"" + blockUrl + "\">" + datanodeAddr + "</a></td>"); } out.println("</tr>"); } out.println("</table>"); out.print("<hr>"); String namenodeHost = jspHelper.nameNodeAddr.getHostName(); out.print( "<br><a href=\"http://" + InetAddress.getByName(namenodeHost).getCanonicalHostName() + ":" + namenodeInfoPort + "/dfshealth.jsp\">Go back to DFS home</a>"); dfs.close(); }