Logo AND Algorithmique Numérique Distribuée

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