Debian Codegraph @

src/globus_sdk/local_endpoint/personal/endpoint.py

raw
1 from __future__ import annotations
2
3 import os
4 import typing as t
5
6 from globus_sdk.exc import GlobusSDKUsageError
7
8 from .owner_info import GlobusConnectPersonalOwnerInfo
9
10 if t.TYPE_CHECKING:
11 import globus_sdk
12
13
14 def _on_windows() -> bool:
15 """
16 Per python docs, this is a safe, reliable way of checking the platform.
17 sys.platform offers more detail -- more than we want, in this case.
18 """
19 return os.name == "nt"
20
21
22 class LocalGlobusConnectPersonal:
23 r"""
24 A LocalGlobusConnectPersonal object represents the available SDK methods
25 for inspecting and controlling a running Globus Connect Personal
26 installation.
27
28 These objects do *not* inherit from BaseClient and do not provide methods
29 for interacting with any Globus Service APIs.
30
31 :param config_dir: Path to a non-default configuration directory. On Linux, this is
32 the same as the value passed to Globus Connect Personal's `-dir` flag
33 (i.e. the default value is ``~/.globusonline``).
34 """
35
36 def __init__(self, *, config_dir: str | None = None) -> None:
37 self._config_dir = config_dir
38 self._endpoint_id: str | None = None
39
40 def _detect_config_dir(self) -> str:
41 if _on_windows():
42 appdata = os.getenv("LOCALAPPDATA")
43 if appdata is None:
44 raise GlobusSDKUsageError(
45 "LOCALAPPDATA not detected in Windows environment. "
46 "Either ensure this variable is set or pass an explicit "
47 "config_dir to LocalGlobusConnectPersonal"
48 )
49 return os.path.join(appdata, "Globus Connect")
50 return os.path.expanduser("~/.globusonline")
51
52 @property
53 def config_dir(self) -> str:
54 """
55 The ``config_dir`` for this endpoint.
56
57 If no directory was given during initialization, this will be computed
58 based on the current platform and environment.
59 """
60 if not self._config_dir:
61 self._config_dir = self._detect_config_dir()
62 return self._config_dir
63
64 @property
65 def _local_data_dir(self) -> str:
66 return (
67 self.config_dir if _on_windows() else os.path.join(self.config_dir, "lta")
68 )
69
70 @t.overload
71 def get_owner_info(
72 self,
73 ) -> globus_sdk.GlobusConnectPersonalOwnerInfo | None: ...
74
75 @t.overload
76 def get_owner_info(
77 self, auth_client: None
78 ) -> globus_sdk.GlobusConnectPersonalOwnerInfo | None: ...
79
80 @t.overload
81 def get_owner_info(
82 self, auth_client: globus_sdk.AuthClient
83 ) -> dict[str, t.Any] | None: ...
84
85 def get_owner_info(
86 self, auth_client: globus_sdk.AuthClient | None = None
87 ) -> None | globus_sdk.GlobusConnectPersonalOwnerInfo | dict[str, t.Any]:
88 """
89 Look up the local GCP information, returning a
90 :class:`GlobusConnectPersonalOwnerInfo` object. The result may have an ``id`` or
91 ``username`` set (depending on the underlying data).
92
93 If you pass an AuthClient, this method will return a dict from the Get
94 Identities API instead of the info object. This can fail (e.g. with network
95 errors if there is no connectivity), so passing this value should be coupled
96 with additional error handling.
97
98 In either case, the result may be ``None`` if the data is missing or cannot be
99 parsed.
100
101 .. note::
102
103 The data returned by this method is not checked for accuracy. It is
104 possible for a user to modify the files used by GCP to list a different
105 user.
106
107 :param auth_client: An AuthClient to use to lookup the full identity information
108 for the GCP owner
109
110 **Examples**
111
112 Getting a username:
113
114 >>> from globus_sdk import LocalGlobusConnectPersonal
115 >>> local_gcp = LocalGlobusConnectPersonal()
116 >>> local_gcp.get_owner_info()
117 GlobusConnectPersonalOwnerInfo(username='[email protected]')
118
119 or you may get back an ID:
120
121 >>> local_gcp = LocalGlobusConnectPersonal()
122 >>> local_gcp.get_owner_info()
123 GlobusConnectPersonalOwnerInfo(id='7deda7cc-077b-11ec-a137-67523ecffd4b')
124
125 Check the result easily by looking to see if these values are ``None``:
126
127 >>> local_gcp = LocalGlobusConnectPersonal()
128 >>> info = local_gcp.get_owner_info()
129 >>> has_username = info.username is not None
130 """
131 fname = os.path.join(self._local_data_dir, "gridmap")
132 try:
133 # read file data into an owner info object
134 try:
135 owner_info = GlobusConnectPersonalOwnerInfo._from_file(fname)
136 except ValueError: # may ValueError on invalid DN data
137 return None
138 except OSError as e:
139 # no such file or directory
140 if e.errno == 2:
141 return None
142 raise
143
144 if auth_client is None:
145 return owner_info
146
147 if owner_info.id is not None:
148 res = auth_client.get_identities(ids=owner_info.id)
149 elif owner_info.username is not None:
150 res = auth_client.get_identities(usernames=owner_info.username)
151 else: # pragma: no cover
152 raise ValueError("Something went wrong. Could not parse owner info.")
153
154 try: # could get no data back in theory, if the identity isn't visible
155 return t.cast(t.Dict[str, t.Any], res["identities"][0])
156 except (KeyError, IndexError):
157 return None
158
159 @property
160 def endpoint_id(self) -> str | None:
161 """
162 The endpoint ID of the local Globus Connect Personal endpoint
163 installation.
164
165 This value is loaded whenever it is first accessed, but saved after
166 that.
167
168 .. note::
169
170 This attribute is not checked for accuracy. It is possible for a user to
171 modify the files used by GCP to list a different ``endpoint_id``.
172
173 Usage:
174
175 >>> from globus_sdk import TransferClient, LocalGlobusConnectPersonal
176 >>> local_ep = LocalGlobusConnectPersonal()
177 >>> ep_id = local_ep.endpoint_id
178 >>> tc = TransferClient(...) # needs auth details
179 >>> for f in tc.operation_ls(ep_id):
180 >>> print("Local file: ", f["name"])
181
182 You can also reset the value, causing it to load again on next access,
183 with ``del local_ep.endpoint_id``
184 """
185 if self._endpoint_id is None:
186 fname = os.path.join(self._local_data_dir, "client-id.txt")
187 try:
188 with open(fname, encoding="utf-8") as fp:
189 self._endpoint_id = fp.read().strip()
190 except OSError as e:
191 # no such file or directory gets ignored, everything else reraise
192 if e.errno != 2:
193 raise
194 return self._endpoint_id
195
196 @endpoint_id.deleter
197 def endpoint_id(self) -> None:
198 """
199 Deleter for LocalGlobusConnectPersonal.endpoint_id
200 """
201 self._endpoint_id = None