Logo AND Algorithmique Numérique Distribuée

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