forked from MycroftAI/mycroft-core
-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathskill_manager.py
More file actions
601 lines (512 loc) · 24.2 KB
/
skill_manager.py
File metadata and controls
601 lines (512 loc) · 24.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# Copyright 2017 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Load, update and manage skills on this device."""
import os
import threading
from threading import Thread, Event
from ovos_bus_client.apis.enclosure import EnclosureAPI
from ovos_bus_client.client import MessageBusClient
from ovos_bus_client.message import Message
from ovos_bus_client.util.scheduler import EventScheduler
from ovos_config.config import Configuration
from ovos_config.locations import get_xdg_config_save_path
from ovos_utils.file_utils import FileWatcher
from ovos_utils.gui import is_gui_connected
from ovos_utils.log import LOG
from ovos_utils.network_utils import is_connected_http
from ovos_utils.process_utils import ProcessStatus, StatusCallbackMap, ProcessState
from ovos_workshop.skill_launcher import PluginSkillLoader
from ovos_core.skill_installer import SkillsStore
from ovos_core.intent_services import IntentService
from ovos_workshop.skills.api import SkillApi
from ovos_plugin_manager.skills import find_skill_plugins
def on_started():
LOG.info('Skills Manager is starting up.')
def on_alive():
LOG.info('Skills Manager is alive.')
def on_ready():
LOG.info('Skills Manager is ready.')
def on_error(e='Unknown'):
LOG.info(f'Skills Manager failed to launch ({e})')
def on_stopping():
LOG.info('Skills Manager is shutting down...')
class SkillManager(Thread):
"""Manages the loading, activation, and deactivation of Mycroft skills."""
def __init__(self, bus, watchdog=None, alive_hook=on_alive, started_hook=on_started, ready_hook=on_ready,
error_hook=on_error, stopping_hook=on_stopping,
enable_installer=False,
enable_intent_service=False,
enable_event_scheduler=False,
enable_file_watcher=True,
enable_skill_api=False):
"""Constructor
Args:
bus (event emitter): Mycroft messagebus connection
watchdog (callable): optional watchdog function
alive_hook (callable): callback function for skill alive status
started_hook (callable): callback function for skill started status
ready_hook (callable): callback function for skill ready status
error_hook (callable): callback function for skill error status
stopping_hook (callable): callback function for skill stopping status
"""
super(SkillManager, self).__init__()
self.bus = bus
self._settings_watchdog = None
# Set watchdog to argument or function returning None
self._watchdog = watchdog or (lambda: None)
callbacks = StatusCallbackMap(on_started=started_hook,
on_alive=alive_hook,
on_ready=ready_hook,
on_error=error_hook,
on_stopping=stopping_hook)
self.status = ProcessStatus('skills', callback_map=callbacks)
self.status.set_started()
self._setup_event = Event()
self._stop_event = Event()
self._connected_event = Event()
self._network_event = Event()
self._gui_event = Event()
self._network_loaded = Event()
self._internet_loaded = Event()
self._network_skill_timeout = 300
self._allow_state_reloads = True
self._logged_skill_warnings = list()
self._detected_installed_skills = bool(find_skill_plugins())
if not self._detected_installed_skills:
LOG.warning(
"No installed skills detected! if you are running skills in standalone mode ignore this warning,"
" otherwise you probably want to install skills first!")
self.config = Configuration()
self.plugin_skills = {}
self.enclosure = EnclosureAPI(bus)
self.num_install_retries = 0
self.empty_skill_dirs = set() # Save a record of empty skill dirs.
self._define_message_bus_events()
self.daemon = True
self.status.bind(self.bus)
# init subsystems
self.osm = SkillsStore(self.bus) if enable_installer else None
self.event_scheduler = EventScheduler(self.bus, autostart=False) if enable_event_scheduler else None
if self.event_scheduler:
self.event_scheduler.daemon = True # TODO - add kwarg in EventScheduler
self.event_scheduler.start()
self.intents = IntentService(self.bus) if enable_intent_service else None
if enable_skill_api:
SkillApi.connect_bus(self.bus)
if enable_file_watcher:
self._init_filewatcher()
@property
def blacklist(self):
"""Get the list of blacklisted skills from the configuration.
Returns:
list: List of blacklisted skill ids.
"""
return Configuration().get("skills", {}).get("blacklisted_skills", [])
def _init_filewatcher(self):
"""Initialize the file watcher to monitor skill settings files for changes."""
sspath = f"{get_xdg_config_save_path()}/skills/"
os.makedirs(sspath, exist_ok=True)
self._settings_watchdog = FileWatcher([sspath],
callback=self._handle_settings_file_change,
recursive=True,
ignore_creation=True)
def _handle_settings_file_change(self, path: str):
"""Handle changes to skill settings files.
Args:
path (str): Path to the settings file that has changed.
"""
if path.endswith("/settings.json"):
skill_id = path.split("/")[-2]
LOG.info(f"skill settings.json change detected for {skill_id}")
self.bus.emit(Message("ovos.skills.settings_changed",
{"skill_id": skill_id}))
def _sync_skill_loading_state(self):
"""Synchronize the loading state of skills with the current system state."""
resp = self.bus.wait_for_response(Message("ovos.PHAL.internet_check"))
network = False
internet = False
if not self._gui_event.is_set() and is_gui_connected(self.bus):
self._gui_event.set()
if resp:
if resp.data.get('internet_connected'):
network = internet = True
elif resp.data.get('network_connected'):
network = True
else:
LOG.debug("ovos-phal-plugin-connectivity-events not detected, performing direct network checks")
network = internet = is_connected_http()
if internet and not self._connected_event.is_set():
LOG.debug("Notify internet connected")
self.bus.emit(Message("mycroft.internet.connected"))
elif network and not self._network_event.is_set():
LOG.debug("Notify network connected")
self.bus.emit(Message("mycroft.network.connected"))
def _define_message_bus_events(self):
"""Define message bus events with handlers defined in this class."""
# Update upon request
self.bus.on('skillmanager.list', self.send_skill_list)
self.bus.on('skillmanager.deactivate', self.deactivate_skill)
self.bus.on('skillmanager.keep', self.deactivate_except)
self.bus.on('skillmanager.activate', self.activate_skill)
# Load skills waiting for connectivity
self.bus.on("mycroft.network.connected", self.handle_network_connected)
self.bus.on("mycroft.internet.connected", self.handle_internet_connected)
self.bus.on("mycroft.gui.available", self.handle_gui_connected)
self.bus.on("mycroft.network.disconnected", self.handle_network_disconnected)
self.bus.on("mycroft.internet.disconnected", self.handle_internet_disconnected)
self.bus.on("mycroft.gui.unavailable", self.handle_gui_disconnected)
@property
def skills_config(self):
"""Get the skills service configuration.
Returns:
dict: Skills configuration.
"""
return self.config['skills']
def handle_gui_connected(self, message):
"""Handle GUI connection event.
Args:
message: Message containing information about the GUI connection.
"""
# Some GUI extensions, such as mobile, may request that skills never unload
self._allow_state_reloads = not message.data.get("permanent", False)
if not self._gui_event.is_set():
LOG.debug("GUI Connected")
self._gui_event.set()
self._load_new_skills()
def handle_gui_disconnected(self, message):
"""Handle GUI disconnection event.
Args:
message: Message containing information about the GUI disconnection.
"""
if self._allow_state_reloads:
self._gui_event.clear()
self._unload_on_gui_disconnect()
def handle_internet_disconnected(self, message):
"""Handle internet disconnection event.
Args:
message: Message containing information about the internet disconnection.
"""
if self._allow_state_reloads:
self._connected_event.clear()
self._unload_on_internet_disconnect()
def handle_network_disconnected(self, message):
"""Handle network disconnection event.
Args:
message: Message containing information about the network disconnection.
"""
if self._allow_state_reloads:
self._network_event.clear()
self._unload_on_network_disconnect()
def handle_internet_connected(self, message):
"""Handle internet connection event.
Args:
message: Message containing information about the internet connection.
"""
if not self._connected_event.is_set():
LOG.debug("Internet Connected")
self._network_event.set()
self._connected_event.set()
self._load_on_internet()
def handle_network_connected(self, message):
"""Handle network connection event.
Args:
message: Message containing information about the network connection.
"""
if not self._network_event.is_set():
LOG.debug("Network Connected")
self._network_event.set()
self._load_on_network()
def load_plugin_skills(self, network=None, internet=None):
"""Load plugin skills based on network and internet status.
Args:
network (bool): Network connection status.
internet (bool): Internet connection status.
"""
loaded_new = False
if network is None:
network = self._network_event.is_set()
if internet is None:
internet = self._connected_event.is_set()
plugins = find_skill_plugins()
for skill_id, plug in plugins.items():
if skill_id in self.blacklist:
if skill_id not in self._logged_skill_warnings:
self._logged_skill_warnings.append(skill_id)
LOG.warning(f"{skill_id} is blacklisted, it will NOT be loaded")
LOG.info(f"Consider uninstalling {skill_id} instead of blacklisting it")
continue
if skill_id not in self.plugin_skills:
skill_loader = self._get_plugin_skill_loader(skill_id, init_bus=False,
skill_class=plug)
requirements = skill_loader.runtime_requirements
if not network and requirements.network_before_load:
continue
if not internet and requirements.internet_before_load:
continue
self._load_plugin_skill(skill_id, plug)
loaded_new = True
return loaded_new
def _get_internal_skill_bus(self):
"""Get a dedicated skill bus connection per skill.
Returns:
MessageBusClient: Internal skill bus.
"""
if not self.config["websocket"].get("shared_connection", True):
# See BusBricker skill to understand why this matters.
# Any skill can manipulate the bus from other skills.
# This patch ensures each skill gets its own connection that can't be manipulated by others.
# https://github.com/EvilJarbas/BusBrickerSkill
bus = MessageBusClient(cache=True)
bus.run_in_thread()
else:
bus = self.bus
return bus
def _get_plugin_skill_loader(self, skill_id, init_bus=True, skill_class=None):
"""Get a plugin skill loader.
Args:
skill_id (str): ID of the skill.
init_bus (bool): Whether to initialize the internal skill bus.
Returns:
PluginSkillLoader: Plugin skill loader instance.
"""
bus = None
if init_bus:
bus = self._get_internal_skill_bus()
loader = PluginSkillLoader(bus, skill_id)
if skill_class:
loader.skill_class = skill_class
return loader
def _load_plugin_skill(self, skill_id, skill_plugin):
"""Load a plugin skill.
Args:
skill_id (str): ID of the skill.
skill_plugin: Plugin skill instance.
Returns:
PluginSkillLoader: Loaded plugin skill loader instance if successful, None otherwise.
"""
skill_loader = self._get_plugin_skill_loader(skill_id, skill_class=skill_plugin)
try:
load_status = skill_loader.load(skill_plugin)
if load_status:
self.bus.emit(Message("mycroft.skill.loaded", {"skill_id": skill_id}))
except Exception:
LOG.exception(f'Load of skill {skill_id} failed!')
load_status = False
finally:
self.plugin_skills[skill_id] = skill_loader
return skill_loader if load_status else None
def wait_for_intent_service(self):
"""ensure IntentService reported ready to accept skill messages"""
while not self._stop_event.is_set():
response = self.bus.wait_for_response(
Message('mycroft.intents.is_ready',
context={"source": "skills", "destination": "intents"}),
timeout=5)
if response and response.data.get('status'):
return
threading.Event().wait(1)
raise RuntimeError("Skill manager stopped while waiting for intent service")
def run(self):
"""Run the skill manager thread."""
self.status.set_alive()
LOG.debug("Waiting for IntentService startup")
self.wait_for_intent_service()
LOG.debug("IntentService reported ready")
self._load_on_startup()
# trigger a sync so we dont need to wait for the plugin to volunteer info
self._sync_skill_loading_state()
if not all((self._network_loaded.is_set(),
self._internet_loaded.is_set())):
self.bus.emit(Message(
'mycroft.skills.error',
{'internet_loaded': self._internet_loaded.is_set(),
'network_loaded': self._network_loaded.is_set()}))
self.bus.emit(Message('mycroft.skills.initialized'))
self.status.set_ready()
LOG.info("ovos-core is ready! additional skills can now be loaded")
# Scan the file folder that contains Skills. If a Skill is updated,
# unload the existing version from memory and reload from the disk.
while not self._stop_event.wait(30):
try:
self._load_new_skills()
self._watchdog()
except Exception:
LOG.exception('Something really unexpected has occurred '
'and the skill manager loop safety harness was '
'hit.')
def _load_on_network(self):
"""Load skills that require a network connection."""
if self._detected_installed_skills: # ensure we have skills installed
LOG.info('Loading skills that require network...')
self._load_new_skills(network=True, internet=False)
self._network_loaded.set()
def _load_on_internet(self):
"""Load skills that require both internet and network connections."""
if self._detected_installed_skills: # ensure we have skills installed
LOG.info('Loading skills that require internet (and network)...')
self._load_new_skills(network=True, internet=True)
self._internet_loaded.set()
self._network_loaded.set()
def _unload_on_network_disconnect(self):
"""Unload skills that require a network connection to work."""
# TODO - implementation missing
def _unload_on_internet_disconnect(self):
"""Unload skills that require an internet connection to work."""
# TODO - implementation missing
def _unload_on_gui_disconnect(self):
"""Unload skills that require a GUI to work."""
# TODO - implementation missing
def _load_on_startup(self):
"""Handle offline skills load on startup."""
if self._detected_installed_skills: # ensure we have skills installed
LOG.info('Loading offline skills...')
self._load_new_skills(network=False, internet=False)
def _load_new_skills(self, network=None, internet=None, gui=None):
"""Handle loading of skills installed since startup.
Args:
network (bool): Network connection status.
internet (bool): Internet connection status.
gui (bool): GUI connection status.
"""
if network is None:
network = self._network_event.is_set()
if internet is None:
internet = self._connected_event.is_set()
if gui is None:
gui = self._gui_event.is_set() or is_gui_connected(self.bus)
loaded_new = self.load_plugin_skills(network=network, internet=internet)
if loaded_new:
LOG.debug("Requesting pipeline intent training")
try:
response = self.bus.wait_for_response(Message("mycroft.skills.train"),
"mycroft.skills.trained",
timeout=60) # 60 second timeout
if not response:
LOG.error("Intent training timed out")
elif response.data.get('error'):
LOG.error(f"Intent training failed: {response.data['error']}")
else:
LOG.debug(f"pipelines trained and ready to go")
except Exception as e:
LOG.exception(f"Error during Intent training: {e}")
def _unload_plugin_skill(self, skill_id):
"""Unload a plugin skill.
Args:
skill_id (str): Identifier of the plugin skill to unload.
"""
if skill_id in self.plugin_skills:
LOG.info('Unloading plugin skill: ' + skill_id)
skill_loader = self.plugin_skills[skill_id]
if skill_loader.instance is not None:
try:
skill_loader.instance.shutdown()
except Exception:
LOG.exception('Failed to run skill specific shutdown code: ' + skill_loader.skill_id)
try:
skill_loader.instance.default_shutdown()
except Exception:
LOG.exception('Failed to shutdown skill: ' + skill_loader.skill_id)
self.plugin_skills.pop(skill_id)
def is_alive(self, message=None):
"""Respond to is_alive status request."""
return self.status.state >= ProcessState.ALIVE
def is_all_loaded(self, message=None):
""" Respond to all_loaded status request."""
return self.status.state == ProcessState.READY
def send_skill_list(self, message=None):
"""Send list of loaded skills."""
try:
message_data = {}
# TODO handle external skills, OVOSAbstractApp/Hivemind skills are not accounted for
skills = self.plugin_skills
for skill_loader in skills.values():
message_data[skill_loader.skill_id] = {
"active": skill_loader.active and skill_loader.loaded,
"id": skill_loader.skill_id}
self.bus.emit(Message('mycroft.skills.list', data=message_data))
except Exception:
LOG.exception('Failed to send skill list')
def deactivate_skill(self, message):
"""Deactivate a skill."""
try:
# TODO handle external skills, OVOSAbstractApp/Hivemind skills are not accounted for
skills = self.plugin_skills
for skill_loader in skills.values():
if message.data['skill'] == skill_loader.skill_id:
LOG.info("Deactivating (unloading) skill: " + skill_loader.skill_id)
skill_loader.deactivate()
self.bus.emit(message.response())
except Exception as err:
LOG.exception('Failed to deactivate ' + message.data['skill'])
self.bus.emit(message.response({'error': f'failed: {err}'}))
def deactivate_except(self, message):
"""Deactivate all skills except the provided."""
try:
skill_to_keep = message.data['skill']
LOG.info(f'Deactivating (unloading) all skills except {skill_to_keep}')
# TODO handle external skills, OVOSAbstractApp/Hivemind skills are not accounted for
skills = self.plugin_skills
for skill in skills.values():
if skill.skill_id != skill_to_keep:
skill.deactivate()
LOG.info('Couldn\'t find skill ' + message.data['skill'])
except Exception:
LOG.exception('An error occurred during skill deactivation!')
def activate_skill(self, message):
"""Activate a deactivated skill."""
try:
# TODO handle external skills, OVOSAbstractApp/Hivemind skills are not accounted for
skills = self.plugin_skills
for skill_loader in skills.values():
if (message.data['skill'] in ('all', skill_loader.skill_id)
and not skill_loader.active):
skill_loader.activate()
self.bus.emit(message.response())
except Exception as err:
LOG.exception(f'Couldn\'t activate (load) skill {message.data["skill"]}')
self.bus.emit(message.response({'error': f'failed: {err}'}))
def stop(self):
"""alias for shutdown (backwards compat)"""
return self.shutdown()
def shutdown(self):
"""Tell the manager to shutdown."""
self.status.set_stopping()
self._stop_event.set()
# Do a clean shutdown of all skills
for skill_id in list(self.plugin_skills.keys()):
try:
self._unload_plugin_skill(skill_id)
except Exception as e:
LOG.error(f"Failed to cleanly unload skill '{skill_id}' ({e})")
if self.intents:
try:
self.intents.shutdown()
except Exception as e:
LOG.error(f"Failed to cleanly unload intent service ({e})")
if self.osm:
try:
self.osm.shutdown()
except Exception as e:
LOG.error(f"Failed to cleanly unload skill installer ({e})")
if self.event_scheduler:
try:
self.event_scheduler.shutdown()
except Exception as e:
LOG.error(f"Failed to cleanly unload event scheduler ({e})")
if self._settings_watchdog:
try:
self._settings_watchdog.shutdown()
except Exception as e:
LOG.error(f"Failed to cleanly unload settings watchdog ({e})")