spade 4.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
spade/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ # -*- coding: utf-8 -*-
2
+ import asyncio
3
+ import logging
4
+
5
+ from . import agent
6
+ from . import behaviour
7
+ from . import fipa_message
8
+ from . import message
9
+ from . import template
10
+ from .agent import AgentType
11
+ from .container import run_container as run # noqa: F401
12
+
13
+ __author__ = """Javi Palanca"""
14
+ __email__ = "jpalanca@gmail.com"
15
+ __version__ = "4.2.0"
16
+
17
+ __all__ = ["agent", "behaviour", "fipa_message", "message", "template"]
18
+
19
+ logger = logging.getLogger("SPADE")
20
+
21
+
22
+ async def wait_until_finished(agents: list[AgentType] | AgentType) -> None:
23
+ """
24
+ Waits until the agents are stopped (e.g. by themselves, or with ctrl+C).
25
+
26
+ If the wait is cancelled (e.g. when ``spade.run()`` ends with ctrl+C), the agents
27
+ that are still alive are stopped.
28
+
29
+ Args:
30
+ agents (Agent | list[Agent]): an agent or a list of agents.
31
+ """
32
+ if not isinstance(agents, list):
33
+ agents = [agents]
34
+ try:
35
+ await asyncio.gather(*[ag._wait_until_stopped() for ag in agents])
36
+ finally: # e.g. cancelled: the agents are stopped
37
+ await asyncio.gather(*[a.stop() for a in agents if a.is_alive()])
38
+
39
+
40
+ async def start_agents(agents: list[AgentType]) -> None:
41
+ """
42
+ Starts several agents concurrently (with the default arguments of ``start()``).
43
+
44
+ Args:
45
+ agents (list[Agent]): the agents to start.
46
+ """
47
+ if not isinstance(agents, list):
48
+ agents = [agents]
49
+ await asyncio.gather(*[ag.start() for ag in agents])
spade/agent.py ADDED
@@ -0,0 +1,590 @@
1
+ import asyncio
2
+ import logging
3
+ from asyncio import Task
4
+ from hashlib import md5
5
+ from types import TracebackType
6
+ from typing import Any, Self, TypeVar
7
+ from collections.abc import Coroutine
8
+
9
+ from slixmpp import JID
10
+ from slixmpp import Message as slixmppMessage
11
+
12
+ from .behaviour import Behaviour, FSMBehaviour, running_behaviour
13
+ from .behaviour import BehaviourType # noqa: F401 (it was imported from here)
14
+ from .container import Container
15
+ from .message import Message
16
+ from .presence import PresenceManager
17
+ from .template import Template
18
+ from .trace import TraceStore
19
+ from .web import WebApp
20
+ from .xmpp_client import XMPPClient
21
+
22
+ logger = logging.getLogger("spade.Agent")
23
+
24
+ AgentType = TypeVar("AgentType", bound="Agent")
25
+ T = TypeVar("T")
26
+
27
+
28
+ class AuthenticationFailure(Exception):
29
+ """ """
30
+
31
+ pass
32
+
33
+
34
+ class DisconnectedException(Exception):
35
+ """ """
36
+
37
+ pass
38
+
39
+
40
+ class ConnectionFailure(DisconnectedException):
41
+ """The agent could not connect to the XMPP server in time."""
42
+
43
+ pass
44
+
45
+
46
+ class Agent(object):
47
+ __slots__ = (
48
+ "jid",
49
+ "password",
50
+ "xmpp_port",
51
+ "verify_security",
52
+ "behaviours",
53
+ "_values",
54
+ "client",
55
+ "presence",
56
+ "loop",
57
+ "container",
58
+ "web",
59
+ "traces",
60
+ "_alive",
61
+ "_stopped",
62
+ "_tasks",
63
+ "__dict__",
64
+ )
65
+
66
+ def __init__(
67
+ self, jid: str, password: str, port: int = 5222, verify_security: bool = False
68
+ ) -> None:
69
+ """
70
+ Creates an agent
71
+
72
+ Args:
73
+ jid (str): The identifier of the agent in the form username@server
74
+ password (str): The password to connect to the server
75
+ port (int): The port of the XMPP server (Default value = 5222). The agent
76
+ connects to the server of its domain (``server``) in that port.
77
+ verify_security (bool): Whether to verify or not the SSL certificates
78
+ """
79
+ self.jid = JID(jid)
80
+ self.password = password
81
+ self.xmpp_port = port
82
+ self.verify_security = verify_security
83
+
84
+ self.behaviours: list[Behaviour] = []
85
+ self._values: dict[str, Any] = {}
86
+
87
+ # created when the agent starts (None until then)
88
+ self.client: XMPPClient = None # type: ignore[assignment]
89
+ self.presence: PresenceManager = None # type: ignore[assignment]
90
+ self.loop: asyncio.AbstractEventLoop | None = None
91
+
92
+ self.container = Container()
93
+ self.container.register(self)
94
+
95
+ self.loop = self.container.loop
96
+
97
+ # Web service
98
+ self.web = WebApp(agent=self)
99
+
100
+ self.traces = TraceStore(size=1000)
101
+
102
+ self._alive = asyncio.Event()
103
+ self._stopped = asyncio.Event() # set while the agent is not alive
104
+ self._stopped.set()
105
+ self._tasks: set[Task[Any]] = (
106
+ set()
107
+ ) # keeps a reference to the tasks of submit()
108
+
109
+ def set_loop(self, loop: asyncio.AbstractEventLoop) -> None:
110
+ self.loop = loop
111
+
112
+ def set_container(self, container: Container) -> None:
113
+ """
114
+ Sets the container to which the agent is attached
115
+
116
+ Args:
117
+ container (spade.container.Container): the container to be attached to
118
+ """
119
+ self.container = container
120
+
121
+ async def start(
122
+ self, auto_register: bool = True, timeout: float | None = 10.0
123
+ ) -> None:
124
+ """
125
+ Starts this agent.
126
+
127
+ Args:
128
+ auto_register (bool): register the agent in the server (Default value = True)
129
+ timeout (float, optional): seconds to wait for the connection to the
130
+ XMPP server, retrying, before raising ``ConnectionFailure``
131
+ (None: no limit) (Default value = 10.0)
132
+
133
+ Returns:
134
+ None
135
+
136
+ Raises:
137
+ ConnectionFailure: if the agent could not connect to the server in time
138
+ AuthenticationFailure: if the server rejected the credentials
139
+ """
140
+ return await self._async_start(auto_register=auto_register, timeout=timeout)
141
+
142
+ async def _async_start(
143
+ self, auto_register: bool = True, timeout: float | None = 10.0
144
+ ) -> None:
145
+ """
146
+ Starts the agent from a coroutine. This fires some actions:
147
+
148
+ * if auto_register: register the agent in the server
149
+ * runs the event loop
150
+ * connects the agent to the server
151
+ * runs the registered behaviours
152
+
153
+ Args:
154
+ auto_register (bool, optional): register the agent in the server (Default value = True)
155
+ timeout (float, optional): seconds to wait for the connection (None: no limit)
156
+
157
+ """
158
+ if self.is_alive():
159
+ logger.warning(f"Agent {self.jid} is already started.")
160
+ return
161
+ # a stopped agent leaves the container: it joins it again
162
+ self.container.register(self)
163
+
164
+ await self._hook_plugin_before_connection()
165
+
166
+ self.client = XMPPClient(
167
+ self.jid, self.password, self.verify_security, auto_register
168
+ )
169
+ # Presence service
170
+ self.presence = PresenceManager(agent=self, approve_all=False)
171
+
172
+ await self._async_connect(timeout=timeout)
173
+
174
+ await self._hook_plugin_after_connection()
175
+
176
+ await self.setup()
177
+ self._alive.set()
178
+ self._stopped.clear()
179
+ for behaviour in self.behaviours:
180
+ if not behaviour.is_running:
181
+ behaviour.set_agent(self)
182
+ if isinstance(behaviour, FSMBehaviour):
183
+ for _, state in behaviour.get_states().items():
184
+ state.set_agent(self)
185
+ behaviour.start()
186
+
187
+ async def _hook_plugin_before_connection(self, *args: Any, **kwargs: Any) -> None:
188
+ """
189
+ Hook for plugins (mixins), run before connecting to the XMPP server.
190
+
191
+ A mixin that overrides it must call
192
+ ``await super()._hook_plugin_before_connection(*args, **kwargs)``
193
+ so that every plugin of the agent is run.
194
+ """
195
+ await self._default_hook_plugin_before_connection()
196
+
197
+ async def _hook_plugin_after_connection(self, *args: Any, **kwargs: Any) -> None:
198
+ """
199
+ Hook for plugins (mixins), run after connecting to the XMPP server and
200
+ before ``setup()``.
201
+
202
+ A mixin that overrides it must call
203
+ ``await super()._hook_plugin_after_connection(*args, **kwargs)``
204
+ so that every plugin of the agent is run.
205
+ """
206
+ await self._default_hook_plugin_after_connection()
207
+
208
+ async def _default_hook_plugin_before_connection(self) -> None:
209
+ """Kept for backwards compatibility: override the hook instead."""
210
+
211
+ async def _default_hook_plugin_after_connection(self) -> None:
212
+ """Kept for backwards compatibility: override the hook instead."""
213
+
214
+ async def _async_connect(self, timeout: float | None = 10.0) -> None:
215
+ """connect and authenticate to the XMPP server. Async mode."""
216
+ client = self.client
217
+ client.connected_event = asyncio.Event()
218
+ client.disconnected_event = asyncio.Event()
219
+ client.failed_auth_event = asyncio.Event()
220
+
221
+ outcome: asyncio.Future[str] = asyncio.get_running_loop().create_future()
222
+ connection_errors: list[Any] = []
223
+
224
+ def finish(event: asyncio.Event, result: str) -> None:
225
+ event.set()
226
+ if not outcome.done():
227
+ outcome.set_result(result)
228
+
229
+ client.add_event_handler(
230
+ "session_start",
231
+ lambda _: finish(client.connected_event, "connected"),
232
+ )
233
+ client.add_event_handler(
234
+ "disconnected",
235
+ lambda _: finish(client.disconnected_event, "disconnected"),
236
+ )
237
+ client.add_event_handler(
238
+ "failed_all_auth",
239
+ lambda _: finish(client.failed_auth_event, "failed_auth"),
240
+ )
241
+ # slixmpp keeps retrying after a failed attempt: remember why it failed
242
+ client.add_event_handler("connection_failed", connection_errors.append)
243
+ client.add_event_handler("message", self._message_received)
244
+
245
+ client.connect(host=self.jid.host, port=self.xmpp_port)
246
+
247
+ try:
248
+ result = await asyncio.wait_for(asyncio.shield(outcome), timeout)
249
+ except TimeoutError:
250
+ client.cancel_connection_attempt()
251
+ client.abort()
252
+ reason = f" ({connection_errors[-1]})" if connection_errors else ""
253
+ raise ConnectionFailure(
254
+ f"Could not connect to the XMPP server at {self.jid.host}:"
255
+ f"{self.xmpp_port} in {timeout} seconds{reason}. Is the server "
256
+ "running? (e.g. 'spade run')"
257
+ ) from None
258
+
259
+ if result == "failed_auth":
260
+ raise AuthenticationFailure(
261
+ "Could not authenticate the agent. Check user and password or use auto_register=True"
262
+ )
263
+ elif result == "disconnected":
264
+ raise DisconnectedException("Error during the connection with the server")
265
+
266
+ logger.info("Agent %s connected and authenticated.", self.jid)
267
+
268
+ async def setup(self) -> None:
269
+ """
270
+ Setup agent before startup.
271
+ This coroutine may be overloaded.
272
+ """
273
+ await asyncio.sleep(0)
274
+
275
+ @property
276
+ def name(self) -> str:
277
+ """
278
+ Returns the name of the agent (the string before the '@')
279
+
280
+ Returns:
281
+ str: the name of the agent (the string before the '@')
282
+ """
283
+ return self.jid.node
284
+
285
+ @property
286
+ def avatar(self) -> str:
287
+ """
288
+ Generates a unique avatar for the agent based on its JID.
289
+ Uses Gravatar service with MonsterID option.
290
+
291
+ Returns:
292
+ str: the url of the agent's avatar
293
+
294
+ """
295
+ return self.build_avatar_url(self.jid.bare)
296
+
297
+ @staticmethod
298
+ def build_avatar_url(jid: str) -> str:
299
+ """
300
+ Static method to build a gravatar url with the agent's JID
301
+
302
+ Args:
303
+ jid (aioxmpp.JID): an XMPP identifier
304
+
305
+ Returns:
306
+ str: a URL for the gravatar
307
+
308
+ """
309
+ digest = md5(str(jid).encode("utf-8")).hexdigest() # nosec
310
+ return "http://www.gravatar.com/avatar/{md5}?d=monsterid".format(md5=digest)
311
+
312
+ def submit(self, coro: Coroutine[Any, Any, T]) -> Task[T]:
313
+ """
314
+ Runs a coroutine in the event loop of the agent.
315
+ this call is not blocking.
316
+
317
+ Args:
318
+ coro (Coroutine): the coroutine to be run
319
+
320
+ Returns:
321
+ asyncio.Task: the Task assigned to the coroutine execution
322
+
323
+ """
324
+ task = asyncio.create_task(coro)
325
+ # the event loop keeps only weak references to its tasks
326
+ self._tasks.add(task)
327
+ task.add_done_callback(self._tasks.discard)
328
+ return task
329
+
330
+ def add_behaviour(
331
+ self, behaviour: Behaviour, template: Template | None = None
332
+ ) -> None:
333
+ """
334
+ Adds and starts a behaviour to the agent.
335
+ If template is not None it is used to match
336
+ new messages and deliver them to the behaviour.
337
+
338
+ Args:
339
+ behaviour (spade.behaviour.Behaviour): the behaviour to be started (of any kind)
340
+ template (spade.template.Template, optional): the template to match messages with (Default value = None)
341
+
342
+ """
343
+ behaviour.set_agent(agent=self)
344
+ if isinstance(behaviour, FSMBehaviour):
345
+ for _, state in behaviour.get_states().items():
346
+ state.set_agent(self)
347
+ behaviour.set_template(template)
348
+ self.behaviours.append(behaviour)
349
+ if self.is_alive():
350
+ behaviour.start()
351
+
352
+ def remove_behaviour(self, behaviour: Behaviour) -> None:
353
+ """
354
+ Removes a behaviour from the agent.
355
+ The behaviour is first killed.
356
+
357
+ Args:
358
+ behaviour (spade.behaviour.Behaviour): the behaviour instance to be removed
359
+
360
+ """
361
+ if not self.has_behaviour(behaviour):
362
+ raise ValueError("This behaviour is not registered")
363
+ self.behaviours.remove(behaviour)
364
+ behaviour.kill()
365
+
366
+ def _behaviour_finished(self, behaviour: Behaviour) -> None:
367
+ """Run by a behaviour when it ends: it is unregistered if it still is."""
368
+ if behaviour in self.behaviours:
369
+ self.behaviours.remove(behaviour)
370
+
371
+ def has_behaviour(self, behaviour: Behaviour) -> bool:
372
+ """
373
+ Checks if a behaviour is added to an agent.
374
+
375
+ Args:
376
+ behaviour (spade.behaviour.Behaviour): the behaviour instance to check
377
+
378
+ Returns:
379
+ bool: a boolean that indicates wether the behaviour is inside the agent.
380
+
381
+ """
382
+ return behaviour in self.behaviours
383
+
384
+ async def stop(self, timeout: float = 5.0) -> None:
385
+ """
386
+ Stops this agent.
387
+
388
+ Its behaviours are killed: the ``run()`` of a behaviour waiting for a
389
+ message (or for its next period) is interrupted, and the behaviours end
390
+ running their ``on_end()`` while the agent is still connected. The
391
+ behaviours still running after ``timeout`` seconds are cancelled (their
392
+ ``on_end()`` is run too).
393
+
394
+ Args:
395
+ timeout (float): seconds to wait for the behaviours to end (Default value = 5.0)
396
+ """
397
+ return await self._async_stop(timeout=timeout)
398
+
399
+ async def _async_stop(self, timeout: float = 5.0) -> None:
400
+ """Stops an agent and kills all its behaviours."""
401
+ if self.presence:
402
+ self.presence.set_unavailable()
403
+ behaviours = list(self.behaviours)
404
+ for behav in behaviours:
405
+ behav.kill()
406
+ await self._wait_behaviours(behaviours, timeout)
407
+ await self.web.stop()
408
+
409
+ if self.is_alive():
410
+ # Disconnect from XMPP server
411
+ await self.client.disconnect()
412
+ logger.info("Client disconnected.")
413
+
414
+ # slixmpp leaves its sending loop running after disconnecting (it is only
415
+ # cancelled when the client is garbage collected): one task per agent
416
+ sending_loop = getattr(self.client, "_run_out_filters", None)
417
+ if sending_loop is not None and not sending_loop.done():
418
+ sending_loop.cancel()
419
+ await asyncio.wait([sending_loop])
420
+
421
+ self._alive.clear()
422
+ self._stopped.set()
423
+ # the messages sent to it from this process go through XMPP from now on
424
+ if (
425
+ self.container.has_agent(str(self.jid))
426
+ and self.container.get_agent(str(self.jid)) is self
427
+ ):
428
+ self.container.unregister(self.jid)
429
+
430
+ @staticmethod
431
+ async def _wait_behaviours(behaviours: list[Behaviour], timeout: float) -> None:
432
+ """Waits for the (killed) behaviours to end, and cancels the late ones."""
433
+ # A behaviour stopping its own agent, directly or from a task it created
434
+ # (e.g. asyncio.gather), is not waited for: it ends after stop() returns.
435
+ current = asyncio.current_task()
436
+ caller = running_behaviour.get()
437
+ tasks = {
438
+ b._task
439
+ for b in behaviours
440
+ if b._task is not None
441
+ and b._task is not current
442
+ and b is not caller
443
+ and not b._task.done()
444
+ }
445
+ if not tasks:
446
+ return
447
+ _, pending = await asyncio.wait(tasks, timeout=timeout)
448
+ if pending:
449
+ logger.warning(
450
+ f"Cancelling {len(pending)} behaviour(s) still running {timeout}s "
451
+ "after stopping the agent."
452
+ )
453
+ for task in pending:
454
+ task.cancel()
455
+ await asyncio.wait(pending, timeout=1.0)
456
+
457
+ async def __aenter__(self) -> Self:
458
+ """
459
+ ``async with Agent(jid, password) as agent:`` starts the agent (with the
460
+ default arguments of ``start()``) and stops it at the end of the block,
461
+ even if an exception is raised.
462
+ """
463
+ await self.start()
464
+ return self
465
+
466
+ async def __aexit__(
467
+ self,
468
+ exc_type: type[BaseException] | None,
469
+ exc: BaseException | None,
470
+ traceback: TracebackType | None,
471
+ ) -> None:
472
+ await self.stop()
473
+
474
+ async def send(self, msg: Message) -> None:
475
+ """
476
+ Sends a message from the agent itself, outside its behaviours (e.g. from
477
+ ``setup()`` or from the main coroutine).
478
+
479
+ The sender is the agent if it is not set. As ``behaviour.send()``, the
480
+ message is delivered directly to a receiver in the same process, or
481
+ through XMPP otherwise.
482
+
483
+ Args:
484
+ msg (spade.message.Message): the message to be sent.
485
+
486
+ Raises:
487
+ RuntimeError: if the agent is not started.
488
+ """
489
+ if not self.is_alive():
490
+ raise RuntimeError(
491
+ f"Agent {self.jid} cannot send messages: it is not started"
492
+ )
493
+ if msg.empty_sender():
494
+ msg.sender = str(self.jid)
495
+ await self.container.send(msg, self)
496
+ msg.sent = True
497
+ self.traces.append(msg)
498
+
499
+ async def _xmpp_send(self, msg: Message) -> None:
500
+ msg.prepare(self.client).send()
501
+
502
+ async def _wait_until_stopped(self) -> None:
503
+ """Waits until the agent is stopped (it returns at once if it is not alive)."""
504
+ await self._stopped.wait()
505
+
506
+ def is_alive(self) -> bool:
507
+ """
508
+ Checks if the agent is alive.
509
+
510
+ Returns:
511
+ bool: wheter the agent is alive or not
512
+
513
+ """
514
+ return self._alive.is_set()
515
+
516
+ def set(self, name: str, value: Any) -> None:
517
+ """
518
+ Stores a knowledge item in the agent knowledge base.
519
+
520
+ Args:
521
+ name (str): name of the item
522
+ value (object): value of the item
523
+
524
+ """
525
+ self._values[name] = value
526
+
527
+ def get(self, name: str) -> Any:
528
+ """
529
+ Recovers a knowledge item from the agent's knowledge base.
530
+
531
+ Args:
532
+ name(str): name of the item
533
+
534
+ Returns:
535
+ object: the object retrieved or None
536
+
537
+ """
538
+ if name in self._values:
539
+ return self._values[name]
540
+ else:
541
+ return None
542
+
543
+ def _message_received(self, msg: slixmppMessage) -> list[asyncio.Future[Any]]:
544
+ """
545
+ Callback run when an XMPP Message is reveived.
546
+ This callback delivers the message to every behaviour
547
+ that is waiting for it. First, the aioxmpp.Message is
548
+ converted to spade.message.Message
549
+
550
+ Args:
551
+ msg (slixmpp.Message): the message just received.
552
+
553
+ Returns:
554
+ list(asyncio.Future): a list of futures of the appended of the message at each matched behaviour.
555
+
556
+ """
557
+
558
+ return self.dispatch(Message.from_node(msg))
559
+
560
+ def dispatch(self, msg: Message) -> list[asyncio.Future[Any]]:
561
+ """
562
+ Dispatch the message to every behaviour that is waiting for
563
+ it using their templates match.
564
+
565
+ Args:
566
+ msg (spade.message.Message): the message to dispatch.
567
+
568
+ Returns:
569
+ list(asyncio.Future): a future for the queuing of the message in each matching behaviour.
570
+
571
+ """
572
+ logger.debug("Got message: %s", msg)
573
+ tasks: list[asyncio.Future[Any]] = []
574
+ matched = False
575
+ for behaviour in (x for x in self.behaviours if x.match(msg)):
576
+ if getattr(behaviour.enqueue, "__func__", None) is Behaviour.enqueue:
577
+ # straight to the mailbox: no task per message and behaviour
578
+ behaviour.queue.put_nowait(msg)
579
+ queued = asyncio.get_running_loop().create_future()
580
+ queued.set_result(None)
581
+ tasks.append(queued)
582
+ else: # enqueue() overridden (e.g. to wake up the behaviour)
583
+ tasks.append(self.submit(behaviour.enqueue(msg)))
584
+ logger.debug("Message enqueued to behaviour: %s", behaviour)
585
+ self.traces.append(msg, category=str(behaviour))
586
+ matched = True
587
+ if not matched:
588
+ logger.warning(f"No behaviour matched for message: {msg}")
589
+ self.traces.append(msg)
590
+ return tasks