Logo AND Algorithmique Numérique Distribuée

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