Logo AND Algorithmique Numérique Distribuée

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