Logo AND Algorithmique Numérique Distribuée

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