Logo AND Algorithmique Numérique Distribuée

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