Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
abb1bacc0e8a8218f0ec3ad00b81a24449123b24
[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 <locale.h>
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 index;
94   int argc = 0;
95   jstring jval;
96   const char *tmp;
97
98   XBT_LOG_CONNECT(java);
99   XBT_LOG_CONNECT(jtrace);
100
101   env->GetJavaVM(&__java_vm);
102
103   simgrid::kernel::context::factory_initializer = &simgrid::kernel::context::java_factory;
104   jthrowable exc = env->ExceptionOccurred();
105   if (exc) {
106     env->ExceptionClear();
107   }
108
109   setlocale(LC_NUMERIC,"C");
110
111   if (jargs)
112     argc = static_cast<int>(env->GetArrayLength(jargs));
113
114   argc++;
115   char** argv = new char*[argc + 1];
116   argv[0] = xbt_strdup("java");
117
118   for (index = 0; index < argc - 1; index++) {
119     jval = (jstring) env->GetObjectArrayElement(jargs, index);
120     tmp = env->GetStringUTFChars(jval, 0);
121     argv[index + 1] = xbt_strdup(tmp);
122     env->ReleaseStringUTFChars(jval, tmp);
123   }
124   argv[argc] = nullptr;
125
126   MSG_init(&argc, argv);
127
128   JAVA_HOST_LEVEL = simgrid::s4u::Host::extension_create(__JAVA_host_priv_free);
129
130   for (index = 0; index < argc - 1; index++) {
131     env->SetObjectArrayElement(jargs, index, (jstring)env->NewStringUTF(argv[index + 1]));
132     free(argv[index]);
133   }
134   free(argv[argc]);
135   delete[] argv;
136 }
137
138 JNIEXPORT void JNICALL JNICALL Java_org_simgrid_msg_Msg_run(JNIEnv * env, jclass cls)
139 {
140   /* Run everything */
141   XBT_DEBUG("Ready to run MSG_MAIN");
142   msg_error_t rv = MSG_main();
143   XBT_DEBUG("Done running MSG_MAIN");
144   jxbt_check_res("MSG_main()", rv, MSG_OK,
145                  xbt_strdup("unexpected error : MSG_main() failed .. please report this bug "));
146
147   XBT_INFO("MSG_main finished; Cleaning up the simulation...");
148   /* Cleanup java hosts */
149   xbt_dynar_t hosts = MSG_hosts_as_dynar();
150   for (unsigned long index = 0; index < xbt_dynar_length(hosts) - 1; index++) {
151     msg_host_t msg_host = xbt_dynar_get_as(hosts,index,msg_host_t);
152     jobject jhost = (jobject) msg_host->extension(JAVA_HOST_LEVEL);
153     if (jhost)
154       jhost_unref(env, jhost);
155
156   }
157   xbt_dynar_free(&hosts);
158
159   /* Cleanup java storages */
160   for (auto elm : java_storage_map)
161     jstorage_unref(env, elm.second);
162 }
163
164 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_createEnvironment(JNIEnv * env, jclass cls, jstring jplatformFile)
165 {
166   const char *platformFile = env->GetStringUTFChars(jplatformFile, 0);
167
168   MSG_create_environment(platformFile);
169
170   env->ReleaseStringUTFChars(jplatformFile, platformFile);
171 }
172
173 JNIEXPORT jobject JNICALL Java_org_simgrid_msg_Msg_environmentGetRoutingRoot(JNIEnv * env, jclass cls)
174 {
175   msg_netzone_t as = MSG_zone_get_root();
176   jobject jas      = jnetzone_new_instance(env);
177   if (not jas) {
178     jxbt_throw_jni(env, "java As instantiation failed");
179     return nullptr;
180   }
181   jas = jnetzone_ref(env, jas);
182   if (not jas) {
183     jxbt_throw_jni(env, "new global ref allocation failed");
184     return nullptr;
185   }
186   jnetzone_bind(jas, as, env);
187
188   return (jobject) jas;
189 }
190
191 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_debug(JNIEnv * env, jclass cls, jstring js)
192 {
193   const char *s = env->GetStringUTFChars(js, 0);
194   XBT_DEBUG("%s", s);
195   env->ReleaseStringUTFChars(js, s);
196 }
197
198 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_verb(JNIEnv * env, jclass cls, jstring js)
199 {
200   const char *s = env->GetStringUTFChars(js, 0);
201   XBT_VERB("%s", s);
202   env->ReleaseStringUTFChars(js, s);
203 }
204
205 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_info(JNIEnv * env, jclass cls, jstring js)
206 {
207   const char *s = env->GetStringUTFChars(js, 0);
208   XBT_INFO("%s", s);
209   env->ReleaseStringUTFChars(js, s);
210 }
211
212 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_warn(JNIEnv * env, jclass cls, jstring js)
213 {
214   const char *s = env->GetStringUTFChars(js, 0);
215   XBT_WARN("%s", s);
216   env->ReleaseStringUTFChars(js, s);
217 }
218
219 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_error(JNIEnv * env, jclass cls, jstring js)
220 {
221   const char *s = env->GetStringUTFChars(js, 0);
222   XBT_ERROR("%s", s);
223   env->ReleaseStringUTFChars(js, s);
224 }
225
226 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_critical(JNIEnv * env, jclass cls, jstring js)
227 {
228   const char *s = env->GetStringUTFChars(js, 0);
229   XBT_CRITICAL("%s", s);
230   env->ReleaseStringUTFChars(js, s);
231 }
232
233 static int java_main(int argc, char *argv[]);
234
235 JNIEXPORT void JNICALL
236 Java_org_simgrid_msg_Msg_deployApplication(JNIEnv * env, jclass cls, jstring jdeploymentFile)
237 {
238   const char *deploymentFile = env->GetStringUTFChars(jdeploymentFile, 0);
239
240   SIMIX_function_register_default(java_main);
241   MSG_launch_application(deploymentFile);
242 }
243
244 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_energyInit() {
245   sg_host_energy_plugin_init();
246 }
247
248 SG_END_DECL()
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   xbt_str_subst(argv[0],'.','/',0);
276   jclass class_Process = env->FindClass(argv[0]);
277   xbt_str_subst(argv[0],'/','.',0);
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()->cname());
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 }}}