Logo AND Algorithmique Numérique Distribuée

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