List of usage examples for java.security PrivilegedExceptionAction run
T run() throws Exception;
From source file:com.datatorrent.stram.client.StramClientUtils.java
public static <T> T doAs(String userName, PrivilegedExceptionAction<T> action) throws Exception { if (StringUtils.isNotBlank(userName) && !userName.equals(UserGroupInformation.getLoginUser().getShortUserName())) { LOG.info("Executing command as {}", userName); UserGroupInformation ugi = UserGroupInformation.createProxyUser(userName, UserGroupInformation.getLoginUser()); return ugi.doAs(action); } else {/*from w w w . java 2 s.co m*/ LOG.info("Executing command as if there is no login info: {}", userName); return action.run(); } }
From source file:ca.nrc.cadc.beacon.web.resources.FileItemServerResourceTest.java
@Test public void uploadFileItem() throws Exception { final Map<String, Object> requestAttributes = new HashMap<>(); final VOSURI parentURI = new VOSURI(URI.create("vos://cadc.nrc.ca!vospace/parent/sub")); final VOSURI expectedURI = new VOSURI(URI.create("vos://cadc.nrc.ca!vospace/parent/sub/MYUPLOADFILE.txt")); final DataNode expectedDataNode = new DataNode(expectedURI); final String data = "MYUPLOADDATA"; final byte[] dataBytes = data.getBytes(); final InputStream inputStream = new ByteArrayInputStream(dataBytes); final List<NodeProperty> propertyList = new ArrayList<>(); propertyList.add(new NodeProperty("ivo://ivoa.net/vospace/core#length", "" + dataBytes.length)); propertyList.add(new NodeProperty("ivo://ivoa.net/vospace/core#MD5", new String(MessageDigest.getInstance("MD5").digest(dataBytes)))); expectedDataNode.setProperties(propertyList); requestAttributes.put("path", "my/file.txt"); expect(mockRequest.getEntity()).andReturn(new EmptyRepresentation()).once(); expect(mockServletContext.getContextPath()).andReturn("/teststorage").once(); replay(mockServletContext);/*from ww w.j a v a2s. co m*/ testSubject = new FileItemServerResource(null, mockVOSpaceClient, new UploadVerifier(), new FileValidator()) { @Override public Response getResponse() { return mockResponse; } @Override ServletContext getServletContext() { return mockServletContext; } @Override public Request getRequest() { return mockRequest; } /** * Returns the request attributes. * * @return The request attributes. * @see Request#getAttributes() */ @Override public Map<String, Object> getRequestAttributes() { return requestAttributes; } @Override VOSURI getCurrentItemURI() { return parentURI; } /** * Abstract away the Transfer stuff. It's cumbersome. * * @param outputStreamWrapper The OutputStream wrapper. * @param dataNode The node to upload. * @throws Exception To capture transfer and upload failures. */ @Override void upload(UploadOutputStreamWrapper outputStreamWrapper, DataNode dataNode) throws Exception { // Do nothing. } @Override <T> T executeSecurely(PrivilegedExceptionAction<T> runnable) throws IOException { try { return runnable.run(); } catch (Exception e) { throw new RuntimeException(e); } } }; final FileItemStream mockFileItemStream = createMock(FileItemStream.class); expect(mockVOSpaceClient.getNode("/parent/sub/MYUPLOADFILE.txt")) .andThrow(new NodeNotFoundException("No such node.")).once(); expect(mockVOSpaceClient.createNode(expectedDataNode, false)).andReturn(expectedDataNode).once(); expect(mockFileItemStream.getName()).andReturn("MYUPLOADFILE.txt").once(); expect(mockFileItemStream.openStream()).andReturn(inputStream).once(); expect(mockFileItemStream.getContentType()).andReturn("text/plain").once(); replay(mockVOSpaceClient, mockResponse, mockRequest, mockFileItemStream); final VOSURI resultURI = testSubject.upload(mockFileItemStream); assertEquals("End URI is wrong.", expectedURI, resultURI); verify(mockVOSpaceClient, mockResponse, mockRequest, mockFileItemStream, mockServletContext); }
From source file:org.apache.hadoop.security.token.delegation.TestDelegationToken.java
private void shouldThrow(PrivilegedExceptionAction<Object> action, Class<? extends Throwable> except) { try {/*from w ww .j av a 2 s. co m*/ action.run(); Assert.fail("action did not throw " + except); } catch (Throwable th) { LOG.info("Caught an exception: " + StringUtils.stringifyException(th)); assertEquals("action threw wrong exception", except, th.getClass()); } }
From source file:org.apache.ranger.audit.provider.MiscUtil.java
/** * Execute the {@link PrivilegedExceptionAction} on the {@link UserGroupInformation} if it's set, otherwise call it directly *//* ww w . ja v a 2s .co m*/ public static <X> X executePrivilegedAction(final PrivilegedExceptionAction<X> action) throws Exception { final UserGroupInformation ugi = getUGILoginUser(); if (ugi != null) { return ugi.doAs(action); } else { return action.run(); } }
From source file:uk.ac.gla.terrier.probos.controller.ControllerServer.java
protected boolean storeJobScript(final JobInformation ji, final String requestorUserName, final byte[] source) throws IOException { final String jobFolderName = String.valueOf(Math.abs(random.nextInt())); final Path jobFolder = new Path(probosFolder, jobFolderName); final Path script = new Path(probosFolder, jobFolderName + ".SC"); PrivilegedExceptionAction<Path> submitAction = new PrivilegedExceptionAction<Path>() { public Path run() throws Exception { FileSystem fs = FileSystem.get(yConf); fs.mkdirs(jobFolder);//from w w w . j a v a 2s. c om OutputStream os = fs.create(script); os.write(source); os.close(); LOG.info("Wrote " + source.length + " bytes to " + script.toString() + " as the job script for job " + ji.jobId); return script; } }; //setuid to the requestor's user id UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(requestorUserName, UserGroupInformation.getLoginUser()); Path rtr = null; try { if (UserGroupInformation.isSecurityEnabled()) rtr = proxyUser.doAs(submitAction); else rtr = submitAction.run(); ji.proxyUser = proxyUser; ji.scriptLocation = rtr; ji.folderLocation = jobFolder; ji.modify(); return true; } catch (Exception e) { LOG.error("Could not store job file!", e); return false; } }
From source file:uk.ac.gla.terrier.probos.controller.ControllerServer.java
protected int yarnJob(final JobInformation ji, final String requestorUserName) throws IOException { assert ji.scriptLocation != null; assert ji.folderLocation != null; final PBSJob job = ji.jobSpec; PrivilegedExceptionAction<Integer> submitAction = new PrivilegedExceptionAction<Integer>() { public Integer run() throws Exception { File luaFile = writeJobKittenSpec(job, ji.scriptLocation, ji.jobId, false); Configuration kConf = new Configuration(yConf); kConf.set(LocalDataHelper.APP_BASE_DIR, ji.folderLocation.toUri().toString()); YarnClientParameters params = new LuaYarnClientParameters(luaFile.toString(), Constants.PRODUCT_NAME, kConf, extraLuaValues, extraLocalResources); ji.jobSpec.setQueue(params.getQueue()); Credentials creds = new Credentials(); //create delegation tokens //interactive rpc InetSocketAddress addr = NetUtils.getConnectAddress(interactiveRpcserver); Text host = new Text(addr.getAddress().getHostAddress() + ":" + addr.getPort()); ProbosDelegationTokenIdentifier tokenId = secretManager.createIdentifier(); Token<ProbosDelegationTokenIdentifier> delgationToken = new Token<ProbosDelegationTokenIdentifier>( tokenId, secretManager); delgationToken.setService(host); creds.addToken(host, delgationToken); LOG.info("Interactive: Generated token for " + creds.toString() + " : " + delgationToken); //client rpc tokenId = secretManager.createIdentifier(); delgationToken = new Token<ProbosDelegationTokenIdentifier>(tokenId, secretManager); addr = NetUtils.getConnectAddress(clientRpcserver); host = new Text(addr.getAddress().getHostAddress() + ":" + addr.getPort()); delgationToken.setService(host); creds.addToken(host, delgationToken); LOG.info("Client: Generated token for " + creds.toString() + " : " + delgationToken); //master rpc tokenId = secretManager.createIdentifier(); delgationToken = new Token<ProbosDelegationTokenIdentifier>(tokenId, secretManager); addr = NetUtils.getConnectAddress(masterRpcserver); host = new Text(addr.getAddress().getHostAddress() + ":" + addr.getPort()); delgationToken.setService(host); creds.addToken(host, delgationToken); LOG.info("Master: Generated token for " + creds.toString() + " : " + delgationToken); YarnClientService service = new YarnClientServiceImpl(params, creds); service.startAndWait();//from w w w . java 2 s. c o m if (!service.isRunning()) { LOG.error("YarnClientService failed to startup, exiting..."); jobArray.remove(ji.jobId); return ji.jobId; } ji.kitten = service; ji.modify(); return ji.jobId; } }; //setuid to the requestor's user id UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(requestorUserName, UserGroupInformation.getLoginUser()); Integer rtr = null; try { if (UserGroupInformation.isSecurityEnabled()) rtr = proxyUser.doAs(submitAction); else rtr = submitAction.run(); ji.proxyUser = proxyUser; ji.modify(); runningJobs.inc(); return rtr.intValue(); } catch (Exception e) { LOG.error("job did not submit!", e); return -1; } }
From source file:uk.ac.gla.terrier.probos.controller.ControllerServer.java
/** Kills the specified job. * @param jobId id of the job to be killed * @return 0 for success, -1 for no such job, -2 for job could not be killed * @throws Exception/*from w ww . j av a 2 s. c o m*/ */ @Override public int killJob(final int jobId, boolean purge) throws Exception { UserGroupInformation caller = Server.getRemoteUser(); LOG.info(caller + " asked to kill job " + jobId); if (!jobArray.containsKey(jobId)) return -1; final JobInformation ji = jobArray.get(jobId); checkOwnerOrRoot(ji); UserGroupInformation proxyUser = ji.proxyUser; Integer status; PrivilegedExceptionAction<Integer> doKill = new PrivilegedExceptionAction<Integer>() { public Integer run() throws Exception { final long kill_deadline = System.currentTimeMillis() + pConf.getLong(PConfiguration.KEY_CONTROLLER_KILL_TIMEOUT, 5000); YarnClientService kittenClient = ji.kitten; YarnClient yarnClient = YarnClient.createYarnClient(); yarnClient.init(yConf); yarnClient.start(); yarnClient.killApplication(kittenClient.getApplicationId()); while (!kittenClient.isApplicationFinished()) { Thread.sleep(100); if (System.currentTimeMillis() > kill_deadline) return -2; } return 0; } }; //perform the actual kill, as the user if (UserGroupInformation.isSecurityEnabled()) status = proxyUser.doAs(doKill); else status = doKill.run(); runningJobs.dec(); killedJobs.inc(); //purge, aka qdel -p. //conditional on superuser if (purge) { jobArray.remove(jobId); status = 0; } return status; }