/interpreter/tags/at2dist090708/src/edu/vub/at/actors/natives/ELActor.java

http://ambienttalk.googlecode.com/ · Java · 508 lines · 266 code · 45 blank · 197 comment · 9 complexity · cee5f7db38bea45ee2ea8713b2e514be MD5 · raw file

  1. /**
  2. * AmbientTalk/2 Project
  3. * ELActor.java created on 27-dec-2006 at 16:17:23
  4. * (c) Programming Technology Lab, 2006 - 2007
  5. * Authors: Tom Van Cutsem & Stijn Mostinckx
  6. *
  7. * Permission is hereby granted, free of charge, to any person
  8. * obtaining a copy of this software and associated documentation
  9. * files (the "Software"), to deal in the Software without
  10. * restriction, including without limitation the rights to use,
  11. * copy, modify, merge, publish, distribute, sublicense, and/or
  12. * sell copies of the Software, and to permit persons to whom the
  13. * Software is furnished to do so, subject to the following
  14. * conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be
  17. * included in all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  21. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  23. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  24. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  25. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  26. * OTHER DEALINGS IN THE SOFTWARE.
  27. */
  28. package edu.vub.at.actors.natives;
  29. import edu.vub.at.actors.ATActorMirror;
  30. import edu.vub.at.actors.ATAsyncMessage;
  31. import edu.vub.at.actors.ATFarReference;
  32. import edu.vub.at.actors.eventloops.BlockingFuture;
  33. import edu.vub.at.actors.eventloops.Callable;
  34. import edu.vub.at.actors.eventloops.Event;
  35. import edu.vub.at.actors.eventloops.EventLoop;
  36. import edu.vub.at.actors.id.ATObjectID;
  37. import edu.vub.at.actors.id.ActorID;
  38. import edu.vub.at.actors.net.comm.Address;
  39. import edu.vub.at.eval.Evaluator;
  40. import edu.vub.at.exceptions.InterpreterException;
  41. import edu.vub.at.exceptions.XClassNotFound;
  42. import edu.vub.at.exceptions.XIOProblem;
  43. import edu.vub.at.exceptions.XIllegalOperation;
  44. import edu.vub.at.exceptions.XObjectOffline;
  45. import edu.vub.at.objects.ATAbstractGrammar;
  46. import edu.vub.at.objects.ATMethod;
  47. import edu.vub.at.objects.ATObject;
  48. import edu.vub.at.objects.ATTable;
  49. import edu.vub.at.objects.ATTypeTag;
  50. import edu.vub.at.objects.mirrors.Reflection;
  51. import edu.vub.at.objects.natives.NATContext;
  52. import edu.vub.at.objects.natives.NATObject;
  53. import edu.vub.at.objects.natives.NATTable;
  54. import edu.vub.at.objects.natives.OBJLexicalRoot;
  55. import edu.vub.at.objects.symbiosis.Symbiosis;
  56. import edu.vub.at.util.logging.Logging;
  57. import java.lang.reflect.Method;
  58. import java.util.EventListener;
  59. /**
  60. * An instance of the class ELActor represents a programmer-defined
  61. * AmbientTalk/2 actor. The event queue of the actor event loop serves as the
  62. * actor's 'meta-level' queue.
  63. *
  64. * The events in the 'meta-level' queue are handled by the actor's mirror object.
  65. * This mirror is normally an instance of NATActorMirror, but it can be any
  66. * programmer-defined object that adheres to the ATActorMirror interface.
  67. *
  68. * @author tvcutsem
  69. */
  70. public class ELActor extends EventLoop {
  71. /**
  72. * A thread-local variable that contains the 'default actor' to use
  73. * when there is currently no ELActor event loop thread running.
  74. * This is primarily useful for performing unit tests where an actor
  75. * is automatically created when actor semantics is required.
  76. *
  77. * A warning is printed to the log because using the default actor should
  78. * only be used for testing purposes.
  79. */
  80. private static final ThreadLocal _DEFAULT_ACTOR_ = new ThreadLocal() {
  81. protected synchronized Object initialValue() {
  82. Logging.Actor_LOG.warn("Creating a default actor for thread " + Thread.currentThread());
  83. try {
  84. ELVirtualMachine host = new ELVirtualMachine(
  85. Evaluator.getNil(),
  86. new SharedActorField[] { },
  87. ELVirtualMachine._DEFAULT_GROUP_NAME_);
  88. return host.createEmptyActor().getFarHost();
  89. } catch (InterpreterException e) {
  90. throw new RuntimeException("Failed to initialize default actor: " + e.getMessage());
  91. }
  92. }
  93. };
  94. /**
  95. * Retrieves the currently running actor. If there is no running actor thread,
  96. * this returns the value stored in the thread-local default actor field.
  97. */
  98. public static final ELActor currentActor() {
  99. try {
  100. return ((ELActor) EventLoop.currentEventLoop());
  101. } catch (ClassCastException e) {
  102. // current event loop is not an actor event loop
  103. } catch (IllegalStateException e) {
  104. // current thread is not an event loop
  105. }
  106. Logging.Actor_LOG.warn("Asked for an actor in non-actor thread " + Thread.currentThread());
  107. return (ELActor) _DEFAULT_ACTOR_.get();
  108. }
  109. private ATActorMirror mirror_;
  110. private final ActorID id_;
  111. protected final ELVirtualMachine host_;
  112. protected final ReceptionistsSet receptionists_;
  113. /*
  114. * This object is created when the actor is initialized: i.e. it is the passed
  115. * version of the isolate that was passed to the actor: primitive by the creating actor.
  116. */
  117. private ATObject behaviour_;
  118. public ELActor(ATActorMirror mirror, ELVirtualMachine host) {
  119. super("actor " + mirror.toString());
  120. id_ = new ActorID();
  121. mirror_ = mirror;
  122. host_ = host;
  123. receptionists_ = new ReceptionistsSet(this);
  124. }
  125. /** constructor dedicated to initialization of discovery actor */
  126. protected ELActor(ELVirtualMachine host) {
  127. super("discovery actor");
  128. id_ = new ActorID();
  129. mirror_ = new NATActorMirror(host);
  130. host_ = host;
  131. receptionists_ = new ReceptionistsSet(this);
  132. }
  133. /**
  134. * Actor event loops handle events by allowing the meta-level events to
  135. * process themselves.
  136. */
  137. public void handle(Event event) {
  138. event.process(mirror_);
  139. }
  140. public ATActorMirror getImplicitActorMirror() { return mirror_; }
  141. public void setActorMirror(ATActorMirror mirror) { mirror_ = mirror; }
  142. public ELVirtualMachine getHost() {
  143. return host_;
  144. }
  145. public ATObject getBehaviour() {
  146. return behaviour_;
  147. }
  148. public ActorID getActorID() {
  149. return id_;
  150. }
  151. public Thread getExecutor() {
  152. return processor_;
  153. }
  154. /**
  155. * Takes offline a given remote object such that it is no longer remotely accessible.
  156. * @param object a **far?** reference to the object to export
  157. * @throws XIllegalOperation if the passed object is not part of the export table - i.e. non-remotely accessible.
  158. */
  159. public void takeOffline(ATObject object) throws InterpreterException {
  160. // receptionist set will check whether ATObject is really remote to me
  161. receptionists_.takeOfflineObject(object);
  162. }
  163. /**
  164. * Resolve the given object id into a local reference. There are three cases to
  165. * consider:
  166. * A) The given id designates an object local to this actor: the returned object
  167. * will be a **near** reference to the object (i.e. the object itself)
  168. * B) The given id designates a far (non-local) object that lives in the same
  169. * address space as this actor: the returned object wil be a **far** reference
  170. * to the object.
  171. * C) The given id designates a far object that lives on a remote machine: the
  172. * returned object will be a **far** and **remote** reference to the object.
  173. *
  174. * @param id the identifier of the object to resolve
  175. * @return a near or far reference to the object, depending on where the designated object lives
  176. */
  177. public ATObject resolve(ATObjectID id, ATTypeTag[] types) throws XObjectOffline {
  178. return receptionists_.resolveObject(id, types);
  179. }
  180. /* -----------------------------
  181. * -- Initialisation Protocol --
  182. * ----------------------------- */
  183. /**
  184. * Initialises the root using the contents of the init file stored by
  185. * the hosting virtual machine.
  186. * @throws InterpreterException
  187. */
  188. protected void initRootObject() throws InterpreterException {
  189. ATAbstractGrammar initialisationCode = host_.getInitialisationCode();
  190. // evaluate the initialization code in the context of the global scope
  191. NATObject globalScope = Evaluator.getGlobalLexicalScope();
  192. NATContext initCtx = new NATContext(globalScope, globalScope);
  193. initialisationCode.meta_eval(initCtx);
  194. }
  195. /**
  196. * Initialises various fields in the lexical root of the actor, which are defined in the
  197. * context of every actor. Candidates are a "system" field which allows the program to
  198. * perform IO operations or a "~" field denoting the current working directory.
  199. *
  200. * @throws InterpreterException when initialisation of a field fails
  201. */
  202. protected void initSharedFields() throws InterpreterException {
  203. SharedActorField[] fields = host_.getFieldsToInitialize();
  204. NATObject globalScope = Evaluator.getGlobalLexicalScope();
  205. for (int i = 0; i < fields.length; i++) {
  206. SharedActorField field = fields[i];
  207. ATObject value = field.initialize();
  208. if (value != null) {
  209. globalScope.meta_defineField(field.getName(), value);
  210. }
  211. }
  212. }
  213. // Events to be processed by the actor event loop
  214. /**
  215. * The initial event sent by the actor mirror to its event loop to intialize itself.
  216. * @param future the synchronization point with the creating actor, needs to be fulfilled with a far ref to the behaviour.
  217. * @param parametersPkt the serialized parameters for the initialization code
  218. * @param initcodePkt the serialized initialization code (e.g. the code in 'actor: { code }')
  219. */
  220. protected void event_init(final BlockingFuture future, final Packet parametersPkt, final Packet initcodePkt) {
  221. receive(new Event("init("+this+")") {
  222. public void process(Object byMyself) {
  223. try {
  224. behaviour_ = new NATObject();
  225. // pass far ref to behaviour to creator actor who is waiting for this
  226. future.resolve(receptionists_.exportObject(behaviour_));
  227. // !! WARNING: the following code is also duplicated in
  228. // ELDiscoveryActor's event_init. If this code is modified, don't
  229. // forget to modify that of the discovery actor as well !!
  230. // initialize lexically visible fields
  231. initSharedFields();
  232. // go on to initialize the root and all lexically visible fields
  233. initRootObject();
  234. ATTable params = parametersPkt.unpack().asTable();
  235. ATMethod initCode = initcodePkt.unpack().asMethod();
  236. // initialize the behaviour using the parameters and the code
  237. initCode.base_applyInScope(params, new NATContext(behaviour_, behaviour_));
  238. } catch (InterpreterException e) {
  239. Logging.Actor_LOG.error(behaviour_ + ": could not initialize actor behaviour", e);
  240. }
  241. }
  242. });
  243. }
  244. /**
  245. * The main entry point for any asynchronous self-sends.
  246. * Asynchronous self-sends (i.e. intra-actor sends) do not undergo any form of parameter passing,
  247. * there is no need to serialize and deserialize the message parameter in a Packet.
  248. *
  249. * When an actor receives an asynchronous message for a given receiver, it delegates control
  250. * to the message itself by means of the message's <tt>process</tt> method.
  251. * @throws InterpreterException
  252. */
  253. public void acceptSelfSend(final ATObject receiver, final ATAsyncMessage msg) throws InterpreterException {
  254. // This is the only place where messages are scheduled
  255. // The receiver is always a local object, receive has
  256. // already been invoked.
  257. mirror_.base_schedule(receiver, msg);
  258. // signal a serve event for every message that is accepted
  259. this.event_serve();
  260. }
  261. /**
  262. * The main entry point for any asynchronous messages sent to this actor
  263. * by external sources.
  264. * @param sender address of the sending actor, used to notify when the receiver has gone offline.
  265. * @param serializedMessage the asynchronous AmbientTalk base-level message to enqueue
  266. */
  267. public void event_remoteAccept(final Address sender, final Packet serializedMessage) {
  268. receive(new Event("remoteAccept("+serializedMessage+")") {
  269. public void process(Object myActorMirror) {
  270. try {
  271. // receive a pair [receiver, message]
  272. ATObject[] pair = serializedMessage.unpack().asNativeTable().elements_;
  273. ATObject receiver = pair[0];
  274. ATAsyncMessage msg = pair[1].asAsyncMessage();
  275. performAccept(receiver, msg);
  276. } catch (XObjectOffline e) {
  277. host_.event_objectTakenOffline(e.getObjectId(), sender);
  278. Logging.Actor_LOG.error(mirror_ + ": error unpacking "+ serializedMessage, e);
  279. } catch (InterpreterException e) {
  280. Logging.Actor_LOG.error(mirror_ + ": error unpacking "+ serializedMessage, e);
  281. }
  282. }
  283. });
  284. }
  285. /**
  286. * The main entry point for any asynchronous messages sent to this actor
  287. * by local actors.
  288. * @param ref the local reference of the sending actor, used to notify when the receiver has gone offline.
  289. * @param serializedMessage the asynchronous AmbientTalk base-level message to enqueue
  290. */
  291. public void event_localAccept(final NATLocalFarRef ref, final Packet serializedMessage) {
  292. receive(new Event("localAccept("+serializedMessage+")") {
  293. public void process(Object myActorMirror) {
  294. try {
  295. // receive a pair [receiver, message]
  296. ATObject[] pair = serializedMessage.unpack().asNativeTable().elements_;
  297. ATObject receiver = pair[0];
  298. ATAsyncMessage msg = pair[1].asAsyncMessage();
  299. performAccept(receiver, msg);
  300. } catch (XObjectOffline e) {
  301. ref.notifyTakenOffline();
  302. Logging.Actor_LOG.error(mirror_ + ": error unpacking "+ serializedMessage, e);
  303. } catch (InterpreterException e) {
  304. Logging.Actor_LOG.error(mirror_ + ": error unpacking "+ serializedMessage, e);
  305. }
  306. }
  307. });
  308. }
  309. public void event_serve() {
  310. receive(new Event("serve()") {
  311. public void process(Object myActorMirror) {
  312. try {
  313. ATObject result = mirror_.base_serve();
  314. Logging.Actor_LOG.debug(mirror_ + ": serve() returned " + result);
  315. } catch (InterpreterException e) {
  316. System.out.println(">>> Exception in actor " + myActorMirror + ": "+e.getMessage());
  317. e.printAmbientTalkStackTrace(System.out);
  318. Logging.Actor_LOG.error(mirror_ + ": serve() failed ", e);
  319. }
  320. }
  321. });
  322. }
  323. private void performAccept(ATObject receiver, ATAsyncMessage msg) {
  324. try {
  325. ATObject result = mirror_.base_receive(receiver, msg);
  326. Logging.Actor_LOG.debug(mirror_ + ": scheduling "+ msg + " returned " + result);
  327. // signal a serve event for every message that is accepted
  328. event_serve();
  329. } catch (InterpreterException e) {
  330. System.out.println(">>> Exception in actor " + getImplicitActorMirror() + ": "+e.getMessage());
  331. e.printAmbientTalkStackTrace(System.out);
  332. Logging.Actor_LOG.error(mirror_ + ": scheduling "+ msg + " failed ", e);
  333. }
  334. }
  335. /**
  336. * This method is invoked by a coercer in order to schedule a purely asynchronous symbiotic invocation
  337. * from the Java world.
  338. *
  339. * This method schedules the call for asynchronous execution. Its return value and or raised exceptions
  340. * are ignored. This method should only be used for {@link Method} objects whose return type is <tt>void</tt>
  341. * and whose declaring class is a subtype of {@link EventListener}. It represents asynchronous method
  342. * invocations from the Java world to the AmbientTalk world.
  343. *
  344. * @param principal the AmbientTalk object owned by this actor on which to invoke the method
  345. * @param method the Java method that was symbiotically invoked on the principal
  346. * @param args the arguments to the Java method call, already converted into AmbientTalk values
  347. */
  348. public void event_symbioticInvocation(final ATObject principal, final Method method, final ATObject[] args) {
  349. receive(new Event("asyncSymbioticInv of "+method.getName()) {
  350. public void process(Object actorMirror) {
  351. try {
  352. Reflection.downInvocation(principal, method, args);
  353. } catch (InterpreterException e) {
  354. System.out.println(">>> Exception in actor " + actorMirror + ": "+e.getMessage());
  355. e.printAmbientTalkStackTrace(System.out);
  356. Logging.Actor_LOG.error("asynchronous symbiotic invocation of "+method.getName()+" failed", e);
  357. }
  358. }
  359. });
  360. }
  361. /**
  362. * This method is invoked by a coercer in order to schedule a symbiotic invocation
  363. * from the Java world, which should be synchronous to the Java thread, but which
  364. * must be scheduled asynchronously to comply with the AT/2 actor model.
  365. *
  366. * The future returned by this method makes the calling (Java) thread <b>block</b> upon
  367. * accessing its value, waiting until the actor has processed the symbiotic invocation.
  368. *
  369. * @param principal the AmbientTalk object owned by this actor on which to invoke the method
  370. * @param meth the Java method that was symbiotically invoked on the principal
  371. * @param args the arguments to the Java method call, already converted into AmbientTalk values
  372. * @return a Java future that is resolved with the result of the symbiotic invocation
  373. * @throws Exception if the symbiotic invocation fails
  374. */
  375. public BlockingFuture sync_event_symbioticInvocation(final ATObject principal, final Method meth, final ATObject[] args) throws Exception {
  376. return receiveAndReturnFuture("syncSymbioticInv of " + meth.getName(), new Callable() {
  377. public Object call(Object actorMirror) throws Exception {
  378. Class targetType = meth.getReturnType();
  379. ATObject[] actualArgs = args;
  380. // if the return type is BlockingFuture, the first argument should specify the type
  381. // of the value with which BlockingFuture will be resolved
  382. if (targetType.equals(BlockingFuture.class)) {
  383. if ((meth.getParameterTypes().length > 0) && (meth.getParameterTypes()[0].equals(Class.class))) {
  384. targetType = args[0].asJavaClassUnderSymbiosis().getWrappedClass();
  385. // drop first argument, it only exists to specify the targetType
  386. ATObject[] newArgs = new ATObject[args.length-1];
  387. System.arraycopy(args, 1, newArgs, 0, newArgs.length);
  388. actualArgs = newArgs;
  389. }
  390. }
  391. ATObject result = Reflection.downInvocation(principal, meth, actualArgs);
  392. // SUPPORT FOR FUTURES
  393. if (Symbiosis.isAmbientTalkFuture(result)) {
  394. Logging.Actor_LOG.debug("Symbiotic futures: symbiotic call to " + meth.getName() + " returned an AT future");
  395. return Symbiosis.ambientTalkFutureToJavaFuture(result, targetType);
  396. } else {
  397. // return the proper value immediately
  398. return Symbiosis.ambientTalkToJava(result, targetType);
  399. }
  400. }
  401. });
  402. }
  403. /**
  404. * This method should only be used for purposes such as the IAT shell or unit testing.
  405. * It allows an external thread to make this actor evaluate an arbitrary expression.
  406. *
  407. * @param ast an abstract syntax tree to be evaluated by the receiving actor (in the
  408. * scope of its behaviour).
  409. * @return the result of the evaluation
  410. * @throws InterpreterException if the evaluation fails
  411. */
  412. public ATObject sync_event_eval(final ATAbstractGrammar ast) throws InterpreterException {
  413. try {
  414. return (ATObject) receiveAndWait("nativeEval("+ast+")", new Callable() {
  415. public Object call(Object inActor) throws Exception {
  416. return OBJLexicalRoot._INSTANCE_.base_eval_in_(ast, behaviour_);
  417. }
  418. });
  419. } catch (Exception e) {
  420. throw (InterpreterException) e;
  421. }
  422. }
  423. /**
  424. * This method should only be used for purposes of unit testing. It allows
  425. * arbitary code to be scheduled by external threads such as unit testing frameworks.
  426. */
  427. public Object sync_event_performTest(Callable c) throws Exception {
  428. return (ATObject) receiveAndWait("performTest("+c+")", c);
  429. }
  430. /**
  431. * When the discovery manager receives a publication from another local actor or
  432. * another remote VM, the actor is asked to compare the incoming publication against
  433. * a subscription that it had announced previously.
  434. *
  435. * @param requiredTypePkt serialized form of the type attached to the actor's subscription
  436. * @param myHandler the closure specified as a handler for the actor's subscription
  437. * @param discoveredTypePkt serialized form of the type attached to the new publication
  438. * @param remoteServicePkt serialized form of the reference to the remote discovered service
  439. */
  440. public void event_serviceJoined(final Packet requiredTypePkt, final ATFarReference myHandler,
  441. final Packet discoveredTypePkt, final Packet remoteServicePkt) {
  442. receive(new Event("serviceJoined") {
  443. public void process(Object myActorMirror) {
  444. try {
  445. ATTypeTag requiredType = requiredTypePkt.unpack().asTypeTag();
  446. ATTypeTag discoveredType = discoveredTypePkt.unpack().asTypeTag();
  447. // is there a match?
  448. if (discoveredType.base_isSubtypeOf(requiredType).asNativeBoolean().javaValue) {
  449. ATObject remoteService = remoteServicePkt.unpack();
  450. // myhandler<-apply([remoteService])@[]
  451. Evaluator.trigger(myHandler, NATTable.of(remoteService));
  452. }
  453. } catch (XIOProblem e) {
  454. Logging.Actor_LOG.error("Error deserializing joined types or services: ", e.getCause());
  455. } catch (XClassNotFound e) {
  456. Logging.Actor_LOG.fatal("Could not find class while deserializing joined types or services: ", e.getCause());
  457. } catch (InterpreterException e) {
  458. Logging.Actor_LOG.error("Error while joining services: ", e);
  459. }
  460. }
  461. });
  462. }
  463. }