Running Jobs from the Command Line

  GigaSpaces 5.X

Documentation Home
Quick Start Guide
Release Notes

Previous release

  Search Here
Searching GigaSpaces Platform 5.X Documentation

                                               

Summary: How to write a command line interface for executing jobs.

The SimpleMaster Class

The SimpleMaster class wraps the job and handles its execution.

/**
 * The Master provides the submission management, writing Tasks and taking
 * Results from the space
 */
public class SimpleMaster {
    /**
     * Submit a PrimeNumberJob for processing
     *
     * @param space The space instance for submission and retrieval
     * @param primeJob The PrimeNumberJob to submit
     * @return If the PrimeNumberJob results in the determination that the
     * number is prime, return true, otherwiae return false
     * @throws Exception If errors occur during processing
     */
    public boolean submit(JavaSpace space, PrimeNumberJob primeJob)
    throws Exception {
        /* Clean space */
        if(space instanceof IJSpace)
            ((IJSpace)space).clear(null,
                                   null);
        Task[] tasks = primeJob.split();
        long t0 = System.currentTimeMillis();
        for(int i = 0; i < tasks.length; i++) {
            tasks[i].setSubmittedTime(System.currentTimeMillis());
            space.write(tasks[i],
                        null,
                        Lease.FOREVER);
        }
        long t1 = System.currentTimeMillis();
        JobResult result = primeJob.process(space,
                                            null,
                                            false);
        long execTime = result.getExecutionTime().longValue();
        System.out.println("Wrote ["+tasks.length+"] "+
                           "entries in "+(t1-t0)+" millis, "+
                           "Workers took total of "+execTime+" millis to "+
                           "process");
        return (((Boolean)result.getResult()).booleanValue());
    }
}

The Mainline

The mainline handles the discovery of spaces and parsing of the command line arguments required to create the job.

/*
* The PrimeCLI class demonstrates the approach to use the Compute Grid from an
 * external client.
 */
public class PrimeCLI {
    /* This is for ease of use, for the invocation of the example.
     * When deploying outside of the example, this should be removed */
    static {
        System.setSecurityManager(new RMISecurityManager() {
            public void checkPermission(Permission perm) {
            }
        });
    }
    /**
     * Utility method providing the operator an opporunity to enter an
     * alternative lookup argment
     *
     * @param br BufferedReader for command line input
     *
     * @return The lookupArgument to use
     *
     * @throws IOException
     */
    static String getLookupArgument(BufferedReader br) throws IOException {
        String groups = System.getProperty("com.gs.jini_lus.groups");
        String lookupArg = "jini://*//*/GigaSpace?groups="+groups;
        while(true) {
            System.out.println("Using Lookup argument : "+lookupArg);
            System.out.print("Proceed? [y]/n ");
            String response = br.readLine();
            if(response.length() == 0 ||
               response.startsWith("y")) {
                break;
            } else if(response.startsWith("q")) {
                System.exit(0);
            } else {
                System.out.print("Enter Lookup argument : ");
                lookupArg = br.readLine();
            }
        }
        return(lookupArg);
    }
    /**
     * Utility method providing the operator the capability to interactively
     * provide a prime number to compute
     *
     * @param br BufferedReader for command line input
     *
     * @return The prime number candiate for processing
     *
     * @throws IOException
     */
    static int getPrimeCandidate(BufferedReader br) throws IOException {
        int num;
        while(true) {
            System.out.print("Enter prime number candidate : ");
            String response = br.readLine();
            try {
                num = Integer.parseInt(response);
                break;
            } catch(NumberFormatException e) {
                System.out.print("Invalid number ["+response+"], ");
            }
        }
        return(num);
    }
    public static void main(String args[]) throws Exception {
        /* Embedded web server to serve up codebase */
        Webster webster = null;
        try {
            CodeSource cs = PrimeCLI.class.getProtectionDomain().getCodeSource();
            if(cs == null)
                throw new RuntimeException("CodeSource is null");
            String path = cs.getLocation().getPath();
            int ndx = path.lastIndexOf("/");
            path = path.substring(0, ndx);
            if(path == null)
                throw new RuntimeException("unable to determine load location");
            /* Setup codebase */
            String localIPAddress = InetAddress.getLocalHost().getHostAddress();
            webster = new Webster(0, path, null, 1, 3);
            int port = webster.getPort();
            StringBuffer buff = new StringBuffer();
            buff.append("http://"+localIPAddress+":"+port+"/prime-job.jar");
            System.setProperty("java.rmi.server.codebase", buff.toString());
            System.out.println("Setting java.rmi.server.codebase : "+
                               System.getProperty("java.rmi.server.codebase"));
            BufferedReader br =
                new BufferedReader(new InputStreamReader(System.in));
            String lookupArg = getLookupArgument(br);
            /* Get the Space */
            System.out.println("Discovering compute grid ...");
            JavaSpace space = null;
            try {
                space = (JavaSpace)SpaceFinder.find(lookupArg);
            } catch(FinderException ex) {
                ex.printStackTrace();
                System.out.println("Could not find space: " + lookupArg);
                System.out.println("Ensure the ServiceGrid has deployed the " +
                                   "compute grid to succesfully "+
                                   "run this example.");
                System.exit(1);
            }
            SimpleMaster master = new SimpleMaster();
            while(true) {
                int primeCandidate = getPrimeCandidate(br);
                if(primeCandidate <= 1) {
                    System.out.println(primeCandidate+" <= 1 ignored");
                    continue;
                }
                if(primeCandidate == 2) {
                    System.out.println(primeCandidate+" == 2 is prime, try a " +
                                       "larger number");
                    continue;
                }
                /* Create the PrimeNumberTask */
                PrimeNumberJob primeJob = new PrimeNumberJob();
                primeJob.setArguments(new Object[]{
                    Integer.toString(primeCandidate)});
                /* Check if prime and print result */
                System.out.println("Submitting PrimeTask ...");
                boolean isPrime = master.submit(space, primeJob);
                System.out.println(primeCandidate+" is prime : "+isPrime);
                System.out.print("Submit another ? [y]/n? ");
                String response = br.readLine();
                if(response.length() == 0 ||
                   response.startsWith("y")) {
                    continue;
                } else {
                    break;
                }
            }
            System.exit(0);
        } finally {
            if(webster!=null)
                webster.terminate();
        }
    }
}

RELATED TOPICS

Compute Grid
Creating a Custom Job
Running Jobs from the Command Line
Spring Parallel Processing Integration
task - Service Grid CLI

Wiki Content Tree


Your Feedback Needed!

We need your help to improve this wiki site. If you have any suggestions or corrections, write to us at techw@gigaspaces.com. Please provide a link to the wiki page you are referring to.

Labels