Logo AND Algorithmique Numérique Distribuée

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