Logo AND Algorithmique Numérique Distribuée

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