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
|
import ast
import atexit
import copy
import errno
import json
import logging
from numbers import Number
import os
import threading
import weakref
from irods.query import Query
from irods.genquery2 import GenQuery2
from irods.pool import Pool
from irods.account import iRODSAccount
from irods.api_number import api_number
from irods.manager.collection_manager import CollectionManager
from irods.manager.data_object_manager import DataObjectManager
from irods.manager.metadata_manager import MetadataManager
from irods.manager.access_manager import AccessManager
from irods.manager.user_manager import UserManager, GroupManager
from irods.manager.resource_manager import ResourceManager
from irods.manager.zone_manager import ZoneManager
from irods.message import iRODSMessage, STR_PI
from irods.exception import NetworkException, NotImplementedInIRODSServer
from irods.password_obfuscation import decode
from irods import NATIVE_AUTH_SCHEME, PAM_AUTH_SCHEMES
from . import at_client_exit
from . import DEFAULT_CONNECTION_TIMEOUT, MAXIMUM_CONNECTION_TIMEOUT
_fds = None
_fds_lock = threading.Lock()
_sessions = None
_sessions_lock = threading.Lock()
def _cleanup_remaining_sessions():
for fd in list((_fds or {}).keys()):
if not fd.closed:
fd.close()
# remove refs to session objects no longer needed
fd._iRODS_session = None
for ses in (_sessions or []).copy():
ses.cleanup() # internally modifies _sessions
with _sessions_lock:
at_client_exit._register(
at_client_exit.LibraryCleanupStage.DURING, _cleanup_remaining_sessions
)
def _weakly_reference(ses):
global _sessions, _fds
try:
if _sessions is None:
with _sessions_lock:
do_register = _sessions is None
if do_register:
_sessions = weakref.WeakKeyDictionary()
_fds = weakref.WeakKeyDictionary()
finally:
_sessions[ses] = None
logger = logging.getLogger(__name__)
class NonAnonymousLoginWithoutPassword(RuntimeError):
pass
class iRODSSession:
def library_features(self):
irods_version_needed = (4, 3, 1)
if self.server_version < irods_version_needed:
raise NotImplementedInIRODSServer("library_features", irods_version_needed)
message = iRODSMessage(
"RODS_API_REQ", int_info=api_number["GET_LIBRARY_FEATURES_AN"]
)
with self.pool.get_connection() as conn:
conn.send(message)
response = conn.recv()
msg = response.get_main_message(STR_PI)
return json.loads(msg.myStr)
@property
def env_file(self):
return self._env_file
@property
def auth_file(self):
return self._auth_file
@property
def available_permissions(self):
from irods.access import iRODSAccess, _iRODSAccess_pre_4_3_0
try:
self.__access
except AttributeError:
self.__access = (
_iRODSAccess_pre_4_3_0 if self.server_version < (4, 3) else iRODSAccess
)
return self.__access
@property
def groups(self):
class _GroupManager(self.user_groups.__class__):
def create(
self, name, group_admin=None
): # NB new default (see user_groups manager and i/f, with False as default)
user_type = "rodsgroup" # These are no longer parameters in the new interface, as they have no reason to vary.
user_zone = "" # Groups (1) are always of type 'rodsgroup', (2) always belong to the local zone, and
auth_str = "" # (3) do not authenticate.
return super(_GroupManager, self).create(
name,
user_type,
user_zone,
auth_str,
group_admin,
suppress_deprecation_warning=True,
)
def addmember(self, group_name, user_name, user_zone="", group_admin=None):
return super(_GroupManager, self).addmember(
group_name,
user_name,
user_zone,
group_admin,
suppress_deprecation_warning=True,
)
def removemember(
self, group_name, user_name, user_zone="", group_admin=None
):
return super(_GroupManager, self).removemember(
group_name,
user_name,
user_zone,
group_admin,
suppress_deprecation_warning=True,
)
_groups = getattr(self, "_groups", None)
if not _groups:
_groups = self._groups = _GroupManager(self.user_groups.sess)
return self._groups
def __init__(self, configure=True, auto_cleanup=True, **kwargs):
self.pool = None
self.numThreads = 0
self._env_file = ""
self._auth_file = ""
self.do_configure = kwargs if configure else {}
self._cached_connection_timeout = None
self.connection_timeout = kwargs.pop(
"connection_timeout", DEFAULT_CONNECTION_TIMEOUT
)
self.__configured = None
if configure:
self.__configured = self.configure(**kwargs)
self.collections = CollectionManager(self)
self.data_objects = DataObjectManager(self)
self.metadata = MetadataManager(self)
self.acls = AccessManager(self)
self.users = UserManager(self)
self.user_groups = GroupManager(self)
self.resources = ResourceManager(self)
self.zones = ZoneManager(self)
self._auto_cleanup = auto_cleanup
self.ticket__ = ""
# A mapping for each connection - holds whether the session's assigned ticket has been applied.
self.ticket_applied = weakref.WeakKeyDictionary()
if auto_cleanup:
_weakly_reference(self)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.cleanup()
def __del__(self):
self.do_configure = {}
# If self.pool has been fully initialized (ie. no exception was
# raised during __init__), then try to clean up.
if self.pool is not None:
self.cleanup()
def clone(self, **kwargs):
other = copy.copy(self)
other.pool = None
for k, v in vars(self).items():
if getattr(v, "_set_manager_session", None) is not None:
vcopy = copy.copy(v)
# Deep-copy into the manager object for the cloned session and set its parent session
# reference to correspond to the clone.
setattr(other, k, vcopy)
vcopy._set_manager_session(other)
elif isinstance(v, iRODSAccount):
# Deep-copy the iRODSAccount subobject, since we might be setting the hostname on that object.
setattr(other, k, copy.copy(v))
other.cleanup(new_host=kwargs.pop("host", ""))
other.ticket__ = kwargs.pop("ticket", self.ticket__)
other.ticket_applied = weakref.WeakKeyDictionary()
if other._auto_cleanup:
_weakly_reference(other)
return other
def cleanup(self, new_host=""):
if self.pool:
for conn in self.pool.active | self.pool.idle:
try:
conn.disconnect()
except NetworkException:
pass
conn.release(True)
if self.do_configure:
if new_host:
d = self.do_configure.setdefault("_overrides", {})
d["irods_host"] = new_host
self.__configured = None
self.__configured = self.configure(**self.do_configure)
def _configure_account(self, **kwargs):
env_file = None
try:
env_file = kwargs["irods_env_file"]
except KeyError:
# For backward compatibility
for key in ["host", "port", "authentication_scheme"]:
if key in kwargs:
kwargs["irods_{}".format(key)] = kwargs.pop(key)
for key in ["user", "zone"]:
if key in kwargs:
kwargs["irods_{}_name".format(key)] = kwargs.pop(key)
return iRODSAccount(**kwargs)
# Get credentials from irods environment file
creds = self.get_irods_env(env_file, session_=self)
# Update with new keywords arguments only
creds.update((key, value) for key, value in kwargs.items() if key not in creds)
if env_file:
creds["env_file"] = env_file
# Get auth scheme
try:
auth_scheme = creds["irods_authentication_scheme"]
except KeyError:
# default
auth_scheme = "native"
if auth_scheme.lower() in PAM_AUTH_SCHEMES:
# inline password
if "password" in creds:
return iRODSAccount(**creds)
else:
# password will be from irodsA file therefore use native login
# but let PAM still be recorded as the original scheme
creds["irods_authentication_scheme"] = (NATIVE_AUTH_SCHEME, auth_scheme)
elif auth_scheme != "native":
return iRODSAccount(**creds)
# Native auth, try to unscramble password
try:
creds["irods_authentication_uid"] = kwargs["irods_authentication_uid"]
except KeyError:
pass
missing_file_path = []
error_args = []
pw = creds["password"] = self.get_irods_password(
session_=self, file_path_if_not_found=missing_file_path, **creds
)
# For native authentication, a missing password should be flagged as an error for non-anonymous logins.
# However, the pam_password case has its own internal checks.
if auth_scheme.lower() not in PAM_AUTH_SCHEMES:
if not pw and creds.get("irods_user_name") != "anonymous":
if missing_file_path:
error_args += [
"Authentication file not found at {!r}".format(
missing_file_path[0]
)
]
raise NonAnonymousLoginWithoutPassword(*error_args)
return iRODSAccount(**creds)
def configure(self, **kwargs):
account = self.__configured
if not account:
account = self._configure_account(**kwargs)
# so that _login_pam can rewrite auth file with new password if requested:
account._auth_file = getattr(self, "_auth_file", "")
connection_refresh_time = self.get_connection_refresh_time(**kwargs)
logger.debug(
"In iRODSSession's configure(). connection_refresh_time set to {}".format(
connection_refresh_time
)
)
self.pool = Pool(
account,
application_name=kwargs.pop("application_name", ""),
connection_refresh_time=connection_refresh_time,
session=self,
)
conn_timeout = getattr(self, "_cached_connection_timeout", None)
self.pool.connection_timeout = conn_timeout
return account
def query(self, *args, **kwargs):
return Query(self, *args, **kwargs)
def genquery2_object(self, **kwargs):
"""Returns GenQuery2 object
Returns GenQuery2 object that can be used to execute GenQuery2 queries,
to retrieve the SQL query for a particular GenQuery2 query, and to
get GenQuery2 column mappings.
"""
return GenQuery2(self, **kwargs)
def genquery2(self, query, **kwargs):
"""Shorthand for executing a single GenQuery2 query."""
q = GenQuery2(self)
return q.execute(query, **kwargs)
@property
def username(self):
return self.pool.account.client_user
@property
def zone(self):
return self.pool.account.client_zone
@property
def host(self):
return self.pool.account.host
@property
def port(self):
return self.pool.account.port
@property
def server_version(self):
reported_vsn = os.environ.get("PYTHON_IRODSCLIENT_REPORTED_SERVER_VERSION", "")
if reported_vsn:
return tuple(ast.literal_eval(reported_vsn))
return self.__server_version()
def __server_version(self):
try:
conn = next(iter(self.pool.active))
return conn.server_version
except StopIteration:
conn = self.pool.get_connection()
version = conn.server_version
conn.release()
return version
@property
def client_hints(self):
message = iRODSMessage("RODS_API_REQ", int_info=api_number["CLIENT_HINTS_AN"])
with self.pool.get_connection() as conn:
conn.send(message)
response = conn.recv()
return response.get_json_encoded_struct()
@property
def pam_pw_negotiated(self):
self.pool.account.store_pw = []
conn = self.pool.get_connection()
pw = getattr(self.pool.account, "store_pw", [])
delattr(self.pool.account, "store_pw")
conn.release()
return pw
@property
def default_resource(self):
return self.pool.account.default_resource
@default_resource.setter
def default_resource(self, name):
self.pool.account.default_resource = name
@property
def connection_timeout(self):
return self.pool.connection_timeout
@connection_timeout.setter
def connection_timeout(self, seconds):
if seconds == 0:
exc = ValueError(
"Setting an iRODS connection_timeout to 0 seconds would make it non-blocking."
)
raise exc
elif isinstance(seconds, Number):
# Note: We can handle infinities because -Inf < 0 and Inf > MAXIMUM_CONNECTION_TIMEOUT.
if seconds < 0 or str(seconds) == "nan":
exc = ValueError(
"The iRODS connection_timeout may not be assigned a negative, out-of-bounds, or otherwise rogue value (eg: NaN, -Inf)."
)
raise exc
elif seconds > MAXIMUM_CONNECTION_TIMEOUT:
logging.getLogger(__name__).warning(
"Hard limiting connection timeout of %g to the maximum allowable value of %g",
seconds,
MAXIMUM_CONNECTION_TIMEOUT,
)
seconds = MAXIMUM_CONNECTION_TIMEOUT
elif seconds is None:
pass
else:
exc = ValueError(
"The iRODS connection_timeout must be assigned a positive int, positive float, or None."
)
raise exc
self._cached_connection_timeout = seconds
if self.pool:
self.pool.connection_timeout = seconds
@staticmethod
def get_irods_password_file():
try:
return os.environ["IRODS_AUTHENTICATION_FILE"]
except KeyError:
return os.path.expanduser("~/.irods/.irodsA")
@staticmethod
def get_irods_env(env_file, session_=None):
try:
with open(env_file, "rt") as f:
j = json.load(f)
if session_ is not None:
session_._env_file = env_file
return j
except IOError:
logger.debug("Could not open file {}".format(env_file))
return {}
@staticmethod
def get_irods_password(session_=None, file_path_if_not_found=(), **kwargs):
path_memo = []
try:
irods_auth_file = kwargs["irods_authentication_file"]
except KeyError:
irods_auth_file = iRODSSession.get_irods_password_file()
try:
uid = kwargs["irods_authentication_uid"]
except KeyError:
uid = None
_retval = ""
try:
with open(irods_auth_file, "r") as f:
_retval = decode(f.read().rstrip("\n"), uid)
return _retval
except IOError as exc:
if exc.errno != errno.ENOENT:
raise # Auth file exists but can't be read
path_memo = [irods_auth_file]
return "" # No auth file (as with anonymous user)
finally:
if isinstance(file_path_if_not_found, list) and path_memo:
file_path_if_not_found[:] = path_memo
if session_ is not None and _retval:
session_._auth_file = irods_auth_file
def get_connection_refresh_time(self, **kwargs):
connection_refresh_time = -1
connection_refresh_time = int(kwargs.get("refresh_time", -1))
if connection_refresh_time != -1:
return connection_refresh_time
try:
env_file = kwargs["irods_env_file"]
except KeyError:
return connection_refresh_time
if env_file is not None:
env_file_map = self.get_irods_env(env_file)
connection_refresh_time = int(
env_file_map.get("irods_connection_refresh_time", -1)
)
if connection_refresh_time < 1:
# Negative values are not allowed.
logger.debug(
"connection_refresh_time in {} file has value of {}. Only values greater than 1 are allowed.".format(
env_file, connection_refresh_time
)
)
connection_refresh_time = -1
return connection_refresh_time
|