Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines.
[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_storage.h"
28 #include "jmsg_task.h"
29 #include "jxbt_utilities.hpp"
30
31 #include "JavaContext.hpp"
32
33 /* Shut up some errors in eclipse online compiler. I wish such a pimple wouldn't be needed */
34 #ifndef JNIEXPORT
35 #define JNIEXPORT
36 #endif
37 #ifndef JNICALL
38 #define JNICALL
39 #endif
40 /* end of eclipse-mandated pimple */
41
42 int JAVA_HOST_LEVEL = -1;
43
44 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(java);
45
46 JavaVM *__java_vm = nullptr;
47
48 JNIEnv *get_current_thread_env()
49 {
50   using simgrid::kernel::context::JavaContext;
51   const JavaContext* ctx = static_cast<JavaContext*>(simgrid::kernel::context::Context::self());
52   if (ctx)
53     return ctx->jenv_;
54   else
55     return nullptr;
56 }
57
58 void jmsg_throw_status(JNIEnv *env, msg_error_t status) {
59   switch (status) {
60     case MSG_TIMEOUT:
61       jxbt_throw_time_out_failure(env, "");
62       break;
63     case MSG_TRANSFER_FAILURE:
64       jxbt_throw_transfer_failure(env, "");
65       break;
66     case MSG_HOST_FAILURE:
67       jxbt_throw_host_failure(env, "");
68       break;
69     case MSG_TASK_CANCELED:
70       jxbt_throw_task_cancelled(env, "");
71       break;
72     default:
73       xbt_die("undefined message failed (please see jmsg_throw_status function in jmsg.cpp)");
74   }
75 }
76
77 /***************************************************************************************
78  * Unsortable functions                                                        *
79  ***************************************************************************************/
80
81 JNIEXPORT jdouble JNICALL Java_org_simgrid_msg_Msg_getClock(JNIEnv*, jclass)
82 {
83   return (jdouble)simgrid_get_clock();
84 }
85
86 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_init(JNIEnv* env, jclass, jobjectArray jargs)
87 {
88   env->GetJavaVM(&__java_vm);
89
90   simgrid::kernel::context::factory_initializer = &simgrid::kernel::context::java_factory;
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     const char* tmp = env->GetStringUTFChars(jval, nullptr);
111     args.emplace_back(tmp);
112     env->ReleaseStringUTFChars(jval, tmp);
113   }
114
115   std::unique_ptr<char* []> argv(new char*[argc + 1]);
116   std::transform(begin(args), end(args), argv.get(), [](std::string& s) { return &s.front(); });
117   argv[argc] = nullptr;
118
119   int argc2 = argc;
120   MSG_init(&argc2, argv.get());
121   xbt_assert(argc2 <= argc);
122
123   for (int index = 1; index < argc2; index++)
124     env->SetObjectArrayElement(jargs, index - 1, (jstring)env->NewStringUTF(argv[index]));
125
126   sg_vm_live_migration_plugin_init();
127   JAVA_HOST_LEVEL = simgrid::s4u::Host::extension_create(nullptr);
128 }
129
130 JNIEXPORT void JNICALL JNICALL Java_org_simgrid_msg_Msg_run(JNIEnv* env, jclass)
131 {
132   /* Run everything */
133   XBT_DEBUG("Ready to run");
134   simgrid_run();
135   XBT_DEBUG("Done running");
136   XBT_INFO("Terminating the simulation...");
137   /* Cleanup java hosts */
138   sg_host_t* hosts  = sg_host_list();
139   size_t host_count = sg_host_count();
140   for (size_t index = 0; index < host_count - 1; index++) {
141     auto jhost = (jobject)hosts[index]->extension(JAVA_HOST_LEVEL);
142     if (jhost)
143       jhost_unref(env, jhost);
144   }
145   xbt_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, jstring jplatformFile)
159 {
160   const char* platformFile = env->GetStringUTFChars(jplatformFile, nullptr);
161
162   simgrid_load_platform(platformFile);
163
164   env->ReleaseStringUTFChars(jplatformFile, platformFile);
165 }
166
167 JNIEXPORT jobject JNICALL Java_org_simgrid_msg_Msg_environmentGetRoutingRoot(JNIEnv* env, jclass)
168 {
169   sg_netzone_t as  = sg_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, jstring js)
186 {
187   const char* s = env->GetStringUTFChars(js, nullptr);
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, jstring js)
193 {
194   const char* s = env->GetStringUTFChars(js, nullptr);
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, jstring js)
200 {
201   const char* s = env->GetStringUTFChars(js, nullptr);
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, jstring js)
207 {
208   const char* s = env->GetStringUTFChars(js, nullptr);
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, jstring js)
214 {
215   const char* s = env->GetStringUTFChars(js, nullptr);
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, jstring js)
221 {
222   const char* s = env->GetStringUTFChars(js, nullptr);
223   XBT_CRITICAL("%s", s);
224   env->ReleaseStringUTFChars(js, s);
225 }
226
227 static void java_main(int argc, char* argv[]);
228
229 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_deployApplication(JNIEnv* env, jclass, jstring jdeploymentFile)
230 {
231   const char* deploymentFile = env->GetStringUTFChars(jdeploymentFile, nullptr);
232
233   simgrid_register_default(java_main);
234   simgrid_load_deployment(deploymentFile);
235 }
236
237 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_energyInit() {
238   sg_host_energy_plugin_init();
239 }
240
241 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_fileSystemInit()
242 {
243   sg_storage_file_system_init();
244 }
245
246 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_loadInit() {
247     sg_host_load_plugin_init();
248 }
249 /** Run a Java org.simgrid.msg.Process
250  *
251  *  If needed, this waits for the process starting time.
252  *  Then it calls the Process.run() method.
253  */
254 static void run_jprocess(JNIEnv *env, jobject jprocess)
255 {
256   // wait for the process's start time
257   jfieldID jprocess_field_Process_startTime = jxbt_get_sfield(env, "org/simgrid/msg/Process", "startTime", "D");
258   jdouble startTime = env->GetDoubleField(jprocess, jprocess_field_Process_startTime);
259   if (startTime > simgrid_get_clock())
260     simgrid::s4u::this_actor::sleep_for(startTime - simgrid_get_clock());
261
262   //Execution of the "run" method.
263   jmethodID id = jxbt_get_smethod(env, "org/simgrid/msg/Process", "run", "()V");
264   xbt_assert((id != nullptr), "Method Process.run() not found...");
265
266   env->CallVoidMethod(jprocess, id);
267   if (env->ExceptionOccurred()) {
268     XBT_DEBUG("Something went wrong in this Java actor, forget about it.");
269     env->ExceptionClear();
270     XBT_ATTRIB_UNUSED jint error = __java_vm->DetachCurrentThread();
271     xbt_assert(error == JNI_OK, "Cannot detach failing thread");
272     simgrid::ForcefulKillException::do_throw();
273   }
274 }
275
276 /** Create a Java org.simgrid.msg.Process with the arguments and run it */
277 static void java_main(int argc, char* argv[])
278 {
279   JNIEnv *env = get_current_thread_env();
280   auto* context = static_cast<simgrid::kernel::context::JavaContext*>(simgrid::kernel::context::Context::self());
281
282   //Change the "." in class name for "/".
283   std::string arg0 = argv[0];
284   std::replace(begin(arg0), end(arg0), '.', '/');
285   jclass class_Process = env->FindClass(arg0.c_str());
286   //Retrieve the methodID for the constructor
287   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]);
288   jmethodID constructor_Process = env->GetMethodID(class_Process, "<init>", "(Lorg/simgrid/msg/Host;Ljava/lang/String;[Ljava/lang/String;)V");
289   xbt_assert((constructor_Process != nullptr), "Constructor not found for class %s. Is there a (Host, String ,String[]) constructor in your class ?", argv[0]);
290
291   //Retrieve the name of the process.
292   jstring jname = env->NewStringUTF(argv[0]);
293   //Build the arguments
294   auto args = static_cast<jobjectArray>(
295       env->NewObjectArray(argc - 1, env->FindClass("java/lang/String"), env->NewStringUTF("")));
296   for (int i = 1; i < argc; i++)
297       env->SetObjectArrayElement(args,i - 1, env->NewStringUTF(argv[i]));
298   //Retrieve the host for the process.
299   jstring jhostName = env->NewStringUTF(simgrid::s4u::Host::current()->get_cname());
300   jobject jhost = Java_org_simgrid_msg_Host_getByName(env, nullptr, jhostName);
301   //creates the process
302   jobject jprocess = env->NewObject(class_Process, constructor_Process, jhost, jname, args);
303   xbt_assert((jprocess != nullptr), "Process allocation failed.");
304   jprocess = env->NewGlobalRef(jprocess);
305   //bind the process to the context
306   const_sg_actor_t actor = sg_actor_self();
307
308   context->jprocess_ = jprocess;
309   /* sets the PID and the PPID of the process */
310   env->SetIntField(jprocess, jprocess_field_Process_pid, static_cast<jint>(actor->get_pid()));
311   env->SetIntField(jprocess, jprocess_field_Process_ppid, static_cast<jint>(actor->get_ppid()));
312   jprocess_bind(jprocess, actor, env);
313
314   run_jprocess(env, context->jprocess_);
315 }
316
317 namespace simgrid {
318 namespace kernel {
319 namespace context {
320
321 /** Run the Java org.simgrid.msg.Process */
322 void java_main_jprocess(jobject jprocess)
323 {
324   JNIEnv *env = get_current_thread_env();
325   auto* context        = static_cast<JavaContext*>(Context::self());
326   context->jprocess_   = jprocess;
327   jprocess_bind(context->jprocess_, sg_actor_self(), env);
328
329   run_jprocess(env, context->jprocess_);
330 }
331 } // namespace context
332 } // namespace kernel
333 } // namespace simgrid