http://git-wip-us.apache.org/repos/asf/airavata/blob/7b809747/modules/gfac/gfac-gsissh/src/main/java/org/apache/airavata/gfac/gsissh/security/TokenizedMyProxyAuthInfo.java ---------------------------------------------------------------------- diff --git a/modules/gfac/gfac-gsissh/src/main/java/org/apache/airavata/gfac/gsissh/security/TokenizedMyProxyAuthInfo.java b/modules/gfac/gfac-gsissh/src/main/java/org/apache/airavata/gfac/gsissh/security/TokenizedMyProxyAuthInfo.java deleted file mode 100644 index 7a2e885..0000000 --- a/modules/gfac/gfac-gsissh/src/main/java/org/apache/airavata/gfac/gsissh/security/TokenizedMyProxyAuthInfo.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ -package org.apache.airavata.gfac.gsissh.security; - -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.credential.store.credential.Credential; -import org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential; -import org.apache.airavata.credential.store.store.CredentialReader; -import org.apache.airavata.gfac.Constants; -import org.apache.airavata.gfac.GFacException; -import org.apache.airavata.gfac.RequestData; -import org.apache.airavata.gfac.core.utils.GFacUtils; -import org.apache.airavata.gsi.ssh.api.authentication.AuthenticationInfo; -import org.apache.airavata.gsi.ssh.api.authentication.GSIAuthenticationInfo; -import org.globus.gsi.X509Credential; -import org.globus.gsi.gssapi.GlobusGSSCredentialImpl; -import org.globus.gsi.provider.GlobusProvider; -import org.globus.myproxy.GetParams; -import org.globus.myproxy.MyProxy; -import org.globus.myproxy.MyProxyException; -import org.gridforum.jgss.ExtendedGSSCredential; -import org.ietf.jgss.GSSCredential; -import org.ietf.jgss.GSSException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.security.Security; -import java.security.cert.X509Certificate; - -public class TokenizedMyProxyAuthInfo extends GSIAuthenticationInfo { - protected static final Logger log = LoggerFactory.getLogger(TokenizedMyProxyAuthInfo.class); - - public static int CREDENTIAL_RENEWING_THRESH_HOLD = 10 * 90; - - private GSSCredential gssCredentials = null; - - - private CredentialReader credentialReader; - - private RequestData requestData; - - public static final String X509_CERT_DIR = "X509_CERT_DIR"; - - - static { - Security.addProvider(new GlobusProvider()); - try { - setUpTrustedCertificatePath(); - } catch (ApplicationSettingsException e) { - log.error(e.getLocalizedMessage(), e); - } - } - - public static void setUpTrustedCertificatePath(String trustedCertificatePath) { - - File file = new File(trustedCertificatePath); - - if (!file.exists() || !file.canRead()) { - File f = new File("."); - log.info("Current directory " + f.getAbsolutePath()); - throw new RuntimeException("Cannot read trusted certificate path " + trustedCertificatePath); - } else { - System.setProperty(Constants.TRUSTED_CERTIFICATE_SYSTEM_PROPERTY, file.getAbsolutePath()); - } - } - - private static void setUpTrustedCertificatePath() throws ApplicationSettingsException { - - String trustedCertificatePath = ServerSettings.getSetting(Constants.TRUSTED_CERT_LOCATION); - - setUpTrustedCertificatePath(trustedCertificatePath); - } - - public TokenizedMyProxyAuthInfo(CredentialReader credentialReader, RequestData requestData) { - this.credentialReader = credentialReader; - this.requestData = requestData; - try { - properties.setProperty(X509_CERT_DIR, ServerSettings.getSetting(Constants.TRUSTED_CERT_LOCATION)); - } catch (ApplicationSettingsException e) { - log.error("Error while reading server properties", e); - }; - } - - public TokenizedMyProxyAuthInfo(RequestData requestData) { - this.requestData = requestData; - try { - properties.setProperty(X509_CERT_DIR, ServerSettings.getSetting(Constants.TRUSTED_CERT_LOCATION)); - } catch (ApplicationSettingsException e) { - log.error("Error while reading server properties", e); - }; - } - - public GSSCredential getCredentials() throws SecurityException { - - if (gssCredentials == null) { - - try { - gssCredentials = getCredentialsFromStore(); - } catch (Exception e) { - log.error("An exception occurred while retrieving credentials from the credential store. " + - "Will continue with my proxy user name and password. Provided TokenId:" + requestData.getTokenId(), e); - } - - if (gssCredentials == null) { - System.out.println("Authenticating with provided token failed, so falling back to authenticate with defaultCredentials"); - try { - gssCredentials = getDefaultCredentials(); - } catch (Exception e) { - throw new SecurityException("Error retrieving my proxy using username password"); - } - } - // if still null, throw an exception - if (gssCredentials == null) { - throw new SecurityException("Unable to retrieve my proxy credentials to continue operation."); - } - } else { - try { - if (gssCredentials.getRemainingLifetime() < CREDENTIAL_RENEWING_THRESH_HOLD) { - try { - return renewCredentials(); - } catch (Exception e) { - throw new SecurityException("Error renewing credentials", e); - } - } - } catch (GSSException e) { - throw new SecurityException("Unable to retrieve remaining life time from credentials.", e); - } - } - - return gssCredentials; - } - - - /** - * Reads the credentials from credential store. - * - * @return If token is found in the credential store, will return a valid credential. Else returns null. - * @throws Exception If an error occurred while retrieving credentials. - */ - public GSSCredential getCredentialsFromStore() throws Exception { - - if (getCredentialReader() == null) { - credentialReader = GFacUtils.getCredentialReader(); - if(credentialReader == null){ - return null; - } - } - - Credential credential = getCredentialReader().getCredential(getRequestData().getGatewayId(), - getRequestData().getTokenId()); - - if (credential != null) { - if (credential instanceof CertificateCredential) { - - log.info("Successfully found credentials for token id - " + getRequestData().getTokenId() + - " gateway id - " + getRequestData().getGatewayId()); - - CertificateCredential certificateCredential = (CertificateCredential) credential; - - X509Certificate[] certificates = certificateCredential.getCertificates(); - X509Credential newCredential = new X509Credential(certificateCredential.getPrivateKey(), certificates); - - GlobusGSSCredentialImpl cred = new GlobusGSSCredentialImpl(newCredential, GSSCredential.INITIATE_AND_ACCEPT); - System.out.print(cred.export(ExtendedGSSCredential.IMPEXP_OPAQUE)); - return cred; - //return new GlobusGSSCredentialImpl(newCredential, - // GSSCredential.INITIATE_AND_ACCEPT); - } else { - log.info("Credential type is not CertificateCredential. Cannot create mapping globus credentials. " + - "Credential type - " + credential.getClass().getName()); - } - } else { - log.info("Could not find credentials for token - " + getRequestData().getTokenId() + " and " - + "gateway id - " + getRequestData().getGatewayId()); - } - - return null; - } - - /** - * Renew GSSCredentials. - * Before executing we need to add current host as a trusted renewer. Note to renew credentials - * we dont need user name and password. - * To do that execute following command - * > myproxy-logon -t <LIFETIME></LIFETIME> -s <MY PROXY SERVER> -l <USER NAME> - * E.g :- > myproxy-logon -t 264 -s myproxy.teragrid.org -l us3 - * Enter MyProxy pass phrase: - * A credential has been received for user us3 in /tmp/x509up_u501. - * > myproxy-init -A --cert /tmp/x509up_u501 --key /tmp/x509up_u501 -l ogce -s myproxy.teragrid.org - * - * @return Renewed credentials. - * @throws org.apache.airavata.gfac.GFacException If an error occurred while renewing credentials. - * @throws org.apache.airavata.common.exception.ApplicationSettingsException - */ - public GSSCredential renewCredentialsAsATrustedHost() throws GFacException, ApplicationSettingsException { - MyProxy myproxy = new MyProxy(getRequestData().getMyProxyServerUrl(), getRequestData().getMyProxyPort()); - GetParams getParams = new GetParams(); - getParams.setAuthzCreds(gssCredentials); - getParams.setUserName(getRequestData().getMyProxyUserName()); - getParams.setLifetime(getRequestData().getMyProxyLifeTime()); - try { - return myproxy.get(gssCredentials, getParams); - } catch (MyProxyException e) { - throw new GFacException("An error occurred while renewing security credentials.", e); - } - } - - - /** - * Gets the default proxy certificate. - * - * @return Default my proxy credentials. - * @throws org.apache.airavata.gfac.GFacException If an error occurred while retrieving credentials. - * @throws org.apache.airavata.common.exception.ApplicationSettingsException - */ - public GSSCredential getDefaultCredentials() throws GFacException, ApplicationSettingsException { - MyProxy myproxy = new MyProxy(getRequestData().getMyProxyServerUrl(), getRequestData().getMyProxyPort()); - try { - return myproxy.get(getRequestData().getMyProxyUserName(), getRequestData().getMyProxyPassword(), - getRequestData().getMyProxyLifeTime()); - } catch (MyProxyException e) { - throw new GFacException("An error occurred while retrieving default security credentials.", e); - } - } - - - /** - * Renews credentials. First try to renew credentials as a trusted renewer. If that failed - * use user name and password to renew credentials. - * - * @return Renewed credentials. - * @throws org.apache.airavata.gfac.GFacException If an error occurred while renewing credentials. - * @throws org.apache.airavata.common.exception.ApplicationSettingsException - */ - public GSSCredential renewCredentials() throws GFacException, ApplicationSettingsException { - - // First try to renew credentials as a trusted renewer - try { - gssCredentials = renewCredentialsAsATrustedHost(); - } catch (Exception e) { - log.warn("Renewing credentials as a trusted renewer failed", e); - gssCredentials = getDefaultCredentials(); - } - - return gssCredentials; - } - - /** - * Gets a new proxy certificate given current credentials. - * - * @return The short lived GSSCredentials - * @throws org.apache.airavata.gfac.GFacException If an error is occurred while retrieving credentials. - * @throws org.apache.airavata.common.exception.ApplicationSettingsException - */ - public GSSCredential getProxyCredentials() throws GFacException, ApplicationSettingsException { - - MyProxy myproxy = new MyProxy(getRequestData().getMyProxyServerUrl(), getRequestData().getMyProxyPort()); - try { - return myproxy.get(gssCredentials, getRequestData().getMyProxyUserName(), getRequestData().getMyProxyPassword(), - getRequestData().getMyProxyLifeTime()); - } catch (MyProxyException e) { - throw new GFacException("An error occurred while renewing security credentials using user/password.", e); - } - } - - public void setGssCredentials(GSSCredential gssCredentials) { - this.gssCredentials = gssCredentials; - } - - public CredentialReader getCredentialReader() { - return credentialReader; - } - - public void setCredentialReader(CredentialReader credentialReader) { - this.credentialReader = credentialReader; - } - - public RequestData getRequestData() { - return requestData; - } - - public void setRequestData(RequestData requestData) { - this.requestData = requestData; - } -}
http://git-wip-us.apache.org/repos/asf/airavata/blob/7b809747/modules/gfac/gfac-gsissh/src/main/java/org/apache/airavata/gfac/gsissh/util/GFACGSISSHUtils.java ---------------------------------------------------------------------- diff --git a/modules/gfac/gfac-gsissh/src/main/java/org/apache/airavata/gfac/gsissh/util/GFACGSISSHUtils.java b/modules/gfac/gfac-gsissh/src/main/java/org/apache/airavata/gfac/gsissh/util/GFACGSISSHUtils.java deleted file mode 100644 index 0428bc0..0000000 --- a/modules/gfac/gfac-gsissh/src/main/java/org/apache/airavata/gfac/gsissh/util/GFACGSISSHUtils.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ -package org.apache.airavata.gfac.gsissh.util; - -import org.airavata.appcatalog.cpi.AppCatalog; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential; -import org.apache.airavata.credential.store.store.CredentialReader; -import org.apache.airavata.gfac.GFacException; -import org.apache.airavata.gfac.RequestData; -import org.apache.airavata.gfac.core.context.JobExecutionContext; -import org.apache.airavata.gfac.core.context.MessageContext; -import org.apache.airavata.gfac.core.utils.GFacUtils; -import org.apache.airavata.gfac.gsissh.security.GSISecurityContext; -import org.apache.airavata.gfac.gsissh.security.TokenizedMyProxyAuthInfo; -import org.apache.airavata.gsi.ssh.api.Cluster; -import org.apache.airavata.gsi.ssh.api.ServerInfo; -import org.apache.airavata.gsi.ssh.api.job.JobDescriptor; -import org.apache.airavata.gsi.ssh.api.job.JobManagerConfiguration; -import org.apache.airavata.gsi.ssh.impl.GSISSHAbstractCluster; -import org.apache.airavata.gsi.ssh.impl.PBSCluster; -import org.apache.airavata.gsi.ssh.util.CommonUtils; -import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription; -import org.apache.airavata.model.appcatalog.appdeployment.ApplicationParallelismType; -import org.apache.airavata.model.appcatalog.appinterface.DataType; -import org.apache.airavata.model.appcatalog.appinterface.InputDataObjectType; -import org.apache.airavata.model.appcatalog.appinterface.OutputDataObjectType; -import org.apache.airavata.model.appcatalog.computeresource.*; -import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference; -import org.apache.airavata.model.workspace.experiment.ComputationalResourceScheduling; -import org.apache.airavata.model.workspace.experiment.TaskDetails; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.util.*; - - -public class GFACGSISSHUtils { - private final static Logger logger = LoggerFactory.getLogger(GFACGSISSHUtils.class); - - public static final String PBS_JOB_MANAGER = "pbs"; - public static final String SLURM_JOB_MANAGER = "slurm"; - public static final String SUN_GRID_ENGINE_JOB_MANAGER = "UGE"; - public static final String LSF_JOB_MANAGER = "lsf"; - - public static int maxClusterCount = 5; - public static Map<String, List<Cluster>> clusters = new HashMap<String, List<Cluster>>(); - - public static void addSecurityContext(JobExecutionContext jobExecutionContext) throws GFacException, ApplicationSettingsException { - JobSubmissionInterface jobSubmissionInterface = jobExecutionContext.getPreferredJobSubmissionInterface(); - JobSubmissionProtocol jobProtocol = jobSubmissionInterface.getJobSubmissionProtocol(); - try { - AppCatalog appCatalog = jobExecutionContext.getAppCatalog(); - SSHJobSubmission sshJobSubmission = appCatalog.getComputeResource().getSSHJobSubmission(jobSubmissionInterface.getJobSubmissionInterfaceId()); - if (jobProtocol == JobSubmissionProtocol.GLOBUS || jobProtocol == JobSubmissionProtocol.UNICORE - || jobProtocol == JobSubmissionProtocol.CLOUD || jobProtocol == JobSubmissionProtocol.LOCAL) { - logger.error("This is a wrong method to invoke to non ssh host types,please check your gfac-config.xml"); - } else if (jobProtocol == JobSubmissionProtocol.SSH && sshJobSubmission.getSecurityProtocol() == SecurityProtocol.GSI) { - String credentialStoreToken = jobExecutionContext.getCredentialStoreToken(); // this is set by the framework - RequestData requestData = new RequestData(jobExecutionContext.getGatewayID()); - requestData.setTokenId(credentialStoreToken); - PBSCluster pbsCluster = null; - GSISecurityContext context = null; - - TokenizedMyProxyAuthInfo tokenizedMyProxyAuthInfo = new TokenizedMyProxyAuthInfo(requestData); - CredentialReader credentialReader = GFacUtils.getCredentialReader(); - if (credentialReader != null) { - CertificateCredential credential = null; - try { - credential = (CertificateCredential) credentialReader.getCredential(jobExecutionContext.getGatewayID(), credentialStoreToken); - requestData.setMyProxyUserName(credential.getCommunityUser().getUserName()); - } catch (Exception e) { - logger.error(e.getLocalizedMessage()); - } - } - - String key = requestData.getMyProxyUserName() + jobExecutionContext.getHostName()+ - sshJobSubmission.getSshPort(); - boolean recreate = false; - synchronized (clusters) { - if (clusters.containsKey(key) && clusters.get(key).size() < maxClusterCount) { - recreate = true; - } else if (clusters.containsKey(key)) { - int i = new Random().nextInt(Integer.MAX_VALUE) % maxClusterCount; - if (clusters.get(key).get(i).getSession().isConnected()) { - pbsCluster = (PBSCluster) clusters.get(key).get(i); - } else { - clusters.get(key).remove(i); - recreate = true; - } - if (!recreate) { - try { - pbsCluster.listDirectory("~/"); // its hard to trust isConnected method, so we try to connect if it works we are good,else we recreate - } catch (Exception e) { - clusters.get(key).remove(i); - logger.info("Connection found the connection map is expired, so we create from the scratch"); - maxClusterCount++; - recreate = true; // we make the pbsCluster to create again if there is any exception druing connection - } - logger.info("Re-using the same connection used with the connection string:" + key); - context = new GSISecurityContext(tokenizedMyProxyAuthInfo.getCredentialReader(), requestData, pbsCluster); - } - } else { - recreate = true; - } - - if (recreate) { - ServerInfo serverInfo = new ServerInfo(requestData.getMyProxyUserName(), jobExecutionContext.getHostName(), - sshJobSubmission.getSshPort()); - - JobManagerConfiguration jConfig = null; - String installedParentPath = sshJobSubmission.getResourceJobManager().getJobManagerBinPath(); - String jobManager = sshJobSubmission.getResourceJobManager().getResourceJobManagerType().toString(); - if (jobManager == null) { - logger.error("No Job Manager is configured, so we are picking pbs as the default job manager"); - jConfig = CommonUtils.getPBSJobManager(installedParentPath); - } else { - if (PBS_JOB_MANAGER.equalsIgnoreCase(jobManager)) { - jConfig = CommonUtils.getPBSJobManager(installedParentPath); - } else if (SLURM_JOB_MANAGER.equalsIgnoreCase(jobManager)) { - jConfig = CommonUtils.getSLURMJobManager(installedParentPath); - } else if (SUN_GRID_ENGINE_JOB_MANAGER.equalsIgnoreCase(jobManager)) { - jConfig = CommonUtils.getUGEJobManager(installedParentPath); - }else if(LSF_JOB_MANAGER.equalsIgnoreCase(jobManager)) { - jConfig = CommonUtils.getLSFJobManager(installedParentPath); - } - } - pbsCluster = new PBSCluster(serverInfo, tokenizedMyProxyAuthInfo, jConfig); - context = new GSISecurityContext(tokenizedMyProxyAuthInfo.getCredentialReader(), requestData, pbsCluster); - List<Cluster> pbsClusters = null; - if (!(clusters.containsKey(key))) { - pbsClusters = new ArrayList<Cluster>(); - } else { - pbsClusters = clusters.get(key); - } - pbsClusters.add(pbsCluster); - clusters.put(key, pbsClusters); - } - } - - jobExecutionContext.addSecurityContext(jobExecutionContext.getHostName(), context); - } - } catch (Exception e) { - throw new GFacException("An error occurred while creating GSI security context", e); - } - } - - public static JobDescriptor createJobDescriptor(JobExecutionContext jobExecutionContext, Cluster cluster) { - JobDescriptor jobDescriptor = new JobDescriptor(); - TaskDetails taskData = jobExecutionContext.getTaskData(); - ResourceJobManager resourceJobManager = jobExecutionContext.getResourceJobManager(); - try { - if(ServerSettings.getSetting(ServerSettings.JOB_NOTIFICATION_ENABLE).equalsIgnoreCase("true")){ - jobDescriptor.setMailOptions(ServerSettings.getSetting(ServerSettings.JOB_NOTIFICATION_FLAGS)); - String emailids = ServerSettings.getSetting(ServerSettings.JOB_NOTIFICATION_EMAILIDS); - - if(jobExecutionContext.getTaskData().isSetEmailAddresses()){ - List<String> emailList = jobExecutionContext.getTaskData().getEmailAddresses(); - String elist = GFacUtils.listToCsv(emailList, ','); - if(emailids != null && !emailids.isEmpty()){ - emailids = emailids +"," + elist; - }else{ - emailids = elist; - } - } - if(emailids != null && !emailids.isEmpty()){ - logger.info("Email list: "+ emailids); - jobDescriptor.setMailAddress(emailids); - } - } - } catch (ApplicationSettingsException e) { - logger.error("ApplicationSettingsException : " +e.getLocalizedMessage()); - } - // this is common for any application descriptor - jobDescriptor.setCallBackIp(ServerSettings.getIp()); - jobDescriptor.setCallBackPort(ServerSettings.getSetting(org.apache.airavata.common.utils.Constants.GFAC_SERVER_PORT, "8950")); - jobDescriptor.setInputDirectory(jobExecutionContext.getInputDir()); - jobDescriptor.setOutputDirectory(jobExecutionContext.getOutputDir()); - jobDescriptor.setExecutablePath(jobExecutionContext.getExecutablePath()); - jobDescriptor.setStandardOutFile(jobExecutionContext.getStandardOutput()); - jobDescriptor.setStandardErrorFile(jobExecutionContext.getStandardError()); - String computationalProjectAccount = taskData.getTaskScheduling().getComputationalProjectAccount(); - taskData.getEmailAddresses(); - if (computationalProjectAccount == null){ - ComputeResourcePreference computeResourcePreference = jobExecutionContext.getApplicationContext().getComputeResourcePreference(); - if (computeResourcePreference != null) { - computationalProjectAccount = computeResourcePreference.getAllocationProjectNumber(); - } - } - if (computationalProjectAccount != null) { - jobDescriptor.setAcountString(computationalProjectAccount); - } - - Random random = new Random(); - int i = random.nextInt(Integer.MAX_VALUE); // We always set the job name - jobDescriptor.setJobName("A" + String.valueOf(i+99999999)); - jobDescriptor.setWorkingDirectory(jobExecutionContext.getWorkingDir()); - - List<String> inputValues = new ArrayList<String>(); - MessageContext input = jobExecutionContext.getInMessageContext(); - // sort the inputs first and then build the command List - Comparator<InputDataObjectType> inputOrderComparator = new Comparator<InputDataObjectType>() { - @Override - public int compare(InputDataObjectType inputDataObjectType, InputDataObjectType t1) { - return inputDataObjectType.getInputOrder() - t1.getInputOrder(); - } - }; - Set<InputDataObjectType> sortedInputSet = new TreeSet<InputDataObjectType>(inputOrderComparator); - for (Object object : input.getParameters().values()) { - if (object instanceof InputDataObjectType) { - InputDataObjectType inputDOT = (InputDataObjectType) object; - sortedInputSet.add(inputDOT); - } - } - for (InputDataObjectType inputDataObjectType : sortedInputSet) { - if (!inputDataObjectType.isRequiredToAddedToCommandLine()) { - continue; - } - if (inputDataObjectType.getApplicationArgument() != null - && !inputDataObjectType.getApplicationArgument().equals("")) { - inputValues.add(inputDataObjectType.getApplicationArgument()); - } - - if (inputDataObjectType.getValue() != null - && !inputDataObjectType.getValue().equals("")) { - if (inputDataObjectType.getType() == DataType.URI) { - // set only the relative path - String filePath = inputDataObjectType.getValue(); - filePath = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1, filePath.length()); - inputValues.add(filePath); - }else { - inputValues.add(inputDataObjectType.getValue()); - } - - } - } - - Map<String, Object> outputParams = jobExecutionContext.getOutMessageContext().getParameters(); - for (Object outputParam : outputParams.values()) { - if (outputParam instanceof OutputDataObjectType) { - OutputDataObjectType output = (OutputDataObjectType) outputParam; - if (output.getApplicationArgument() != null - && !output.getApplicationArgument().equals("")) { - inputValues.add(output.getApplicationArgument()); - } - if (output.getValue() != null && !output.getValue().equals("") && output.isRequiredToAddedToCommandLine()) { - if (output.getType() == DataType.URI){ - String filePath = output.getValue(); - filePath = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1, filePath.length()); - inputValues.add(filePath); - } - } - } - } - jobDescriptor.setInputValues(inputValues); - - jobDescriptor.setUserName(((GSISSHAbstractCluster) cluster).getServerInfo().getUserName()); - jobDescriptor.setShellName("/bin/bash"); - jobDescriptor.setAllEnvExport(true); - jobDescriptor.setOwner(((PBSCluster) cluster).getServerInfo().getUserName()); - - ComputationalResourceScheduling taskScheduling = taskData.getTaskScheduling(); - if (taskScheduling != null) { - int totalNodeCount = taskScheduling.getNodeCount(); - int totalCPUCount = taskScheduling.getTotalCPUCount(); - -// jobDescriptor.setJobSubmitter(applicationDeploymentType.getJobSubmitterCommand()); - if (taskScheduling.getComputationalProjectAccount() != null) { - jobDescriptor.setAcountString(taskScheduling.getComputationalProjectAccount()); - } - if (taskScheduling.getQueueName() != null) { - jobDescriptor.setQueueName(taskScheduling.getQueueName()); - } - - if (totalNodeCount > 0) { - jobDescriptor.setNodes(totalNodeCount); - } - if (taskScheduling.getComputationalProjectAccount() != null) { - jobDescriptor.setAcountString(taskScheduling.getComputationalProjectAccount()); - } - if (taskScheduling.getQueueName() != null) { - jobDescriptor.setQueueName(taskScheduling.getQueueName()); - } - if (totalCPUCount > 0) { - int ppn = totalCPUCount / totalNodeCount; - jobDescriptor.setProcessesPerNode(ppn); - jobDescriptor.setCPUCount(totalCPUCount); - } - if (taskScheduling.getWallTimeLimit() > 0) { - jobDescriptor.setMaxWallTime(String.valueOf(taskScheduling.getWallTimeLimit())); - if(resourceJobManager.getResourceJobManagerType().equals(ResourceJobManagerType.LSF)){ - jobDescriptor.setMaxWallTimeForLSF(String.valueOf(taskScheduling.getWallTimeLimit())); - } - } - - if (taskScheduling.getTotalPhysicalMemory() > 0) { - jobDescriptor.setUsedMemory(taskScheduling.getTotalPhysicalMemory() + ""); - } - } else { - logger.error("Task scheduling cannot be null at this point.."); - } - - ApplicationDeploymentDescription appDepDescription = jobExecutionContext.getApplicationContext().getApplicationDeploymentDescription(); - List<String> moduleCmds = appDepDescription.getModuleLoadCmds(); - if (moduleCmds != null) { - for (String moduleCmd : moduleCmds) { - jobDescriptor.addModuleLoadCommands(moduleCmd); - } - } - List<String> preJobCommands = appDepDescription.getPreJobCommands(); - if (preJobCommands != null) { - for (String preJobCommand : preJobCommands) { - jobDescriptor.addPreJobCommand(parseCommand(preJobCommand, jobExecutionContext)); - } - } - - List<String> postJobCommands = appDepDescription.getPostJobCommands(); - if (postJobCommands != null) { - for (String postJobCommand : postJobCommands) { - jobDescriptor.addPostJobCommand(parseCommand(postJobCommand, jobExecutionContext)); - } - } - - ApplicationParallelismType parallelism = appDepDescription.getParallelism(); - if (parallelism != null){ - if (parallelism == ApplicationParallelismType.MPI || parallelism == ApplicationParallelismType.OPENMP || parallelism == ApplicationParallelismType.OPENMP_MPI){ - Map<JobManagerCommand, String> jobManagerCommands = resourceJobManager.getJobManagerCommands(); - if (jobManagerCommands != null && !jobManagerCommands.isEmpty()) { - for (JobManagerCommand command : jobManagerCommands.keySet()) { - if (command == JobManagerCommand.SUBMISSION) { - String commandVal = jobManagerCommands.get(command); - jobDescriptor.setJobSubmitter(commandVal); - } - } - } - } - } - return jobDescriptor; - } - - private static String parseCommand(String value, JobExecutionContext jobExecutionContext) { - String parsedValue = value.replaceAll("\\$workingDir", jobExecutionContext.getWorkingDir()); - parsedValue = parsedValue.replaceAll("\\$inputDir", jobExecutionContext.getInputDir()); - parsedValue = parsedValue.replaceAll("\\$outputDir", jobExecutionContext.getOutputDir()); - return parsedValue; - } -} http://git-wip-us.apache.org/repos/asf/airavata/blob/7b809747/modules/gfac/gfac-gsissh/src/main/resources/errors.properties ---------------------------------------------------------------------- diff --git a/modules/gfac/gfac-gsissh/src/main/resources/errors.properties b/modules/gfac/gfac-gsissh/src/main/resources/errors.properties deleted file mode 100644 index 88c41b8..0000000 --- a/modules/gfac/gfac-gsissh/src/main/resources/errors.properties +++ /dev/null @@ -1,197 +0,0 @@ -# -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# Directly copied from jglobus. Not a good way to manager error properties. -1 = Parameter not supported -2 = The RSL length is greater than the maximum allowed -3 = No resources available -4 = Bad directory specified -5 = The executable does not exist -6 = Insufficient funds -7 = Authentication with the remote server failed -8 = Job cancelled by user -9 = Job cancelled by system - -10 = Data transfer to the server failed -11 = The stdin file does not exist -12 = The connection to the server failed (check host and port) -13 = The provided RSL 'maxtime' value is invalid (not an integer or must be greater than 0) -14 = The provided RSL 'count' value is invalid (not an integer or must be greater than 0) -15 = The job manager received an invalid RSL -16 = Could not connect to job manager -17 = The job failed when the job manager attempted to run it -18 = Paradyn error -19 = The provided RSL 'jobtype' value is invalid - -20 = The provided RSL 'myjob' value is invalid -21 = The job manager failed to locate an internal script argument file -22 = The job manager failed to create an internal script argument file -23 = The job manager detected an invalid job state -24 = The job manager detected an invalid script response -25 = The job manager detected an invalid job state -26 = The provided RSL 'jobtype' value is not supported by this job manager -27 = Unimplemented -28 = The job manager failed to create an internal script submission file -29 = The job manager cannot find the user proxy - -30 = The job manager failed to open the user proxy -31 = The job manager failed to cancel the job as requested -32 = System memory allocation failed -33 = The interprocess job communication initialization failed -34 = The interprocess job communication setup failed -35 = The provided RSL 'host count' value is invalid -36 = One of the provided RSL parameters is unsupported -37 = The provided RSL 'queue' parameter is invalid -38 = The provided RSL 'project' parameter is invalid -39 = The provided RSL string includes variables that could not be identified - -40 = The provided RSL 'environment' parameter is invalid -41 = The provided RSL 'dryrun' parameter is invalid -42 = The provided RSL is invalid (an empty string) -43 = The job manager failed to stage the executable -44 = The job manager failed to stage the stdin file -45 = The requested job manager type is invalid -46 = The provided RSL 'arguments' parameter is invalid -47 = The gatekeeper failed to run the job manager -48 = The provided RSL could not be properly parsed -49 = There is a version mismatch between GRAM components - -50 = The provided RSL 'arguments' parameter is invalid -51 = The provided RSL 'count' parameter is invalid -52 = The provided RSL 'directory' parameter is invalid -53 = The provided RSL 'dryrun' parameter is invalid -54 = The provided RSL 'environment' parameter is invalid -55 = The provided RSL 'executable' parameter is invalid -56 = The provided RSL 'host_count' parameter is invalid -57 = The provided RSL 'jobtype' parameter is invalid -58 = The provided RSL 'maxtime' parameter is invalid -59 = The provided RSL 'myjob' parameter is invalid - -60 = The provided RSL 'paradyn' parameter is invalid -61 = The provided RSL 'project' parameter is invalid -62 = The provided RSL 'queue' parameter is invalid -63 = The provided RSL 'stderr' parameter is invalid -64 = The provided RSL 'stdin' parameter is invalid -65 = The provided RSL 'stdout' parameter is invalid -66 = The job manager failed to locate an internal script -67 = The job manager failed on the system call pipe() -68 = The job manager failed on the system call fcntl() -69 = The job manager failed to create the temporary stdout filename - -70 = The job manager failed to create the temporary stderr filename -71 = The job manager failed on the system call fork() -72 = The executable file permissions do not allow execution -73 = The job manager failed to open stdout -74 = The job manager failed to open stderr -75 = The cache file could not be opened in order to relocate the user proxy -76 = Cannot access cache files in ~/.globus/.gass_cache, check permissions, quota, and disk space -77 = The job manager failed to insert the contact in the client contact list -78 = The contact was not found in the job manager's client contact list -79 = Connecting to the job manager failed. Possible reasons: job terminated, invalid job contact, network problems, ... - -80 = The syntax of the job contact is invalid -81 = The executable parameter in the RSL is undefined -82 = The job manager service is misconfigured. condor arch undefined -83 = The job manager service is misconfigured. condor os undefined -84 = The provided RSL 'min_memory' parameter is invalid -85 = The provided RSL 'max_memory' parameter is invalid -86 = The RSL 'min_memory' value is not zero or greater -87 = The RSL 'max_memory' value is not zero or greater -88 = The creation of a HTTP message failed -89 = Parsing incoming HTTP message failed - -90 = The packing of information into a HTTP message failed -91 = An incoming HTTP message did not contain the expected information -92 = The job manager does not support the service that the client requested -93 = The gatekeeper failed to find the requested service -94 = The jobmanager does not accept any new requests (shutting down) -95 = The client failed to close the listener associated with the callback URL -96 = The gatekeeper contact cannot be parsed -97 = The job manager could not find the 'poe' command -98 = The job manager could not find the 'mpirun' command -99 = The provided RSL 'start_time' parameter is invalid" -100 = The provided RSL 'reservation_handle' parameter is invalid - -101 = The provided RSL 'max_wall_time' parameter is invalid -102 = The RSL 'max_wall_time' value is not zero or greater -103 = The provided RSL 'max_cpu_time' parameter is invalid -104 = The RSL 'max_cpu_time' value is not zero or greater -105 = The job manager is misconfigured, a scheduler script is missing -106 = The job manager is misconfigured, a scheduler script has invalid permissions -107 = The job manager failed to signal the job -108 = The job manager did not recognize/support the signal type -109 = The job manager failed to get the job id from the local scheduler - -110 = The job manager is waiting for a commit signal -111 = The job manager timed out while waiting for a commit signal -112 = The provided RSL 'save_state' parameter is invalid -113 = The provided RSL 'restart' parameter is invalid -114 = The provided RSL 'two_phase' parameter is invalid -115 = The RSL 'two_phase' value is not zero or greater -116 = The provided RSL 'stdout_position' parameter is invalid -117 = The RSL 'stdout_position' value is not zero or greater -118 = The provided RSL 'stderr_position' parameter is invalid -119 = The RSL 'stderr_position' value is not zero or greater - -120 = The job manager restart attempt failed -121 = The job state file doesn't exist -122 = Could not read the job state file -123 = Could not write the job state file -124 = The old job manager is still alive -125 = The job manager state file TTL expired -126 = It is unknown if the job was submitted -127 = The provided RSL 'remote_io_url' parameter is invalid -128 = Could not write the remote io url file -129 = The standard output/error size is different - -130 = The job manager was sent a stop signal (job is still running) -131 = The user proxy expired (job is still running) -132 = The job was not submitted by original jobmanager -133 = The job manager is not waiting for that commit signal -134 = The provided RSL scheduler specific parameter is invalid -135 = The job manager could not stage in a file -136 = The scratch directory could not be created -137 = The provided 'gass_cache' parameter is invalid -138 = The RSL contains attributes which are not valid for job submission -139 = The RSL contains attributes which are not valid for stdio update - -140 = The RSL contains attributes which are not valid for job restart -141 = The provided RSL 'file_stage_in' parameter is invalid -142 = The provided RSL 'file_stage_in_shared' parameter is invalid -143 = The provided RSL 'file_stage_out' parameter is invalid -144 = The provided RSL 'gass_cache' parameter is invalid -145 = The provided RSL 'file_cleanup' parameter is invalid -146 = The provided RSL 'scratch_dir' parameter is invalid -147 = The provided scheduler-specific RSL parameter is invalid -148 = A required RSL attribute was not defined in the RSL spec -149 = The gass_cache attribute points to an invalid cache directory - -150 = The provided RSL 'save_state' parameter has an invalid value -151 = The job manager could not open the RSL attribute validation file -152 = The job manager could not read the RSL attribute validation file -153 = The provided RSL 'proxy_timeout' is invalid -154 = The RSL 'proxy_timeout' value is not greater than zero -155 = The job manager could not stage out a file -156 = The job contact string does not match any which the job manager is handling -157 = Proxy delegation failed -158 = The job manager could not lock the state lock file - -1000 = Failed to start up callback handler -1003 = Job contact not set http://git-wip-us.apache.org/repos/asf/airavata/blob/7b809747/modules/gfac/gfac-gsissh/src/main/resources/service.properties ---------------------------------------------------------------------- diff --git a/modules/gfac/gfac-gsissh/src/main/resources/service.properties b/modules/gfac/gfac-gsissh/src/main/resources/service.properties deleted file mode 100644 index 391bfea..0000000 --- a/modules/gfac/gfac-gsissh/src/main/resources/service.properties +++ /dev/null @@ -1,58 +0,0 @@ -# -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# -# - - -# -# Class which implemented Scheduler interface. It will be used to determine a Provider -# -scheduler.class= org.apache.airavata.core.gfac.scheduler.impl.SchedulerImpl - -# -# Data Service Plugins classes -# -datachain.classes= org.apache.airavata.core.gfac.extension.data.RegistryDataService - -# -# Pre execution Plugins classes. For example, GridFTP Input Staging -# -prechain.classes= org.apache.airavata.core.gfac.extension.pre.GridFtpInputStaging -prechain.classes= org.apache.airavata.core.gfac.extension.pre.HttpInputStaging - -# -# Post execution Plugins classes. For example, GridFTP Output Staging -# -postchain.classes= org.apache.airavata.core.gfac.extension.post.GridFtpOutputStaging -postchain.classes= org.apache.airavata.core.gfac.extension.post.OutputRegister - -# -# SSH private key location. It will be used by SSHProvider -# -# ssh.key=/home/user/.ssh/id_rsa -# ssh.keypass= -# ssh.username=usernameAtHost - -# -# MyProxy credential. It will be used by GridFTP Plugins and GramProvider. -# -# myproxy.server=myproxy.teragrid.org -# myproxy.user=username -# myproxy.pass=password -# myproxy.life=3600 \ No newline at end of file http://git-wip-us.apache.org/repos/asf/airavata/blob/7b809747/modules/gfac/gfac-gsissh/src/test/java/org/apache/airavata/core/gfac/services/impl/GSISSHProviderTestWithMyProxyAuth.java ---------------------------------------------------------------------- diff --git a/modules/gfac/gfac-gsissh/src/test/java/org/apache/airavata/core/gfac/services/impl/GSISSHProviderTestWithMyProxyAuth.java b/modules/gfac/gfac-gsissh/src/test/java/org/apache/airavata/core/gfac/services/impl/GSISSHProviderTestWithMyProxyAuth.java deleted file mode 100644 index 630cd5c..0000000 --- a/modules/gfac/gfac-gsissh/src/test/java/org/apache/airavata/core/gfac/services/impl/GSISSHProviderTestWithMyProxyAuth.java +++ /dev/null @@ -1,229 +0,0 @@ -///* -// * -// * Licensed to the Apache Software Foundation (ASF) under one -// * or more contributor license agreements. See the NOTICE file -// * distributed with this work for additional information -// * regarding copyright ownership. The ASF licenses this file -// * to you under the Apache License, Version 2.0 (the -// * "License"); you may not use this file except in compliance -// * with the License. You may obtain a copy of the License at -// * -// * http://www.apache.org/licenses/LICENSE-2.0 -// * -// * Unless required by applicable law or agreed to in writing, -// * software distributed under the License is distributed on an -// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// * KIND, either express or implied. See the License for the -// * specific language governing permissions and limitations -// * under the License. -// * -//*/ -//package org.apache.airavata.core.gfac.services.impl; -// -//import java.io.File; -//import java.net.URL; -//import java.util.ArrayList; -//import java.util.Date; -//import java.util.List; -//import java.util.UUID; -// -//import org.apache.aiaravata.application.catalog.data.model.ApplicationInterface; -//import org.apache.airavata.commons.gfac.type.ActualParameter; -//import org.apache.airavata.commons.gfac.type.ApplicationDescription; -//import org.apache.airavata.commons.gfac.type.HostDescription; -//import org.apache.airavata.commons.gfac.type.ServiceDescription; -//import org.apache.airavata.gfac.GFacConfiguration; -//import org.apache.airavata.gfac.GFacException; -//import org.apache.airavata.gfac.SecurityContext; -//import org.apache.airavata.gfac.core.context.ApplicationContext; -//import org.apache.airavata.gfac.core.context.JobExecutionContext; -//import org.apache.airavata.gfac.core.context.MessageContext; -//import org.apache.airavata.gfac.core.cpi.BetterGfacImpl; -//import org.apache.airavata.gfac.gsissh.security.GSISecurityContext; -//import org.apache.airavata.gsi.ssh.api.Cluster; -//import org.apache.airavata.gsi.ssh.api.SSHApiException; -//import org.apache.airavata.gsi.ssh.api.ServerInfo; -//import org.apache.airavata.gsi.ssh.api.authentication.GSIAuthenticationInfo; -//import org.apache.airavata.gsi.ssh.impl.PBSCluster; -//import org.apache.airavata.gsi.ssh.impl.authentication.MyProxyAuthenticationInfo; -//import org.apache.airavata.gsi.ssh.util.CommonUtils; -//import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription; -//import org.apache.airavata.model.workspace.experiment.TaskDetails; -//import org.apache.airavata.persistance.registry.jpa.impl.RegistryFactory; -//import org.apache.airavata.schemas.gfac.ApplicationDeploymentDescriptionType; -//import org.apache.airavata.schemas.gfac.GsisshHostType; -//import org.apache.airavata.schemas.gfac.HpcApplicationDeploymentType; -//import org.apache.airavata.schemas.gfac.InputParameterType; -//import org.apache.airavata.schemas.gfac.JobTypeType; -//import org.apache.airavata.schemas.gfac.OutputParameterType; -//import org.apache.airavata.schemas.gfac.ProjectAccountType; -//import org.apache.airavata.schemas.gfac.QueueType; -//import org.apache.airavata.schemas.gfac.StringParameterType; -//import org.testng.annotations.BeforeClass; -//import org.testng.annotations.Test; -// -//public class GSISSHProviderTestWithMyProxyAuth { -// private JobExecutionContext jobExecutionContext; -// -// //FIXME: move job properties to configuration file -// private static final String hostAddress = "trestles.sdsc.edu"; -// private static final String hostName = "trestles"; -// private String myProxyUserName; -// private String myProxyPassword; -// private String workingDirectory; -// private String certificateLocation = "/Users/lahirugunathilake/Downloads/certificates"; -// -// @BeforeClass -// public void setUp() throws Exception { -//// System.setProperty("myproxy.user", "ogce"); -//// System.setProperty("myproxy.password", ""); -//// System.setProperty("basedir", "/Users/lahirugunathilake/Downloads"); -//// System.setProperty("gsi.working.directory", "/home/ogce"); -//// System.setProperty("gsi.certificate.path", "/Users/lahirugunathilake/Downloads/certificates"); -// certificateLocation = System.getProperty("trusted.cert.location"); -// myProxyUserName = System.getProperty("myproxy.username"); -// myProxyPassword = System.getProperty("myproxy.password"); -// workingDirectory = System.getProperty("gsi.working.directory"); -// -// if (myProxyUserName == null || myProxyPassword == null || certificateLocation == null) { -// System.out.println(">>>>>> Please run tests with my proxy user name and password. " + -// "E.g :- mvn clean install -Dmyproxy.username=xxx -Dmyproxy.password=xxx -Dgsi.working.directory=/path<<<<<<<"); -// throw new Exception("Need my proxy user name password to run tests."); -// } -// URL resource = GSISSHProviderTestWithMyProxyAuth.class.getClassLoader().getResource(org.apache.airavata.common.utils.Constants.GFAC_CONFIG_XML); -// assert resource != null; -// System.out.println(resource.getFile()); -// GFacConfiguration gFacConfiguration = GFacConfiguration.create(new File(resource.getPath()), null); -// -// /* -// * Host -// */ -// HostDescription host = new HostDescription(GsisshHostType.type); -// host.getType().setHostAddress(hostAddress); -// host.getType().setHostName(hostName); -// -// /* -// * App -// */ -// ApplicationDescription appDesc = new ApplicationDescription(HpcApplicationDeploymentType.type); -// HpcApplicationDeploymentType app = (HpcApplicationDeploymentType) appDesc.getType(); -// ApplicationDeploymentDescriptionType.ApplicationName name = ApplicationDeploymentDescriptionType.ApplicationName.Factory.newInstance(); -// name.setStringValue("EchoLocal"); -// app.setApplicationName(name); -// ProjectAccountType projectAccountType = app.addNewProjectAccount(); -// projectAccountType.setProjectAccountNumber("sds128"); -// -// QueueType queueType = app.addNewQueue(); -// queueType.setQueueName("normal"); -// -// app.setCpuCount(1); -// app.setJobType(JobTypeType.SERIAL); -// app.setNodeCount(1); -// app.setProcessorsPerNode(1); -// -// /* -// * Use bat file if it is compiled on Windows -// */ -// app.setExecutableLocation("/bin/echo"); -// -// /* -// * Default tmp location -// */ -// String tempDir = "/home/ogce/scratch/"; -// String date = (new Date()).toString(); -// date = date.replaceAll(" ", "_"); -// date = date.replaceAll(":", "_"); -// -// tempDir = workingDirectory + File.separator -// + "SimpleEcho" + "_" + date + "_" + UUID.randomUUID(); -// -// System.out.println(tempDir); -// app.setScratchWorkingDirectory(tempDir); -// app.setStaticWorkingDirectory(tempDir); -// app.setInputDataDirectory(tempDir + File.separator + "inputData"); -// app.setOutputDataDirectory(tempDir + File.separator + "outputData"); -// app.setStandardOutput(tempDir + File.separator + app.getApplicationName().getStringValue() + ".stdout"); -// app.setStandardError(tempDir + File.separator + app.getApplicationName().getStringValue() + ".stderr"); -// app.setMaxWallTime(5); -// app.setInstalledParentPath("/opt/torque/bin/"); -// -// /* -// * Service -// */ -// ServiceDescription serv = new ServiceDescription(); -// serv.getType().setName("SimpleEcho"); -// -// List<InputParameterType> inputList = new ArrayList<InputParameterType>(); -// -// InputParameterType input = InputParameterType.Factory.newInstance(); -// input.setParameterName("echo_input"); -// input.setParameterType(StringParameterType.Factory.newInstance()); -// inputList.add(input); -// -// InputParameterType[] inputParamList = inputList.toArray(new InputParameterType[inputList -// -// .size()]); -// List<OutputParameterType> outputList = new ArrayList<OutputParameterType>(); -// OutputParameterType output = OutputParameterType.Factory.newInstance(); -// output.setParameterName("echo_output"); -// output.setParameterType(StringParameterType.Factory.newInstance()); -// outputList.add(output); -// -// OutputParameterType[] outputParamList = outputList -// .toArray(new OutputParameterType[outputList.size()]); -// -// serv.getType().setInputParametersArray(inputParamList); -// serv.getType().setOutputParametersArray(outputParamList); -// -// jobExecutionContext = new JobExecutionContext(gFacConfiguration, serv.getType().getName()); -// // Adding security context -// jobExecutionContext.addSecurityContext(GSISecurityContext.GSI_SECURITY_CONTEXT, getSecurityContext(app)); -// ApplicationContext applicationContext = new ApplicationContext(); -// jobExecutionContext.setApplicationContext(applicationContext); -// applicationContext.setServiceDescription(serv); -// applicationContext.setApplicationDeploymentDescription(appDesc); -// applicationContext.setHostDescription(host); -// -// MessageContext inMessage = new MessageContext(); -// ActualParameter echo_input = new ActualParameter(); -// ((StringParameterType) echo_input.getType()).setValue("echo_output=hello"); -// inMessage.addParameter("echo_input", echo_input); -// -// -// jobExecutionContext.setInMessageContext(inMessage); -// -// MessageContext outMessage = new MessageContext(); -// ActualParameter echo_out = new ActualParameter(); -//// ((StringParameterType)echo_input.getType()).setValue("echo_output=hello"); -// outMessage.addParameter("echo_output", echo_out); -// jobExecutionContext.setRegistry(RegistryFactory.getLoggingRegistry()); -// jobExecutionContext.setTaskData(new TaskDetails("11323")); -// jobExecutionContext.setOutMessageContext(outMessage); -// -// } -// -// private SecurityContext getSecurityContext(HpcApplicationDeploymentType app) { -// GSIAuthenticationInfo authenticationInfo -// = new MyProxyAuthenticationInfo(myProxyUserName, myProxyPassword, "myproxy.teragrid.org", -// 7512, 17280000, certificateLocation); -// -// // Server info -// ServerInfo serverInfo = new ServerInfo("ogce", "trestles.sdsc.edu"); -// Cluster pbsCluster = null; -// try { -// pbsCluster = new PBSCluster(serverInfo, authenticationInfo, CommonUtils.getPBSJobManager(app.getInstalledParentPath())); -// } catch (SSHApiException e) { -// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. -// } -// GSISecurityContext sshSecurityContext = new GSISecurityContext(pbsCluster); -// return sshSecurityContext; -// } -// @Test -// public void testGSISSHProvider() throws GFacException { -// BetterGfacImpl gFacAPI = new BetterGfacImpl(); -// gFacAPI.submitJob(jobExecutionContext.getExperimentID(), jobExecutionContext.getTaskData().getTaskID(), jobExecutionContext.getGatewayID()); -// System.out.println(jobExecutionContext.getJobDetails().getJobDescription()); -// System.out.println(jobExecutionContext.getJobDetails().getJobID()); -// } -// -//} http://git-wip-us.apache.org/repos/asf/airavata/blob/7b809747/modules/gfac/gfac-gsissh/src/test/java/org/apache/airavata/core/gfac/services/impl/security/GSISecurityContextTestWithMyProxyAuth.java ---------------------------------------------------------------------- diff --git a/modules/gfac/gfac-gsissh/src/test/java/org/apache/airavata/core/gfac/services/impl/security/GSISecurityContextTestWithMyProxyAuth.java b/modules/gfac/gfac-gsissh/src/test/java/org/apache/airavata/core/gfac/services/impl/security/GSISecurityContextTestWithMyProxyAuth.java deleted file mode 100644 index 9268d84..0000000 --- a/modules/gfac/gfac-gsissh/src/test/java/org/apache/airavata/core/gfac/services/impl/security/GSISecurityContextTestWithMyProxyAuth.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.airavata.core.gfac.services.impl.security; - -import junit.framework.Assert; -import org.apache.airavata.common.utils.AiravataUtils; -import org.apache.airavata.common.utils.DatabaseTestCases; -import org.apache.airavata.common.utils.DerbyUtil; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.credential.store.store.CredentialReader; -import org.apache.airavata.credential.store.store.CredentialReaderFactory; -import org.apache.airavata.gfac.RequestData; -import org.apache.airavata.gfac.gsissh.security.GSISecurityContext; -import org.apache.airavata.gfac.gsissh.security.TokenizedMyProxyAuthInfo; -import org.apache.log4j.Logger; -import org.ietf.jgss.GSSCredential; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - - -public class GSISecurityContextTestWithMyProxyAuth extends DatabaseTestCases { - - private static String userName; - private static String password; - - private static final Logger log = Logger.getLogger(GSISecurityContextTestWithMyProxyAuth.class); - - @BeforeClass - public static void setUpClass() throws Exception { - -// System.setProperty("myproxy.username", "ogce"); -// System.setProperty("myproxy.password", ""); - userName = System.getProperty("myproxy.username"); - password = System.getProperty("myproxy.password"); - System.setProperty("myproxy.server", "myproxy.teragrid.org"); - System.setProperty("myproxy.life", "3600"); - System.setProperty("credential.store.keystore.url", "../configuration/server/src/main/resources/airavata.jks"); - System.setProperty("credential.store.keystore.alias", "airavata"); - System.setProperty("credential.store.keystore.password", "airavata"); - - if (userName == null || password == null || userName.trim().equals("") || password.trim().equals("")) { - log.error("===== Please set myproxy.username and myproxy.password system properties. ======="); - Assert.fail("Please set myproxy.user and myproxy.password system properties."); - } - - log.info("Using my proxy user name - " + userName); - - setUpDatabase(); - - } - - public static void setUpDatabase() throws Exception { - DerbyUtil.startDerbyInServerMode(getHostAddress(), getPort(), getUserName(), getPassword()); - - waitTillServerStarts(); - - - String createTable = "CREATE TABLE CREDENTIALS\n" + "(\n" - + " GATEWAY_ID VARCHAR(256) NOT NULL,\n" - + " TOKEN_ID VARCHAR(256) NOT NULL,\n" - + // Actual token used to identify the credential - " CREDENTIAL BLOB NOT NULL,\n" + " PORTAL_USER_ID VARCHAR(256) NOT NULL,\n" - + " TIME_PERSISTED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n" - + " PRIMARY KEY (GATEWAY_ID, TOKEN_ID)\n" + ")"; - - String dropTable = "drop table CREDENTIALS"; - - try { - executeSQL(dropTable); - } catch (Exception e) { - } - - executeSQL(createTable); - - } - - @AfterClass - public static void shutDownDatabase() throws Exception { - DerbyUtil.stopDerbyServer(); - } - - private GSSCredential getGSSCredentials() throws Exception { - - TokenizedMyProxyAuthInfo gsiTokenizedMyProxyAuthInfo = getGSISecurityContext(); - return gsiTokenizedMyProxyAuthInfo.getCredentials(); - } - - private TokenizedMyProxyAuthInfo getGSISecurityContext() throws Exception { - - RequestData requestData = new RequestData(); - - requestData.setMyProxyUserName(userName); - requestData.setMyProxyPassword(password); - requestData.setMyProxyServerUrl(ServerSettings.getMyProxyServer()); - requestData.setMyProxyLifeTime(ServerSettings.getMyProxyLifetime()); - CredentialReader credentialReader = CredentialReaderFactory.createCredentialStoreReader(getDbUtil()); - - return new TokenizedMyProxyAuthInfo(requestData); - } - - @Test - public void testGetGssCredentials() throws Exception { - - Assert.assertNotNull(getGSSCredentials()); - } - /* - @Test - public void testRenewCredentials() throws Exception { - GSISecurityContext gsiSecurityContext = getGSISecurityContext(); - gsiSecurityContext.getGssCredentials(); - Assert.assertNotNull(gsiSecurityContext.renewCredentials()); - - } - - @Test - public void testGetCredentialsFromStore() throws Exception { - GSISecurityContext gsiSecurityContext = getGSISecurityContext(); - Assert.assertNotNull(gsiSecurityContext.getCredentialsFromStore()); - - } */ - - @Test - public void testGetDefaultCredentials() throws Exception { - TokenizedMyProxyAuthInfo gsiSecurityContext = getGSISecurityContext(); - Assert.assertNotNull(gsiSecurityContext.getDefaultCredentials()); - - } - - @Test - public void testGetProxyCredentials() throws Exception { - TokenizedMyProxyAuthInfo gsiSecurityContext = getGSISecurityContext(); - Assert.assertNotNull(gsiSecurityContext.getProxyCredentials()); - - } - /* - @Test - public void testRenewCredentialsAsATrustedHost() throws Exception { - GSISecurityContext gsiSecurityContext = getGSISecurityContext(); - gsiSecurityContext.getGssCredentials(); - Assert.assertNotNull(gsiSecurityContext.renewCredentialsAsATrustedHost()); - } */ - -} http://git-wip-us.apache.org/repos/asf/airavata/blob/7b809747/modules/gfac/gfac-gsissh/src/test/resources/PBSTemplate.xslt ---------------------------------------------------------------------- diff --git a/modules/gfac/gfac-gsissh/src/test/resources/PBSTemplate.xslt b/modules/gfac/gfac-gsissh/src/test/resources/PBSTemplate.xslt deleted file mode 100644 index 4c49bd8..0000000 --- a/modules/gfac/gfac-gsissh/src/test/resources/PBSTemplate.xslt +++ /dev/null @@ -1,78 +0,0 @@ -<!--Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file - distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under - the Apache License, Version 2.0 (theà "License"); you may not use this file except in compliance with the License. You may - obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to - in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF - ANY ~ KIND, either express or implied. See the License for the specific language governing permissions and limitations under - the License. --> -<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://airavata.apache.org/gsi/ssh/2012/12"> -<xsl:output method="text" /> -<xsl:template match="/ns:JobDescriptor"> -#! /bin/sh -# PBS batch job script built by Globus job manager -# <xsl:choose> - <xsl:when test="ns:shellName"> -##PBS -S <xsl:value-of select="ns:shellName"/> - </xsl:when></xsl:choose> - <xsl:choose> - <xsl:when test="ns:queueName"> -#PBS -q <xsl:value-of select="ns:queueName"/> - </xsl:when> - </xsl:choose> - <xsl:choose> - <xsl:when test="ns:mailOptions"> -#PBS -m <xsl:value-of select="ns:mailOptions"/> - </xsl:when> - </xsl:choose> - <xsl:choose> -<xsl:when test="ns:acountString"> -#PBS -A <xsl:value-of select="ns:acountString"/> - </xsl:when> - </xsl:choose> - <xsl:choose> - <xsl:when test="ns:maxWallTime"> -#PBS -l walltime=<xsl:value-of select="ns:maxWallTime"/> - </xsl:when> - </xsl:choose> - <xsl:choose> - <xsl:when test="ns:standardOutFile"> -#PBS -o <xsl:value-of select="ns:standardOutFile"/> - </xsl:when> - </xsl:choose> - <xsl:choose> - <xsl:when test="ns:standardOutFile"> -#PBS -e <xsl:value-of select="ns:standardErrorFile"/> - </xsl:when> - </xsl:choose> - <xsl:choose> - <xsl:when test="ns:usedMem"> -#PBS -l mem=<xsl:value-of select="ns:usedMem"/> - </xsl:when> - </xsl:choose> - <xsl:choose> - <xsl:when test="(ns:nodes) and (ns:processesPerNode)"> -#PBS -l nodes=<xsl:value-of select="ns:nodes"/>:ppn=<xsl:value-of select="ns:processesPerNode"/> -<xsl:text>
</xsl:text> - </xsl:when> - </xsl:choose> -<xsl:for-each select="ns:exports/ns:name"> -<xsl:value-of select="."/>=<xsl:value-of select="./@value"/><xsl:text>
</xsl:text> -export<xsl:text> </xsl:text><xsl:value-of select="."/> -<xsl:text>
</xsl:text> -</xsl:for-each> -<xsl:for-each select="ns:preJobCommands/ns:command"> - <xsl:value-of select="."/><xsl:text> </xsl:text> - </xsl:for-each> -cd <xsl:text> </xsl:text><xsl:value-of select="ns:workingDirectory"/><xsl:text>
</xsl:text> - <xsl:choose><xsl:when test="ns:jobSubmitterCommand"> -<xsl:value-of select="ns:jobSubmitterCommand"/><xsl:text> </xsl:text></xsl:when></xsl:choose><xsl:value-of select="ns:executablePath"/><xsl:text> </xsl:text> -<xsl:for-each select="ns:inputs/ns:input"> - <xsl:value-of select="."/><xsl:text> </xsl:text> - </xsl:for-each> -<xsl:for-each select="ns:postJobCommands/ns:command"> - <xsl:value-of select="."/><xsl:text> </xsl:text> -</xsl:for-each> - -</xsl:template> - -</xsl:stylesheet> \ No newline at end of file http://git-wip-us.apache.org/repos/asf/airavata/blob/7b809747/modules/gfac/gfac-gsissh/src/test/resources/logging.properties ---------------------------------------------------------------------- diff --git a/modules/gfac/gfac-gsissh/src/test/resources/logging.properties b/modules/gfac/gfac-gsissh/src/test/resources/logging.properties deleted file mode 100644 index 0584d38..0000000 --- a/modules/gfac/gfac-gsissh/src/test/resources/logging.properties +++ /dev/null @@ -1,42 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# -# -#default/fallback log4j configuration -# - -# Set root logger level to WARN and its only appender to A1. -log4j.rootLogger=INFO, A1, A2 - -# A1 is set to be a rolling file appender with default params -log4j.appender.A1=org.apache.log4j.RollingFileAppender -log4j.appender.A1.File=target/seclogs.txt - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n - -# A2 is a console appender -log4j.appender.A2=org.apache.log4j.ConsoleAppender - -# A2 uses PatternLayout. -log4j.appender.A2.layout=org.apache.log4j.PatternLayout -log4j.appender.A2.layout.ConversionPattern=%d [%t] %-5p %c{1} %x - %m%n - -log4j.logger.unicore.security=INFO - http://git-wip-us.apache.org/repos/asf/airavata/blob/7b809747/modules/gfac/gfac-impl/pom.xml ---------------------------------------------------------------------- diff --git a/modules/gfac/gfac-impl/pom.xml b/modules/gfac/gfac-impl/pom.xml new file mode 100644 index 0000000..72a9f34 --- /dev/null +++ b/modules/gfac/gfac-impl/pom.xml @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<!--Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file + distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under + the Apache License, Version 2.0 (theà "License"); you may not use this file except in compliance with the License. You may + obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to + in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF + ANY ~ KIND, either express or implied. See the License for the specific language governing permissions and limitations under + the License. --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <groupId>org.apache.airavata</groupId> + <artifactId>gfac</artifactId> + <version>0.16-SNAPSHOT</version> + <relativePath>../pom.xml</relativePath> + </parent> + + <modelVersion>4.0.0</modelVersion> + <artifactId>gfac-impl</artifactId> + <name>Airavata GFac Local implementation</name> + <description>This is the extension of GFAC Local.</description> + <url>http://airavata.apache.org/</url> + + <dependencies> + + <!-- Logging --> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </dependency> + + <!-- GFAC schemas --> + <dependency> + <groupId>org.apache.airavata</groupId> + <artifactId>airavata-gfac-core</artifactId> + <version>${project.version}</version> + </dependency> + + <!-- Test --> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.testng</groupId> + <artifactId>testng</artifactId> + <version>6.1.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>jcl-over-slf4j</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + <scope>test</scope> + </dependency> + + </dependencies> + +</project> http://git-wip-us.apache.org/repos/asf/airavata/blob/7b809747/modules/gfac/gfac-impl/src/main/java/org/apache/airavata/gfac/gsi/ssh/GSSContextX509.java ---------------------------------------------------------------------- diff --git a/modules/gfac/gfac-impl/src/main/java/org/apache/airavata/gfac/gsi/ssh/GSSContextX509.java b/modules/gfac/gfac-impl/src/main/java/org/apache/airavata/gfac/gsi/ssh/GSSContextX509.java new file mode 100644 index 0000000..1c07a39 --- /dev/null +++ b/modules/gfac/gfac-impl/src/main/java/org/apache/airavata/gfac/gsi/ssh/GSSContextX509.java @@ -0,0 +1,210 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.gfac.ssh; + + +import java.io.File; +import java.io.FileInputStream; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import org.globus.common.CoGProperties; +import org.globus.gsi.gssapi.auth.HostAuthorization; +import org.gridforum.jgss.ExtendedGSSCredential; +import org.gridforum.jgss.ExtendedGSSManager; +import org.ietf.jgss.GSSContext; +import org.ietf.jgss.GSSCredential; +import org.ietf.jgss.GSSException; +import org.ietf.jgss.GSSName; +import org.ietf.jgss.MessageProp; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jcraft.jsch.JSchException; + +/** + * This class is based on GSSContextKrb5; it substitutes the globus + * ExtendedGSSManager and uses the SecurityUtils method to get the credential if + * one is not passed in from memory. + * + */ +public class GSSContextX509 implements com.jcraft.jsch.GSSContext { + + private GSSContext context = null; + private GSSCredential credential; + private static final Logger logger = LoggerFactory.getLogger(GSSContextX509.class); + + public void create(String user, String host) throws JSchException { + try { +// ExtendedGSSManager manager = (ExtendedGSSManager) ExtendedGSSManager.getInstance(); + + if (credential == null) { + try { + credential = getCredential(); + } catch (SecurityException t) { + System.out.printf("Could not get proxy: %s: %s\n", t.getClass().getSimpleName(), t.getMessage()); + throw new JSchException(t.toString()); + } + } + + String cname = host; + + try { + cname = InetAddress.getByName(cname).getCanonicalHostName(); + } catch (UnknownHostException e) { + } + + GSSName name = HostAuthorization.getInstance().getExpectedName(credential, cname); + +// context = manager.createContext(name, null, credential, GSSContext.DEFAULT_LIFETIME); +// +// // RFC4462 3.4. GSS-API Session +// // +// // When calling GSS_Init_sec_context(), the client MUST set +// // integ_req_flag to "true" to request that per-message integrity +// // protection be supported for this context. In addition, +// // deleg_req_flag MAY be set to "true" to request access delegation, +// // if +// // requested by the user. +// // +// // Since the user authentication process by its nature authenticates +// // only the client, the setting of mutual_req_flag is not needed for +// // this process. This flag SHOULD be set to "false". +// +// // TODO: OpenSSH's sshd does accept 'false' for mutual_req_flag +// // context.requestMutualAuth(false); +// context.requestMutualAuth(true); +// context.requestConf(true); +// context.requestInteg(true); // for MIC +// context.requestCredDeleg(true); +// context.requestAnonymity(false); + +// context = new BCGSSContextImpl(name, (GlobusGSSCredentialImpl) credential); +// context.requestLifetime(GSSCredential.DEFAULT_LIFETIME); +// context.requestCredDeleg(true); +// context.requestMutualAuth(true); +// context.requestReplayDet(true); +// context.requestSequenceDet(true); +// context.requestConf(false); +// context.requestInteg(true); +// ((ExtendedGSSContext)context).setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_FULL); + + return; + } catch (GSSException ex) { + throw new JSchException(ex.toString()); + } + } + + private static GSSCredential getProxy() { + return getProxy(null, GSSCredential.DEFAULT_LIFETIME); + } + + /** + * @param x509_USER_PROXY + * path to the proxy. + * @param credentialLifetime + * in seconds. + * @return valid credential. + * if proxy task throws exception (or if proxy cannot be found). + */ + private static GSSCredential getProxy(String x509_USER_PROXY, int credentialLifetime) throws SecurityException { + if (x509_USER_PROXY == null) + x509_USER_PROXY = System.getProperty("x509.user.proxy"); + +// if (x509_USER_PROXY == null) { +// SystemUtils.envToProperties(); +// x509_USER_PROXY = System.getProperty("x509.user.proxy"); +// } + + if (x509_USER_PROXY == null || "".equals(x509_USER_PROXY)) + x509_USER_PROXY = CoGProperties.getDefault().getProxyFile(); + + if (x509_USER_PROXY == null) + throw new SecurityException("could not get credential; no location defined"); + + ExtendedGSSManager manager = (ExtendedGSSManager) ExtendedGSSManager.getInstance(); + + // file...load file into a buffer + try { + File f = new File(x509_USER_PROXY); + byte[] data = new byte[(int) f.length()]; + FileInputStream in = new FileInputStream(f); + // read in the credential data + in.read(data); + in.close(); + return manager.createCredential(data, ExtendedGSSCredential.IMPEXP_OPAQUE, credentialLifetime, null, // use + // default + // mechanism + // - + // GSI + GSSCredential.INITIATE_AND_ACCEPT); + } catch (Throwable t) { + throw new SecurityException("could not get credential from " + x509_USER_PROXY, t); + } + } + + public boolean isEstablished() { + // this must check to see if the call returned GSS_S_COMPLETE + if (context != null){ + return context.isEstablished(); + } + return false; + } + + public byte[] init(byte[] token, int s, int l) throws JSchException { + try { + if (context != null){ + return context.initSecContext(token, s, l); + }else { + throw new JSchException("Context is null.."); + } + } catch (GSSException ex) { + throw new JSchException(ex.toString()); + } + } + + public byte[] getMIC(byte[] message, int s, int l) { + try { + MessageProp prop = new MessageProp(0, false); + return context.getMIC(message, s, l, prop); + } catch (GSSException ex) { + logger.error(ex.getMessage(), ex); + return null; + } + } + + public void dispose() { + try { + context.dispose(); + } catch (GSSException ex) { + } + } + + public void setCredential(GSSCredential credential) { + this.credential = credential; + } + + public GSSCredential getCredential() { + return credential; + } +} +
