From fdcca005a4dd62a55476f013945a5930d4f88f53 Mon Sep 17 00:00:00 2001 From: A_D Date: Sun, 18 Oct 2020 09:48:23 +0200 Subject: [PATCH 01/40] Added name mangling support to EDMCContextFilter Python name mangling is more about name collisions than actually making things private. This commit adds a check to resolve mangled names to their runtime names, and adds a just-in-case default to fetching the attribute. Fixes #764 --- EDMCLogging.py | 8 ++++++-- EDMarketConnector.py | 4 ++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/EDMCLogging.py b/EDMCLogging.py index 246ee78d..846dba84 100644 --- a/EDMCLogging.py +++ b/EDMCLogging.py @@ -287,11 +287,15 @@ class EDMCContextFilter(logging.Filter): frame_info = inspect.getframeinfo(frame) args, _, _, value_dict = inspect.getargvalues(frame) if len(args) and args[0] in ('self', 'cls'): - frame_class = value_dict[args[0]] + frame_class: 'object' = value_dict[args[0]] if frame_class: + # See https://en.wikipedia.org/wiki/Name_mangling#Python for how name mangling works. + if (name := frame_info.function).startswith("__") and not name.endswith("__"): + name = f'_{frame_class.__class__.__name__}{frame_info.function}' + # Find __qualname__ of the caller - fn = getattr(frame_class, frame_info.function) + fn = getattr(frame_class, name, None) if fn and fn.__qualname__: caller_qualname = fn.__qualname__ diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 90ff631f..63cc2f6f 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1165,6 +1165,10 @@ sys.path: {sys.path}''' def __init__(self): logger.debug('A call from A.B.__init__') + self.__test() + + def __test(self): + logger.debug("A call from A.B.__test") # abinit = A.B() From 0f3c784f33e38f2640abb74647b5591911c3277d Mon Sep 17 00:00:00 2001 From: Athanasius Date: Sun, 18 Oct 2020 12:05:28 +0100 Subject: [PATCH 02/40] Logging: Backport name mangling support for Python 3.7 --- EDMCLogging.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/EDMCLogging.py b/EDMCLogging.py index 846dba84..308e85fc 100644 --- a/EDMCLogging.py +++ b/EDMCLogging.py @@ -291,7 +291,8 @@ class EDMCContextFilter(logging.Filter): if frame_class: # See https://en.wikipedia.org/wiki/Name_mangling#Python for how name mangling works. - if (name := frame_info.function).startswith("__") and not name.endswith("__"): + name = frame_info.function + if name.startswith("__") and not name.endswith("__"): name = f'_{frame_class.__class__.__name__}{frame_info.function}' # Find __qualname__ of the caller From 57f3e08f85a2aabd9dc0b944b55c07702747f8d1 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 26 Oct 2020 13:45:28 +0000 Subject: [PATCH 03/40] requirements: py2exe now on pypi, bump to 0.10.0.2 Confirmed working with python 3.7.9 --- requirements-dev.txt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 7f756495..b50ae664 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -20,9 +20,8 @@ autopep8==1.5.4 grip>=4.5.2 # Packaging -# This isn't available via 'pip install', so has to be commented out in order for -# GitHub Action Workflows to not error out -#py2exe==0.9.3.2 +# We only need py2exe on windows. +py2exe==0.10.0.2; sys_platform == 'win32' # All of the normal requirements -r requirements.txt From a65d77a67ed90dd36a0c8fecbaeab3baaf5ad1e4 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Fri, 18 Dec 2020 12:32:45 +0000 Subject: [PATCH 04/40] PLUGINS.md: Make the disctinction between "ShutDown" and "Shutdown" clear --- PLUGINS.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/PLUGINS.md b/PLUGINS.md index 00d48155..3ab73734 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -418,8 +418,16 @@ running. In this case you won't receive initial events such as "LoadGame", "Rank", "Location", etc. However the `state` dictionary will reflect the cumulative effect of these missed events. -Similarly, a special "ShutDown" entry is sent when the game is quitted while -EDMC is running. This event is not sent when EDMC is running on a different +Similarly, a special "ShutDown" entry is sent when the game stops writing +to the Journal without writing a "Shutdown" event. +This might happen, for example, when the game client crashes. +Note that this is distinct in (letter) case from the "Shutdown" event that +the game itself writes to the Journal when you exit normally. If you want to +react to either in your plugin code then either compare in a case insensitive +manner or check for both. The difference in case allows you to differentiate +between the two scenarios. + +This event is not sent when EDMC is running on a different machine so you should not *rely* on receiving this event. #### Player Dashboard From 1cb876c594d251eeac00314646fda4a9af1b6c08 Mon Sep 17 00:00:00 2001 From: A_D Date: Mon, 21 Dec 2020 12:27:19 +0200 Subject: [PATCH 05/40] Added support for logging from properties This is some best effort support for using logging in properties. This works by using the (as suggested by reporter) inspect `getattr_static` method, and failing that (as it can possibly fail), wrapping a `getattr` in a try/catch for a RecursionError--don't want to catch other things, probably best if that explodes on its own. From there as the `property` object will not have location information, we rebuild as best we can to an approximation of what the path would be. With a healthy dash of defensive programming "Just in case". I don't think that this will have any adverse effects to other logging methods, as all the new code should only be touched if we hit a property object. Closes #808 --- EDMCLogging.py | 29 ++++++++++++++++++++++++++--- EDMarketConnector.py | 10 ++++++++-- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/EDMCLogging.py b/EDMCLogging.py index 308e85fc..4df210f8 100644 --- a/EDMCLogging.py +++ b/EDMCLogging.py @@ -296,9 +296,32 @@ class EDMCContextFilter(logging.Filter): name = f'_{frame_class.__class__.__name__}{frame_info.function}' # Find __qualname__ of the caller - fn = getattr(frame_class, name, None) - if fn and fn.__qualname__: - caller_qualname = fn.__qualname__ + fn = inspect.getattr_static(frame_class, name, None) + if fn is None: + # For some reason getattr_static cant grab this. Try and grab it with getattr, bail out + # if we get a RecursionError indicating a property + try: + fn = getattr(frame_class, name, None) + except RecursionError: + print( + "EDMCLogging:EDMCContextFilter:caller_attributes():" + "Failed to get attribute for function info. Bailing out" + ) + return "??", "??", "??" + + if fn is not None: + if isinstance(fn, property): + class_name = str(frame_class) + # If somehow you make your __class__ or __class__.__qualname__ recursive, I'll be impressed. + if hasattr(frame_class, '__class__') and hasattr(frame_class.__class__, "__qualname__"): + class_name = frame_class.__class__.__qualname__ + caller_qualname = f"{class_name}.{name}(property)" + + else: + caller_qualname = f"" + + elif fn.__qualname__: + caller_qualname = fn.__qualname__ # Find containing class name(s) of caller, if any if frame_class.__class__ and frame_class.__class__.__qualname__: diff --git a/EDMarketConnector.py b/EDMarketConnector.py index b1b2a55f..8e30cba5 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1238,7 +1238,6 @@ executable: {sys.executable} sys.path: {sys.path}''' ) - # We prefer a UTF-8 encoding gets set, but older Windows versions have # issues with this. From Windows 10 1903 onwards we can rely on the # manifest ActiveCodePage to set this, but that is silently ignored on @@ -1287,7 +1286,8 @@ sys.path: {sys.path}''' logger.exception(f"Could not set LC_ALL to ('{locale_startup[0]}', 'UTF_8')") except Exception: - logger.exception(f"Exception other than locale.Error on setting LC_ALL=('{locale_startup[0]}', 'UTF_8')") + logger.exception( + f"Exception other than locale.Error on setting LC_ALL=('{locale_startup[0]}', 'UTF_8')") else: log_locale('After switching to UTF-8 encoding (same language)') @@ -1303,10 +1303,16 @@ sys.path: {sys.path}''' def __init__(self): logger.debug('A call from A.B.__init__') self.__test() + _ = self.test_prop def __test(self): logger.debug("A call from A.B.__test") + @property + def test_prop(self): + logger.debug("test log from property") + return "Test property is testy" + # abinit = A.B() # Plain, not via `logger` From c1dcd30280178d289c70749fc0ca080efe6beb5a Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 21 Dec 2020 14:44:39 +0000 Subject: [PATCH 06/40] PLUGINS.md: Be explicit about why plugin_prefs(...) -> Optional[tk.Frame] --- PLUGINS.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/PLUGINS.md b/PLUGINS.md index 3ab73734..036715e6 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -225,6 +225,11 @@ with core EDMC or other plugins.** Use `numberFromString()` from EDMC's `l10n.Locale` object to parse input numbers in a locale-independent way. +Note that in the following example the function signature defines that it +returns `Optional[tk.Frame]` only because we need to allow for `None` if +something goes wrong with the creation of the frame (the calling code checks +this). You absolutely need to return the `nb.Frame()` instance that you get +as in the code below. ```python import tkinter as tk from tkinter import ttk From b04b39fa8afafe78fd4814d1706e3457dd0c79b9 Mon Sep 17 00:00:00 2001 From: A_D Date: Wed, 30 Dec 2020 17:13:54 +0200 Subject: [PATCH 07/40] Fix multiple missions with the same cargo type A user can collect multiple missions with the same mission cargo, which is added to the cargo.json as distinct entries. Previously we would take the last number as the total, leading to invalid counts (and possibly negative counts). This adds a method to sum cargo entries based on the cargo name. It also adds a field on status to access the original cargo JSON data. Fixes #817 --- monitor.py | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/monitor.py b/monitor.py index 63c4e25a..484ca1c7 100644 --- a/monitor.py +++ b/monitor.py @@ -7,7 +7,7 @@ from os.path import basename, expanduser, isdir, join from sys import platform from time import gmtime, localtime, sleep, strftime, strptime, time from calendar import timegm -from typing import Any, Optional, OrderedDict as OrderedDictT, Tuple, TYPE_CHECKING, Union +from typing import Any, List, MutableMapping, Optional, OrderedDict as OrderedDictT, Tuple, TYPE_CHECKING, Union if TYPE_CHECKING: import tkinter @@ -118,6 +118,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below 'ModulesValue': None, 'Rebuy': None, 'Modules': None, + 'CargoJSON': None, # The raw data from the last time cargo.json was read } def start(self, root: 'tkinter.Tk'): @@ -363,7 +364,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below try: # Preserve property order because why not? - entry: OrderedDictT[str, Any] = json.loads(line, object_pairs_hook=OrderedDict) + entry: MutableMapping[str, Any] = json.loads(line, object_pairs_hook=OrderedDict) entry['timestamp'] # we expect this to exist # TODO: replace with assert? or an if key in check event_type = entry['event'] @@ -608,8 +609,11 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below if 'Inventory' not in entry: with open(join(self.currentdir, 'Cargo.json'), 'rb') as h: # type: ignore entry = json.load(h, object_pairs_hook=OrderedDict) # Preserve property order because why not? + self.state['CargoJSON'] = entry - self.state['Cargo'].update({self.canonicalise(x['Name']): x['Count'] for x in entry['Inventory']}) + clean = self.coalesce_cargo(entry['Inventory']) + + self.state['Cargo'].update({self.canonicalise(x['Name']): x['Count'] for x in clean}) elif event_type in ('CollectCargo', 'MarketBuy', 'BuyDrones', 'MiningRefined'): commodity = self.canonicalise(entry['Type']) @@ -966,6 +970,35 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below with open(filename, 'wt') as h: h.write(string) + def coalesce_cargo(self, raw_cargo: List[MutableMapping[str, Any]]) -> List[MutableMapping[str, Any]]: + """ + Coalesce multiple entries of the same cargo into one. + + This exists due to the fact that a user can accept multiple missions that all require the same cargo. On the ED + side, this is represented as multiple entries in the `Inventory` List with the same names etc. Just a differing + MissionID. We (as in EDMC Core) dont want to support the multiple mission IDs, but DO want to have correct cargo + counts. Thus, we reduce all existing cargo down to one total. + + :param raw_cargo: Raw cargo data (usually from Cargo.json) + :return: Coalesced data + """ + # self.state['Cargo'].update({self.canonicalise(x['Name']): x['Count'] for x in entry['Inventory']}) + out: List[MutableMapping[str, Any]] = [] + for inventory_item in raw_cargo: + if not any(self.canonicalise(x['Name']) == self.canonicalise(inventory_item['Name']) for x in out): + out.append(dict(inventory_item)) + continue + + # We've seen this before, update that count + x = list(filter(lambda x: self.canonicalise(x['Name']) == self.canonicalise(inventory_item['Name']), out)) + + if len(x) != 1: + logger.debug(f'Unexpected number of items: {len(x)} where 1 was expected. {x}') + + x[0]['Count'] += inventory_item['Count'] + + return out + # singleton monitor = EDLogs() From 1be723e24988f54a27e7fdceb30127679f2e7d38 Mon Sep 17 00:00:00 2001 From: A_D Date: Wed, 30 Dec 2020 18:01:50 +0200 Subject: [PATCH 08/40] Added additional doccumentation --- PLUGINS.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/PLUGINS.md b/PLUGINS.md index 036715e6..33b37a2b 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -456,6 +456,11 @@ typically about once a second when in orbital flight. For more info on `status.json`, See the "Status File" section in the Frontier [Journal documentation](https://forums.frontier.co.uk/showthread.php/401661) for the available `entry` properties and for the list of available `"Flags"`. Refer to the source code of [plug.py](./plug.py) for the list of available constants. +New in version 4.1.6: + +`CargoJSON` contains the raw data from the last read of `cargo.json` passed through json.load. +It contains more information about the cargo contents, such as the mission ID for mission specific cargo + #### Getting Commander Data ```python From 13f7b62fe8727fdc535ccc71784c933c11730e0c Mon Sep 17 00:00:00 2001 From: A_D Date: Wed, 30 Dec 2020 18:51:58 +0200 Subject: [PATCH 09/40] Added cargoJSON to state docs --- PLUGINS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/PLUGINS.md b/PLUGINS.md index 33b37a2b..29923b6f 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -417,6 +417,7 @@ Content of `state` (updated to the current journal entry): | `ModulesValue` | `int` | Value of the current ship's modules | | `Rebuy` | `int` | Current ship's rebuy cost | | `Modules` | `dict` | Currently fitted modules | +| `CargoJSON` | `dict` | content of cargo.json as of last read. | A special "StartUp" entry is sent if EDMC is started while the game is already running. In this case you won't receive initial events such as "LoadGame", From 416b73bc3bb357284b32176bb05b187fe774b447 Mon Sep 17 00:00:00 2001 From: A_D Date: Wed, 30 Dec 2020 19:40:18 +0200 Subject: [PATCH 10/40] Modified location of state updates --- PLUGINS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/PLUGINS.md b/PLUGINS.md index 29923b6f..9f73df7f 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -397,7 +397,8 @@ Content of `state` (updated to the current journal entry): | Field | Type | Description | | :------------- | :-------------------------: | :-------------------------------------------------------------------------------------------------------------- | | `Captian` | `Optional[str]` | Name of the commander who's crew you're on, if any | -| `Cargo` | `dict` | Current cargo | +| `Cargo` | `dict` | Current cargo. Note that this will be totals, and any mission specific duplicates will be counted together | +| `CargoJSON` | `dict` | content of cargo.json as of last read. | | `Credits` | `int` | Current credits balance | | `FID` | `str` | Frontier commander ID | | `Loan` | `Optional[int]` | Current loan amount, if any | @@ -417,7 +418,6 @@ Content of `state` (updated to the current journal entry): | `ModulesValue` | `int` | Value of the current ship's modules | | `Rebuy` | `int` | Current ship's rebuy cost | | `Modules` | `dict` | Currently fitted modules | -| `CargoJSON` | `dict` | content of cargo.json as of last read. | A special "StartUp" entry is sent if EDMC is started while the game is already running. In this case you won't receive initial events such as "LoadGame", From 525f0b05e7f9503582460c7054503b46c1a2feb5 Mon Sep 17 00:00:00 2001 From: A_D Date: Wed, 30 Dec 2020 20:55:28 +0200 Subject: [PATCH 11/40] Added doctest --- monitor.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/monitor.py b/monitor.py index 484ca1c7..3ecb3a0a 100644 --- a/monitor.py +++ b/monitor.py @@ -978,6 +978,14 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below side, this is represented as multiple entries in the `Inventory` List with the same names etc. Just a differing MissionID. We (as in EDMC Core) dont want to support the multiple mission IDs, but DO want to have correct cargo counts. Thus, we reduce all existing cargo down to one total. + >>> test = [ + ... { "Name":"basicmedicines", "Name_Localised":"BM", "MissionID":684359162, "Count":147, "Stolen":0 }, + ... { "Name":"survivalequipment", "Name_Localised":"SE", "MissionID":684358939, "Count":147, "Stolen":0 }, + ... { "Name":"survivalequipment", "Name_Localised":"SE", "MissionID":684359344, "Count":36, "Stolen":0 } + ... ] + >>> EDLogs().coalesce_cargo(test) # doctest: +NORMALIZE_WHITESPACE + [{'Name': 'basicmedicines', 'Name_Localised': 'BM', 'MissionID': 684359162, 'Count': 147, 'Stolen': 0}, + {'Name': 'survivalequipment', 'Name_Localised': 'SE', 'MissionID': 684358939, 'Count': 183, 'Stolen': 0}] :param raw_cargo: Raw cargo data (usually from Cargo.json) :return: Coalesced data From 207bb9920fdb9a3b9b1ba39674916271c5d68bdd Mon Sep 17 00:00:00 2001 From: Athanasius Date: Tue, 5 Jan 2021 15:01:09 +0000 Subject: [PATCH 12/40] 4.1.6-rc1: version bump and changelog --- ChangeLog.md | 15 +++++++++++++++ config.py | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/ChangeLog.md b/ChangeLog.md index e0debc15..333a4eb3 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,6 +1,21 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are in reverse chronological order (latest first). --- +Release 4.1.6-rc1 +=== + +* Cargo tracking will now correctly count all instances of the same type of + cargo for different missions. Previously it only counted the cargo for + the last mission requiring that cargo type, as found in Cargo.json. + +* The loaded contents of Cargo.json can now be found in `monitor.state['CargoJSON']`. + `monitor.state` is what is passed to plugins as `state` in the + `journal_entry()` call. + +* Our logging code should now cope with logging from a property. + +* Miscellaneous updates to PLUGINS.md - mostly to clarify some things. + Release 4.1.5 === diff --git a/config.py b/config.py index e60ff1cd..08d7ec89 100644 --- a/config.py +++ b/config.py @@ -13,7 +13,7 @@ appcmdname = 'EDMC' # appversion **MUST** follow Semantic Versioning rules: # # Major.Minor.Patch(-prerelease)(+buildmetadata) -appversion = '4.1.5' #-rc1+a872b5f' +appversion = '4.1.6-rc1' #-rc1+a872b5f' # For some things we want appversion without (possible) +build metadata appversion_nobuild = str(semantic_version.Version(appversion).truncate('prerelease')) copyright = u'© 2015-2019 Jonathan Harris, 2020 EDCD' From d58d831ebe878011f5427d6683b86da455aed54e Mon Sep 17 00:00:00 2001 From: A_D Date: Tue, 5 Jan 2021 17:20:21 +0200 Subject: [PATCH 13/40] Replace python checks with jq in workflow Also makes sure that pushes to main ARE checked --- .github/workflows/push-checks.yml | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/.github/workflows/push-checks.yml b/.github/workflows/push-checks.yml index ba8367c7..b6ad01a5 100644 --- a/.github/workflows/push-checks.yml +++ b/.github/workflows/push-checks.yml @@ -9,7 +9,7 @@ name: Push-Checks on: push: - branches: [ develop ] + branches: [ main ] jobs: build: @@ -27,27 +27,15 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install flake8 pytest + pip install flake8 pytest wheel if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi - name: Lint with flake8 env: ROOT_SHA: ${{github.base_ref}} run: | - DATA=$(python3 < Date: Fri, 8 Jan 2021 14:25:49 +0000 Subject: [PATCH 14/40] monitor: Detect shutdown and bail in log reading loop This should mean not even generating <> Tk events once self.thread == None. --- monitor.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/monitor.py b/monitor.py index 3ecb3a0a..b86a8590 100644 --- a/monitor.py +++ b/monitor.py @@ -327,6 +327,11 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below loghandle.seek(0, SEEK_END) # required to make macOS notice log change over SMB loghandle.seek(log_pos, SEEK_SET) # reset EOF flag # TODO: log_pos reported as possibly unbound for line in loghandle: + # Paranoia check to see if we're shutting down + if threading.current_thread() != self.thread: + logger.info("We're not meant to be running, exiting...") + return # Terminate + if b'"event":"Location"' in line: logger.trace('Found "Location" event, appending to event_queue') From 8a0a82fe43cc34853ba7e287915c86010b332c25 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Fri, 8 Jan 2021 14:28:10 +0000 Subject: [PATCH 15/40] monitor: Bail from get_entry() if self.thread is None If there's no thread to have sent the message then we shouldn't care about it as this means we're in shutdown. --- monitor.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/monitor.py b/monitor.py index b86a8590..792d2a77 100644 --- a/monitor.py +++ b/monitor.py @@ -828,6 +828,10 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below :return: dict representing the event """ + if self.thread is None: + logger.debug('Called whilst self.thread is None, returning') + return None + if not self.event_queue: logger.debug('Called with no event_queue') return None From be18f36e543568e1509ab78a161aeae1b9753828 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Fri, 8 Jan 2021 14:31:54 +0000 Subject: [PATCH 16/40] EDMarketConnector: Bail in AppWindow.journal_entry if monitor.thread is None monitor.thread should only be none when there's a <> to process if we're in shutdown, in which case we do *not* want to be processing journal events. --- EDMarketConnector.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 9a03547e..155415d3 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -743,6 +743,10 @@ class AppWindow(object): 'FlightCon': _('Helm'), # Multicrew role }.get(role, role) + if monitor.thread is None: + logger.debug('monitor.thread is None, assuming shutdown and returning') + return + while True: entry = monitor.get_entry() if not entry: From 81974f66ec3eb8cabc5b7484476e42a68e3bc629 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Fri, 8 Jan 2021 14:45:08 +0000 Subject: [PATCH 17/40] monitor/dashboard: move away from `if __debug__` This includes changing one print_exc() to logger.exception() --- dashboard.py | 21 ++++++++++----------- monitor.py | 3 +-- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/dashboard.py b/dashboard.py index 43ac67a7..4e7f9ce6 100644 --- a/dashboard.py +++ b/dashboard.py @@ -1,16 +1,13 @@ import json from calendar import timegm -from operator import itemgetter -from os import listdir from os.path import isdir, isfile, join, getsize from sys import platform import time -if __debug__: - from traceback import print_exc - from config import config +from EDMCLogging import get_main_logger +logger = get_main_logger() if platform=='darwin': from watchdog.observers import Observer @@ -67,8 +64,10 @@ class Dashboard(FileSystemEventHandler): if not self.observed and not polling: self.observed = self.observer.schedule(self, self.currentdir) - if __debug__: - print('%s Dashboard "%s"' % (polling and 'Polling' or 'Monitoring', self.currentdir)) + if polling: + logger.debug(f'Polling Dashboard "{self.currentdir}"') + else: + logger.debug(f'Monitoring Dashboard "{self.currentdir}"') # Even if we're not intending to poll, poll at least once to process pre-existing # data and to check whether the watchdog thread has crashed due to events not @@ -78,8 +77,8 @@ class Dashboard(FileSystemEventHandler): return True def stop(self): - if __debug__: - print('Stopping monitoring Dashboard') + logger.debug('Stopping monitoring Dashboard') + self.currentdir = None if self.observed: self.observed = None @@ -127,8 +126,8 @@ class Dashboard(FileSystemEventHandler): self.status != entry): self.status = entry self.root.event_generate('<>', when="tail") - except: - if __debug__: print_exc() + except Exception: + logger.exception('Reading Status.json') # singleton dashboard = Dashboard() diff --git a/monitor.py b/monitor.py index 792d2a77..9b57ef2d 100644 --- a/monitor.py +++ b/monitor.py @@ -187,8 +187,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below return True def stop(self): - if __debug__: - print('Stopping monitoring Journal') + logger.debug('Stopping monitoring Journal') self.currentdir = None self.version = None From 90ddd4e1e3991186f1d742d2e8892bedf1e3237b Mon Sep 17 00:00:00 2001 From: Athanasius Date: Fri, 8 Jan 2021 14:53:30 +0000 Subject: [PATCH 18/40] plugins: Log plugin names as we ask them to stop, and when we're done with them all This should point the finger at any plugin(s) that aren't stopping properly. Well, at least those that are hanging *in* their `plugin_stop()`. --- plug.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/plug.py b/plug.py index dd960704..07d43dfb 100644 --- a/plug.py +++ b/plug.py @@ -251,10 +251,14 @@ def notify_stop(): plugin_stop = plugin._get_func('plugin_stop') if plugin_stop: try: + logger.info(f'Asking plugin "{plugin.name}" to stop...') newerror = plugin_stop() error = error or newerror except Exception as e: logger.exception(f'Plugin "{plugin.name}" failed') + + logger.info('Done') + return error From 590cd608d39829f693356be6ecc355cafd7982f3 Mon Sep 17 00:00:00 2001 From: Ash Holland Date: Wed, 6 Jan 2021 15:54:01 +0000 Subject: [PATCH 19/40] Fix logging from mangled methods where class name starts with "_" Python's name-mangling rules are quite complex. Previously, EDMC was incorrectly mangling names where the class name starts with one or more underscores; if the class name starts with any underscores, they should be removed before prepending to the identifier being mangled. If the class name contains *only* underscores, no mangling should be performed. --- EDMCLogging.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/EDMCLogging.py b/EDMCLogging.py index b1cac32e..c0898941 100644 --- a/EDMCLogging.py +++ b/EDMCLogging.py @@ -309,9 +309,11 @@ class EDMCContextFilter(logging.Filter): if frame_class: # See https://en.wikipedia.org/wiki/Name_mangling#Python for how name mangling works. + # For more detail, see _Py_Mangle in CPython's Python/compile.c. name = frame_info.function - if name.startswith("__") and not name.endswith("__"): - name = f'_{frame_class.__class__.__name__}{frame_info.function}' + class_name = frame_class.__class__.__name__.lstrip("_") + if name.startswith("__") and not name.endswith("__") and class_name: + name = f'_{class_name}{frame_info.function}' # Find __qualname__ of the caller fn = inspect.getattr_static(frame_class, name, None) From e51bde44ef65ad1e3527468a749a6ea600ac93c8 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Fri, 8 Jan 2021 15:44:06 +0000 Subject: [PATCH 20/40] Shutdown: re-order the top level calls 1. The updater is in a thread/DLL and we don't want that firing part way through shutdown, so it gets asked to stop first. 2. Then plugins, so they're out of the way and we won't have already stopped something they might rely on. 3. Hotkey after that to head off the user triggering something via them. 4. Now stop the programmatic input from Journal files (including Status.json). 5. Frontier auth handling. 6. And then anything else. --- EDMarketConnector.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 155415d3..210186e3 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1069,27 +1069,36 @@ class AppWindow(object): self.w.update_idletasks() logger.info('Starting shutdown procedures...') - logger.info('Closing protocol handler...') - protocolhandler.close() + # First so it doesn't interrupt us + logger.info('Closing update checker...') + self.updater.close() + # Earlier than anything else so plugin code can't interfere *and* it + # won't still be running in a manner that might rely on something + # we'd otherwise have already stopped. + logger.info('Notifying plugins to stop...') + plug.notify_stop() + + # Handling of application hotkeys now so the user can't possible cause + # an issue via triggering one. logger.info('Unregistering hotkey manager...') hotkeymgr.unregister() + # Now the main programmatic input methods logger.info('Closing dashboard...') dashboard.close() logger.info('Closing journal monitor...') monitor.close() - logger.info('Notifying plugins to stop...') - plug.notify_stop() - - logger.info('Closing update checker...') - self.updater.close() + # Frontier auth/CAPI handling + logger.info('Closing protocol handler...') + protocolhandler.close() logger.info('Closing Frontier CAPI sessions...') companion.session.close() + # Now anything else. logger.info('Closing config...') config.close() From decb8892422cfae62b23bcde5a0395040d7e58c9 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Fri, 8 Jan 2021 15:51:27 +0000 Subject: [PATCH 21/40] Pre-Release 4.1.6-rc2 version and changelog --- ChangeLog.md | 16 ++++++++++++++++ config.py | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/ChangeLog.md b/ChangeLog.md index 333a4eb3..6dfc06ad 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,6 +1,22 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are in reverse chronological order (latest first). --- +Release 4.1.6-rc2 +=== + +* We've applied extra paranoia to some of the application shutdown code to + ensure we're not still trying to handle journal events during this sequence. + + We also re-ordered the shutdown sequence, which might help avoid the shutdown + hang. + + If you encounter a shutdown hang then please add a comment and log files to + [Application can leave a zombie process on shutdown #678](https://github.com/EDCD/EDMarketConnector/issues/678) + to help us track down the cause and fix it. + + +* Logging from any name-mangled method should now work properly. + Release 4.1.6-rc1 === diff --git a/config.py b/config.py index 08d7ec89..b2e296c0 100644 --- a/config.py +++ b/config.py @@ -13,7 +13,7 @@ appcmdname = 'EDMC' # appversion **MUST** follow Semantic Versioning rules: # # Major.Minor.Patch(-prerelease)(+buildmetadata) -appversion = '4.1.6-rc1' #-rc1+a872b5f' +appversion = '4.1.6-rc2' #-rc1+a872b5f' # For some things we want appversion without (possible) +build metadata appversion_nobuild = str(semantic_version.Version(appversion).truncate('prerelease')) copyright = u'© 2015-2019 Jonathan Harris, 2020 EDCD' From f92385244c8f8deaaafe2e0dd9499220a0188e08 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 15:37:17 +0000 Subject: [PATCH 22/40] config: Add class member and methods for signalling/checking shutdown status --- config.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/config.py b/config.py index 08d7ec89..f0915cac 100644 --- a/config.py +++ b/config.py @@ -117,6 +117,8 @@ class Config(object): if platform=='darwin': def __init__(self): + self.in_shutdown = False # Is the application currently shutting down ? + self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname) if not isdir(self.app_dir): mkdir(self.app_dir) @@ -177,9 +179,16 @@ class Config(object): self.save() self.defaults = None + def set_shutdown(self): + self.in_shutdown = True + + def shutting_down(self) -> bool: + return self.in_shutdown + elif platform=='win32': def __init__(self): + self.in_shutdown = False # Is the application currently shutting down ? self.app_dir = join(KnownFolderPath(FOLDERID_LocalAppData), appname) if not isdir(self.app_dir): @@ -268,11 +277,18 @@ class Config(object): RegCloseKey(self.hkey) self.hkey = None + def set_shutdown(self): + self.in_shutdown = True + + def shutting_down(self) -> bool: + return self.in_shutdown + elif platform=='linux': SECTION = 'config' def __init__(self): + self.in_shutdown = False # Is the application currently shutting down ? # http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html self.app_dir = join(getenv('XDG_DATA_HOME', expanduser('~/.local/share')), appname) @@ -346,6 +362,12 @@ class Config(object): self.save() self.config = None + def set_shutdown(self): + self.in_shutdown = True + + def shutting_down(self) -> bool: + return self.in_shutdown + def _escape(self, val): return str(val).replace(u'\\', u'\\\\').replace(u'\n', u'\\n').replace(u';', u'\\;') From 08f1f3e7d99e2e1f47a89ba5e1bf9eabcec24bc1 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 15:37:47 +0000 Subject: [PATCH 23/40] EDMarketConnector: call config.set_shutdown() in AppWindow.onexit() --- EDMarketConnector.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 210186e3..aba22e7b 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -1059,6 +1059,8 @@ class AppWindow(object): self.status['text'] = str(e) def onexit(self, event=None): + config.set_shutdown() # Signal we're in shutdown now. + # http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7 if platform != 'darwin' or self.w.winfo_rooty() > 0: x, y = self.w.geometry().split('+')[1:3] # e.g. '212x170+2881+1267' From 5175136419876d0fb1269bc81a5d3aabed785f4a Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 15:49:08 +0000 Subject: [PATCH 24/40] plug.py: Avoid Tk event_generate() call from show_error() if in shutdown --- plug.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/plug.py b/plug.py index 07d43dfb..98591a84 100644 --- a/plug.py +++ b/plug.py @@ -366,9 +366,16 @@ def notify_newdata(data, is_beta): def show_error(err): """ Display an error message in the status line of the main window. + + Will be NOP during shutdown to avoid Tk hang. :param err: .. versionadded:: 2.3.7 """ + + if config.shutting_down(): + logger.info(f'Called during shutdown: "{str(err)}"') + return + if err and last_error['root']: last_error['msg'] = str(err) last_error['root'].event_generate('<>', when="tail") From 50f520ab66ff4720e99c92ddd884d8d758a912f7 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 15:53:12 +0000 Subject: [PATCH 25/40] config: Change self.in_shutdown to be mangled. I specifically made set_shutdown() *not* take an argument and only ever set this true so no-one else can monkey with it, so might as well mangle it too. --- config.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/config.py b/config.py index f0915cac..0ff7ae7e 100644 --- a/config.py +++ b/config.py @@ -117,7 +117,7 @@ class Config(object): if platform=='darwin': def __init__(self): - self.in_shutdown = False # Is the application currently shutting down ? + self.__in_shutdown = False # Is the application currently shutting down ? self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname) if not isdir(self.app_dir): @@ -180,15 +180,15 @@ class Config(object): self.defaults = None def set_shutdown(self): - self.in_shutdown = True + self.__in_shutdown = True def shutting_down(self) -> bool: - return self.in_shutdown + return self.__in_shutdown elif platform=='win32': def __init__(self): - self.in_shutdown = False # Is the application currently shutting down ? + self.__in_shutdown = False # Is the application currently shutting down ? self.app_dir = join(KnownFolderPath(FOLDERID_LocalAppData), appname) if not isdir(self.app_dir): @@ -278,17 +278,17 @@ class Config(object): self.hkey = None def set_shutdown(self): - self.in_shutdown = True + self.__in_shutdown = True def shutting_down(self) -> bool: - return self.in_shutdown + return self.__in_shutdown elif platform=='linux': SECTION = 'config' def __init__(self): - self.in_shutdown = False # Is the application currently shutting down ? + self.__in_shutdown = False # Is the application currently shutting down ? # http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html self.app_dir = join(getenv('XDG_DATA_HOME', expanduser('~/.local/share')), appname) @@ -363,10 +363,10 @@ class Config(object): self.config = None def set_shutdown(self): - self.in_shutdown = True + self.__in_shutdown = True def shutting_down(self) -> bool: - return self.in_shutdown + return self.__in_shutdown def _escape(self, val): return str(val).replace(u'\\', u'\\\\').replace(u'\n', u'\\n').replace(u';', u'\\;') From cb9bd30a05f7389f8d95721a1485cc95856e41dc Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 16:41:36 +0000 Subject: [PATCH 26/40] dashboard: Bail early from process() if in shutdown --- dashboard.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/dashboard.py b/dashboard.py index 4e7f9ce6..68e828e5 100644 --- a/dashboard.py +++ b/dashboard.py @@ -115,6 +115,9 @@ class Dashboard(FileSystemEventHandler): # Can be called either in watchdog thread or, if polling, in main thread. def process(self, logfile=None): + if config.shutting_down(): + return + try: with open(join(self.currentdir, 'Status.json'), 'rb') as h: data = h.read().strip() @@ -126,6 +129,7 @@ class Dashboard(FileSystemEventHandler): self.status != entry): self.status = entry self.root.event_generate('<>', when="tail") + except Exception: logger.exception('Reading Status.json') From 6cdc1dc20cafc296b86a87740511d20230fc8d60 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 16:41:57 +0000 Subject: [PATCH 27/40] hotkey: Avoid event_generate() calls during shutdown --- hotkey.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/hotkey.py b/hotkey.py index 8ee8762d..5b3323b8 100644 --- a/hotkey.py +++ b/hotkey.py @@ -92,11 +92,15 @@ if platform == 'darwin': self.observer = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, self._handler) def _poll(self): + if config.shutting_down(): + return + # No way of signalling to Tkinter from within the callback handler block that doesn't # cause Python to crash, so poll. if self.activated: self.activated = False self.root.event_generate('<>', when="tail") + if self.keycode or self.modifiers: self.root.after(HotkeyMgr.POLL, self._poll) @@ -123,6 +127,9 @@ if platform == 'darwin': self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE def _acquire_poll(self): + if config.shutting_down(): + return + # No way of signalling to Tkinter from within the monkey-patched event handler that doesn't # cause Python to crash, so poll. if self.acquire_state: @@ -316,7 +323,8 @@ elif platform == 'win32': while GetMessage(ctypes.byref(msg), None, 0, 0) != 0: if msg.message == WM_HOTKEY: if config.getint('hotkey_always') or WindowTitle(GetForegroundWindow()).startswith('Elite - Dangerous'): - self.root.event_generate('<>', when="tail") + if not config.shutting_down(): + self.root.event_generate('<>', when="tail") else: # Pass the key on UnregisterHotKey(None, 1) From 571f9665b3dc3cc74577b174361f9ae2ce0d030b Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 16:43:07 +0000 Subject: [PATCH 28/40] monitor: Avoid Tk event_generate() calls during shutdown. --- monitor.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/monitor.py b/monitor.py index 9b57ef2d..4901c3f2 100644 --- a/monitor.py +++ b/monitor.py @@ -337,7 +337,8 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.event_queue.append(line) if self.event_queue: - self.root.event_generate('<>', when="tail") + if not config.shutting_down(): + self.root.event_generate('<>', when="tail") log_pos = loghandle.tell() @@ -355,7 +356,9 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below '{{ "timestamp":"{}", "event":"ShutDown" }}'.format(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())) ) - self.root.event_generate('<>', when="tail") + if not config.shutting_down(): + self.root.event_generate('<>', when="tail") + self.game_was_running = False else: From 4bddc4c0cb8fac74b85316577d1910bc18f84ddc Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 16:43:33 +0000 Subject: [PATCH 29/40] prefs: Avoid Tk event_generate() calls during shutdown --- prefs.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/prefs.py b/prefs.py index 95612e6a..69f7140c 100644 --- a/prefs.py +++ b/prefs.py @@ -1157,4 +1157,5 @@ class PreferencesDialog(tk.Toplevel): except Exception: AXIsProcessTrustedWithOptions({kAXTrustedCheckOptionPrompt: True}) - self.parent.event_generate('<>', when="tail") + if not config.shutting_down(): + self.parent.event_generate('<>', when="tail") From 92d5657e216ae5b60713624b7b53843878d00f10 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 16:43:53 +0000 Subject: [PATCH 30/40] protocol: Avoid Tk event_generate() calls during shutdown --- protocol.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/protocol.py b/protocol.py index 49345643..ea7bfaf6 100644 --- a/protocol.py +++ b/protocol.py @@ -32,7 +32,9 @@ class GenericProtocolHandler(object): def event(self, url): self.lastpayload = url - self.master.event_generate('<>', when="tail") + + if not config.shutting_down(): + self.master.event_generate('<>', when="tail") if sys.platform == 'darwin' and getattr(sys, 'frozen', False): From fb1c9fc0347e38043d2a4873688177dc956b2304 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 16:44:11 +0000 Subject: [PATCH 31/40] update: Avoid Tk event_generate() calls during shutdown. --- update.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/update.py b/update.py index c234dfc9..3b57fb9e 100644 --- a/update.py +++ b/update.py @@ -40,7 +40,8 @@ class Updater(object): Receive (Win)Sparkle shutdown request and send it to parent. :rtype: None """ - self.root.event_generate('<>', when="tail") + if not config.shutting_down(): + self.root.event_generate('<>', when="tail") def use_internal(self) -> bool: """ From bca0231dfc6d6166514a50515b3f67f2d17600a9 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 16:45:26 +0000 Subject: [PATCH 32/40] plugins/edsm: Avoid Tk event_generate() calls during shutdown --- plugins/edsm.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/plugins/edsm.py b/plugins/edsm.py index 80c0077a..a77de879 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -598,8 +598,10 @@ def worker() -> None: if not closing and e['event'] in ('StartUp', 'Location', 'FSDJump', 'CarrierJump'): # Update main window's system status this.lastlookup = r - # calls update_status in main thread - this.system_link.event_generate('<>', when="tail") + + if not config.shutting_down(): + # calls update_status in main thread + this.system_link.event_generate('<>', when="tail") if r['msgnum'] // 100 != 1: logger.warning(f'EDSM event with not-1xx status:\n{r["msgnum"]}\n{r["msg"]}\n' From 111f445cac62291870f2354eacf907c8020d22cc Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 16:45:45 +0000 Subject: [PATCH 33/40] plugins/inara: Avoid Tk event_generate() calls during shutdown --- plugins/inara.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/plugins/inara.py b/plugins/inara.py index 4b61322c..9aeef582 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -1290,13 +1290,17 @@ def send_data(url: str, data: Mapping[str, Any]) -> bool: 'setCommanderTravelLocation' ): this.lastlocation = reply_event.get('eventData', {}) - # calls update_location in main thread - this.system_link.event_generate('<>', when="tail") + + if not config.shutting_down(): + # calls update_location in main thread + this.system_link.event_generate('<>', when="tail") elif data_event['eventName'] in ['addCommanderShip', 'setCommanderShip']: this.lastship = reply_event.get('eventData', {}) - # calls update_ship in main thread - this.system_link.event_generate('<>', when="tail") + + if not config.shutting_down(): + # calls update_ship in main thread + this.system_link.event_generate('<>', when="tail") return True # regardless of errors above, we DID manage to send it, therefore inform our caller as such From 462cd253129319d67e0b715e6b3f6cf17b511375 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 16:54:09 +0000 Subject: [PATCH 34/40] config: Make config.shutting_down() a property, and change 'callers' --- config.py | 1 + dashboard.py | 4 ++-- hotkey.py | 6 +++--- monitor.py | 4 ++-- plug.py | 2 +- plugins/edsm.py | 2 +- plugins/inara.py | 4 ++-- prefs.py | 2 +- protocol.py | 2 +- update.py | 4 ++-- 10 files changed, 16 insertions(+), 15 deletions(-) diff --git a/config.py b/config.py index 0ff7ae7e..76013029 100644 --- a/config.py +++ b/config.py @@ -182,6 +182,7 @@ class Config(object): def set_shutdown(self): self.__in_shutdown = True + @property def shutting_down(self) -> bool: return self.__in_shutdown diff --git a/dashboard.py b/dashboard.py index 68e828e5..4259dccb 100644 --- a/dashboard.py +++ b/dashboard.py @@ -115,9 +115,9 @@ class Dashboard(FileSystemEventHandler): # Can be called either in watchdog thread or, if polling, in main thread. def process(self, logfile=None): - if config.shutting_down(): + if config.shutting_down: return - + try: with open(join(self.currentdir, 'Status.json'), 'rb') as h: data = h.read().strip() diff --git a/hotkey.py b/hotkey.py index 5b3323b8..9b261ccc 100644 --- a/hotkey.py +++ b/hotkey.py @@ -92,7 +92,7 @@ if platform == 'darwin': self.observer = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, self._handler) def _poll(self): - if config.shutting_down(): + if config.shutting_down: return # No way of signalling to Tkinter from within the callback handler block that doesn't @@ -127,7 +127,7 @@ if platform == 'darwin': self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE def _acquire_poll(self): - if config.shutting_down(): + if config.shutting_down: return # No way of signalling to Tkinter from within the monkey-patched event handler that doesn't @@ -323,7 +323,7 @@ elif platform == 'win32': while GetMessage(ctypes.byref(msg), None, 0, 0) != 0: if msg.message == WM_HOTKEY: if config.getint('hotkey_always') or WindowTitle(GetForegroundWindow()).startswith('Elite - Dangerous'): - if not config.shutting_down(): + if not config.shutting_down: self.root.event_generate('<>', when="tail") else: # Pass the key on diff --git a/monitor.py b/monitor.py index 4901c3f2..f8d4a201 100644 --- a/monitor.py +++ b/monitor.py @@ -337,7 +337,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below self.event_queue.append(line) if self.event_queue: - if not config.shutting_down(): + if not config.shutting_down: self.root.event_generate('<>', when="tail") log_pos = loghandle.tell() @@ -356,7 +356,7 @@ class EDLogs(FileSystemEventHandler): # type: ignore # See below '{{ "timestamp":"{}", "event":"ShutDown" }}'.format(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime())) ) - if not config.shutting_down(): + if not config.shutting_down: self.root.event_generate('<>', when="tail") self.game_was_running = False diff --git a/plug.py b/plug.py index 98591a84..755fec1c 100644 --- a/plug.py +++ b/plug.py @@ -372,7 +372,7 @@ def show_error(err): .. versionadded:: 2.3.7 """ - if config.shutting_down(): + if config.shutting_down: logger.info(f'Called during shutdown: "{str(err)}"') return diff --git a/plugins/edsm.py b/plugins/edsm.py index a77de879..e9fbd46c 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -599,7 +599,7 @@ def worker() -> None: # Update main window's system status this.lastlookup = r - if not config.shutting_down(): + if not config.shutting_down: # calls update_status in main thread this.system_link.event_generate('<>', when="tail") diff --git a/plugins/inara.py b/plugins/inara.py index 9aeef582..ac5d53f5 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -1291,14 +1291,14 @@ def send_data(url: str, data: Mapping[str, Any]) -> bool: ): this.lastlocation = reply_event.get('eventData', {}) - if not config.shutting_down(): + if not config.shutting_down: # calls update_location in main thread this.system_link.event_generate('<>', when="tail") elif data_event['eventName'] in ['addCommanderShip', 'setCommanderShip']: this.lastship = reply_event.get('eventData', {}) - if not config.shutting_down(): + if not config.shutting_down: # calls update_ship in main thread this.system_link.event_generate('<>', when="tail") diff --git a/prefs.py b/prefs.py index 69f7140c..e9c3afab 100644 --- a/prefs.py +++ b/prefs.py @@ -1157,5 +1157,5 @@ class PreferencesDialog(tk.Toplevel): except Exception: AXIsProcessTrustedWithOptions({kAXTrustedCheckOptionPrompt: True}) - if not config.shutting_down(): + if not config.shutting_down: self.parent.event_generate('<>', when="tail") diff --git a/protocol.py b/protocol.py index ea7bfaf6..7990b952 100644 --- a/protocol.py +++ b/protocol.py @@ -33,7 +33,7 @@ class GenericProtocolHandler(object): def event(self, url): self.lastpayload = url - if not config.shutting_down(): + if not config.shutting_down: self.master.event_generate('<>', when="tail") diff --git a/update.py b/update.py index 3b57fb9e..aa2a1a8f 100644 --- a/update.py +++ b/update.py @@ -40,7 +40,7 @@ class Updater(object): Receive (Win)Sparkle shutdown request and send it to parent. :rtype: None """ - if not config.shutting_down(): + if not config.shutting_down: self.root.event_generate('<>', when="tail") def use_internal(self) -> bool: @@ -209,4 +209,4 @@ class Updater(object): :return: None """ - pass \ No newline at end of file + pass From 247577c5f4b778c2ac81ba26497b3036d941236d Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 17:13:31 +0000 Subject: [PATCH 35/40] config: Also set Config.shutting_down to be @propety on win32 and linux --- config.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/config.py b/config.py index 76013029..76fa6fdf 100644 --- a/config.py +++ b/config.py @@ -281,6 +281,7 @@ class Config(object): def set_shutdown(self): self.__in_shutdown = True + @property def shutting_down(self) -> bool: return self.__in_shutdown @@ -366,6 +367,7 @@ class Config(object): def set_shutdown(self): self.__in_shutdown = True + @property def shutting_down(self) -> bool: return self.__in_shutdown From 67e72f7477ada4b9f419b816007d7075db75ad10 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 17:35:54 +0000 Subject: [PATCH 36/40] Pre-Release 4.1.6-rc3: config version and changelog --- ChangeLog.md | 23 +++++++++++++++++++++++ config.py | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/ChangeLog.md b/ChangeLog.md index 6dfc06ad..060bdcf8 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,6 +1,29 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are in reverse chronological order (latest first). --- +Release 4.1.6-rc3 +=== + +We might have finally found the cause of the application hangs during shutdown. +Note that this became easier to track down due to the current (2021-01-11) +downtime for migration of www.edsm.net. EDMarketConnector will hang during +shutdown prior to this version whilst EDSM isn't available. + +* Avoid making Tk event_generate() calls whilst the appliction is shutting + down. + +* Plugins should actively avoid making any sort of Tk event_generate() call + during application shutdown. + + This means using `if not config.shutting_down:` to gate any code in worker + threads that might attempt this. Also, be sure you're not attempting such + in your `plugin_stop()` function. + + See plugins/edsm.py and plugins/inara.py for example of the usage. + +* Any use of plug.show_error() won't actually change the UI status line during + shutdown, but the text you tried to show will be logged instead. + Release 4.1.6-rc2 === diff --git a/config.py b/config.py index b3001d2a..695fda23 100644 --- a/config.py +++ b/config.py @@ -13,7 +13,7 @@ appcmdname = 'EDMC' # appversion **MUST** follow Semantic Versioning rules: # # Major.Minor.Patch(-prerelease)(+buildmetadata) -appversion = '4.1.6-rc2' #-rc1+a872b5f' +appversion = '4.1.6-rc3' #-rc1+a872b5f' # For some things we want appversion without (possible) +build metadata appversion_nobuild = str(semantic_version.Version(appversion).truncate('prerelease')) copyright = u'© 2015-2019 Jonathan Harris, 2020 EDCD' From 501f34836aba9af11b3cdf4c28e2073a2e950b2d Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 17:48:47 +0000 Subject: [PATCH 37/40] update.py: Need to `from config import config` to access shutting_down --- update.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/update.py b/update.py index aa2a1a8f..de7eb8cd 100644 --- a/update.py +++ b/update.py @@ -9,7 +9,7 @@ if TYPE_CHECKING: import tkinter as tk # ensure registry is set up on Windows before we start -from config import appname, appversion, appversion_nobuild, update_feed +from config import appname, appversion, appversion_nobuild, config, update_feed class EDMCVersion(object): """ From 3d515ba9196248247556d3edbc47d7c537d71f06 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 18:20:58 +0000 Subject: [PATCH 38/40] protocol.py: Need `from config import config` --- protocol.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/protocol.py b/protocol.py index 7990b952..408b3082 100644 --- a/protocol.py +++ b/protocol.py @@ -5,7 +5,7 @@ import threading import urllib.request, urllib.error, urllib.parse import sys -from config import appname +from config import appname, config if sys.platform == 'win32': From 6a8d950b8751b3f84557d58d8bddb415f32664d8 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Mon, 11 Jan 2021 19:28:56 +0000 Subject: [PATCH 39/40] Change all requirements to latest tested and use '==' on all. Although the issue we've identified with GitHub builds isn't to do with a python module version it's best to nail precise versions so we can be sure it will build with the same as we've tested locally. --- requirements-dev.txt | 2 +- requirements.txt | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index b50ae664..e2ea8f11 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -17,7 +17,7 @@ pep8-naming==0.11.1 autopep8==1.5.4 # HTML changelogs -grip>=4.5.2 +grip==4.5.2 # Packaging # We only need py2exe on windows. diff --git a/requirements.txt b/requirements.txt index bf29adc9..7f6952ba 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ certifi==2019.9.11 -requests>=2.11.1 -watchdog>=0.8.3 +requests==2.25.1 +watchdog==0.10.3 # argh==0.26.2 watchdog dep # pyyaml==5.3.1 watchdog dep semantic-version==2.8.5 From 52193a9f0700671cc41ee67358519a552c1c9220 Mon Sep 17 00:00:00 2001 From: Athanasius Date: Tue, 12 Jan 2021 16:24:10 +0000 Subject: [PATCH 40/40] Release 4.1.6: config version and changelog --- ChangeLog.md | 52 +++++++++++++++++++++++----------------------------- config.py | 2 +- 2 files changed, 24 insertions(+), 30 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 060bdcf8..48743c1c 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,60 +1,54 @@ This is the master changelog for Elite Dangerous Market Connector. Entries are in reverse chronological order (latest first). --- -Release 4.1.6-rc3 +Release 4.1.6 === We might have finally found the cause of the application hangs during shutdown. -Note that this became easier to track down due to the current (2021-01-11) -downtime for migration of www.edsm.net. EDMarketConnector will hang during -shutdown prior to this version whilst EDSM isn't available. +Note that this became easier to track down due to the downtime +for migration of www.edsm.net around 2021-01-11. Before these fixes EDSM's +API not being available would cause an EDMC hang on shutdown. -* Avoid making Tk event_generate() calls whilst the appliction is shutting - down. - -* Plugins should actively avoid making any sort of Tk event_generate() call - during application shutdown. - - This means using `if not config.shutting_down:` to gate any code in worker - threads that might attempt this. Also, be sure you're not attempting such - in your `plugin_stop()` function. - - See plugins/edsm.py and plugins/inara.py for example of the usage. - -* Any use of plug.show_error() won't actually change the UI status line during - shutdown, but the text you tried to show will be logged instead. - -Release 4.1.6-rc2 -=== - -* We've applied extra paranoia to some of the application shutdown code to +* We've applied extra paranoia to some of the application shutdown code to ensure we're not still trying to handle journal events during this sequence. - + We also re-ordered the shutdown sequence, which might help avoid the shutdown hang. - + If you encounter a shutdown hang then please add a comment and log files to [Application can leave a zombie process on shutdown #678](https://github.com/EDCD/EDMarketConnector/issues/678) to help us track down the cause and fix it. +* We now avoid making Tk event_generate() calls whilst the appliction is + shutting down. -* Logging from any name-mangled method should now work properly. +* Plugins should actively avoid making any sort of Tk event_generate() call + during application shutdown. -Release 4.1.6-rc1 -=== + This means using `if not config.shutting_down:` to gate any code in worker + threads that might attempt this. Also, be sure you're not attempting such + in your `plugin_stop()` function. + + See plugins/edsm.py and plugins/inara.py for example of the usage. + +* Any use of `plug.show_error()` won't actually change the UI status line + during shutdown, but the text you tried to show will be logged instead. * Cargo tracking will now correctly count all instances of the same type of cargo for different missions. Previously it only counted the cargo for the last mission requiring that cargo type, as found in Cargo.json. * The loaded contents of Cargo.json can now be found in `monitor.state['CargoJSON']`. - `monitor.state` is what is passed to plugins as `state` in the + `monitor.state` is what is passed to plugins as `state` in the `journal_entry()` call. * Our logging code should now cope with logging from a property. +* Logging from any name-mangled method should now work properly. + * Miscellaneous updates to PLUGINS.md - mostly to clarify some things. + Release 4.1.5 === diff --git a/config.py b/config.py index 695fda23..41d56f3f 100644 --- a/config.py +++ b/config.py @@ -13,7 +13,7 @@ appcmdname = 'EDMC' # appversion **MUST** follow Semantic Versioning rules: # # Major.Minor.Patch(-prerelease)(+buildmetadata) -appversion = '4.1.6-rc3' #-rc1+a872b5f' +appversion = '4.1.6' #-rc1+a872b5f' # For some things we want appversion without (possible) +build metadata appversion_nobuild = str(semantic_version.Version(appversion).truncate('prerelease')) copyright = u'© 2015-2019 Jonathan Harris, 2020 EDCD'