├── .github └── workflows │ ├── codecov.yml │ ├── linter.yml │ └── tests.yml ├── .gitignore ├── .pre-commit-config.yaml ├── Dockerfile ├── LICENSE ├── README.md ├── docker-compose.yml ├── pydfs ├── __init__.py ├── __main__.py ├── arg_parse.py ├── cmd_dfs.py ├── cmd_init.py ├── logger.py ├── master_app.py ├── slave_app.py └── utils.py ├── requirements.txt ├── setup.py ├── tests ├── __init__.py ├── test_info.py ├── test_init.py └── test_utils.py └── wait-for-it.sh /.github/workflows/codecov.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies and run codecov 2 | # https://github.com/codecov/codecov-action#example-workflowyml-with-codecov-action 3 | 4 | name: codecov 5 | 6 | on: 7 | push: 8 | branches: [main, develop] 9 | pull_request: 10 | branches: [main, develop] 11 | 12 | jobs: 13 | build: 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | os: [ubuntu-latest] 18 | steps: 19 | - uses: actions/checkout@master 20 | - name: Set up Python 21 | uses: actions/setup-python@master 22 | with: 23 | python-version: 3.7 24 | - name: Install dependencies 25 | run: | 26 | pip install --upgrade pip 27 | pip install -r requirements.txt 28 | pip install pytest pytest-cov 29 | - name: Generate coverage report 30 | run: pytest --cov=./ --cov-report=xml 31 | - name: Upload coverage to Codecov 32 | uses: codecov/codecov-action@v1 33 | with: 34 | flags: unittests 35 | env_vars: OS,PYTHON 36 | fail_ci_if_error: true 37 | verbose: true 38 | -------------------------------------------------------------------------------- /.github/workflows/linter.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies and run linter 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | # TODO: update linters 5 | 6 | name: linter 7 | 8 | on: 9 | push: 10 | branches: [main, develop] 11 | pull_request: 12 | branches: [main, develop] 13 | 14 | jobs: 15 | build: 16 | runs-on: ${{ matrix.os }} 17 | strategy: 18 | matrix: 19 | os: [ubuntu-latest] 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Set up Python 23 | uses: actions/setup-python@v2 24 | with: 25 | python-version: 3.7 26 | - name: Install dependencies 27 | run: | 28 | pip install --upgrade pip 29 | pip install isort black flake8 mypy 30 | - name: Code format check with isort 31 | run: isort --check-only --profile black . 32 | - name: Code format check with black 33 | run: black --check . 34 | - name: Code format check with flake8 35 | run: flake8 --ignore E501,E203,W503 . 36 | - name: Type check with mypy 37 | run: mypy --ignore-missing-imports . 38 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies and run tests with a variety of Python versions 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: tests 5 | 6 | on: 7 | push: 8 | branches: [main, develop] 9 | pull_request: 10 | branches: [main, develop] 11 | 12 | jobs: 13 | build: 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | python-version: ['3.7', '3.8', '3.9', '3.10'] 18 | os: [ubuntu-latest, macOS-latest] # TODO: add windows-latest 19 | steps: 20 | - uses: actions/checkout@v2 21 | - name: Set up Python 22 | uses: actions/setup-python@v2 23 | with: 24 | python-version: ${{ matrix.python-version }} 25 | - name: Install dependencies 26 | run: | 27 | pip install --upgrade pip 28 | pip install -r requirements.txt 29 | - name: Unittests 30 | run: python -m unittest discover 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | .python-version 3 | *.ipynb 4 | *.ipynb_checkpoints 5 | 6 | *__pycache__ 7 | *.mypy_cache 8 | *.cache 9 | 10 | *.coverage 11 | *coverage.xml 12 | 13 | venv 14 | .idea 15 | 16 | master.sqlite 17 | master.sqlite-journal 18 | 19 | dfspy.egg-info 20 | build/ 21 | dist/ 22 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/mirrors-isort 3 | rev: v5.10.1 4 | hooks: 5 | - id: isort 6 | args: ["--profile", "black"] 7 | - repo: https://github.com/psf/black 8 | rev: 22.3.0 9 | hooks: 10 | - id: black 11 | - repo: https://github.com/pycqa/flake8 12 | rev: 4.0.1 13 | hooks: 14 | - id: flake8 15 | args: ["--ignore", "E501,E203,W503"] 16 | - repo: https://github.com/pre-commit/mirrors-mypy 17 | rev: v0.961 18 | hooks: 19 | - id: mypy 20 | - repo: https://github.com/pre-commit/pre-commit-hooks 21 | rev: v4.3.0 22 | hooks: 23 | - id: check-yaml 24 | - id: name-tests-test 25 | args: ['--django'] 26 | - id: debug-statements 27 | - id: end-of-file-fixer 28 | types: [python] 29 | - id: trailing-whitespace 30 | - id: check-docstring-first 31 | - id: requirements-txt-fixer 32 | # - repo: local 33 | # hooks: 34 | # - id: unittest 35 | # name: unittest 36 | # entry: venv/bin/python -m unittest discover 37 | # language: python 38 | # always_run: true 39 | # pass_filenames: false 40 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.7-slim-buster 2 | LABEL maintainer = "Dani El-Ayyass " 3 | 4 | WORKDIR /workdir 5 | COPY . . 6 | 7 | RUN pip install --no-cache-dir --upgrade pip && \ 8 | pip install --no-cache-dir . 9 | 10 | CMD ["bash"] 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyDFS 2 | Distributed File System written in Python. 3 | 4 | ## Installation 5 | ``` 6 | pip install dfspy 7 | ``` 8 | 9 | ## Usage 10 | PyDFS is Centralized Distributed File System, which means there is a *master* and *slave* nodes. 11 | The current implementation assumes that the system has only one master node and many slave nodes. 12 | 13 | PyDFS supports *command line interface* (*CLI*) to interact with it. 14 | There are 2 groups of the commands (like Docker Management Commands): 15 | - `pydfs init` - to initialize, manage and sync nodes 16 | - `pydfs dfs` - to interact with DFS itself (put/get data to/from it) 17 | 18 | Let's take a closer look at these commands. 19 | 20 | ### init commands 21 | With `pydfs init` command you can initialize master and slave nodes - it's pretty simple: 22 | - `pydfs init master` 23 | - `pydfs init slave --master_ip [IP]` 24 | 25 | ### dfs commands 26 | - `pydfs dfs put --path [PATH] --master_ip [IP]` 27 | - `pydfs dfs get --path [PATH] --master_ip [IP]` 28 | 29 | ### other commands 30 | - `pydfs --version` 31 | - `pydfs --info` 32 | 33 | ### Docker 34 | You can also use *docker-compose* to run multi-container application with: 35 | - 1 master node 36 | - 2 slave nodes 37 | - 2 user nodes 38 | ``` 39 | docker-compose up --build 40 | ``` 41 | 42 | ## Requirements 43 | Python >= 3.7 44 | 45 | ## Citation 46 | If you use **PyDFS** in a scientific publication, we would appreciate references to the following BibTex entry: 47 | ```bibtex 48 | @misc{silkwayai2022pydfs, 49 | author = {Dani El-Ayyass and Artem Fomin}, 50 | title = {Distributed File System written in Python}, 51 | howpublished = {\url{https://github.com/silkway-ai/pydfs}}, 52 | year = {2022} 53 | } 54 | ``` 55 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | 3 | services: 4 | 5 | master_node: 6 | container_name: master_node 7 | build: . 8 | command: pydfs init master 9 | 10 | slave_node_1: 11 | container_name: slave_node_1 12 | build: . 13 | command: | 14 | bash -c " 15 | ./wait-for-it.sh master_node:5000 && 16 | pydfs init slave --master_ip master_node 17 | " 18 | depends_on: 19 | - master_node 20 | 21 | slave_node_2: 22 | container_name: slave_node_2 23 | build: . 24 | command: | 25 | bash -c " 26 | ./wait-for-it.sh master_node:5000 && 27 | pydfs init slave --master_ip master_node 28 | " 29 | depends_on: 30 | - master_node 31 | 32 | user_node_1: 33 | container_name: user_node_1 34 | build: . 35 | command: | 36 | bash -c " 37 | ./wait-for-it.sh master_node:5000 && 38 | ./wait-for-it.sh slave_node_1:5000 && 39 | ./wait-for-it.sh slave_node_2:5000 && 40 | pydfs dfs put --path wait-for-it.sh --master_ip master_node && 41 | tail -f /dev/null 42 | " 43 | depends_on: 44 | - master_node 45 | - slave_node_1 46 | - slave_node_2 47 | 48 | user_node_2: 49 | container_name: user_node_2 50 | build: . 51 | command: | 52 | bash -c " 53 | ./wait-for-it.sh master_node:5000 && 54 | ./wait-for-it.sh slave_node_1:5000 && 55 | ./wait-for-it.sh slave_node_2:5000 && 56 | sleep 2 && 57 | cd / && 58 | pydfs dfs get --path wait-for-it.sh --master_ip master_node && 59 | tail -f /dev/null 60 | " 61 | depends_on: 62 | - master_node 63 | - slave_node_1 64 | - slave_node_2 65 | - user_node_1 66 | -------------------------------------------------------------------------------- /pydfs/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.1.0" 2 | -------------------------------------------------------------------------------- /pydfs/__main__.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | from base64 import b64decode 4 | 5 | from pydfs import __version__ # noqa: E402 6 | from pydfs.arg_parse import get_argparse # noqa: E402 7 | from pydfs.cmd_dfs import cmd_dfs_get_request, cmd_dfs_put_request # noqa: E402 8 | from pydfs.cmd_init import cmd_init_master, cmd_init_slave # noqa: E402 9 | from pydfs.logger import _logger # noqa: E402 10 | 11 | 12 | def main() -> None: 13 | """ 14 | pydfs main function (entry point) 15 | """ 16 | 17 | args = get_argparse().parse_args() 18 | _main(args) 19 | 20 | 21 | def _main(args: argparse.Namespace) -> int: 22 | """ 23 | pydfs main function (entry point) 24 | 25 | Args: 26 | args (argparse.Namespace): CLI arguments. 27 | 28 | Returns: 29 | int: exit code. 30 | """ 31 | 32 | if args.version and (not args.command): 33 | _version() 34 | return 0 35 | 36 | if args.info and (not args.command): 37 | _info() 38 | return 0 39 | 40 | _logger.debug(f"CLI arguments: {args}") 41 | 42 | if args.command == "init": 43 | 44 | if args.subcommand == "master": 45 | _logger.info(f"pydfs init {args.subcommand}") 46 | cmd_init_master() 47 | 48 | elif args.subcommand == "slave": 49 | _logger.info(f"pydfs init {args.subcommand} --master_ip {args.master_ip}") 50 | cmd_init_slave(master_ip=args.master_ip) 51 | 52 | else: 53 | err_msg = f"unknown init subcommand: '{args.subcommand}' (use 'master' or 'slave')" 54 | _logger.error(err_msg) 55 | raise ValueError(err_msg) 56 | 57 | elif args.command == "dfs": 58 | 59 | if args.subcommand == "put": 60 | _logger.info( 61 | f"pydfs dfs put --path {args.path} --master_ip {args.master_ip}" 62 | ) 63 | cmd_dfs_put_request( 64 | ip=args.master_ip, 65 | files={"upload_file": open(args.path, mode="rb")}, 66 | ) 67 | # TODO add error handler 68 | _logger.info(f"putting file {args.path} to pydfs succeeded") 69 | 70 | elif args.subcommand == "get": 71 | _logger.info( 72 | f"pydfs dfs get --path {args.path} --master_ip {args.master_ip}" 73 | ) 74 | response = cmd_dfs_get_request( 75 | ip=args.master_ip, 76 | path=args.path, 77 | ) 78 | 79 | _logger.info(f"slave response on user: {response}") 80 | 81 | file = b64decode(response.json()["download_file"]) 82 | with open(args.path, mode="wb") as fp: 83 | fp.write(file) 84 | 85 | # TODO add error handler 86 | _logger.info(f"getting and saving file {args.path} from pydfs succeeded") 87 | 88 | else: 89 | err_msg = ( 90 | f"unknown dfs subcommand: '{args.subcommand}' (use 'put' or 'get')" 91 | ) 92 | _logger.error(err_msg) 93 | raise ValueError(err_msg) 94 | 95 | else: 96 | err_msg = f"unknown command: '{args.command}' (use 'init' or 'dfs')" 97 | _logger.error(err_msg) 98 | raise ValueError(err_msg) 99 | 100 | return 0 101 | 102 | 103 | def _version() -> None: 104 | """ 105 | pydfs --version 106 | """ 107 | 108 | # TODO: maybe not use print 109 | print(f"v{__version__}") 110 | 111 | 112 | def _info() -> None: 113 | """ 114 | pydfs --info 115 | """ 116 | 117 | path_to_pydfs = os.path.join(os.environ["HOME"], ".pydfs") 118 | path_to_master_db = os.path.join(path_to_pydfs, "master.sqlite") 119 | 120 | # TODO: maybe not use print 121 | # TODO: maybe allow master and slave node at the same time 122 | if os.path.exists(path_to_master_db): 123 | # TODO: add slave nodes info 124 | print("pydfs master node\n") 125 | elif os.path.exists(path_to_pydfs): 126 | # TODO: add master node info 127 | print("pydfs slave node\n") 128 | else: 129 | msg = ( 130 | "not a pydfs node\n" 131 | "init it as a master node with `pydfs init master` or\n" 132 | "init it as a slave node with `pydfs init slave --master_ip [IP]`\n" 133 | ) 134 | print(msg) 135 | 136 | 137 | if __name__ == "__main__": 138 | main() 139 | -------------------------------------------------------------------------------- /pydfs/arg_parse.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | 4 | def get_argparse() -> argparse.ArgumentParser: 5 | """ 6 | Function to get CLI arguments parser. 7 | 8 | Returns: 9 | argparse.ArgumentParser: CLI arguments parser. 10 | """ 11 | 12 | # TODO: add --info argument 13 | # TODO: add login 14 | parser = argparse.ArgumentParser() 15 | parser.add_argument( 16 | "--version", 17 | action="store_true", 18 | help="pydfs version", 19 | ) 20 | parser.add_argument( 21 | "--info", 22 | action="store_true", 23 | help="pydfs node info", 24 | ) 25 | 26 | # https://stackoverflow.com/questions/8250010/argparse-identify-which-subparser-was-used 27 | subparsers = parser.add_subparsers(dest="command") 28 | 29 | # init commands 30 | subparser_init = subparsers.add_parser( 31 | "init", 32 | help="init commands", 33 | ) 34 | subsubparsers_init = subparser_init.add_subparsers(dest="subcommand") 35 | 36 | # init master command 37 | subsubparsers_init.add_parser( 38 | "master", 39 | help="init pydfs master node", 40 | ) 41 | 42 | # init slave command 43 | subsubparser_init_slave = subsubparsers_init.add_parser( 44 | "slave", 45 | help="init pydfs slave node", 46 | ) 47 | subsubparser_init_slave.add_argument( 48 | "--master_ip", 49 | type=str, 50 | required=True, 51 | help="pydfs master node IP", 52 | ) 53 | 54 | # dfs commands 55 | subparser_dfs = subparsers.add_parser( 56 | "dfs", 57 | help="dfs commands", 58 | ) 59 | subsubparsers_dfs = subparser_dfs.add_subparsers(dest="subcommand") 60 | 61 | # dfs put command 62 | subsubparser_dfs_put = subsubparsers_dfs.add_parser( 63 | "put", 64 | help="command to put local file in pydfs", 65 | ) 66 | subsubparser_dfs_put.add_argument( 67 | "--path", 68 | type=str, 69 | required=True, 70 | help="path to local file to put in pydfs", 71 | ) 72 | # TODO: remove master_ip 73 | subsubparser_dfs_put.add_argument( 74 | "--master_ip", 75 | type=str, 76 | required=True, 77 | help="pydfs master node IP", 78 | ) 79 | 80 | # dfs get command 81 | subsubparser_dfs_get = subsubparsers_dfs.add_parser( 82 | "get", 83 | help="command to get pydfs file back to local", 84 | ) 85 | subsubparser_dfs_get.add_argument( 86 | "--path", 87 | type=str, 88 | required=True, 89 | help="path to pydfs file to get it locally", 90 | ) 91 | # TODO: remove master_ip 92 | subsubparser_dfs_get.add_argument( 93 | "--master_ip", 94 | type=str, 95 | required=True, 96 | help="pydfs master node IP", 97 | ) 98 | 99 | return parser 100 | -------------------------------------------------------------------------------- /pydfs/cmd_dfs.py: -------------------------------------------------------------------------------- 1 | import random 2 | from io import BufferedReader 3 | from typing import Dict, List 4 | 5 | import requests # type: ignore 6 | 7 | from pydfs.logger import _logger # noqa: E402 8 | 9 | 10 | def cmd_dfs_put_request(ip: str, files: Dict[str, BufferedReader]): 11 | response = requests.put( # TODO: maybe post 12 | url=f"http://{ip}:5000/put_file", # TODO: add https 13 | files=files, 14 | ) 15 | if response.status_code == 200: 16 | _logger.info(f"sending file {files['upload_file']} to {ip} succeeded") 17 | else: 18 | _logger.error(f"sending file {files['upload_file']} to {ip} failed") 19 | 20 | 21 | def cmd_dfs_get_request(ip: str, path: str): 22 | response = requests.get( 23 | url=f"http://{ip}:5000/get_file", # TODO: add https 24 | params={"path": path}, 25 | ) 26 | if response.status_code == 200: 27 | _logger.info(f"requesting file {path} from {ip} succeeded") 28 | else: # TODO: add error handler 29 | _logger.error(f"requesting file {path} from {ip} failed") 30 | 31 | # TODO: standartize interface with cmd_dfs_get_request 32 | # TODO: error handler 33 | return response 34 | 35 | 36 | # TODO: add type annotation without cycle import 37 | def _choose_slave_node( 38 | slave_nodes: List, 39 | ): 40 | slave_node_tgt = random.choice(slave_nodes) 41 | return slave_node_tgt 42 | -------------------------------------------------------------------------------- /pydfs/cmd_init.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import requests # type: ignore 4 | 5 | from pydfs.logger import _logger # noqa: E402 6 | from pydfs.utils import ping # noqa: E402 7 | 8 | 9 | # TODO: make daemon from it 10 | def cmd_init_master() -> None: 11 | """ 12 | pydfs init master 13 | """ 14 | 15 | _mkdir_pydfs() 16 | 17 | # TODO: maybe move it up 18 | # TODO: validate if import is correct 19 | from pydfs.master_app import app # noqa: E402 20 | 21 | _logger.info("master node initialized successfully") 22 | 23 | # TODO: add WSGI (e.g. gunicorn) 24 | # TODO: remove host="0.0.0.0" 25 | app.run(host="0.0.0.0") 26 | 27 | 28 | # TODO: think how to match existed slave to master 29 | # TODO: check if master and slave are already connected 30 | def cmd_init_slave(master_ip: str) -> None: 31 | """ 32 | pydfs init slave --master_ip ... 33 | 34 | Args: 35 | master_ip (str): pydfs master node IP. 36 | """ 37 | 38 | # TODO: maybe change order 39 | _mkdir_pydfs() 40 | # _ping_master_node(master_ip=master_ip) # TODO: fix with docker-compose 41 | _send_slave_ip_to_master(master_ip=master_ip) 42 | 43 | # TODO: maybe move it up 44 | # TODO: validate if import is correct 45 | from pydfs.slave_app import app # noqa: E402 46 | 47 | _logger.info("slave node initialized successfully") 48 | 49 | # TODO: add WSGI (e.g. gunicorn) 50 | # TODO: remove host="0.0.0.0" 51 | app.run(host="0.0.0.0") 52 | 53 | 54 | def _mkdir_pydfs() -> None: 55 | """ 56 | Create pydfs working directory ~/.pydfs 57 | """ 58 | 59 | path = os.path.join(os.environ["HOME"], ".pydfs") 60 | if not os.path.exists(path): 61 | os.makedirs(path, exist_ok=False) 62 | _logger.info(f"'{path}' folder created") 63 | else: 64 | # TODO: think about workflow (behaviour) 65 | _logger.info(f"'{path}' folder has already been created") 66 | 67 | 68 | # TODO: save pydfs init info, for example master_ip for slave nodes 69 | def _ping_master_node(master_ip: str) -> None: 70 | """ 71 | Function to ping master node by its IP. 72 | 73 | Args: 74 | master_ip (str): pydfs master node IP. 75 | """ 76 | 77 | if ping(master_ip): 78 | _logger.info(f"master node '{master_ip}' was found") 79 | else: 80 | # TODO: make more informative error message 81 | err_msg = f"master node '{master_ip}' was not found" 82 | _logger.error(err_msg) 83 | raise ConnectionError(err_msg) 84 | 85 | 86 | def _send_slave_ip_to_master(master_ip: str) -> None: 87 | """ 88 | Function to sent slave node IP to master node. 89 | 90 | Args: 91 | master_ip (str): pydfs master node IP. 92 | """ 93 | 94 | # TODO: add https 95 | # TODO: remove port hardcode (parametrize) 96 | # TODO: maybe post request, not put 97 | # TODO: send local api for validation 98 | response = requests.put( 99 | f"http://{master_ip}:5000/add_slave", 100 | data={}, # TODO: validate 101 | ) 102 | 103 | if response.status_code == 200: 104 | _logger.info("successfully send ip to master") 105 | else: 106 | try: # TODO: fix try/except block 107 | _logger.debug(f"response json keys: {response.json().keys()}") 108 | err_msg = f"HTTP {response.status_code}: {response.json()['message']}" 109 | except: # noqa: E722 110 | _logger.debug("response doesn't have json in it") 111 | err_msg = f"HTTP {response.status_code}" 112 | 113 | # TODO: maybe warning, not error 114 | _logger.error(f"{err_msg}: slave node was NOT initialized successfully") 115 | raise requests.HTTPError(err_msg) 116 | -------------------------------------------------------------------------------- /pydfs/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | 4 | # https://stackoverflow.com/questions/14058453/making-python-loggers-output-all-messages-to-stdout-in-addition-to-log-file 5 | _logger = logging.getLogger() 6 | _logger.setLevel(logging.DEBUG) 7 | 8 | handler = logging.StreamHandler(sys.stdout) 9 | handler.setLevel(logging.DEBUG) 10 | formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") 11 | handler.setFormatter(formatter) 12 | _logger.addHandler(handler) 13 | -------------------------------------------------------------------------------- /pydfs/master_app.py: -------------------------------------------------------------------------------- 1 | import os 2 | from datetime import datetime 3 | 4 | from flask import Flask, request 5 | from flask_restful import Api, Resource 6 | from flask_sqlalchemy import SQLAlchemy 7 | 8 | from pydfs.cmd_dfs import ( # noqa: E402 9 | _choose_slave_node, 10 | cmd_dfs_get_request, 11 | cmd_dfs_put_request, 12 | ) 13 | from pydfs.logger import _logger # noqa: E402 14 | 15 | app = Flask(__name__) 16 | api = Api(app) 17 | 18 | # database 19 | # TODO: maybe add successful messages in logger 20 | # TODO: come up with behaviour when db already exists 21 | # TODO: add db admin user with password 22 | # TODO: create normal workflow if slave IP already in db 23 | _logger.info("creating master.sqlite in ~/.pydfs") 24 | uri = f"sqlite:///{os.path.join(os.environ['HOME'], '.pydfs', 'master.sqlite')}" 25 | 26 | app.config["SQLALCHEMY_DATABASE_URI"] = uri 27 | app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False # TODO: validate 28 | db = SQLAlchemy(app) 29 | 30 | 31 | class Slave(db.Model): # type: ignore 32 | 33 | __tablename__ = "slave" # TODO: check the need 34 | # __table_args__ = {"extend_existing": True} # TODO: check it 35 | 36 | id = db.Column(db.Integer, primary_key=True, autoincrement=True) 37 | ip_address = db.Column(db.String(15), unique=True, nullable=False) 38 | timestamp = db.Column(db.String(23), unique=False, nullable=False) 39 | 40 | def __repr__(self): 41 | return f"" 42 | 43 | 44 | _logger.info("creating slave table in master.sqlite") 45 | 46 | 47 | # TODO: link (relation) with Slave table by ip_address 48 | class Files(db.Model): # type: ignore 49 | 50 | __tablename__ = "files" # TODO: check the need 51 | # __table_args__ = {"extend_existing": True} # TODO: check it 52 | 53 | id = db.Column(db.Integer, primary_key=True, autoincrement=True) 54 | # TODO: fix 255 length 55 | filename = db.Column(db.String(255), unique=True, nullable=False) 56 | ip_address = db.Column(db.String(15), unique=True, nullable=False) 57 | timestamp = db.Column(db.String(23), unique=False, nullable=False) 58 | 59 | def __repr__(self): 60 | return f"" 61 | 62 | 63 | _logger.info("creating files table in master.sqlite") 64 | 65 | 66 | db.create_all() 67 | 68 | 69 | class AddSlave(Resource): 70 | def put(self): 71 | # https://stackoverflow.com/questions/3759981/get-ip-address-of-visitors-using-flask-for-python 72 | _logger.info( 73 | f"inserting slave node address {request.remote_addr} in master.sqlite" 74 | ) 75 | 76 | slave = Slave( 77 | ip_address=request.remote_addr, 78 | timestamp=datetime.now().strftime(r"%Y-%m-%d %H:%M:%S.%f")[:-3], 79 | ) 80 | db.session.add(slave) 81 | db.session.commit() 82 | 83 | return {} # TODO: validate 84 | 85 | 86 | class PutFileMaster(Resource): 87 | def put(self): 88 | 89 | _logger.debug(f"request.files: {request.files}") 90 | _logger.debug(f"receive file: {request.files['upload_file']}") 91 | 92 | slave_nodes = Slave.query.all() 93 | _logger.debug(f"available slave nodes: {slave_nodes}") 94 | 95 | slave_node_tgt = _choose_slave_node(slave_nodes=slave_nodes) 96 | _logger.debug(f"chosen slave node: {slave_node_tgt}") 97 | 98 | file = request.files["upload_file"] 99 | 100 | # TODO: add redirect 101 | # TODO: make as a transaction 102 | # https://stackoverflow.com/questions/32460524/post-uploaded-file-using-requests 103 | cmd_dfs_put_request( 104 | ip=slave_node_tgt.ip_address, 105 | files={"upload_file": (file.filename, file.stream, file.mimetype)}, 106 | ) 107 | 108 | # TODO add error handler 109 | file_db = Files( 110 | filename=file.filename, 111 | ip_address=slave_node_tgt.ip_address, 112 | timestamp=datetime.now().strftime(r"%Y-%m-%d %H:%M:%S.%f")[:-3], 113 | ) 114 | db.session.add(file_db) 115 | db.session.commit() 116 | 117 | return {} # TODO: validate 118 | 119 | 120 | class GetFileMaster(Resource): 121 | def get(self): 122 | 123 | _logger.debug(f"request args: {request.args}") 124 | 125 | path = request.args["path"] # TODO: rename filename 126 | _logger.debug(f"request 'path' param: {path}") 127 | 128 | _logger.info(f"getting slave node ip with file: {path}") 129 | files = Files.query.filter_by(filename=path).all() 130 | assert len(files) == 1 # TODO: remove and create good error handler 131 | slave_node_tgt_ip_address = files[0].ip_address 132 | 133 | # TODO: add redirect 134 | # TODO: make as a transaction 135 | # https://stackoverflow.com/questions/32460524/post-uploaded-file-using-requests 136 | response = cmd_dfs_get_request( 137 | ip=slave_node_tgt_ip_address, 138 | path=path, 139 | ) 140 | 141 | _logger.info(f"slave response on master: {response}") 142 | 143 | return response.json() 144 | 145 | 146 | api.add_resource(AddSlave, "/add_slave") 147 | api.add_resource(PutFileMaster, "/put_file") 148 | api.add_resource(GetFileMaster, "/get_file") 149 | -------------------------------------------------------------------------------- /pydfs/slave_app.py: -------------------------------------------------------------------------------- 1 | import os 2 | from base64 import b64encode 3 | 4 | from flask import Flask, jsonify, request 5 | from flask_restful import Api, Resource 6 | from flask_sqlalchemy import SQLAlchemy 7 | 8 | from pydfs.logger import _logger # noqa: E402 9 | 10 | app = Flask(__name__) 11 | api = Api(app) 12 | 13 | # database 14 | # TODO: maybe add successful messages in logger 15 | # TODO: come up with behaviour when db already exists 16 | # TODO: add db admin user with password 17 | # TODO: create normal workflow if slave IP already in db 18 | _logger.info("creating slave.sqlite in ~/.pydfs") 19 | uri = f"sqlite:///{os.path.join(os.environ['HOME'], '.pydfs', 'slave.sqlite')}" 20 | 21 | app.config["SQLALCHEMY_DATABASE_URI"] = uri 22 | app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False # TODO: validate 23 | db = SQLAlchemy(app) 24 | 25 | # TODO: add slave and master file tables 26 | db.create_all() 27 | 28 | 29 | class PutFileSlave(Resource): 30 | def put(self): 31 | 32 | _logger.debug(f"request.files: {request.files}") 33 | _logger.debug(f"receive file: {request.files['upload_file']}") 34 | 35 | request.files["upload_file"].save( 36 | os.path.join( 37 | os.environ["HOME"], 38 | ".pydfs", 39 | request.files["upload_file"].filename, # TODO: validate 40 | ), 41 | ) 42 | 43 | return {} # TODO: validate 44 | 45 | 46 | class GetFileSlave(Resource): 47 | def get(self): 48 | 49 | _logger.debug(f"request args: {request.args}") 50 | 51 | path = request.args["path"] # TODO: rename filename 52 | _logger.debug(f"request 'path' param: {path}") 53 | 54 | full_path = os.path.join( 55 | os.environ["HOME"], 56 | ".pydfs", 57 | path, # TODO: validate 58 | ) 59 | _logger.debug(f"full path: {full_path}") 60 | 61 | # TODO: maybe not b64encode 62 | # TODO: close opened file 63 | return jsonify( 64 | { 65 | "download_file": b64encode(open(full_path, mode="rb").read()).decode( 66 | "utf-8" 67 | ) 68 | } 69 | ) 70 | 71 | 72 | api.add_resource(PutFileSlave, "/put_file") 73 | api.add_resource(GetFileSlave, "/get_file") 74 | -------------------------------------------------------------------------------- /pydfs/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from pydfs.logger import _logger # noqa: E402 4 | 5 | 6 | # TODO: use with IP 7 | # TODO: validate 8 | # TODO: maybe rename hostname 9 | def ping(hostname: str) -> bool: 10 | """ 11 | https://stackoverflow.com/questions/2953462/pinging-servers-in-python 12 | """ 13 | 14 | cmd = f"ping -c 1 {hostname}" 15 | _logger.debug(f"ping command: {cmd}") 16 | 17 | response = os.system(cmd) 18 | _logger.debug(f"ping response code: {response}") 19 | 20 | success = not bool(response) 21 | 22 | return success 23 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | coverage==6.4.1 # dev 2 | flask==2.1.2 3 | flask-restful==0.3.9 4 | flask-sqlalchemy==2.5.1 5 | pre-commit==2.19.0 # dev 6 | requests==2.28.1 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | with open("README.md", mode="r", encoding="utf-8") as fp: 4 | long_description = fp.read() 5 | 6 | 7 | # TODO: add license 8 | setup( 9 | name="dfspy", 10 | version="0.1.0", 11 | description="Distributed File System written in Python", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | author="Dani El-Ayyass, Artem Fomin", 15 | author_email="dayyass@yandex.ru, artfom02@gmail.com", 16 | url="https://github.com/silkway-ai/pydfs", 17 | packages=["pydfs"], 18 | entry_points={"console_scripts": ["pydfs = pydfs.__main__:main"]}, 19 | install_requires=[ 20 | "flask==2.1.2", 21 | "flask-restful==0.3.9", 22 | "flask-sqlalchemy==2.5.1", 23 | "requests==2.28.1", 24 | ], 25 | keywords=[ 26 | "python", 27 | "distributed-systems", 28 | "hadoop", 29 | "filesystem", 30 | "hdfs", 31 | "mapreduce", 32 | ], 33 | ) 34 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dayyass/pydfs/7f3a38fb4a950d58c4d63c2330fc806ae105cd38/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_info.py: -------------------------------------------------------------------------------- 1 | import sys # TODO: remove it 2 | import unittest 3 | 4 | sys.path.append(".") 5 | from pydfs.__main__ import _main # noqa: E402 6 | from pydfs.arg_parse import get_argparse # noqa: E402 7 | 8 | 9 | class TestInfo(unittest.TestCase): 10 | """ 11 | Class for testing pydfs --info and pydfs --version. 12 | """ 13 | 14 | def setUp(self): 15 | # https://stackoverflow.com/questions/18160078/how-do-you-write-tests-for-the-argparse-portion-of-a-python-module 16 | self.parser = get_argparse() 17 | 18 | def test_version(self): 19 | args = self.parser.parse_args(["--version"]) 20 | exit_code = _main(args) 21 | self.assertEqual(exit_code, 0) 22 | 23 | # TODO: test different workflows 24 | def test_info(self): 25 | args = self.parser.parse_args(["--info"]) 26 | exit_code = _main(args) 27 | self.assertEqual(exit_code, 0) 28 | 29 | 30 | if __name__ == "__main__": 31 | unittest.main() 32 | -------------------------------------------------------------------------------- /tests/test_init.py: -------------------------------------------------------------------------------- 1 | import sys # TODO: remove it 2 | import threading 3 | import time 4 | import unittest 5 | 6 | sys.path.append(".") 7 | from pydfs.__main__ import _main # noqa: E402 8 | from pydfs.arg_parse import get_argparse # noqa: E402 9 | 10 | 11 | # TODO: test different workflows 12 | # TODO: maybe use flask-testing 13 | class TestInit(unittest.TestCase): 14 | """ 15 | Class for testing pydfs init commands. 16 | """ 17 | 18 | def setUp(self): 19 | # https://stackoverflow.com/questions/18160078/how-do-you-write-tests-for-the-argparse-portion-of-a-python-module 20 | self.parser = get_argparse() 21 | 22 | # TODO: test different workflows 23 | def test_init_master_and_slave(self): 24 | 25 | # init master 26 | args_master = self.parser.parse_args(["init", "master"]) 27 | 28 | # create a thread that will contain running server 29 | # https://gist.github.com/prschmid/4643738 30 | master_node_thread = threading.Thread( 31 | target=_main, 32 | args=(args_master,), 33 | daemon=True, # TODO: check correctness 34 | ) 35 | master_node_thread.start() 36 | time.sleep(5) # TODO: fix hardcode 37 | 38 | # init slave 39 | args_slave = self.parser.parse_args( 40 | ["init", "slave", "--master_ip", "127.0.0.1"] 41 | ) 42 | exit_code = _main(args_slave) 43 | self.assertEqual(exit_code, 0) 44 | 45 | 46 | if __name__ == "__main__": 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import sys # TODO: remove it 2 | import unittest 3 | 4 | sys.path.append(".") 5 | from pydfs.utils import ping # noqa: E402 6 | 7 | 8 | class TestUtils(unittest.TestCase): 9 | """ 10 | Class for testing utils. 11 | """ 12 | 13 | def test_ping(self): 14 | self.assertTrue(ping("localhost")) 15 | self.assertTrue(ping("127.0.0.1")) 16 | self.assertFalse(ping("127001")) 17 | 18 | 19 | if __name__ == "__main__": 20 | unittest.main() 21 | -------------------------------------------------------------------------------- /wait-for-it.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Use this script to test if a given TCP host/port are available 3 | 4 | # https://stackoverflow.com/questions/52699899/depends-on-doesnt-wait-for-another-service-in-docker-compose-1-22-0 5 | # https://github.com/vishnubob/wait-for-it 6 | 7 | WAITFORIT_cmdname=${0##*/} 8 | 9 | echoerr() { if [[ $WAITFORIT_QUIET -ne 1 ]]; then echo "$@" 1>&2; fi } 10 | 11 | usage() 12 | { 13 | cat << USAGE >&2 14 | Usage: 15 | $WAITFORIT_cmdname host:port [-s] [-t timeout] [-- command args] 16 | -h HOST | --host=HOST Host or IP under test 17 | -p PORT | --port=PORT TCP port under test 18 | Alternatively, you specify the host and port as host:port 19 | -s | --strict Only execute subcommand if the test succeeds 20 | -q | --quiet Don't output any status messages 21 | -t TIMEOUT | --timeout=TIMEOUT 22 | Timeout in seconds, zero for no timeout 23 | -- COMMAND ARGS Execute command with args after the test finishes 24 | USAGE 25 | exit 1 26 | } 27 | 28 | wait_for() 29 | { 30 | if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then 31 | echoerr "$WAITFORIT_cmdname: waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT" 32 | else 33 | echoerr "$WAITFORIT_cmdname: waiting for $WAITFORIT_HOST:$WAITFORIT_PORT without a timeout" 34 | fi 35 | WAITFORIT_start_ts=$(date +%s) 36 | while : 37 | do 38 | if [[ $WAITFORIT_ISBUSY -eq 1 ]]; then 39 | nc -z $WAITFORIT_HOST $WAITFORIT_PORT 40 | WAITFORIT_result=$? 41 | else 42 | (echo -n > /dev/tcp/$WAITFORIT_HOST/$WAITFORIT_PORT) >/dev/null 2>&1 43 | WAITFORIT_result=$? 44 | fi 45 | if [[ $WAITFORIT_result -eq 0 ]]; then 46 | WAITFORIT_end_ts=$(date +%s) 47 | echoerr "$WAITFORIT_cmdname: $WAITFORIT_HOST:$WAITFORIT_PORT is available after $((WAITFORIT_end_ts - WAITFORIT_start_ts)) seconds" 48 | break 49 | fi 50 | sleep 1 51 | done 52 | return $WAITFORIT_result 53 | } 54 | 55 | wait_for_wrapper() 56 | { 57 | # In order to support SIGINT during timeout: http://unix.stackexchange.com/a/57692 58 | if [[ $WAITFORIT_QUIET -eq 1 ]]; then 59 | timeout $WAITFORIT_BUSYTIMEFLAG $WAITFORIT_TIMEOUT $0 --quiet --child --host=$WAITFORIT_HOST --port=$WAITFORIT_PORT --timeout=$WAITFORIT_TIMEOUT & 60 | else 61 | timeout $WAITFORIT_BUSYTIMEFLAG $WAITFORIT_TIMEOUT $0 --child --host=$WAITFORIT_HOST --port=$WAITFORIT_PORT --timeout=$WAITFORIT_TIMEOUT & 62 | fi 63 | WAITFORIT_PID=$! 64 | trap "kill -INT -$WAITFORIT_PID" INT 65 | wait $WAITFORIT_PID 66 | WAITFORIT_RESULT=$? 67 | if [[ $WAITFORIT_RESULT -ne 0 ]]; then 68 | echoerr "$WAITFORIT_cmdname: timeout occurred after waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT" 69 | fi 70 | return $WAITFORIT_RESULT 71 | } 72 | 73 | # process arguments 74 | while [[ $# -gt 0 ]] 75 | do 76 | case "$1" in 77 | *:* ) 78 | WAITFORIT_hostport=(${1//:/ }) 79 | WAITFORIT_HOST=${WAITFORIT_hostport[0]} 80 | WAITFORIT_PORT=${WAITFORIT_hostport[1]} 81 | shift 1 82 | ;; 83 | --child) 84 | WAITFORIT_CHILD=1 85 | shift 1 86 | ;; 87 | -q | --quiet) 88 | WAITFORIT_QUIET=1 89 | shift 1 90 | ;; 91 | -s | --strict) 92 | WAITFORIT_STRICT=1 93 | shift 1 94 | ;; 95 | -h) 96 | WAITFORIT_HOST="$2" 97 | if [[ $WAITFORIT_HOST == "" ]]; then break; fi 98 | shift 2 99 | ;; 100 | --host=*) 101 | WAITFORIT_HOST="${1#*=}" 102 | shift 1 103 | ;; 104 | -p) 105 | WAITFORIT_PORT="$2" 106 | if [[ $WAITFORIT_PORT == "" ]]; then break; fi 107 | shift 2 108 | ;; 109 | --port=*) 110 | WAITFORIT_PORT="${1#*=}" 111 | shift 1 112 | ;; 113 | -t) 114 | WAITFORIT_TIMEOUT="$2" 115 | if [[ $WAITFORIT_TIMEOUT == "" ]]; then break; fi 116 | shift 2 117 | ;; 118 | --timeout=*) 119 | WAITFORIT_TIMEOUT="${1#*=}" 120 | shift 1 121 | ;; 122 | --) 123 | shift 124 | WAITFORIT_CLI=("$@") 125 | break 126 | ;; 127 | --help) 128 | usage 129 | ;; 130 | *) 131 | echoerr "Unknown argument: $1" 132 | usage 133 | ;; 134 | esac 135 | done 136 | 137 | if [[ "$WAITFORIT_HOST" == "" || "$WAITFORIT_PORT" == "" ]]; then 138 | echoerr "Error: you need to provide a host and port to test." 139 | usage 140 | fi 141 | 142 | WAITFORIT_TIMEOUT=${WAITFORIT_TIMEOUT:-15} 143 | WAITFORIT_STRICT=${WAITFORIT_STRICT:-0} 144 | WAITFORIT_CHILD=${WAITFORIT_CHILD:-0} 145 | WAITFORIT_QUIET=${WAITFORIT_QUIET:-0} 146 | 147 | # Check to see if timeout is from busybox? 148 | WAITFORIT_TIMEOUT_PATH=$(type -p timeout) 149 | WAITFORIT_TIMEOUT_PATH=$(realpath $WAITFORIT_TIMEOUT_PATH 2>/dev/null || readlink -f $WAITFORIT_TIMEOUT_PATH) 150 | 151 | WAITFORIT_BUSYTIMEFLAG="" 152 | if [[ $WAITFORIT_TIMEOUT_PATH =~ "busybox" ]]; then 153 | WAITFORIT_ISBUSY=1 154 | # Check if busybox timeout uses -t flag 155 | # (recent Alpine versions don't support -t anymore) 156 | if timeout &>/dev/stdout | grep -q -e '-t '; then 157 | WAITFORIT_BUSYTIMEFLAG="-t" 158 | fi 159 | else 160 | WAITFORIT_ISBUSY=0 161 | fi 162 | 163 | if [[ $WAITFORIT_CHILD -gt 0 ]]; then 164 | wait_for 165 | WAITFORIT_RESULT=$? 166 | exit $WAITFORIT_RESULT 167 | else 168 | if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then 169 | wait_for_wrapper 170 | WAITFORIT_RESULT=$? 171 | else 172 | wait_for 173 | WAITFORIT_RESULT=$? 174 | fi 175 | fi 176 | 177 | if [[ $WAITFORIT_CLI != "" ]]; then 178 | if [[ $WAITFORIT_RESULT -ne 0 && $WAITFORIT_STRICT -eq 1 ]]; then 179 | echoerr "$WAITFORIT_cmdname: strict mode, refusing to execute subprocess" 180 | exit $WAITFORIT_RESULT 181 | fi 182 | exec "${WAITFORIT_CLI[@]}" 183 | else 184 | exit $WAITFORIT_RESULT 185 | fi 186 | --------------------------------------------------------------------------------