Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Fix another bunch of warnings in doc generation.
[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/Host.hpp"
20
21 #include "src/simix/smx_private.hpp"
22
23 #include "jmsg.hpp"
24 #include "jmsg_as.hpp"
25 #include "jmsg_host.h"
26 #include "jmsg_process.h"
27 #include "jmsg_task.h"
28 #include "jxbt_utilities.hpp"
29
30 #include "JavaContext.hpp"
31
32 /* Shut up some errors in eclipse online compiler. I wish such a pimple wouldn't be needed */
33 #ifndef JNIEXPORT
34 #define JNIEXPORT
35 #endif
36 #ifndef JNICALL
37 #define JNICALL
38 #endif
39 /* end of eclipse-mandated pimple */
40
41 int JAVA_HOST_LEVEL = -1;
42
43 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(java);
44
45 JavaVM *__java_vm = nullptr;
46
47 JNIEnv *get_current_thread_env()
48 {
49   using simgrid::kernel::context::JavaContext;
50   const JavaContext* ctx = static_cast<JavaContext*>(simgrid::kernel::context::Context::self());
51   if (ctx)
52     return ctx->jenv_;
53   else
54     return nullptr;
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*, jclass)
81 {
82   return (jdouble)simgrid_get_clock();
83 }
84
85 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_init(JNIEnv* env, jclass, jobjectArray jargs)
86 {
87   env->GetJavaVM(&__java_vm);
88
89   simgrid::kernel::context::factory_initializer = &simgrid::kernel::context::java_factory;
90   const _jthrowable* exc                        = env->ExceptionOccurred();
91   if (exc) {
92     env->ExceptionClear();
93   }
94
95   setlocale(LC_NUMERIC,"C");
96
97   int argc = 1;
98   if (jargs)
99     argc += static_cast<int>(env->GetArrayLength(jargs));
100   xbt_assert(argc > 0);
101
102   // Need a static storage because the XBT layer saves the arguments in xbt::binary_name and xbt::cmdline.
103   static std::vector<std::string> args;
104   args.reserve(argc);
105
106   args.emplace_back("java");
107   for (int index = 1; index < argc; index++) {
108     auto jval       = (jstring)env->GetObjectArrayElement(jargs, index - 1);
109     const char* tmp = env->GetStringUTFChars(jval, nullptr);
110     args.emplace_back(tmp);
111     env->ReleaseStringUTFChars(jval, tmp);
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   const char* platformFile = env->GetStringUTFChars(jplatformFile, nullptr);
156
157   simgrid_load_platform(platformFile);
158
159   env->ReleaseStringUTFChars(jplatformFile, platformFile);
160 }
161
162 JNIEXPORT jobject JNICALL Java_org_simgrid_msg_Msg_environmentGetRoutingRoot(JNIEnv* env, jclass)
163 {
164   sg_netzone_t as  = sg_zone_get_root();
165   jobject jas      = jnetzone_new_instance(env);
166   if (not jas) {
167     jxbt_throw_jni(env, "java As instantiation failed");
168     return nullptr;
169   }
170   jas = jnetzone_ref(env, jas);
171   if (not jas) {
172     jxbt_throw_jni(env, "new global ref allocation failed");
173     return nullptr;
174   }
175   jnetzone_bind(jas, as, env);
176
177   return (jobject) jas;
178 }
179
180 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_debug(JNIEnv* env, jclass, jstring js)
181 {
182   const char* s = env->GetStringUTFChars(js, nullptr);
183   XBT_DEBUG("%s", s);
184   env->ReleaseStringUTFChars(js, s);
185 }
186
187 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_verb(JNIEnv* env, jclass, jstring js)
188 {
189   const char* s = env->GetStringUTFChars(js, nullptr);
190   XBT_VERB("%s", s);
191   env->ReleaseStringUTFChars(js, s);
192 }
193
194 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_info(JNIEnv* env, jclass, jstring js)
195 {
196   const char* s = env->GetStringUTFChars(js, nullptr);
197   XBT_INFO("%s", s);
198   env->ReleaseStringUTFChars(js, s);
199 }
200
201 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_warn(JNIEnv* env, jclass, jstring js)
202 {
203   const char* s = env->GetStringUTFChars(js, nullptr);
204   XBT_WARN("%s", s);
205   env->ReleaseStringUTFChars(js, s);
206 }
207
208 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_error(JNIEnv* env, jclass, jstring js)
209 {
210   const char* s = env->GetStringUTFChars(js, nullptr);
211   XBT_ERROR("%s", s);
212   env->ReleaseStringUTFChars(js, s);
213 }
214
215 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_critical(JNIEnv* env, jclass, jstring js)
216 {
217   const char* s = env->GetStringUTFChars(js, nullptr);
218   XBT_CRITICAL("%s", s);
219   env->ReleaseStringUTFChars(js, s);
220 }
221
222 static void java_main(int argc, char* argv[]);
223
224 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_deployApplication(JNIEnv* env, jclass, jstring jdeploymentFile)
225 {
226   const char* deploymentFile = env->GetStringUTFChars(jdeploymentFile, nullptr);
227
228   simgrid_register_default(java_main);
229   simgrid_load_deployment(deploymentFile);
230 }
231
232 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_energyInit() {
233   sg_host_energy_plugin_init();
234 }
235
236 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_loadInit() {
237     sg_host_load_plugin_init();
238 }
239 /** Run a Java org.simgrid.msg.Process
240  *
241  *  If needed, this waits for the process starting time.
242  *  Then it calls the Process.run() method.
243  */
244 static void run_jprocess(JNIEnv *env, jobject jprocess)
245 {
246   // wait for the process's start time
247   jfieldID jprocess_field_Process_startTime = jxbt_get_sfield(env, "org/simgrid/msg/Process", "startTime", "D");
248   jdouble startTime = env->GetDoubleField(jprocess, jprocess_field_Process_startTime);
249   if (startTime > simgrid_get_clock())
250     simgrid::s4u::this_actor::sleep_for(startTime - simgrid_get_clock());
251
252   //Execution of the "run" method.
253   jmethodID id = jxbt_get_smethod(env, "org/simgrid/msg/Process", "run", "()V");
254   xbt_assert((id != nullptr), "Method Process.run() not found...");
255
256   env->CallVoidMethod(jprocess, id);
257   if (env->ExceptionOccurred()) {
258     XBT_DEBUG("Something went wrong in this Java actor, forget about it.");
259     env->ExceptionClear();
260     xbt_assert(__java_vm->DetachCurrentThread() == JNI_OK, "Cannot detach failing thread");
261     simgrid::ForcefulKillException::do_throw();
262   }
263 }
264
265 /** Create a Java org.simgrid.msg.Process with the arguments and run it */
266 static void java_main(int argc, char* argv[])
267 {
268   JNIEnv *env = get_current_thread_env();
269   auto* context = static_cast<simgrid::kernel::context::JavaContext*>(simgrid::kernel::context::Context::self());
270
271   //Change the "." in class name for "/".
272   std::string arg0 = argv[0];
273   std::replace(begin(arg0), end(arg0), '.', '/');
274   jclass class_Process = env->FindClass(arg0.c_str());
275   //Retrieve the methodID for the constructor
276   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]);
277   jmethodID constructor_Process = env->GetMethodID(class_Process, "<init>", "(Lorg/simgrid/msg/Host;Ljava/lang/String;[Ljava/lang/String;)V");
278   xbt_assert((constructor_Process != nullptr), "Constructor not found for class %s. Is there a (Host, String ,String[]) constructor in your class ?", argv[0]);
279
280   //Retrieve the name of the process.
281   jstring jname = env->NewStringUTF(argv[0]);
282   //Build the arguments
283   auto args = static_cast<jobjectArray>(
284       env->NewObjectArray(argc - 1, env->FindClass("java/lang/String"), env->NewStringUTF("")));
285   for (int i = 1; i < argc; i++)
286       env->SetObjectArrayElement(args,i - 1, env->NewStringUTF(argv[i]));
287   //Retrieve the host for the process.
288   jstring jhostName = env->NewStringUTF(simgrid::s4u::Host::current()->get_cname());
289   jobject jhost = Java_org_simgrid_msg_Host_getByName(env, nullptr, jhostName);
290   //creates the process
291   jobject jprocess = env->NewObject(class_Process, constructor_Process, jhost, jname, args);
292   xbt_assert((jprocess != nullptr), "Process allocation failed.");
293   jprocess = env->NewGlobalRef(jprocess);
294   //bind the process to the context
295   const_sg_actor_t actor = sg_actor_self();
296
297   context->jprocess_ = jprocess;
298   /* sets the PID and the PPID of the process */
299   env->SetIntField(jprocess, jprocess_field_Process_pid, static_cast<jint>(actor->get_pid()));
300   env->SetIntField(jprocess, jprocess_field_Process_ppid, static_cast<jint>(actor->get_ppid()));
301   jprocess_bind(jprocess, actor, env);
302
303   run_jprocess(env, context->jprocess_);
304 }
305
306 namespace simgrid {
307 namespace kernel {
308 namespace context {
309
310 /** Run the Java org.simgrid.msg.Process */
311 void java_main_jprocess(jobject jprocess)
312 {
313   JNIEnv *env = get_current_thread_env();
314   auto* context        = static_cast<JavaContext*>(Context::self());
315   context->jprocess_   = jprocess;
316   jprocess_bind(context->jprocess_, sg_actor_self(), env);
317
318   run_jprocess(env, context->jprocess_);
319 }
320 } // namespace context
321 } // namespace kernel
322 } // namespace simgrid