Logo AND Algorithmique Numérique Distribuée

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