psytricks 2.3.0__tar.gz → 2.4.0a1__tar.gz

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.

Potentially problematic release.


This version of psytricks might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: psytricks
3
- Version: 2.3.0
3
+ Version: 2.4.0a1
4
4
  Summary: PowerShell Python Citrix Tricks.
5
5
  License-Expression: GPL-3.0-or-later
6
6
  License-File: LICENSE
@@ -14,6 +14,7 @@ Classifier: Programming Language :: Python :: 3.11
14
14
  Classifier: Programming Language :: Python :: 3.12
15
15
  Classifier: Programming Language :: Python :: 3.13
16
16
  Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Programming Language :: Python :: 3.15
17
18
  Requires-Dist: click (>=8.1.3,<9.0.0)
18
19
  Requires-Dist: loguru (>=0.7.0,<0.8.0)
19
20
  Requires-Dist: requests (>=2.30.0,<3.0.0)
@@ -6,7 +6,7 @@ authors = [
6
6
  ]
7
7
  license = "GPL-3.0-or-later"
8
8
  dynamic = ["readme"]
9
- version = "2.3.0"
9
+ version = "2.4.0-a.1"
10
10
 
11
11
  [tool.poetry]
12
12
  documentation = "https://imcf.one/apidocs/psytricks/psytricks.html"
@@ -3,7 +3,7 @@
3
3
  .. include:: ../../CHANGELOG.md
4
4
  """
5
5
 
6
- __version__ = "2.3.0"
6
+ __version__ = "2.4.0-a.1"
7
7
 
8
8
  # style exceptions for pdoc-include-only docstrings:
9
9
  # ruff: noqa: D400 (missing-trailing-period)
@@ -5,7 +5,7 @@ Collection of functions and other definitions to be sourced by other scripts.
5
5
  #>
6
6
 
7
7
  # the version variable will be filled by poetry at build time:
8
- $Version = "2.3.0"
8
+ $Version = "2.4.0-a.1"
9
9
 
10
10
 
11
11
  #region properties-selectors
@@ -105,6 +105,8 @@ if ($Shutdown) {
105
105
  #region boilerplate
106
106
 
107
107
  Add-PSSnapIn Citrix.Broker.Admin.V2 -ErrorAction Stop
108
+ # required for 'Get-ConfigSite' (see the "citrix-site" region below):
109
+ Add-PSSnapIn Citrix.Configuration.Admin.V2 -ErrorAction Stop
108
110
 
109
111
  # locate and dot-source the libs file:
110
112
  $LibPath = Join-Path $ScriptPath "psytricks-lib.ps1"
@@ -116,6 +118,30 @@ if (!(Test-Path $LibPath)) {
116
118
  #endregion boilerplate
117
119
 
118
120
 
121
+ #region citrix-site
122
+
123
+ <#
124
+ The Citrix site the Delivery Controller belongs to is added to the "Status"
125
+ object of every JSON response, so clients can verify which site the data is
126
+ coming from (e.g. to notice they're talking to another site than expected).
127
+
128
+ The site is identified by its GUID, its name is for humans only (a new site may
129
+ well get the same name as the previous one). A controller can't change its site
130
+ while the server is running, so the site is only queried once - the server
131
+ refuses to start if it can't be determined (as 'ErrorActionPreference' is set to
132
+ "Stop").
133
+ #>
134
+ $CitrixSite = Get-ConfigSite -AdminAddress $AdminAddress
135
+ # a [guid] can't be serialized by 'ConvertTo-Json', so both are stored as strings:
136
+ $SiteGuid = [string]$CitrixSite.SiteGuid
137
+ $SiteName = [string]$CitrixSite.SiteName
138
+ if ($SiteGuid -eq "") {
139
+ throw "Unable to determine the Citrix site of [$AdminAddress]!"
140
+ }
141
+
142
+ #endregion citrix-site
143
+
144
+
119
145
  #region route-keywords
120
146
 
121
147
  $GetRoutes = @(
@@ -187,6 +213,8 @@ function Send-Response {
187
213
  ScriptPath = $ScriptPath
188
214
  PSyTricksVersion = $Version
189
215
  Timestamp = [int64](Get-Date -UFormat %s)
216
+ SiteGuid = $SiteGuid
217
+ SiteName = $SiteName
190
218
  }
191
219
 
192
220
  $Payload = @{
@@ -478,6 +506,7 @@ function Start-ListenerLoop {
478
506
  Write-Host "Starting: $ScriptPath" @Blue
479
507
  Write-Host "PSyTricksVersion: $Version" @Blue
480
508
  Write-Host "Citrix 'AdminAddress': $AdminAddress" @Blue
509
+ Write-Host "Citrix site: $SiteName ($SiteGuid)" @Blue
481
510
  Write-Host "====================================================" @Blue
482
511
 
483
512
 
@@ -0,0 +1,84 @@
1
+ """PSyTricks exception classes."""
2
+
3
+ import requests
4
+
5
+
6
+ class ResTricksConnectionError(requests.exceptions.ConnectionError, ConnectionError):
7
+ """Communicating with the ResTricks server failed.
8
+
9
+ Raised by `psytricks.wrapper.ResTricksWrapper` instead of the low-level
10
+ exceptions of `requests` / `urllib3` in case the server couldn't be reached
11
+ or didn't answer in time, using a concise message that states
12
+ the request method, the URL and the root cause of the failure (e.g.
13
+ `ConnectionRefusedError: [Errno 111] Connection refused`).
14
+
15
+ The class derives from both, `requests.exceptions.ConnectionError` and the
16
+ built-in `ConnectionError`, so existing code catching either of them will
17
+ continue to work.
18
+
19
+ The (potentially long) chain of underlying exceptions is suppressed when
20
+ raising this exception to keep tracebacks short, but the original exception
21
+ is still accessible through the `original` attribute (and `__context__`).
22
+
23
+ Parameters
24
+ ----------
25
+ message : str
26
+ The exception message.
27
+ method : str, optional
28
+ The HTTP method of the failed request (e.g. `GET`).
29
+ url : str, optional
30
+ The URL of the failed request.
31
+ original : Exception, optional
32
+ The exception that triggered this one.
33
+
34
+ Attributes
35
+ ----------
36
+ method : str or None
37
+ See the constructor for details.
38
+ url : str or None
39
+ See the constructor for details.
40
+ original : Exception or None
41
+ See the constructor for details.
42
+ reason : Exception or None
43
+ The innermost exception in the chain of `original`, i.e. the actual
44
+ root cause (e.g. a `ConnectionRefusedError` or `TimeoutError`).
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ message: str,
50
+ method: str | None = None,
51
+ url: str | None = None,
52
+ original: Exception | None = None,
53
+ ):
54
+ super().__init__(message)
55
+ self.method = method
56
+ self.url = url
57
+ self.original = original
58
+ self.reason = root_cause(original) if original is not None else None
59
+
60
+
61
+ def root_cause(ex: BaseException) -> BaseException:
62
+ """Find the innermost exception in the chain of the given one.
63
+
64
+ Follows `__cause__` (explicit chaining via `raise ... from ...`) and falls
65
+ back to `__context__` (implicit chaining, "during handling of the above
66
+ exception...") until the end of the chain is reached.
67
+
68
+ Parameters
69
+ ----------
70
+ ex : BaseException
71
+ The exception to start from.
72
+
73
+ Returns
74
+ -------
75
+ BaseException
76
+ The innermost exception of the chain (`ex` itself if it isn't chained).
77
+ """
78
+ seen = {id(ex)} # guard against (theoretically possible) cycles
79
+ while True:
80
+ nxt = ex.__cause__ or ex.__context__
81
+ if nxt is None or id(nxt) in seen:
82
+ return ex
83
+ seen.add(id(nxt))
84
+ ex = nxt
@@ -1,10 +1,9 @@
1
1
  """PowerShell Python Citrix Tricks."""
2
2
 
3
- import subprocess
4
3
  import json
5
4
  import os
5
+ import subprocess
6
6
  import time
7
-
8
7
  from os.path import dirname
9
8
  from pathlib import Path
10
9
  from sys import platform
@@ -14,7 +13,17 @@ from loguru import logger as log
14
13
 
15
14
  from . import __version__
16
15
  from .decoder import parse_powershell_json
17
- from .literals import Action, RequestName, MsgStyle
16
+ from .literals import Action, MsgStyle, RequestName
17
+ from .exceptions import ResTricksConnectionError, root_cause
18
+
19
+ # `requests` exceptions to be converted into a `ResTricksConnectionError`, i.e.
20
+ # the server couldn't be reached or didn't answer in time - other exceptions
21
+ # (e.g. `MissingSchema`, `InvalidHeader`) indicate a misconfiguration or a bug
22
+ # and are re-raised unchanged instead:
23
+ _CONNECTION_ERRORS = (
24
+ requests.exceptions.ConnectionError,
25
+ requests.exceptions.Timeout,
26
+ )
18
27
 
19
28
 
20
29
  class ResTricksWrapper:
@@ -46,6 +55,15 @@ class ResTricksWrapper:
46
55
  The server version as a list of version components, where the first
47
56
  three components are of type `int` (representing `major.minor.patch`),
48
57
  whereas the last component may be a `str` as well.
58
+ site_guid : str or None
59
+ The GUID of the Citrix site the server's Delivery Controller belongs
60
+ to, as given by the `Status` of the latest response (`None` before the
61
+ first response, or if the server doesn't provide it, e.g. a version
62
+ older than 2.4.0). Checking it right after a request tells which site
63
+ the data of that request's response is coming from.
64
+ site_name : str or None
65
+ The name of that Citrix site (same as for `site_guid`). For humans only,
66
+ as a new site may well get the same name as the previous one.
49
67
  headers : dict
50
68
  A dict of headers to be sent along the requests.
51
69
  """
@@ -54,6 +72,8 @@ class ResTricksWrapper:
54
72
  self.base_url = "http://localhost:8080/" if not base_url else base_url
55
73
  self.timeout = 5
56
74
  self.server_version = [0, 0, 0, 0]
75
+ self.site_guid = None
76
+ self.site_name = None
57
77
 
58
78
  # FIXME: currently "localhost" is hardcoded here as this is what the
59
79
  # service expects (see `Listener.Prefixes` in `restricks-server.ps1` for
@@ -135,10 +155,9 @@ class ResTricksWrapper:
135
155
 
136
156
  Raises
137
157
  ------
138
- ValueError
139
- Raised in case the server version doesn't match the local version.
140
- ConnectionError
141
- Raised in case the initial connection check failed.
158
+ ResTricksConnectionError
159
+ Raised in case the initial connection check failed (including a
160
+ mismatching server version), unless `verify` was set to `False`.
142
161
  """
143
162
  if self._connected:
144
163
  log.trace("Connection 🔌 established previously, not reconnecting.")
@@ -161,10 +180,16 @@ class ResTricksWrapper:
161
180
  self._connected = True
162
181
 
163
182
  except Exception as ex: # pylint: disable-msg=broad-except
164
- if self._verify:
165
- raise ConnectionError(
166
- f"Connecting to {self.base_url} failed: {ex}"
167
- ) from ex
183
+ if not self._verify:
184
+ return
185
+ # already a concise exception from send_get_request(), don't wrap it:
186
+ if isinstance(ex, ResTricksConnectionError):
187
+ raise
188
+ raise ResTricksConnectionError(
189
+ f"Connecting to {self.base_url} failed: {ex}",
190
+ url=self.base_url,
191
+ original=ex,
192
+ ) from ex
168
193
 
169
194
  def validate_version(self, server_ver) -> bool:
170
195
  """Validate the server version against the local module.
@@ -225,6 +250,32 @@ class ResTricksWrapper:
225
250
  log.error("Version mismatch! 🧨")
226
251
  return False
227
252
 
253
+ def _request_failed(
254
+ self, method: str, raw_url: str, ex: Exception
255
+ ) -> ResTricksConnectionError:
256
+ """Log a failed request and create a concise exception for it.
257
+
258
+ Parameters
259
+ ----------
260
+ method : str
261
+ The HTTP method of the failed request (e.g. `GET`).
262
+ raw_url : str
263
+ The part of the URL that was appended to `self.base_url`.
264
+ ex : Exception
265
+ The exception raised by `requests`, one of `_CONNECTION_ERRORS`.
266
+
267
+ Returns
268
+ -------
269
+ ResTricksConnectionError
270
+ The exception to be raised by the caller (using `from None` to
271
+ suppress the chain of low-level exceptions).
272
+ """
273
+ url = self.base_url + raw_url
274
+ reason = root_cause(ex)
275
+ msg = f"{method} request [{url}] failed: {type(reason).__name__}: {reason}"
276
+ log.error(msg)
277
+ return ResTricksConnectionError(msg, method=method, url=url, original=ex)
278
+
228
279
  def _check_response(self, response: requests.Response) -> None:
229
280
  """Check the HTTP response code and JSON status attributes."""
230
281
  self._write_response_dump(response)
@@ -249,6 +300,25 @@ class ResTricksWrapper:
249
300
  log.warning(response.text)
250
301
  raise ValueError(f"Malformed response: {response.text}") from ex
251
302
 
303
+ def _record_site(self, data) -> None:
304
+ """Record the Citrix site from the `Status` of a parsed response.
305
+
306
+ Both `site_guid` and `site_name` are set from every response, so they
307
+ always tell where the latest response is coming from - they're reset to
308
+ `None` if the response doesn't provide them (e.g. an older server).
309
+
310
+ Parameters
311
+ ----------
312
+ data : list or dict or None
313
+ The parsed `JSON` of the response, see `send_get_request()`.
314
+ """
315
+ status = {}
316
+ if isinstance(data, dict):
317
+ status = data.get("Status") or {}
318
+ self.site_guid = status.get("SiteGuid") or None
319
+ self.site_name = status.get("SiteName") or None
320
+ log.trace(f"Citrix site of the response: {self.site_name} ({self.site_guid})")
321
+
252
322
  def _write_response_dump(self, response: requests.Response) -> Path | None:
253
323
  """Dump the response to disk if `dump_responses_to` is set."""
254
324
  if not self.dump_responses_to:
@@ -300,9 +370,11 @@ class ResTricksWrapper:
300
370
  response = requests.get(
301
371
  self.base_url + raw_url, timeout=self.timeout, headers=self.headers
302
372
  )
373
+ except _CONNECTION_ERRORS as ex:
374
+ raise self._request_failed("GET", raw_url, ex) from None
303
375
  except Exception as ex: # pylint: disable-msg=broad-except
304
- log.error(f"GET request [{raw_url}] failed: {ex}")
305
- raise ex
376
+ log.error(f"GET request [{raw_url}] failed unexpectedly: {ex}")
377
+ raise
306
378
 
307
379
  try:
308
380
  data = response.json(object_hook=parse_powershell_json)
@@ -322,6 +394,7 @@ class ResTricksWrapper:
322
394
  raise json.JSONDecodeError(msg, doc=response.text, pos=0)
323
395
 
324
396
  self._check_response(response)
397
+ self._record_site(data)
325
398
 
326
399
  return data
327
400
 
@@ -378,17 +451,23 @@ class ResTricksWrapper:
378
451
  timeout=self.timeout,
379
452
  headers=self.headers,
380
453
  )
454
+ except _CONNECTION_ERRORS as ex:
455
+ raise self._request_failed("POST", raw_url, ex) from None
381
456
  except Exception as ex: # pylint: disable-msg=broad-except
382
- log.error(f"POST request [{raw_url}] failed: {ex}")
383
- raise ex
457
+ log.error(f"POST request [{raw_url}] failed unexpectedly: {ex}")
458
+ raise
384
459
 
385
460
  self._check_response(response)
386
461
 
387
462
  if no_json:
388
463
  log.debug(f"No-payload response status code: {response.status_code}")
464
+ # no `Status` to take the site from, so it's unknown for this one:
465
+ self._record_site(None)
389
466
  return []
390
467
 
391
- return response.json(object_hook=parse_powershell_json)
468
+ data = response.json(object_hook=parse_powershell_json)
469
+ self._record_site(data)
470
+ return data
392
471
 
393
472
  def get_machine_status(self) -> list:
394
473
  """Send a `GET` request with `GetMachineStatus`.
File without changes
File without changes
File without changes