Logo AND Algorithmique Numérique Distribuée

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