From 4af1f057e2156042def08c79dfb9365856ff5510 Mon Sep 17 00:00:00 2001 From: Tom Zhong Date: Tue, 1 Dec 2026 18:04:30 +1030 Subject: [PATCH] delete obselete builds and files and arrange file structure --- .github/copilot-instructions.md | 11 +- .github/workflows/ci.yml | 4 +- Dockerfile | 29 - INSTALL | 2 +- README.md | 2 +- bitbucket-pipelines.yml | 13 - build_release | 3 + build_test | 2 +- data/.mf_config | 23 - data/__init__.py | 0 docker/Dockerfile.py2env | 11 - docker/Dockerfile.py3env | 11 - keystone.py | 199 ----- makefile | 50 -- profile_pshell | 1 - pshell.spec | 40 - setup.py | 14 - test_all | 11 +- test_mfclient.py => tests/test_mfclient.py | 1 + test_parser.py => tests/test_parser.py | 4 +- test_pshell.py => tests/test_pshell.py | 4 +- test_release.py => tests/test_release.py | 4 +- test_runner.py => tests/test_runner.py | 6 +- test_s3client.py => tests/test_s3client.py | 2 + v3/.mf_config | 155 ---- v3/README | 3 - v3/fuse.py | 978 -------------------- v3/mfclient.py | 989 --------------------- v3/pmount.py | 894 ------------------- v3/test_mfclient.py | 166 ---- v3/test_pshell.py | 92 -- 31 files changed, 32 insertions(+), 3692 deletions(-) delete mode 100644 Dockerfile delete mode 100644 bitbucket-pipelines.yml delete mode 100644 data/.mf_config delete mode 100644 data/__init__.py delete mode 100644 docker/Dockerfile.py2env delete mode 100644 docker/Dockerfile.py3env delete mode 100644 keystone.py delete mode 100644 makefile delete mode 100755 profile_pshell delete mode 100644 pshell.spec delete mode 100644 setup.py rename test_mfclient.py => tests/test_mfclient.py (99%) rename test_parser.py => tests/test_parser.py (96%) rename test_pshell.py => tests/test_pshell.py (95%) rename test_release.py => tests/test_release.py (97%) rename test_runner.py => tests/test_runner.py (90%) rename test_s3client.py => tests/test_s3client.py (99%) delete mode 100644 v3/.mf_config delete mode 100644 v3/README delete mode 100644 v3/fuse.py delete mode 100644 v3/mfclient.py delete mode 100755 v3/pmount.py delete mode 100755 v3/test_mfclient.py delete mode 100755 v3/test_pshell.py diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index c6d9de9..d7b998d 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -5,13 +5,12 @@ SFTP-like command line client for Mediaflux and S3 (Pawsey). Python >= 3.6, stan ## Build, test, run - Run: `python3 pshell.py [-c config] [-v 0|1|2] [-i script] [-o failed_script] [-u url -t mflux|s3] ["cmd1 && cmd2"]` -- All tests: `./test_all` (runs the four main test modules and `test_runner.py` with `python3`; release bundle tests are separate) -- Single module: `python3 test_parser.py` (also `test_mfclient.py`, `test_s3client.py`, `test_pshell.py`) -- The four main test modules use `unittest` with a custom `__main__` that builds the suite from a `test_class_list`. Single method: `python3 -m unittest test_s3client.s3client_standard.test_convert` — except `test_s3client.py`/`test_mfclient.py`, whose `setUp` uses a client global created in `__main__` (and `test_pshell.py`, which uses `config`, `python`, `script`, `verbosity` globals); for those, edit `test_class_list` and run as a script. -- `test_mfclient.py` / `test_s3client.py` use dummy clients (no server needed); `test_pshell.py` runs `pshell.py` as a subprocess and checks exit codes. -- No linter configured. GitHub Actions runs the full suite and release bundle tests on Python 3.9, 3.12 and 3.6 (in a container). The older Bitbucket pipeline only runs `python test_mfclient.py` on python:3.6. +- All tests: `./test_all` (runs the four main test modules and `tests/test_runner.py` with `python3`; release bundle tests are separate) +- Single module: `python3 tests/test_parser.py` (also `tests/test_mfclient.py`, `tests/test_s3client.py`, `tests/test_pshell.py`) +- The four main test modules use `unittest` with a custom `__main__` that builds the suite from a `test_class_list`. Single method: `python3 -m unittest tests.test_s3client.s3client_standard.test_convert` — except `tests/test_s3client.py`/`tests/test_mfclient.py`, whose `setUp` uses a client global created in `__main__` (and `tests/test_pshell.py`, which uses `config`, `python`, `script`, `verbosity` globals); for those, edit `test_class_list` and run as a script. +- `tests/test_mfclient.py` / `tests/test_s3client.py` use dummy clients (no server needed); `tests/test_pshell.py` runs `pshell.py` as a subprocess and checks exit codes. +- No linter configured. GitHub Actions runs the full suite and release bundle tests on Python 3.9, 3.12 and 3.6 (in a container). - Packaging: `build_test` calls `build_release`, which uses `release_main.py` as `__main__.py` and bundles `pshell.py`, `parser.py`, `mfclient.py`, `s3client.py`, `util.py`, `LICENSE`, `NOTICE`, and both dependency sets into an executable zip. Add new application modules to the file list in `build_release`. The release script stamps the `build` line in its staged copy of `pshell.py`. -- `v3/` is a legacy/experimental tree (FUSE mount, older mfclient); `keystone.py` is a standalone helper. Main code is at the repo root. ## Architecture diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bcd470f..d3029d7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,7 +38,7 @@ jobs: run: ./build_test - name: Test executable bundle - run: python test_release.py + run: python tests/test_release.py test-python-36: name: Python 3.6 @@ -63,4 +63,4 @@ jobs: --volume "$GITHUB_WORKSPACE:/workspace" \ --workdir /workspace \ python:3.6.15-bullseye \ - bash -ec 'python -m pip install -r requirements.txt && ./test_all && python test_release.py' + bash -ec 'python -m pip install -r requirements.txt && ./test_all && python tests/test_release.py' diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index da4876f..0000000 --- a/Dockerfile +++ /dev/null @@ -1,29 +0,0 @@ -FROM python:3 - -# won't work without a properly conifgured gcc ... -#RUN pip3 install pyinstaller -#RUN git clone https://bitbucket.org/datapawsey/mfclient.git -# TODO - add to requirements? -# lint checking -#RUN pip3 install pyflakes -# windows building -#RUN pip3 install pynsist - -COPY requirements.txt ./ -RUN pip install --no-cache-dir -r requirements.txt - -COPY pshell.py / -COPY parser.py / -COPY mfclient.py / -COPY s3client.py / -COPY util.py / -COPY test_* / - -# only way I could get this file (which usually sits in ~ into the container) -COPY .pshell_config /root/.pshell_config - -# pshell -#CMD ["python", "./pshell.py", "-v", "1"] - -# tests -CMD ["bash", "./test_all"] diff --git a/INSTALL b/INSTALL index 579031f..015fb33 100644 --- a/INSTALL +++ b/INSTALL @@ -11,7 +11,7 @@ The build includes separate dependency sets for Python 3.6-3.12 and Python Python runtime. Run it with `./release/pshell`. -After building, run `python3 test_release.py` to check the packaged executable. +After building, run `python3 tests/test_release.py` to check the packaged executable. ### Docker diff --git a/README.md b/README.md index f0c657e..ca9290d 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ require a compatible boto3 installation. ### How do I run the tests? ### -Run test_all +Run `./test_all` ### Command line client ### diff --git a/bitbucket-pipelines.yml b/bitbucket-pipelines.yml deleted file mode 100644 index 90f973b..0000000 --- a/bitbucket-pipelines.yml +++ /dev/null @@ -1,13 +0,0 @@ -# This is a sample build configuration for Python. -# Check our guides at https://confluence.atlassian.com/x/x4UWN for more examples. -# Only use spaces to indent your .yml configuration. -# ----- -# You can specify a custom docker image from Docker Hub as your build environment. -image: python:3.6 - -pipelines: - default: - - step: - script: - - echo "testing" - - python test_mfclient.py diff --git a/build_release b/build_release index 8339202..cd1f4b9 100755 --- a/build_release +++ b/build_release @@ -1,6 +1,9 @@ #!/bin/bash set -e +# run from the repository root regardless of invocation directory +cd "$(dirname "$0")" + echo "Building a zip bundle with version timestamp for release" # stage the application and its dependencies outside the release directory diff --git a/build_test b/build_test index d485f10..997b4f1 100755 --- a/build_test +++ b/build_test @@ -2,5 +2,5 @@ set -e echo "Building a zip bundle for testing - use build_release for artifact publishing" -./build_release +"$(dirname "$0")/build_release" diff --git a/data/.mf_config b/data/.mf_config deleted file mode 100644 index b168496..0000000 --- a/data/.mf_config +++ /dev/null @@ -1,23 +0,0 @@ -[pawsey] -server = data.pawsey.org.au -protocol = https -port = 443 -encrypt = True -domain = ivec -namespace = /projects - -[mflux] -server = mflux -protocol = http -port = 80 -encrypt = False -debug = False -domain = system -namespace = / - -[dummy] -server = localhost -protocol = http -port = 80 -domain = system -dummy = True diff --git a/data/__init__.py b/data/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/docker/Dockerfile.py2env b/docker/Dockerfile.py2env deleted file mode 100644 index 2e17ae8..0000000 --- a/docker/Dockerfile.py2env +++ /dev/null @@ -1,11 +0,0 @@ -FROM alpine:3.8 - -RUN apk add git -RUN apk add bash -RUN apk add python2 - -RUN git clone https://bitbucket.org/datapawsey/mfclient.git - -ENTRYPOINT ["/bin/bash"] - -#ENTRYPOINT ["python", "test_mfclient.py"] diff --git a/docker/Dockerfile.py3env b/docker/Dockerfile.py3env deleted file mode 100644 index deb8baa..0000000 --- a/docker/Dockerfile.py3env +++ /dev/null @@ -1,11 +0,0 @@ -FROM alpine:3.8 - -RUN apk add git -RUN apk add bash -RUN apk add python3 - -RUN git clone https://bitbucket.org/datapawsey/mfclient.git - -ENTRYPOINT ["/bin/bash"] - -#ENTRYPOINT ["python", "/mfclient/test_mfclient.py"] diff --git a/keystone.py b/keystone.py deleted file mode 100644 index 79e482f..0000000 --- a/keystone.py +++ /dev/null @@ -1,199 +0,0 @@ -#!/usr/bin/env python3 -# THIS MODULE IS NO LONGER USED - -""" -This module is a Python 3.x (standard lib only) implementation of a simple keystone client -Author: Sean Fleming -""" - -import json -import urllib.request -import getpass -import logging - -######################################################### -class keystone: - """ - Basic Keystone authentication and communication client - """ - - def __init__(self, url): - """ - Create a Keystone server connection instance. - - Args: - url: a STRING which is the full address to the keystone REST API - - Returns: - A keystone object - - Raises: - Error if service appears to be unreachable - TODO - """ - - self.url = url - self.token = "" - self.user = None - self.project_dict = {} - self.credential_list = None - self.logging = logging.getLogger('keystone') -# CURRENT - self.logging.setLevel(logging.DEBUG) - -#------------------------------------------------------------ -# connect to keystone and acquire a token -# NEW - removed all updating mechanisms as ingest cluster is returning server errors for credential queries - which bombs the discovery - def connect(self): - self.logging.info("url=%r" % self.url) -# SSO auth - I don't like the mflux dependency -# self.sso_mfclient(mfclient) -# manual auth - print("Keystone authentication required.") - user = input("User: ") - password = getpass.getpass("Password: ") - self.get_auth_token(user, password) - -#------------------------------------------------------------ - def get_auth_token(self, user, password): - data = '{ "auth": { "identity": { "methods": ["password"], "password": { "user": { "name": "%s", "domain": { "name": "pawsey" }, "password": "%s" } } } } }' % (user, password) - length = len(data) - headers = {"Content-type": "application/json", "Content-length": "%d" % length } - request = urllib.request.Request(self.url + "/v3/auth/tokens", data=data.encode(), headers=headers) - response = urllib.request.urlopen(request) - reply = response.read() - stuff = json.loads(reply) - self.user = stuff['token']['user']['id'] - self.token = response.headers.get('x-subject-token') - self.logging.debug("acquired token for user [%s]" % self.user) - -#------------------------------------------------------------ -# deprec - def sso_mfclient(self, mfclient): - xml_reply = mfclient.aterm_run('user.self.describe') - elem = xml_reply.find(".//user") - user = elem.attrib['user'] - self.logging.debug("accessing mediaflux wallet for user [%s]" % user) -# attempt use secure wallet for SSO - wallet_recreate = False - xml_reply = mfclient.aterm_run("secure.wallet.can.be.used") - elem = xml_reply.find(".//can") - if "true" in elem.text: - self.logging.info("wallet is accessible") - try: - xml_reply = mfclient.aterm_run("secure.wallet.get :key ldap") - elem = xml_reply.find(".//value") - # main call - self.get_auth_token(user, elem.text) - return - except Exception as e: - self.logging.debug(str(e)) - else: - wallet_recreate = True - -# failed due to no key or no useable wallet - print("Keystone authentication for user [%s] required." % user) - password = getpass.getpass("Password: ") - if wallet_recreate is True: - mfclient.aterm_run("secure.wallet.recreate :password %s" % password) -# TODO - encrypt so it's not plain text - mfclient.aterm_run("secure.wallet.set :key ldap :value %s" % password) - self.get_auth_token(user, password) - -#------------------------------------------------------------ - def get_credentials(self): -# get user ec2 credentials - self.logging.info("url=[%s] token=[%r]" % (self.url, self.token)) -# if self.token is None: -# raise Exception("Not authenticated to keystone") - ec2_url = "/v3/users/%s/credentials/OS-EC2" % self.user - headers = {"X-Auth-Token": self.token, "Content-type": "application/json"} - request = urllib.request.Request(self.url + ec2_url, headers=headers) - response = urllib.request.urlopen(request) - reply = response.read() - self.credential_list = json.loads(reply)['credentials'] - self.logging.info("success") - -#------------------------------------------------------------ - def get_projects(self): -# get user project membership - self.logging.info("url=[%s] token=[%r]" % (self.url, self.token)) - projects_url = "/v3/users/%s/projects" % self.user - headers = {"X-Auth-Token": self.token, "Content-type": "application/json"} - request = urllib.request.Request(self.url + projects_url, headers=headers) - response = urllib.request.urlopen(request) - reply = response.read() - project_list = json.loads(reply) - self.project_dict = {} - for entry in project_list['projects']: - project_id = entry['id'] - project_name = entry['name'] - project_enabled = entry['enabled'] - self.project_dict[project_name] = project_id - self.logging.info("success") - -#------------------------------------------------------------ - def discover_s3_endpoint(self): -# HACK - change the port on the keystone URL to get the s3 gateway -# FIXME - make this a bit more robust - s3url = self.url[:-4] + "8080" - endpoint = {'name':'s3project', 'type':'s3', 'url':s3url} - for project_name in self.project_dict: - for credential in self.credential_list: - if credential['tenant_id'] == self.project_dict[project_name]: - endpoint['name'] = project_name - endpoint['access'] = credential['access'] - endpoint['secret'] = credential['secret'] - - return endpoint - -#------------------------------------------------------------ - def credentials_print(self): - for project_name in self.project_dict: - print("project = %s" % project_name) - for credential in self.credential_list: - if credential['tenant_id'] == self.project_dict[project_name]: - print(" access = %s : secret = %s" % (credential['access'], credential['secret'])) -# print(" access = %s " % (credential['access'])) - -#------------------------------------------------------------ - def credentials_create(self, project): - - if project in self.project_dict.keys(): - project_id = self.project_dict[project] - else: - project_id = project - - self.logging.info("Creating ec2 credential for project_id [%s]" % project_id) - -# curl -g -i -X POST https://nimbus.pawsey.org.au:5000/v3/users/0da49abca73d9eaf24fab0a6cc14c6b953494b8008e3f436a4e2223db9c18115/credentials/OS-EC2 -H "Accept: application/json" -H "Content-Type: application/json" -H "User-Agent: python-keystoneclient" -H "X-Auth-Token: {SHA256}1a415063e2de80ec509085a7102068cebb70443a9e7b53f9503882b18c03ad2a" -d '{"tenant_id": "e26b4c0824854f09b13bb7ac6eb6a909"}' -#RESP BODY: {"credential": {"user_id": "0da49abca73d9eaf24fab0a6cc14c6b953494b8008e3f436a4e2223db9c18115", "tenant_id": "e26b4c0824854f09b13bb7ac6eb6a909", "access": "ff64589a348c4fa893e93caa6c19cfbb", "secret": "677cdcfe90a446b48ba69d449d20db12", "trust_id": null, "links": {"self": "https://nimbus.pawsey.org.au:5000/v3/users/0da49abca73d9eaf24fab0a6cc14c6b953494b8008e3f436a4e2223db9c18115/credentials/OS-EC2/ff64589a348c4fa893e93caa6c19cfbb"}}} -# NB: project name has to be *exactly* right ... even a space in front of the project id string will bollocks it -# print("create credential: [%s]" % project) - -# TODO - this the correct/safe way to construct json payload? - data = json.dumps({ "tenant_id": project_id }) - headers = {"Accept": "application/json", "Content-type": "application/json", "X-Auth-Token": self.token } - url = "%s/v3/users/%s/credentials/OS-EC2" % (self.url, self.user) - request = urllib.request.Request(url, data=data.encode(), headers=headers, method="POST") - response = urllib.request.urlopen(request) - reply = response.read() - credential = json.loads(reply) - # re-populate - self.get_credentials() - return credential['credential']['access'] - -#------------------------------------------------------------ - def credentials_delete(self, access): - -#REQ: curl -g -i -X DELETE https://nimbus.pawsey.org.au:5000/v3/users/0da49abca73d9eaf24fab0a6cc14c6b953494b8008e3f436a4e2223db9c18115/credentials/OS-EC2/ff64589a348c4fa893e93caa6c19cfbb -H "Accept: application/json" -H "User-Agent: python-keystoneclient" -H "X-Auth-Token: {SHA256}236b14f7b2eabb1b7c411f8a558396ea2fc8e218d73ebb2a1056905f099c5ce2" - self.logging.info("Destroying ec2 credential for access [%s]" % access) - url = "%s/v3/users/%s/credentials/OS-EC2/%s" % (self.url, self.user, access) - headers = {"Accept": "application/json", "X-Auth-Token": self.token } - request = urllib.request.Request(url, headers=headers, method="DELETE") - response = urllib.request.urlopen(request) -# expected response.status = 204 (empty content) - if response.status == 204: - self.get_credentials() - return("Delete successful") - return("Delete failed") - diff --git a/makefile b/makefile deleted file mode 100644 index fd0bd02..0000000 --- a/makefile +++ /dev/null @@ -1,50 +0,0 @@ -# spin up 2 containers: mediaflux & python + pshell -# we could use docker compose - but there are a lot of config variables to pass around which makes it more awkward - -PY_VERSION?=2 -PY_DOCKERFILE=Dockerfile.py2env -PY_IMAGE=seanfleming/python-$(PY_VERSION) -PY_CONTAINER=py-container - -MF_IMAGE=mediaflux_mflux -MF_CONTAINER=mf-container -# join 2 containers via this network -MF_NET=mflux -# the server= setting in .mf_config -MF_SERVER=mflux - - -mfenv: - docker network create -d bridge mflux - docker run --name $(MF_CONTAINER) --rm -d -p 80:80 --network $(MF_NET) --network-alias $(MF_SERVER) --mac-address 00:1E:67:6B:01:C6 $(MF_IMAGE) - touch mfenv - -# TODO - for the life of me could not figure out how to convert the output of a command into a variable (eval, shell etc all don't work on OS-X) -# docker inspect -f "{{ .NetworkSettings.IPAddress }}" $(MF_CONTAINER) > "mfenv" -# $(eval MFLUX_IP=$(shell docker inspect -f "{{ .NetworkSettings.IPAddress }}" $$(MF_CONTAINER))) - - -pyenv: $(PY_DOCKERFILE) mfenv - docker build --tag $(PY_IMAGE) -f $(PY_DOCKERFILE) . - @echo "PY_IMAGE=$(PY_IMAGE)" > ".env" - docker run --name $(PY_CONTAINER) --network $(MF_NET) --rm -dit $(PY_IMAGE) - docker cp data/.mf_config $(PY_CONTAINER):/root/.mf_config - touch pyenv - - -pshell: mfclient.py pshell.py pyenv mfenv - docker cp mfclient.py $(PY_CONTAINER):/mfclient.py - docker cp pshell.py $(PY_CONTAINER):/pshell.py - docker exec -ti $(PY_CONTAINER) sh -c "sleep 10 && /pshell.py -c mflux" -# FIXME - sleep for 10 is a hack to allow mediaflux to fully boot in the other container ... - - -clean: - rm -f pyenv mfenv - docker stop $(MF_CONTAINER) - docker stop $(PY_CONTAINER) - docker network rm mflux - - -.PHONY: clean pshell getopts - diff --git a/profile_pshell b/profile_pshell deleted file mode 100755 index c0b7d29..0000000 --- a/profile_pshell +++ /dev/null @@ -1 +0,0 @@ -python -m cProfile -s cumtime pshell.py diff --git a/pshell.spec b/pshell.spec deleted file mode 100644 index a2ddaa5..0000000 --- a/pshell.spec +++ /dev/null @@ -1,40 +0,0 @@ -# -*- mode: python ; coding: utf-8 -*- - - -block_cipher = None - - -a = Analysis(['pshell.py'], - pathex=[], - binaries=[], - datas=[], - hiddenimports=[], - hookspath=[], - hooksconfig={}, - runtime_hooks=[], - excludes=[], - win_no_prefer_redirects=False, - win_private_assemblies=False, - cipher=block_cipher, - noarchive=False) -pyz = PYZ(a.pure, a.zipped_data, - cipher=block_cipher) - -exe = EXE(pyz, - a.scripts, - a.binaries, - a.zipfiles, - a.datas, - [], - name='pshell', - debug=False, - bootloader_ignore_signals=False, - strip=False, - upx=True, - upx_exclude=[], - runtime_tmpdir=None, - console=True, - disable_windowed_traceback=False, - target_arch=None, - codesign_identity=None, - entitlements_file=None ) diff --git a/setup.py b/setup.py deleted file mode 100644 index ce6195b..0000000 --- a/setup.py +++ /dev/null @@ -1,14 +0,0 @@ -from distutils.core import setup -setup(name='pshell', - version='1.0', - description='Python SFTP-like client for Mediaflux', - author='Sean Fleming', - author_email='sean.fleming@pawsey.org.au', - url='https://bitbucket.org/datapawsey/mfclient', - license='Apache-2.0', - classifiers=[ - 'License :: OSI Approved :: Apache Software License', - ], - packages=['data'], - py_modules=['pshell','parser', 'mfclient', 's3client', 'util'], - ) diff --git a/test_all b/test_all index a7a7b3e..368a87e 100755 --- a/test_all +++ b/test_all @@ -1,9 +1,10 @@ #!/bin/sh +cd "$(dirname "$0")" status=0 -python3 test_pshell.py || status=1 -python3 test_parser.py || status=1 -python3 test_mfclient.py || status=1 -python3 test_s3client.py || status=1 -python3 test_runner.py || status=1 +python3 tests/test_pshell.py || status=1 +python3 tests/test_parser.py || status=1 +python3 tests/test_mfclient.py || status=1 +python3 tests/test_s3client.py || status=1 +python3 tests/test_runner.py || status=1 exit "$status" diff --git a/test_mfclient.py b/tests/test_mfclient.py similarity index 99% rename from test_mfclient.py rename to tests/test_mfclient.py index 698bc7e..002633c 100755 --- a/test_mfclient.py +++ b/tests/test_mfclient.py @@ -2,6 +2,7 @@ import os import sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import time import shutil import getpass diff --git a/test_parser.py b/tests/test_parser.py similarity index 96% rename from test_parser.py rename to tests/test_parser.py index 82bd408..66f7c33 100755 --- a/test_parser.py +++ b/tests/test_parser.py @@ -1,7 +1,9 @@ #!/usr/bin/env python3 -import parser +import os import sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import parser import unittest # global to avoid setup for every test class diff --git a/test_pshell.py b/tests/test_pshell.py similarity index 95% rename from test_pshell.py rename to tests/test_pshell.py index 198ba42..f99191e 100755 --- a/test_pshell.py +++ b/tests/test_pshell.py @@ -79,7 +79,7 @@ def test_lls(self): flag = False p = Popen([self.python, self.script, "-v", self.verbosity, "lls"], stdout=PIPE, stderr=STDOUT) for line in p.stdout: - if "test_pshell.py" in line.decode(): + if "pshell.py" in line.decode(): flag = True self.assertTrue(flag) @@ -95,7 +95,7 @@ def test_lls(self): python = "python3" config = "test" - script = "pshell.py" + script = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "pshell.py") verbosity = "0" # class suite to test diff --git a/test_release.py b/tests/test_release.py similarity index 97% rename from test_release.py rename to tests/test_release.py index ece2fc6..682e25c 100644 --- a/test_release.py +++ b/tests/test_release.py @@ -14,7 +14,7 @@ from http.server import BaseHTTPRequestHandler, HTTPServer -ROOT = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) RELEASE = os.path.join(ROOT, "release", "pshell") @@ -44,7 +44,7 @@ class ReleaseTest(unittest.TestCase): @classmethod def setUpClass(cls): if not os.path.isfile(RELEASE): - raise RuntimeError("Run ./build_release before test_release.py") + raise RuntimeError("Run ./build_release before tests/test_release.py") cls.temp = tempfile.TemporaryDirectory() cls.root = cls.temp.name cls.home = os.path.join(cls.root, "home") diff --git a/test_runner.py b/tests/test_runner.py similarity index 90% rename from test_runner.py rename to tests/test_runner.py index 12bf3bf..18be22a 100644 --- a/test_runner.py +++ b/tests/test_runner.py @@ -7,9 +7,9 @@ import unittest -ROOT = os.path.dirname(os.path.abspath(__file__)) -TEST_SCRIPTS = ("test_pshell.py", "test_parser.py", "test_mfclient.py", - "test_s3client.py", "test_runner.py") +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TEST_SCRIPTS = ("tests/test_pshell.py", "tests/test_parser.py", "tests/test_mfclient.py", + "tests/test_s3client.py", "tests/test_runner.py") class TestRunnerStatus(unittest.TestCase): diff --git a/test_s3client.py b/tests/test_s3client.py similarity index 99% rename from test_s3client.py rename to tests/test_s3client.py index 44e8307..e850cbc 100755 --- a/test_s3client.py +++ b/tests/test_s3client.py @@ -3,7 +3,9 @@ import json import hashlib import logging +import os import sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import s3client from unittest import mock import unittest diff --git a/v3/.mf_config b/v3/.mf_config deleted file mode 100644 index 6f73f83..0000000 --- a/v3/.mf_config +++ /dev/null @@ -1,155 +0,0 @@ -[pawsey] -server = data.pawsey.org.au -protocol = https -port = 443 -encrypt = True -debug = False -domain = ivec -session = 166ec40b5cfGUwiNDPaTXZf1mSQ9TNCWA8sZZwLT1Fj315 -token = 6tn4zgkhjxo8IGnaMRx94UDjpfd8Ifcc63BsxGfu8ICY2dVHKkXKLb6qQhj5nUvHVC6MWNXgmMVkso4wVV106731243 - -[monitor] -server = data.pawsey.org.au -protocol = https -port = 443 -encrypt = True -debug = False -domain = ivec -namespace = /projects -token = M8sdRZ1ohxZojbecDqLNpFU3UldSAbq3106730942 -session = 165410dba66FdZkkq3CjmvzA1M7HPk7Chi92gappXOk309 - -[public] -server = data.pawsey.org.au -protocol = https -port = 443 -encrypt = True -debug = False -domain = public -session = 164c5a0b9784smIE9e76h4hG6evVYJZnPswimrM4GCt308 - -[unsafe] -server = data.pawsey.org.au -protocol = http -port = 80 -encrypt = False -domain = ivec -namespace = /projects -session = 15e5f50d28fuGPic6fF4rLmhgcAFDY26KxwshjAGhTo - -[unsafemaster] -server = data.pawsey.org.au -protocol = http -port = 80 -encrypt = False -domain = system -namespace = /projects -session = 15e07dab635jHgZdtGmErF6DRm4OZPeQv9NAJgxCQ6e - -[master] -server = data.pawsey.org.au -protocol = https -port = 443 -encrypt = True -debug = False -domain = system -session = 166f0dd88f7Xp4zvH5EdyAeiIKQCSc1NCOE8nHnbPeZ315 - -[cou] -server = data.pawsey.org.au -protocol = https -port = 443 -encrypt = True -debug = False -domain = ivec -token = fR91lbSnlzVpaM4p106724942 -session = 15ce296ffedyIqiqkmt3BW7gU7iPK1vevQI7XNya61X - -[test] -server = mfvm2.test.pawsey.org.au -protocol = http -port = 80 -encrypt = False -debug = True -domain = ivec -namespace = /projects/Data Team -token = BS3Te4VO3hPKIBfJ2kM21ojPVOaT4sADsVmSOcTyOlDIRWOp5FeFkj52kzbNy59M1Ep598751 -session = 162b8b89fceeykbugeOvpVNnCdGF65f3CRYtLAkhJvk - -[testmaster] -server = mfvm2.test.pawsey.org.au -protocol = http -port = 80 -encrypt = False -debug = False -domain = system -session = 162b8b8d2a91zQjubq2i1xgYKA86NkxxhYBxCe55pWY - -[local] -server = 0.0.0.0 -protocol = http -port = 80 -encrypt = False -debug = False -domain = ivec -token = 3T9naDp2gbDfaoqLiULVwRutoAbm7fnj7EUwb1HWjIW91Q5lOD33Cbc2n4XfsOgg3JR6sEu1lIqbAcOidLI59821 -session = 1634d1ecb70xzeassqIZVlVT6UJQCumzW2gJJ2TJlRy - -[localmaster] -server = 0.0.0.0 -protocol = http -port = 80 -encrypt = False -debug = False -domain = system -token = -session = 165e5728e21XYYVn1ynNp3IMm7XrvxTsRtWdDhSQPzt1 - -[devmaster] -server = 172.16.76.141 -protocol = http -port = 80 -encrypt = False -debug = False -domain = system -namespace = /projects -session = 166ec55cc80pfVI8OxrtLAwQuKopODfJRiuB4DY4BHt -token = MsJzFunorpuhxSChls7ucPrbDpL1vnUTcvVkCmUKj5AG93SrbjwOrbAjFgj7NQnMpfIYO2aA5981037 - -[dev] -server = 172.16.76.141 -protocol = http -port = 80 -encrypt = False -debug = False -domain = ivec -token = MJnGjVZISrcnUYf9OuJuHTt2xxTyxWT71gAqgKVPve8ZbGfm1CaI5pvaZAuAi1UnyHcp8uABAJ3DVPHgQyCou5CEGUdt7atP5981001 -session = 16294ca78f1lOda92aEZHETgjQ147sIgAoAYH5j94LD - -[dummy] -server = localhost -protocol = http -port = 80 -domain = system -dummy = True - -[new] -server = 172.16.76.141 -protocol = http -port = 80 -encrypt = False -domain = system -namespace = /projects/Data Team -session = 166e2eff26fTn23GFpXSbO9wwERdWJqdbxRafuTdT7x -token = Xh6kT3f16FIX1lmwPWosess1oqZj5981039 - -[gok] -server = 172.16.76.141 -protocol = http -port = 80 -encrypt = False -domain = system -namespace = /projects/Data Team -session = 166e2f33654bSMPE4rfnRvMPkOzT1R3VeL1SzvFfCzP -token = 127os8qkbsSXcmLeIdLOqMe8H7wKDC24WqbPxnhaLPgoIpbcvfQDkuWV25co1ksONqQR4q3fBQXxli6FUULyae59810311 - diff --git a/v3/README b/v3/README deleted file mode 100644 index 6177f8e..0000000 --- a/v3/README +++ /dev/null @@ -1,3 +0,0 @@ -docker build . - -docker run --rm -it 068f5c462d8d diff --git a/v3/fuse.py b/v3/fuse.py deleted file mode 100644 index 8fca823..0000000 --- a/v3/fuse.py +++ /dev/null @@ -1,978 +0,0 @@ -# Copyright (c) 2012 Terence Honles (maintainer) -# Copyright (c) 2008 Giorgos Verigakis (author) -# -# Permission to use, copy, modify, and distribute this software for any -# purpose with or without fee is hereby granted, provided that the above -# copyright notice and this permission notice appear in all copies. -# -# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - - - -from ctypes import * -from ctypes.util import find_library -from errno import * -from os import strerror -from platform import machine, system -from signal import signal, SIGINT, SIG_DFL -from stat import S_IFDIR -from traceback import print_exc - -import logging - -try: - from functools import partial -except ImportError: - # http://docs.python.org/library/functools.html#functools.partial - def partial(func, *args, **keywords): - def newfunc(*fargs, **fkeywords): - newkeywords = keywords.copy() - newkeywords.update(fkeywords) - return func(*(args + fargs), **newkeywords) - - newfunc.func = func - newfunc.args = args - newfunc.keywords = keywords - return newfunc - -try: - str -except NameError: - str = str - -class c_timespec(Structure): - _fields_ = [('tv_sec', c_long), ('tv_nsec', c_long)] - -class c_utimbuf(Structure): - _fields_ = [('actime', c_timespec), ('modtime', c_timespec)] - -class c_stat(Structure): - pass # Platform dependent - -_system = system() -_machine = machine() - -if _system == 'Darwin': - _libiconv = CDLL(find_library('iconv'), RTLD_GLOBAL) # libfuse dependency - _libfuse_path = (find_library('fuse4x') or find_library('osxfuse') or - find_library('fuse')) -else: - _libfuse_path = find_library('fuse') - -if not _libfuse_path: - raise EnvironmentError('Unable to find libfuse') -else: - _libfuse = CDLL(_libfuse_path) - -if _system == 'Darwin' and hasattr(_libfuse, 'macfuse_version'): - _system = 'Darwin-MacFuse' - - -if _system in ('Darwin', 'Darwin-MacFuse', 'FreeBSD'): - ENOTSUP = 45 - c_dev_t = c_int32 - c_fsblkcnt_t = c_ulong - c_fsfilcnt_t = c_ulong - c_gid_t = c_uint32 - c_mode_t = c_uint16 - c_off_t = c_int64 - c_pid_t = c_int32 - c_uid_t = c_uint32 - setxattr_t = CFUNCTYPE(c_int, c_char_p, c_char_p, POINTER(c_byte), - c_size_t, c_int, c_uint32) - getxattr_t = CFUNCTYPE(c_int, c_char_p, c_char_p, POINTER(c_byte), - c_size_t, c_uint32) - if _system == 'Darwin': - c_stat._fields_ = [ - ('st_dev', c_dev_t), - ('st_mode', c_mode_t), - ('st_nlink', c_uint16), - ('st_ino', c_uint64), - ('st_uid', c_uid_t), - ('st_gid', c_gid_t), - ('st_rdev', c_dev_t), - ('st_atimespec', c_timespec), - ('st_mtimespec', c_timespec), - ('st_ctimespec', c_timespec), - ('st_birthtimespec', c_timespec), - ('st_size', c_off_t), - ('st_blocks', c_int64), - ('st_blksize', c_int32), - ('st_flags', c_int32), - ('st_gen', c_int32), - ('st_lspare', c_int32), - ('st_qspare', c_int64)] - else: - c_stat._fields_ = [ - ('st_dev', c_dev_t), - ('st_ino', c_uint32), - ('st_mode', c_mode_t), - ('st_nlink', c_uint16), - ('st_uid', c_uid_t), - ('st_gid', c_gid_t), - ('st_rdev', c_dev_t), - ('st_atimespec', c_timespec), - ('st_mtimespec', c_timespec), - ('st_ctimespec', c_timespec), - ('st_size', c_off_t), - ('st_blocks', c_int64), - ('st_blksize', c_int32)] -elif _system == 'Linux': - ENOTSUP = 95 - c_dev_t = c_ulonglong - c_fsblkcnt_t = c_ulonglong - c_fsfilcnt_t = c_ulonglong - c_gid_t = c_uint - c_mode_t = c_uint - c_off_t = c_longlong - c_pid_t = c_int - c_uid_t = c_uint - setxattr_t = CFUNCTYPE(c_int, c_char_p, c_char_p, POINTER(c_byte), - c_size_t, c_int) - - getxattr_t = CFUNCTYPE(c_int, c_char_p, c_char_p, POINTER(c_byte), - c_size_t) - - if _machine == 'x86_64': - c_stat._fields_ = [ - ('st_dev', c_dev_t), - ('st_ino', c_ulong), - ('st_nlink', c_ulong), - ('st_mode', c_mode_t), - ('st_uid', c_uid_t), - ('st_gid', c_gid_t), - ('__pad0', c_int), - ('st_rdev', c_dev_t), - ('st_size', c_off_t), - ('st_blksize', c_long), - ('st_blocks', c_long), - ('st_atimespec', c_timespec), - ('st_mtimespec', c_timespec), - ('st_ctimespec', c_timespec)] - elif _machine == 'mips': - c_stat._fields_ = [ - ('st_dev', c_dev_t), - ('__pad1_1', c_ulong), - ('__pad1_2', c_ulong), - ('__pad1_3', c_ulong), - ('st_ino', c_ulong), - ('st_mode', c_mode_t), - ('st_nlink', c_ulong), - ('st_uid', c_uid_t), - ('st_gid', c_gid_t), - ('st_rdev', c_dev_t), - ('__pad2_1', c_ulong), - ('__pad2_2', c_ulong), - ('st_size', c_off_t), - ('__pad3', c_ulong), - ('st_atimespec', c_timespec), - ('__pad4', c_ulong), - ('st_mtimespec', c_timespec), - ('__pad5', c_ulong), - ('st_ctimespec', c_timespec), - ('__pad6', c_ulong), - ('st_blksize', c_long), - ('st_blocks', c_long), - ('__pad7_1', c_ulong), - ('__pad7_2', c_ulong), - ('__pad7_3', c_ulong), - ('__pad7_4', c_ulong), - ('__pad7_5', c_ulong), - ('__pad7_6', c_ulong), - ('__pad7_7', c_ulong), - ('__pad7_8', c_ulong), - ('__pad7_9', c_ulong), - ('__pad7_10', c_ulong), - ('__pad7_11', c_ulong), - ('__pad7_12', c_ulong), - ('__pad7_13', c_ulong), - ('__pad7_14', c_ulong)] - elif _machine == 'ppc': - c_stat._fields_ = [ - ('st_dev', c_dev_t), - ('st_ino', c_ulonglong), - ('st_mode', c_mode_t), - ('st_nlink', c_uint), - ('st_uid', c_uid_t), - ('st_gid', c_gid_t), - ('st_rdev', c_dev_t), - ('__pad2', c_ushort), - ('st_size', c_off_t), - ('st_blksize', c_long), - ('st_blocks', c_longlong), - ('st_atimespec', c_timespec), - ('st_mtimespec', c_timespec), - ('st_ctimespec', c_timespec)] - elif _machine == 'aarch64': - c_stat._fields_ = [ - ('st_dev', c_dev_t), - ('st_ino', c_ulong), - ('st_mode', c_mode_t), - ('st_nlink', c_uint), - ('st_uid', c_uid_t), - ('st_gid', c_gid_t), - ('st_rdev', c_dev_t), - ('__pad1', c_ulong), - ('st_size', c_off_t), - ('st_blksize', c_int), - ('__pad2', c_int), - ('st_blocks', c_long), - ('st_atimespec', c_timespec), - ('st_mtimespec', c_timespec), - ('st_ctimespec', c_timespec)] - else: - # i686, use as fallback for everything else - c_stat._fields_ = [ - ('st_dev', c_dev_t), - ('__pad1', c_ushort), - ('__st_ino', c_ulong), - ('st_mode', c_mode_t), - ('st_nlink', c_uint), - ('st_uid', c_uid_t), - ('st_gid', c_gid_t), - ('st_rdev', c_dev_t), - ('__pad2', c_ushort), - ('st_size', c_off_t), - ('st_blksize', c_long), - ('st_blocks', c_longlong), - ('st_atimespec', c_timespec), - ('st_mtimespec', c_timespec), - ('st_ctimespec', c_timespec), - ('st_ino', c_ulonglong)] -else: - raise NotImplementedError('%s is not supported.' % _system) - - -class c_statvfs(Structure): - _fields_ = [ - ('f_bsize', c_ulong), - ('f_frsize', c_ulong), - ('f_blocks', c_fsblkcnt_t), - ('f_bfree', c_fsblkcnt_t), - ('f_bavail', c_fsblkcnt_t), - ('f_files', c_fsfilcnt_t), - ('f_ffree', c_fsfilcnt_t), - ('f_favail', c_fsfilcnt_t), - ('f_fsid', c_ulong), - #('unused', c_int), - ('f_flag', c_ulong), - ('f_namemax', c_ulong)] - -if _system == 'FreeBSD': - c_fsblkcnt_t = c_uint64 - c_fsfilcnt_t = c_uint64 - setxattr_t = CFUNCTYPE(c_int, c_char_p, c_char_p, POINTER(c_byte), - c_size_t, c_int) - - getxattr_t = CFUNCTYPE(c_int, c_char_p, c_char_p, POINTER(c_byte), - c_size_t) - - class c_statvfs(Structure): - _fields_ = [ - ('f_bavail', c_fsblkcnt_t), - ('f_bfree', c_fsblkcnt_t), - ('f_blocks', c_fsblkcnt_t), - ('f_favail', c_fsfilcnt_t), - ('f_ffree', c_fsfilcnt_t), - ('f_files', c_fsfilcnt_t), - ('f_bsize', c_ulong), - ('f_flag', c_ulong), - ('f_frsize', c_ulong)] - -class fuse_file_info(Structure): - _fields_ = [ - ('flags', c_int), - ('fh_old', c_ulong), - ('writepage', c_int), - ('direct_io', c_uint, 1), - ('keep_cache', c_uint, 1), - ('flush', c_uint, 1), - ('padding', c_uint, 29), - ('fh', c_uint64), - ('lock_owner', c_uint64)] - -class fuse_context(Structure): - _fields_ = [ - ('fuse', c_voidp), - ('uid', c_uid_t), - ('gid', c_gid_t), - ('pid', c_pid_t), - ('private_data', c_voidp)] - -_libfuse.fuse_get_context.restype = POINTER(fuse_context) - - -class fuse_operations(Structure): - _fields_ = [ - ('getattr', CFUNCTYPE(c_int, c_char_p, POINTER(c_stat))), - ('readlink', CFUNCTYPE(c_int, c_char_p, POINTER(c_byte), c_size_t)), - ('getdir', c_voidp), # Deprecated, use readdir - ('mknod', CFUNCTYPE(c_int, c_char_p, c_mode_t, c_dev_t)), - ('mkdir', CFUNCTYPE(c_int, c_char_p, c_mode_t)), - ('unlink', CFUNCTYPE(c_int, c_char_p)), - ('rmdir', CFUNCTYPE(c_int, c_char_p)), - ('symlink', CFUNCTYPE(c_int, c_char_p, c_char_p)), - ('rename', CFUNCTYPE(c_int, c_char_p, c_char_p)), - ('link', CFUNCTYPE(c_int, c_char_p, c_char_p)), - ('chmod', CFUNCTYPE(c_int, c_char_p, c_mode_t)), - ('chown', CFUNCTYPE(c_int, c_char_p, c_uid_t, c_gid_t)), - ('truncate', CFUNCTYPE(c_int, c_char_p, c_off_t)), - ('utime', c_voidp), # Deprecated, use utimens - ('open', CFUNCTYPE(c_int, c_char_p, POINTER(fuse_file_info))), - - ('read', CFUNCTYPE(c_int, c_char_p, POINTER(c_byte), c_size_t, - c_off_t, POINTER(fuse_file_info))), - - ('write', CFUNCTYPE(c_int, c_char_p, POINTER(c_byte), c_size_t, - c_off_t, POINTER(fuse_file_info))), - - ('statfs', CFUNCTYPE(c_int, c_char_p, POINTER(c_statvfs))), - ('flush', CFUNCTYPE(c_int, c_char_p, POINTER(fuse_file_info))), - ('release', CFUNCTYPE(c_int, c_char_p, POINTER(fuse_file_info))), - ('fsync', CFUNCTYPE(c_int, c_char_p, c_int, POINTER(fuse_file_info))), - ('setxattr', setxattr_t), - ('getxattr', getxattr_t), - ('listxattr', CFUNCTYPE(c_int, c_char_p, POINTER(c_byte), c_size_t)), - ('removexattr', CFUNCTYPE(c_int, c_char_p, c_char_p)), - ('opendir', CFUNCTYPE(c_int, c_char_p, POINTER(fuse_file_info))), - - ('readdir', CFUNCTYPE(c_int, c_char_p, c_voidp, - CFUNCTYPE(c_int, c_voidp, c_char_p, - POINTER(c_stat), c_off_t), - c_off_t, POINTER(fuse_file_info))), - - ('releasedir', CFUNCTYPE(c_int, c_char_p, POINTER(fuse_file_info))), - - ('fsyncdir', CFUNCTYPE(c_int, c_char_p, c_int, - POINTER(fuse_file_info))), - - ('init', CFUNCTYPE(c_voidp, c_voidp)), - ('destroy', CFUNCTYPE(c_voidp, c_voidp)), - ('access', CFUNCTYPE(c_int, c_char_p, c_int)), - - ('create', CFUNCTYPE(c_int, c_char_p, c_mode_t, - POINTER(fuse_file_info))), - - ('ftruncate', CFUNCTYPE(c_int, c_char_p, c_off_t, - POINTER(fuse_file_info))), - - ('fgetattr', CFUNCTYPE(c_int, c_char_p, POINTER(c_stat), - POINTER(fuse_file_info))), - - ('lock', CFUNCTYPE(c_int, c_char_p, POINTER(fuse_file_info), - c_int, c_voidp)), - - ('utimens', CFUNCTYPE(c_int, c_char_p, POINTER(c_utimbuf))), - ('bmap', CFUNCTYPE(c_int, c_char_p, c_size_t, POINTER(c_ulonglong))), - ('flag_nullpath_ok', c_uint, 1), - ('flag_nopath', c_uint, 1), - ('flag_utime_omit_ok', c_uint, 1), - ('flag_reserved', c_uint, 29), - ] - - -def time_of_timespec(ts): - return ts.tv_sec + ts.tv_nsec / 10 ** 9 - -def set_st_attrs(st, attrs): - for key, val in list(attrs.items()): - if key in ('st_atime', 'st_mtime', 'st_ctime', 'st_birthtime'): - timespec = getattr(st, key + 'spec', None) - if timespec is None: - continue - timespec.tv_sec = int(val) - timespec.tv_nsec = int((val - timespec.tv_sec) * 10 ** 9) - elif hasattr(st, key): - setattr(st, key, val) - - -def fuse_get_context(): - 'Returns a (uid, gid, pid) tuple' - - ctxp = _libfuse.fuse_get_context() - ctx = ctxp.contents - return ctx.uid, ctx.gid, ctx.pid - - -class FuseOSError(OSError): - def __init__(self, errno): - super(FuseOSError, self).__init__(errno, strerror(errno)) - - -class FUSE(object): - ''' - This class is the lower level interface and should not be subclassed under - normal use. Its methods are called by fuse. - - Assumes API version 2.6 or later. - ''' - - OPTIONS = ( - ('foreground', '-f'), - ('debug', '-d'), - ('nothreads', '-s'), - ) - - def __init__(self, operations, mountpoint, raw_fi=False, encoding='utf-8', - **kwargs): - - ''' - Setting raw_fi to True will cause FUSE to pass the fuse_file_info - class as is to Operations, instead of just the fh field. - - This gives you access to direct_io, keep_cache, etc. - ''' - - self.operations = operations - self.raw_fi = raw_fi - self.encoding = encoding - - args = ['fuse'] - - args.extend(flag for arg, flag in self.OPTIONS - if kwargs.pop(arg, False)) - - kwargs.setdefault('fsname', operations.__class__.__name__) - args.append('-o') - args.append(','.join(self._normalize_fuse_options(**kwargs))) - args.append(mountpoint) - - args = [arg.encode(encoding) for arg in args] - argv = (c_char_p * len(args))(*args) - - fuse_ops = fuse_operations() - for ent in fuse_operations._fields_: - name, prototype = ent[:2] - - val = getattr(operations, name, None) - if val is None: - continue - - # Function pointer members are tested for using the - # getattr(operations, name) above but are dynamically - # invoked using self.operations(name) - if hasattr(prototype, 'argtypes'): - val = prototype(partial(self._wrapper, getattr(self, name))) - - setattr(fuse_ops, name, val) - - try: - old_handler = signal(SIGINT, SIG_DFL) - except ValueError: - old_handler = SIG_DFL - - err = _libfuse.fuse_main_real(len(args), argv, pointer(fuse_ops), - sizeof(fuse_ops), None) - - try: - signal(SIGINT, old_handler) - except ValueError: - pass - - del self.operations # Invoke the destructor - if err: - raise RuntimeError(err) - - @staticmethod - def _normalize_fuse_options(**kargs): - for key, value in list(kargs.items()): - if isinstance(value, bool): - if value is True: yield key - else: - yield '%s=%s' % (key, value) - - @staticmethod - def _wrapper(func, *args, **kwargs): - 'Decorator for the methods that follow' - - try: - return func(*args, **kwargs) or 0 - except OSError as e: - return -(e.errno or EFAULT) - except: - print_exc() - return -EFAULT - - def _decode_optional_path(self, path): - # NB: this method is intended for fuse operations that - # allow the path argument to be NULL, - # *not* as a generic path decoding method - if path is None: - return None - return path.decode(self.encoding) - - def getattr(self, path, buf): - return self.fgetattr(path, buf, None) - - def readlink(self, path, buf, bufsize): - ret = self.operations('readlink', path.decode(self.encoding)) \ - .encode(self.encoding) - - # copies a string into the given buffer - # (null terminated and truncated if necessary) - data = create_string_buffer(ret[:bufsize - 1]) - memmove(buf, data, len(data)) - return 0 - - def mknod(self, path, mode, dev): - return self.operations('mknod', path.decode(self.encoding), mode, dev) - - def mkdir(self, path, mode): - return self.operations('mkdir', path.decode(self.encoding), mode) - - def unlink(self, path): - return self.operations('unlink', path.decode(self.encoding)) - - def rmdir(self, path): - return self.operations('rmdir', path.decode(self.encoding)) - - def symlink(self, source, target): - 'creates a symlink `target -> source` (e.g. ln -s source target)' - - return self.operations('symlink', target.decode(self.encoding), - source.decode(self.encoding)) - - def rename(self, old, new): - return self.operations('rename', old.decode(self.encoding), - new.decode(self.encoding)) - - def link(self, source, target): - 'creates a hard link `target -> source` (e.g. ln source target)' - - return self.operations('link', target.decode(self.encoding), - source.decode(self.encoding)) - - def chmod(self, path, mode): - return self.operations('chmod', path.decode(self.encoding), mode) - - def chown(self, path, uid, gid): - # Check if any of the arguments is a -1 that has overflowed - if c_uid_t(uid + 1).value == 0: - uid = -1 - if c_gid_t(gid + 1).value == 0: - gid = -1 - - return self.operations('chown', path.decode(self.encoding), uid, gid) - - def truncate(self, path, length): - return self.operations('truncate', path.decode(self.encoding), length) - - def open(self, path, fip): - fi = fip.contents - if self.raw_fi: - return self.operations('open', path.decode(self.encoding), fi) - else: - fi.fh = self.operations('open', path.decode(self.encoding), - fi.flags) - - return 0 - - def read(self, path, buf, size, offset, fip): - if self.raw_fi: - fh = fip.contents - else: - fh = fip.contents.fh - - ret = self.operations('read', self._decode_optional_path(path), size, - offset, fh) - - if not ret: return 0 - - retsize = len(ret) - assert retsize <= size, \ - 'actual amount read %d greater than expected %d' % (retsize, size) - - data = create_string_buffer(ret, retsize) - memmove(buf, data, retsize) - return retsize - - def write(self, path, buf, size, offset, fip): - data = string_at(buf, size) - - if self.raw_fi: - fh = fip.contents - else: - fh = fip.contents.fh - - return self.operations('write', self._decode_optional_path(path), data, - offset, fh) - - def statfs(self, path, buf): - stv = buf.contents - attrs = self.operations('statfs', path.decode(self.encoding)) - for key, val in list(attrs.items()): - if hasattr(stv, key): - setattr(stv, key, val) - - return 0 - - def flush(self, path, fip): - if self.raw_fi: - fh = fip.contents - else: - fh = fip.contents.fh - - return self.operations('flush', self._decode_optional_path(path), fh) - - def release(self, path, fip): - if self.raw_fi: - fh = fip.contents - else: - fh = fip.contents.fh - - return self.operations('release', self._decode_optional_path(path), fh) - - def fsync(self, path, datasync, fip): - if self.raw_fi: - fh = fip.contents - else: - fh = fip.contents.fh - - return self.operations('fsync', self._decode_optional_path(path), datasync, - fh) - - def setxattr(self, path, name, value, size, options, *args): - return self.operations('setxattr', path.decode(self.encoding), - name.decode(self.encoding), - string_at(value, size), options, *args) - - def getxattr(self, path, name, value, size, *args): - ret = self.operations('getxattr', path.decode(self.encoding), - name.decode(self.encoding), *args) - - retsize = len(ret) - # allow size queries - if not value: return retsize - - # do not truncate - if retsize > size: return -ERANGE - - buf = create_string_buffer(ret, retsize) # Does not add trailing 0 - memmove(value, buf, retsize) - - return retsize - - def listxattr(self, path, namebuf, size): - attrs = self.operations('listxattr', path.decode(self.encoding)) or '' - ret = '\x00'.join(attrs).encode(self.encoding) - if len(ret) > 0: - ret += '\x00'.encode(self.encoding) - - retsize = len(ret) - # allow size queries - if not namebuf: return retsize - - # do not truncate - if retsize > size: return -ERANGE - - buf = create_string_buffer(ret, retsize) - memmove(namebuf, buf, retsize) - - return retsize - - def removexattr(self, path, name): - return self.operations('removexattr', path.decode(self.encoding), - name.decode(self.encoding)) - - def opendir(self, path, fip): - # Ignore raw_fi - fip.contents.fh = self.operations('opendir', - path.decode(self.encoding)) - - return 0 - - def readdir(self, path, buf, filler, offset, fip): - # Ignore raw_fi - for item in self.operations('readdir', self._decode_optional_path(path), - fip.contents.fh): - - if isinstance(item, str): - name, st, offset = item, None, 0 - else: - name, attrs, offset = item - if attrs: - st = c_stat() - set_st_attrs(st, attrs) - else: - st = None - - if filler(buf, name.encode(self.encoding), st, offset) != 0: - break - - return 0 - - def releasedir(self, path, fip): - # Ignore raw_fi - return self.operations('releasedir', self._decode_optional_path(path), - fip.contents.fh) - - def fsyncdir(self, path, datasync, fip): - # Ignore raw_fi - return self.operations('fsyncdir', self._decode_optional_path(path), - datasync, fip.contents.fh) - - def init(self, conn): - return self.operations('init', '/') - - def destroy(self, private_data): - return self.operations('destroy', '/') - - def access(self, path, amode): - return self.operations('access', path.decode(self.encoding), amode) - - def create(self, path, mode, fip): - fi = fip.contents - path = path.decode(self.encoding) - - if self.raw_fi: - return self.operations('create', path, mode, fi) - else: - fi.fh = self.operations('create', path, mode) - return 0 - - def ftruncate(self, path, length, fip): - if self.raw_fi: - fh = fip.contents - else: - fh = fip.contents.fh - - return self.operations('truncate', self._decode_optional_path(path), - length, fh) - - def fgetattr(self, path, buf, fip): - memset(buf, 0, sizeof(c_stat)) - - st = buf.contents - if not fip: - fh = fip - elif self.raw_fi: - fh = fip.contents - else: - fh = fip.contents.fh - - attrs = self.operations('getattr', self._decode_optional_path(path), fh) - set_st_attrs(st, attrs) - return 0 - - def lock(self, path, fip, cmd, lock): - if self.raw_fi: - fh = fip.contents - else: - fh = fip.contents.fh - - return self.operations('lock', self._decode_optional_path(path), fh, cmd, - lock) - - def utimens(self, path, buf): - if buf: - atime = time_of_timespec(buf.contents.actime) - mtime = time_of_timespec(buf.contents.modtime) - times = (atime, mtime) - else: - times = None - - return self.operations('utimens', path.decode(self.encoding), times) - - def bmap(self, path, blocksize, idx): - return self.operations('bmap', path.decode(self.encoding), blocksize, - idx) - - -class Operations(object): - ''' - This class should be subclassed and passed as an argument to FUSE on - initialization. All operations should raise a FuseOSError exception on - error. - - When in doubt of what an operation should do, check the FUSE header file - or the corresponding system call man page. - ''' - - def __call__(self, op, *args): - if not hasattr(self, op): - raise FuseOSError(EFAULT) - return getattr(self, op)(*args) - - def access(self, path, amode): - return 0 - - bmap = None - - def chmod(self, path, mode): - raise FuseOSError(EROFS) - - def chown(self, path, uid, gid): - raise FuseOSError(EROFS) - - def create(self, path, mode, fi=None): - ''' - When raw_fi is False (default case), fi is None and create should - return a numerical file handle. - - When raw_fi is True the file handle should be set directly by create - and return 0. - ''' - - raise FuseOSError(EROFS) - - def destroy(self, path): - 'Called on filesystem destruction. Path is always /' - - pass - - def flush(self, path, fh): - return 0 - - def fsync(self, path, datasync, fh): - return 0 - - def fsyncdir(self, path, datasync, fh): - return 0 - - def getattr(self, path, fh=None): - ''' - Returns a dictionary with keys identical to the stat C structure of - stat(2). - - st_atime, st_mtime and st_ctime should be floats. - - NOTE: There is an incombatibility between Linux and Mac OS X - concerning st_nlink of directories. Mac OS X counts all files inside - the directory, while Linux counts only the subdirectories. - ''' - - if path != '/': - raise FuseOSError(ENOENT) - return dict(st_mode=(S_IFDIR | 0o755), st_nlink=2) - - def getxattr(self, path, name, position=0): - raise FuseOSError(ENOTSUP) - - def init(self, path): - ''' - Called on filesystem initialization. (Path is always /) - - Use it instead of __init__ if you start threads on initialization. - ''' - - pass - - def link(self, target, source): - 'creates a hard link `target -> source` (e.g. ln source target)' - - raise FuseOSError(EROFS) - - def listxattr(self, path): - return [] - - lock = None - - def mkdir(self, path, mode): - raise FuseOSError(EROFS) - - def mknod(self, path, mode, dev): - raise FuseOSError(EROFS) - - def open(self, path, flags): - ''' - When raw_fi is False (default case), open should return a numerical - file handle. - - When raw_fi is True the signature of open becomes: - open(self, path, fi) - - and the file handle should be set directly. - ''' - - return 0 - - def opendir(self, path): - 'Returns a numerical file handle.' - - return 0 - - def read(self, path, size, offset, fh): - 'Returns a string containing the data requested.' - - raise FuseOSError(EIO) - - def readdir(self, path, fh): - ''' - Can return either a list of names, or a list of (name, attrs, offset) - tuples. attrs is a dict as in getattr. - ''' - - return ['.', '..'] - - def readlink(self, path): - raise FuseOSError(ENOENT) - - def release(self, path, fh): - return 0 - - def releasedir(self, path, fh): - return 0 - - def removexattr(self, path, name): - raise FuseOSError(ENOTSUP) - - def rename(self, old, new): - raise FuseOSError(EROFS) - - def rmdir(self, path): - raise FuseOSError(EROFS) - - def setxattr(self, path, name, value, options, position=0): - raise FuseOSError(ENOTSUP) - - def statfs(self, path): - ''' - Returns a dictionary with keys identical to the statvfs C structure of - statvfs(3). - - On Mac OS X f_bsize and f_frsize must be a power of 2 - (minimum 512). - ''' - - return {} - - def symlink(self, target, source): - 'creates a symlink `target -> source` (e.g. ln -s source target)' - - raise FuseOSError(EROFS) - - def truncate(self, path, length, fh=None): - raise FuseOSError(EROFS) - - def unlink(self, path): - raise FuseOSError(EROFS) - - def utimens(self, path, times=None): - 'Times is a (atime, mtime) tuple. If None use current time.' - - return 0 - - def write(self, path, data, offset, fh): - raise FuseOSError(EROFS) - - -class LoggingMixIn: - log = logging.getLogger('fuse.log-mixin') - - def __call__(self, op, path, *args): - self.log.debug('-> %s %s %s', op, path, repr(args)) - ret = '[Unhandled Exception]' - try: - ret = getattr(self, op)(path, *args) - return ret - except OSError as e: - ret = str(e) - raise - finally: - self.log.debug('<- %s %s', op, repr(ret)) diff --git a/v3/mfclient.py b/v3/mfclient.py deleted file mode 100644 index e24d459..0000000 --- a/v3/mfclient.py +++ /dev/null @@ -1,989 +0,0 @@ -#!/usr/bin/python3 - -""" -This module is a Python 3.x (standard lib only) implementation of a mediaflux client -Author: Sean Fleming -""" - -import os -import re -import sys -import ssl -import time -import zlib -import shlex -import random -import string -import socket -import signal -import urllib.request, urllib.error, urllib.parse -import http.client -import datetime -import functools -import mimetypes -import posixpath -import multiprocessing -import xml.etree.ElementTree as ET - -# Globals - multiprocess IO monitoring is hard -manage_lock = multiprocessing.Lock() -bytes_sent = multiprocessing.Value('d', 0, lock=True) -bytes_recv = multiprocessing.Value('d', 0, lock=True) - -#------------------------------------------------------------ -def put_jump(mfclient, data): - """ - Global multiprocessing function for concurrent uploading - - Args: - data: ARRAY of 2 STRINGS which are the arguments for the put() method: (remote namespace, local filepath) - - Returns: - triplet of STRINGS (asset_ID/status, 2 input arguments) which will be concatenated on the mf_manager's summary list - """ - - try: - mfclient.log("DEBUG", "[pid=%d] put_jump(%s,%s)" % (os.getpid(), data[0], data[1])) - asset_id = mfclient.put(data[0], data[1]) - except Exception as e: - mfclient.log("ERROR", "[pid=%d] put_jump(%s): %s" % (os.getpid(), data[1], str(e))) - return (-1, data[0], data[1]) - - return (int(asset_id), data[0], data[1]) - -#------------------------------------------------------------ -def get_jump(mfclient, data): - """ - Global (multiprocessing) function for concurrent downloading - - Args: - data: ARRAY of 2 STRINGS which are the arguments for the get() method: (asset_ID, local filepath) - - Returns: - A triplet of STRINGS (status, 2 input arguments) which will be concatenated on the mf_manager's summary list - """ - - try: - mfclient.log("DEBUG", "[pid=%d] get_jump(%s,%s)" % (os.getpid(), data[0], data[1])) - mfclient.get(data[0], data[1]) - except Exception as e: - mfclient.log("ERROR", "[pid=%d] get_jump(): %s" % (os.getpid(), str(e))) - return (-1, data[0], data[1]) - - return (0, data[0], data[1]) - -#------------------------------------------------------------ -def init_jump(recv, sent): - """ - Global (multiprocessing) initialiser for byte transfer counts - """ - global bytes_sent - global bytes_recv -# initialize the globals in this process with the main process globals O.O - bytes_sent = sent - bytes_recv = recv - - -######################################################### -class mf_client: - """ - Base Mediaflux authentication and communication client - Parallel transfers are handled by multiprocessing (urllib2 and httplib are not thread-safe) - All unexpected failures are handled by raising exceptions - """ - - def __init__(self, protocol, port, server, domain="system", session="", timeout=120, enforce_encrypted_login=True, debug=0, dummy=False): - """ - Create a Mediaflux server connection instance. Raises an exception on failure. - - Args: - protocol: a STRING which should be either "http" or "https" - port: a STRING which is usually "80" or "443" - server: a STRING giving the FQDN of the server - domain: a STRING giving the authentication domain to use when authenticating - session: a STRING supplying the session ID which, if it exists, enables re-use of an existing authenticated session - timeout: an INTEGER specifying the connection timeout - enforce_encrypted_login: a BOOLEAN that should only be False on a safe internal dev/test network - debug: an INTEGER which controls output of troubleshooting information - dummy: a BOOLEAN used for testing only (no actual server connection) - - Returns: - A reachable mediaflux server object that has not been tested for its authentication status - - Raises: - Error if server appears to be unreachable - """ -# configure interfaces - self.protocol = protocol - self.port = int(port) - self.server = server - self.domain = domain - self.timeout = timeout - self.session = session - self.token = None - self.dummy = dummy - self.debug = int(debug) - self.encrypted_post = bool(enforce_encrypted_login) - self.encrypted_data = self.encrypted_post -# service call URL - self.post_url = "%s://%s/__mflux_svc__" % (protocol, server) -# download/upload buffers - self.get_buffer = 8192 - self.put_buffer = 8192 -# XML pretty print hack - self.indent = 0 -# build data URLs - if self.encrypted_data: - self.data_get = "https://%s/mflux/content.mfjp" % server - self.data_put = "%s:%s" % (server, 443) - else: - self.data_get = "http://%s/mflux/content.mfjp" % server - self.data_put = "%s:%s" % (server, 80) - -# test mode - don't check server connection - if dummy: - return - -# initial connection check - s = socket.socket() - s.settimeout(7) - s.connect((self.server, self.port)) - s.close() -# allow unencrypted transfers if on the internal network - try: - s = socket.socket() - s.settimeout(2) - s.connect((self.server, 80)) - client_ip = s.getsockname() - server_ip = s.getpeername() - m1 = re.match(r"\d+.\d+", server_ip[0]) - m2 = re.match(r"\d+.\d+", client_ip[0]) -# can open 80 and appear to be on the same network => you lucky duck - if m1 and m2: - if m1.group(0) == m2.group(0): - self.encrypted_data = False - self.data_put = "%s:%s" % (server, 80) - self.data_get = "http://%s/mflux/content.mfjp" % server - s.close() - except Exception as e: - pass - -# if required, attempt to display more connection info - if self.debug > 0: - print(("POST-URL: %s" % self.post_url)) - print(("DATA-GET: %s" % self.data_get)) - print(("DATA-PUT: %s" % self.data_put)) - if self.protocol == "https": -# first line of python version info is all we're interested in - version = sys.version - i = version.find("\n") - print((" PYTHON: %s" % version[:i])) - print((" OPENSSL:", ssl.OPENSSL_VERSION)) -# early versions of python 2.7.x are missing the SSL context method - try: - context = ssl.create_default_context() - context.verify_mode = ssl.CERT_REQUIRED - context.check_hostname = True - c = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=self.server) - c.connect((self.server, self.port)) - print((" CIPHER:", c.cipher())) - except Exception as e: - print((" WARNING: %s" % str(e))) - -#------------------------------------------------------------ - @staticmethod - def _xml_succint_error(xml): - """ - Primitive for extracting more concise error messages from Java stack traces - """ - max_size = 600 - -# pattern 1 - remove context - match = re.search(r"Syntax error.*Context", xml, re.DOTALL) - if match: - message = match.group(0)[:-7] - return message[:max_size] - -# pattern 2 - other - match = re.search(r"failed:.*", xml) - if match: - message = match.group(0)[7:] - return message[:max_size] - -# give up - return xml[:max_size] - -#------------------------------------------------------------ - def _post(self, xml_string, output_local_filepath=None): - """ - Primitive for sending an XML message to the Mediaflux server - """ - global bytes_recv - -# dummy mode passback for pshell offline tests - if self.dummy: - raise Exception(xml_string) - -# print "\nINPUT===================\n" -# print xml_string -# print "\n===================\n" - -# NB: timeout exception if server is unreachable - request = urllib.request.Request(self.post_url, data=xml_string.encode('utf-8'), headers={'Content-Type': 'text/xml'}) - response = urllib.request.urlopen(request, timeout=self.timeout) - xml = response.read().decode('utf-8') - -# print "\nOUTPUT===================\n" -# print xml -# print "\n===================\n" - - tree = ET.fromstring(xml) - -# outputs-via = session -# NB: outputs-via attachements has an attachment element with an id ATTRIBUTE - that can be used in the same way - elem_output = tree.find(".//outputs") - if elem_output is not None: - # TODO - findall ... - elem_id = elem_output.find(".//id") - output_id = elem_id.text - url = self.data_get + "?_skey=%s&id=%s" % (self.session, output_id) - url = url.replace("content", "output") - self.log("DEBUG", "_post() appending output url: [%s]" % url) - elem_url = ET.SubElement(elem_output, "url") - elem_url.text = url - -# if error - attempt to extract a useful message - elem = tree.find(".//reply/error") - if elem is not None: - elem = tree.find(".//message") - error_message = self._xml_succint_error(elem.text) - self.log("DEBUG", "_post() raise: [%s]" % error_message) - raise Exception(error_message) - - return tree - -#------------------------------------------------------------ - def _post_multipart_buffered(self, xml, filepath): - """ - Primitive for doing buffered upload on a single file. Used by the put() method - Sends a multipart POST to the server; consisting of the initial XML, followed by a streamed, buffered read of the file contents - """ - global bytes_sent - -# mediaflux seems to have random periods of unresponsiveness - particularly around final ACK of transfer -# retries don't seem to work at all, but increasing the timeout seems to help cover the problem - upload_timeout = 1800 - -# setup - pid = os.getpid() - boundary = ''.join(random.choice(string.digits + string.ascii_letters) for i in range(30)) - filename = os.path.basename(filepath) - -# if we get anything other than a single clear mimetype to use - default to generic - mimetype = mimetypes.guess_type(filepath, strict=True) - if len(mimetype) != 1: - mimetype = 'application/octet-stream' - -# multipart - request xml and file - lines = [] - lines.extend(('--%s' % boundary, 'Content-Disposition: form-data; name="request"', '', str(xml),)) -# specifying nb-data-attachments is the key for getting the data direct to the store - lines.extend(('--%s' % boundary, 'Content-Disposition: form-data; name="nb-data-attachments"', '', "1",)) -# file - lines.extend(('--%s' % boundary, 'Content-Disposition: form-data; name="filename"; filename="%s"' % filename, 'Content-Type: %s' % mimetype, '', '')) - body = '\r\n'.join(lines) -# NB - should include everything AFTER the first /r/n after the headers - total_size = len(body) + os.path.getsize(filepath) + len(boundary) + 8 - -# different connection object for HTTPS vs HTTP - if self.encrypted_data is True: - self.log("DEBUG", "Using https for data: [%s]" % self.data_put, level=2) - conn = http.client.HTTPSConnection(self.data_put, timeout=upload_timeout) - else: - self.log("DEBUG", "Using http for data: [%s]" % self.data_put, level=2) - conn = http.client.HTTPConnection(self.data_put, timeout=upload_timeout) - -# kickoff - self.log("DEBUG", "[pid=%d] File send starting: %s" % (pid, filepath)) - conn.putrequest('POST', "/__mflux_svc__") -# headers - conn.putheader('Connection', 'keep-alive') - conn.putheader('Cache-Control', 'no-cache') - conn.putheader('Content-Length', str(total_size)) - conn.putheader('Content-Type', 'multipart/form-data; boundary=%s' % boundary) - conn.putheader('Content-Transfer-Encoding', 'binary') - conn.endheaders() - -# start sending the file - conn.send(body) - with open(filepath, 'rb') as infile: - while True: -# trap disk IO issues - try: - chunk = infile.read(self.put_buffer) - except Exception as e: - raise Exception("File read error: %s" % str(e)) -# exit condition - if not chunk: - break -# trap network IO issues - try: - conn.send(chunk) - except Exception as e: - raise Exception("Network send error: %s" % str(e)) -# record progress - with bytes_sent.get_lock(): - bytes_sent.value += len(chunk) - -# terminating line (len(boundary) + 8) - chunk = "\r\n--%s--\r\n" % boundary - conn.send(chunk) - self.log("DEBUG", "[pid=%d] File send completed, waiting for server..." % pid) - -# get ACK from server (asset ID) else error (raise exception) - resp = conn.getresponse() - reply = resp.read() - conn.close() - tree = ET.fromstring(reply) - - message = "response did not contain an asset ID." - for elem in tree.iter(): - if elem.tag == 'id': - return int(elem.text) - if elem.tag == 'message': - message = elem.text - - raise Exception(message) - -#------------------------------------------------------------ - @staticmethod - def _xml_sanitise(text): - """ - Helper method to sanitise text for the server XML parsing routines - """ - if isinstance(text, str): - text = text.replace('&', "&") - text = text.replace('<', "<") - text = text.replace('>', ">") - text = text.replace('"', """) - return text - -#------------------------------------------------------------ - @staticmethod - def _xml_cloak(text): - """ - Helper method for hiding sensitive text in XML posts - """ - text1 = re.sub(r'session=[^>]*', 'session="..."', text) - text2 = re.sub(r'.*?', 'xxxxxxx', text1) - text3 = re.sub(r'.*?', 'xxxxxxx', text2) - return text3 - -#------------------------------------------------------------ - def aterm_run(self, service_call, post=True): - """ - Method for parsing aterm's compressed XML syntax and sending to the Mediaflux server - - Args: - service_call: raw input text that is assumed to be in aterm syntax - post: if False will just return the argument part of the serialized XML, if True will post and return reply - - Returns: - A STRING containing the server reply (if post is TRUE, if false - just the XML for test comparisons) - """ - -# intercept (before lexer!) and remove ampersand at end of line -> background job - if service_call[-1:] == '&': - flag_background = True - service_call = aterm_line[:-1] - else: - flag_background = False - -# NB - use posix=True as it's the closest to the way aterm processes input strings - lexer = shlex.shlex(service_call, posix=True) - lexer.whitespace_split = True - xml_root = ET.Element(None) - xml_node = xml_root - child = None - stack = [] - data_out_min = 0 - data_out_name = None - flag_no_wrap = False - -# first token is the service call, the rest are child arguments - service_call = lexer.get_token() - token = lexer.get_token() - -# better handling of deletions to the XML - xml_unwanted = None - try: - while token: - if token[0] == ':': - child = ET.SubElement(xml_node, '%s' % token[1:]) - self.log("DEBUG", "XML elem [%s]" % token[1:], level=2) -# if element contains : (eg csiro:seismic) then we need to inject the xmlns stuff - if ":" in token[1:]: - item_list = token[1:].split(":") - self.log("DEBUG", "XML associate namespace [%s] with element [%s]" % (item_list[0], token[1:]), level=2) - child.set("xmlns:%s" % item_list[0], item_list[0]) - elif token[0] == '<': - stack.append(xml_node) - xml_node = child - elif token[0] == '>': - xml_node = stack.pop() - elif token[0] == '-': - try: -# -number => it's a text value - number = float(token) - child.text = token - self.log("DEBUG", "XML text [%s]" % child.text, level=2) - except: -# -other => it's an XML attribute/property - key = token[1:] - value = lexer.get_token() - if value.startswith('"') and value.endswith('"'): - value = value[1:-1] - child.set(key, value) - self.log("DEBUG", "XML prop [%r = %r]" % (key, value), level=2) - else: -# FIXME - potentially some issues here with data strings with multiple spaces (ie we are doing a whitespace split & only adding one back) - if child.text is not None: - child.text += " " + token - else: - if token.startswith('"') and token.endswith('"'): - child.text = token[1:-1] - else: - child.text = token -# don't display sensitive info - if child.tag.lower() == "password" or child.tag.lower() == 'token': - self.log("DEBUG", "XML text [xxxxxxxx]", level=2) - else: - self.log("DEBUG", "XML text [%s]" % child.text, level=2) - -# special case - out element - needs to be removed (replaced with outputs-via and an outputs-expected attribute) - if child.tag.lower() == "out": - data_out_name = child.text - data_out_min = 1 -# NEW - schedule for deletion but don't delete yet due to potentially multiple passthroughs - xml_unwanted = child - -# don't treat quotes as special characters in password string - if "password" in token: - save_lexer_quotes = lexer.quotes - lexer.quotes = iter('') - token = lexer.get_token() - lexer.quotes = save_lexer_quotes - else: - token = lexer.get_token() - - except Exception as e: - self.log("DEBUG", "aterm_run() error: %s" % str(e)) - raise SyntaxError - -# do any deletions to the tree after processing - if xml_unwanted is not None: - xml_node.remove(xml_unwanted) - -# build the request XML tree - xml = ET.Element("request") - child = ET.SubElement(xml, "service") - -# special case for "system.login" as it does not work when wrapped with "service.execute" - which requires a valid session - if service_call == "system.logon": - child.set("name", service_call) - args = ET.SubElement(child, "args") - args.append(xml_root) -# special case for calls that are already wrapped in a service.execute - elif service_call == 'service.execute': - child.set("name", service_call) - child.set("session", self.session) - args = ET.SubElement(child, "args") - args.append(xml_root) -# FIXME - this should better merge with below so we also cover the case with outputs ... - else: -# wrap the service call in a service.execute to allow background execution, if desired - child.set("name", "service.execute") - child.set("session", self.session) - args = ET.SubElement(child, "args") - if flag_background is True: - bg = ET.SubElement(args, "background") - bg.text = "True" - call = ET.SubElement(args, "service") - call.set("name", service_call) - call.append(xml_root) -# return data via the output URL - if data_out_min > 0: - call.set("outputs", "%s" % data_out_min) - output = ET.SubElement(args, "outputs-via") - output.text = "session" - -# convert XML to string for posting ... - xml_text = ET.tostring(xml, method = 'xml').decode('utf-8') - -# debug - password hiding for system.logon ... - xml_hidden = self._xml_cloak(xml_text) - self.log("DEBUG", "XML out: %s" % xml_hidden, level=2) - -# testing hook - if post is not True: - return xml_hidden - -# send the service call and see what happens ... - message = "This shouldn't happen" - while True: - try: - reply = self._post(xml_text, output_local_filepath=data_out_name) - if flag_background is True: - elem = reply.find(".//id") - job = elem.text - while True: - self.log("DEBUG", "Background job [%s] poll..." % job) - xml_poll = self.aterm_run("service.background.describe :id %s" % job) - elem = xml_poll.find(".//task/state") - item = xml_poll.find(".//task/exec-time") - text = elem.text + " [ " + item.text + " " + item.attrib['unit'] + "(s) ]" - if "executing" in elem.text: - sys.stdout.write("\r"+text) - sys.stdout.flush() - time.sleep(5) - continue - else: - print(("\r%s " % text)) - break -# NB: it is an exception (error) to get results BEFORE completion - self.log("DEBUG", "Background job [%s] complete, getting results" % job) - xml_poll = self.aterm_run("service.background.results.get :id %s" % job) - return xml_poll - else: - return reply - - except Exception as e: - message = str(e) - self.log("DEBUG", "POST exception: %s" % message) - if "session is not valid" in message: -# FIXME - if mf_config has a valid session it will stop and not read the token (even if the token is valid) -# TODO - we could restart the session if we can implement a way to always grab the token if it's there - if self.token is not None: - self.log("DEBUG", "We have a token, attempting to establish new session") - self.login(token=self.token) - xml_text = re.sub('session=[^>]*', 'session="%s"' % self.session, xml_text) - self.log("DEBUG", "Session restored, retrying command") - continue - break - -# couldn't post without an error - give up - raise Exception(message) - -#------------------------------------------------------------ - def _xml_recurse(self, elem, text=""): - """ - Helper method for traversing XML and generating formatted output - """ - - if elem.text is not None: - text += ' '*self.indent + '%s="%s" ' % (elem.tag, elem.text) - else: - text += ' '*self.indent + '%s ' % elem.tag - for key, value in list(elem.attrib.items()): - text += ' -%s="%s"' % (key, value) - text += '\n' - - self.indent += 4 - for child in elem.getchildren(): - text = self._xml_recurse(child, text) - self.indent -= 4 - - return text - -#------------------------------------------------------------ - def xml_print(self, xml_tree, trim=True): - """ - Helper method for displaying XML nicely, as much as is possible - """ -# seek for "normal" response - elem = None - if trim is True: - elem = xml_tree.find(".//result") -# seek for error message - if elem is None: - elem = xml_tree.find(".//message") -# still nothing? give up and print the whole thing - if elem is None: - elem = xml_tree - if elem is not None: - for child in list(elem): - print((self._xml_recurse(child).strip('\n'))) - else: - print("Empty XML document") - return - -#------------------------------------------------------------ - def log(self, prefix, message, level=1): - """ - Timestamp based message logging. - """ - - if "DEBUG" in prefix: - if level > int(self.debug): - return - - ts = time.time() - st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') - message = st + " >>> " + message - print(("%8s: %s" % (prefix, message))) - -#------------------------------------------------------------ - def logout(self): - """ - Destroy the current session (NB: delegate can auto-create a new session if available) - """ - self.aterm_run("system.logoff") - self.session = "" - -#------------------------------------------------------------ - def login(self, user=None, password=None, token=None): - """ - Authenticate to the current Mediaflux server and record the session ID on success - - Input: - user, password: STRINGS specifying user login details - token: STRING specifying a delegate credential - - Raises: - An error if authentication fails - """ -# security check - if self.protocol != "https": - if self.encrypted_post: - raise Exception("Forbidding unencrypted password post") - else: - self.log("DEBUG", "Permitting unencrypted login; I hope you know what you're doing.") -# attempt token authentication first (if supplied) - if token is not None: - reply = self.aterm_run("system.logon :token %s" % token) - self.token = token - else: - reply = self.aterm_run("system.logon :domain %s :user %s :password %s" % (self.domain, user, password)) -# extract session key - elem = reply.find(".//session") - if elem is not None: - self.session = elem.text - return - - raise Exception("Login failed") - -#------------------------------------------------------------ - def authenticated(self): - """ - Check client authentication state - - Returns: - A BOOLEAN value depending on the current authentication status of the Mediaflux connection - """ - if self.dummy: - return True - try: -# NEW - this approach seems to work better for the expired token + valid session edge case - self.aterm_run("system.session.self.describe") - return True - except Exception as e: - self.session = "" -# NB: max licence error can occur here - self.log("DEBUG", str(e)) - - return False - -#------------------------------------------------------------ - def namespace_exists(self, namespace): - """ - Wrapper around the generic service call mechanism (for testing namespace existence) that parses the result XML and returns a BOOLEAN - """ - reply = self.aterm_run('asset.namespace.exists :namespace "%s"' % namespace.replace('"', '\\\"')) - elem = reply.find(".//exists") - if elem is not None: - if elem.text == "true": - return True - - return False - -#------------------------------------------------------------ - def get_local_checksum(self, filepath): - current = 0 - with open(filepath, 'rb') as fd: - while True: - data = fd.read(self.put_buffer) - if not data: - break - current = zlib.crc32(data, current) - fd.close() - return current & 0xFFFFFFFF - -#------------------------------------------------------------ - def get(self, asset_id, filepath, overwrite=False): - """ - Download an asset to a local filepath - - Args: - asset_id: an INTEGER representing the Mediaflux asset ID on the server - filepath: a STRING representing the full path and filename to download the asset content to - overwrite: a BOOLEAN indicating action if local copy exists - - Raises: - An error on failure - """ - global bytes_recv - - if os.path.isfile(filepath) and not overwrite: - self.log("DEBUG", "Local file of that name (%s) already exists, skipping." % filepath) - with bytes_recv.get_lock(): - bytes_recv.value += os.path.getsize(filepath) - return - -# NEW - filename is ignored ... -# TODO - wrap the processing of the output URL in aterm_run ... ? -# a bit tricky as we want the control for chunked FUSE data requests - reply = self.aterm_run("asset.get :id %s :out %s" % (asset_id, filepath)) - elem = reply.find(".//outputs/url") - url = elem.text - response = urllib.request.urlopen(url) - with open(filepath, 'wb') as output: - while True: -# trap network IO issues - try: - data = response.read(self.get_buffer) - except Exception as e: - raise Exception("Network read error: %s" % str(e)) -# exit condition - if not data: - break -# trap disk IO issues - try: - output.write(data) - except Exception as e: - raise Exception("File write error: %s" % str(e)) -# record progress - with bytes_recv.get_lock(): - bytes_recv.value += len(data) - -#------------------------------------------------------------ - def get_managed(self, list_asset_filepath, total_bytes, processes=4): - """ - Managed multiprocessing download of a list of assets from the Mediaflux server. Uses get() as the file transfer primitive - - Args: - list_asset_filepath: a LIST of pairs representing the asset ID and local filepath destination - total_bytes: the total bytes to download - processes: the number of processes the multiprocessing manager should use - - Returns: - A queryable mf_manager object - """ - -# shenanigans to enable mfclient method to be called from the global process pool (python can't serialize instance methods) - get_alias = functools.partial(get_jump, self) - - return mf_manager(function=get_alias, arguments=list_asset_filepath, processes=processes, total_bytes=total_bytes) - -#------------------------------------------------------------ - def put(self, namespace, filepath, overwrite=True): - """ - Creates a new asset on the Mediaflux server and uploads from a local filepath to supply its content - - Args: - namespace: a STRING representing the remote destination in which to create the asset - filepath: a STRING giving the absolute path and name of the local file - overwrite: a BOOLEAN indicating action if remote copy exists - - Returns: - asset_id: an INTEGER representing the mediaflux asset ID - - Raises: - An error message if unsuccessful - """ - global bytes_sent - -# construct destination argument - filename = os.path.basename(filepath) - filename = self._xml_sanitise(filename) - namespace = self._xml_sanitise(namespace) - remotepath = posixpath.join(namespace, filename) - asset_id = -1 - -# NB: avoid generating exception if asset doesn't exist - result = self.aterm_run('asset.get :id -only-if-exists true "path=%s" :xpath -ename id id :xpath -ename crc32 content/csum :xpath -ename size content/size' % remotepath) - -# attempt checksum compare - try: - elem = result.find(".//id") - asset_id = int(elem.text) - elem = result.find(".//crc32") - remote_crc32 = int(elem.text, 16) - elem = result.find(".//size") - remote_size = int(elem.text) -# NB: checksum calc on large files (several GB+) on an external HDD can be SLOW - slower than uploading the file again -# local_crc32 = self.get_local_checksum(filepath) - local_size = int(os.path.getsize(filepath)) -# if local_crc32 == remote_crc32: - if local_size == remote_size: - self.log("DEBUG", "Match; skipping [%s] -> [%s]" % (filepath, remotepath)) - with bytes_sent.get_lock(): - bytes_sent.value += remote_size - return asset_id - else: - self.log("DEBUG", "Mismatch; local=%r -> remote=%r" % (local_size, remote_size)) - - except Exception as e: - if "NoneType" in str(e): -# the file doesn't exist or has no content -> trigger upload - self.log("DEBUG", "No remote file found: [%s]" % remotepath) - overwrite = True - else: -# I'm horribly confused -> report error and don't do anything - self.log("ERROR", str(e)) - overwrite = False - -# local and remote crc32 don't match -> decision time ... - if overwrite is True: - self.log("DEBUG", "Uploading: [%s] -> [%s]" % (filepath, remotepath)) - xml_string = '' % self.session - xml_string += 'path=%strue' % remotepath - asset_id = self._post_multipart_buffered(xml_string, filepath) - - return asset_id - -#------------------------------------------------------------ - def put_managed(self, list_namespace_filepath, total_bytes=None, processes=4): - """ - Managed multiprocessing upload of a list of files to the Mediaflux server. Uses put() as the file transfer primitive - - Args: - list_namespace_filepath: a LIST of STRING pairs representing the remote namespace destination and the local filepath source - total_bytes: the total bytes to upload - processes: the number of processes the multiprocessing manager should use - - Returns: - A queryable mf_manager object - """ - -# CURRENT - require total_bytes to be pre-computed -# if not supplied - count (potentially a lot slower) - if total_bytes is None: - total_bytes = 0 - self.log("DEBUG", "Total upload bytes not supplied, counting...") - for namespace, filepath in list_namespace_filepath: - try: - total_bytes += os.path.getsize(filepath) - except: - self.log("DEBUG", "Can't read %s, skipping." % filepath) - - self.log("DEBUG", "Total upload bytes: %d" % total_bytes) - if total_bytes == 0: - print() - raise Exception("No data to upload") - -# shenanigans to enable mfclient method to be called from the global process pool (python can't serialize instance methods) - put_alias = functools.partial(put_jump, self) - - return mf_manager(function=put_alias, arguments=list_namespace_filepath, processes=processes, total_bytes=total_bytes) - - -############################################################# -class mf_manager: - """ - Multiprocessing file transfer management object. - """ - -# a list which is appended to as individual transfers are completed - summary = None - task = None - pool = None - - def __init__(self, function, arguments, processes=1, total_bytes=0): - """ - Args: - function: the primitive transfer METHOD put() or get() to invoke in transferring a single file - arguments: a LIST of STRING pairs to be supplied to the transfer function primitive - processes: INTEGER number of processes to spawn to deal with the input list - total_bytes: INTEGER size of the transfer, for progress reporting - - Returns: - manager object which can be queried for progress (see methods below) and final status - """ - global bytes_sent - global bytes_recv - -# fail if there is already a managed transfer (there can only be one!) - if not manage_lock.acquire(block=False): - raise TypeError - -# init monitoring - self.start_time = time.time() - self.bytes_total = total_bytes - self.summary = [] - bytes_sent.value = 0 - bytes_recv.value = 0 - -# ref:http://stackoverflow.com/questions/11312525/catch-ctrlc-sigint-and-exit-multiprocesses-gracefully-in-python -# force control-C to be ignored by process pool - handler = signal.signal(signal.SIGINT, signal.SIG_IGN) -# NB: urllib2 and httplib are not thread safe -> use process pool instead of threads -# shared mem globals aren't preserved with a Windows fork() - need an explicit init - self.pool = multiprocessing.Pool(processes, init_jump, (bytes_recv, bytes_sent)) - -# restore control-C - signal.signal(signal.SIGINT, handler) - self.task = self.pool.map_async(function, arguments, callback=self.summary.extend) - self.pool.close() - -# cleanup - normal or interrupted - def cleanup(self): - """ - Invoke to properly terminate the process pool (eg if user cancels via control-C) - """ - self.pool.terminate() - self.pool.join() - manage_lock.release() - - def byte_sent_rate(self): - """ - Returns the upload transfer rate - """ - elapsed = time.time() - self.start_time - try: - rate = bytes_sent.value / elapsed - rate /= 1000000.0 - except: - rate = 0.0 - return rate - - def byte_recv_rate(self): - """ - Returns the download transfer rate - """ - elapsed = time.time() - self.start_time - try: - rate = bytes_recv.value / elapsed - rate /= 1000000.0 - except: - rate = 0.0 - return rate - - @staticmethod - def bytes_sent(): - """ - Returns the total bytes sent for the current process - """ - return bytes_sent.value - - @staticmethod - def bytes_recv(): - """ - Returns the total bytes recieved for the current process - """ - return bytes_recv.value - - def is_done(self): - """ - BOOLEAN test for transfer completion - """ - return self.task.ready() diff --git a/v3/pmount.py b/v3/pmount.py deleted file mode 100755 index 9f54e01..0000000 --- a/v3/pmount.py +++ /dev/null @@ -1,894 +0,0 @@ -#!/usr/bin/env python3 - -import os -import sys -import math -import stat -import time -import errno -import random -import shutil -import string -import getpass -import logging -import http.client -import urllib.request, urllib.error, urllib.parse -import argparse -import tempfile -import posixpath -import configparser -from datetime import datetime -import mfclient - -try: - from .fuse import FUSE, FuseOSError, Operations -except: - print("Error: this system does not seem to have FUSE installed.") - -# === -class mfread(): - """ - Handle downloads from mediaflux - """ - def __init__(self, response): - self.response = response - self.offset = 0 - -# === -class mfwrite(): - """ - Handle buffered uploads to Mediaflux - """ - def __init__(self, store=None, quota=None, tmpfile=None): - self.buffer = bytearray() - self.length = 0 - self.offset = 0 - self.total = 0 - self.tmpfile = tmpfile - self.store = store - self.quota = quota - - def inject(self, buff, offset): - size = len(buff) - if offset == self.total: - # sequential buffer extend - self.buffer.extend(buff) - self.length += size - self.total += size - else: - # inject at unexpected (non-sequential) offset ... shouldn't happen??? - print(("inject() A: buffer => offset=%d,length=%d,total=%d : input => offset=%d,size=%d" % (self.offset,self.length,self.total,offset,size))) - if offset == self.offset: - # case 1 - restart at same offset as the current buffer -> truncate buffer to the current input - self.buffer[0:] = buff - self.length = size - self.total = self.offset + size - print(("inject() B: buffer => offset=%d,length=%d,total=%d" % (self.offset,self.length,self.total))) - else: - # case 2 - random buffer insert??? ... I give up - raise FuseOSError(errno.EILSEQ) - -# fail if we've exceed the destination store quota - if self.quota is not None: - if self.total > self.quota: - raise FuseOSError(errno.EDQUOT) - - return size - - def truncate(self): - self.buffer = self.buffer[:0] - self.offset = self.total - self.length = 0 - -# === -class pmount(Operations): - """ - FUSE implementation for mounting a Mediaflux namespace as a local folder - """ - -# --- performance decorators - class iostats(): - t_count = dict() - t_bytes = dict() - t_time = dict() - - @classmethod - def human(mystats, value): - units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] - if value: - rank = int((math.log10(value)) / 3) - rank = min(rank, len(units) - 1) - human = value / (1000.0 ** rank) - f = ("%.2f" % human).rstrip('0').rstrip('.') - else: - f = "0" - rank = 0 - return "%s %-s" % (f, units[rank]) - - @classmethod - def display(mystats, logger): - logger.info(" === iostats times ===") - for fname in list(mystats.t_count.keys()): - size = mystats.t_bytes[fname] - time = mystats.t_time[fname] - if size == 0: - logger.info("%-20s : %d calls : total time = %f s" % (fname, mystats.t_count[fname], time)) - - logger.info(" === iostats rates ===") - for fname in list(mystats.t_count.keys()): - time = max(0.1, mystats.t_time[fname]) - size = mystats.t_bytes[fname] - if size != 0: - rate = float(size) / time - h_rate = mystats.human(rate) - logger.info("%-20s : %d bytes @ %s/s" % (fname, mystats.t_bytes[fname], h_rate)) - - @classmethod - def record(mystats, func): - def wrapper(*args): -# setup for stats recording - if func.__name__ == 'read': - fname = "net_r" - size = int(args[2]) - elif func.__name__ == 'write': - fname = "net_w" - size = len(args[2]) - else: - fname = func.__name__ - size = 0 -# time the wrapped function - start = time.time() - res = func(*args) - elapsed = time.time() - start - -# fill out dictionaries - if fname in list(mystats.t_count.keys()): - mystats.t_count[fname] += 1 - mystats.t_bytes[fname] += size - mystats.t_time[fname] += elapsed - else: - mystats.t_count[fname] = 1 - mystats.t_bytes[fname] = size - mystats.t_time[fname] = elapsed - - return res - return wrapper - - -# --- MAIN setup - def __init__(self, args): - -# debugging - self.log = logging.getLogger('pmount') - if args.verbose: - self.log.setLevel(logging.DEBUG) - else: - self.log.setLevel(logging.INFO) - if args.logfile: - logfile = datetime.now().strftime('pmount-%Y-%m-%d-%H:%M:%S.log') - print(("Writing log to: %s" % logfile)) - logging.basicConfig(filename=logfile, format='%(asctime)s - %(levelname)s - %(message)s') - else: - logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') - -# NB: always use config file as we want a secure location to store the authentication token - token = "xyz123" - try: - config_filepath = os.path.expanduser("~/.mf_config") - self.log.debug("init() : config=%s" % config_filepath) - config = configparser.ConfigParser() - config.read(config_filepath) - - if config.has_section(args.config) is False: - config.add_section(args.config) - - if config.has_option(args.config, 'server'): - args.server = config.get(args.config, 'server') - - if config.has_option(args.config, 'protocol'): - args.protocol = config.get(args.config, 'protocol') - - if config.has_option(args.config, 'port'): - args.port = config.get(args.config, 'port') - - if config.has_option(args.config, 'encrypt'): - args.encrypt = config.get(args.config, 'encrypt') - - if config.has_option(args.config, 'domain'): - args.domain = config.get(args.config, 'domain') - - if config.has_option(args.config, 'token'): - token = config.get(args.config, 'token') - - if config.has_option(args.config, 'namespace'): - args.namespace = config.get(args.config, 'namespace') - - except Exception as e: - self.log.error("init(): %s" % str(e)) - -# remote filesystem - self.remote_root = args.namespace - self.readonly = args.readonly -# dictionary cache of assets and namespaces -# NB: have to separate as they are quite distinct objects in mediaflux -# key = parent namespace, value = another dictionary of children in the namespace -# second dictionary key is the child namespace or asset name, value = inode attributes - self.namespace_cache = dict() - self.asset_cache = dict() -# temporary local cache for new files - self.inode_cache = dict() -# mediaflux readonly and writeonly communication objects (keys are the fake filehandles to pass around) - self.mf_ronly = dict() - self.mf_wonly = dict() -# ownership cheat - self.uid = os.getuid() - self.gid = os.getgid() -# mtime cheat - delta = datetime.utcnow() - datetime(1970, 1, 1) - self.st_time = delta.total_seconds() - -# communication setup - self.timeout = 1800 -# around 100 MB is the best "sweet spot" so far ... but performance can be quite variable - self.buffer_max = 100000000 - -# attempt to connect and authenticate - self.log.info("init(): protocol=%s, server=%s, port=%s, encrypt=%r, domain=%s, namespace=%s" % (args.protocol, args.server, args.port, args.encrypt, args.domain, args.namespace)) - try: - self.mf_client = mfclient.mf_client(protocol=args.protocol, server=args.server, port=args.port, domain=args.domain, enforce_encrypted_login=eval(args.encrypt), debug=0) - except Exception as e: - self.log.error("init(): failed to connect: %s" % str(e)) - exit(-1) - try: - self.mf_client.login(token=token) - except Exception as e: - self.log.debug("init(): %s" % str(e)) - response = eval(input("No valid token found. Do you want to create one? ")) - if response.startswith('y') or response.startswith('Y'): - print(("Login to server [%s] and domain [%s] required." % (args.server, args.domain))) - user = eval(input("Username: ")) - password = getpass.getpass("Password: ") - self.mf_client.login(user, password) -# create token - actor = "%s:%s" % (args.domain, user) - result = self.mf_client.aterm_run('secure.identity.token.create :role -type user "%s" :role -type domain "%s" :min-token-length 16' % (actor, args.domain)) - for elem in result.iter(): - if elem.tag == 'token': - token = elem.text - self.mf_client.token = token - self.log.info("init(): Token created successfully") -# save configuration - config.set(args.config, 'server', args.server) - config.set(args.config, 'protocol', args.protocol) - config.set(args.config, 'port', args.port) - config.set(args.config, 'encrypt', args.encrypt) - config.set(args.config, 'domain', args.domain) - config.set(args.config, 'namespace', args.namespace) - config.set(args.config, 'session', self.mf_client.session) - config.set(args.config, 'token', token) - f = open(config_filepath, "w") - config.write(f) - f.close() - else: - print("Authentication failed") - exit(-1) -# success - self.verbose = args.verbose - self.log.info("init(): connection established") - -# --- triggered on ctrl-C or unmount - def destroy(self, path): - self.iostats.display(self.log) - return 0 - -# --- fake filehandle for download (read only) - def mf_ronly_open(self, namespace, filename): - - # get the asset ID (NB: asset.query with :get-content-status True doesn't work) - reply = self.mf_client.aterm_run('asset.query :where "namespace=\'%s\' and name=\'%s\'"' % (namespace, filename)) - elem = reply.find(".//id") - if elem is not None: - asset_id = int(elem.text) - else: - self.log.debug("mf_ronly_open(): couldn't find asset [%s] in namespace [%s]" % (filename, namespace)) - raise FuseOSError(errno.ENOENT) -# get the content status - reply = self.mf_client.aterm_run('asset.content.status :id %d' % asset_id) - elem = reply.find(".//asset/state") - if elem is not None: -# recall if offline and raise a "Try Again" ref: https://github.com/sahlberg/libnfs/issues/164 - if "online" not in elem.text: - self.log.info("mf_ronly_open(): asset [%s] in namespace [%s] is OFFLINE -> migrating [%d] ONLINE" % (filename, namespace, asset_id)) - self.mf_client.aterm_run("asset.content.migrate :id %d :destination 'online'" % asset_id) - raise FuseOSError(errno.EAGAIN) - else: - self.log.warning("mf_ronly_open(): failed to retrieve content status for asset [%s] in namespace [%s]" % (filename, namespace)) - -# construct URL to the file and open - url = self.mf_client.data_get + "?_skey=%s&id=%d" % (self.mf_client.session, asset_id) - response = urllib.request.urlopen(url, timeout=self.timeout) -# FIXME - end of range = max open files ... - for fh in range(1,100): - if self.mf_ronly.get(fh) is None: - self.mf_ronly[fh] = mfread(response) - return fh -# couldn't get a free filehandle - give up - raise FuseOSError(errno.EMFILE) - -# --- fake filehandle for upload (write only) - def mf_wonly_open(self, folder, filename): -# get info on destination - try: - reply = self.mf_client.aterm_run("asset.namespace.describe :namespace %s" % folder) - elem = reply.find(".//store") - store = elem.text -# NB: doesn't fit the namespace quota scheme - reply = self.mf_client.aterm_run("asset.store.describe :name %s" % store) - elem = reply.find(".//mount/free") - quota = int(elem.text) - except Exception as e: - self.log.error("mf_wonly_open() : %s" % str(e)) - raise FuseOSError(errno.ENODATA) -# create server upload job - try: - reply = self.mf_client.aterm_run("server.io.job.create :store 'asset:%s'" % store) - elem = reply.find(".//ticket") - ticket = int(elem.text) - reply = self.mf_client.aterm_run("server.io.job.describe :ticket %d" % ticket) - elem = reply.find(".//path") - tmpfile = elem.text - self.mf_wonly[ticket] = mfwrite(store=store, quota=quota, tmpfile=tmpfile) - except Exception as e: - self.log.error("mf_wonly_open() : %s" % str(e)) - raise FuseOSError(errno.EPERM) - - self.log.debug("mf_wonly_open(): backing store=%s, quota=%d, tmpfile=%s, ticket=%s" % (store, quota, tmpfile, ticket)) - return ticket - -# --- convert virtual path to the server path - def _remote_fullpath(self, partial): - if self.remote_root == '/': - return partial - if partial.startswith("/"): - partial = partial[1:] - path = os.path.join(self.remote_root, partial) - if path.endswith('/'): - path = path[:-1] - return path - -# --- TODO - window's metadata files too? - def _should_ignore(self, filename): - if filename.startswith(".local"): - return True - if filename.startswith("._"): - return True - return False - -# --- create a new attribute dictionary - def inode_new(self, mode, links, size=0, mtime=-1): - if self.readonly is False: - mode = mode | 0o200 - if mtime == -1: - mtime = self.st_time - - attr = { 'st_uid':self.uid, 'st_gid':self.gid, 'st_size':size, 'st_mode':mode, 'st_nlinks':links, 'st_mtime':mtime } - return attr - -# --- namespace only population of inode and directory listing caches -# NB: assumes this inode and content listing are not cached & creates new entries - @iostats.record - def get_namespaces(self, fullpath): - -# add inodes for all child namespaces and populate directory listing - reply = self.mf_client.aterm_run('asset.namespace.list :namespace %s' % fullpath) - this_folder = dict() - for elem in reply.findall(".//namespace/namespace"): - folder = posixpath.join(fullpath, elem.text) - this_folder[elem.text] = self.inode_new(stat.S_IFDIR | 0o500, 2) -# cache the directory listing (namespaces only) - self.namespace_cache[fullpath] = this_folder - -# --- get asset query as an iterator object - @iostats.record - def get_asset_iter(self, namespace): - reply = self.mf_client.aterm_run('asset.query :where "namespace=\'%s\'" :action get-meta :as iterator' % namespace) - elem = reply.find(".//iterator") - return elem.text - -# --- get asset metadata for single item - @iostats.record - def get_asset(self, namespace, filename): - try: - reply = self.mf_client.aterm_run('asset.query :where "namespace=\'%s\' and name=\'%s\'" :action get-meta' % (namespace, filename)) - # no match? => doesn't exist - xml_path = reply.find(".//path") - if xml_path is None: - return None - # NB: some assets have no content => missing size element - xml_size = reply.find(".//size") - if xml_size is not None: - size = int(xml_size.text) - else: - size = 0 - mtime = self.st_time - xml_mtime = reply.find(".//mtime") - if xml_mtime is not None: - for k,v in list(xml_mtime.attrib.items()): - if k == 'millisec': - mtime = int(v) / 1000 - # it's an asset -> return info - return { 'st_uid':self.uid, 'st_gid':self.gid, 'st_size':size, 'st_mode':stat.S_IFREG | 0o400, 'st_nlink':1, 'st_mtime':mtime } - - except Exception as e: - self.log.error("get_asset(): %s" % str(e)) - - return None - -# --- testing mechanism - def fail_session(self): - print("Injecting session failure") - print(("old session = %s" % self.mf_client.session)) - self.mf_client.session = None - -# --- grant visibility of virtual fs - def access(self, path, mode): - return 0 - -# --- get file/folder attributes - @iostats.record - def getattr(self, path, fh=None): - -# check the temporary cache - inode = self.inode_cache.get(path) - if inode is not None: - return inode - - fullpath = self._remote_fullpath(path) - name = posixpath.basename(fullpath) - parent = posixpath.dirname(fullpath) - -# ignore silly metadata files which shouldn't exist (or be silently created by the OS) - if self._should_ignore(name): - raise FuseOSError(errno.ENOENT) - -# attempt to get parent namespace's namespace listing, else generate - namespace_cache = self.namespace_cache.get(parent) - if namespace_cache is None: - self.get_namespaces(parent) - -# attempt to find in parent namespace - inode = self.namespace_cache[parent].get(name) - if inode is not None: - return inode - -# attempt to get parent namespace's asset listing - asset_cache = self.asset_cache.get(parent) - if asset_cache is not None: - inode = asset_cache.get(name) - if inode is not None: - return inode - -# triggered on non-navigational file query (eg file /some/random/path/file) - inode = self.get_asset(parent, name) - if inode is not None: - self.log.debug("getattr(): returning standalone inode for [%s/%s]" % (parent, name)) - return inode - -# I got nothing - raise FuseOSError(errno.ENOENT) - - -# --- display cached entries, otherwise lookup - @iostats.record - def readdir(self, path, fh): - namespace = self._remote_fullpath(path) - -# namespace entries - items = self.namespace_cache.get(namespace) - if items is None: - self.log.debug("readdir() : namespace listing server call needed [%s]" % namespace) - self.get_namespaces(namespace) - for item in list(self.namespace_cache[namespace].keys()): - yield item - -# asset entries - items = self.asset_cache.get(namespace) - if items is not None: - for item in list(items.keys()): - yield item - else: - self.log.debug("readdir() : asset listing server call needed [%s]" % namespace) - -# NB: we do the asset query inline (with yield) for performance reasons on very large directories - iterator = self.get_asset_iter(namespace) - done = False - this_folder = dict() - while not done: - result = self.mf_client.aterm_run("asset.query.iterate :id %s :size %d" % (iterator, 100)) - for elem in result.iter("asset"): - xml_path = elem.find(".//path") - if xml_path is not None: - xml_size = elem.find(".//size") - if xml_size is not None: - size = int(xml_size.text) - else: - size = 0 - fullpath = xml_path.text - filename = posixpath.basename(fullpath) - mtime = self.st_time - xml_mtime = elem.find(".//mtime") - if xml_mtime is not None: - for k,v in list(xml_mtime.attrib.items()): - if k == 'millisec': - mtime = int(v) / 1000 -# add the inode - this_folder[filename] = self.inode_new(stat.S_IFREG | 0o400, 1, size=size, mtime=mtime) - yield filename - else: - self.log.debug("readdir() : bad asset metadata for element [%r]" % elem) -# check for completion - for elem in result.iter("iterated"): - state = elem.get('complete') - if "true" in state: - done = True - -# completed ... now we can cache the full asset listing - self.asset_cache[namespace] = this_folder - -# --- - def statfs(self, path): -# FUSE seems to ignore the recommened block size values, as far as I can tell ... - keys = ['f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax'] - fake = dict() - for key in keys: - fake[key] = 0 - return fake - -# --- - def utimens(self, path, times=None): - self.log.debug("utimens() : path=%s " % path) - return 0 - -# --- TODO - metadata via extended attributes? -# def getxattr(self, path, name, *args): -# self.log.debug("getxattr() : path=%s : name=%s" % (path, name)) -# return "value[%s]" % name -# def listxattr(self, path): -# self.log.debug("listxattr() : path=%s" % path) -# return ["xpath1", "xpath2"] - -# --- - def mkdir(self, path, mode): - if self.readonly: - raise FuseOSError(errno.EACCES) -# build paths - fullpath = self._remote_fullpath(path) - parent = posixpath.dirname(fullpath) - child = posixpath.basename(fullpath) -# run mkdir command and update cache on success - try: - self.mf_client.aterm_run('asset.namespace.create :namespace "%s"' % fullpath) - namespace_cache = self.namespace_cache.get(parent) - if namespace_cache is not None: - namespace_cache[child] = self.inode_new(stat.S_IFDIR | 0o500, 2) - except Exception as e: - self.log.debug("mkdir(): %s" % str(e)) - raise FuseOSError(errno.EACCES) - -# --- - def rmdir(self, path): - if self.readonly: - raise FuseOSError(errno.EACCES) -# check if there is any content under this folder - fullpath = self._remote_fullpath(path) - parent = posixpath.dirname(fullpath) - child = posixpath.basename(fullpath) - reply = self.mf_client.aterm_run('asset.query :where "namespace>=\'%s\'" :action count :size 1' % fullpath) - elem = reply.find(".//value") - count = int(elem.text) -# delete ony if there is absolutely no content (helps me sleep better at nights) - if count == 0: - self.log.info("rmdir(): removing empty folder: %s" % fullpath) - try: - self.mf_client.aterm_run('asset.namespace.destroy :namespace "%s"' % fullpath) - namespace_cache = self.namespace_cache.get(parent) - if namespace_cache is not None: - del self.namespace_cache[parent][child] - return - except Exception as e: - self.log.debug("rmdir(): %s" % str(e)) - raise FuseOSError(errno.EACCES) -# non empty folder error - raise FuseOSError(errno.ENOTEMPTY) - -# --- - def rename(self, old, new): - if self.readonly: - raise FuseOSError(errno.EACCES) - try: -# build source and destination paths - old_fullpath = self._remote_fullpath(old) - oldname = posixpath.basename(old_fullpath) - new_fullpath = self._remote_fullpath(new) - namespace = posixpath.dirname(new_fullpath) - newname = posixpath.basename(new_fullpath) -# file - inode = self.getattr(old) - if inode['st_mode'] & stat.S_IFREG: - self.mf_client.aterm_run('asset.move :id "path=%s" :namespace "%s" :name "%s"' % (old_fullpath, namespace, newname)) - asset_cache = self.asset_cache.get(namespace) - if asset_cache is not None: - asset_cache[newname] = asset_cache.pop(oldname) -# directory -# NB: mediaflux command only seems to allow rename ... can't move a folder into another folder (for example) - if inode['st_mode'] & stat.S_IFDIR: - self.mf_client.aterm_run('asset.namespace.rename :namespace "%s" :name "%s"' % (old_fullpath, newname)) - namespace_cache = self.namespace_cache.get(namespace) - if namespace_cache is not None: - namespace_cache[newname] = namespace_cache.pop(oldname) - - except Exception as e: - self.log.debug("rename(): %s" % str(e)) - raise FuseOSError(errno.EACCES) - -# --- - def unlink(self, path): - if self.readonly: - raise FuseOSError(errno.EACCES) - fullpath = self._remote_fullpath(path) - namespace = posixpath.dirname(fullpath) - filename = posixpath.basename(fullpath) -# run delete command and remove from cache on success - try: - self.mf_client.aterm_run('asset.destroy :id "path=%s"' % fullpath) - asset_cache = self.asset_cache.get(namespace) - if asset_cache is not None: - del asset_cache[filename] - except Exception as e: -# FIXME - raise the correct error for other cases (eg doesn't exist, deleted from the server by 3rd party) - self.log.debug("unlink(): %s" % str(e)) - raise FuseOSError(errno.EACCESS) - -# --- not supported - def mknod(self, path, mode, dev): - self.log.debug("mknod() : path=%s" % path) - raise FuseOSError(errno.EACCES) - - def readlink(self, path): - self.log.debug("readlink() : path=%s" % path) - raise FuseOSError(errno.EPERM) - - def symlink(self, name, target): - self.log.debug("symlink() : name=%s, target=%s" % (name, target)) - raise FuseOSError(errno.EPERM) - - def link(self, target, name): - self.log.debug("link() : target=%s, name=%s" % (target, name)) - raise FuseOSError(errno.EPERM) - -# --- - def open(self, path, flags): - self.log.debug("open() : path=%s, flags=%r" % (path, flags)) - if flags & os.O_RDWR: - # not sure we can ever support this - raise FuseOSError(errno.EPERM) - if flags & os.O_WRONLY: - # TODO - might be able to use the create() upload path here ... - raise FuseOSError(errno.EPERM) -# init paths - fullpath = self._remote_fullpath(path) - namespace = posixpath.dirname(fullpath) - filename = posixpath.basename(fullpath) - -# start the download and associate with a fake filehandle - return self.mf_ronly_open(namespace, filename) - -# --- - @iostats.record - def read(self, path, size, offset, fh): - mfobj = self.mf_ronly[fh] -# if offset matches our mediaflux stream object - continue the sequential read (faster) - if offset == mfobj.offset and mfobj.response is not None: - try: - data = mfobj.response.read(size) - mfobj.offset += len(data) - return data - - except Exception as e: - self.log.error("read() sequential access ERROR: %s" % str(e)) - pass - else: -# ensure we stick to random access mode - mfobj.reponse = None -# fallback to slower random access method - fullpath = self._remote_fullpath(path) - reply = self.mf_client.aterm_run('asset.content.get :id "path=%s" :length %d :offset %d :out dummy' % (fullpath, size, offset)) - try: - elem = reply.find(".//outputs/url") - url = elem.text - response = urllib.request.urlopen(url, timeout=self.timeout) - return response.read(size) - - except Exception as e: - self.log.error("read() random access ERROR: %s" % str(e)) - pass - - raise FuseOSError(errno.EREMOTEIO) - -# --- - def create(self, path, mode, fi=None): - self.log.debug("create() : path=%s, mode=%d" % (path, mode)) - if self.readonly: - raise FuseOSError(errno.EACCES) - - fullpath = self._remote_fullpath(path) - namespace = posixpath.dirname(fullpath) - filename = posixpath.basename(fullpath) - -# don't allow the OS to silently pollute - if self._should_ignore(filename): - raise FuseOSError(errno.EPERM) - -# get ref to use as filehandle for write() - fakehandle = self.mf_wonly_open(namespace, filename) - -# create temporary inode - required as the kernel calls getattr() to enforce there is an inode after create() - self.inode_cache[path] = self.inode_new(mode=mode, links=1, size=0) - - return fakehandle - -# --- write the current buffer to the io job ticket - def mf_write(self, mfbuffer, ticket): - if mfbuffer.length == 0: - return - -# custom multipart post to mediaflux - xml_string = '' % self.mf_client.session - xml_string += '%d%d' % (ticket, mfbuffer.offset) - boundary = ''.join(random.choice(string.digits + string.ascii_letters) for i in range(30)) - mimetype = 'application/octet-stream' - lines = [] - lines.extend(('--%s' % boundary, 'Content-Disposition: form-data; name="request"', '', str(xml_string),)) - lines.extend(('--%s' % boundary, 'Content-Disposition: form-data; name="nb-data-attachments"', '', "1",)) -# NB: the tmp file name is required (otherwise the bytes go into a black hole) - lines.extend(('--%s' % boundary, 'Content-Disposition: form-data; name="filename"; filename="%s"' % mfbuffer.tmpfile, 'Content-Type: %s' % mimetype, '', '')) - - body = '\r\n'.join(lines) - total_size = len(body) + mfbuffer.length + len(boundary) + 8 - - if self.mf_client.encrypted_data is True: - conn = http.client.HTTPSConnection(self.mf_client.data_put, timeout=self.timeout) - else: - conn = http.client.HTTPConnection(self.mf_client.data_put, timeout=self.timeout) - - conn.putrequest('POST', "/__mflux_svc__") - conn.putheader('Connection', 'keep-alive') - conn.putheader('Cache-Control', 'no-cache') - conn.putheader('Content-Length', str(total_size)) - conn.putheader('Content-Type', 'multipart/form-data; boundary=%s' % boundary) - conn.putheader('Content-Transfer-Encoding', 'binary') - conn.endheaders() - -# main send - conn.send(body) - conn.send(mfbuffer.buffer) - -# terminating line (len(boundary) + 8) - tail = "\r\n--%s--\r\n" % boundary - conn.send(tail) -# get ACK from server (asset ID) else error (raise exception) - resp = conn.getresponse() - reply = resp.read() - conn.close() - -# --- buffer the data and send when limit has been exceeded - @iostats.record - def write(self, path, buf, offset, fh): - mfbuffer = self.mf_wonly[fh] - size = mfbuffer.inject(buf, offset) - if mfbuffer.length > self.buffer_max: - self.mf_write(mfbuffer, fh) - mfbuffer.truncate() -# NB: update inode immediately to stop the system retrying write() chunks - inode = self.inode_cache[path] - inode['st_size'] = mfbuffer.total - return size - -# CURRENT - pretend these worked and return success ... -# TODO - explore implications/better solutions? -# --- - def chmod(self, path, mode): - self.log.debug("chmod() : path=%s, mode=%d" % (path, mode)) - return 0 -# --- - def chown(self, path, uid, gid): - self.log.debug("chown() : path=%s, uid=%d, gid=%d" % (path, uid, gid)) - return 0 -# --- - def truncate(self, path, length, fh=None): -# if length=0, could use asset.content.remove() ... but doesn't seem to be a general solution - self.log.debug("truncate() : path=%s, length=%d" % (path, length)) - return 0 -# --- - def lock(self, path, fip, cmd, lock): - self.log.debug("lock() : path=%s, fip=%r, cmd=%r, lock=%r" % (path, fip, cmd, lock)) - return 0 -# --- - def flush(self, path, fh): - self.log.debug("flush() : path=%s, fh=%d" % (path, fh)) - return 0 -# --- - def fsync(self, path, fdatasync, fh): - return self.flush(path, fh) - -# --- -# NB - release() return code/exceptions are ignored by FUSE - so there's no way to fail the operation from this method - def release(self, path, fh): -# init - fullpath = self._remote_fullpath(path) - namespace = posixpath.dirname(fullpath) - filename = posixpath.basename(fullpath) - - mfobj = self.mf_wonly.get(fh) - if mfobj is not None: -# path1 - create() was used for the file handle - empty the buffer (if needed) and tell the server the job is done - try: - self.mf_write(mfobj, fh) - except Exception as e: - self.log.error("release(1): %s" % str(e)) - try: - self.mf_client.aterm_run("server.io.write.finish :ticket %d" % fh) - except Exception as e: - self.log.error("release(2): %s" % str(e)) - try: -# create the asset -# NB: explicitly set the store here to workaround mediaflux bug -# xml_string = '' % self.mf_client.session -# xml_string += '%s%s%s'% (namespace, filename, mfobj.store) -# xml_string += '%d' % fh -# reply = self.mf_client._post(xml_string) -# NEW - fixed mfclient to cope with this case - reply = self.mf_client.aterm_run('service.execute :service -name "asset.create" < :namespace "%s" :name "%s" :store "%s" > :input-ticket %d' % (namespace, filename, mfobj.store, fh)) - -# update directory cache if it exists (if it doesn't it'll be generated by a server call when needed anyway) - asset_cache = self.asset_cache.get(namespace) - if asset_cache is not None: - asset_cache[filename] = self.inode_new(mode=stat.S_IFREG | 0o400, links=1, size=mfobj.total) - except Exception as e: - self.log.error("release(3): %s" % str(e)) -# cleanup - del self.inode_cache[path] - self.mf_wonly[fh] = None - else: -# path2 - open() was used for the file handle - del self.mf_ronly[fh] - - -# --- main: process arguments and pass to FUSE -if __name__ == '__main__': - - parser = argparse.ArgumentParser() - parser.add_argument("path", help="Local path to present the virtual filesystem") - parser.add_argument("-c", dest="config", default="pawsey", help="Use the section named [CONFIG] in $HOME/.mf_config") - parser.add_argument("-s", dest="server", default="data.pawsey.org.au", help="The mediaflux server") - parser.add_argument("-p", dest="port", default=443, help="The mediaflux port") - parser.add_argument("-d", dest="domain", default="ivec", help="The mediaflux authentication domain") - parser.add_argument("-n", dest="namespace", default="/projects", help="Top level mediaflux namespace") - parser.add_argument("-b", "--background", help="Run in the background", action="store_true") - parser.add_argument("-r", "--readonly", help="Mount as readonly", action="store_true") - parser.add_argument("-l", "--logfile", help="Create timestamped logfile", action="store_true") - parser.add_argument("-v", "--verbose", help="Activate verbose logging", action="store_true") - args = parser.parse_args() - -# default protocol for mediaflux - if int(args.port) == 80: - args.protocol = "http" - args.encrypt = "False" - else: - args.protocol = "https" - args.encrypt = "True" - -# main call -# NB: disallow threads (httplib/urllib2 are not thread safe) - FUSE(pmount(args), args.path, nothreads=True, foreground=not args.background) - diff --git a/v3/test_mfclient.py b/v3/test_mfclient.py deleted file mode 100755 index 2c362d1..0000000 --- a/v3/test_mfclient.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/python3 - -import os -import sys -import time -import shutil -import getpass -import urllib.request, urllib.error, urllib.parse -import binascii -import unittest -import mfclient -import posixpath -import configparser - -# global mfclient instance to avoid setup for every test class -mf_client = None - -################################################ -# serverless aterm style XML serialisation tests -################################################ -class mfclient_syntax(unittest.TestCase): - - def setUp(self): - global mf_client - self.mf_client = mf_client - - -# --- helper: remove common XML wrapper - def _peel(self, text): - prefix = '' - postfix = '' - if text.startswith(prefix): - text = text[len(prefix):] - text = text[:len(text)-len(postfix)] - return text - - - def test_asset_get(self): - line = 'asset.get :id 123 :format extended' - reply = self.mf_client.aterm_run(line, post=False) - self.assertEqual(self._peel(reply), '123extended') - - def test_actor_grant(self): - line = 'actor.grant :perm < :access access :resource -type service asset.* > :name request-review :type role' - reply = self.mf_client.aterm_run(line, post=False) - self.assertEqual(self._peel(reply), 'accessasset.*request-reviewrole') - - def test_acl_grant(self): - line = 'asset.namespace.acl.grant :namespace /www :acl < :actor -type user "public:public" :access < :namespace access :asset access > >' - reply = self.mf_client.aterm_run(line, post=False) - self.assertEqual(self._peel(reply), '/wwwpublic:publicaccessaccess') - - def test_asset_query(self): - line = 'asset.query :where "namespace>=/www" :action pipe :service -name asset.label.add < :label "PUBLISHED" >' - reply = self.mf_client.aterm_run(line, post=False) - self.assertEqual(self._peel(reply), 'namespace>=/wwwpipe') - - def test_empty_property_value(self): - reply = self.mf_client.aterm_run(r'dummy.call :element -property " " :element2 text', post=False) - self.assertEqual(self._peel(reply), 'text') - -# FIXME - in practise, might have to escape the [] chars as they are special in TCL (but this should be done internal to the string itself) - def test_service_add(self): - line = 'system.service.add :name custom.service :replace-if-exists true :access ACCESS :definition < :element -name arg1 -type string :element -name arg2 -type string -min-occurs 0 -default " " :element -name arg3 -type boolean -min-occurs 0 -default false > :execute \"return [xvalue result [asset.script.execute :id 1 :arg -name namespace [xvalue namespace $args] :arg -name page [xvalue page $args] :arg -name recurse [xvalue recurse $args]]]\"' - reply = self.mf_client.aterm_run(line, post=False) - self.assertEqual(self._peel(reply), 'custom.servicetrueACCESSreturn [xvalue result [asset.script.execute :id 1 :arg -name namespace [xvalue namespace $args] :arg -name page [xvalue page $args] :arg -name recurse [xvalue recurse $args]]]') - - def test_semicolon_value(self): - line = 'actor.grant :name public:public :type user :role -type role read-only' - reply = self.mf_client.aterm_run(line, post=False) - self.assertEqual(self._peel(reply), 'public:publicuserread-only') - - def test_whitespace_text(self): - line = 'asset.namespace.rename :name test3 :namespace /projects/Data Team/sean/test2 :id 123' - reply = self.mf_client.aterm_run(line, post=False) - self.assertEqual(self._peel(reply), 'test3/projects/Data Team/sean/test2123') - - def test_quoted_query(self): - line = "asset.query :where \"namespace='/www' and name='system-alert'\" :action get-name" - reply = self.mf_client.aterm_run(line, post=False) - self.assertEqual(self._peel(reply), 'namespace=\'/www\' and name=\'system-alert\'get-name') - - def test_sanitise_asset(self): -# as out input string is using double quotes - have to test escaped double quotes separately (see next test) - tmp_name = r"asset_^#%-&{}<>[]()*? $!':;,.@+`|=~1234567890\\" - reply = self.mf_client.aterm_run('asset.create :namespace /projects/Data Team :name "%s"' % tmp_name, post=False) - self.assertEqual(self._peel(reply), '/projects/Data Teamasset_^#%-&{}<>[]()*? $!\':;,.@+`|=~1234567890\\') - - def test_sanitise_asset_quotes(self): - reply = self.mf_client.aterm_run(r'asset.create :namespace /projects/Data Team :name "sean\"file"', post=False) - self.assertEqual(self._peel(reply), '/projects/Data Teamsean"file') - - def test_sanitise_namespace(self): - tmp_remote = r"/projects/Data Team/namespace_^#%-&{}<>[]()*? $!':;,.@+`|=~13457890\\" - reply = self.mf_client.aterm_run('asset.namespace.create :namespace "%s" :quota < :allocation "10 TB" >' % tmp_remote, post=False) - self.assertEqual(self._peel(reply), '/projects/Data Team/namespace_^#%-&{}<>[]()*? $!\':;,.@+`|=~13457890\\10 TB') - - def test_sanitise_namespace_quotes(self): - reply = self.mf_client.aterm_run(r'asset.namespace.create :namespace "namespace_\"" :quota < :allocation "10 TB" >', post=False) - self.assertEqual(self._peel(reply), 'namespace_"10 TB') - - def test_sanitise_www_list(self): - reply = self.mf_client.aterm_run('www.list :namespace "/projects/Data Team/sean\'s dir" :page 1 :size 30', post=False) - self.assertEqual(self._peel(reply), '/projects/Data Team/sean\'s dir130') - - def test_xmlns_parsing(self): - reply = self.mf_client.aterm_run(r'asset.set :id 123 :meta < :pawsey:custom < :pawsey-key "pawsey value" >', post=False) - self.assertEqual(self._peel(reply), '123pawsey value') - - def test_negative_not_attribute(self): - reply = self.mf_client.aterm_run('asset.set :id 123 :geoshape < :point < :latitude -31.95 :longitude 115.86 :elevation 10.0 > >', post=False) - self.assertEqual(self._peel(reply), '123-31.95115.8610.0') - - def test_asset_get_out(self): - reply = self.mf_client.aterm_run('asset.get :id 123 :format extended :out /Users/sean/test123', post=False) - self.assertEqual(self._peel(reply), '123extendedsession') - - def test_service_execute(self): - reply = self.mf_client.aterm_run('service.execute :service -name "asset.create" < :namespace "folder" :name "file" > :input-ticket 1', post=False) - self.assertEqual(reply, 'folderfile1') - - -######################################## -# convenience wrapper for squishing bugs -######################################## -class mfclient_bugs(unittest.TestCase): - def setUp(self): - global mf_client - self.mf_client = mf_client - -# DONE - def test_service_execute(self): - reply = self.mf_client.aterm_run('service.execute :service -name "asset.create" < :namespace "folder" :name "file" > :input-ticket 1', post=False) - self.assertEqual(reply, 'folderfile1') - - -###### -# main -###### -if __name__ == '__main__': - -# acquire a dummy (non-connected/authenticated) client instance - try: - mf_client = mfclient.mf_client("http", "80", "localhost", dummy=True) - print("\n----------------------------------------------------------------------") - print("Running offline tests for: mfclient module") - print("----------------------------------------------------------------------\n") - except Exception as e: - print((str(e))) - exit(-1) - - -# classes to test - test_class_list = [mfclient_syntax] -# test_class_list = [mfclient_bugs] - - -# build suite - suite_list = [] - for test_class in test_class_list: - suite_list.append(unittest.TestLoader().loadTestsFromTestCase(test_class)) - suite = unittest.TestSuite(suite_list) - -# run suite - unittest.TextTestRunner(verbosity=2).run(suite) - diff --git a/v3/test_pshell.py b/v3/test_pshell.py deleted file mode 100755 index ed97613..0000000 --- a/v3/test_pshell.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/python - -import os -import sys -import unittest -import subprocess -import xml.etree.ElementTree as ET -from . import pshell - -######################### -# serverless pshell tests -######################### -class pshell_syntax(unittest.TestCase): - - def test_cd(self): - proc = subprocess.Popen(["pshell.py", "-c", "dummy", "cd /projects\"'"], stdout=subprocess.PIPE) - for line in proc.stdout: - if "request" in line: - self.assertEqual(line.strip(), '/projects"\'') - - def test_rm(self): - proc = subprocess.Popen(["pshell.py", "-c", "dummy", "rm *\'*"], stdout=subprocess.PIPE) - for line in proc.stdout: - if "request" in line: - self.assertEqual(line.strip(), 'namespace=\'/projects\' and name=\'*\\\'*\'count') - - def test_file(self): - proc = subprocess.Popen(["pshell.py", "-c", "dummy", r'file "/dir1/../dir2/test_!@#\""'], stdout=subprocess.PIPE) - for line in proc.stdout: - if "request" in line: - self.assertEqual(line.strip(), 'path=/dir2/test_!@#"') - - def test_mkdir(self): - proc = subprocess.Popen(["pshell.py", "-c", "dummy", "mkdir /dir1/../dir2/namespace\"'"], stdout=subprocess.PIPE) - for line in proc.stdout: - if "request" in line: - self.assertEqual(line.strip(), '/dir2/namespace"\'') - - def test_rmdir(self): - proc = subprocess.Popen(["pshell.py", "-c", "dummy", "rmdir sean's dir"], stdout=subprocess.PIPE) - for line in proc.stdout: - if "request" in line: - self.assertEqual(line.strip(), '/projects/sean\'s dir') - -# NEW - test conversion of XML to Arcitecta's shorthand format - used for metadata import - def test_import_metadata(self): - pp = pshell.parser() - xml_root = ET.fromstring('"image/tiff"') - result = pp.xml_to_mf(xml_root, result=None) - self.assertEqual(result, ' :ctype "image/tiff"') - xml_root = ET.fromstring('5.0') - result = pp.xml_to_mf(xml_root, result=None) - self.assertEqual(result, ' :geoshape < :point < :elevation 5.0 > >') - - -######################################## -# convenience wrapper for squishing bugs -######################################## -class pshell_bugs(unittest.TestCase): - def setUp(self): - print("setup") - -# TODO - more testing of pshell - def test_squish(self): - proc = subprocess.Popen(["pshell.py", "-c", "dummy", "import script2"], stdout=subprocess.PIPE) - for line in proc.stdout: - print((line.strip())) - -###### -# main -###### -if __name__ == '__main__': - - print("\n----------------------------------------------------------------------") - print("Running offline tests for: pshell") - print("----------------------------------------------------------------------\n") - -# classes to test - test_class_list = [pshell_syntax] - -# test_class_list = [pshell_bugs] - - -# build suite - suite_list = [] - for test_class in test_class_list: - suite_list.append(unittest.TestLoader().loadTestsFromTestCase(test_class)) - suite = unittest.TestSuite(suite_list) - -# run suite - unittest.TextTestRunner(verbosity=2).run(suite) -