Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fix (#220) ?
[simgrid.git] / src / bindings / java / jmsg.cpp
1 /* Java Wrappers to the MSG API.                                            */
2
3 /* Copyright (c) 2007-2019. The SimGrid Team. All rights reserved.          */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 #include <algorithm>
9 #include <clocale>
10 #include <string>
11
12 #include "simgrid/Exception.hpp"
13 #include "simgrid/msg.h"
14 #include "simgrid/plugins/energy.h"
15 #include "simgrid/plugins/file_system.h"
16 #include "simgrid/plugins/live_migration.h"
17 #include "simgrid/plugins/load.h"
18 #include "simgrid/simix.h"
19
20 #include "simgrid/s4u/Host.hpp"
21
22 #include "src/simix/smx_private.hpp"
23
24 #include "jmsg.hpp"
25 #include "jmsg_as.hpp"
26 #include "jmsg_host.h"
27 #include "jmsg_process.h"
28 #include "jmsg_storage.h"
29 #include "jmsg_task.h"
30 #include "jxbt_utilities.hpp"
31
32 #include "JavaContext.hpp"
33
34
35 /* Shut up some errors in eclipse online compiler. I wish such a pimple wouldn't be needed */
36 #ifndef JNIEXPORT
37 #define JNIEXPORT
38 #endif
39 #ifndef JNICALL
40 #define JNICALL
41 #endif
42 /* end of eclipse-mandated pimple */
43
44 int JAVA_HOST_LEVEL = -1;
45
46 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(java);
47
48 JavaVM *__java_vm = nullptr;
49
50 JNIEnv *get_current_thread_env()
51 {
52   using simgrid::kernel::context::JavaContext;
53   JavaContext* ctx = static_cast<JavaContext*>(simgrid::kernel::context::Context::self());
54   if (ctx)
55     return ctx->jenv_;
56   else
57     return nullptr;
58 }
59
60 void jmsg_throw_status(JNIEnv *env, msg_error_t status) {
61   switch (status) {
62     case MSG_TIMEOUT:
63       jxbt_throw_time_out_failure(env, "");
64       break;
65     case MSG_TRANSFER_FAILURE:
66       jxbt_throw_transfer_failure(env, "");
67       break;
68     case MSG_HOST_FAILURE:
69       jxbt_throw_host_failure(env, "");
70       break;
71     case MSG_TASK_CANCELED:
72       jxbt_throw_task_cancelled(env, "");
73       break;
74     default:
75       xbt_die("undefined message failed (please see jmsg_throw_status function in jmsg.cpp)");
76   }
77 }
78
79 /***************************************************************************************
80  * Unsortable functions                                                        *
81  ***************************************************************************************/
82
83 JNIEXPORT jdouble JNICALL Java_org_simgrid_msg_Msg_getClock(JNIEnv * env, jclass cls)
84 {
85   return (jdouble) MSG_get_clock();
86 }
87
88 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_init(JNIEnv * env, jclass cls, jobjectArray jargs)
89 {
90   int argc = 0;
91
92   env->GetJavaVM(&__java_vm);
93
94   simgrid::kernel::context::factory_initializer = &simgrid::kernel::context::java_factory;
95   jthrowable exc = env->ExceptionOccurred();
96   if (exc) {
97     env->ExceptionClear();
98   }
99
100   setlocale(LC_NUMERIC,"C");
101
102   if (jargs)
103     argc = static_cast<int>(env->GetArrayLength(jargs));
104
105   argc++;
106   char** argv = new char*[argc + 1];
107   argv[0] = xbt_strdup("java");
108
109   for (int index = 0; index < argc - 1; index++) {
110     jstring jval    = (jstring)env->GetObjectArrayElement(jargs, index);
111     const char* tmp = env->GetStringUTFChars(jval, 0);
112     argv[index + 1] = xbt_strdup(tmp);
113     env->ReleaseStringUTFChars(jval, tmp);
114   }
115   argv[argc] = nullptr;
116
117   MSG_init(&argc, argv);
118   sg_vm_live_migration_plugin_init();
119
120   JAVA_HOST_LEVEL = simgrid::s4u::Host::extension_create(nullptr);
121
122   for (int index = 0; index < argc - 1; index++) {
123     env->SetObjectArrayElement(jargs, index, (jstring)env->NewStringUTF(argv[index + 1]));
124     free(argv[index]);
125   }
126   free(argv[argc]);
127   delete[] argv;
128 }
129
130 JNIEXPORT void JNICALL JNICALL Java_org_simgrid_msg_Msg_run(JNIEnv * env, jclass cls)
131 {
132   /* Run everything */
133   XBT_DEBUG("Ready to run MSG_MAIN");
134   msg_error_t rv = MSG_main();
135   XBT_DEBUG("Done running MSG_MAIN");
136   jxbt_check_res("MSG_main()", rv, MSG_OK,
137                  xbt_strdup("unexpected error : MSG_main() failed .. please report this bug "));
138
139   XBT_INFO("MSG_main finished; Terminating the simulation...");
140   /* Cleanup java hosts */
141   xbt_dynar_t hosts = MSG_hosts_as_dynar();
142   for (unsigned long index = 0; index < xbt_dynar_length(hosts) - 1; index++) {
143     msg_host_t msg_host = xbt_dynar_get_as(hosts,index,msg_host_t);
144     jobject jhost = (jobject) msg_host->extension(JAVA_HOST_LEVEL);
145     if (jhost)
146       jhost_unref(env, jhost);
147   }
148   xbt_dynar_free(&hosts);
149
150   /* Cleanup java storages */
151   for (auto const& elm : java_storage_map)
152     jstorage_unref(env, elm.second);
153
154   /* Display the status of remaining threads. None should survive, but who knows */
155   jclass clsProcess = jxbt_get_class(env, "org/simgrid/msg/Process");
156   jmethodID idDebug = jxbt_get_static_jmethod(env, clsProcess, "debugAllThreads", "()V");
157   xbt_assert(idDebug != nullptr, "Method Process.debugAllThreads() not found...");
158   env->CallStaticVoidMethod(clsProcess, idDebug);
159 }
160
161 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_createEnvironment(JNIEnv * env, jclass cls, jstring jplatformFile)
162 {
163   const char *platformFile = env->GetStringUTFChars(jplatformFile, 0);
164
165   MSG_create_environment(platformFile);
166
167   env->ReleaseStringUTFChars(jplatformFile, platformFile);
168 }
169
170 JNIEXPORT jobject JNICALL Java_org_simgrid_msg_Msg_environmentGetRoutingRoot(JNIEnv * env, jclass cls)
171 {
172   msg_netzone_t as = MSG_zone_get_root();
173   jobject jas      = jnetzone_new_instance(env);
174   if (not jas) {
175     jxbt_throw_jni(env, "java As instantiation failed");
176     return nullptr;
177   }
178   jas = jnetzone_ref(env, jas);
179   if (not jas) {
180     jxbt_throw_jni(env, "new global ref allocation failed");
181     return nullptr;
182   }
183   jnetzone_bind(jas, as, env);
184
185   return (jobject) jas;
186 }
187
188 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_debug(JNIEnv * env, jclass cls, jstring js)
189 {
190   const char *s = env->GetStringUTFChars(js, 0);
191   XBT_DEBUG("%s", s);
192   env->ReleaseStringUTFChars(js, s);
193 }
194
195 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_verb(JNIEnv * env, jclass cls, jstring js)
196 {
197   const char *s = env->GetStringUTFChars(js, 0);
198   XBT_VERB("%s", s);
199   env->ReleaseStringUTFChars(js, s);
200 }
201
202 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_info(JNIEnv * env, jclass cls, jstring js)
203 {
204   const char *s = env->GetStringUTFChars(js, 0);
205   XBT_INFO("%s", s);
206   env->ReleaseStringUTFChars(js, s);
207 }
208
209 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_warn(JNIEnv * env, jclass cls, jstring js)
210 {
211   const char *s = env->GetStringUTFChars(js, 0);
212   XBT_WARN("%s", s);
213   env->ReleaseStringUTFChars(js, s);
214 }
215
216 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_error(JNIEnv * env, jclass cls, jstring js)
217 {
218   const char *s = env->GetStringUTFChars(js, 0);
219   XBT_ERROR("%s", s);
220   env->ReleaseStringUTFChars(js, s);
221 }
222
223 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_critical(JNIEnv * env, jclass cls, jstring js)
224 {
225   const char *s = env->GetStringUTFChars(js, 0);
226   XBT_CRITICAL("%s", s);
227   env->ReleaseStringUTFChars(js, s);
228 }
229
230 static int java_main(int argc, char *argv[]);
231
232 JNIEXPORT void JNICALL
233 Java_org_simgrid_msg_Msg_deployApplication(JNIEnv * env, jclass cls, jstring jdeploymentFile)
234 {
235   const char *deploymentFile = env->GetStringUTFChars(jdeploymentFile, 0);
236
237   SIMIX_function_register_default(java_main);
238   MSG_launch_application(deploymentFile);
239 }
240
241 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_energyInit() {
242   sg_host_energy_plugin_init();
243 }
244
245 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_fileSystemInit()
246 {
247   sg_storage_file_system_init();
248 }
249
250 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_loadInit() {
251     sg_host_load_plugin_init();
252 }
253 /** Run a Java org.simgrid.msg.Process
254  *
255  *  If needed, this waits for the process starting time.
256  *  Then it calls the Process.run() method.
257  */
258 static void run_jprocess(JNIEnv *env, jobject jprocess)
259 {
260   // wait for the process's start time
261   jfieldID jprocess_field_Process_startTime = jxbt_get_sfield(env, "org/simgrid/msg/Process", "startTime", "D");
262   jdouble startTime = env->GetDoubleField(jprocess, jprocess_field_Process_startTime);
263   if (startTime > MSG_get_clock())
264     MSG_process_sleep(startTime - MSG_get_clock());
265
266   //Execution of the "run" method.
267   jmethodID id = jxbt_get_smethod(env, "org/simgrid/msg/Process", "run", "()V");
268   xbt_assert((id != nullptr), "Method Process.run() not found...");
269
270   env->CallVoidMethod(jprocess, id);
271   if (env->ExceptionOccurred()) {
272     XBT_DEBUG("Something went wrong in this Java actor, forget about it.");
273     env->ExceptionClear();
274     XBT_ATTRIB_UNUSED jint error = __java_vm->DetachCurrentThread();
275     xbt_assert(error == JNI_OK, "Cannot detach failing thread");
276     simgrid::kernel::context::StopRequest::do_throw();
277   }
278 }
279
280 /** Create a Java org.simgrid.msg.Process with the arguments and run it */
281 static int java_main(int argc, char *argv[])
282 {
283   JNIEnv *env = get_current_thread_env();
284   simgrid::kernel::context::JavaContext* context =
285       static_cast<simgrid::kernel::context::JavaContext*>(simgrid::kernel::context::Context::self());
286
287   //Change the "." in class name for "/".
288   std::string arg0 = argv[0];
289   std::replace(begin(arg0), end(arg0), '.', '/');
290   jclass class_Process = env->FindClass(arg0.c_str());
291   //Retrieve the methodID for the constructor
292   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]);
293   jmethodID constructor_Process = env->GetMethodID(class_Process, "<init>", "(Lorg/simgrid/msg/Host;Ljava/lang/String;[Ljava/lang/String;)V");
294   xbt_assert((constructor_Process != nullptr), "Constructor not found for class %s. Is there a (Host, String ,String[]) constructor in your class ?", argv[0]);
295
296   //Retrieve the name of the process.
297   jstring jname = env->NewStringUTF(argv[0]);
298   //Build the arguments
299   jobjectArray args = static_cast<jobjectArray>(env->NewObjectArray(argc - 1, env->FindClass("java/lang/String"),
300                                                                     env->NewStringUTF("")));
301   for (int i = 1; i < argc; i++)
302       env->SetObjectArrayElement(args,i - 1, env->NewStringUTF(argv[i]));
303   //Retrieve the host for the process.
304   jstring jhostName = env->NewStringUTF(MSG_host_self()->get_cname());
305   jobject jhost = Java_org_simgrid_msg_Host_getByName(env, nullptr, jhostName);
306   //creates the process
307   jobject jprocess = env->NewObject(class_Process, constructor_Process, jhost, jname, args);
308   xbt_assert((jprocess != nullptr), "Process allocation failed.");
309   jprocess = env->NewGlobalRef(jprocess);
310   //bind the process to the context
311   msg_process_t process = MSG_process_self();
312
313   context->jprocess_ = jprocess;
314   /* sets the PID and the PPID of the process */
315   env->SetIntField(jprocess, jprocess_field_Process_pid, static_cast<jint>(MSG_process_get_PID(process)));
316   env->SetIntField(jprocess, jprocess_field_Process_ppid, static_cast<jint>(MSG_process_get_PPID(process)));
317   jprocess_bind(jprocess, process, env);
318
319   run_jprocess(env, context->jprocess_);
320   return 0;
321 }
322
323 namespace simgrid {
324 namespace kernel {
325 namespace context {
326
327 /** Run the Java org.simgrid.msg.Process */
328 void java_main_jprocess(jobject jprocess)
329 {
330   JNIEnv *env = get_current_thread_env();
331   simgrid::kernel::context::JavaContext* context =
332       static_cast<simgrid::kernel::context::JavaContext*>(simgrid::kernel::context::Context::self());
333   context->jprocess_                             = jprocess;
334   jprocess_bind(context->jprocess_, MSG_process_self(), env);
335
336   run_jprocess(env, context->jprocess_);
337 }
338 }}}