Logo AND Algorithmique Numérique Distribuée

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