Logo AND Algorithmique Numérique Distribuée

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