Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'actor-startkilltime' of https://github.com/Takishipp/simgrid into Takis...
[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 <algorithm>
9 #include <clocale>
10 #include <string>
11
12 #include "simgrid/msg.h"
13 #include "simgrid/plugins/energy.h"
14 #include "simgrid/simix.h"
15
16 #include "simgrid/s4u/Host.hpp"
17
18 #include "src/simix/smx_private.hpp"
19
20 #include "jmsg.hpp"
21 #include "jmsg_as.hpp"
22 #include "jmsg_host.h"
23 #include "jmsg_process.h"
24 #include "jmsg_storage.h"
25 #include "jmsg_task.h"
26 #include "jxbt_utilities.hpp"
27
28 #include "JavaContext.hpp"
29
30 #include <xbt/ex.hpp>
31
32 /* Shut up some errors in eclipse online compiler. I wish such a pimple wouldn't be needed */
33 #ifndef JNIEXPORT
34 #define JNIEXPORT
35 #endif
36 #ifndef JNICALL
37 #define JNICALL
38 #endif
39 /* end of eclipse-mandated pimple */
40
41 extern "C" {
42
43 int JAVA_HOST_LEVEL = -1;
44
45 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(java);
46
47 JavaVM *__java_vm = nullptr;
48
49 JavaVM *get_java_VM()
50 {
51   return __java_vm;
52 }
53
54 JNIEnv *get_current_thread_env()
55 {
56   using simgrid::kernel::context::JavaContext;
57   JavaContext* ctx = static_cast<JavaContext*>(xbt_os_thread_get_extra_data());
58   return ctx->jenv;
59 }
60
61 void jmsg_throw_status(JNIEnv *env, msg_error_t status) {
62   switch (status) {
63     case MSG_TIMEOUT:
64       jxbt_throw_time_out_failure(env, "");
65       break;
66     case MSG_TRANSFER_FAILURE:
67       jxbt_throw_transfer_failure(env, "");
68       break;
69     case MSG_HOST_FAILURE:
70       jxbt_throw_host_failure(env, "");
71       break;
72     case MSG_TASK_CANCELED:
73       jxbt_throw_task_cancelled(env, "");
74       break;
75     default:
76       xbt_die("undefined message failed (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 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_init(JNIEnv * env, jclass cls, jobjectArray jargs)
94 {
95   int argc = 0;
96
97   XBT_LOG_CONNECT(java);
98   XBT_LOG_CONNECT(jtrace);
99
100   env->GetJavaVM(&__java_vm);
101
102   simgrid::kernel::context::factory_initializer = &simgrid::kernel::context::java_factory;
103   jthrowable exc = env->ExceptionOccurred();
104   if (exc) {
105     env->ExceptionClear();
106   }
107
108   setlocale(LC_NUMERIC,"C");
109
110   if (jargs)
111     argc = static_cast<int>(env->GetArrayLength(jargs));
112
113   argc++;
114   char** argv = new char*[argc + 1];
115   argv[0] = xbt_strdup("java");
116
117   for (int index = 0; index < argc - 1; index++) {
118     jstring jval    = (jstring)env->GetObjectArrayElement(jargs, index);
119     const char* tmp = env->GetStringUTFChars(jval, 0);
120     argv[index + 1] = xbt_strdup(tmp);
121     env->ReleaseStringUTFChars(jval, tmp);
122   }
123   argv[argc] = nullptr;
124
125   MSG_init(&argc, argv);
126
127   JAVA_HOST_LEVEL = simgrid::s4u::Host::extension_create(__JAVA_host_priv_free);
128
129   for (int index = 0; index < argc - 1; index++) {
130     env->SetObjectArrayElement(jargs, index, (jstring)env->NewStringUTF(argv[index + 1]));
131     free(argv[index]);
132   }
133   free(argv[argc]);
134   delete[] argv;
135 }
136
137 JNIEXPORT void JNICALL JNICALL Java_org_simgrid_msg_Msg_run(JNIEnv * env, jclass cls)
138 {
139   /* Run everything */
140   XBT_DEBUG("Ready to run MSG_MAIN");
141   msg_error_t rv = MSG_main();
142   XBT_DEBUG("Done running MSG_MAIN");
143   jxbt_check_res("MSG_main()", rv, MSG_OK,
144                  xbt_strdup("unexpected error : MSG_main() failed .. please report this bug "));
145
146   XBT_INFO("MSG_main finished; Cleaning up the simulation...");
147   /* Cleanup java hosts */
148   xbt_dynar_t hosts = MSG_hosts_as_dynar();
149   for (unsigned long index = 0; index < xbt_dynar_length(hosts) - 1; index++) {
150     msg_host_t msg_host = xbt_dynar_get_as(hosts,index,msg_host_t);
151     jobject jhost = (jobject) msg_host->extension(JAVA_HOST_LEVEL);
152     if (jhost)
153       jhost_unref(env, jhost);
154
155   }
156   xbt_dynar_free(&hosts);
157
158   /* Cleanup java storages */
159   for (auto const& elm : java_storage_map)
160     jstorage_unref(env, elm.second);
161 }
162
163 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_createEnvironment(JNIEnv * env, jclass cls, jstring jplatformFile)
164 {
165   const char *platformFile = env->GetStringUTFChars(jplatformFile, 0);
166
167   MSG_create_environment(platformFile);
168
169   env->ReleaseStringUTFChars(jplatformFile, platformFile);
170 }
171
172 JNIEXPORT jobject JNICALL Java_org_simgrid_msg_Msg_environmentGetRoutingRoot(JNIEnv * env, jclass cls)
173 {
174   msg_netzone_t as = MSG_zone_get_root();
175   jobject jas      = jnetzone_new_instance(env);
176   if (not jas) {
177     jxbt_throw_jni(env, "java As instantiation failed");
178     return nullptr;
179   }
180   jas = jnetzone_ref(env, jas);
181   if (not jas) {
182     jxbt_throw_jni(env, "new global ref allocation failed");
183     return nullptr;
184   }
185   jnetzone_bind(jas, as, env);
186
187   return (jobject) jas;
188 }
189
190 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_debug(JNIEnv * env, jclass cls, jstring js)
191 {
192   const char *s = env->GetStringUTFChars(js, 0);
193   XBT_DEBUG("%s", s);
194   env->ReleaseStringUTFChars(js, s);
195 }
196
197 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_verb(JNIEnv * env, jclass cls, jstring js)
198 {
199   const char *s = env->GetStringUTFChars(js, 0);
200   XBT_VERB("%s", s);
201   env->ReleaseStringUTFChars(js, s);
202 }
203
204 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_info(JNIEnv * env, jclass cls, jstring js)
205 {
206   const char *s = env->GetStringUTFChars(js, 0);
207   XBT_INFO("%s", s);
208   env->ReleaseStringUTFChars(js, s);
209 }
210
211 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_warn(JNIEnv * env, jclass cls, jstring js)
212 {
213   const char *s = env->GetStringUTFChars(js, 0);
214   XBT_WARN("%s", s);
215   env->ReleaseStringUTFChars(js, s);
216 }
217
218 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_error(JNIEnv * env, jclass cls, jstring js)
219 {
220   const char *s = env->GetStringUTFChars(js, 0);
221   XBT_ERROR("%s", s);
222   env->ReleaseStringUTFChars(js, s);
223 }
224
225 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_critical(JNIEnv * env, jclass cls, jstring js)
226 {
227   const char *s = env->GetStringUTFChars(js, 0);
228   XBT_CRITICAL("%s", s);
229   env->ReleaseStringUTFChars(js, s);
230 }
231
232 static int java_main(int argc, char *argv[]);
233
234 JNIEXPORT void JNICALL
235 Java_org_simgrid_msg_Msg_deployApplication(JNIEnv * env, jclass cls, jstring jdeploymentFile)
236 {
237   const char *deploymentFile = env->GetStringUTFChars(jdeploymentFile, 0);
238
239   SIMIX_function_register_default(java_main);
240   MSG_launch_application(deploymentFile);
241 }
242
243 JNIEXPORT void JNICALL Java_org_simgrid_msg_Msg_energyInit() {
244   sg_host_energy_plugin_init();
245 }
246 } // extern "C"
247
248 /** Run a Java org.simgrid.msg.Process
249  *
250  *  If needed, this waits for the process starting time.
251  *  Then it calls the Process.run() method.
252  */
253 static void run_jprocess(JNIEnv *env, jobject jprocess)
254 {
255   // wait for the process's start time
256   jfieldID jprocess_field_Process_startTime = jxbt_get_sfield(env, "org/simgrid/msg/Process", "startTime", "D");
257   jdouble startTime = env->GetDoubleField(jprocess, jprocess_field_Process_startTime);
258   if (startTime > MSG_get_clock())
259     MSG_process_sleep(startTime - MSG_get_clock());
260   //Execution of the "run" method.
261   jmethodID id = jxbt_get_smethod(env, "org/simgrid/msg/Process", "run", "()V");
262   xbt_assert((id != nullptr), "Method run() not found...");
263   env->CallVoidMethod(jprocess, id);
264 }
265
266 /** Create a Java org.simgrid.msg.Process with the arguments and run it */
267 static int java_main(int argc, char *argv[])
268 {
269   JNIEnv *env = get_current_thread_env();
270   simgrid::kernel::context::JavaContext* context = static_cast<simgrid::kernel::context::JavaContext*>(SIMIX_context_self());
271
272   //Change the "." in class name for "/".
273   std::string arg0 = argv[0];
274   std::replace(begin(arg0), end(arg0), '.', '/');
275   jclass class_Process = env->FindClass(arg0.c_str());
276   //Retrieve the methodID for the constructor
277   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]);
278   jmethodID constructor_Process = env->GetMethodID(class_Process, "<init>", "(Lorg/simgrid/msg/Host;Ljava/lang/String;[Ljava/lang/String;)V");
279   xbt_assert((constructor_Process != nullptr), "Constructor not found for class %s. Is there a (Host, String ,String[]) constructor in your class ?", argv[0]);
280
281   //Retrieve the name of the process.
282   jstring jname = env->NewStringUTF(argv[0]);
283   //Build the arguments
284   jobjectArray args = static_cast<jobjectArray>(env->NewObjectArray(argc - 1, env->FindClass("java/lang/String"),
285                                                                     env->NewStringUTF("")));
286   for (int i = 1; i < argc; i++)
287       env->SetObjectArrayElement(args,i - 1, env->NewStringUTF(argv[i]));
288   //Retrieve the host for the process.
289   jstring jhostName = env->NewStringUTF(MSG_host_self()->getCname());
290   jobject jhost = Java_org_simgrid_msg_Host_getByName(env, nullptr, jhostName);
291   //creates the process
292   jobject jprocess = env->NewObject(class_Process, constructor_Process, jhost, jname, args);
293   xbt_assert((jprocess != nullptr), "Process allocation failed.");
294   jprocess = env->NewGlobalRef(jprocess);
295   //bind the process to the context
296   msg_process_t process = MSG_process_self();
297
298   context->jprocess = jprocess;
299   /* sets the PID and the PPID of the process */
300   env->SetIntField(jprocess, jprocess_field_Process_pid, static_cast<jint>(MSG_process_get_PID(process)));
301   env->SetIntField(jprocess, jprocess_field_Process_ppid, static_cast<jint>(MSG_process_get_PPID(process)));
302   jprocess_bind(jprocess, process, env);
303
304   run_jprocess(env, context->jprocess);
305   return 0;
306 }
307
308 namespace simgrid {
309 namespace kernel {
310 namespace context {
311
312 /** Run the Java org.simgrid.msg.Process */
313 void java_main_jprocess(jobject jprocess)
314 {
315   JNIEnv *env = get_current_thread_env();
316   simgrid::kernel::context::JavaContext* context = static_cast<simgrid::kernel::context::JavaContext*>(SIMIX_context_self());
317   context->jprocess = jprocess;
318   jprocess_bind(context->jprocess, MSG_process_self(), env);
319
320   run_jprocess(env, context->jprocess);
321 }
322 }}}