Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
less calls to simix.h + cosmetics
[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
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::factory_initializer = &simgrid::kernel::context::java_factory;
88   const _jthrowable* exc                        = env->ExceptionOccurred();
89   if (exc) {
90     env->ExceptionClear();
91   }
92
93   setlocale(LC_NUMERIC,"C");
94
95   int argc = 1;
96   if (jargs)
97     argc += static_cast<int>(env->GetArrayLength(jargs));
98   xbt_assert(argc > 0);
99
100   // Need a static storage because the XBT layer saves the arguments in xbt::binary_name and xbt::cmdline.
101   static std::vector<std::string> args;
102   args.reserve(argc);
103
104   args.emplace_back("java");
105   for (int index = 1; index < argc; index++) {
106     auto jval       = (jstring)env->GetObjectArrayElement(jargs, index - 1);
107     const char* tmp = env->GetStringUTFChars(jval, nullptr);
108     args.emplace_back(tmp);
109     env->ReleaseStringUTFChars(jval, tmp);
110   }
111
112   std::unique_ptr<char* []> argv(new char*[argc + 1]);
113   std::transform(begin(args), end(args), argv.get(), [](std::string& s) { return &s.front(); });
114   argv[argc] = nullptr;
115
116   int argc2 = argc;
117   MSG_init(&argc2, argv.get());
118   xbt_assert(argc2 <= argc);
119
120   for (int index = 1; index < argc2; index++)
121     env->SetObjectArrayElement(jargs, index - 1, (jstring)env->NewStringUTF(argv[index]));
122
123   sg_vm_live_migration_plugin_init();
124   JAVA_HOST_LEVEL = simgrid::s4u::Host::extension_create(nullptr);
125 }
126
127 JNIEXPORT void JNICALL JNICALL Java_org_simgrid_msg_Msg_run(JNIEnv* env, jclass)
128 {
129   /* Run everything */
130   XBT_DEBUG("Ready to run");
131   simgrid_run();
132   XBT_DEBUG("Done running");
133   XBT_INFO("Terminating the simulation...");
134   /* Cleanup java hosts */
135   sg_host_t* hosts  = sg_host_list();
136   size_t host_count = sg_host_count();
137   for (size_t index = 0; index < host_count - 1; index++) {
138     auto jhost = (jobject)hosts[index]->extension(JAVA_HOST_LEVEL);
139     if (jhost)
140       jhost_unref(env, jhost);
141   }
142   xbt_free(hosts);
143
144   /* Display the status of remaining threads. None should survive, but who knows */
145   jclass clsProcess = jxbt_get_class(env, "org/simgrid/msg/Process");
146   jmethodID idDebug = jxbt_get_static_jmethod(env, clsProcess, "debugAllThreads", "()V");
147   xbt_assert(idDebug != nullptr, "Method Process.debugAllThreads() not found...");
148   env->CallStaticVoidMethod(clsProcess, idDebug);
149 }
150
151 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_createEnvironment(JNIEnv* env, jclass, jstring jplatformFile)
152 {
153   const char* platformFile = env->GetStringUTFChars(jplatformFile, nullptr);
154
155   simgrid_load_platform(platformFile);
156
157   env->ReleaseStringUTFChars(jplatformFile, platformFile);
158 }
159
160 JNIEXPORT jobject JNICALL Java_org_simgrid_msg_Msg_environmentGetRoutingRoot(JNIEnv* env, jclass)
161 {
162   sg_netzone_t as  = sg_zone_get_root();
163   jobject jas      = jnetzone_new_instance(env);
164   if (not jas) {
165     jxbt_throw_jni(env, "java As instantiation failed");
166     return nullptr;
167   }
168   jas = jnetzone_ref(env, jas);
169   if (not jas) {
170     jxbt_throw_jni(env, "new global ref allocation failed");
171     return nullptr;
172   }
173   jnetzone_bind(jas, as, env);
174
175   return (jobject) jas;
176 }
177
178 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_debug(JNIEnv* env, jclass, jstring js)
179 {
180   const char* s = env->GetStringUTFChars(js, nullptr);
181   XBT_DEBUG("%s", s);
182   env->ReleaseStringUTFChars(js, s);
183 }
184
185 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_verb(JNIEnv* env, jclass, jstring js)
186 {
187   const char* s = env->GetStringUTFChars(js, nullptr);
188   XBT_VERB("%s", s);
189   env->ReleaseStringUTFChars(js, s);
190 }
191
192 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_info(JNIEnv* env, jclass, jstring js)
193 {
194   const char* s = env->GetStringUTFChars(js, nullptr);
195   XBT_INFO("%s", s);
196   env->ReleaseStringUTFChars(js, s);
197 }
198
199 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_warn(JNIEnv* env, jclass, jstring js)
200 {
201   const char* s = env->GetStringUTFChars(js, nullptr);
202   XBT_WARN("%s", s);
203   env->ReleaseStringUTFChars(js, s);
204 }
205
206 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_error(JNIEnv* env, jclass, jstring js)
207 {
208   const char* s = env->GetStringUTFChars(js, nullptr);
209   XBT_ERROR("%s", s);
210   env->ReleaseStringUTFChars(js, s);
211 }
212
213 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_critical(JNIEnv* env, jclass, jstring js)
214 {
215   const char* s = env->GetStringUTFChars(js, nullptr);
216   XBT_CRITICAL("%s", s);
217   env->ReleaseStringUTFChars(js, s);
218 }
219
220 static void java_main(int argc, char* argv[]);
221
222 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_deployApplication(JNIEnv* env, jclass, jstring jdeploymentFile)
223 {
224   const char* deploymentFile = env->GetStringUTFChars(jdeploymentFile, nullptr);
225
226   simgrid_register_default(java_main);
227   simgrid_load_deployment(deploymentFile);
228 }
229
230 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_energyInit() {
231   sg_host_energy_plugin_init();
232 }
233
234 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_loadInit() {
235     sg_host_load_plugin_init();
236 }
237 /** Run a Java org.simgrid.msg.Process
238  *
239  *  If needed, this waits for the process starting time.
240  *  Then it calls the Process.run() method.
241  */
242 static void run_jprocess(JNIEnv *env, jobject jprocess)
243 {
244   // wait for the process's start time
245   jfieldID jprocess_field_Process_startTime = jxbt_get_sfield(env, "org/simgrid/msg/Process", "startTime", "D");
246   jdouble startTime = env->GetDoubleField(jprocess, jprocess_field_Process_startTime);
247   if (startTime > simgrid_get_clock())
248     simgrid::s4u::this_actor::sleep_for(startTime - simgrid_get_clock());
249
250   //Execution of the "run" method.
251   jmethodID id = jxbt_get_smethod(env, "org/simgrid/msg/Process", "run", "()V");
252   xbt_assert((id != nullptr), "Method Process.run() not found...");
253
254   env->CallVoidMethod(jprocess, id);
255   if (env->ExceptionOccurred()) {
256     XBT_DEBUG("Something went wrong in this Java actor, forget about it.");
257     env->ExceptionClear();
258     xbt_assert(__java_vm->DetachCurrentThread() == JNI_OK, "Cannot detach failing thread");
259     simgrid::ForcefulKillException::do_throw();
260   }
261 }
262
263 /** Create a Java org.simgrid.msg.Process with the arguments and run it */
264 static void java_main(int argc, char* argv[])
265 {
266   JNIEnv *env = get_current_thread_env();
267   auto* context = static_cast<simgrid::kernel::context::JavaContext*>(simgrid::kernel::context::Context::self());
268
269   //Change the "." in class name for "/".
270   std::string arg0 = argv[0];
271   std::replace(begin(arg0), end(arg0), '.', '/');
272   jclass class_Process = env->FindClass(arg0.c_str());
273   //Retrieve the methodID for the constructor
274   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]);
275   jmethodID constructor_Process = env->GetMethodID(class_Process, "<init>", "(Lorg/simgrid/msg/Host;Ljava/lang/String;[Ljava/lang/String;)V");
276   xbt_assert((constructor_Process != nullptr), "Constructor not found for class %s. Is there a (Host, String ,String[]) constructor in your class ?", argv[0]);
277
278   //Retrieve the name of the process.
279   jstring jname = env->NewStringUTF(argv[0]);
280   //Build the arguments
281   auto args = static_cast<jobjectArray>(
282       env->NewObjectArray(argc - 1, env->FindClass("java/lang/String"), env->NewStringUTF("")));
283   for (int i = 1; i < argc; i++)
284       env->SetObjectArrayElement(args,i - 1, env->NewStringUTF(argv[i]));
285   //Retrieve the host for the process.
286   jstring jhostName = env->NewStringUTF(simgrid::s4u::Host::current()->get_cname());
287   jobject jhost = Java_org_simgrid_msg_Host_getByName(env, nullptr, jhostName);
288   //creates the process
289   jobject jprocess = env->NewObject(class_Process, constructor_Process, jhost, jname, args);
290   xbt_assert((jprocess != nullptr), "Process allocation failed.");
291   jprocess = env->NewGlobalRef(jprocess);
292   //bind the process to the context
293   const_sg_actor_t actor = sg_actor_self();
294
295   context->jprocess_ = jprocess;
296   /* sets the PID and the PPID of the process */
297   env->SetIntField(jprocess, jprocess_field_Process_pid, static_cast<jint>(actor->get_pid()));
298   env->SetIntField(jprocess, jprocess_field_Process_ppid, static_cast<jint>(actor->get_ppid()));
299   jprocess_bind(jprocess, actor, env);
300
301   run_jprocess(env, context->jprocess_);
302 }
303
304 namespace simgrid {
305 namespace kernel {
306 namespace context {
307
308 /** Run the Java org.simgrid.msg.Process */
309 void java_main_jprocess(jobject jprocess)
310 {
311   JNIEnv *env = get_current_thread_env();
312   auto* context        = static_cast<JavaContext*>(Context::self());
313   context->jprocess_   = jprocess;
314   jprocess_bind(context->jprocess_, sg_actor_self(), env);
315
316   run_jprocess(env, context->jprocess_);
317 }
318 } // namespace context
319 } // namespace kernel
320 } // namespace simgrid