Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
78b7dfe590d62f8760990f43ee669d2bbd82408e
[simgrid.git] / src / bindings / java / jmsg.cpp
1 /* Java Wrappers to the MSG API.                                            */
2
3 /* Copyright (c) 2007-2018. The SimGrid Team. All rights reserved.          */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 #include <algorithm>
9 #include <clocale>
10 #include <string>
11
12 #include "simgrid/msg.h"
13 #include "simgrid/plugins/energy.h"
14 #include "simgrid/plugins/file_system.h"
15 #include "simgrid/plugins/live_migration.h"
16 #include "simgrid/simix.h"
17
18 #include "simgrid/s4u/Host.hpp"
19
20 #include "src/simix/smx_private.hpp"
21
22 #include "jmsg.hpp"
23 #include "jmsg_as.hpp"
24 #include "jmsg_host.h"
25 #include "jmsg_process.h"
26 #include "jmsg_storage.h"
27 #include "jmsg_task.h"
28 #include "jxbt_utilities.hpp"
29
30 #include "JavaContext.hpp"
31
32 #include <xbt/ex.hpp>
33
34 /* Shut up some errors in eclipse online compiler. I wish such a pimple wouldn't be needed */
35 #ifndef JNIEXPORT
36 #define JNIEXPORT
37 #endif
38 #ifndef JNICALL
39 #define JNICALL
40 #endif
41 /* end of eclipse-mandated pimple */
42
43 extern "C" {
44
45 int JAVA_HOST_LEVEL = -1;
46
47 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(java);
48
49 JavaVM *__java_vm = nullptr;
50
51 JavaVM *get_java_VM()
52 {
53   return __java_vm;
54 }
55
56 JNIEnv *get_current_thread_env()
57 {
58   using simgrid::kernel::context::JavaContext;
59   JavaContext* ctx = static_cast<JavaContext*>(xbt_os_thread_get_extra_data());
60   return ctx->jenv;
61 }
62
63 void jmsg_throw_status(JNIEnv *env, msg_error_t status) {
64   switch (status) {
65     case MSG_TIMEOUT:
66       jxbt_throw_time_out_failure(env, "");
67       break;
68     case MSG_TRANSFER_FAILURE:
69       jxbt_throw_transfer_failure(env, "");
70       break;
71     case MSG_HOST_FAILURE:
72       jxbt_throw_host_failure(env, "");
73       break;
74     case MSG_TASK_CANCELED:
75       jxbt_throw_task_cancelled(env, "");
76       break;
77     default:
78       xbt_die("undefined message failed (please see jmsg_throw_status function in jmsg.cpp)");
79   }
80 }
81
82 /***************************************************************************************
83  * Unsortable functions                                                        *
84  ***************************************************************************************/
85
86 JNIEXPORT jdouble JNICALL Java_org_simgrid_msg_Msg_getClock(JNIEnv * env, jclass cls)
87 {
88   return (jdouble) MSG_get_clock();
89 }
90
91 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_init(JNIEnv * env, jclass cls, jobjectArray jargs)
92 {
93   int argc = 0;
94
95   env->GetJavaVM(&__java_vm);
96
97   simgrid::kernel::context::factory_initializer = &simgrid::kernel::context::java_factory;
98   jthrowable exc = env->ExceptionOccurred();
99   if (exc) {
100     env->ExceptionClear();
101   }
102
103   setlocale(LC_NUMERIC,"C");
104
105   if (jargs)
106     argc = static_cast<int>(env->GetArrayLength(jargs));
107
108   argc++;
109   char** argv = new char*[argc + 1];
110   argv[0] = xbt_strdup("java");
111
112   for (int index = 0; index < argc - 1; index++) {
113     jstring jval    = (jstring)env->GetObjectArrayElement(jargs, index);
114     const char* tmp = env->GetStringUTFChars(jval, 0);
115     argv[index + 1] = xbt_strdup(tmp);
116     env->ReleaseStringUTFChars(jval, tmp);
117   }
118   argv[argc] = nullptr;
119
120   MSG_init(&argc, argv);
121   sg_vm_live_migration_plugin_init();
122
123   JAVA_HOST_LEVEL = simgrid::s4u::Host::extension_create(nullptr);
124
125   for (int index = 0; index < argc - 1; index++) {
126     env->SetObjectArrayElement(jargs, index, (jstring)env->NewStringUTF(argv[index + 1]));
127     free(argv[index]);
128   }
129   free(argv[argc]);
130   delete[] argv;
131 }
132
133 JNIEXPORT void JNICALL JNICALL Java_org_simgrid_msg_Msg_run(JNIEnv * env, jclass cls)
134 {
135   /* Run everything */
136   XBT_DEBUG("Ready to run MSG_MAIN");
137   msg_error_t rv = MSG_main();
138   XBT_DEBUG("Done running MSG_MAIN");
139   jxbt_check_res("MSG_main()", rv, MSG_OK,
140                  xbt_strdup("unexpected error : MSG_main() failed .. please report this bug "));
141
142   XBT_INFO("MSG_main finished; Cleaning up the simulation...");
143   /* Cleanup java hosts */
144   xbt_dynar_t hosts = MSG_hosts_as_dynar();
145   for (unsigned long index = 0; index < xbt_dynar_length(hosts) - 1; index++) {
146     msg_host_t msg_host = xbt_dynar_get_as(hosts,index,msg_host_t);
147     jobject jhost = (jobject) msg_host->extension(JAVA_HOST_LEVEL);
148     if (jhost)
149       jhost_unref(env, jhost);
150
151   }
152   xbt_dynar_free(&hosts);
153
154   /* Cleanup java storages */
155   for (auto const& elm : java_storage_map)
156     jstorage_unref(env, elm.second);
157 }
158
159 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_createEnvironment(JNIEnv * env, jclass cls, jstring jplatformFile)
160 {
161   const char *platformFile = env->GetStringUTFChars(jplatformFile, 0);
162
163   MSG_create_environment(platformFile);
164
165   env->ReleaseStringUTFChars(jplatformFile, platformFile);
166 }
167
168 JNIEXPORT jobject JNICALL Java_org_simgrid_msg_Msg_environmentGetRoutingRoot(JNIEnv * env, jclass cls)
169 {
170   msg_netzone_t as = MSG_zone_get_root();
171   jobject jas      = jnetzone_new_instance(env);
172   if (not jas) {
173     jxbt_throw_jni(env, "java As instantiation failed");
174     return nullptr;
175   }
176   jas = jnetzone_ref(env, jas);
177   if (not jas) {
178     jxbt_throw_jni(env, "new global ref allocation failed");
179     return nullptr;
180   }
181   jnetzone_bind(jas, as, env);
182
183   return (jobject) jas;
184 }
185
186 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_debug(JNIEnv * env, jclass cls, jstring js)
187 {
188   const char *s = env->GetStringUTFChars(js, 0);
189   XBT_DEBUG("%s", s);
190   env->ReleaseStringUTFChars(js, s);
191 }
192
193 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_verb(JNIEnv * env, jclass cls, jstring js)
194 {
195   const char *s = env->GetStringUTFChars(js, 0);
196   XBT_VERB("%s", s);
197   env->ReleaseStringUTFChars(js, s);
198 }
199
200 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_info(JNIEnv * env, jclass cls, jstring js)
201 {
202   const char *s = env->GetStringUTFChars(js, 0);
203   XBT_INFO("%s", s);
204   env->ReleaseStringUTFChars(js, s);
205 }
206
207 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_warn(JNIEnv * env, jclass cls, jstring js)
208 {
209   const char *s = env->GetStringUTFChars(js, 0);
210   XBT_WARN("%s", s);
211   env->ReleaseStringUTFChars(js, s);
212 }
213
214 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_error(JNIEnv * env, jclass cls, jstring js)
215 {
216   const char *s = env->GetStringUTFChars(js, 0);
217   XBT_ERROR("%s", s);
218   env->ReleaseStringUTFChars(js, s);
219 }
220
221 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_critical(JNIEnv * env, jclass cls, jstring js)
222 {
223   const char *s = env->GetStringUTFChars(js, 0);
224   XBT_CRITICAL("%s", s);
225   env->ReleaseStringUTFChars(js, s);
226 }
227
228 static int java_main(int argc, char *argv[]);
229
230 JNIEXPORT void JNICALL
231 Java_org_simgrid_msg_Msg_deployApplication(JNIEnv * env, jclass cls, jstring jdeploymentFile)
232 {
233   const char *deploymentFile = env->GetStringUTFChars(jdeploymentFile, 0);
234
235   SIMIX_function_register_default(java_main);
236   MSG_launch_application(deploymentFile);
237 }
238
239 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_energyInit() {
240   sg_host_energy_plugin_init();
241 }
242
243 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_fileSystemInit()
244 {
245   sg_storage_file_system_init();
246 }
247 } // extern "C"
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 > MSG_get_clock())
260     MSG_process_sleep(startTime - MSG_get_clock());
261   //Execution of the "run" method.
262   jmethodID id = jxbt_get_smethod(env, "org/simgrid/msg/Process", "run", "()V");
263   xbt_assert((id != nullptr), "Method run() not found...");
264   env->CallVoidMethod(jprocess, id);
265 }
266
267 /** Create a Java org.simgrid.msg.Process with the arguments and run it */
268 static int java_main(int argc, char *argv[])
269 {
270   JNIEnv *env = get_current_thread_env();
271   simgrid::kernel::context::JavaContext* context = static_cast<simgrid::kernel::context::JavaContext*>(SIMIX_context_self());
272
273   //Change the "." in class name for "/".
274   std::string arg0 = argv[0];
275   std::replace(begin(arg0), end(arg0), '.', '/');
276   jclass class_Process = env->FindClass(arg0.c_str());
277   //Retrieve the methodID for the constructor
278   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]);
279   jmethodID constructor_Process = env->GetMethodID(class_Process, "<init>", "(Lorg/simgrid/msg/Host;Ljava/lang/String;[Ljava/lang/String;)V");
280   xbt_assert((constructor_Process != nullptr), "Constructor not found for class %s. Is there a (Host, String ,String[]) constructor in your class ?", argv[0]);
281
282   //Retrieve the name of the process.
283   jstring jname = env->NewStringUTF(argv[0]);
284   //Build the arguments
285   jobjectArray args = static_cast<jobjectArray>(env->NewObjectArray(argc - 1, env->FindClass("java/lang/String"),
286                                                                     env->NewStringUTF("")));
287   for (int i = 1; i < argc; i++)
288       env->SetObjectArrayElement(args,i - 1, env->NewStringUTF(argv[i]));
289   //Retrieve the host for the process.
290   jstring jhostName = env->NewStringUTF(MSG_host_self()->getCname());
291   jobject jhost = Java_org_simgrid_msg_Host_getByName(env, nullptr, jhostName);
292   //creates the process
293   jobject jprocess = env->NewObject(class_Process, constructor_Process, jhost, jname, args);
294   xbt_assert((jprocess != nullptr), "Process allocation failed.");
295   jprocess = env->NewGlobalRef(jprocess);
296   //bind the process to the context
297   msg_process_t process = MSG_process_self();
298
299   context->jprocess = jprocess;
300   /* sets the PID and the PPID of the process */
301   env->SetIntField(jprocess, jprocess_field_Process_pid, static_cast<jint>(MSG_process_get_PID(process)));
302   env->SetIntField(jprocess, jprocess_field_Process_ppid, static_cast<jint>(MSG_process_get_PPID(process)));
303   jprocess_bind(jprocess, process, env);
304
305   run_jprocess(env, context->jprocess);
306   return 0;
307 }
308
309 namespace simgrid {
310 namespace kernel {
311 namespace context {
312
313 /** Run the Java org.simgrid.msg.Process */
314 void java_main_jprocess(jobject jprocess)
315 {
316   JNIEnv *env = get_current_thread_env();
317   simgrid::kernel::context::JavaContext* context = static_cast<simgrid::kernel::context::JavaContext*>(SIMIX_context_self());
318   context->jprocess = jprocess;
319   jprocess_bind(context->jprocess, MSG_process_self(), env);
320
321   run_jprocess(env, context->jprocess);
322 }
323 }}}