Logo AND Algorithmique Numérique Distribuée

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