Commit 36b786b7 authored by Luc Yriarte's avatar Luc Yriarte
Browse files

os-wellbore-ddms snapshot @3268a78

parents
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# IDE
.idea/
# Distribution / packaging
.Python
develop-eggs/
dist/
eggs/
.eggs/
sdist/
wheels/
*.egg-info/
.installed.cfg
*.egg
python-packages
# Unit test / coverage reports
.pytest_cache/
# Environments
.env
.venv
env/
venv/
venv*/
ENV/
env.bak/
venv.bak/
.envs/
secrets/
.DS_Store
deploy/.DS_Store
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
\ No newline at end of file
# Introduction
Wellbore Data Management Services (WDMS) Open Subsurface Data Universe (OSDU) is one of the several backend services that comprise Schlumberger's Exploration and Production (E&P) software ecosystem. It is a single, containerized service written in Python that provides an API for wellbore related data.
## Install Software and Packages
1. Clone the os-wellbore-ddms repository
2. Download [Python](https://www.python.org/downloads/) >=3.7
3. Ensure pip, a pre-installed package manager and installer for Python, is installed and is upgraded to the latest version.
Windows:
```bash
py -m pip install --upgrade pip
py -m pip --version
```
Linux and macOS:
```bash
python3 -m pip install --upgrade pip
python3 -m pip --version
```
4. Using pip, download [FastAPI](https://fastapi.tiangolo.com/), the main framework to build the service APIs. To install fastapi and uvicorn (to work as the server), run the following command:
```bash
pip install fastapi[all]
```
5. venv - venv allows you to manage separate package installations for different projects. They essentially allow you to create a "virtual" isolated Python installation and packages into that virtual environment. venv is already included in the Python standard library and requires no addtional installation.
### Fast API Dependencies
- [pydantic](https://pydantic-docs.helpmanual.io/): provides the ability to do data validation using python type annotations. It enforces type hints at runtime provide a more robust data validation option.
- [dataclasses](https://pydantic-docs.helpmanual.io/usage/dataclasses/): module in python which provides a decorator and functions for automatically adding generated special methods to user-defined classes.
- [starlette](https://fastapi.tiangolo.com/features/#starlette-features): lightweight ASGI framework. FastAPI is a sub-class of Starlette and includes features such as websocket support, startup and shutdown events, session and cookie support.
### Additional Dependencies
- [uvicorn](https://www.uvicorn.org/) used as ASGI server to run WDMS app
- [cachetools](https://pypi.org/project/cachetools/)
- [pyjwt](https://pypi.org/project/PyJWT/) and [cryptography](https://pypi.org/project/cryptography/) for auth purposes
- [pandas](https://pandas.pydata.org/) and [numpy](https://numpy.org/) for data manipulation
- [pyarrow](https://pypi.org/project/pyarrow/) for load and save data into parquet format
- [opencensus](https://opencensus.io/guides/grpc/python/) for tracing and logging on cloud provider
### Library Dependencies
- Common parts and interfaces
- osdu-core-python
- Implementation of blob storage on GCP
- osdu-core-python-gcp
- Storage, search and entitlements
- osdu-python-clients
## Project Startup
### Run the service locally
1. Create [virtual](https://pypi.org/project/virtualenv/) environment in the wellbore project directory. This will create a folder inside of the wellbore project directory. For example: ~/os-wellbore-ddms/nameofvirtualenv
Windows:
```bash
py -m venv env
```
on macOS and Linux:
```bash
python3 -m venv env
```
2. Activate the virtual environment
Windows:
```bash
env/Scripts/activate
```
macOS and Linux:
```bash
source env/bin/activate
```
3. Create pip.ini (Windows) or pip.conf (Mac) file inside the venv directory. This allows us to set a global index url which can download packages from specific sources.
Note: It is also possible to use [--extra-index-url parameter](https://pip.pypa.io/en/stable/reference/pip_install/#install-extra-index-url) to specify it on the pip install cmd inline
4. Install dependencies
```bash
pip install -r requirements.txt
```
5. Run the service
```bash
# Run the service which will default to http://127.0.0.1:8097
python main.py
# Run on specific host, port and enforce dev mode
python main.py --host MY_HOST --port MY_PORT --dev_mode 1
```
If host is `127.0.0.1` or `localhost`, the dev_mode is automatically set to True.
The only significant change if dev_mode is on, is that configuration errors at startup are logged but don’t prevent the service to run, and allow to override some implementations.
The hosts for the entitlements, search and storage services have to be provided as environment variables, or on the command line.
```bash
python main.py -e SERVICE_HOST_ENTITLEMENTS https://api.example.com/entitlements -e SERVICE_HOST_STORAGE https://api.example.com/storage -e SERVICE_HOST_SEARCH https://api.example.com/search
```
### Connect and Run Endpoints
1. Generate bearer token as all APIs but `/about` require authentication.
- Navigate to `http://127.0.0.1:8097/token` and follow the steps to generate a bearer token.
- Navigate to `http://127.0.0.1:8097/docs`. Click `Authorize` and enter your token. That will allow for authenticated requests.
2. Choose storage option
Even if the service runs locally it still relies on osdu data ecosystem storage service to store documents and google blob store to store binary data (`bulk data`). It is possible to override this and use your local file system instead by setting the following environment variables:
- `USE_INTERNAL_STORAGE_SERVICE_WITH_PATH` to store on a local folder instead of osdu ecosystem storage service.
- `USE_LOCALFS_BLOB_STORAGE_WITH_PATH` to store on a local folder instead of google blob storage.
```bash
# Create temp storage folders
mkdir tmpstorage
mkdir tmpblob
# Set your repo path
path="C:/source"
python main.py -e USE_INTERNAL_STORAGE_SERVICE_WITH_PATH $path/os-wellbore-ddms/tmpstorage -e USE_LOCALFS_BLOB_STORAGE_WITH_PATH $path/os-wellbore-ddms/tmpblob
```
To create a `log` record, below is a payload sample for the PUT `/ddms/v2/logs` API. The response will contain an id you can use on the `/ddms/v2/logs/{logid}/data` to create some bulk data.
```bash
[{
"data": {
"log": {
"family": "Gamma Ray",
"familyType": "Gamma Ray",
"format": "float64",
"mnemonic": "GR",
"name": "GAMM",
"unitKey": "gAPI"
}
},
"kind": "opendes:osdu:log:1.0.5",
"namespace": "opendes:osdu",
"legal": {
"legaltags": [
"opendes-public-usa-dataset-1"
],
"otherRelevantDataCountries": [
"US"
],
"status": "compliant"
},
"acl": {
"viewers": [
"data.default.viewers@opendes.p4d.cloud.slb-ds.com"
],
"owners": [
"data.default.owners@opendes.p4d.cloud.slb-ds.com"
]
},
"type": "log"
}
]
```
### Run with Uvicorn
```bash
uvicorn app.wdms_app:wdms_app --port LOCAL_PORT
```
Then access app on `http://localhost:LOCAL_PORT/docs`
### Run with Docker
#### Build Image
A Personal Access Token (PAT) is required to pull all the python packages.
```bash
USER=<username>
PAT=<PAT>
# Set PIP_EXTRA_URL
PIP_EXTRA_URL="<URL>"
# Set IMAGE_TAG
IMAGE_TAG="os-wellbore-ddms:dev"
# Build Image
docker build -t=$IMAGE_TAG --rm . -f ./build/dockerfile --build-arg PIP_EXTRA_URL=$PIP_EXTRA_URL --build-arg PIP_WHEEL_DIR=python-packages
```
#### Run Image
1. Run the image
Replace the LOCAL_PORT value with a local port
```bash
LOCAL_PORT=<local_port>
docker run -d -p $LOCAL_PORT:8097 -e OS_WELLBORE_DDMS_DEV_MODE=1 -e USE_LOCALFS_BLOB_STORAGE_WITH_PATH=1 $IMAGE_TAG
```
2. Access app on `http://localhost:LOCAL_PORT/docs`
3. The environment variable `OS_WELLBORE_DDMS_DEV_MODE=1` enables dev mode
4. Logs can be checked by running
```bash
docker logs CONTAINER_ID
```
### Run Unit Tests Locally
```bash
# Install test dependencies
pip install -r requirements_dev.txt
python -m pytest --junit-xml=unit_tests_report.xml --cov=app --cov-report=html --cov-report=xml ./tests/unit
```
Coverage reports can be viewed after the command is run. The HMTL reports are saved in the htmlcov directory.
### Port Forward from Kubernetes
1.List the pods
```bash
kubectl get pods
```
2.Port forward
```bash
kubectl port-forward pods/POD_NAME LOCAL_PORT:8097
```
3.Access it on `http://localhost:LOCAL_PORT/docs`
# this file will be updated in the build pipeline
__version__ = '0.2'
__build_number__ = 'local'
__app_name__ = 'Wellbore DDMS OSDU'
from cachetools import TTLCache
from fastapi import HTTPException, Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from jwt import PyJWTError
from starlette.authentication import AuthCredentials
from starlette.requests import Request
from starlette.status import HTTP_401_UNAUTHORIZED
from app.model.user import User
from app.utils import Context, async_with_cache
from app.helper import logger
import jwt
# manually using basic global cache for now as decorator doesn't work with coroutine
_user_info_cache = TTLCache(maxsize=512, ttl=60, getsizeof=lambda x: 1)
# Make the name very explicit for now
class OpenDESBearerToken(HTTPBearer):
pass
security = OpenDESBearerToken()
async def require_opendes_authorized_user(request: Request,
credentials: HTTPAuthorizationCredentials = Depends(security)):
token = credentials.credentials
ctx = Context.current()
user = await _get_user_from_token(ctx, token)
request.scope['auth'] = AuthCredentials(['authenticated'])
request.scope['user'] = user
Context.set_current_with_value(auth=token, user=user)
async def _get_user_from_token(ctx: Context, token: str) -> User:
global _user_info_cache
cache_key: str = token
return await async_with_cache(_user_info_cache, cache_key, get_user_from_token_not_cached, ctx, token)
async def get_user_from_token_not_cached(ctx: Context, token: str) -> User:
# TODO REAL entitlement call is needed here, for now basic decode without verify
try:
token_payload = jwt.decode(token, verify=False)
email = token_payload['email']
except (KeyError, PyJWTError):
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail='invalid token',
headers={'WWW-Authenticate': 'Bearer'},
)
groups = []
return User(email=email, authenticated=True, groups=groups)
import odes_storage
import odes_search
import odes_entitlements
from odes_storage.api_client import AsyncRecordsApi
from odes_search.api_client import AsyncSearchApi
from odes_entitlements.api_client import AsyncEntitlementsAuthAdministrationApi
__all__ = ['EntitlementsAuthServiceClient',
'SearchServiceClient',
'StorageRecordServiceClient',
'make_entitlements_auth_client',
'make_search_client',
'make_storage_record_client']
EntitlementsAuthServiceClient = AsyncEntitlementsAuthAdministrationApi
SearchServiceClient = AsyncSearchApi
StorageRecordServiceClient = AsyncRecordsApi
def make_entitlements_auth_client(host, token=None) -> EntitlementsAuthServiceClient:
return odes_entitlements.AsyncApis(odes_entitlements.AuthApiClient(host=host, token=token)).entitlements_auth_administration_api
def make_search_client(host, token=None) -> SearchServiceClient:
return odes_search.AsyncApis(odes_search.AuthApiClient(host=host, token=token)).search_api
def make_storage_record_client(host, token=None) -> StorageRecordServiceClient:
return odes_storage.AsyncApis(odes_storage.AuthApiClient(host=host, token=token)).records_api
from app.clients import EntitlementsAuthServiceClient
from app.utils import Context
async def get_entitlements_auth_service(ctx: Context) -> EntitlementsAuthServiceClient:
return await ctx.app_injector.get(EntitlementsAuthServiceClient, appkey=ctx.app_key, token=ctx.auth)
from app.clients import SearchServiceClient
from app.utils import Context
async def get_search_service(ctx: Context) -> SearchServiceClient:
return await ctx.app_injector.get(SearchServiceClient, appkey=ctx.app_key, token=ctx.auth)
from asyncio import iscoroutinefunction, gather
import uuid
from odes_storage.models import *
from osdu.core.api.storage.blob_storage_base import BlobStorageBase
async def no_check_appkey_token(appkey, token):
# empty method
pass
class StorageRecordServiceBlobStorage:
"""
implementation of storage service using blob storage. Security check (appkey & token) responsibility is delegated.
This is not meant to be used in production but for various testing and debugging purposes. Use injectors to override
the osdu impl to use this one instead
"""
def __init__(self,
blob_storage: BlobStorageBase,
project: str,
container: str,
auth_check_coro=no_check_appkey_token):
"""
:param blob_storage:
:param project: project than will pass to the blob storage calls
:param container: project than will pass to the blob storage calls
:param auth_check_coro:
"""
assert blob_storage
assert iscoroutinefunction(auth_check_coro)
self._storage: BlobStorageBase = blob_storage
self._project: str = project
self._container: str = container
self._auth_check = auth_check_coro
def _build_record_path(self, id: str, data_partition: str):
return f'{data_partition or "global"}_r_{id.replace(":", "_")}'
async def _check_auth(self, appkey=None, token=None):
await self._auth_check(appkey, token)
async def create_or_update_records(self,
record: List[Record] = None,