Commit a5560a69 authored by Staiger, Christine's avatar Staiger, Christine
Browse files

Update 07-python-API-for-users.ipynb

parent fd508a1a
......@@ -102,7 +102,7 @@
"from irods.session import iRODSSession\n",
"session = iRODSSession(host='scomp1447.wurnet.nl', \n",
" port=1247, user='irods-user1', \n",
" password='irods-user1', zone='aliceZone', \n",
" password='<your password>', zone='aliceZone', \n",
" **{\"irods_default_hash_scheme\": \"MD5\"})"
]
},
......
%% Cell type:markdown id: tags:
# Introduction Python API for iRODS
**Authors**
- Arthur Newton (SURFsara)
- Christine Staiger (SURFsara)
- Claudia Behnke (SURFsara)
**License**
Copyright 2018 SURFsara BV
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
## Goal
You will learn how to interact with iRODS via the python API. In this module we will explore the API in interactive mode. You will:
- Up and download data
- Up and download data collections
- Add and edit metadata
- Set Accession control lists for data objects and collections
- Query for data using user defined metadata
## Exploring the python API to iRODS in ipython
We prepared some data for you. Please clone the repository to your home folder:
%% Cell type:code id: tags:
``` python
!git clone https://git.wur.nl/staig001/irodstraining.git
```
%% Cell type:code id: tags:
``` python
%cd irodstraining/
%ls
```
%% Cell type:markdown id: tags:
### Prerequisites
- Credentials and access to an iRODS instance
- [python-irodsclient](https://github.com/irods/python-irodsclient)
Install the *irods-pythonclient*:
%% Cell type:code id: tags:
``` python
pip install --upgrade python-irodsclient
```
%% Cell type:code id: tags:
``` python
import irods
irods.__version__
```
%% Cell type:markdown id: tags:
## Data objects
### Connect to iRODS
To connect we need information on the iRODS server, your user name and other details that the iRODS admin can provide you with.
Note, in the tutorial we are working with open passwords. In real life please protect your passwords by loading them from encrypted files or getting them interactively e.g. with the getpass module in python.
%% Cell type:code id: tags:
``` python
from irods.session import iRODSSession
session = iRODSSession(host='scomp1447.wurnet.nl',
port=1247, user='irods-user1',
password='irods-user1', zone='aliceZone',
password='<your password>', zone='aliceZone',
**{"irods_default_hash_scheme": "MD5"})
```
%% Cell type:markdown id: tags:
The main parameters needed to establish the connection are *host*, *port*, *user* and *password*. We can give other parameters which will set certain behaviour. Here for example we set that iRODS will by default create md5 checksums to verify the integrity of the data.
Now let's list what data we have in our iRODS account:
%% Cell type:code id: tags:
``` python
coll = session.collections.get('/aliceZone/home/irods-user1')
print(coll.path)
print(coll.data_objects)
print(coll.subcollections)
```
%% Cell type:markdown id: tags:
There is not much or no data stored yet.
Since we will need our home-collection path much more often in this tutorial let us save it in an extra variable:
%% Cell type:code id: tags:
``` python
iHome = coll.path
```
%% Cell type:markdown id: tags:
### Upload a data object
The preferred way to upload data to iRODS is a data object *put*.
Now we create the logical path and upload the German version of Alice in wonderland to iRODS. Note, we will also ensure that a checksum is created and verified:
%% Cell type:code id: tags:
``` python
import irods.keywords as kw
# options for storing the checksum in the iCAT and verification of the checksum upon upload
options = {kw.VERIFY_CHKSUM_KW: '', kw.REG_CHKSUM_KW: "regChksum"}
iPath = iHome+'/Alice-DE.txt'
session.data_objects.put('aliceInWonderland-DE.txt.utf-8', iPath, **options)
```
%% Cell type:markdown id: tags:
The object carries some vital system information, otherwise it is empty.
%% Cell type:code id: tags:
``` python
obj = session.data_objects.get(iPath)
print("Name: ", obj.name)
print("Owner: ", obj.owner_name)
print("Size: ", obj.size)
print("Checksum:", obj.checksum)
print("Create: ", obj.create_time)
print("Modify: ", obj.modify_time)
print("Metadata: ", obj.metadata.items())
```
%% Cell type:code id: tags:
``` python
vars(obj)
```
%% Cell type:markdown id: tags:
We can do actions and modifications on the data object, e.g renaming it:
%% Cell type:code id: tags:
``` python
session.data_objects.move(obj.path, iHome + '/Alice.txt')
print(coll.data_objects)
```
%% Cell type:markdown id: tags:
### Creating metadata
Working with metadata is not completely intuitive, you need a good understanding of python dictionaries and the iRODS python API classes *dataobject*, *collection*, *iRODSMetaData* and *iRODSMetaCollection*.
We start slowly with first creating some metadata for our data.
Currently, our data object does not carry any user-defined metadata:
%% Cell type:code id: tags:
``` python
iPath = iHome + '/Alice.txt'
obj = session.data_objects.get(iPath)
print(obj.metadata.items())
```
%% Cell type:markdown id: tags:
Create a key, value, unit entry for our data object:
%% Cell type:code id: tags:
``` python
obj.metadata.add('SOURCE', 'python API training', 'version 1')
obj.metadata.add('TYPE', 'test file')
print(obj.metadata.items())
```
%% Cell type:code id: tags:
``` python
[(item.name, item.value, item.units) for item in obj.metadata.items()]
```
%% Cell type:markdown id: tags:
### Download a data object
We can download a data object as follows (note that we use the environment variable 'HOME' that is defined to be your homefolder):
%% Cell type:code id: tags:
``` python
import os
options = {kw.VERIFY_CHKSUM_KW: ''}
localpath = os.environ['HOME']+'/'+os.path.basename(obj.path)
session.data_objects.get(obj.path,local_path=localpath, num_threads=2, **options)
%ls /home/WUR/staig001
```
%% Cell type:markdown id: tags:
### Streaming data
Streaming data is an alternative to upload large data to iRODS or to accumulate data in a data object over time. First you need to create an empty data object in iRODS beofre you can stream in the data.
%% Cell type:code id: tags:
``` python
content = 'My contents!'.encode()
obj = session.data_objects.create(iHome + '/stream.txt')
```
%% Cell type:markdown id: tags:
This will create a place holder for the data object with no further metadata:
%% Cell type:code id: tags:
``` python
print("Name: ", obj.name)
print("Owner: ", obj.owner_name)
print("Size: ", obj.size)
print("Checksum:", obj.checksum)
print("Create: ", obj.create_time)
print("Modify: ", obj.modify_time)
print("Metadata: ", obj.metadata.items())
```
%% Cell type:markdown id: tags:
We can now stream in our data into that placeholder
%% Cell type:code id: tags:
``` python
with obj.open('w') as obj_desc:
obj_desc.write(content)
obj = session.data_objects.get(iHome + '/stream.txt')
```
%% Cell type:markdown id: tags:
Now we check the metadata again:
%% Cell type:code id: tags:
``` python
print("Name: ", obj.name)
print("Owner: ", obj.owner_name)
print("Size: ", obj.size)
print("Checksum:", obj.checksum)
print("Create: ", obj.create_time)
print("Modify: ", obj.modify_time)
print("Metadata: ", obj.metadata.items())
```
%% Cell type:markdown id: tags:
### Deleting data
With the python API you can only unlink data:
```py
obj.unlink()
```
This will move the data object to its respective location under */zone/trash/home/user/obj* but it will not remove the data from the iRODS instance and will also not clean up the data storage and metadata entries.
%% Cell type:code id: tags:
``` python
print(coll.data_objects)
obj.unlink()
print(coll.data_objects)
```
%% Cell type:markdown id: tags:
## iRODS collections
You can organise your data in iRODS just like on a POSIX file system.
### Create a collection (even recursively)
... and list its content
%% Cell type:code id: tags:
``` python
session.collections.create(iHome + '/Books/Alice')
print(coll.path)
coll.subcollections
```
%% Cell type:markdown id: tags:
Now we can move the Alice in Wonderland text in that collection.
%% Cell type:code id: tags:
``` python
coll = session.collections.get(iHome + '/Books/Alice')
coll.data_objects
session.data_objects.move(iHome + '/Alice.txt', coll.path)
print(coll.data_objects)
```
%% Cell type:markdown id: tags:
### Move a collection
Just as data objects you can also move and rename collections with all their data objects and subcollections:
%% Cell type:code id: tags:
``` python
session.collections.move(iHome + '/Books', iHome + '/MyBooks')
coll = session.collections.get(iHome)
coll.subcollections
```
%% Cell type:markdown id: tags:
### Remove a Collection
Remove a collection recursively with all data objects.
%% Cell type:code id: tags:
``` python
coll = session.collections.get(iHome + '/MyBooks')
coll.remove(recurse=True)
```
%% Cell type:markdown id: tags:
Do not be fooled, the python object 'coll' looks like as if the collection is still in iRODS. You need to refetch the collection (refresh).
%% Cell type:code id: tags:
``` python
coll.subcollections
coll = session.collections.get(iHome)
coll.subcollections
```
%% Cell type:markdown id: tags:
### Upload collection
To upload a collection from the unix file system one has to iterate over the directory and create collections and data objects.
We will upload the directory 'aliceInWonderland'
%% Cell type:code id: tags:
``` python
import os
dPath = os.environ['HOME']+'/irodstraining'+'/aliceInWonderland'
print(dPath)
walk = [dPath]
print(walk)
while len(walk) > 0:
for srcDir, dirs, files in os.walk(walk.pop()):
print(srcDir, dirs, files)
walk.extend(dirs)
iPath = iHome + srcDir.split(os.environ['HOME'])[1]
print("CREATE", iPath)
newColl = session.collections.create(iPath)
for fname in files:
print("CREATE", newColl.path+'/'+fname)
session.data_objects.put(srcDir+'/'+fname, newColl.path+'/'+fname)
```
%% Cell type:markdown id: tags:
### Iterate over collection
Similar to we walked over a directory with sub directories and files in the unix file system we can walk over collections and subcollections in iRODS. Here we walk over the whole aliceInWonderland collection and list Collections and Data objects:
%% Cell type:code id: tags:
``` python
for srcColl, colls, objs in coll.walk():
print('C-', srcColl.path)
for o in objs:
print(o.name)
```
%% Cell type:markdown id: tags:
## Sharing data
You can set ACLs on data objects and collections in iRODS.
To check the default ACLs do:
%% Cell type:code id: tags:
``` python
print(session.permissions.get(coll))
print(session.permissions.get(obj))
```
%% Cell type:code id: tags:
``` python
[vars(p) for p in session.permissions.get(coll)]
```
%% Cell type:markdown id: tags:
Here we share a collection with the iRODS group public. Every member of the group will have read rights.
%% Cell type:code id: tags:
``` python
from irods.access import iRODSAccess
acl = iRODSAccess('read', coll.path, 'public', session.zone)
session.permissions.set(acl)
print(session.permissions.get(coll))
```
%% Cell type:markdown id: tags:
To withdraw certain ACLs do:
%% Cell type:code id: tags:
``` python
acl = iRODSAccess('null', coll.path, 'public', session.zone)
session.permissions.set(acl)
print(session.permissions.get(coll))
```
%% Cell type:markdown id: tags:
One can also give 'write' access or set the 'own'ership.
Collections have a special ACL, the 'inherit' ACL. If 'inherit' is set, all subcollections and data objects will inherit their ACLs from their parent collection automatically.
## Searching for data in iRODS
We will now try to find all data in this iRODS instance we have access to and which carries the key *AUTHOR* with value *Lewis Carroll*. And we need to assemble the iRODS logical path. First let us have a look at the information models that iRODS offers:
%% Cell type:code id: tags:
``` python
vars(irods.models)
```
%% Cell type:markdown id: tags:
We see that we have nodels for a Data object, colletcion, storage resource, user and their respective metadata (CollectionMeta, DataObjectMeta, ResourceMeta) etc.
Now let us import some of these models and see how we can use them to search for information on the items in iRODS.
%% Cell type:code id: tags:
``` python
from irods.models import Collection, DataObject, CollectionMeta, DataObjectMeta
```
%% Cell type:markdown id: tags:
We need the collection name and data object name of the data objects. This command will give us all data objec
%% Cell type:code id: tags:
``` python
query = session.query(Collection.name, DataObject.name)
```
%% Cell type:markdown id: tags:
Now we can filter the results for data objects which carry a user-defined metadata item with name 'AUTHOR' and value 'Lewis Carroll'. To this end we have to chain two filters:
%% Cell type:code id: tags:
``` python
filteredQuery = query.filter(DataObjectMeta.name == 'AUTHOR').\
filter(DataObjectMeta.value == 'Lewis Carroll')
print(filteredQuery.all())
```
%% Cell type:markdown id: tags:
Python prints the results neatly on the prompt, however to extract the information and parsing it to other functions is pretty complicated. Every entry you see in the output is not a string, but actually a python object with many functions. That gives you the advantage to link the output to the rows and comlumns in the sql database running in the background of iRODS. For normal user interaction, however, it needs some explanation and help.
### Parsing the iquest output
To work with the results of the query, we need to get them in an iterable format:
%% Cell type:code id: tags:
``` python
results = filteredQuery.get_results()
```
%% Cell type:markdown id: tags:
**Watch out**: *results* is a generator which you can only use once to iterate over.
We can now iterate over the results and build our iRODS paths (*COLL_NAME/DATA_NAME*) of the data files:
%% Cell type:code id: tags:
``` python
iPaths = []
for item in results:
for k in item.keys():
if k.icat_key == 'DATA_NAME':
name = item[k]
elif k.icat_key == 'COLL_NAME':
coll = item[k]
else:
continue
iPaths.append(coll+'/'+name)
print('\n'.join(iPaths))
```
%% Cell type:markdown id: tags:
How did we know which keys to use?
We asked in the query for *Collection.name* and *DataObject.name*.
Have look at these two objects:
%% Cell type:code id: tags:
``` python
print(Collection.name.icat_key)
print(DataObject.name.icat_key)
```
%% Cell type:markdown id: tags:
The *icat_key* is the keyword used in the database behind iRODS to store the information.
Another example: Assume we want to check for the last date of change of the data (Watch out: there is also a DataObjectMeta.modify_time which is the last time of change of the Metadata!)
%% Cell type:code id: tags:
``` python
query = session.query(
DataObject.name,
DataObject.checksum,
DataObject.size,
DataObject.modify_time)
filteredQuery = query.filter(DataObjectMeta.name == 'AUTHOR').\
filter(DataObjectMeta.value == 'Lewis Carroll')
print(filteredQuery.all())
```
%% Cell type:markdown id: tags:
The modify time is given in epoche in the overview. However, when we extract it from the iterator it is presented in datetime:
%% Cell type:code id: tags:
``` python
import time
results = filteredQuery.get_results()
for item in results:
for key in item:
if key.icat_key == "DATA_SIZE":
print(str(item[key]/1024**3)+" GB")
print(item[key])
```
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment