Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
bundle the native library into the jar file
[simgrid.git] / org / simgrid / msg / Msg.java
1 /*
2  * JNI interface to C code for MSG.
3  * 
4  * Copyright 2006-2012 The SimGrid Team.           
5  * All right reserved. 
6  *
7  * This program is free software; you can redistribute 
8  * it and/or modify it under the terms of the license 
9  * (GNU LGPL) which comes with this package.
10  */
11
12 package org.simgrid.msg;
13
14 import java.io.FileOutputStream;
15 import java.io.InputStream;
16 import java.io.OutputStream;
17 import java.io.File;
18
19
20 public final class Msg {
21         /* Statically load the library which contains all native functions used in here */
22         static {
23                 try {
24                         /* prefer the version on disk, if existing */
25                         System.loadLibrary("SG_java");
26                 } catch (UnsatisfiedLinkError e) {
27                         /* If not found, unpack the one bundled into the jar file and use it */
28                         loadLib("simgrid");
29                         loadLib("SG_java");
30                 }
31         }
32         private static void loadLib (String name) {
33                 String Path = "NATIVE/"+System.getProperty("os.name")+"/"+System.getProperty("os.arch")+"/";
34                 String filename=name;
35                 InputStream in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
36                 
37                 if (in == null) {
38                         filename = "lib"+name+".so";
39                         in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
40                 } 
41                 if (in == null) {
42                         filename = name+".dll";
43                         in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
44                 }  
45                 if (in == null) {
46                         filename = "lib"+name+".dylib";
47                         in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
48                 }  
49                 if (in == null) {
50                         throw new RuntimeException("Cannot find library "+name+" in path "+Path+". Sorry, but this jar does not seem to be usable on your machine.");
51                 }
52 // Caching the file on disk: desactivated because it could fool the users               
53 //              if (new File(filename).isFile()) {
54 //                      // file was already unpacked -- use it directly
55 //                      System.load(new File(".").getAbsolutePath()+File.separator+filename);
56 //                      return;
57 //              }
58                 try {
59                         // We must write the lib onto the disk before loading it -- stupid operating systems
60                         File fileOut = new File(filename);
61 //                      if (!new File(".").canWrite()) {
62 //                              System.out.println("Cannot write in ."+File.separator+filename+"; unpacking the library into a temporary file instead");
63                                 fileOut = File.createTempFile("simgrid-", ".tmp");
64                                 // don't leak the file on disk, but remove it on JVM shutdown
65                                 Runtime.getRuntime().addShutdownHook(new Thread(new FileCleaner(fileOut.getAbsolutePath())));
66 //                      }
67 //                      System.out.println("Unpacking SimGrid native library to " + fileOut.getAbsolutePath());
68                         OutputStream out = new FileOutputStream(fileOut);
69                         
70                         /* copy the library in position */  
71                         byte[] buffer = new byte[4096]; 
72                         int bytes_read; 
73                         while ((bytes_read = in.read(buffer)) != -1)     // Read until EOF
74                                 out.write(buffer, 0, bytes_read); 
75                       
76                         /* close all file descriptors, and load that shit */
77                         in.close();
78                         out.close();
79                         System.load(fileOut.getAbsolutePath());
80                 } catch (Exception e) {
81                         System.err.println("Cannot load the bindings to the simgrid library: ");
82                         e.printStackTrace();
83                         System.err.println("This jar file does not seem to fit your system, sorry");
84                         System.exit(1);
85                 }
86         }               
87         /* A hackish mechanism used to remove the file containing our library when the JVM shuts down */
88         private static class FileCleaner implements Runnable {
89                 private String target;
90                 public FileCleaner(String name) {
91                         target = name;
92                 }
93         public void run() {
94             try {
95                 new File(target).delete();
96             } catch(Exception e) {
97                 System.out.println("Unable to clean temporary file "+target+" during shutdown.");
98                 e.printStackTrace();
99             }
100         }    
101         }
102
103     /** Retrieve the simulation time
104      * @return
105      */
106         public final static native double getClock();
107         /**
108          * Issue a debug logging message.
109          * @param s message to log.
110          */
111         public final static native void debug(String s);
112         /**
113          * Issue an verbose logging message.
114          * @param s message to log.
115          */
116         public final static native void verb(String s);
117
118         /** Issue an information logging message
119      * @param s
120      */
121         public final static native void info(String s);
122         /**
123          * Issue an warning logging message.
124          * @param s message to log.
125          */
126         public final static native void warn(String s);
127         /**
128          * Issue an error logging message.
129          * @param s message to log.
130          */
131         public final static native void error(String s);
132         /**
133          * Issue an critical logging message.
134          * @param s message to log.
135          */
136         public final static native void critical(String s);
137
138         /*********************************************************************************
139          * Deployment and initialization related functions                               *
140          *********************************************************************************/
141
142         /**
143          * The natively implemented method to initialize a MSG simulation.
144          *
145          * @param args            The arguments of the command line of the simulation.
146          *
147          * @see                    Msg.init()
148          */
149         public final static native void init(String[]args);
150
151         /**
152          * Run the MSG simulation.
153          *
154          * The simulation is not cleaned afterward (see  
155          * {@link #clean()} if you really insist on cleaning the C side), so you can freely 
156          * retrieve the informations that you want from the simulation. In particular, retrieving the status 
157          * of a process or the current date is perfectly ok. 
158          *
159          * @see                    MSG_run
160          */
161         public final static native void run() ;
162         
163         /** This function is useless nowadays, just stop calling it. */
164         @Deprecated
165         public final static void clean(){}
166
167         /**
168          * The native implemented method to create the environment of the simulation.
169          *
170          * @param platformFile    The XML file which contains the description of the environment of the simulation
171          *
172          */
173         public final static native void createEnvironment(String platformFile);
174
175         /**
176          * The method to deploy the simulation.
177          *
178      *
179      * @param deploymentFile
180      */
181         public final static native void deployApplication(String deploymentFile);
182
183     /** Example launcher. You can use it or provide your own launcher, as you wish
184      * @param args
185      * @throws MsgException
186      */
187         static public void main(String[]args) throws MsgException {
188                 /* initialize the MSG simulation. Must be done before anything else (even logging). */
189                 Msg.init(args);
190
191                 if (args.length < 2) {
192                         Msg.info("Usage: Msg platform_file deployment_file");
193                         System.exit(1);
194                 }
195
196                 /* Load the platform and deploy the application */
197                 Msg.createEnvironment(args[0]);
198                 Msg.deployApplication(args[1]);
199                 /* Execute the simulation */
200                 Msg.run();
201         }
202 }