Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
50639d9ea818524c2f9bab327f86e5592df3ad34
[simgrid.git] / src / bindings / java / jmsg.cpp
1 /* Java Wrappers to the MSG API.                                            */
2
3 /* Copyright (c) 2007-2015. 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 #include <simgrid/msg.h>
10 #include <simgrid/simix.h>
11 #include <surf/surfxml_parse.h>
12 #include <locale.h>
13 #include <src/simix/smx_private.h>
14
15 #include "jmsg_process.h"
16
17 #include "jmsg_as.h"
18
19 #include "jmsg_host.h"
20 #include "jmsg_storage.h"
21 #include "jmsg_task.h"
22 #include "jxbt_utilities.h"
23
24 #include "jmsg.h"
25
26 #include "JavaContext.hpp"
27
28 /* Shut up some errors in eclipse online compiler. I wish such a pimple wouldn't be needed */
29 #ifndef JNIEXPORT
30 #define JNIEXPORT
31 #endif
32 #ifndef JNICALL
33 #define JNICALL
34 #endif
35 /* end of eclipse-mandated pimple */
36
37 SG_BEGIN_DECL()
38
39 int JAVA_HOST_LEVEL;
40 int JAVA_STORAGE_LEVEL;
41
42 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(jmsg);
43
44 JavaVM *__java_vm = NULL;
45
46 JavaVM *get_java_VM(void)
47 {
48   return __java_vm;
49 }
50
51 JNIEnv *get_current_thread_env(void)
52 {
53   JNIEnv *env;
54
55   __java_vm->AttachCurrentThread((void **) &env, NULL);
56   return env;
57 }
58
59 void jmsg_throw_status(JNIEnv *env, msg_error_t status) {
60   switch (status) {
61     case MSG_TIMEOUT:
62         jxbt_throw_time_out_failure(env,NULL);
63     break;
64     case MSG_TRANSFER_FAILURE:
65         jxbt_throw_transfer_failure(env,NULL);
66     break;
67     case MSG_HOST_FAILURE:
68         jxbt_throw_host_failure(env,NULL);
69     break;
70     case MSG_TASK_CANCELED:
71         jxbt_throw_task_cancelled(env,NULL);
72     break;
73     default:
74         jxbt_throw_native(env,xbt_strdup("undefined message failed (please see jmsg_throw_status function in jmsg.c)"));
75   }
76 }
77
78
79 /***************************************************************************************
80  * Unsortable functions                                                        *
81  ***************************************************************************************/
82
83 JNIEXPORT jdouble JNICALL
84 Java_org_simgrid_msg_Msg_getClock(JNIEnv * env, jclass cls)
85 {
86   return (jdouble) MSG_get_clock();
87 }
88
89 static void __JAVA_host_priv_free(void *host)
90 {
91 }
92
93 static void __JAVA_storage_priv_free(void *storage)
94 {
95 }
96
97 JNIEXPORT void JNICALL
98 Java_org_simgrid_msg_Msg_init(JNIEnv * env, jclass cls, jobjectArray jargs)
99 {
100   char **argv = NULL;
101   int index;
102   int argc = 0;
103   jstring jval;
104   const char *tmp;
105
106   XBT_LOG_CONNECT(jmsg);
107   XBT_LOG_CONNECT(jtrace);
108
109   env->GetJavaVM(&__java_vm);
110
111   simgrid::simix::factory_initializer = simgrid::java::java_factory;
112   jthrowable exc = env->ExceptionOccurred();
113   if (exc) {
114     env->ExceptionClear();
115   }
116
117   setlocale(LC_NUMERIC,"C");
118
119   if (jargs)
120     argc = (int) env->GetArrayLength(jargs);
121
122   argc++;
123   argv = xbt_new(char *, argc + 1);
124   argv[0] = xbt_strdup("java");
125
126   for (index = 0; index < argc - 1; index++) {
127     jval = (jstring) env->GetObjectArrayElement(jargs, index);
128     tmp = env->GetStringUTFChars(jval, 0);
129     argv[index + 1] = xbt_strdup(tmp);
130     env->ReleaseStringUTFChars(jval, tmp);
131   }
132   argv[argc] = NULL;
133
134   MSG_init(&argc, argv);
135
136   JAVA_HOST_LEVEL = xbt_lib_add_level(host_lib, (void_f_pvoid_t) __JAVA_host_priv_free);
137   JAVA_STORAGE_LEVEL = xbt_lib_add_level(storage_lib, (void_f_pvoid_t) __JAVA_storage_priv_free);
138
139   for (index = 0; index < argc; index++)
140     free(argv[index]);
141
142   free(argv);
143 }
144
145 JNIEXPORT void JNICALL
146     JNICALL Java_org_simgrid_msg_Msg_run(JNIEnv * env, jclass cls)
147 {
148   /* Run everything */
149   XBT_DEBUG("Ready to run MSG_MAIN");
150   msg_error_t rv = MSG_main();
151   XBT_DEBUG("Done running MSG_MAIN");
152   jxbt_check_res("MSG_main()", rv, MSG_OK,
153                  xbt_strdup("unexpected error : MSG_main() failed .. please report this bug "));
154
155   XBT_INFO("MSG_main finished; Cleaning up the simulation...");
156   /* Cleanup java hosts */
157   xbt_dynar_t hosts = MSG_hosts_as_dynar();
158   for (unsigned long index = 0; index < xbt_dynar_length(hosts) - 1; index++) {
159     jobject jhost = (jobject) xbt_lib_get_level(xbt_dynar_get_as(hosts,index,msg_host_t), JAVA_HOST_LEVEL);
160     if (jhost)
161       jhost_unref(env, jhost);
162
163   }
164   xbt_dynar_free(&hosts);
165
166   /* Cleanup java storages */
167   xbt_dynar_t storages = MSG_storages_as_dynar();
168   if(!xbt_dynar_is_empty(storages)){
169     for (unsigned long index = 0; index < xbt_dynar_length(storages) - 1; index++) {
170       jobject jstorage = (jobject) xbt_lib_get_level(xbt_dynar_get_as(storages,index,msg_storage_t), JAVA_STORAGE_LEVEL);
171       if (jstorage)
172         jstorage_unref(env, jstorage);
173     }
174   }
175   xbt_dynar_free(&storages);
176
177 }
178
179 JNIEXPORT void JNICALL
180 Java_org_simgrid_msg_Msg_createEnvironment(JNIEnv * env, jclass cls,
181                                        jstring jplatformFile)
182 {
183
184   const char *platformFile =
185       env->GetStringUTFChars(jplatformFile, 0);
186
187   MSG_create_environment(platformFile);
188
189   env->ReleaseStringUTFChars(jplatformFile, platformFile);
190 }
191
192 JNIEXPORT jobject JNICALL
193 Java_org_simgrid_msg_Msg_environmentGetRoutingRoot(JNIEnv * env, jclass cls)
194 {
195   msg_as_t as = MSG_environment_get_routing_root();
196   jobject jas = jas_new_instance(env);
197   if (!jas) {
198     jxbt_throw_jni(env, "java As instantiation failed");
199     return NULL;
200   }
201   jas = jas_ref(env, jas);
202   if (!jas) {
203     jxbt_throw_jni(env, "new global ref allocation failed");
204     return NULL;
205   }
206   jas_bind(jas, as, env);
207
208   return (jobject) jas;
209 }
210
211 JNIEXPORT void JNICALL
212 Java_org_simgrid_msg_Msg_debug(JNIEnv * env, jclass cls, jstring js)
213 {
214   const char *s = env->GetStringUTFChars(js, 0);
215   XBT_DEBUG("%s", s);
216   env->ReleaseStringUTFChars(js, s);
217 }
218 JNIEXPORT void JNICALL
219 Java_org_simgrid_msg_Msg_verb(JNIEnv * env, jclass cls, jstring js)
220 {
221   const char *s = env->GetStringUTFChars(js, 0);
222   XBT_VERB("%s", s);
223   env->ReleaseStringUTFChars(js, s);
224 }
225 JNIEXPORT void JNICALL
226 Java_org_simgrid_msg_Msg_info(JNIEnv * env, jclass cls, jstring js)
227 {
228   const char *s = env->GetStringUTFChars(js, 0);
229   XBT_INFO("%s", s);
230   env->ReleaseStringUTFChars(js, s);
231 }
232 JNIEXPORT void JNICALL
233 Java_org_simgrid_msg_Msg_warn(JNIEnv * env, jclass cls, jstring js)
234 {
235   const char *s = env->GetStringUTFChars(js, 0);
236   XBT_WARN("%s", s);
237   env->ReleaseStringUTFChars(js, s);
238 }
239 JNIEXPORT void JNICALL
240 Java_org_simgrid_msg_Msg_error(JNIEnv * env, jclass cls, jstring js)
241 {
242   const char *s = env->GetStringUTFChars(js, 0);
243   XBT_ERROR("%s", s);
244   env->ReleaseStringUTFChars(js, s);
245 }
246 JNIEXPORT void JNICALL
247 Java_org_simgrid_msg_Msg_critical(JNIEnv * env, jclass cls, jstring js)
248 {
249   const char *s = env->GetStringUTFChars(js, 0);
250   XBT_CRITICAL("%s", s);
251   env->ReleaseStringUTFChars(js, s);
252 }
253
254 static int java_main(int argc, char *argv[]);
255
256 JNIEXPORT void JNICALL
257 Java_org_simgrid_msg_Msg_deployApplication(JNIEnv * env, jclass cls,
258                                        jstring jdeploymentFile)
259 {
260
261   const char *deploymentFile =
262       env->GetStringUTFChars(jdeploymentFile, 0);
263
264   SIMIX_function_register_default(java_main);
265   MSG_launch_application(deploymentFile);
266 }
267
268 SG_END_DECL()
269
270 /** Run a Java org.simgrid.msg.Process
271  *
272  *  If needed, this waits for the process starting time.
273  *  Then it calls the Process.run() method.
274  */
275 static void run_jprocess(JNIEnv *env, jobject jprocess)
276 {
277   xbt_assert(jprocess != nullptr, "Process not created...");
278   //wait for the process to be able to begin
279   //TODO: Cache it
280   jfieldID jprocess_field_Process_startTime = jxbt_get_sfield(env, "org/simgrid/msg/Process", "startTime", "D");
281   jdouble startTime = env->GetDoubleField(jprocess, jprocess_field_Process_startTime);
282   if (startTime > MSG_get_clock())
283     MSG_process_sleep(startTime - MSG_get_clock());
284   //Execution of the "run" method.
285   jmethodID id = jxbt_get_smethod(env, "org/simgrid/msg/Process", "run", "()V");
286   xbt_assert( (id != nullptr), "Method not found...");
287   env->CallVoidMethod(jprocess, id);
288 }
289
290 /** Create a Java org.simgrid.msg.Process with the arguments and run it */
291 static int java_main(int argc, char *argv[])
292 {
293   JNIEnv *env = get_current_thread_env();
294   simgrid::java::JavaContext* context =
295     (simgrid::java::JavaContext*) SIMIX_context_self();
296
297   //Change the "." in class name for "/".
298   xbt_str_subst(argv[0],'.','/',0);
299   jclass class_Process = env->FindClass(argv[0]);
300   xbt_str_subst(argv[0],'/','.',0);
301   //Retrieve the methodID for the constructor
302   xbt_assert((class_Process != NULL), "Class not found (%s). The deployment file must use the fully qualified class name, including the package. The case is important.", argv[0]);
303   jmethodID constructor_Process = env->GetMethodID(class_Process, "<init>", "(Lorg/simgrid/msg/Host;Ljava/lang/String;[Ljava/lang/String;)V");
304   xbt_assert((constructor_Process != NULL), "Constructor not found for class %s. Is there a (Host, String ,String[]) constructor in your class ?", argv[0]);
305
306   //Retrieve the name of the process.
307   jstring jname = env->NewStringUTF(argv[0]);
308   //Build the arguments
309   jobjectArray args = (jobjectArray)env->NewObjectArray(argc - 1,
310     env->FindClass("java/lang/String"),
311     env->NewStringUTF(""));
312   int i;
313   for (i = 1; i < argc; i++)
314       env->SetObjectArrayElement(args,i - 1,
315         env->NewStringUTF(argv[i]));
316   //Retrieve the host for the process.
317   jstring jhostName = env->NewStringUTF(MSG_host_get_name(MSG_host_self()));
318   jobject jhost = Java_org_simgrid_msg_Host_getByName(env, NULL, jhostName);
319   //creates the process
320   jobject jprocess = env->NewObject(class_Process, constructor_Process, jhost, jname, args);
321   xbt_assert((jprocess != NULL), "Process allocation failed.");
322   jprocess = env->NewGlobalRef(jprocess);
323   //bind the process to the context
324   msg_process_t process = MSG_process_self();
325
326   context->jprocess = jprocess;
327   /* sets the PID and the PPID of the process */
328   env->SetIntField(jprocess, jprocess_field_Process_pid,(jint) MSG_process_get_PID(process));
329   env->SetIntField(jprocess, jprocess_field_Process_ppid, (jint) MSG_process_get_PPID(process));
330   jprocess_bind(jprocess, process, env);
331
332   run_jprocess(env, context->jprocess);
333   return 0;
334 }
335
336 namespace simgrid {
337 namespace java {
338
339 /** Run the Java org.simgrid.msg.Process */
340 void java_main_jprocess(jobject jprocess)
341 {
342   JNIEnv *env = get_current_thread_env();
343   simgrid::java::JavaContext* context =
344     (simgrid::java::JavaContext*) SIMIX_context_self();
345   context->jprocess = jprocess;
346   smx_process_t process = SIMIX_process_self();
347   jprocess_bind(context->jprocess, process, env);
348
349   // Adrien, ugly path, just to bypass creation of context at low levels
350   // (i.e such as for the VM migration for instance)
351   if (context->jprocess == nullptr)
352     return;
353   else
354     run_jprocess(env, context->jprocess);
355 }
356
357 }
358 }
359