Logo AND Algorithmique Numérique Distribuée

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