Package: python-irodsclient
Python iRODS Client (PRC)iRODSis an open source distributed data management system. This is a client API implemented in Python.Currently supported:Python 2.7, 3.4 or newerEstablish a connection to iRODSAuthenticate via password, GSI, PAMiRODS connection over SSLImplement basic GenQueries (select columns and filtering)Support more advanced GenQueries with limits, offsets, and aggregationsQuery the collections and data objects within a collectionExecute direct SQL queriesExecute iRODS rulesSupport read, write, and seek operations for filesParallel PUT/GET data objectsCreate collectionsRename collectionsDelete collectionsCreate data objectsRename data objectsChecksum data objectsDelete data objectsRegister files and directoriesQuery metadata for collections and data objectsAdd, edit, remove metadataReplicate data objects to different resource serversConnection pool managementImplement GenQuery result sets as lazy queriesReturn empty result sets when CAT_NO_ROWS_FOUND is raisedManage permissionsManage users and groupsManage resourcesUnicode stringsTicket based accessInstallingPRC requires Python 2.7 or 3.4+.Canonically, to install with pip:pip install python-irodsclientor:pip install git+https://github.com/irods/python-irodsclient.git[@branch|@commit|@tag]Uninstallingpip uninstall python-irodsclientHazard: Outdated PythonWith older versions of Python (as of this writing, the aforementioned
2.7 and 3.4), we can take preparatory steps toward securing workable
versions of pip and virtualenv by using these commands:$ pip install --upgrade --user pip'<21.0'
$ python -m pip install --user virtualenvWe are then ready to use any of the following commands relevant to and
required for the installation:$ python -m virtualenv ... 
$ python -m pip install ...Establishing a (secure) connectionOne way of starting a session is to pass iRODS credentials as keyword
arguments:>>>fromirods.sessionimportiRODSSession>>>withiRODSSession(host='localhost',port=1247,user='bob',password='1234',zone='tempZone')assession:...# workload...>>>If you're an administrator acting on behalf of another user:>>>fromirods.sessionimportiRODSSession>>>withiRODSSession(host='localhost',port=1247,user='rods',password='1234',zone='tempZone',client_user='bob',client_zone='possibly_another_zone')assession:...# workload...>>>If noclient_zoneis provided, thezoneparameter is used in its place.Using environment files (including any SSL settings) in~/.irods/:>>>importos>>>importssl>>>fromirods.sessionimportiRODSSession>>>try:...env_file=os.environ['IRODS_ENVIRONMENT_FILE']...exceptKeyError:...env_file=os.path.expanduser('~/.irods/irods_environment.json')...>>>ssl_settings={}# Or, optionally: {'ssl_context': <user_customized_SSLContext>}>>>withiRODSSession(irods_env_file=env_file,**ssl_settings)assession:...# workload...>>>In the above example, an SSL connection can be made even if no
'ssl_context' argument is specified, in which case the Python client
internally generates its own SSLContext object to best match the iRODS
SSL configuration parameters (such as
"irods_ssl_ca_certificate_file", etc.) used to initialize the
iRODSSession. Those parameters can be given either in the environment
file, or in the iRODSSession constructor call as shown by the next
example.A pure Python SSL session (without a localenv_filerequires a few more things defined:>>>importssl>>>fromirods.sessionimportiRODSSession>>>ssl_settings={'client_server_negotiation':'request_server_negotiation',...'client_server_policy':'CS_NEG_REQUIRE',...'encryption_algorithm':'AES-256-CBC',...'encryption_key_size':32,...'encryption_num_hash_rounds':16,...'encryption_salt_size':8,...'ssl_context':ssl_context...'ssl_verify_server':'cert',...'ssl_ca_certificate_file':'/etc/irods/ssl/irods.crt'...}If necessary, a user may provide a custom SSLContext object; although,
as of release v1.1.6, this will rarely be required:>>>ssl_settings['ssl_context']=ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH,# ... other options...)At this point, we are ready to instantiate and use the session:>>>withiRODSSession(host='irods-provider',port=1247,user='bob',password='1234',zone='tempZone',**ssl_settings)assession:...# workloadNote that theirods_prefix is unnecessary when providing
theencryption_*andssl_*options
directly to the constructor as keyword arguments, even though it is
required when they are placed in the environment file.Maintaining a connectionThe default library timeout for a connection to an iRODS Server is 120
seconds.This can be overridden by changing the sessionconnection_timeoutimmediately after creation of the
session object:>>>session.connection_timeout=300This will set the timeout to five minutes for any associated
connections.Session objects and cleanupWhen iRODSSession objects are kept as state in an application, spurious
SYS_HEADER_READ_LEN_ERR errors can sometimes be seen in the
connected iRODS server's log file. This is frequently seen at program
exit because socket connections are terminated without having been
closed out by the session object's cleanup() method.Starting with PRC Release 0.9.0, code has been included in the session
object's__del__method to call cleanup(), properly closing out
network connections. However,__del__cannot be relied to run under
all circumstances (Python2 being more problematic), so an alternative
may be to call session.cleanup() on any session variable which might not
be used again.Simple PUTs and GETsWe can use the just-created session object to put files to (or get them
from) iRODS.>>>logical_path="/{0.zone}/home/{0.username}/{1}".format(session,"myfile.dat")>>>session.data_objects.put("myfile.dat",logical_path)>>>session.data_objects.get(logical_path,"/tmp/myfile.dat.copy")Note that local file paths may be relative, but iRODS data objects must
always be referred to by their absolute paths. This is in contrast to
theiputandigeticommands, which keep track of the current working
collection (as modified byicd) for the unix shell.Parallel TransferStarting with release 0.9.0, data object transfers using put() and get()
will spawn a number of threads in order to optimize performance for
iRODS server versions 4.2.9+ and file sizes larger than a default
threshold value of 32 Megabytes.Working with collections>>>coll=session.collections.get("/tempZone/home/rods")>>>coll.id45798>>>coll.path/tempZone/home/rods>>>forcolincoll.subcollections:>>>print(col)<iRODSCollection/tempZone/home/rods/subcol1><iRODSCollection/tempZone/home/rods/subcol2>>>>forobjincoll.data_objects:>>>print(obj)<iRODSDataObject/tempZone/home/rods/file.txt><iRODSDataObject/tempZone/home/rods/file2.txt>Create a new collection:>>>coll=session.collections.create("/tempZone/home/rods/testdir")>>>coll.id45799Working with data objects (files)Create a new data object:>>>obj=session.data_objects.create("/tempZone/home/rods/test1")<iRODSDataObject/tempZone/home/rods/test1>Get an existing data object:>>>obj=session.data_objects.get("/tempZone/home/rods/test1")>>>obj.id12345>>>obj.nametest1>>>obj.collection<iRODSCollection/tempZone/home/rods>>>>forreplicainobj.replicas:...print(replica.resource_name)...print(replica.number)...print(replica.path)...print(replica.status)...demoResc0/var/lib/irods/Vault/home/rods/test11Using the put() method rather than the create() method will trigger different policy enforcement points (PEPs) on the server.Put an existing file as a new data object:>>>session.data_objects.put("test.txt","/tempZone/home/rods/test2")>>>obj2=session.data_objects.get("/tempZone/home/rods/test2")>>>obj2.id56789Specifying pathsPath strings for collection and data objects are usually expected to be
absolute in most contexts in the PRC. They must also be normalized to a
form including single slashes separating path elements and no slashes at
the string's end. If there is any doubt that a path string fulfills
this requirement, the wrapper classirods.path.iRODSPath(a subclass ofstr) may be used to normalize it:if not session.collections.exists( iRODSPath( potentially_unnormalized_path )): #....The wrapper serves also as a path joiner; thus:iRODSPath( zone, "home", user )may replace:"/".join(["", zone, "home", user])iRODSPathis available beginning with PRC releasev1.1.2.Reading and writing filesPRC providesfile-like
objectsfor reading and writing files.>>>obj=session.data_objects.get("/tempZone/home/rods/test1")>>>withobj.open('r+')asf:...f.write('foonbarn')...f.seek(0,0)...forlineinf:...print(line)...foobarAs of v1.1.9, there is also an auto-close configuration setting for data
objects, set toFalseby default, which may be assigned
the valueTruefor guaranteed auto-closing of open data
object handles at the proper time.In a small but illustrative example, the following Python session does
not require an explicit call tof.close():>>>importirods.client_configurationasconfig,irods.test.helpersashelpers>>>config.data_objects.auto_close=True>>>session=helpers.make_session()>>>f=session.data_objects.open('/{0.zone}/home/{0.username}/new_object.txt'.format(session),'w')>>>f.write(b'new content.')This may be useful for Python programs in which frequent flushing of
write updates to data objects is undesirable -- with descriptors on such
objects possibly being held open for indeterminately long lifetimes --
yet the eventual application of those updates prior to the teardown of
the Python interpreter is required.The current value of the setting is global in scope (i.e. applies to all
sessions, whenever created) and is always consulted for the creation of
any data object handle to govern that handle's cleanup behavior.Python iRODS Client Settings FileAs of v1.1.9, Python iRODS client configuration can be saved in, and
loaded from, a settings file.If the settings file exists, each of its lines contains (a) a dotted
name identifying a particular configuration setting to be assigned
within the PRC, potentially changing its runtime behavior; and (b) the
specific value, in Python "repr"-style format, that should be assigned
into it.An example follows:data_objects.auto_close TrueNew dotted names may be created following the example of the one valid
example created thus far,data_objects.auto_close],
initialized inirods/client_configuration/__init__.py.
Each such name should correspond to a globally set value which the PRC
routinely checks when performing the affected library function.The use of a settings file can be indicated, and the path to that file
determined, by setting the environment variable:PYTHON_IRODSCLIENT_CONFIGURATION_PATH. If this variable
is present but empty, this denotes use of a default settings file path
of~/.python-irodsclient; if the variable's value is of
non-zero length, the value should be an absolute path to the settings
file whose use is desired. Also, if the variable is set, auto-load of
settings will be performed, meaning that the act of importingirodsor any of its submodules will cause the automatic
loading the settings from the settings file, assuming it exists.
(Failure to find the file at the indicated path will be logged as a
warning.)Settings can also be saved and loaded manually using thesave()andload()functions in theirods.client_configurationmodule. Each of these functions accepts an optionalfileparameter which, if set to a non-empty string, will override the
settings file path currently "in force" (i.e., the
CONFIG_DEFAULT_PATH, as optionally overridden by the environment
variable PYTHON_IRODSCLIENT_CONFIGURATION_PATH).Configuration settings may also be individually overridden by defining
certain environment variables. Here are relevant descriptions for each
one currently available, including the names of the environment
variables serving as overrides:Setting: Auto-close option for all data objects.Dotted Name:data_objects.auto_closeType:boolDefault Value:FalseEnvironment Variable Override:PYTHON_IRODSCLIENT_CONFIG__DATA_OBJECTS__AUTO_CLOSESetting: Number of hours to request for the new password entry's TTL (Time To Live) when auto-renewing PAM-authenticated sessions.Dotted Name:legacy_auth.pam.time_to_live_in_hoursType:intDefault Value:0(Meaning: conform to server's default TTL value.)Environment Variable Override:PYTHON_IRODSCLIENT_CONFIG__LEGACY_AUTH__PAM__TIME_TO_LIVE_IN_HOURSSetting: Plaintext PAM password value, to be used when auto-renewing PAM-authenticated sessions because TTL has expired.Dotted Name:legacy_auth.pam.password_for_auto_renewType:strDefault Value:""(Meaning: no password is set, and thus no automatic attempts will be made at auto-renewing PAM authentication.)Environment Variable Override:PYTHON_IRODSCLIENT_CONFIG__LEGACY_AUTH__PAM__PASSWORD_FOR_AUTO_RENEW.  (But note that use of the environment variable could pose a threat to password security.)Setting: Whether to write the (native encoded) new hashed password to the iRODS password file.  This step is only performed while auto-renewing PAM authenticated sessions.Dotted Name:legacy_auth.pam.store_password_to_environmentType:boolDefault Value:FalseEnvironment Variable Override:PYTHON_IRODSCLIENT_CONFIG__LEGACY_AUTH__PAM__STORE_PASSWORD_TO_ENVIRONMENTSetting: Default choice of XML parser for all new threads.Dotted Name:connections.xml_parser_defaultType:strDefault Value:"STANDARD_XML"Possible Values: Any of["STANDARD_XML", "QUASI_XML", "SECURE_XML"]Environment Variable Override:PYTHON_IRODSCLIENT_CONFIG__CONNECTIONS__XML_PARSER_DEFAULTFor example, if~/python_irodsclientcontains the line :connections.xml_parser_default        "QUASI_XML"then the session below illustrates the effect of defining the
appropriate environment variable. Note the value stored in the variable
must be a valid input forast.literal_eval(); that is, a
primitive Pythonic value - and quoted, for instance, if a string.$PYTHON_IRODSCLIENT_CONFIGURATION_PATH=""\PYTHON_IRODSCLIENT_CONFIG__CONNECTIONS__XML_PARSER_DEFAULT="'SECURE_XML'"\python-c"import irods.message, irods.client_configuration as c; print (irods.message.default_XML_parser())"XML_Parser_Type.SECURE_XML
$PYTHON_IRODSCLIENT_CONFIGURATION_PATH=""\python-c"import irods.message, irods.client_configuration as c; print (irods.message.default_XML_parser())"XML_Parser_Type.QUASI_XMLComputing and Retrieving ChecksumsEach data object may be associated with a checksum by calling chksum()
on the object in question. Various behaviors can be elicited by passing
in combinations of keywords (for a description of which, please consult
theheader documentation.)As with most other iRODS APIs, it is straightforward to specify keywords
by adding them to an option dictionary:>>>data_object_1.chksum()# - computes the checksum if already in the catalog, otherwise computes and stores it...# (i.e. default behavior with no keywords passed in.)>>>fromirods.manager.data_object_managerimportServer_Checksum_Warning>>>importirods.keywordsaskw>>>opts={kw.VERIFY_CHKSUM_KW:''}>>>try:...data_object_2.chksum(**opts)# - Uses verification option. (Does not auto-vivify a checksum field)....# or:...opts[kw.NO_COMPUTE_KW]=''...data_object_2.chksum(**opts)# - Uses both verification and no-compute options. (Like `ichksum -K --no-compute`)...exceptServer_Checksum_Warning:...print('some checksums are missing or wrong')Additionally, if a freshly createdirods.message.RErrorStackinstance is
given, information can be returned and read by the client:>>>fromirods.messageimportRErrorStack>>>r_err_stk=RErrorStack()>>>warn=None>>>try:# Here, data_obj has one replica, not yet checksummed....data_obj.chksum(r_error=r_err_stk,**{kw.VERIFY_CHKSUM_KW:''})...exceptServer_Checksum_Warningasexc:...warn=exc>>>print(r_err_stk)[RError<message=u'WARNING: No checksum available for replica [0].',status=-862000CAT_NO_CHECKSUM_FOR_REPLICA>]Working with metadataTo enumerate AVUs on an object. With no metadata attached, the result
is an empty list:>>>fromirods.metaimportiRODSMeta>>>obj=session.data_objects.get("/tempZone/home/rods/test1")>>>print(obj.metadata.items())[]We then add some metadata. Just as with the icommand equivalent "imeta
add ...", we can add multiple AVUs with the same name field:>>>obj.metadata.add('key1','value1','units1')>>>obj.metadata.add('key1','value2')>>>obj.metadata.add('key2','value3')>>>obj.metadata.add('key2','value4')>>>print(obj.metadata.items())[<iRODSMeta13182key1value1units1>,<iRODSMeta13185key2value4None>,<iRODSMeta13183key1value2None>,<iRODSMeta13184key2value3None>]We can also use Python's item indexing syntax to perform the equivalent
of an "imeta set ...", e.g. overwriting all AVUs with a name field
of "key2" in a single update:>>>new_meta=iRODSMeta('key2','value5','units2')>>>obj.metadata\[new_meta.name\]=new_meta>>>print(obj.metadata.items())[<iRODSMeta13182key1value1units1>,<iRODSMeta13183key1value2None>,<iRODSMeta13186key2value5units2>]Now, with only one AVU on the object with a name of "key2",get_oneis assured of not throwing an exception:>>>print(obj.metadata.get_one('key2'))<iRODSMeta13186key2value5units2>However, the same is not true of "key1":>>>print(obj.metadata.get_one('key1'))Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>File"/[...]/python-irodsclient/irods/meta.py",line41,inget_oneraiseKeyErrorKeyErrorFinally, to remove a specific AVU from an object:>>>obj.metadata.remove('key1','value1','units1')>>>print(obj.metadata.items())[<iRODSMeta13186key2value5units2>,<iRODSMeta13183key1value2None>]Alternately,thisformofthe`remove()`methodcanalsobeuseful:```python>>>foravuinobj.metadata.items():...obj.metadata.remove(avu)>>>print(obj.metadata.items())[]If we intended on deleting the data object anyway, we could have just
done this instead:>>> obj.unlink(force=True)But notice that the force option is important, since a data object in
the trash may still have AVUs attached.At the end of a long session of AVU add/manipulate/delete operations,
one should make sure to delete all unused AVUs. We can in fact use any*Metadata model in the queries below, since unattached AVUs are
not aware of the (type of) catalog object they once annotated:>>>fromirods.modelsimport(DataObjectMeta,ResourceMeta)>>>len(list(session.query(ResourceMeta)))4>>>fromirods.test.helpersimportremove_unused_metadata>>>remove_unused_metadata(session)>>>len(list(session.query(ResourceMeta)))0When altering a fetched iRODSMeta, we must copy it first to avoid
errors, due to the fact the reference is cached by the iRODS object
reference. A shallow copy is sufficient:>>>meta=album.metadata.items()[0]>>>meta.units'quid'>>>importcopy;meta=copy.copy(meta);meta.units='pounds sterling'>>>album.metadata[meta.name]=metaFortunately, as of PRC >= 1.1.4, we can simply do this instead:>>>album.metadata.set(meta)In versions of iRODS 4.2.12 and later, we can also do:>>>album.metadata.set(meta,\*\*{kw.ADMIN_KW:''})or even:>>>album.metadata(admin=True)\[meta.name\]=metaIn v1.1.5, the "timestamps" keyword is provided to enable the loading
of create and modify timestamps for every AVU returned from the server:>>>avus=album.metadata(timestamps=True).items()>>>avus[0].create_timedatetime.datetime(2022,9,19,15,26,7)Atomic operations on metadataWith release 4.2.8 of iRODS, the atomic metadata API was introduced to
allow a group of metadata add and remove operations to be performed
transactionally, within a single call to the server. This capability can
be leveraged in version 0.8.6 of the PRC.So, for example, if 'obj' is a handle to an object in the iRODS
catalog (whether a data object, collection, user or storage resource),
we can send an arbitrary number of AVUOperation instances to be executed
together as one indivisible operation on that object:>>>fromirods.metaimportiRODSMeta,AVUOperation>>>obj.metadata.apply_atomic_operations(AVUOperation(operation='remove',avu=iRODSMeta('a1','v1','these_units')),...AVUOperation(operation='add',avu=iRODSMeta('a2','v2','those_units')),...AVUOperation(operation='remove',avu=iRODSMeta('a3','v3'))\# , ......)The list of operations will applied in the order given, so that a
"remove" followed by an "add" of the same AVU is, in effect, a
metadata "set" operation. Also note that a "remove" operation will
be ignored if the AVU value given does not exist on the target object at
that point in the sequence of operations.We can also source from a pre-built list of AVUOperations using
Python'sf(*args_list)syntax. For example, this
function uses the atomic metadata API to very quickly remove all AVUs
from an object:>>>defremove_all_avus(Object):...avus_on_Object=Object.metadata.items()...Object.metadata.apply_atomic_operations(*[AVUOperation(operation='remove',avu=i)foriinavus_on_Object])Special CharactersOf course, it is fine to put Unicode characters into your collection and
data object names. However, certain non-printable ASCII characters, and
the backquote character as well, have historically presented problemsespecially for clients using iRODS's human readable XML protocol.
Consider this small, only slighly contrived, application:fromirods.test.helpersimportmake_sessiondefcreate_notes(session,obj_name,content=u''):get_home_coll=lambdases:"/{0.zone}/home/{0.username}".format(ses)path=get_home_coll(session)+"/"+obj_namewithsession.data_objects.open(path,"a")asf:f.seek(0,2)# SEEK_ENDf.write(content.encode('utf8'))returnsession.data_objects.get(path)withmake_session()assession:# Example 1 : exception thrown when name has non-printable charactertry:create_notes(session,"lucky\033.dat",content=u'test')except:pass# Example 2 (Ref. issue: irods/irods #4132, fixed for 4.2.9 release of iRODS)print(create_notes(session,"Alice's diary").name# note diff (' != ') in printed name)This creates two data objects, but with less than optimal success. The
first example object is created but receives no content because an
exception is thrown trying to query its name after creation. In the
second example, for iRODS 4.2.8 and before, a deficiency in packStruct
XML protocol causes the backtick to be read back as an apostrophe, which
could create problems manipulating or deleting the object later.As of PRC v1.1.0, we can mitigate both problems by switching in the
QUASI_XML parser for the default one:from irods.message import (XML_Parser_Type, ET)
    ET( XML_Parser_Type.QUASI_XML, session.server_version )Two dedicated environment variables may also be used to customize the
Python client's XML parsing behavior via the setting of global defaults
during start-up.For example, we can set the default parser to QUASI_XML, optimized for
use with version 4.2.8 of the iRODS server, in the following manner:Bash-Shell> export PYTHON_IRODSCLIENT_DEFAULT_XML=QUASI_XML PYTHON_IRODSCLIENT_QUASI_XML_SERVER_VERSION=4,2,8Other alternatives for PYTHON_IRODSCLIENT_DEFAULT_XML are
"STANDARD_XML" and "SECURE_XML". These two latter options denote
use of the xml.etree and defusedxml modules, respectively.Only the choice of "QUASI_XML" is affected by the specification of a
particular server version.Finally, note that these global defaults, once set, may be overridden on
a per-thread basis usingET(parser_type, server_version).
We can also revert the current thread's XML parser back to the global
default by callingET(None).Rule ExecutionA simple example of how to execute an iRODS rule from the Python client
is as follows. Suppose we have a rule filenative1.rwhich contains a rule in native iRODS Rule Language:main() {
        writeLine("*stream",
                  *X ++ " squared is " ++ str(double(*X)^2) )
    }

    INPUT *X="3", *stream="serverLog"
    OUTPUT nullThe following Python client code will run the rule and produce the
appropriate output in the irods server log:r = irods.rule.Rule( session, rule_file = 'native1.r')
    r.execute()With release v1.1.1, not only can we target a specific rule engine
instance by name (which is useful when more than one is present), but we
can also use a file-like object for therule_fileparameter:Rule( session, rule_file = io.StringIO(u'''mainRule() { anotherRule(*x); writeLine('stdout',*x) }\n'''
                                           u'''anotherRule(*OUT) {*OUT='hello world!'}\n\n'''
                                           u'''OUTPUT ruleExecOut\n'''),
          instance_name = 'irods_rule_engine_plugin-irods_rule_language-instance' )Incidentally, if we wanted to change thenative1.rrule
code print to stdout also, we could set theINPUTparameter,*stream, using the Rule constructor'sparamskeyword argument. Similarly, we can change theOUTPUTparameter fromnulltoruleExecOut, to accommodate the output stream, via theoutputargument:r = irods.rule.Rule( session, rule_file = 'native1.r',
               instance_name = 'irods_rule_engine_plugin-irods_rule_language-instance',
               params={'*stream':'"stdout"'} , output = 'ruleExecOut' )
    output = r.execute( )
    if output and len(output.MsParam_PI):
        buf = output.MsParam_PI[0].inOutStruct.stdoutBuf.buf
        if buf: print(buf.rstrip(b'\0').decode('utf8'))(Changing the input value to be squared in this example is left as an
exercise for the reader!)To deal with errors resulting from rule execution failure, two
approaches can be taken. Suppose we have defined this in the/etc/irods/core.rerule-base:rule_that_fails_with_error_code(*x) {
      *y = (if (*x!="") then int(*x) else 0)
    # if (SOME_PROCEDURE_GOES_WRONG) {
        if (*y < 0) { failmsg(*y,"-- my error message --"); }  #-> throws an error code of int(*x) in REPF
        else { fail(); }                                       #-> throws FAIL_ACTION_ENCOUNTERED_ERR in REPF
    # }
    }We can run the rule thus:>>>Rule(session,body='rule_that_fails_with_error_code(""), instance_name = 'irods_rule_engine_plugin-irods_rule_language-instance',...).execute(r_error=(r_errs:=irods.message.RErrorStack()))Where we've used the Python 3.8 "walrus operator" for brevity. The
error will automatically be caught and translated to a returned-error
stack:>>>pprint.pprint([vars(r)forrinr_errs])[{'raw_msg_':'DEBUG: fail action encountered\n''line 14, col 15, rule base core\n''        else { fail(); }\n''               ^\n''\n','status_':-1220000}]Note, if a stringized negative integer is given , i.e. as a special fail
code to be thrown within the rule, we must add this code into a special
parameter to have this automatically caught as well:>>>Rule(session,body='rule_that_fails_with_error_code("-2")',instance_name='irods_rule_engine_plugin-irods_rule_language-instance'...).execute(acceptable_errors=(FAIL_ACTION_ENCOUNTERED_ERR,-2),...r_error=(r_errs:=irods.message.RErrorStack()))Because the rule is written to emit a custom error message viafailmsg()in this case, the resulting r_error stack will now include that custom
error message as a substring:>>>pprint.pprint([vars(r)forrinr_errs])[{'raw_msg_':'DEBUG: -- my error message --\n''line 21, col 20, rule base core\n''      if (*y < 0) { failmsg(*y,"-- my error message --"); }  ''#-> throws an error code of int(*x) in REPF\n''                    ^\n''\n','status_':-1220000}]Alternatively, or in combination with the automatic catching of errors,
we may also catch errors as exceptions on the client side. For example,
if the Python rule engine is configured, and the following rule is
placed in/etc/irods/core.py:defpython_rule(rule_args,callback,rei):#   if some operation fails():raiseRuntimeErrorwe can trap the error thus:try:Rule(session,body='python_rule',instance_name='irods_rule_engine_plugin-python-instance').execute()exceptirods.exception.RULE_ENGINE_ERROR:print('Rule execution failed!')exit(1)print('Rule execution succeeded!')As fail actions from native rules are not thrown by default (refer to
the help text forRule.execute), if we anticipate these
and prefer to catch them as exceptions, we can do it this way:try:Rule(session,body='python_rule',instance_name='irods_rule_engine_plugin-python-instance').execute(acceptable_errors=())except(irods.exception.RULE_ENGINE_ERROR,irods.exception.FAIL_ACTION_ENCOUNTERED_ERR)ase:print('Rule execution failed!')exit(1)print('Rule execution succeeded!')Finally, keep in mind that rule code submitted through anirods.rule.Ruleobject is processed by the
exec_rule_text function in the targeted plugin instance. This may be a
limitation for plugins not equipped to handle rule code in this way. In
a sort of middle-ground case, the iRODS Python Rule Engine Plugin is not
currently able to handle simple rule calls and the manipulation of iRODS
core primitives (like simple parameter passing and variable expansion')
as flexibly as the iRODS Rule Language.Also, core.py rules may not be run directly (as is also true withirule) by other than a rodsadmin user pending the
resolution ofthis
issue.General Queries>>>importos>>>fromirods.sessionimportiRODSSession>>>fromirods.modelsimportCollection,DataObject>>>>>>env_file=os.path.expanduser('~/.irods/irods_environment.json')>>>withiRODSSession(irods_env_file=env_file)assession:...query=session.query(Collection.name,DataObject.id,DataObject.name,DataObject.size)......forresultinquery:...print('{}/{}id={}size={}'.format(result[Collection.name],result[DataObject.name],result[DataObject.id],result[DataObject.size])).../tempZone/home/rods/manager/access_manager.pyid=212665size=2164/tempZone/home/rods/manager/access_manager.pycid=212668size=2554/tempZone/home/rods/manager/collection_manager.pyid=212663size=4472/tempZone/home/rods/manager/collection_manager.pycid=212664size=4464/tempZone/home/rods/manager/data_object_manager.pyid=212662size=10291/tempZone/home/rods/manager/data_object_manager.pycid=212667size=8772/tempZone/home/rods/manager/__init__.pyid=212670size=79/tempZone/home/rods/manager/__init__.pycid=212671size=443/tempZone/home/rods/manager/metadata_manager.pyid=212660size=4263/tempZone/home/rods/manager/metadata_manager.pycid=212659size=4119/tempZone/home/rods/manager/resource_manager.pyid=212666size=5329/tempZone/home/rods/manager/resource_manager.pycid=212661size=4570/tempZone/home/rods/manager/user_manager.pyid=212669size=5509/tempZone/home/rods/manager/user_manager.pycid=212658size=5233Query using other models:>>>fromirods.columnimportCriterion>>>fromirods.modelsimportDataObject,DataObjectMeta,Collection,CollectionMeta>>>fromirods.sessionimportiRODSSession>>>importos>>>env_file=os.path.expanduser('~/.irods/irods_environment.json')>>>withiRODSSession(irods_env_file=env_file)assession:...# by metadata...# equivalent to 'imeta qu -C type like Project'...results=session.query(Collection,CollectionMeta).filter(\...Criterion('=',CollectionMeta.name,'type')).filter(\...Criterion('like',CollectionMeta.value,'%Project%'))...forrinresults:...print(r[Collection.name],r[CollectionMeta.name],r[CollectionMeta.value],r[CollectionMeta.units])...('/tempZone/home/rods','type','Project',None)Beginning with version 0.8.3 of PRC, the 'in' genquery operator is
also available:>>>fromirods.modelsimportResource>>>fromirods.columnimportIn>>>[resc[Resource.id]forrescinsession.query(Resource).filter(In(Resource.name,['thisResc','thatResc']))][10037,10038]Query with aggregation(min, max, sum, avg, count):>>>withiRODSSession(irods_env_file=env_file)assession:...query=session.query(DataObject.owner_name).count(DataObject.id).sum(DataObject.size)...print(next(query.get_results())){<irods.column.Column411D_OWNER_NAME>:'rods',<irods.column.Column407DATA_SIZE>:62262,<irods.column.Column401D_DATA_ID>:14}In this case since we are expecting only one row we can directly callquery.execute():>>>withiRODSSession(irods_env_file=env_file)assession:...query=session.query(DataObject.owner_name).count(DataObject.id).sum(DataObject.size)...print(query.execute())+--------------+-----------+-----------+|D_OWNER_NAME|D_DATA_ID|DATA_SIZE|+--------------+-----------+-----------+|rods|14|62262|+--------------+-----------+-----------+For a case-insensitive query, add acase_sensitive=Falseparameter to the query:>>>withiRODSSession(irods_env_file=env_file)assession:...query=session.query(DataObject.name,case_sensitive=False).filter(Like(DataObject.name,"%oBjEcT"))...print(query.all())+---------------------+|DATA_NAME|+---------------------+|caseSENSITIVEobject|+---------------------+Specific Queries>>>importos>>>fromirods.sessionimportiRODSSession>>>fromirods.modelsimportCollection,DataObject>>>fromirods.queryimportSpecificQuery>>>>>>env_file=os.path.expanduser('~/.irods/irods_environment.json')>>>withiRODSSession(irods_env_file=env_file)assession:...# define our query...sql="select data_name, data_id from r_data_main join r_coll_main using (coll_id) where coll_name = '/tempZone/home/rods/manager'"...alias='list_data_name_id'...columns=[DataObject.name,DataObject.id]# optional, if we want to get results by key...query=SpecificQuery(session,sql,alias,columns)......# register specific query in iCAT..._=query.register()......forresultinquery:...print('{}{}'.format(result[DataObject.name],result[DataObject.id]))......# delete specific query..._=query.remove()...user_manager.pyc212658metadata_manager.pyc212659metadata_manager.py212660resource_manager.pyc212661data_object_manager.py212662collection_manager.py212663collection_manager.pyc212664access_manager.py212665resource_manager.py212666data_object_manager.pyc212667access_manager.pyc212668user_manager.py212669__init__.py212670__init__.pyc212671Recherché QueriesIn some cases you might like to use a GenQuery operator not directly
offered by this Python library, or even combine query filters in ways
GenQuery may not directly support.As an example, the code below finds metadata value fields
lexicographically outside the range of decimal integers, while also
requiring that the data objects to which they are attached do not reside
in the trash.>>>search_tuple=(DataObject.name,Collection.name,...DataObjectMeta.name,DataObjectMeta.value)>>># "not like" : direct instantiation of Criterion (operator in literal string)>>>not_in_trash=Criterion('not like',Collection.name,'%/trash/%')>>># "not between"( column, X, Y) := column < X OR column > Y ("OR" done via chained iterators)>>>res1=session.query(*search_tuple).filter(not_in_trash).filter(DataObjectMeta.value<'0')>>>res2=session.query(*search_tuple).filter(not_in_trash).filter(DataObjectMeta.value>'9'*9999)>>>chained_results=itertools.chain(res1.get_results(),res2.get_results())>>>pprint(list(chained_results))Instantiating iRODS objects from query resultsThe General query works well for getting information out of the ICAT if
all we're interested in is information representable with primitive
types (i.e. object names, paths, and ID's, as strings or integers). But
Python's object orientation also allows us to create object references
to mirror the persistent entities (instances ofCollection,DataObject,User, orResource, etc.) inhabiting the ICAT.Background:Certain iRODS object types can be instantiated easily
using the session object's custom type managers, particularly if some
parameter (often just the name or path) of the object is already known:>>>type(session.users)<class'irods.manager.user_manager.UserManager'>>>>u=session.users.get('rods')>>>u.id10003Type managers are good for specific operations, including object
creation and removal:>>>session.collections.create('/tempZone/home/rods/subColln')>>>session.collections.remove('/tempZone/home/rods/subColln')>>>session.data_objects.create('/tempZone/home/rods/dataObj')>>>session.data_objects.unlink('/tempZone/home/rods/dataObj')When we retrieve a reference to an existing collection usingget:>>>c=session.collections.get('/tempZone/home/rods')>>>c<iRODSCollection10011rods>we have, in that variablec, a reference to an iRODSCollectionobject whose properties provide useful information:>>>[xforxindir(c)ifnotx.startswith('__')]['_meta','data_objects','id','manager','metadata','move','name','path','remove','subcollections','unregister','walk']>>>c.name'rods'>>>c.path'/tempZone/home/rods'>>>c.data_objects[<iRODSDataObject10019test1>]>>>c.metadata.items()[<...listofAVUsattachedtoCollectionc...>]or whose methods can do useful things:>>>forsub_collinc.walk():print('---');pprint(sub_coll)[...<seriesofPythondatastructuresgivingthecompletetreestructurebelowcollection'c'>...]This approach of finding objects by name, or via their relations with
other objects (ie "contained by", or in the case of metadata,
"attached to"), is helpful if we know something about the location or
identity of what we're searching for, but we don't always have that
kind of a-priori knowledge.So, although we can (as seen in the last example) walk aniRODSCollectionrecursively to discover all subordinate collections
and their data objects, this approach will not always be best for a
given type of application or data discovery, especially in more advanced
use cases.A Different Approach:For the PRC to be sufficiently powerful for general use, we'll often need at least:general queries, andthe capabilities afforded by the PRC's object-relational mapping.Suppose, for example, we wish to enumerate all collections in the iRODS
catalog.Again, the object managers are the answer, but they are now invoked
using a different scheme:>>>fromirods.collectionimportiRODSCollection;fromirods.modelsimportCollection>>>all_collns=[iRODSCollection(session.collections,result)forresultinsession.query(Collection)]From there, we have the ability to do useful work, or filtering based on
the results of the enumeration. And, becauseall_collnsis an
iterable of true objects, we can either use Python's list
comprehensions or execute more catalog queries to achieve further aims.Note that, for similar system-wide queries of Data Objects (which, as it
happens, are inextricably joined to their parent Collection objects), a
bit more finesse is required. Let us query, for example, to find all
data objects in a particular zone with an AVU that matches the following
condition:META_DATA_ATTR_NAME = "irods::alert_time" and META_DATA_ATTR_VALUE like '+0%'>>>importirods.keywords>>>fromirods.data_objectimportiRODSDataObject>>>fromirods.modelsimportDataObjectMeta,DataObject>>>fromirods.columnimportLike>>>q=session.query(DataObject).filter(DataObjectMeta.name=='irods::alert_time',Like(DataObjectMeta.value,'+0%'))>>>zone_hint=""# --> add a zone name in quotes to search another zone>>>ifzone_hint:q=q.add_keyword(irods.keywords.ZONE_KW,zone_hint)>>>forresinq:...colln_id=res[DataObject.collection_id]...collObject=get_collection(colln_id,session,zone=zone_hint)...dataObject=iRODSDataObject(session.data_objects,parent=collObject,results=[res])...print('{coll}/{data}'.format(coll=collObject.path,data=dataObject.name))In the above loop we have used a helper function,get_collection, to
minimize the number of hits to the object catalog. Otherwise, me might
find within a typical application that some Collection objects are being
queried at a high rate of redundancy.get_collectioncan be
implemented thusly:importcollections# of the Pythonic, not iRODS, kinddefmakehash():# see https://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-pythonreturncollections.defaultdict(makehash)fromirods.collectionimportiRODSCollectionfromirods.modelsimportCollectiondefget_collection(Id,session,zone=None,memo=makehash()):ifnotzone:zone=""c_obj=memo[session][zone].get(Id)ifc_objisNone:q=session.query(Collection).filter(Collection.id==Id)ifzone!='':q=q.add_keyword(irods.keywords.ZONE_KW,zone)c_id=q.one()c_obj=iRODSCollection(session,result=c_id)memo[session][zone][Id]=c_objreturnc_objOnce instantiated, of course, anyiRODSDataObject's data to which we
have access permissions is available via its open() method.As stated, this type of object discovery requires some extra study and
effort, but the ability to search arbitrary iRODS zones (to which we are
federated and have the user permissions) is powerful indeed.TicketsTheirods.ticket.Ticketclass lets us issue "tickets"
which grant limited permissions for other users to access our own data
objects (or collections of data objects). As with the iticket client,
the access may be either "read" or "write". The recipient of the
ticket could be a rodsuser, or even an anonymous user.Below is a demonstration of how to generate a new ticket for access to a
logical path - in this case, say a collection containing 1 or more data
objects. (We assume the creation of the granting_session and
receiving_session for the users respectively for the users providing
and consuming the ticket access.)The user who wishes to provide an access may execute the following:>>>fromirods.ticketimportTicket>>>new_ticket=Ticket(granting_session)>>>The_Ticket_String=new_ticket.issue('read',...'/zone/home/my/collection_with_data_objects_for/somebody').stringat which point that ticket's unique string may be given to other users,
who can then apply the ticket to any existing session object in order to
gain access to the intended object(s):>>>fromirods.modelsimportCollection,DataObject>>>ses=receiving_session>>>Ticket(ses,The_Ticket_String).supply()>>>c_result=ses.query(Collection).one()>>>c=iRODSCollection(ses.collections,c_result)>>>fordobjin(c.data_objects):...ses.data_objects.get(dobj.path,'/tmp/'+dobj.name)# download objectsIn this case, however, modification will not be allowed because the
ticket is for read only:>>>c.data_objects[0].open('w').write(# raises...b'new content')#  CAT_NO_ACCESS_PERMISSIONIn another example, we could generate a ticket that explicitly allows
'write' access on a specific data object, thus granting other users
the permissions to modify as well as read it:>>>ses=iRODSSession(user='anonymous',password='',host='localhost',port=1247,zone='tempZone')>>>Ticket(ses,write_data_ticket_string).supply()>>>d_result=ses.query(DataObject.name,Collection.name).one()>>>d_path=(d_result[Collection.name]+'/'+...d_result[DataObject.name])>>>old_content=ses.data_objects.open(d_path,'r').read()>>>withtempfile.NamedTemporaryFile()asf:...f.write(b'blah');f.flush()...ses.data_objects.put(f.name,d_path)As with iticket, we may set a time limit on the availability of a
ticket, either as a timestamp or in seconds since the epoch:>>>t=Ticket(ses);s=t.stringvIOQ6qzrWWPO9X7>>>t.issue('read','/some/path')>>>t.modify('expiry','2021-04-01.12:34:56')# timestamp assumed as UTCTo check the results of the above, we could invoke this icommand
elsewhere in a shell prompt:iticket ls vIOQ6qzrWWPO9X7and the server should report back the same expiration timestamp.And, if we are the issuer of a ticket, we may also query, filter on, and
extract information based on a ticket's attributes and catalog
relations:>>>fromirods.modelsimportTicketQuery>>>delay=lambdasecs:int(time.time()+secs+1)>>>Ticket(ses).issue('read','/path/to/data_object').modify('expiry',delay(7*24*3600))# lasts 1 week>>>Q=ses.query(TicketQuery.Ticket,TicketQuery.DataObject).filter(...TicketQuery.DataObject.name=='data_object')>>>print([_[TicketQuery.Ticket.expiry_ts]for_inQ])['1636757427']Tracking and manipulating replicas of Data ObjectsPutting together the techniques we've seen so far, it's not hard to write client code to accomplish
useful, common tasks.  Suppose, for instance, that a data object contains replicas on a given resource
or resource hierarchy (the "source"), and we want those replicas "moved" to a second resource
(the "destination").  This can be done by combining the replicate and trim operations, as in the following
code excerpt.We'll assume, for our current purposes, that all pre-existing replicas are good (ie. they have astatusattribute of'1'); and that the nodes in question are namedsrcanddest,
withsrcbeing the root node of a resource hierarchy anddestjust a simple storage node.Then we can accomplish the replica "move" thus:path='/path/to/data/object'data=session.data_objects.get('/path/to/data/object')# Replicate the data object to the destination.data.replicate(**{kw.DEST_RESC_NAME_KW:'dest'})# Find and trim replicas on the source resource hierarchy.replica_numbers=[r.numberforrind.replicasifr.resc_hier.startswith('src;')]fornumberinreplica_numbers:session.data_objects.trim(path,**{kw.DATA_REPL_NUM:number,kw.COPIES_KW:1})Listing Users and Groups ; calculating Group MembershipiRODS tracks groups and users using two tables, R_USER_MAIN and
R_USER_GROUP. Under this database schema, all "user groups" are also
users:>>>fromirods.modelsimportUser,Group>>>frompprintimportpprint>>>pprint(list((x[User.id],x[User.name])forxinsession.query(User)))[(10048,'alice'),(10001,'rodsadmin'),(13187,'bobby'),(10045,'collab'),(10003,'rods'),(13193,'empty'),(10002,'public')]But it's also worth noting that the User.type field will be
'rodsgroup' for any user ID that iRODS internally recognizes as a
"Group":>>>groups=session.query(User).filter(User.type=='rodsgroup')>>>[x[User.name]forxingroups]['collab','public','rodsadmin','empty']Since we can instantiate iRODSGroup and iRODSUser objects directly from
the rows of a general query on the corresponding tables, it is also
straightforward to trace out the groups' memberships:>>>fromirods.userimportiRODSUser,iRODSGroup>>>grp_usr_mapping=[(iRODSGroup(session.groups,result),iRODSUser(session.users,result))\...forresultinsession.query(Group,User)]>>>pprint([(x,y)forx,yingrp_usr_mappingifx.id!=y.id])[(<iRODSGroup10045collab>,<iRODSUser10048alicerodsusertempZone>),(<iRODSGroup10001rodsadmin>,<iRODSUser10003rodsrodsadmintempZone>),(<iRODSGroup10002public>,<iRODSUser10003rodsrodsadmintempZone>),(<iRODSGroup10002public>,<iRODSUser10048alicerodsusertempZone>),(<iRODSGroup10045collab>,<iRODSUser13187bobbyrodsusertempZone>),(<iRODSGroup10002public>,<iRODSUser13187bobbyrodsusertempZone>)](Note that in general queries, fields cannot be compared to each other,
only to literal constants; thus the '!=' comparison in the Python list
comprehension.)From the above, we can see that the group 'collab' (with user ID
10045) contains users 'bobby'(13187) and 'alice'(10048) but not
'rods'(10003), as the tuple (10045,10003) is not listed. Group
'rodsadmin'(10001) contains user 'rods'(10003) but no other users;
and group 'public'(10002) by default contains all canonical users
(those whose User.type is 'rodsadmin' or 'rodsuser'). The empty
group ('empty') has no users as members, so it doesn't show up in our
final list.Group Administrator CapabilitiesWith v1.1.7, PRC acquires the full range of abilities possessed by the
igroupadmin command.Firstly, a groupadmin may invoke methods to create groups, and may add
users to, or remove them from, any group to which they themselves
belong:>>>session.groups.create('lab')>>>session.groups.addmember('lab',session.username)# allow self to administer group>>>session.groups.addmember('lab','otheruser')>>>session.groups.removemember('lab','otheruser')In addition, a groupadmin may also create accounts for new users and
enable their logins by initializing a native password for them:>>>session.users.create_with_password('alice','change_me')iRODS Permissions (ACLs)TheiRODSAccessclass offers a convenient dictionary
interface mapping iRODS permission strings to the corresponding integer
codes:>>>fromirods.accessimportiRODSAccess>>>iRODSAccess.keys()['null','read_metadata','read_object','create_metadata','modify_metadata','delete_metadata','create_object','modify_object','delete_object','own']>>>WRITE=iRODSAccess.to_int('modify_object')Armed with that, we can then query on all data objects with ACLs that
allow our user to write them:>>>fromirods.modelsimport(DataObject,User,DataAccess)>>>data_objects_writable=list(session.query(DataObject,User,DataAccess).filter(User.name==session.username,DataAccess.type>=WRITE))Finally, we can also access the list of permissions available through a
given session object via theavailable_permissionsproperty. Note that -- in keeping with changes in iRODS server 4.3 --
the permissions list will be longer, as appropriate, for session objects
connected to the more recent servers; and also that the embedded spaces
in some 4.2 permission strings will be replaced by underscores in 4.3
and later.>>>session.server_version(4,2,11)>>>session.available_permissions.items()[('null',1000),('read object',1050),('modify object',1120),('own',1200)]Getting and setting permissionsWe can find the ID's of all the collections writable (ie having
"modify" ACL) by, but not owned by, alice (or even alice#otherZone):>>>fromirods.modelsimportCollection,CollectionAccess,CollectionUser,User>>>fromirods.columnimportLike>>>q=session.query(Collection,CollectionAccess).filter(...CollectionUser.name=='alice',# User.zone == 'otherZone', # zone optional...Like(CollectionAccess.name,'modify%'))#defaults to current zoneIf we then want to downgrade those permissions to read-only, we can do
the following:>>>fromirods.accessimportiRODSAccess>>>forcinq:...session.acls.set(iRODSAccess('read',c[Collection.name],'alice',# 'otherZone' # zone optional...))A call tosession.acls.get(c)-- withcbeing the result ofsessions.collections.get(c[Collection.name])-- would
then verify the desired change had taken place (as well as list all ACLs
stored in the catalog for that collection).One last note on permissions: The older access manager,<session>.permissions, produced inconsistent results when
theget()method was invoked with the parameterreport_raw_aclsset (or defaulting) toFalse. Specifically, collections would exhibit the
"non-raw-ACL" behavior of reporting individual member users'
permissions as a by-product of group ACLs, whereas data objects would
not.In release v1.1.6, we moved to correct this inconsistency by introducing
the synonym<session>.aclsthat acts almost identically
like<session>.permissions, except that the<session>.acls.get(...)method does not accept thereport_raw_aclsparameter. When we need to detect users'
permissions independent of their access to an object via group
membership, this can be achieved with another query.<session>.permissionswas therefore removed in v2.0.0
in favor of<session>.acls.Quotas (v2.0.0)Quotas may be set for a group:session.groups.set_quota('my_group',50000,resource='my_limited_resource')or per user, prior to iRODS 4.3.0:session.users.set_quota('alice',100000)(The default for the resource parameter is "total", denoting a general
quota usage not bound to a particular resource.)The Quota model is also available for queries. So, to determine the
space remaining for a certain group on a given resource:fromirods.modelsimportQuotasession.groups.calculate_usage()group,resource=['my_group','my_limited_resource']space_left_in_bytes=list(session.query(Quota.over).filter(Quota.user_id==session.groups.get(group).id,Quota.resc_id==session.resources.get(resource).id))[0][Quota.over]*-1And, to remove all quotas for a given group, one might (as a rodsadmin)
do the following:fromirods.modelsimportResource,Quotaresc_map=dict([(x[Resource.id],x[Resource.name])forxinsess.query(Resource)]+[(0,'total')])group=sess.groups.get('my_group')forquotainsess.query(Quota).filter(Quota.user_id==group.id):sess.groups.remove_quota(group.name,resource=resc_map[quota.resc_id])Managing usersYou can create a user in the current zone (with an optional auth_str):>>>session.users.create('user','rodsuser','MyZone',auth_str)If you want to create a user in a federated zone, use:>>>session.users.create('user','rodsuser','OtherZone',auth_str)And more ...Additional code samples are available in thetest
directoryTestingSetting up and running testsThe Python iRODS Client comes with its own suite of tests. Some amount
of setting up may be necessary first:Useiinitto specify the iRODS client environment.
For best results, point the client at a server running on the local
host.Install the python-irodsclient along with theunittest unittest_xml_reportingmodule or the olderxmlrunnerequivalent.for PRC versions 1.1.1 and later:pip install ./path-to-python-irodsclient-repo[tests](when using a local Git repo); or,pip install python-irodsclient[tests]'>=1.1.1'(when installing directly from PyPI).earlier releases (<= 1.1.0) will install the outdatedxmlrunnermodule automaticallyFollow further instructions in thetest
directoryTesting S3 parallel transferSystem requirements:- Ubuntu 18 user with Docker installed.
- Local instance of iRODS server running.
- Logged in sudo privileges.Run a MinIO service:$ docker run -d -p 9000:9000 -p 9001:9001 minio/minio server /data --console-address ":9001"Set up a buckets3://irodsunder MinIO:$ pip install awscli

$ aws configure
AWS Access Key ID [None]: minioadmin
AWS Secret Access Key [None]: minioadmin
Default region name [None]:
Default output format [None]:

$ aws --endpoint-url http://127.0.0.1:9000 s3 mb s3://irodsSet up s3 credentials for the iRODS s3 storage resource:$ sudo su - irods -c "/bin/echo -e 'minioadmin\nminioadmin' >/var/lib/irods/s3-credentials"
$ sudo chown 600 /var/lib/irods/s3-credentialsCreate the s3 storage resource:$ sudo apt install irods-resource-plugin-s3As the 'irods' service account user:$ iadmin mkresc s3resc s3 $(hostname):/irods/ \
  "S3_DEFAULT_HOSTNAME=localhost:9000;"\
  "S3_AUTH_FILE=/var/lib/irods/s3-credentials;"\
  "S3_REGIONNAME=us-east-1;"\
  "S3_RETRY_COUNT=1;"\
  "S3_WAIT_TIME_SEC=3;"\
  "S3_PROTO=HTTP;"\
  "ARCHIVE_NAMING_POLICY=consistent;"\
  "HOST_MODE=cacheless_attached"

$ dd if=/dev/urandom of=largefile count=40k bs=1k # create 40-megabyte test file

$ pip install 'python-irodsclient>=1.1.2'

$ python -c"from irods.test.helpers import make_session
            import irods.keywords as kw
            with make_session() as sess:
                sess.data_objects.put( 'largefile',
                                       '/tempZone/home/rods/largeFile1',
                                       **{kw.DEST_RESC_NAME_KW:'s3resc'} )
                sess.data_objects.get( '/tempZone/home/rods/largeFile1',
                                       '/tmp/largefile')