List of usage examples for java.net InetAddress getAddress
public byte[] getAddress()
From source file:it.infn.ct.code_rade_portlet.java
/** * -- WARNING ------------------------------------------------------- * (DEPRECATED) This method will be left only for some future commits * ------------------------------------------------------------------ * This method sends the job into the distributed infrastructure using * the GridEngine methods// w ww .j a v a 2 s .c o m * * @param appInput AppInput instance storing the jobSubmission data */ void submitJob(AppInput appInput) { // Job details String executable = "/bin/sh"; // Application executable String arguments = appPreferences.getPilotScript(); // executable' arguments String outputPath = "/tmp/"; // Output Path String outputFile = "code-rade-Output.txt"; // Distributed application standard output String errorFile = "code-rade-Error.txt"; // Distrubuted application standard error String appFile = "code-rade-Files.tar.gz"; // Hostname output files (created by the pilot script) // InputSandbox (string with comma separated list of file names) String inputSandbox = appServerPath + "WEB-INF/job/" // + appPreferences.getPilotScript() // pilot script + "," + appInput.inputSandbox_inputFile // input file ; // OutputSandbox (string with comma separated list of file names) String outputSandbox = appFile; // Output file // Take care of job requirements // More requirements can be specified in the preference value 'jobRequirements' // separating each requirement by the ';' character // The loop prepares a string array with GridEngine/JSAGA compliant requirements String jdlRequirements[] = appPreferences.getJobRequirements().split(";"); int numRequirements = 0; for (int i = 0; i < jdlRequirements.length; i++) { if (!jdlRequirements[i].equals("")) { jdlRequirements[numRequirements] = "JDLRequirements=(" + jdlRequirements[i] + ")"; numRequirements++; _log.info("Requirement[" + i + "]='" + jdlRequirements[i] + "'"); } } // for each jobRequirement // Prepare the GridEngine job description GEJobDescription jobDesc = new GEJobDescription(); jobDesc.setExecutable(executable); // Specify the executeable jobDesc.setArguments(arguments); // Specify the application' arguments jobDesc.setOutputPath(outputPath); // Specify the output directory jobDesc.setOutput(outputFile); // Specify the std-output file jobDesc.setError(errorFile); // Specify the std-error file jobDesc.setOutputFiles(outputSandbox); // Setup output files (OutputSandbox) (*) jobDesc.setInputFiles(inputSandbox); // Setut input files (InputSandbox) // GridEngine' MultiInfrastructure job submission object MultiInfrastructureJobSubmission miJobSubmission = null; // // Initialize the GridEngine Multi Infrastructure Job Submission object // // GridEngine uses two different kind of constructors. The constructor // taking no database arguments is used for production environments, while // the constructor taking SciGwyUserTrackingDB parameters is normally used // for development purposes. In order to switch-on the production constructor // just set to empty strings the following portlet init parameters or form // the portlet preferences: // sciGwyUserTrackingDB_Hostname // sciGwyUserTrackingDB_Username // sciGwyUserTrackingDB_Password // sciGwyUserTrackingDB_Database // if (null != appPreferences.getSciGwyUserTrackingDB_Hostname() && !appPreferences.getSciGwyUserTrackingDB_Hostname().equals("") && null != appPreferences.getSciGwyUserTrackingDB_Username() && !appPreferences.getSciGwyUserTrackingDB_Username().equals("") && null != appPreferences.getSciGwyUserTrackingDB_Password() && !appPreferences.getSciGwyUserTrackingDB_Password().equals("") && null != appPreferences.getSciGwyUserTrackingDB_Database() && !appPreferences.getSciGwyUserTrackingDB_Database().equals("")) { String DBNM = "jdbc:mysql://" + appPreferences.getSciGwyUserTrackingDB_Hostname() + "/" + appPreferences.getSciGwyUserTrackingDB_Database(); String DBUS = appPreferences.getSciGwyUserTrackingDB_Username(); String DBPW = appPreferences.getSciGwyUserTrackingDB_Password(); miJobSubmission = new MultiInfrastructureJobSubmission(DBNM, DBUS, DBPW, jobDesc); _log.info("MultiInfrastructureJobSubmission [DEVEL]\n" + LS + " DBNM: '" + DBNM + "'" + LS + " DBUS: '" + DBUS + "'" + LS + " DBPW: '" + DBPW + "'"); } else { miJobSubmission = new MultiInfrastructureJobSubmission(jobDesc); _log.info("MultiInfrastructureJobSubmission [PROD]"); } // Assigns now all enabled infrastructures InfrastructureInfo[] infrastructuresInfo = appPreferences.getEnabledInfrastructures(); for (int i = 0; i < infrastructuresInfo.length; i++) { _log.info("Adding infrastructure #" + (i + 1) + " - Name: '" + infrastructuresInfo[i].getName() + "'" + LS); miJobSubmission.addInfrastructure(infrastructuresInfo[i]); } // Check the enabled infrastructures if (infrastructuresInfo.length > 0) { // GridOperations' Application Id int applicationId = Integer.parseInt(appPreferences.getGridOperationId()); // Grid Engine' UserTraking needs the portal IP address String portalIPAddress = ""; try { InetAddress addr = InetAddress.getLocalHost(); byte[] ipAddr = addr.getAddress(); portalIPAddress = "" + (short) (ipAddr[0] & 0xff) + ":" + (short) (ipAddr[1] & 0xff) + ":" + (short) (ipAddr[2] & 0xff) + ":" + (short) (ipAddr[3] & 0xff); } catch (Exception e) { _log.error("Unable to get the portal IP address"); } // Setup job requirements if (numRequirements > 0) miJobSubmission.setJDLRequirements(jdlRequirements); // Ready now to submit the Job miJobSubmission.submitJobAsync(appInput.username, portalIPAddress, applicationId, appInput.jobIdentifier); // Show log // View jobSubmission details in the log _log.info(LS + "JobSent" + LS + "-------" + LS + "Portal address: '" + portalIPAddress + "'" + LS + "Executable : '" + executable + "'" + LS + "Arguments : '" + arguments + "'" + LS + "Output path : '" + outputPath + "'" + LS + "Output sandbox: '" + outputSandbox + "'" + LS + "Ouput file : '" + outputFile + "'" + LS + "Error file : '" + errorFile + "'" + LS + "Input sandbox : '" + inputSandbox + "'" + LS); // _log.info } // numInfra > 0 else { _log.warn(LS + "There are no enough enabled infrastructures!" + LS + "It is impossible to send any job" + LS + "Configure the application preferences in order to setup" + LS + "or enable at least one infrastructure." + LS); } // numInfra == 0 }
From source file:it.infn.ct.mi_hostname_portlet.java
/** * -- WARNING ------------------------------------------------------- * (DEPRECATED) This method will be left only for some future commits * ------------------------------------------------------------------ * This method sends the job into the distributed infrastructure using * the GridEngine methods/*from w ww . j a v a 2 s . c o m*/ * * @param appInput AppInput instance storing the jobSubmission data */ void submitJob(AppInput appInput) { // Job details String executable = "/bin/sh"; // Application executable String arguments = appPreferences.getPilotScript(); // executable' arguments String outputPath = "/tmp/"; // Output Path String outputFile = "hostname-Output.txt"; // Distributed application standard output String errorFile = "hostname-Error.txt"; // Distrubuted application standard error String appFile = "hostname-Files.tar.gz"; // Hostname output files (created by the pilot script) // InputSandbox (string with comma separated list of file names) String inputSandbox = appServerPath + "WEB-INF/job/" // + appPreferences.getPilotScript() // pilot script + "," + appInput.inputSandbox_inputFile // input file ; // OutputSandbox (string with comma separated list of file names) String outputSandbox = appFile; // Output file // Take care of job requirements // More requirements can be specified in the preference value 'jobRequirements' // separating each requirement by the ';' character // The loop prepares a string array with GridEngine/JSAGA compliant requirements String jdlRequirements[] = appPreferences.getJobRequirements().split(";"); int numRequirements = 0; for (int i = 0; i < jdlRequirements.length; i++) { if (!jdlRequirements[i].equals("")) { jdlRequirements[numRequirements] = "JDLRequirements=(" + jdlRequirements[i] + ")"; numRequirements++; _log.info("Requirement[" + i + "]='" + jdlRequirements[i] + "'"); } } // for each jobRequirement // Prepare the GridEngine job description GEJobDescription jobDesc = new GEJobDescription(); jobDesc.setExecutable(executable); // Specify the executeable jobDesc.setArguments(arguments); // Specify the application' arguments jobDesc.setOutputPath(outputPath); // Specify the output directory jobDesc.setOutput(outputFile); // Specify the std-output file jobDesc.setError(errorFile); // Specify the std-error file jobDesc.setOutputFiles(outputSandbox); // Setup output files (OutputSandbox) (*) jobDesc.setInputFiles(inputSandbox); // Setut input files (InputSandbox) // GridEngine' MultiInfrastructure job submission object MultiInfrastructureJobSubmission miJobSubmission = null; // // Initialize the GridEngine Multi Infrastructure Job Submission object // // GridEngine uses two different kind of constructors. The constructor // taking no database arguments is used for production environments, while // the constructor taking SciGwyUserTrackingDB parameters is normally used // for development purposes. In order to switch-on the production constructor // just set to empty strings the following portlet init parameters or form // the portlet preferences: // sciGwyUserTrackingDB_Hostname // sciGwyUserTrackingDB_Username // sciGwyUserTrackingDB_Password // sciGwyUserTrackingDB_Database // if (null != appPreferences.getSciGwyUserTrackingDB_Hostname() && !appPreferences.getSciGwyUserTrackingDB_Hostname().equals("") && null != appPreferences.getSciGwyUserTrackingDB_Username() && !appPreferences.getSciGwyUserTrackingDB_Username().equals("") && null != appPreferences.getSciGwyUserTrackingDB_Password() && !appPreferences.getSciGwyUserTrackingDB_Password().equals("") && null != appPreferences.getSciGwyUserTrackingDB_Database() && !appPreferences.getSciGwyUserTrackingDB_Database().equals("")) { String DBNM = "jdbc:mysql://" + appPreferences.getSciGwyUserTrackingDB_Hostname() + "/" + appPreferences.getSciGwyUserTrackingDB_Database(); String DBUS = appPreferences.getSciGwyUserTrackingDB_Username(); String DBPW = appPreferences.getSciGwyUserTrackingDB_Password(); miJobSubmission = new MultiInfrastructureJobSubmission(DBNM, DBUS, DBPW, jobDesc); _log.info("MultiInfrastructureJobSubmission [DEVEL]\n" + LS + " DBNM: '" + DBNM + "'" + LS + " DBUS: '" + DBUS + "'" + LS + " DBPW: '" + DBPW + "'"); } else { miJobSubmission = new MultiInfrastructureJobSubmission(jobDesc); _log.info("MultiInfrastructureJobSubmission [PROD]"); } // Assigns now all enabled infrastructures InfrastructureInfo[] infrastructuresInfo = appPreferences.getEnabledInfrastructures(); for (int i = 0; i < infrastructuresInfo.length; i++) { _log.info("Adding infrastructure #" + (i + 1) + " - Name: '" + infrastructuresInfo[i].getName() + "'" + LS); miJobSubmission.addInfrastructure(infrastructuresInfo[i]); } // Check the enabled infrastructures if (infrastructuresInfo.length > 0) { // GridOperations' Application Id int applicationId = Integer.parseInt(appPreferences.getGridOperationId()); // Grid Engine' UserTraking needs the portal IP address String portalIPAddress = ""; try { InetAddress addr = InetAddress.getLocalHost(); byte[] ipAddr = addr.getAddress(); portalIPAddress = "" + (short) (ipAddr[0] & 0xff) + ":" + (short) (ipAddr[1] & 0xff) + ":" + (short) (ipAddr[2] & 0xff) + ":" + (short) (ipAddr[3] & 0xff); } catch (Exception e) { _log.error("Unable to get the portal IP address"); } // Setup job requirements if (numRequirements > 0) miJobSubmission.setJDLRequirements(jdlRequirements); // Ready now to submit the Job miJobSubmission.submitJobAsync(appInput.username, portalIPAddress, applicationId, appInput.jobIdentifier); // Show log // View jobSubmission details in the log _log.info(LS + "JobSent" + LS + "-------" + LS + "Portal address: '" + portalIPAddress + "'" + LS + "Executable : '" + executable + "'" + LS + "Arguments : '" + arguments + "'" + LS + "Output path : '" + outputPath + "'" + LS + "Output sandbox: '" + outputSandbox + "'" + LS + "Ouput file : '" + outputFile + "'" + LS + "Error file : '" + errorFile + "'" + LS + "Input sandbox : '" + inputSandbox + "'" + LS); // _log.info } // numInfra > 0 else { _log.warn(LS + "There are no enough enabled infrastructures!" + LS + "It is impossible to send any job" + LS + "Configure the application preferences in order to setup" + LS + "or enable at least one infrastructure." + LS); } // numInfra == 0 }
From source file:org.opendaylight.netvirt.dhcpservice.DhcpPktHandler.java
protected byte[] getDhcpPacketOut(DHCP reply, Ethernet etherPkt, String phyAddrees) { if (reply == null) { /*/*from w w w . j av a2 s.com*/ * DECLINE or RELEASE don't result in reply packet */ return null; } LOG.trace("Sending DHCP Pkt {}", reply); InetAddress serverIp = reply.getOptionInetAddr(DHCPConstants.OPT_SERVER_IDENTIFIER); // create UDP pkt UDP udpPkt = new UDP(); byte[] rawPkt; try { rawPkt = reply.serialize(); } catch (PacketException e) { LOG.warn("Failed to serialize packet", e); return null; } udpPkt.setRawPayload(rawPkt); udpPkt.setDestinationPort(DhcpMConstants.DHCP_CLIENT_PORT); udpPkt.setSourcePort(DhcpMConstants.DHCP_SERVER_PORT); udpPkt.setLength((short) (rawPkt.length + 8)); //Create IP Pkt try { rawPkt = udpPkt.serialize(); } catch (PacketException e) { LOG.warn("Failed to serialize packet", e); return null; } short checkSum = 0; boolean computeUdpChecksum = true; if (computeUdpChecksum) { checkSum = computeChecksum(rawPkt, serverIp.getAddress(), NetUtils.intToByteArray4(DhcpMConstants.BCAST_IP)); } udpPkt.setChecksum(checkSum); IPv4 ip4Reply = new IPv4(); ip4Reply.setPayload(udpPkt); ip4Reply.setProtocol(IPProtocols.UDP.byteValue()); ip4Reply.setSourceAddress(serverIp); ip4Reply.setDestinationAddress(DhcpMConstants.BCAST_IP); ip4Reply.setTotalLength((short) (rawPkt.length + 20)); ip4Reply.setTtl((byte) 32); // create Ethernet Frame Ethernet ether = new Ethernet(); if (etherPkt.getEtherType() == (short) NwConstants.ETHTYPE_802_1Q) { IEEE8021Q vlanPacket = (IEEE8021Q) etherPkt.getPayload(); IEEE8021Q vlanTagged = new IEEE8021Q(); vlanTagged.setCFI(vlanPacket.getCfi()); vlanTagged.setPriority(vlanPacket.getPriority()); vlanTagged.setVlanId(vlanPacket.getVlanId()); vlanTagged.setPayload(ip4Reply); vlanTagged.setEtherType(EtherTypes.IPv4.shortValue()); ether.setPayload(vlanTagged); ether.setEtherType((short) NwConstants.ETHTYPE_802_1Q); } else { ether.setEtherType(EtherTypes.IPv4.shortValue()); ether.setPayload(ip4Reply); } ether.setSourceMACAddress(getServerMacAddress(phyAddrees)); ether.setDestinationMACAddress(etherPkt.getSourceMACAddress()); try { rawPkt = ether.serialize(); } catch (PacketException e) { LOG.warn("Failed to serialize ethernet reply", e); return null; } return rawPkt; }
From source file:it.infn.ct.corsika_portlet.java
void submitJobSingle(AppInput appInput, ActionRequest request) { InfrastructureInfo[] infrastructuresInfo = appPreferences.getEnabledInfrastructures(); // Check the enabled infrastructures if (infrastructuresInfo.length > 0) { // Application Id int applicationId = Integer.parseInt(appPreferences.getGridOperationId()); // Grid Engine' UserTraking needs the portal IP address String portalIPAddress = ""; try {//from w ww .ja v a 2 s .co m InetAddress addr = InetAddress.getLocalHost(); byte[] ipAddr = addr.getAddress(); portalIPAddress = "" + ipAddr[0] + ":" + ipAddr[1] + ":" + ipAddr[2] + ":" + ipAddr[3]; } catch (Exception e) { _log.error("Unable to get the portal IP address"); } // Other job initialization settings MultiInfrastructureJobSubmission miJobSubmission = new MultiInfrastructureJobSubmission(); ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); User user = themeDisplay.getUser(); String emailAddress = user.getDisplayEmailAddress(); // Setting the user's email for notifications //MANUEL if (appInput.emailWhenFinished) { _log.info("Setting user email address: " + emailAddress); miJobSubmission.setUserEmail(emailAddress); miJobSubmission.setSenderEmail("manuel@testmail.com"); _log.info("Setting sender email adress: manuel@testmail.com"); } String inputFiles = ""; String inputFileName = ""; if (appInput.inputFile == "") { inputFiles = appServerPath + "corsikaFiles/URLParser.py"; } else { inputFiles = appInput.inputFile; String[] inputFileNames = appInput.inputFile.split("/"); inputFileName = inputFileNames[inputFileNames.length - 1]; System.out.print("inputFile vale " + appInput.inputFile); System.out.print("inputFileNames vale " + inputFileNames); System.out.print("inputFile vale " + inputFileName); } if (appInput.useStorageElement) inputFiles += "," + appServerPath + "corsikaFiles/corsikaStorageElements.sh"; else inputFiles += "," + appServerPath + "corsikaFiles/corsika.sh"; miJobSubmission.setExecutable("/usr/bin/env"); // Application executable miJobSubmission.setArguments(this.createJobArguments(appInput, inputFileName)); miJobSubmission.setOutputPath("/tmp/"); // Output Path miJobSubmission.setJobOutput("corsika-Output.txt"); // Distributed application standard output miJobSubmission.setJobError("corsika-Error.txt"); // Distrubuted application standard error miJobSubmission.setOutputFiles("corsika-Files.tar.gz"); // Hostname output files (created by the pilot script) miJobSubmission.setInputFiles(inputFiles); // Submit Job //miJobSubmission.submitJobAsync(username, hostUTDB, applicationId, appInput.jobIdentifier); // JobCollection(java.lang.String commonName, java.lang.String description, java.lang.String outputPath, java.util.ArrayList<GEJobDescription> subJobDescriptions) // JobCollection collection = new JobCollection(appInput.username, appInput.jobIdentifier, "/tmp", tasksToExecute); for (InfrastructureInfo i : infrastructuresInfo) miJobSubmission.addInfrastructure(i); miJobSubmission.submitJobAsync(appInput.username, portalIPAddress, applicationId, appInput.jobIdentifier); // Show log // View jobSubmission details in the log _log.info("JobSent"); // _log.info } // numInfra > 0 else { _log.warn(LS + "There are no infrastructures configured; impossible to send any job" + LS + "Configure the application preferences in order to setup at least" + LS + "an infrastructure." + LS); } // numInfra == 0 }
From source file:it.infn.ct.corsika_portlet.java
void submitJobParametric(AppInput appInput, ActionRequest request) { ArrayList<GEJobDescription> descriptions = new ArrayList<GEJobDescription>(); ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); User user = themeDisplay.getUser();/*from w ww. jav a 2s . co m*/ //job description int applicationId = Integer.parseInt(appPreferences.getGridOperationId()); String emailAddress = user.getDisplayEmailAddress(); String executable = "/usr/bin/env"; String outputPath = "/tmp/"; // Output Path String output = "corsika-Output.txt"; // Distributed application standard output String error = "corsika-Error.txt"; // Distrubuted application standard error String outputFiles = "corsika-Files.tar.gz"; // Hostname output files (created by the pilot script) String scriptName = ""; if (appInput.useStorageElement) scriptName = "corsikaFiles/corsikaStorageElements.sh"; else scriptName += "corsikaFiles/corsika.sh"; String uncompressedFolder = uncompress(appInput.inputFile, "/tmp"); ArrayList<String> fileNames = listFolderContents(uncompressedFolder); //requirements String _requirements = appPreferences.getJobRequirements(); for (String fileName : files) { _log.info("File = " + fileName); GEJobDescription description = new GEJobDescription(); //String inputfiles = uncompressedFolder + "/"+ fileName + ", " + appServerPath + scriptName; String inputfiles = fileName + ", " + appServerPath + scriptName; //NEW GIUSEPPE FILES inputfiles += ", " + appServerPath + "corsikaFiles/curl, " + appServerPath + "corsikaFiles/libcrypto.so.6, " + appServerPath + "corsikaFiles/libcurl.so.3, " + appServerPath + "corsikaFiles/libssl.so.6"; description.setArguments(this.createJobArguments(appInput, fileName)); description.setExecutable(executable); description.setOutputPath(outputPath); description.setOutput(output); description.setError(error); description.setInputFiles(inputfiles); descriptions.add(description); if ((_requirements != null) && (!_requirements.isEmpty())) description.setJDLRequirements(_requirements); } // GridEngine' JobCollectionSubmission job submission object JobCollection collection = new JobParametric(appInput.username, appInput.jobIdentifier, emailAddress, "/tmp", descriptions, executable); JobCollectionSubmission tmpJobCollectionSubmission = new JobCollectionSubmission(collection); // Assigns all enabled infrastructures InfrastructureInfo[] infrastructuresInfo = appPreferences.getEnabledInfrastructures(); // Check the enabled infrastructures if (infrastructuresInfo.length > 0) { // Grid Engine' UserTraking needs the portal IP address String portalIPAddress = ""; try { InetAddress addr = InetAddress.getLocalHost(); byte[] ipAddr = addr.getAddress(); portalIPAddress = "" + ipAddr[0] + ":" + ipAddr[1] + ":" + ipAddr[2] + ":" + ipAddr[3]; } catch (Exception e) { _log.error("Unable to get the portal IP address"); } // Submit Collection tmpJobCollectionSubmission.submitJobCollection(infrastructuresInfo, portalIPAddress, applicationId); // Show log // View jobSubmission details in the log _log.info(LS + "Job Collection Sent" + LS + "-------" + LS + "Portal address: '" + portalIPAddress + "'" + LS); // _log.info } // numInfra > 0 else { _log.warn(LS + "There are no enough enabled infrastructures!" + LS + "It is impossible to send any job" + LS + "Configure the application preferences in order to setup" + LS + "or enable at least one infrastructure." + LS); } // numInfra == 0 }
From source file:it.infn.ct.molon_portlet.java
/** * This method sends the job into the distributed infrastructure using the * GridEngine methods/* w w w . ja va 2 s.c om*/ * * @param appInput AppInput instance storing the jobSubmission data */ /* void submitJobGroup(AppInput appInput) { _log.info("Starting to submit job"); String inputFiles= appServerPath + "molonFiles/URLParser.py"; inputFiles += "," + appServerPath+ "molonFiles/Molon.sh"; GEJobDescription taskToExecute = new GEJobDescription(); taskToExecute.setExecutable("/usr/bin/env"); // Application executable taskToExecute.setArguments("sh Molon.sh " + appInput.jobPID); taskToExecute.setOutputPath("/tmp/"); // Output Path taskToExecute.setOutput("molon-Output.txt"); // Distributed application standard output taskToExecute.setError("molon-Error.txt"); // Distrubuted application standard error taskToExecute.setOutputFiles("molon-Files.tar.gz"); // Hostname output files (created by the pilot script) taskToExecute.setInputFiles(inputFiles); ArrayList<GEJobDescription> tasksToExecute = new ArrayList<GEJobDescription>(); tasksToExecute.add(taskToExecute); // GridEngine' JobCollectionSubmission job submission object JobCollectionSubmission tmpJobCollectionSubmission = null; JobCollection collection = new JobCollection(appInput.username, appInput.jobIdentifier, "/tmp", tasksToExecute); if (null != appPreferences.getSciGwyUserTrackingDB_Hostname() && !appPreferences.getSciGwyUserTrackingDB_Hostname().equals("") && null != appPreferences.getSciGwyUserTrackingDB_Username() && !appPreferences.getSciGwyUserTrackingDB_Username().equals("") && null != appPreferences.getSciGwyUserTrackingDB_Password() && !appPreferences.getSciGwyUserTrackingDB_Password().equals("") && null != appPreferences.getSciGwyUserTrackingDB_Database() && !appPreferences.getSciGwyUserTrackingDB_Database().equals("")) { String arg1 = "jdbc:mysql://" + appPreferences.getSciGwyUserTrackingDB_Hostname() + "/" + appPreferences.getSciGwyUserTrackingDB_Database(); String arg2 = appPreferences.getSciGwyUserTrackingDB_Username(); String arg3 = appPreferences.getSciGwyUserTrackingDB_Password(); _log.info("JobCollectionSubmission [DEVEL]\n" + LS + " Arg1: '" + arg1 + "'" + LS + " Arg2: '" + arg2 + "'" + LS + " Arg3: '" + arg3 + "'"); tmpJobCollectionSubmission = new JobCollectionSubmission(arg1, arg2, arg3, collection); } else { tmpJobCollectionSubmission = new JobCollectionSubmission(collection); _log.info("JobCollectionSubmission [PROD]"); } // Assigns all enabled infrastructures InfrastructureInfo[] infrastructuresInfo = appPreferences.getEnabledInfrastructures(); // Check the enabled infrastructures if (infrastructuresInfo.length > 0) { // Application Id int applicationId = Integer.parseInt(appPreferences.getGridOperationId()); // Grid Engine' UserTraking needs the portal IP address String portalIPAddress = ""; try { InetAddress addr = InetAddress.getLocalHost(); byte[] ipAddr = addr.getAddress(); portalIPAddress = "" + ipAddr[0] + ":" + ipAddr[1] + ":" + ipAddr[2] + ":" + ipAddr[3]; } catch (Exception e) { _log.error("Unable to get the portal IP address"); } // Submit Collection tmpJobCollectionSubmission.submitJobCollection(infrastructuresInfo, portalIPAddress, applicationId); // Show log // View jobSubmission details in the log _log.info( LS + "Job Collection Sent" + LS + "-------" + LS + "Portal address: '" + portalIPAddress + "'" + LS); // _log.info } // numInfra > 0 else { _log.warn( LS + "There are no enough enabled infrastructures!" + LS + "It is impossible to send any job" + LS + "Configure the application preferences in order to setup" + LS + "or enable at least one infrastructure." + LS); } // numInfra == 0 } // submitJob */ void submitJob(AppInput appInput) { InfrastructureInfo[] infrastructuresInfo = appPreferences.getEnabledInfrastructures(); // Check the enabled infrastructures if (infrastructuresInfo.length > 0) { // Application Id int applicationId = Integer.parseInt(appPreferences.getGridOperationId()); // Grid Engine' UserTraking needs the portal IP address String portalIPAddress = ""; try { InetAddress addr = InetAddress.getLocalHost(); byte[] ipAddr = addr.getAddress(); portalIPAddress = "" + ipAddr[0] + ":" + ipAddr[1] + ":" + ipAddr[2] + ":" + ipAddr[3]; } catch (Exception e) { _log.error("Unable to get the portal IP address"); } // Data below should not used by portlets //String unameUTDB=appInit.sciGwyUserTrackingDB_Username; // Username //String passwdUTDB=appInit.sciGwyUserTrackingDB_Password; // Password //String dbnameUTDB=appInit.sciGwyUserTrackingDB_Database; // Database // Job details // Other job initialization settings MultiInfrastructureJobSubmission miJobSubmission = new MultiInfrastructureJobSubmission(); String inputFiles = ""; String inputFileName = ""; if (appInput.jobPID.length() > 1) { inputFiles = appServerPath + "molonFiles/URLParser.py,"; } else if (appInput.inputFile.length() > 1) { inputFiles = appInput.inputFile + ","; String[] inputFileNames = appInput.inputFile.split("/"); inputFileName = inputFileNames[inputFileNames.length - 1]; System.out.print("inputFile vale " + appInput.inputFile); System.out.print("inputFileNames vale " + inputFileNames); System.out.print("inputFile vale " + inputFileName); } inputFiles += appServerPath + "molonFiles/Molon.sh"; inputFiles += "," + appServerPath + "molonFiles/molon.cpp"; miJobSubmission.setExecutable("/usr/bin/env"); // Application executable if (appInput.jobPID.length() > 1) miJobSubmission.setArguments("sh Molon.sh PID " + appInput.jobPID); else if (appInput.inputURL.length() > 1) { String escapedURL = StringUtils.replace(appInput.inputURL, "(", "\\("); escapedURL = StringUtils.replace(escapedURL, ")", "\\)"); escapedURL = StringUtils.replace(escapedURL, "%", "\\%"); escapedURL = StringUtils.replace(escapedURL, "-", "\\-"); escapedURL = StringUtils.replace(escapedURL, "_", "\\_"); miJobSubmission.setArguments("sh Molon.sh URL " + escapedURL); //QUYIZA HAYA QUE PONER COMILLAS AQUI } else miJobSubmission.setArguments("sh Molon.sh FILE " + inputFileName); miJobSubmission.setOutputFiles("outputFile.txt"); // Hostname output files (created by the pilot script) miJobSubmission.setOutputPath("/tmp/"); // Output Path miJobSubmission.setJobOutput("molon-Output.txt"); // Distributed application standard output miJobSubmission.setJobError("molon-Error.txt"); // Distrubuted application standard error miJobSubmission.setInputFiles(inputFiles); // Submit Job //miJobSubmission.submitJobAsync(username, hostUTDB, applicationId, appInput.jobIdentifier); // JobCollection(java.lang.String commonName, java.lang.String description, java.lang.String outputPath, java.util.ArrayList<GEJobDescription> subJobDescriptions) // JobCollection collection = new JobCollection(appInput.username, appInput.jobIdentifier, "/tmp", tasksToExecute); for (InfrastructureInfo i : infrastructuresInfo) miJobSubmission.addInfrastructure(i); miJobSubmission.submitJobAsync(appInput.username, portalIPAddress, applicationId, appInput.jobIdentifier); // Show log // View jobSubmission details in the log _log.info("JobSent"); // _log.info } // numInfra > 0 else { _log.warn(LS + "There are no infrastructures configured; impossible to send any job" + LS + "Configure the application preferences in order to setup at least" + LS + "an infrastructure." + LS); } // numInfra == 0 }
From source file:it.infn.ct.picalc_portlet.java
/** * This method sends the job into the distributed infrastructure using * the GridEngine methods/*from w w w . java2 s. c om*/ * * @param appInput AppInput instance storing the jobSubmission data */ void submitJob(AppInput appInput, PortalInfo portalInfo) { // // Initialize the GridEngine Multi Infrastructure Job Submission object // MultiInfrastructureJobSubmission miJobSubmission = new MultiInfrastructureJobSubmission(); // Assigns all enabled infrastructures InfrastructureInfo[] infrastructuresInfo = appPreferences.getEnabledInfrastructures(); for (int i = 0; i < infrastructuresInfo.length; i++) { _log.info("Adding infrastructure #" + (i + 1) + " - Name: '" + infrastructuresInfo[i].getName() + "'" + LS); miJobSubmission.addInfrastructure(infrastructuresInfo[i]); } // Check the enabled infrastructures if (infrastructuresInfo.length > 0) { // Application Id int applicationId = Integer.parseInt(appPreferences.getGridOperationId()); // Grid Engine' UserTraking needs the portal IP address String portalIPAddress = ""; try { InetAddress addr = InetAddress.getLocalHost(); byte[] ipAddr = addr.getAddress(); portalIPAddress = "" + (ipAddr[0] & 0xff) + ":" + (ipAddr[1] & 0xff) + ":" + (ipAddr[2] & 0xff) + ":" + (ipAddr[3] & 0xff); } catch (Exception e) { _log.error("Unable to get the portal IP address"); } // Multimiddleware boolean readyToSubmit = false; // True only if the selected middleware is recognized and properly setup InfrastructureInfo infrastructure = miJobSubmission.getInfrastructure(); // Returns one of the added infrastructures // Update the middleware info into PortalInfo portalInfo.setMiddleware(infrastructure.getMiddleware()); _log.info(LS + "----------------------------------" + LS + "MULTIMIDDLEWARE: " + infrastructure.getMiddleware() + LS + "----------------------------------"); // // Get the PortalInfo script file name // String PortalInfoScript = portalInfo.jobPortalInfo(); String executable = ""; String arguments = ""; String outputPath = "/tmp/"; String cpunumber = "4"; String outputFile = "Hello-Parallel-Output.txt"; // Distributed application standard output String errorFile = ".Hello-Parallel-Error.txt"; // Distrubuted application standard error String outputSandbox = "README.txt"; // PiCalc output files (created by the mpi-hooks scripts) // InputSandbox (string with comma separated list of file names) String inputSandbox = appServerPath + "WEB-INF/job/" // + appPreferences.getPilotScript() // pilot script + "," + PortalInfoScript // portalinfo + "," + appServerPath + "WEB-INF/job/README.txt" // README.txt + "," + appServerPath + "WEB-INF/job/cpi.c" // MPI code to compute cpi + "," + appServerPath + "images/AppLogo.png" // application logo (used by notification) + "," + appServerPath + "WEB-INF/job/mpi-hooks.sh" // mpi-wrapper-script + "," + appServerPath + "WEB-INF/job/mpi-start-wrapper.sh" // mpi-wrapper-script + "," + appServerPath + "WEB-INF/job/cpi_xn03" // GARUDA binary + "," + appServerPath + "WEB-INF/job/cpi_ec" // GARUDA binary + "," + appServerPath + "WEB-INF/job/hello.mpi" // UNICORE binary ; // Infrastructure specific settings if (infrastructure.getMiddleware().equals("glite")) { executable = "/bin/sh"; // Application executable (mpi-start) arguments = appPreferences.getPilotScript() // executable' arguments: (pilot_script) + " " + PortalInfoScript; // PortalInfo.sh script (full path in local filesystem) // Take care of job requirements // More requirements can be specified in the preference value 'jobRequirements' // separating each requirement by the ';' character // The ';' separated list will be translated into an array of strings // including the statement 'JDLRequirements=(x)' where x is the requirement field String jdlRequirements[] = appPreferences.getJobRequirements().split(";"); int numRequirements = 0; for (int i = 0; i < jdlRequirements.length; i++) { if (!jdlRequirements[i].equals("")) { jdlRequirements[numRequirements] = "JDLRequirements=(" + jdlRequirements[i] + ")"; numRequirements++; _log.info("Requirement[" + i + "]='" + jdlRequirements[i] + "'"); } } // for each jobRequirement if (numRequirements > 0) miJobSubmission.setJDLRequirements(jdlRequirements); miJobSubmission.setExecutable(executable); miJobSubmission.setTotalCPUCount(cpunumber); miJobSubmission.setArguments(arguments); // Infrastructure specific settings have been specified // the job is ready to be submitted readyToSubmit = true; } // if supported middleware (gLite) else if (infrastructure.getMiddleware().equals("wsgram")) { //WSGRAM MPI miJobSubmission.setExecutable("cpi_xn03"); miJobSubmission.setSPMDVariation("MPI"); // Infrastructure specific settings have been specified // the job is ready to be submitted readyToSubmit = true; } // if supported middleware (wsgram) else if (infrastructure.getMiddleware().equals("unicore")) { miJobSubmission.setExecutable("hello.mpi"); miJobSubmission.setSPMDVariation("OpenMPI"); miJobSubmission.setTotalCPUCount("4"); // Infrastructure specific settings have been specified // the job is ready to be submitted readyToSubmit = true; } // if supported middleware (unicore) else if (infrastructure.getMiddleware().equals("ssh")) { // determine the queue name String infrastructureName = infrastructure.getName(); String[] nameItems = infrastructureName.split(";"); String infrastructureQueue = ""; String infrastructureHost = ""; if (nameItems.length > 1) { String[] infraQatH = nameItems[1].split("@"); if (infraQatH.length > 0) infrastructureQueue = infraQatH[0]; if (infraQatH.length > 1) infrastructureHost = infraQatH[1]; _log.info(LS + "----------------------" + LS + "SSH:" + LS + " infraQueue: " + infrastructureQueue + LS + " infraHost : " + infrastructureHost + LS + "----------------------"); } // Prepare job description miJobSubmission.setExecutable("start.sh"); miJobSubmission.setArguments(infrastructureHost + " lsf.sh mpi.job " + infrastructureQueue); outputSandbox = "job.output,job.error,pwd.out"; inputSandbox = appServerPath + "WEB-INF/job/start.sh" + "," + appServerPath + "WEB-INF/job/lsf.sh" //+","+appServerPath+"WEB-INF/job/mpi.job" automatically generated by start.sh + "," + appServerPath + "WEB-INF/job/hello.mpi" //+","+appServerPath+"WEB-INF/job/cpi.mpi" ; // Infrastructure specific settings have been specified // the job is ready to be submitted readyToSubmit = true; } // if supported middleware (ssh) // No possible to use ourgrid with MPI // else if (infrastructure.getMiddleware().equals("ourgrid")) { // } // if supported middleware (ourgrid) else { // Unsupported middleware _log.warn(LS + "The selected middleware: '" + infrastructure.getMiddleware() + "' is unsupported!"); } // If ready for submission if (readyToSubmit) { // Common job initialization settings miJobSubmission.setNumberOfProcesses("4"); // Number of processes miJobSubmission.setOutputPath(outputPath); // Specify the output directory miJobSubmission.setOutputFiles(outputSandbox); // Setup output files (OutputSandbox) miJobSubmission.setJobOutput(outputFile); // Specify the std-outputr file miJobSubmission.setJobError(errorFile); // Specify the std-error file if (null != inputSandbox // Setup input files (InputSandbox) avoiding && inputSandbox.length() > 0) // null or empty inputSandboxes miJobSubmission.setInputFiles(inputSandbox); // Input files // // Submit the job // miJobSubmission.submitJobAsync(infrastructure, appInput.username, portalIPAddress, applicationId, appInput.jobIdentifier); // Show log // View jobSubmission details in the log _log.info(LS + "JobSent" + LS + "-------" + LS + "Portal address: '" + portalIPAddress + "'" + LS + "Executable : '" + executable + "'" + LS + "Arguments : '" + arguments + "'" + LS + "Output path : '" + outputPath + "'" + LS + "Output sandbox: '" + outputSandbox + "'" + LS + "Ouput file : '" + outputFile + "'" + LS + "Error file : '" + errorFile + "'" + LS + "Input sandbox : '" + inputSandbox + "'" + LS); // _log.info } // readyToSubmit } // numInfra > 0 else { _log.warn(LS + "There are no enough enabled infrastructures!" + LS + "It is impossible to send any job" + LS + "Configure the application preferences in order to setup" + LS + "or enable at least one infrastructure." + LS); } // numInfra == 0 }
From source file:it.infn.ct.aleph_portlet.java
public int occiSubmit(String username, String firstName, String lastName, String portalname, String alephfile, String alephAlg) {// w w w . ja v a2 s. com // Retrieve the full path to the job directory String jobPath = appServerPath + "WEB-INF/job/"; String rOCCIResourcesList[] = null; Boolean useCloudProviderInfrastructure = false; InfrastructureInfo infrastructure; MultiInfrastructureJobSubmission mijs = new MultiInfrastructureJobSubmission(); if (cloudProvider != null && cloudProvider.isEnabled() && cloudProvider.getProviderList(alephGridOperation) > 0) { if (!useCloudProviderInfrastructure) { _log.info("Submission aided by CloudProvider - Using the resourceList method (no Infrastructures)"); rOCCIResourcesList = cloudProvider.getResourcesList(); // Retrieve preference settings first eTokenHost = prefs.getPrefValue("eTokenHost"); eTokenPort = prefs.getPrefValue("eTokenPort"); eTokenMd5Sum = prefs.getPrefValue("eTokenMd5Sum"); eTokenVO = prefs.getPrefValue("eTokenVO"); eTokenVOGroup = prefs.getPrefValue("eTokenVOGroup"); eTokenProxyRenewal = prefs.getPrefValue("eTokenProxyRenewal"); // Prepare the GridEngine' InfrastructureInfo object infrastructure = new InfrastructureInfo("GridCT" // Infrastruture name , "rocci" // Adaptor , "" // , rOCCIResourcesList // Resources list , eTokenHost // eTokenServer host , eTokenPort // eTokenServer port , eTokenMd5Sum // eToken id (md5sum) , eTokenVO // VO , eTokenVOGroup // VO.group.role , true // ProxyRFC ); // Add infrastructure to an array of infrastructures and add them to MultiInfrastructureJobSubmission object mijs.addInfrastructure(infrastructure); } else { _log.info("Submission aided by CloudProvider - Using the infrastructure method"); cloudProvider.AppInfrastructures(alephGridOperation); //InfrastructureInfo[] infrastructuresInfo = new InfrastructureInfo[cloudProvider.infrastructuresList.size()]; for (int i = 0; i < cloudProvider.infrastructuresList.size(); i++) { CloudProvider.Infrastructure cpinfra = (CloudProvider.Infrastructure) cloudProvider.infrastructuresList .get(i); _log.info("Infrastructure[" + i + "]:" + LS + " name: '" + cpinfra.name + "'" + LS + " adaptor: '" + cpinfra.adaptor + "'" + LS + " enabled: '" + cpinfra.enabled + "'"); infrastructure = new InfrastructureInfo(cpinfra.name, cpinfra.adaptor, "", cpinfra.resourceList(), cpinfra.getParam("etoken_host"), cpinfra.getParam("etoken_port"), cpinfra.getParam("etoken_id"), cpinfra.getParam("VO"), cpinfra.getParam("VO_GroupRole"), cpinfra.getParam("ProxyRFC").equalsIgnoreCase("true")); //infrastructuresInfo[i]=infraInfo; // Enabled flag is obtained ANDing Infrastructure main flag with applicationInfrastructure flag if (cpinfra.enabled) { mijs.addInfrastructure(infrastructure); _log.info("Added infrastructure - '" + cpinfra.name + "'"); } else _log.info("Skipping infrastructure - '" + cpinfra.name + "' because not enabled"); } } } else { // Setup CloudProvider object for nebula-server-01 CloudProvider cp1 = new CloudProvider("nebula-server-01", "nebula-server-01.ct.infn.it", 9000, "rocci"); // Assign OCCI parameters to the CloudProvider object String params1[][] = { { "resource", "compute" }, { "action", "create" }, { "attributes_title", "aleph2k" }, { "mixin_os_tpl", "uuid_aleph2000_vm_71" }, { "mixin_resource_tpl", "small" }, { "auth", "x509" } //,{ "publickey_file" , jobPath + ".ssh/id_dsa.pub" } // (!) UNUSED; GE uses: $HOME/.ssh/id_rsa.pub //,{ "privatekey_file" , jobPath + ".ssh/id_dsa" } // (!) UNUSED; GE uses: $HOME/.ssh/id_rsa }; // Add OCCI parameters to the cloud provider object cp1.addParams(params1); // Setup CloudProvider object for stack-server-01 CloudProvider cp2 = new CloudProvider("stack-server-01", "stack-server-01.ct.infn.it", 8787, "rocci"); // Assign OCCI parameters to the CloudProvider object String params2[][] = { { "resource", "compute" }, { "action", "create" }, { "attributes_title", "aleph2k" }, { "mixin_os_tpl", "c3484114-9c67-44ff-a3da-ea9e6058fe3b" }, { "mixin_resource_tpl", "m1-large" }, { "auth", "x509" } }; // Add OCCI parameters to the cloud provider object cp2.addParams(params2); // Retrieve from cloud provider objects the OCCI endpoints String rOCCIURL1 = cp1.endPoint(); _log.info("OCCI Endpoint1: '" + rOCCIURL1 + "'"); String rOCCIURL2 = cp2.endPoint(); _log.info("OCCI Endpoint2: '" + rOCCIURL2 + "'"); // Prepare the ROCCI resource list String resList[] = { rOCCIURL1 // ,rOCCIURL2 }; rOCCIResourcesList = resList; // Prepare the GridEngine' InfrastructureInfo object infrastructure = new InfrastructureInfo("GridCT" // Infrastruture name , "rocci" // Adaptor , "" // , rOCCIResourcesList // Resources list , "etokenserver.ct.infn.it" // eTokenServer host , "8082" // eTokenServer port , "bc779e33367eaad7882b9dfaa83a432c"// eToken id (md5sum) , "fedcloud.egi.eu" // VO , "fedcloud.egi.eu" // VO.group.role , true // ProxyRFC ); // Add infrastructure to an array of infrastructures and add them to MultiInfrastructureJobSubmission object mijs.addInfrastructure(infrastructure); } // Cloud job requires a valid proxy to operate // The eTokenserver proxy will be included into the inputSandbox //File temp=null; //String alephPxyFile = "/tmp/aleph.pxy"; //temp = new File(alephPxyFile); iSrv.getRobotProxyFile("etokenserver.ct.infn.it", "8082", "bc779e33367eaad7882b9dfaa83a432c", "fedcloud.egi.eu", "fedcloud.egi.eu", "true", proxyFile); // Build the job identifier String[] alephfile_path = { "" }; String alephfileName = ""; int vmduration = -1; if (null != alephfile) { alephfile_path = alephfile.split("/"); alephfileName = alephfile_path[alephfile_path.length - 1]; } String vmuuid = ""; String GE_JobId = "aleph: "; if (isAlephVMEnabled && alephAlg == null) { String moreInfo = ""; if (!alephfileName.equals("")) moreInfo = "'" + alephfile + "'"; vmuuid = iSrv.getUUID(); vmduration = iSrv.getServiceDuration(); GE_JobId = "VM('" + vmuuid + "') " + moreInfo; } else GE_JobId = "'" + alephfileName + "'"; // Set job properties mijs.setExecutable("aleph.sh"); // Executable mijs.setArguments( // Arguments (null == alephfile ? "\"\"" : alephfile) + " " // aleph file + proxyFile + " " // proxy certificate file (having full path) + portalSSHKey + " " // portal public SSH key (having full path) + portalHost + " " // portlal host (needed to get notify) + username + " " // portal username + "\"" + firstName + "\" " // portal user first name + "\"" + lastName + "\" " // portal user last name + userMail + " " // portal user email address + cloudmgrHost + " " // cloudmgr contacting URL + "\"" + vmuuid + "\" " // VM UUID + (null == alephAlg ? "\"\"" : alephAlg) + " " // ALEPH analisys application (MITQCD,6LEP,...) + "\"" + portalname + "\" " // portal name + vmduration + " " // VM duration in seconds + "\"" + GE_JobId + "\" " // the job identifier ); mijs.setJobOutput("stdout.txt"); // std-output mijs.setJobError("stderr.txt"); // std-error mijs.setOutputPath("/tmp/"); // Output path mijs.setInputFiles(jobPath + "aleph.sh" + "," + // Aleph pilot script proxyFile + "," + // proxy file full path portalSSHKey // portal public ssh key ); // InputSandbox mijs.setOutputFiles("aleph_output.tar"); // OutputSandbox // Determine the host IP address String portalIPAddress = ""; try { InetAddress addr = InetAddress.getLocalHost(); byte[] ipAddr = addr.getAddress(); portalIPAddress = "" + (short) (ipAddr[0] & 0xff) + ":" + (short) (ipAddr[1] & 0xff) + ":" + (short) (ipAddr[2] & 0xff) + ":" + (short) (ipAddr[3] & 0xff); } catch (Exception e) { _log.error("Unable to get the portal IP address"); } // Submit the job // Submission uses addInfrastructure method; this call is no longer necessary // mijs.submitJobAsync(infrastructure, username, portalIPAddress, alephGridOperation, GE_JobId); mijs.submitJobAsync(username, portalIPAddress, alephGridOperation, GE_JobId); // Remove proxy temporary file // temp.delete(); Cannot remove here the file, job submission fails // Interactive job execution (iservices) if (isAlephVMEnabled && alephAlg == null) { iSrv.allocService(username, vmuuid); iSrv.dumpAllocations(); } return 0; }
From source file:org.openbaton.clients.interfaces.client.openstack.OpenstackClient.java
private static String translateToNAT(String floatingIp) throws UnknownHostException { Properties natRules = new Properties(); try {//from ww w . j a v a2s .com File file = new File("/etc/openbaton/plugin/openstack/nat-translation-rules.properties"); if (file.exists()) { natRules.load(new FileInputStream(file)); } else { natRules.load(OpenstackClient.class.getResourceAsStream("/nat-translation-rules.properties")); } } catch (IOException e) { log.warn("no translation rules!"); return floatingIp; } for (Map.Entry<Object, Object> entry : natRules.entrySet()) { String fromCidr = (String) entry.getKey(); String toCidr = (String) entry.getValue(); log.debug("cidr is: " + fromCidr); SubnetUtils utilsFrom = new SubnetUtils(fromCidr); SubnetUtils utilsTo = new SubnetUtils(toCidr); SubnetUtils.SubnetInfo subnetInfoFrom = utilsFrom.getInfo(); SubnetUtils.SubnetInfo subnetInfoTo = utilsTo.getInfo(); InetAddress floatingIpNetAddr = InetAddress.getByName(floatingIp); if (subnetInfoFrom.isInRange(floatingIp)) { //translation! log.debug("From networkMask " + subnetInfoFrom.getNetmask()); log.debug("To networkMask " + subnetInfoTo.getNetmask()); if (!subnetInfoFrom.getNetmask().equals(subnetInfoTo.getNetmask())) { log.error("Not translation possible, netmasks are different"); return floatingIp; } byte[] host = new byte[4]; for (int i = 0; i < floatingIpNetAddr.getAddress().length; i++) { byte value = (byte) (floatingIpNetAddr.getAddress()[i] | InetAddress.getByName(subnetInfoFrom.getNetmask()).getAddress()[i]); if (value == -1) { host[i] = 0; } else { host[i] = value; } } byte[] netaddress = InetAddress.getByName(subnetInfoTo.getNetworkAddress()).getAddress(); String[] result = new String[4]; for (int i = 0; i < netaddress.length; i++) { int intValue = new Byte((byte) (netaddress[i] | Byte.valueOf(host[i]))).intValue(); if (intValue < 0) { intValue = intValue & 0xFF; } result[i] = String.valueOf(intValue); } return StringUtils.join(result, "."); } } return floatingIp; }
From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java
public static List<InetAddress> getDns(Context context) { List<InetAddress> listDns = new ArrayList<>(); List<String> sysDns = Util.getDefaultDNS(context); // Get custom DNS servers SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String vpnDns1 = prefs.getString("dns", null); String vpnDns2 = prefs.getString("dns2", null); Log.i(TAG, "DNS system=" + TextUtils.join(",", sysDns) + " VPN1=" + vpnDns1 + " VPN2=" + vpnDns2); if (vpnDns1 != null) try {//w ww .jav a 2 s. c o m InetAddress dns = InetAddress.getByName(vpnDns1); if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress())) listDns.add(dns); } catch (Throwable ignored) { } if (vpnDns2 != null) try { InetAddress dns = InetAddress.getByName(vpnDns2); if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress())) listDns.add(dns); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } // Use system DNS servers only when no two custom DNS servers specified if (listDns.size() <= 1) for (String def_dns : sysDns) try { InetAddress ddns = InetAddress.getByName(def_dns); if (!listDns.contains(ddns) && !(ddns.isLoopbackAddress() || ddns.isAnyLocalAddress())) listDns.add(ddns); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } // Remove local DNS servers when not routing LAN boolean lan = prefs.getBoolean("lan", false); if (lan) { List<InetAddress> listLocal = new ArrayList<>(); try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); if (nis != null) while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); if (ni != null && ni.isUp() && !ni.isLoopback()) { List<InterfaceAddress> ias = ni.getInterfaceAddresses(); if (ias != null) for (InterfaceAddress ia : ias) { InetAddress hostAddress = ia.getAddress(); BigInteger host = new BigInteger(1, hostAddress.getAddress()); int prefix = ia.getNetworkPrefixLength(); BigInteger mask = BigInteger.valueOf(-1) .shiftLeft(hostAddress.getAddress().length * 8 - prefix); for (InetAddress dns : listDns) if (hostAddress.getAddress().length == dns.getAddress().length) { BigInteger ip = new BigInteger(1, dns.getAddress()); if (host.and(mask).equals(ip.and(mask))) { Log.i(TAG, "Local DNS server host=" + hostAddress + "/" + prefix + " dns=" + dns); listLocal.add(dns); } } } } } } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } List<InetAddress> listDns4 = new ArrayList<>(); List<InetAddress> listDns6 = new ArrayList<>(); try { listDns4.add(InetAddress.getByName("8.8.8.8")); listDns4.add(InetAddress.getByName("8.8.4.4")); listDns6.add(InetAddress.getByName("2001:4860:4860::8888")); listDns6.add(InetAddress.getByName("2001:4860:4860::8844")); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } for (InetAddress dns : listLocal) { listDns.remove(dns); if (dns instanceof Inet4Address) { if (listDns4.size() > 0) { listDns.add(listDns4.get(0)); listDns4.remove(0); } } else { if (listDns6.size() > 0) { listDns.add(listDns6.get(0)); listDns6.remove(0); } } } } // Prefer IPv4 addresses Collections.sort(listDns, new Comparator<InetAddress>() { @Override public int compare(InetAddress a, InetAddress b) { boolean a4 = (a instanceof Inet4Address); boolean b4 = (b instanceof Inet4Address); if (a4 && !b4) return -1; else if (!a4 && b4) return 1; else return 0; } }); return listDns; }