diff --git a/.gitignore b/.gitignore index a1c2a23..89ea27e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,23 +1,6 @@ -# Compiled class file -*.class - -# Log file *.log +*.gz -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar +# Ignore __pycache__ directories in any path +**/__pycache__ -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index c5f705a..13a91c1 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,210 @@ -# DeepPhe-CR-Release -Public release of the Deep Phenotype Extraction for Cancer Registries project. +# DeepPhe Stream Multi-Container Stack - release branch + +This multi-container docker stack consists of the following 2 containers: + +- 1: `dphe-stream-nginx` (reverse proxy and load balancer) +- 2: `dphe-stream` (document and patient summary REST API) + +## Changes needed to make a release + +- 1: Place the source code zip file, for instance `v0.1.0-cr-release.zip`, to the directory `dphe-stream`. This zip file will be used to build the `dphe-stream` docker image. +- 2: Edit the `dphe-stream/Dockerfile` and specify to use the target release version, for instance `0.1.0`. + +## Overview of tools + +- [Docker Engine](https://docs.docker.com/install/) +- [Docker Compose](https://docs.docker.com/compose/install/) + +Note: Docker Compose requires Docker to be installed and running first. + +## Docker post-installation configurations + +The Docker daemon binds to a Unix socket instead of a TCP port. By default, that Unix socket is owned by the user root and other users can only access it using sudo. The Docker daemon always runs as the root user. + +If you're using Linux and you don't want to preface the docker command with sudo, you can add users to the `docker` group: + +```` +sudo usermod -aG docker $USER +```` + +The log out and log back in so that your group membership is re-evaluated. If testing on a virtual machine, it may be necessary to restart the virtual machine for changes to take effect. + +Note: the following instructions with docker commands are based on managing Docker as a non-root user. + +## Docker build + +### Specify authentication token + +Before starting building the child images, specify the auth token in `dphe-stream/deepphe.properties`. This auth token will be used later when interacting with the REST API calls via the standard HTTP request `Authorization` header with the Bearer scheme in the form of: + +```` +Authorization: Bearer +```` + +This auth layer as a gateway will apply to all the HTTP requests before they can reach to the actual API endpoints. + +A default token is provided in the `dphe-stream/deepphe.propertiers` file. For greater security, it is strongly advised that you change this token to a new value for any deployed instance. + +### Build docker images + +Under the project root directory where we can find the `docker-compose.yml`: + +```` +docker-compose build +```` + +#### Start up services + +There are two configurable environment variables to keep in mind before starting up the containers: + +- `HOST_UID`: the user id on the host machine to be mapped to all the containers. Default to 1000 if not set or null. +- `HOST_GID`: the user's group id on the host machine to be mapped to all the containers. Default to 1000 if not set or null. + +We can set and verify the environment variable like below: + +```` +export HOST_UID=1000 +echo $HOST_UID +export HOST_GID=1000 +echo $HOST_GID +```` + +In security practice, the processes within a running container should not run as root, or assume that they are root. The system user on the host machine should be in the docker group, and it should also be the user who builds the images and starts the containers. That's why we wanted to use this user's UID and GID within the containers to avoid security holes and file system permission issues as well. + +```` +docker-compose up -d +```` + +This command spins up all the services (in the background and leaves them running) defined in the `docker-compose.yml` and aggregates the output of each container. + +Note: the initialization of containers takes some time, you can use the following command in another terminal window to monitor the progress: + +```` +docker-compose logs -f --tail="all" +```` + +You will have the following API base URL for the REST API container: + +- `dphe-stream`: `http://localhost:8080/deepphe` + +## Interact with the REST API + +Please remember that you'll need to send over the auth token (specified prior the docker build) in the `Authorization` header for each HTTP request: + +```` +Authorization: Bearer +```` + +If the auth token is missing from request or an invalid token being used, you'll get the HTTP 401 Unauthorized response. + +### Submit a document, do not cache information + +Use the following URL pattern to process a document, and submit the document text in the request body. HTTP header `Content-Type: text/plain` is required to make the call. + +```` +GET http://localhost:8080/deepphe/summarizeDoc/doc/ +```` + +Example CURL command: + +```` +curl -i -X GET http://localhost:8080/deepphe/summarizeDoc/doc/doc1 \ + -H "Content-Type: text/plain" \ + -H "Authorization: Bearer AbCdEf123456" \ + --data-binary "@patientX_doc1_RAD.txt" +```` + +### Submit a document, cache information for patient summary + +Use the following URL pattern to process a document for a given patient, and submit the document text in the PUT body with HTTP header `Content-Type: text/plain`. The patient ID is not used in document processing but is required for future patient summarization. + +```` +PUT http://localhost:8080/deepphe/summarizePatientDoc/patient//doc/ +```` + +Example CURL command: + +```` +curl -i -X PUT http://localhost:8080/deepphe/summarizePatientDoc/patient/patientX/doc/doc1 \ + -H "Content-Type: text/plain" \ + -H "Authorization: Bearer AbCdEf123456" \ + --data-binary "@patientX_doc1_RAD.txt" +```` + +You can also queue up the process by using the following call with the document text in request body. HTTP header `Content-Type: text/plain` is required to make the call: + +```` +PUT http://localhost:8080/deepphe/queuePatientDoc/patient//doc/ +```` + +Example CURL command: + +```` +curl -i -X PUT http://localhost:8080/deepphe/queuePatientDoc/patient/patientX/doc/doc1 \ + -H "Content-Type: text/plain" \ + -H "Authorization: Bearer AbCdEf123456" \ + --data-binary "@patientX_doc1_RAD.txt" +```` + +For this call, you won't get back the resulting JSON since the text processing is queued up. + +Note: The document information cache is automatically cleaned every 15 minutes, removing any document information that has not been accessed within the last 60 minutes. + +### Summarize a patient + +A patient summary can only be created using document information that was cached. This following call doesn't require a request body: + +```` +GET http://localhost:8080/deepphe/summarizePatient/patient/ +```` + +Example CURL command: + +```` +curl -i -X GET http://localhost:8080/deepphe/summarizePatient/patient/patientX \ + -H "Authorization: Bearer AbCdEf123456" +```` + +### Shell into the running container + +Sometimes you may want to shell into a running container to check more details, this can be done by: + +```` +docker exec -it bash +```` + +### Stop the running services + +```` +docker-compose stop +```` +The above command stops all the running containers of this project without removing them. It preserves containers, volumes, and networks, along with every modification made to them. The stopped containers can be started again with `docker-compose start`. + +Instead of stopping all the containers, you can also stop a particular service: + +```` +docker-compose stop +```` + +### Reset the status of our project + +```` +docker-compose down +```` + +This command stops both containers of this project and removes them as well the `dphe-stream-network`. All cached document information will be lost. + +Note: At this time DeepPhe Stream could be run with a single container. The multi-container stack exists to facilitate addition future workflows that may require additional containers. + + +## Run integration tests manually + +Once the containers are up running, we can run some integration tests written in Python within the `dphe-stream-nginx` container manually to verify the pipeline output by submitting some sample reports to the REST API. + +The test cases and configuration are located at `dphe-stream-dock/dphe-stream-nginx/integration-test`. If a different auth token is specified during the image creation phase, that same auth token should be specified in the `test.cfg` as well. + +```` +docker exec -it dphe-stream-nginx bash +cd integration-test/ +python3 test.py +```` diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..1f664a3 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,54 @@ +version: "3.7" +services: + + dphe-stream: + build: + context: ./dphe-stream + # Build the image with name and tag + image: dphe-stream:0.1.0-cr + hostname: dphe-stream + container_name: dphe-stream + init: true + restart: always + environment: + - HOST_GID=${HOST_GID:-1000} + - HOST_UID=${HOST_UID:-1000} + ports: + # Only for testing directly against the container + # dphe-stream container listens on port 8080 for the rest api + - "8181:8080" + volumes: + # Make log accessible on host + - "./dphe-stream/logs:/usr/src/app/v0.1.0-cr-release/dphe-stream-rest/logs" + networks: + - dphe-stream-network + + dphe-stream-nginx: + build: ./dphe-stream-nginx + # Build the image with name and tag + image: dphe-stream-nginx:0.1.0-cr + hostname: dphe-stream-nginx + container_name: dphe-stream-nginx + init: true + restart: always + environment: + - HOST_GID=${HOST_GID:-1000} + - HOST_UID=${HOST_UID:-1000} + ports: + # Map host machine port 8080 to container port 8080 (since nginx runs as non-root) + - "8080:8080" + volumes: + # Make log accessible on host + - "./dphe-stream-nginx/logs:/usr/src/app/logs" + # Mount nginx configuration file from host to container + - "./dphe-stream-nginx/dphe-stream.conf:/etc/nginx/conf.d/dphe-stream.conf" + # Mount the integration test + - "./dphe-stream-nginx/integration-test:/usr/src/app/integration-test" + depends_on: + # nginx reverse proxy forwarding requires the upstream servers running when nginx starts + - dphe-stream + networks: + - dphe-stream-network + +networks: + dphe-stream-network: diff --git a/dphe-stream-nginx/.dockerignore b/dphe-stream-nginx/.dockerignore new file mode 100644 index 0000000..d792ece --- /dev/null +++ b/dphe-stream-nginx/.dockerignore @@ -0,0 +1,11 @@ +**/*.png + +**/.git + +**/.gitignore + +Dockerfile + +.dockerignore + +**/*.md \ No newline at end of file diff --git a/dphe-stream-nginx/Dockerfile b/dphe-stream-nginx/Dockerfile new file mode 100644 index 0000000..f736c6d --- /dev/null +++ b/dphe-stream-nginx/Dockerfile @@ -0,0 +1,54 @@ +# Base image +FROM centos:7 + +# Change to directory that contains the Dockerfile +WORKDIR /usr/src/app + +# Copy from host to image +COPY . . + +# Nginx package from EPEL is old, we create a new repository file to install the latest mainline version of Nginx +RUN echo $'[nginx-mainline]\n\ +name=nginx mainline repo\n\ +baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/\n\ +gpgcheck=0\n\ +enabled=1\n'\ +>> /etc/yum.repos.d/nginx.repo + +# Reduce the number of layers in image by minimizing the number of separate RUN commands +# Update packages +# Install nginx (using the custom yum repo specified earlier) +# Remove the default nginx config file +# Overwrite the nginx.conf with ours to run nginx as non-root +# Install Extra Packages for Enterprise Linux (EPEL) +# Use the EPEL repo for installing python, pip +# Upgrade pip, after upgrading, both pip and pip3 are the same version +# Install the Python dependencies of integration test +# Clean all yum cache +# Copy the entrypoint script and make it executible +# Install gosu for de-elevating root to deepphe user +RUN yum update -y && \ + yum install -y nginx && \ + rm /etc/nginx/conf.d/default.conf && \ + mv nginx.conf /etc/nginx/nginx.conf && \ + yum install -y epel-release && \ + yum install -y python36 python36-pip && \ + pip3 install --upgrade pip && \ + pip install -r integration-test/requirements.txt && \ + yum clean all && \ + cp /usr/src/app/entrypoint.sh /usr/local/bin/entrypoint.sh && \ + chmod +x /usr/local/bin/entrypoint.sh && \ + curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/1.14/gosu-amd64" && \ + curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/1.14/gosu-amd64.asc" && \ + rm /usr/local/bin/gosu.asc && \ + chmod +x /usr/local/bin/gosu + +# Set an entrypoint +ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] + +# The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime. +# EXPOSE does not make the ports of the container accessible to the host. +# Here 8080 for nginx running as non-root +EXPOSE 8080 + +CMD ["nginx", "-g", "daemon off;"] \ No newline at end of file diff --git a/dphe-stream-nginx/dphe-stream.conf b/dphe-stream-nginx/dphe-stream.conf new file mode 100644 index 0000000..74246c6 --- /dev/null +++ b/dphe-stream-nginx/dphe-stream.conf @@ -0,0 +1,38 @@ +server { + # Only root can listen on ports below 1024, we use higher-numbered ports + # since nginx is running under non-root user hubmap + listen 8080; + + server_name localhost; + + root /usr/share/nginx/html; + + # Logging to the mounted volume for outside container access + access_log /usr/src/app/logs/nginx_access_dphe-stream.log; + error_log /usr/src/app/logs/nginx_error_dphe-stream.log warn; + + # Forward data submission calls to dphe-stream container by using the dphe-stream hostname + # Port 8080 specified in dphe-stream/application.properties + location /deepphe/ { + # Transform strings like `/nlp/WHATEVER` to `/WHATEVER` + rewrite ^/deepphe/(.*) /$1 break; + # Then forward to the dphe-stream container based on hostname + proxy_pass http://dphe-stream:8080; + + proxy_set_header Host $http_host; + proxy_redirect off; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Increase gateway timeout + proxy_connect_timeout 300; + proxy_send_timeout 300; + proxy_read_timeout 300; + send_timeout 300; + } + +} \ No newline at end of file diff --git a/dphe-stream-nginx/entrypoint.sh b/dphe-stream-nginx/entrypoint.sh new file mode 100644 index 0000000..2fe7fa8 --- /dev/null +++ b/dphe-stream-nginx/entrypoint.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +# Pass the HOST_UID and HOST_UID from environment variables specified in the child image docker-compose +HOST_GID=${HOST_GID} +HOST_UID=${HOST_UID} + +echo "Starting dphe-stream-nginx container with the same host user UID: $HOST_UID and GID: $HOST_GID" + +# Create a new user with the same host UID to run processes on container +# The Filesystem doesn't really care what the user is called, +# it only cares about the UID attached to that user +# Check if user already exists and don't recreate across container restarts +getent passwd $HOST_UID > /dev/null 2&>1 +# $? is a special variable that captures the exit status of last task +if [ $? -ne 0 ]; then + groupadd -r -g $HOST_GID deepphe + useradd -r -u $HOST_UID -g $HOST_GID -m deepphe +fi + +# When running Nginx as a non-root user, we need to create the pid file +# and give read and write access to /var/run/nginx.pid, /var/cache/nginx, and /var/log/nginx +# In individual nginx *.conf, also don't listen on ports 80 or 443 because +# only root processes can listen to ports below 1024 +touch /var/run/nginx.pid +chown -R deepphe:deepphe /var/run/nginx.pid +chown -R deepphe:deepphe /var/cache/nginx +chown -R deepphe:deepphe /var/log/nginx + +# Make /usr/src/app accessible +chown -R deepphe:deepphe /usr/src/app + +# Lastly we use gosu to execute our process "$@" as that user +# Remember CMD from a Dockerfile of child image gets passed to the entrypoint.sh as command line arguments +# "$@" is a shell variable that means "all the arguments" +exec /usr/local/bin/gosu deepphe "$@" diff --git a/dphe-stream-nginx/integration-test/patientX/patientX_doc1_RAD.txt b/dphe-stream-nginx/integration-test/patientX/patientX_doc1_RAD.txt new file mode 100644 index 0000000..7cbead0 --- /dev/null +++ b/dphe-stream-nginx/integration-test/patientX/patientX_doc1_RAD.txt @@ -0,0 +1,54 @@ +=================================================================== +Report ID.....................1,doc1 +Patient ID....................pt123456789 +Patient Name..................PatientX +Principal Date................20100121 1345 +Record Type...................RAD +=================================================================== +[Report de-identified (Limited dataset compliant) by De-ID v.6.24.5.1] + +CLINICAL HISTORY: +50 year old peri-menopausal female who presents with new hard palpable lump +in the left breast. + +TECHNIQUE: +Full field digital mammography with CAD was performed including +routine views of both breasts, spot magnification views on the right +with a full 90 degree lateral and spot compression views on the left. + +Left breast and axillary ultrasound evaluation was performed. + +COMPARISON: +This study is compared to previous examinations dating back to 2004. + +FINDINGS: +Heterogeneously dense fibroglandular tissue is present throughout +both breasts limiting the sensitivity of the mammogram. There is no evidence +of mass or calcifications in the right breast. + +A large firm mass is seen in the upper outer left breast at the 12:30 +o'clock region. The mass measures 1x2 cm on the CC view. Calcifications are +seen adjacent to the mass. + +Ultrasound evaluation was performed on the area and a 1.2x3.4x5.6 cm hypoechoic +mass is seen in the left breast at the 12:30 o'clock region. + +Ultrasound of the left axillary lymph nodes were performed revealing multiple +abnormally thickened lymph nodes. The largest lymph node has a thickened cortex +of at least 7 mm. + +IMPRESSION: +A large hypoechoic mass at the 10:30 location of the left breast is highly +suggestive of a malignancy. The mass measures 1.2x3.4x5.6 cm. Ultrasound guided +core biopsy is recommended. + +Abnormal left axillary lymph nodes are highly suspicious of metastatic disease. + +MR evaluation of extent of disease is recommended. + +ASSESSMENT AND RECOMMENDATIONS: +ACR BI-RADS Category: +5: (Breast Imaging Left) Highly suggestive for malignancy +RECOMMENDATION:Ultrasound guided core biopsy +OVERALL ASSESSMENT: +5 - Highly suggestive for malignancy \ No newline at end of file diff --git a/dphe-stream-nginx/integration-test/patientX/patientX_doc2_SP.txt b/dphe-stream-nginx/integration-test/patientX/patientX_doc2_SP.txt new file mode 100644 index 0000000..eafd6f3 --- /dev/null +++ b/dphe-stream-nginx/integration-test/patientX/patientX_doc2_SP.txt @@ -0,0 +1,89 @@ +=================================================================== +Report ID.....................2,doc2 +Patient ID....................pt123456789 +Patient Name..................PatientX +Principal Date................20100130 1215 +Record Type...................SP +=================================================================== +[Report de-identified (Limited dataset compliant) by De-ID v.6.24.5.1] + + +FINAL DIAGNOSIS: +PART 1: BREAST, LEFT, MODIFIED RADICAL MASTECTOMY +A. INVASIVE DUCTAL CARCINOMA IN UPPER OUTER QUADRANT, 1.3 CM IN +GREATEST DIMENSION ASSOCIATED WITH MICROCALCIFICATIONS. +B. NOTTINGHAM SCORE 8/9 (TUBULES 2, NUCLEAR GRADE 3, MITOTIC RATE 3) +NOTTINGHAM GRADE 3. +C. NO DEFINITE LYMPHOVASCULAR INVASION IDENTIFIED. +D. SURGICAL MARGINS ARE NEGATIVE. +E. TUMOR IS ESTROGEN RECEPTOR NEGATIVE, PROGESTERONE RECEPTOR NEGATIVE, +HER-2/NEU NEGATIVE WITH A KI-67 INDEX OF 45%. +F. NO EVIDENCE OF IN-SITU COMPONENT SEEN. +PART 2: AXILLARY LYMPH NODES, LEFT, BIOPSY +A. TWO OUT OF TEN AXILLARY LYMPH NODES POSITIVE FOR METASTATIC +CARCINOMA (2/10). +B. LARGEST METASTATIC TUMOR MEASURES 2.5 CM IN GREATEST DIMENSION. +C. NO EXTRACAPSULAR EXTENSION IS IDENTIFIED. + +COMMENT: +Immunostaining for AE1/AE3 supports the status of the axillary lymph node. + +Pathologist: Person9, M.D. +** Report Electronically Signed Out ** +By Pathologist: Person9, M.D. +1/30/2010 15:21 +My signature is attestation that I have personally reviewed the submitted +material(s) and the final diagnosis reflects that evaluation. + +GROSS DESCRIPTION: +The specimen is received fixed, labeled with the patient's name, initials, +medical record number and "left radical modified breast mastectomy". + +CASE SYNOPSIS: +SYNOPTIC - PRIMARY INVASIVE CARCINOMA OF BREAST +LATERALITY: Left +PROCEDURE: Modified radical mastectomy +LOCATION: Upper outer quadrant +Clock position: 12:30 +SIZE OF TUMOR: Maximum dimension invasive component: 13 mm +MULTICENTRICITY/MULTIFOCALITY OF INVASIVE FOCI: +No +TUMOR AGGREGATE SIZE: Sum of the sizes of multiple invasive tumors: +TUMOR TYPE (invasive component): Ductal adenocarcinoma +NOTTINGHAM SCORE: 8 Nuclear grade: 3 +Tubule formation: 2 +Mitotic activity score: 3 +Nottingham grade (1, 2, 3): 3 +ANGIOLYMPHATIC INVASION: No +DERMAL LYMPHATIC INVASION: No +CALCIFICATION: Yes +TUMOR TYPE, IN SITU: Not present +Percent of tumor occupied by in situ component: 0 % +SURGICAL MARGINS INVOLVED BY INVASIVE COMPONENT: +No +Distance of invasive tumor to closest margin: 10 mm +SURG MARGINS INVOLVED BY IN SITU COMPONENT: +No +Distance of in situ disease to closest margin: +PAGET's DISEASE OF NIPPLE: No +LYMPH NODES POSITIVE: 2 +LYMPH NODES EXAMINED: 10 +METHOD(S) OF LYMPH NODE EXAMINATION: +H/E stain +ONLY KERATIN POSITIVE CELLS ARE PRESENT: +No +SIZE OF NODAL METASTASES: Diameter of largest lymph node metastasis: 15 mm +LYMPH NODE METASTASIS(-ES) WITH EXTRACAPSULAR EXTENSION: +No +METASTASES TO IPSILATERAL INTERNAL MAMMARY LYMPH NODE (IF APPLICABLE): +No +SKIN INVOLVED (ULCERATION): No +NON-NEOPLASTIC BREAST TISSUE: ADH, FCD +T STAGE, PATHOLOGIC: pT1c +N STAGE, PATHOLOGIC: pN1a +M STAGE: Not applicable +ESTROGEN RECEPTORS: negative, H-score: 0 +PROGESTERONE RECEPTORS: negative, H-score: 0 +HER2/NEU: negative, 0 +HER2/NEU (FISH): Not applicable +-------------------------------------------------------- diff --git a/dphe-stream-nginx/integration-test/patientX/patientX_doc3_NOTE.txt b/dphe-stream-nginx/integration-test/patientX/patientX_doc3_NOTE.txt new file mode 100644 index 0000000..37d4d8b --- /dev/null +++ b/dphe-stream-nginx/integration-test/patientX/patientX_doc3_NOTE.txt @@ -0,0 +1,29 @@ +=================================================================== +Report ID.....................3,doc3 +Patient ID....................pt123456789 +Patient Name..................PatientX +Principal Date................20101202 +Record Type...................NOTE +=================================================================== +[Report de-identified (Limited dataset compliant) by De-ID v.6.24.5.1] + + +DIAGNOSIS: Stage IIA (T1 N1 M0) infiltrating ductal carcinoma, left breast, +triple negative. + +Therapy completed 9 cycles of weekly Abraxane. + +REASON FOR VISIT: Assess response to neoadjuvant chemotherapy. + +Patient92 returns to the office today for ongoing management of biopsy-proven left breast cancer with axillary lymph node metastasis. +Her initial office visit was on September 30, 2010. +Her clinical breast examination at that time was significant for a 2 cm palpable mass in the upper outer aspect of the left breast extending from 12:30 o'clock. +She also had multiple abnormally enlarged left axillary lymph nodes. + +She has now completed 9 of a planned 12 cycles of weekly Abraxane. +She has tolerated her chemotherapy overall without significant sequela. +She denies any hospitalizations. + +Her past medical history, surgical history, medications, and allergies were reviewed as noted in the electronic medical record. + +IMPRESSION: Partial response to neoadjuvant chemotherapy for a locally advanced, triple negative, left breast cancer. \ No newline at end of file diff --git a/dphe-stream-nginx/integration-test/requirements.txt b/dphe-stream-nginx/integration-test/requirements.txt new file mode 100644 index 0000000..d5c2bc9 --- /dev/null +++ b/dphe-stream-nginx/integration-test/requirements.txt @@ -0,0 +1 @@ +requests>=2.22.0 diff --git a/dphe-stream-nginx/integration-test/test.cfg b/dphe-stream-nginx/integration-test/test.cfg new file mode 100644 index 0000000..e62757b --- /dev/null +++ b/dphe-stream-nginx/integration-test/test.cfg @@ -0,0 +1,4 @@ +[TEST] +AUTH_TOKEN = AbCdEf123456 +BASE_URL = http://localhost:8080/deepphe/ +REPORT = patientX/patientX_doc1_RAD.txt \ No newline at end of file diff --git a/dphe-stream-nginx/integration-test/test.py b/dphe-stream-nginx/integration-test/test.py new file mode 100644 index 0000000..6477aaa --- /dev/null +++ b/dphe-stream-nginx/integration-test/test.py @@ -0,0 +1,145 @@ +import unittest +import requests +import logging +from pathlib import Path +import configparser + +# Set logging fromat and level (default is warning) +# All the API logging is forwarded to the uWSGI server and gets written into the log file `uwsgo-entity-api.log` +# Log rotation is handled via logrotate on the host system with a configuration file +# Do NOT handle log file and rotation via the Python logging to avoid issues with multi-worker processes +logging.basicConfig(format='[%(asctime)s] %(levelname)s in %(module)s: %(message)s', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S') +logger = logging.getLogger(__name__) + +# Load configuration items +config = configparser.ConfigParser() +config.read(Path(__file__).absolute().parent / 'test.cfg') + +user_token = config['TEST']['AUTH_TOKEN'] +# Remove trailing slash / from URL base to avoid "//" caused by config with trailing slash +base_url = config['TEST']['BASE_URL'].strip('/') +report = config['TEST']['REPORT'] + +""" +Create a dict of HTTP Authorization header with Bearer token + +Parameters +---------- +user_token: str + The user's auth token +Returns +------- +dict + The headers dict to be used by requests +""" +def create_request_headers(user_token): + auth_header_name = 'Authorization' + auth_scheme = 'Bearer' + + headers_dict = { + # Don't forget the space between scheme and the token value + auth_header_name: auth_scheme + ' ' + user_token + } + + return headers_dict + + +class TestRestApi(unittest.TestCase): + + def test_summarize_doc(self): + with self.assertRaises(Exception) as context: + broken_function() + + target_url = f'{base_url}/summarizeDoc/doc/doc1' + request_headers = create_request_headers(user_token) + # Add content-type header + request_headers['content-type'] = 'text/plain' + + report_text = (Path(__file__).absolute().parent / report).read_text() + + logger.debug(report_text) + + # HTTP GET + response = requests.get(url = target_url, headers = request_headers, data = report_text) + + result_dict = response.json() + + logger.debug(result_dict) + + expr = ('id' in result_dict) and (result_dict['id'] == 'doc1') + + self.assertTrue(expr, "doc1 summarized") + + + def test_summarize_patient_doc(self): + with self.assertRaises(Exception) as context: + broken_function() + + target_url = f'{base_url}/summarizePatientDoc/patient/patientX/doc/doc1' + request_headers = create_request_headers(user_token) + # Add content-type header + request_headers['content-type'] = 'text/plain' + + report_text = (Path(__file__).absolute().parent / report).read_text() + + logger.debug(report_text) + + # HTTP PUT + response = requests.put(url = target_url, headers = request_headers, data = report_text) + + result_dict = response.json() + + logger.debug(result_dict) + + expr = ('id' in result_dict) and (result_dict['id'] == 'patientX') + + self.assertTrue(expr, "patientX doc1 summarized") + + + def test_queue_patient_doc(self): + with self.assertRaises(Exception) as context: + broken_function() + + target_url = f'{base_url}/queuePatientDoc/patient/patientX/doc/doc1' + request_headers = create_request_headers(user_token) + # Add content-type header + request_headers['content-type'] = 'text/plain' + + report_text = (Path(__file__).absolute().parent / report).read_text() + + logger.debug(report_text) + + # HTTP PUT + response = requests.put(url = target_url, headers = request_headers, data = report_text) + + result_dict = response.json() + + logger.debug(result_dict) + + # {'name': 'Document Queued', 'value': 'Added patinetX doc1 to the Text Processing Queue.'} + expr = ('name' in result_dict) and (result_dict['name'] == 'Document Queued') + + self.assertTrue(expr, "patientX doc1 queued up") + + + def test_summarize_patient(self): + with self.assertRaises(Exception) as context: + broken_function() + + target_url = f'{base_url}/summarizePatient/patient/patientX' + request_headers = create_request_headers(user_token) + + # HTTP GET + response = requests.get(url = target_url, headers = request_headers) + + result_dict = response.json() + + logger.debug(result_dict) + + expr = ('id' in result_dict) and (result_dict['id'] == 'patientX') + + self.assertTrue(expr, "patientX summarized") + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/dphe-stream-nginx/logs/README.md b/dphe-stream-nginx/logs/README.md new file mode 100644 index 0000000..e69de29 diff --git a/dphe-stream-nginx/nginx.conf b/dphe-stream-nginx/nginx.conf new file mode 100644 index 0000000..1833493 --- /dev/null +++ b/dphe-stream-nginx/nginx.conf @@ -0,0 +1,33 @@ +# The only change needed is to comment out the user nginx; line +# to avoid a warning since this directive is only meaningful when Nginx is running as root +# user nginx; +worker_processes 1; + +error_log /var/log/nginx/error.log warn; +pid /var/run/nginx.pid; + + +events { + worker_connections 1024; +} + + +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + + log_format main '$remote_addr - $remote_user [$time_local] "$request" ' + '$status $body_bytes_sent "$http_referer" ' + '"$http_user_agent" "$http_x_forwarded_for"'; + + access_log /var/log/nginx/access.log main; + + sendfile on; + #tcp_nopush on; + + keepalive_timeout 65; + + #gzip on; + + include /etc/nginx/conf.d/*.conf; +} diff --git a/dphe-stream/.dockerignore b/dphe-stream/.dockerignore new file mode 100644 index 0000000..d90d890 --- /dev/null +++ b/dphe-stream/.dockerignore @@ -0,0 +1,11 @@ +**/.git + +**/.gitignore + +**/*.md + +logs + +Dockerfile + +.dockerignore diff --git a/dphe-stream/Dockerfile b/dphe-stream/Dockerfile new file mode 100644 index 0000000..f69b9f6 --- /dev/null +++ b/dphe-stream/Dockerfile @@ -0,0 +1,72 @@ +# Base image +FROM centos:7 + +# Set Maven version to be installed, default to 3.8.2 +ARG MAVEN_VERSION=3.8.2 + +WORKDIR /usr/src/app + +# Copy everything else from host to image +COPY . . + +# Reduce the number of layers in image by minimizing the number of separate RUN commands +# Update packages +# Install unzip, which, Java 8 via yum repository +# Download Maven tar file and install +# Unzip the DeepPhe dependencies source code +# Clean all yum cache +RUN yum update -y && \ + yum install -y unzip which java-1.8.0-openjdk java-1.8.0-openjdk-devel && \ + curl -fsSL https://archive.apache.org/dist/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz | tar xzf - -C /usr/share && \ + mv /usr/share/apache-maven-$MAVEN_VERSION /usr/share/maven && \ + ln -s /usr/share/maven/bin/mvn /usr/bin/mvn && \ + unzip v0.1.0-cr-release.zip && \ + yum clean all + +# Set environment variables for Java and Maven +ENV JAVA_HOME /usr/lib/jvm/java +ENV M2_HOME /usr/share/maven +ENV maven.home $M2_HOME +ENV M2 $M2_HOME/bin +ENV PATH $M2:$PATH + +# Install local dependencies +RUN mvn -f /usr/src/app/v0.1.0-cr-release/dphe-onto-db/pom.xml clean install -DskipTests && \ + mvn -f /usr/src/app/v0.1.0-cr-release/dphe-neo4j/pom.xml clean install -DskipTests && \ + mvn -f /usr/src/app/v0.1.0-cr-release/dphe-core/pom.xml clean install -DskipTests && \ + mvn -f /usr/src/app/v0.1.0-cr-release/dphe-stream/pom.xml clean install -DskipTests + +# Change directory to build the REST API application jar +WORKDIR /usr/src/app/v0.1.0-cr-release/dphe-stream-rest + +# Remove the default application.properties +# Remove the default deepphe.properties +# Replace with new application.properties(use port 8080 instead of 9000) +# Replace with new deepphe.properties(use a different auth token) +# Maven build +# Copy the entrypoint script and make it executible +# Install gosu for de-elevating root to deepphe user +RUN rm -rf src/main/resources/application.properties && \ + rm -rf src/main/resources/deepphe.properties && \ + mv /usr/src/app/application.properties src/main/resources/application.properties && \ + mv /usr/src/app/deepphe.properties src/main/resources/deepphe.properties && \ + mvn clean package -DskipTests && \ + cp /usr/src/app/entrypoint.sh /usr/local/bin/entrypoint.sh && \ + chmod +x /usr/local/bin/entrypoint.sh && \ + curl -o /usr/local/bin/gosu -SL "https://github.com/tianon/gosu/releases/download/1.14/gosu-amd64" && \ + curl -o /usr/local/bin/gosu.asc -SL "https://github.com/tianon/gosu/releases/download/1.14/gosu-amd64.asc" && \ + rm /usr/local/bin/gosu.asc && \ + chmod +x /usr/local/bin/gosu + +# Set an entrypoint +ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] + +# The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime. +# EXPOSE does not make the ports of the container accessible to the host. +# Here use 8080 because in application.properties we use port 8080 +EXPOSE 8080 + +# Start the rest api server on port 8080 running as non-root +# Note: since the current work dir is /usr/src/app/v0.1.0-cr-release/dphe-stream-rest, the logs will be generated here too +# Thus we use /usr/src/app/v0.1.0-cr-release/dphe-stream-rest/logs for the volume mount in docker-compose.yml +CMD ["java", "-jar","-Xmx6G","/usr/src/app/v0.1.0-cr-release/dphe-stream-rest/target/deepphe-stream-rest-0.1.0-cr.jar"] diff --git a/dphe-stream/application.properties b/dphe-stream/application.properties new file mode 100644 index 0000000..9f86dc8 --- /dev/null +++ b/dphe-stream/application.properties @@ -0,0 +1,13 @@ +# APPLICATION SETTINGS (SpringApplication) +spring.main.banner-mode=off +spring.main.allow-bean-definition-overriding=true + +# LOGGING +logging.file.name=logs/dphe-stream.log +logging.level.*=INFO +logging.level.org.springframework.web=INFO + +# EMBEDDED SERVER CONFIGURATION (ServerProperties) +server.port=8080 +server.servlet.session.timeout=60m +server.servlet.context-path=/ diff --git a/dphe-stream/deepphe.properties b/dphe-stream/deepphe.properties new file mode 100644 index 0000000..5d01db0 --- /dev/null +++ b/dphe-stream/deepphe.properties @@ -0,0 +1,2 @@ +# Auth Token +deepphe.auth.token=AbCdEf123456 \ No newline at end of file diff --git a/dphe-stream/entrypoint.sh b/dphe-stream/entrypoint.sh new file mode 100644 index 0000000..f0a83f8 --- /dev/null +++ b/dphe-stream/entrypoint.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +# Pass the HOST_UID and HOST_UID from environment variables specified in the child image docker-compose +HOST_GID=${HOST_GID} +HOST_UID=${HOST_UID} + +echo "Starting dphe-stream container with the same host user UID: $HOST_UID and GID: $HOST_GID" + +# Create a new user with the same host UID to run processes on container +# The Filesystem doesn't really care what the user is called, +# it only cares about the UID attached to that user +# Check if user already exists and don't recreate across container restarts +getent passwd $HOST_UID > /dev/null 2&>1 +# $? is a special variable that captures the exit status of last task +if [ $? -ne 0 ]; then + groupadd -r -g $HOST_GID deepphe + useradd -r -u $HOST_UID -g $HOST_GID -m deepphe +fi + +# Make /usr/src/app accessible +chown -R deepphe:deepphe /usr/src/app + +# Lastly we use gosu to execute our process "$@" as that user +# Remember CMD from a Dockerfile of child image gets passed to the entrypoint.sh as command line arguments +# "$@" is a shell variable that means "all the arguments" +exec /usr/local/bin/gosu deepphe "$@" diff --git a/dphe-stream/logs/README.md b/dphe-stream/logs/README.md new file mode 100644 index 0000000..e69de29