├── .dockerignore ├── .github ├── release-drafter-config.yml ├── requirements.txt └── workflows │ ├── check-pypi.yml │ ├── platform_builds.yml │ ├── publish-pypi.yml │ ├── release-drafter.yml │ └── tox-tests.yml ├── .gitignore ├── LICENSE ├── README.md ├── build └── reqpacks │ ├── Dockerfile │ ├── build │ ├── build-internal │ ├── dockerfile.tmpl │ ├── requirements.txt │ └── system-setup.py ├── demo └── WriteBehindDemo.gif ├── example-cql.py ├── examples ├── db2 │ ├── README.md │ ├── example.py │ └── requirements.txt ├── mongo │ ├── README.md │ ├── example.py │ └── requirements.txt ├── mssql │ ├── README.md │ ├── example.py │ ├── mssql_init.sql │ ├── requirements.txt │ ├── setupAndcreate_redb.sh │ └── setup_mssql.sh ├── mysql │ ├── README.md │ ├── example.py │ └── requirements.txt ├── postgres │ ├── README.md │ ├── example.py │ └── requirements.txt ├── redis │ ├── README.md │ ├── example-redis-cluster.py │ ├── example-redis-standalone.py │ └── requirements.txt ├── snowflake │ ├── README.md │ ├── example.py │ └── requirements.txt └── sqlite │ ├── README.md │ ├── example.py │ └── requirements.txt ├── pyproject.toml ├── rgsync ├── Connectors │ ├── __init__.py │ ├── cql_connector.py │ ├── mongo_connector.py │ ├── redis_connector.py │ ├── simple_hash_connector.py │ └── sql_connectors.py ├── __init__.py ├── common.py └── redis_gears_write_behind.py ├── sbin ├── db2wait.sh ├── deploy-artifacts ├── setup-gears └── system-setup.py ├── tests ├── __init__.py ├── init-mongo.js ├── test_mongowritebehind.py └── test_sqlwritebehind.py └── tox.ini /.dockerignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | /[0-9]*/ 3 | /venv*/ 4 | /artifacts/ 5 | /pytest/logs/ 6 | /VARIANT 7 | -------------------------------------------------------------------------------- /.github/release-drafter-config.yml: -------------------------------------------------------------------------------- 1 | name-template: 'Version $NEXT_PATCH_VERSION' 2 | tag-template: 'v$NEXT_PATCH_VERSION' 3 | categories: 4 | - title: 'Features' 5 | labels: 6 | - 'feature' 7 | - 'enhancement' 8 | - title: 'Bug Fixes' 9 | labels: 10 | - 'fix' 11 | - 'bugfix' 12 | - 'bug' 13 | - title: 'Maintenance' 14 | label: 'chore' 15 | change-template: '- $TITLE (#$NUMBER)' 16 | exclude-labels: 17 | - 'skip-changelog' 18 | template: | 19 | ## Changes 20 | 21 | $CHANGES 22 | -------------------------------------------------------------------------------- /.github/requirements.txt: -------------------------------------------------------------------------------- 1 | poetry==1.1.9 2 | tox>=3.23.1 3 | tox-poetry==0.4.0 4 | tox-docker==3.0.0 5 | -------------------------------------------------------------------------------- /.github/workflows/check-pypi.yml: -------------------------------------------------------------------------------- 1 | name: Check if required secrets are set to publish to Pypi 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | checksecret: 10 | name: check if PYPI_TOKEN and TESTPYPI_TOKEN are set in github secrets 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Check PYPI_TOKEN 14 | env: 15 | PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }} 16 | run: | 17 | if ${{ env.PYPI_TOKEN == '' }} ; then 18 | echo "PYPI_TOKEN secret is not set" 19 | exit 1 20 | fi 21 | - name: Check TESTPYPI_TOKEN 22 | env: 23 | TESTPYPI_TOKEN: ${{ secrets.TESTPYPI_TOKEN }} 24 | run: | 25 | if ${{ env.TESTPYPI_TOKEN == '' }} ; then 26 | echo "TESTPYPI_TOKEN secret is not set" 27 | exit 1 28 | fi 29 | -------------------------------------------------------------------------------- /.github/workflows/platform_builds.yml: -------------------------------------------------------------------------------- 1 | name: Reqpack builds 2 | on: 3 | push: 4 | branches: 5 | - master 6 | - '[0-9].[0-9]' 7 | 8 | jobs: 9 | 10 | platform-build: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | max-parallel: 10 14 | matrix: 15 | osnick: [bionic, xenial, centos7, rocky8] 16 | steps: 17 | - uses: actions/checkout@v2 18 | - uses: actions/checkout@v2 19 | with: 20 | repository: redislabsmodules/readies 21 | path: deps/readies 22 | - name: dependencies 23 | run: | 24 | ./deps/readies/bin/getpy2 25 | ./sbin/system-setup.py 26 | - name: Platform build ${{matrix.osnick}} 27 | run: | 28 | OSNICK=${{matrix.osnick}} ./build/reqpacks/build 29 | - name: persist 30 | uses: actions/upload-artifact@v3 31 | with: 32 | name: rgsync-${{matrix.osnick}}.zip 33 | path: | 34 | bin/artifacts/*.zip 35 | 36 | deploy-artifacts: 37 | needs: ['platform-build'] 38 | runs-on: ubuntu-latest 39 | steps: 40 | - name: set up s3cmd 41 | uses: s3-actions/s3cmd@v1.2.0 42 | with: 43 | provider: aws 44 | region: us-east-1 45 | access_key: ${{ secrets.AWS_ACCESS_KEY_ID }} 46 | secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} 47 | - name: fetch dependencies 48 | uses: actions/download-artifact@v3 49 | with: 50 | path: artifacts 51 | - name: display downloaded file structure 52 | run: ls -R 53 | working-directory: artifacts 54 | 55 | - name: deploy artifacts to s3 snapshots 56 | working-directory: artifacts 57 | run: | 58 | s3cmd put */*.zip --acl-public s3://redismodules/rgsync/snapshots/ 59 | if: startsWith(github.ref, 'refs/tags/') != true 60 | 61 | - name: deploy artifacts to s3 snapshots 62 | working-directory: artifacts 63 | run: | 64 | s3cmd put */*.zip --acl-public s3://redismodules/rgsync/snapshots/ 65 | if: startsWith(github.ref, 'refs/tags/') -------------------------------------------------------------------------------- /.github/workflows/publish-pypi.yml: -------------------------------------------------------------------------------- 1 | name: Publish Pypi 2 | on: 3 | release: 4 | types: [ published ] 5 | 6 | jobs: 7 | pytest: 8 | name: Publish to PyPi 9 | runs-on: ubuntu-latest 10 | env: 11 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 12 | steps: 13 | - uses: actions/checkout@master 14 | 15 | - name: get version from tag 16 | id: get_version 17 | run: | 18 | realversion="${GITHUB_REF/refs\/tags\//}" 19 | realversion="${realversion//v/}" 20 | echo "::set-output name=VERSION::$realversion" 21 | 22 | - name: Set the version for publishing 23 | uses: ciiiii/toml-editor@1.0.0 24 | with: 25 | file: "pyproject.toml" 26 | key: "tool.poetry.version" 27 | value: "${{ steps.get_version.outputs.VERSION }}" 28 | 29 | - name: Set up Python 3.7 30 | uses: actions/setup-python@v1 31 | with: 32 | python-version: 3.7 33 | 34 | - name: Install Poetry 35 | uses: dschep/install-poetry-action@v1.3 36 | 37 | - name: Cache Poetry virtualenv 38 | uses: actions/cache@v1 39 | id: cache 40 | with: 41 | path: ~/.virtualenvs 42 | key: poetry-${{ hashFiles('**/poetry.lock') }} 43 | restore-keys: | 44 | poetry-${{ hashFiles('**/poetry.lock') }} 45 | 46 | - name: Set Poetry config 47 | run: | 48 | poetry config virtualenvs.in-project false 49 | poetry config virtualenvs.path ~/.virtualenvs 50 | 51 | - name: Install Dependencies 52 | run: poetry install 53 | if: steps.cache.outputs.cache-hit != 'true' 54 | 55 | - name: Publish to PyPI 56 | if: github.event_name == 'release' 57 | run: | 58 | poetry publish -u __token__ -p ${{ secrets.PYPI_TOKEN }} --build 59 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | # branches to consider in the event; optional, defaults to all 6 | branches: 7 | - master 8 | 9 | jobs: 10 | update_release_draft: 11 | runs-on: ubuntu-latest 12 | steps: 13 | # Drafts your next Release notes as Pull Requests are merged into "master" 14 | - uses: release-drafter/release-drafter@v5 15 | with: 16 | # (Optional) specify config name to use, relative to .github/. Default: release-drafter.yml 17 | config-name: release-drafter-config.yml 18 | env: 19 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 20 | -------------------------------------------------------------------------------- /.github/workflows/tox-tests.yml: -------------------------------------------------------------------------------- 1 | name: WriteBehind Tests 2 | on: push 3 | 4 | jobs: 5 | 6 | lint: 7 | name: lint 8 | runs-on: ubuntu-18.04 9 | env: 10 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Set up Python ${{matrix.python-version}} 14 | uses: actions/setup-python@v2 15 | with: 16 | python-version: "3.10" 17 | 18 | - name: Install Dependencies 19 | run: | 20 | pip install --user -r .github/requirements.txt 21 | 22 | - name: Run the linter 23 | run: tox -e linters 24 | 25 | run_tests: 26 | runs-on: ubuntu-latest 27 | strategy: 28 | max-parallel: 15 29 | matrix: 30 | toxenv: [ mongo, mysql, postgres] 31 | python-versions: ['3.6', '3.7', '3.8', '3.9', '3.10'] 32 | env: 33 | ACTIONS_ALLOW_UNSECURE_COMMANDS: true 34 | steps: 35 | - uses: actions/checkout@v2 36 | 37 | - name: Set up Python ${{matrix.python-version}} 38 | uses: actions/setup-python@v2 39 | with: 40 | python-version: ${{matrix.python-version}} 41 | 42 | - name: Install Poetry 43 | uses: snok/install-poetry@v1 44 | with: 45 | version: latest 46 | virtualenvs-in-project: false 47 | virtualenvs-create: true 48 | installer-parallel: true 49 | virtualenvs-path: ~/.virtualenvs 50 | 51 | - name: Cache paths 52 | uses: actions/cache@v2 53 | with: 54 | path: | 55 | .tox 56 | ~/.virtualenvs 57 | ~/.cache/pip 58 | ~/.cache/pypoetry 59 | key: poetry-${{ hashFiles('**/poetry.lock', '**/tox.ini', '**/pyproject.toml') }}-${{ matrix.toxenv }} 60 | restore-keys: | 61 | poetry-${{ hashFiles('**/poetry.lock', '**/tox.ini', '**/pyproject.toml') }}-${{ matrix.toxenv }} 62 | 63 | - name: Install Dependencies 64 | run: | 65 | pip install --user -r .github/requirements.txt 66 | 67 | - name: run ${{ matrix.toxenv }} tests 68 | run: | 69 | tox -e ${{ matrix.toxenv }} 70 | 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | /deps/readies/ 3 | /[0-9]*/ 4 | /build/reqpacks/env 5 | /build/reqpacks/requirements.final 6 | 7 | # Byte-compiled / optimized / DLL files 8 | __pycache__/ 9 | *.py[cod] 10 | *$py.class 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | /build/bdist.linux-x86_64/ 18 | /build/lib/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | wheels/ 30 | pip-wheel-metadata/ 31 | share/python-wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .nox/ 51 | .coverage 52 | .coverage.* 53 | .cache 54 | nosetests.xml 55 | coverage.xml 56 | *.cover 57 | *.py,cover 58 | .hypothesis/ 59 | .pytest_cache/ 60 | 61 | # Translations 62 | *.mo 63 | *.pot 64 | 65 | # Django stuff: 66 | *.log 67 | local_settings.py 68 | db.sqlite3 69 | db.sqlite3-journal 70 | 71 | # Flask stuff: 72 | instance/ 73 | .webassets-cache 74 | 75 | # Scrapy stuff: 76 | .scrapy 77 | 78 | # Sphinx documentation 79 | docs/_build/ 80 | 81 | # PyBuilder 82 | target/ 83 | 84 | # Jupyter Notebook 85 | .ipynb_checkpoints 86 | 87 | # IPython 88 | profile_default/ 89 | ipython_config.py 90 | 91 | # pyenv 92 | .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 102 | __pypackages__/ 103 | 104 | # Celery stuff 105 | celerybeat-schedule 106 | celerybeat.pid 107 | 108 | # SageMath parsed files 109 | *.sage.py 110 | 111 | # Environments 112 | .env 113 | .venv 114 | env/ 115 | venv/ 116 | ENV/ 117 | env.bak/ 118 | venv.bak/ 119 | 120 | # Spyder project settings 121 | .spyderproject 122 | .spyproject 123 | 124 | # Rope project settings 125 | .ropeproject 126 | 127 | # mkdocs documentation 128 | /site 129 | 130 | # mypy 131 | .mypy_cache/ 132 | .dmypy.json 133 | dmypy.json 134 | 135 | # Pyre type checker 136 | .pyre/ 137 | 138 | # Eclipse 139 | .project 140 | .pydevproject 141 | 142 | # redis 143 | *.rdb 144 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Server Side Public License 2 | VERSION 1, OCTOBER 16, 2018 3 | 4 | Copyright © 2022 Redis, Inc. 5 | 6 | Everyone is permitted to copy and distribute verbatim copies of this 7 | license document, but changing it is not allowed. 8 | 9 | TERMS AND CONDITIONS 10 | 11 | 0. Definitions. 12 | 13 | “This License” refers to Server Side Public License. 14 | 15 | “Copyright” also means copyright-like laws that apply to other kinds of 16 | works, such as semiconductor masks. 17 | 18 | “The Program” refers to any copyrightable work licensed under this 19 | License. Each licensee is addressed as “you”. “Licensees” and 20 | “recipients” may be individuals or organizations. 21 | 22 | To “modify” a work means to copy from or adapt all or part of the work in 23 | a fashion requiring copyright permission, other than the making of an 24 | exact copy. The resulting work is called a “modified version” of the 25 | earlier work or a work “based on” the earlier work. 26 | 27 | A “covered work” means either the unmodified Program or a work based on 28 | the Program. 29 | 30 | To “propagate” a work means to do anything with it that, without 31 | permission, would make you directly or secondarily liable for 32 | infringement under applicable copyright law, except executing it on a 33 | computer or modifying a private copy. Propagation includes copying, 34 | distribution (with or without modification), making available to the 35 | public, and in some countries other activities as well. 36 | 37 | To “convey” a work means any kind of propagation that enables other 38 | parties to make or receive copies. Mere interaction with a user through a 39 | computer network, with no transfer of a copy, is not conveying. 40 | 41 | An interactive user interface displays “Appropriate Legal Notices” to the 42 | extent that it includes a convenient and prominently visible feature that 43 | (1) displays an appropriate copyright notice, and (2) tells the user that 44 | there is no warranty for the work (except to the extent that warranties 45 | are provided), that licensees may convey the work under this License, and 46 | how to view a copy of this License. If the interface presents a list of 47 | user commands or options, such as a menu, a prominent item in the list 48 | meets this criterion. 49 | 50 | 1. Source Code. 51 | 52 | The “source code” for a work means the preferred form of the work for 53 | making modifications to it. “Object code” means any non-source form of a 54 | work. 55 | 56 | A “Standard Interface” means an interface that either is an official 57 | standard defined by a recognized standards body, or, in the case of 58 | interfaces specified for a particular programming language, one that is 59 | widely used among developers working in that language. The “System 60 | Libraries” of an executable work include anything, other than the work as 61 | a whole, that (a) is included in the normal form of packaging a Major 62 | Component, but which is not part of that Major Component, and (b) serves 63 | only to enable use of the work with that Major Component, or to implement 64 | a Standard Interface for which an implementation is available to the 65 | public in source code form. A “Major Component”, in this context, means a 66 | major essential component (kernel, window system, and so on) of the 67 | specific operating system (if any) on which the executable work runs, or 68 | a compiler used to produce the work, or an object code interpreter used 69 | to run it. 70 | 71 | The “Corresponding Source” for a work in object code form means all the 72 | source code needed to generate, install, and (for an executable work) run 73 | the object code and to modify the work, including scripts to control 74 | those activities. However, it does not include the work's System 75 | Libraries, or general-purpose tools or generally available free programs 76 | which are used unmodified in performing those activities but which are 77 | not part of the work. For example, Corresponding Source includes 78 | interface definition files associated with source files for the work, and 79 | the source code for shared libraries and dynamically linked subprograms 80 | that the work is specifically designed to require, such as by intimate 81 | data communication or control flow between those subprograms and other 82 | parts of the work. 83 | 84 | The Corresponding Source need not include anything that users can 85 | regenerate automatically from other parts of the Corresponding Source. 86 | 87 | The Corresponding Source for a work in source code form is that same work. 88 | 89 | 2. Basic Permissions. 90 | 91 | All rights granted under this License are granted for the term of 92 | copyright on the Program, and are irrevocable provided the stated 93 | conditions are met. This License explicitly affirms your unlimited 94 | permission to run the unmodified Program, subject to section 13. The 95 | output from running a covered work is covered by this License only if the 96 | output, given its content, constitutes a covered work. This License 97 | acknowledges your rights of fair use or other equivalent, as provided by 98 | copyright law. Subject to section 13, you may make, run and propagate 99 | covered works that you do not convey, without conditions so long as your 100 | license otherwise remains in force. You may convey covered works to 101 | others for the sole purpose of having them make modifications exclusively 102 | for you, or provide you with facilities for running those works, provided 103 | that you comply with the terms of this License in conveying all 104 | material for which you do not control copyright. Those thus making or 105 | running the covered works for you must do so exclusively on your 106 | behalf, under your direction and control, on terms that prohibit them 107 | from making any copies of your copyrighted material outside their 108 | relationship with you. 109 | 110 | Conveying under any other circumstances is permitted solely under the 111 | conditions stated below. Sublicensing is not allowed; section 10 makes it 112 | unnecessary. 113 | 114 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 115 | 116 | No covered work shall be deemed part of an effective technological 117 | measure under any applicable law fulfilling obligations under article 11 118 | of the WIPO copyright treaty adopted on 20 December 1996, or similar laws 119 | prohibiting or restricting circumvention of such measures. 120 | 121 | When you convey a covered work, you waive any legal power to forbid 122 | circumvention of technological measures to the extent such circumvention is 123 | effected by exercising rights under this License with respect to the 124 | covered work, and you disclaim any intention to limit operation or 125 | modification of the work as a means of enforcing, against the work's users, 126 | your or third parties' legal rights to forbid circumvention of 127 | technological measures. 128 | 129 | 4. Conveying Verbatim Copies. 130 | 131 | You may convey verbatim copies of the Program's source code as you 132 | receive it, in any medium, provided that you conspicuously and 133 | appropriately publish on each copy an appropriate copyright notice; keep 134 | intact all notices stating that this License and any non-permissive terms 135 | added in accord with section 7 apply to the code; keep intact all notices 136 | of the absence of any warranty; and give all recipients a copy of this 137 | License along with the Program. You may charge any price or no price for 138 | each copy that you convey, and you may offer support or warranty 139 | protection for a fee. 140 | 141 | 5. Conveying Modified Source Versions. 142 | 143 | You may convey a work based on the Program, or the modifications to 144 | produce it from the Program, in the form of source code under the terms 145 | of section 4, provided that you also meet all of these conditions: 146 | 147 | a) The work must carry prominent notices stating that you modified it, 148 | and giving a relevant date. 149 | 150 | b) The work must carry prominent notices stating that it is released 151 | under this License and any conditions added under section 7. This 152 | requirement modifies the requirement in section 4 to “keep intact all 153 | notices”. 154 | 155 | c) You must license the entire work, as a whole, under this License to 156 | anyone who comes into possession of a copy. This License will therefore 157 | apply, along with any applicable section 7 additional terms, to the 158 | whole of the work, and all its parts, regardless of how they are 159 | packaged. This License gives no permission to license the work in any 160 | other way, but it does not invalidate such permission if you have 161 | separately received it. 162 | 163 | d) If the work has interactive user interfaces, each must display 164 | Appropriate Legal Notices; however, if the Program has interactive 165 | interfaces that do not display Appropriate Legal Notices, your work 166 | need not make them do so. 167 | 168 | A compilation of a covered work with other separate and independent 169 | works, which are not by their nature extensions of the covered work, and 170 | which are not combined with it such as to form a larger program, in or on 171 | a volume of a storage or distribution medium, is called an “aggregate” if 172 | the compilation and its resulting copyright are not used to limit the 173 | access or legal rights of the compilation's users beyond what the 174 | individual works permit. Inclusion of a covered work in an aggregate does 175 | not cause this License to apply to the other parts of the aggregate. 176 | 177 | 6. Conveying Non-Source Forms. 178 | 179 | You may convey a covered work in object code form under the terms of 180 | sections 4 and 5, provided that you also convey the machine-readable 181 | Corresponding Source under the terms of this License, in one of these 182 | ways: 183 | 184 | a) Convey the object code in, or embodied in, a physical product 185 | (including a physical distribution medium), accompanied by the 186 | Corresponding Source fixed on a durable physical medium customarily 187 | used for software interchange. 188 | 189 | b) Convey the object code in, or embodied in, a physical product 190 | (including a physical distribution medium), accompanied by a written 191 | offer, valid for at least three years and valid for as long as you 192 | offer spare parts or customer support for that product model, to give 193 | anyone who possesses the object code either (1) a copy of the 194 | Corresponding Source for all the software in the product that is 195 | covered by this License, on a durable physical medium customarily used 196 | for software interchange, for a price no more than your reasonable cost 197 | of physically performing this conveying of source, or (2) access to 198 | copy the Corresponding Source from a network server at no charge. 199 | 200 | c) Convey individual copies of the object code with a copy of the 201 | written offer to provide the Corresponding Source. This alternative is 202 | allowed only occasionally and noncommercially, and only if you received 203 | the object code with such an offer, in accord with subsection 6b. 204 | 205 | d) Convey the object code by offering access from a designated place 206 | (gratis or for a charge), and offer equivalent access to the 207 | Corresponding Source in the same way through the same place at no 208 | further charge. You need not require recipients to copy the 209 | Corresponding Source along with the object code. If the place to copy 210 | the object code is a network server, the Corresponding Source may be on 211 | a different server (operated by you or a third party) that supports 212 | equivalent copying facilities, provided you maintain clear directions 213 | next to the object code saying where to find the Corresponding Source. 214 | Regardless of what server hosts the Corresponding Source, you remain 215 | obligated to ensure that it is available for as long as needed to 216 | satisfy these requirements. 217 | 218 | e) Convey the object code using peer-to-peer transmission, provided you 219 | inform other peers where the object code and Corresponding Source of 220 | the work are being offered to the general public at no charge under 221 | subsection 6d. 222 | 223 | A separable portion of the object code, whose source code is excluded 224 | from the Corresponding Source as a System Library, need not be included 225 | in conveying the object code work. 226 | 227 | A “User Product” is either (1) a “consumer product”, which means any 228 | tangible personal property which is normally used for personal, family, 229 | or household purposes, or (2) anything designed or sold for incorporation 230 | into a dwelling. In determining whether a product is a consumer product, 231 | doubtful cases shall be resolved in favor of coverage. For a particular 232 | product received by a particular user, “normally used” refers to a 233 | typical or common use of that class of product, regardless of the status 234 | of the particular user or of the way in which the particular user 235 | actually uses, or expects or is expected to use, the product. A product 236 | is a consumer product regardless of whether the product has substantial 237 | commercial, industrial or non-consumer uses, unless such uses represent 238 | the only significant mode of use of the product. 239 | 240 | “Installation Information” for a User Product means any methods, 241 | procedures, authorization keys, or other information required to install 242 | and execute modified versions of a covered work in that User Product from 243 | a modified version of its Corresponding Source. The information must 244 | suffice to ensure that the continued functioning of the modified object 245 | code is in no case prevented or interfered with solely because 246 | modification has been made. 247 | 248 | If you convey an object code work under this section in, or with, or 249 | specifically for use in, a User Product, and the conveying occurs as part 250 | of a transaction in which the right of possession and use of the User 251 | Product is transferred to the recipient in perpetuity or for a fixed term 252 | (regardless of how the transaction is characterized), the Corresponding 253 | Source conveyed under this section must be accompanied by the 254 | Installation Information. But this requirement does not apply if neither 255 | you nor any third party retains the ability to install modified object 256 | code on the User Product (for example, the work has been installed in 257 | ROM). 258 | 259 | The requirement to provide Installation Information does not include a 260 | requirement to continue to provide support service, warranty, or updates 261 | for a work that has been modified or installed by the recipient, or for 262 | the User Product in which it has been modified or installed. Access 263 | to a network may be denied when the modification itself materially 264 | and adversely affects the operation of the network or violates the 265 | rules and protocols for communication across the network. 266 | 267 | Corresponding Source conveyed, and Installation Information provided, in 268 | accord with this section must be in a format that is publicly documented 269 | (and with an implementation available to the public in source code form), 270 | and must require no special password or key for unpacking, reading or 271 | copying. 272 | 273 | 7. Additional Terms. 274 | 275 | “Additional permissions” are terms that supplement the terms of this 276 | License by making exceptions from one or more of its conditions. 277 | Additional permissions that are applicable to the entire Program shall be 278 | treated as though they were included in this License, to the extent that 279 | they are valid under applicable law. If additional permissions apply only 280 | to part of the Program, that part may be used separately under those 281 | permissions, but the entire Program remains governed by this License 282 | without regard to the additional permissions. When you convey a copy of 283 | a covered work, you may at your option remove any additional permissions 284 | from that copy, or from any part of it. (Additional permissions may be 285 | written to require their own removal in certain cases when you modify the 286 | work.) You may place additional permissions on material, added by you to 287 | a covered work, for which you have or can give appropriate copyright 288 | permission. 289 | 290 | Notwithstanding any other provision of this License, for material you add 291 | to a covered work, you may (if authorized by the copyright holders of 292 | that material) supplement the terms of this License with terms: 293 | 294 | a) Disclaiming warranty or limiting liability differently from the 295 | terms of sections 15 and 16 of this License; or 296 | 297 | b) Requiring preservation of specified reasonable legal notices or 298 | author attributions in that material or in the Appropriate Legal 299 | Notices displayed by works containing it; or 300 | 301 | c) Prohibiting misrepresentation of the origin of that material, or 302 | requiring that modified versions of such material be marked in 303 | reasonable ways as different from the original version; or 304 | 305 | d) Limiting the use for publicity purposes of names of licensors or 306 | authors of the material; or 307 | 308 | e) Declining to grant rights under trademark law for use of some trade 309 | names, trademarks, or service marks; or 310 | 311 | f) Requiring indemnification of licensors and authors of that material 312 | by anyone who conveys the material (or modified versions of it) with 313 | contractual assumptions of liability to the recipient, for any 314 | liability that these contractual assumptions directly impose on those 315 | licensors and authors. 316 | 317 | All other non-permissive additional terms are considered “further 318 | restrictions” within the meaning of section 10. If the Program as you 319 | received it, or any part of it, contains a notice stating that it is 320 | governed by this License along with a term that is a further restriction, 321 | you may remove that term. If a license document contains a further 322 | restriction but permits relicensing or conveying under this License, you 323 | may add to a covered work material governed by the terms of that license 324 | document, provided that the further restriction does not survive such 325 | relicensing or conveying. 326 | 327 | If you add terms to a covered work in accord with this section, you must 328 | place, in the relevant source files, a statement of the additional terms 329 | that apply to those files, or a notice indicating where to find the 330 | applicable terms. Additional terms, permissive or non-permissive, may be 331 | stated in the form of a separately written license, or stated as 332 | exceptions; the above requirements apply either way. 333 | 334 | 8. Termination. 335 | 336 | You may not propagate or modify a covered work except as expressly 337 | provided under this License. Any attempt otherwise to propagate or modify 338 | it is void, and will automatically terminate your rights under this 339 | License (including any patent licenses granted under the third paragraph 340 | of section 11). 341 | 342 | However, if you cease all violation of this License, then your license 343 | from a particular copyright holder is reinstated (a) provisionally, 344 | unless and until the copyright holder explicitly and finally terminates 345 | your license, and (b) permanently, if the copyright holder fails to 346 | notify you of the violation by some reasonable means prior to 60 days 347 | after the cessation. 348 | 349 | Moreover, your license from a particular copyright holder is reinstated 350 | permanently if the copyright holder notifies you of the violation by some 351 | reasonable means, this is the first time you have received notice of 352 | violation of this License (for any work) from that copyright holder, and 353 | you cure the violation prior to 30 days after your receipt of the notice. 354 | 355 | Termination of your rights under this section does not terminate the 356 | licenses of parties who have received copies or rights from you under 357 | this License. If your rights have been terminated and not permanently 358 | reinstated, you do not qualify to receive new licenses for the same 359 | material under section 10. 360 | 361 | 9. Acceptance Not Required for Having Copies. 362 | 363 | You are not required to accept this License in order to receive or run a 364 | copy of the Program. Ancillary propagation of a covered work occurring 365 | solely as a consequence of using peer-to-peer transmission to receive a 366 | copy likewise does not require acceptance. However, nothing other than 367 | this License grants you permission to propagate or modify any covered 368 | work. These actions infringe copyright if you do not accept this License. 369 | Therefore, by modifying or propagating a covered work, you indicate your 370 | acceptance of this License to do so. 371 | 372 | 10. Automatic Licensing of Downstream Recipients. 373 | 374 | Each time you convey a covered work, the recipient automatically receives 375 | a license from the original licensors, to run, modify and propagate that 376 | work, subject to this License. You are not responsible for enforcing 377 | compliance by third parties with this License. 378 | 379 | An “entity transaction” is a transaction transferring control of an 380 | organization, or substantially all assets of one, or subdividing an 381 | organization, or merging organizations. If propagation of a covered work 382 | results from an entity transaction, each party to that transaction who 383 | receives a copy of the work also receives whatever licenses to the work 384 | the party's predecessor in interest had or could give under the previous 385 | paragraph, plus a right to possession of the Corresponding Source of the 386 | work from the predecessor in interest, if the predecessor has it or can 387 | get it with reasonable efforts. 388 | 389 | You may not impose any further restrictions on the exercise of the rights 390 | granted or affirmed under this License. For example, you may not impose a 391 | license fee, royalty, or other charge for exercise of rights granted 392 | under this License, and you may not initiate litigation (including a 393 | cross-claim or counterclaim in a lawsuit) alleging that any patent claim 394 | is infringed by making, using, selling, offering for sale, or importing 395 | the Program or any portion of it. 396 | 397 | 11. Patents. 398 | 399 | A “contributor” is a copyright holder who authorizes use under this 400 | License of the Program or a work on which the Program is based. The work 401 | thus licensed is called the contributor's “contributor version”. 402 | 403 | A contributor's “essential patent claims” are all patent claims owned or 404 | controlled by the contributor, whether already acquired or hereafter 405 | acquired, that would be infringed by some manner, permitted by this 406 | License, of making, using, or selling its contributor version, but do not 407 | include claims that would be infringed only as a consequence of further 408 | modification of the contributor version. For purposes of this definition, 409 | “control” includes the right to grant patent sublicenses in a manner 410 | consistent with the requirements of this License. 411 | 412 | Each contributor grants you a non-exclusive, worldwide, royalty-free 413 | patent license under the contributor's essential patent claims, to make, 414 | use, sell, offer for sale, import and otherwise run, modify and propagate 415 | the contents of its contributor version. 416 | 417 | In the following three paragraphs, a “patent license” is any express 418 | agreement or commitment, however denominated, not to enforce a patent 419 | (such as an express permission to practice a patent or covenant not to 420 | sue for patent infringement). To “grant” such a patent license to a party 421 | means to make such an agreement or commitment not to enforce a patent 422 | against the party. 423 | 424 | If you convey a covered work, knowingly relying on a patent license, and 425 | the Corresponding Source of the work is not available for anyone to copy, 426 | free of charge and under the terms of this License, through a publicly 427 | available network server or other readily accessible means, then you must 428 | either (1) cause the Corresponding Source to be so available, or (2) 429 | arrange to deprive yourself of the benefit of the patent license for this 430 | particular work, or (3) arrange, in a manner consistent with the 431 | requirements of this License, to extend the patent license to downstream 432 | recipients. “Knowingly relying” means you have actual knowledge that, but 433 | for the patent license, your conveying the covered work in a country, or 434 | your recipient's use of the covered work in a country, would infringe 435 | one or more identifiable patents in that country that you have reason 436 | to believe are valid. 437 | 438 | If, pursuant to or in connection with a single transaction or 439 | arrangement, you convey, or propagate by procuring conveyance of, a 440 | covered work, and grant a patent license to some of the parties receiving 441 | the covered work authorizing them to use, propagate, modify or convey a 442 | specific copy of the covered work, then the patent license you grant is 443 | automatically extended to all recipients of the covered work and works 444 | based on it. 445 | 446 | A patent license is “discriminatory” if it does not include within the 447 | scope of its coverage, prohibits the exercise of, or is conditioned on 448 | the non-exercise of one or more of the rights that are specifically 449 | granted under this License. You may not convey a covered work if you are 450 | a party to an arrangement with a third party that is in the business of 451 | distributing software, under which you make payment to the third party 452 | based on the extent of your activity of conveying the work, and under 453 | which the third party grants, to any of the parties who would receive the 454 | covered work from you, a discriminatory patent license (a) in connection 455 | with copies of the covered work conveyed by you (or copies made from 456 | those copies), or (b) primarily for and in connection with specific 457 | products or compilations that contain the covered work, unless you 458 | entered into that arrangement, or that patent license was granted, prior 459 | to 28 March 2007. 460 | 461 | Nothing in this License shall be construed as excluding or limiting any 462 | implied license or other defenses to infringement that may otherwise be 463 | available to you under applicable patent law. 464 | 465 | 12. No Surrender of Others' Freedom. 466 | 467 | If conditions are imposed on you (whether by court order, agreement or 468 | otherwise) that contradict the conditions of this License, they do not 469 | excuse you from the conditions of this License. If you cannot use, 470 | propagate or convey a covered work so as to satisfy simultaneously your 471 | obligations under this License and any other pertinent obligations, then 472 | as a consequence you may not use, propagate or convey it at all. For 473 | example, if you agree to terms that obligate you to collect a royalty for 474 | further conveying from those to whom you convey the Program, the only way 475 | you could satisfy both those terms and this License would be to refrain 476 | entirely from conveying the Program. 477 | 478 | 13. Offering the Program as a Service. 479 | 480 | If you make the functionality of the Program or a modified version 481 | available to third parties as a service, you must make the Service Source 482 | Code available via network download to everyone at no charge, under the 483 | terms of this License. Making the functionality of the Program or 484 | modified version available to third parties as a service includes, 485 | without limitation, enabling third parties to interact with the 486 | functionality of the Program or modified version remotely through a 487 | computer network, offering a service the value of which entirely or 488 | primarily derives from the value of the Program or modified version, or 489 | offering a service that accomplishes for users the primary purpose of the 490 | Program or modified version. 491 | 492 | “Service Source Code” means the Corresponding Source for the Program or 493 | the modified version, and the Corresponding Source for all programs that 494 | you use to make the Program or modified version available as a service, 495 | including, without limitation, management software, user interfaces, 496 | application program interfaces, automation software, monitoring software, 497 | backup software, storage software and hosting software, all such that a 498 | user could run an instance of the service using the Service Source Code 499 | you make available. 500 | 501 | 14. Revised Versions of this License. 502 | 503 | Redis, Inc. may publish revised and/or new versions of the Server Side 504 | Public License from time to time. Such new versions will be similar in 505 | spirit to the present version, but may differ in detail to address new 506 | problems or concerns. 507 | 508 | Each version is given a distinguishing version number. If the Program 509 | specifies that a certain numbered version of the Server Side Public 510 | License “or any later version” applies to it, you have the option of 511 | following the terms and conditions either of that numbered version or of 512 | any later version published by Redis, Inc. If the Program does not 513 | specify a version number of the Server Side Public License, you may 514 | choose any version ever published by Redis, Inc. 515 | 516 | If the Program specifies that a proxy can decide which future versions of 517 | the Server Side Public License can be used, that proxy's public statement 518 | of acceptance of a version permanently authorizes you to choose that 519 | version for the Program. 520 | 521 | Later license versions may give you additional or different permissions. 522 | However, no additional obligations are imposed on any author or copyright 523 | holder as a result of your choosing to follow a later version. 524 | 525 | 15. Disclaimer of Warranty. 526 | 527 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 528 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 529 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY 530 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 531 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 532 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 533 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 534 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 535 | 536 | 16. Limitation of Liability. 537 | 538 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 539 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 540 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING 541 | ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF 542 | THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO 543 | LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU 544 | OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 545 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 546 | POSSIBILITY OF SUCH DAMAGES. 547 | 548 | 17. Interpretation of Sections 15 and 16. 549 | 550 | If the disclaimer of warranty and limitation of liability provided above 551 | cannot be given local legal effect according to their terms, reviewing 552 | courts shall apply local law that most closely approximates an absolute 553 | waiver of all civil liability in connection with the Program, unless a 554 | warranty or assumption of liability accompanies a copy of the Program in 555 | return for a fee. 556 | 557 | END OF TERMS AND CONDITIONS 558 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![license](https://img.shields.io/github/license/RedisGears/rgsync.svg)](https://github.com/RedisGears/rgsync) 2 | ![GitHub Actions](https://github.com/redisgears/rgsync/actions/workflows/tox-tests.yml/badge.svg) 3 | [![PyPI version](https://badge.fury.io/py/rgsync.svg)](https://badge.fury.io/py/rgsync) 4 | [![Known Vulnerabilities](https://snyk.io/test/github/RedisGears/rgsync/badge.svg?targetFile=requirements.txt)](https://snyk.io/test/github/RedisGears/rgsync?targetFile=requirements.txt) 5 | 6 | 7 | # RGSync 8 | [![Forum](https://img.shields.io/badge/Forum-RedisGears-blue)](https://forum.redislabs.com/c/modules/redisgears) 9 | [![Discord](https://img.shields.io/discord/697882427875393627?style=flat-square)](https://discord.gg/6yaVTtp) 10 | 11 | A _Write Behind_ and _Write Through_ Recipe for [RedisGears](https://github.com/RedisGears/RedisGears) 12 | 13 | ## Demo 14 | ![WriteBehind demo](demo/WriteBehindDemo.gif) 15 | 16 | ## Example 17 | The following is a RedisGears recipe that shows how to use the _Write Behind_ pattern to map data from Redis Hashes to MySQL tables. The recipe maps all Redis Hashes with the prefix `person:` to the MySQL table `persons`, with `` being the primary key and mapped to the `person_id` column. Similarly, it maps all Hashes with the prefix `car:` to the `cars` table. 18 | 19 | ```python 20 | from rgsync import RGWriteBehind, RGWriteThrough 21 | from rgsync.Connectors import MySqlConnector, MySqlConnection 22 | 23 | ''' 24 | Create MySQL connection object 25 | ''' 26 | connection = MySqlConnection('demouser', 'Password123!', 'localhost:3306/test') 27 | 28 | ''' 29 | Create MySQL persons connector 30 | ''' 31 | personsConnector = MySqlConnector(connection, 'persons', 'person_id') 32 | 33 | personsMappings = { 34 | 'first_name':'first', 35 | 'last_name':'last', 36 | 'age':'age' 37 | } 38 | 39 | RGWriteBehind(GB, keysPrefix='person', mappings=personsMappings, connector=personsConnector, name='PersonsWriteBehind', version='99.99.99') 40 | 41 | ''' 42 | Create MySQL cars connector 43 | ''' 44 | carsConnector = MySqlConnector(connection, 'cars', 'car_id') 45 | 46 | carsMappings = { 47 | 'id':'id', 48 | 'color':'color' 49 | } 50 | 51 | RGWriteBehind(GB, keysPrefix='car', mappings=carsMappings, connector=carsConnector, name='CarsWriteBehind', version='99.99.99') 52 | ``` 53 | 54 | ## Running the recipe 55 | You can use [this utility](https://github.com/RedisGears/gears-cli) to send a RedisGears recipe for execution. For example, run this repository's [example.py recipe](examples/mysql/example.py) and install its dependencies with the following command: 56 | 57 | ```bash 58 | gears-cli --host --port --password run example.py REQUIREMENTS rgsync PyMySQL cryptography 59 | ``` 60 | 61 | ## Overview of the recipe's operation 62 | The [`RGWriteBehind()` class](rgsync/redis_gears_write_behind.py) implements the _Write Behind_ recipe, that mainly consists of two RedisGears functions and operates as follows: 63 | 1. A write operation to a Redis Hash key triggers the execution of a RedisGears function. 64 | 1. That RedisGears function reads the data from the Hash and writes into a Redis Stream. 65 | 1. Another RedisGears function is executed asynchronously in the background and writes the changes to the target database. 66 | 67 | ### The motivation for using a Redis Stream 68 | The use of a Redis Stream in the _Write Behind_ recipe implementation is to ensure the persistence of captured changes while mitigating the performance penalty associated with shipping them to the target database. 69 | 70 | The recipe's first RedisGears function is registered to run synchronously, which means that the function runs in the same main Redis thread in which the command was executed. This mode of execution is needed so changes events are recorded in order and to eliminate the possibility of losing events in case of failure. 71 | 72 | Applying the changes to the target database is usually much slower, effectively excluding the possibility of doing that in the main thread. The second RedisGears function is executed asynchronously on batches and in intervals to do that. 73 | 74 | The Redis Stream is the channel through which both of the recipe's parts communicate, where the changes are persisted in order synchronously and are later processed in the background asynchronously. 75 | 76 | ## Controlling what gets replicated 77 | Sometimes you want to modify the data in Redis without replicating it to the target. For that purpose, the recipe can be customized by adding the special field `#` to your Hash's fields and setting it to one of these values: 78 | * `+` - Adds the data but does not replicate it to the target 79 | * `=` - Adds the data with and replicates it (the default behavior) 80 | * `-` - Deletes the data but does not replicate 81 | * `~` - Deletes the data from Redis and the target (the default behavior when using `del` command) 82 | 83 | When the Hash's value contains the `#` field, the recipe will act according to its value and will delete the `#` field from the Hash afterward. For example, the following shows how to delete a Hash without replicating the delete operation: 84 | 85 | ``` 86 | redis> HSET person:1 # - 87 | ``` 88 | 89 | Alternatively, to add a Hash without having it replicated: 90 | ``` 91 | redis> HSET person:007 first_name James last_name Bond age 42 # + 92 | ``` 93 | 94 | ## At Least Once and Exactly Once semantics 95 | By default the _Write Behind_ recipe provides the _At Least Once_ property for writes, meaning that data will be written once to the target, but possibly more than that in cases of failure. 96 | 97 | It is possible to have the recipe provide _Exactly Once_ delivery semantics by using the Stream's message ID as an increasing ID of the operations. The writer RedisGears function can use that ID and record it in another table in the target to ensure that any given ID is only be written once. 98 | 99 | All of the recipe's SQL connectors support this capability. To use it, you need to provide the connector with the name of the "exactly once" table. This table should contain 2 columns, the `id` which represents some unique ID of the writer (used to distinguish between shards for example) and `val` which is the last Stream ID written to the target. The "exactly once" table's name can be specified to the connector in the constructor via the optional `exactlyOnceTableName` variable. 100 | 101 | ## Getting write acknowledgment 102 | It is possible to use the recipe and get an acknowledgment of successful writes to the target. Follow these steps to do so: 103 | 1. For each data-changing operation generate a `uuid`. 104 | 2. Add the operation's `uuid` immediately after the value in the special `#` field, that is after the `+`/`=`/`-`/`~` character. Enabling write acknowledgment requires the use of the special `#`. 105 | 3. After performing the operation, perform an `XREAD BLOCK STREAMS {} 0-0`. Once the recipe has written to the target, it will create a message in that (`{}`) Stream that has a single field named 'status' with the value 'done'. 106 | 4. For housekeeping purposes, it is recommended to delete that Stream after getting the acknowledgment. This is not a must, however, as these Streams are created with TTL of one hour. 107 | 108 | ### Acknowledgment example 109 | ``` 110 | 127.0.0.1:6379> hset person:007 first_name James last_name Bond age 42 # =6ce0c902-30c2-4ac9-8342-2f04fb359a94 111 | (integer) 1 112 | 127.0.0.1:6379> XREAD BLOCK 2000 STREAMS {person:1}6ce0c902-30c2-4ac9-8342-2f04fb359a94 0-0 113 | 1) 1) "{person:1}6ce0c902-30c2-4ac9-8342-2f04fb359a94" 114 | 2) 1) 1) "1581927201056-0" 115 | 2) 1) "status" 116 | 2) "done" 117 | ``` 118 | 119 | ## Write Through 120 | _Write Through_ is done by using a temporary key. The recipe registers to changes of that key and writes them to the target. Writing to the target is executed in the Server's main thread, in synchronous mode, which means that the server will be blocked at that time and the client will not get the reply until it is finished. 121 | 122 | Writing the changes to the target may succeed or fail. If successful, the recipe renames the temporary key to its intended final name. A failure will prevent the rename. In either case, the temporary key is deleted. 123 | 124 | The semantics of the acknowledgment Stream remains nearly the same as _Write Behind_. The only change is in the message's structure. Failed writes create a message in that (`{}`) Stream that has: 125 | 126 | * A 'status' field with the value 'failed' 127 | * An 'error' field containing the error's description 128 | 129 | Note that when using _Write Through_ it is mandatory to supply a `uuid` and read the acknowledgment Stream. That is the only way to tell whether the write had succeeded. 130 | 131 | _Write Through_ is registered using the `RGWriteThrough` class: 132 | ```python 133 | RGWriteThrough(GB, keysPrefix, mappings, connector, name, version) 134 | ``` 135 | 136 | The `keysPrefix` argument is the prefix of the key on which the writes will be triggered. The temporary key's name will be in the following format: 137 | ``` 138 | {} 139 | ``` 140 | Upon success, the key is renamed to ``. 141 | 142 | Any failure in writing to the target will cause the recipe to abort. In such cases, the temporary key is not renamed and is deleted. 143 | 144 | Note that in some cases, such as connection failures, it is impossible to tell whether the operation had succeeded or failed on the target. The recipe considers these as failures, although in reality, the write may have succeeded. 145 | 146 | ### Example 147 | These examples assume that the `keysPrefix` is set to "__". The first shows a successful write: 148 | 149 | ``` 150 | 127.0.0.1:6379> HSET __{person:1} first_name foo last_name bar age 20 # =6ce0c902-30c2-4ac9-8342-2f04fb359a94 151 | (integer) 4 152 | 127.0.0.1:6379> XREAD BLOCK 2000 STREAMS {person:1}6ce0c902-30c2-4ac9-8342-2f04fb359a94 0-0 153 | 1) 1) "{person:1}6ce0c902-30c2-4ac9-8342-2f04fb359a94" 154 | 2) 1) 1) "1583321726502-0" 155 | 2) 1) "status" 156 | 2) "done" 157 | 127.0.0.1:6379> HGETALL person:1 158 | 1) "age" 159 | 2) "20" 160 | 3) "last_name" 161 | 4) "bar" 162 | 5) "first_name" 163 | 6) "foo" 164 | ``` 165 | 166 | An a example of a failed _Write Through_: 167 | 168 | ``` 169 | 127.0.0.1:6379> HSET __{person:1} first_name foo last_name bar age 20 # =6ce0c902-30c2-4ac9-8342-2f04fb359a94 170 | (integer) 4 171 | 127.0.0.1:6379> XREAD BLOCK 2000 STREAMS {person:1}6ce0c902-30c2-4ac9-8342-2f04fb359a94 0-0 172 | 1) 1) "{person:1}6ce0c902-30c2-4ac9-8342-2f04fb359a94" 173 | 2) 1) 1) "1583322141455-0" 174 | 2) 1) "status" 175 | 2) "failed" 176 | 3) "error" 177 | 4) "Failed connecting to SQL database, error=\"(pymysql.err.OperationalError) (2003, \"Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)\")\n(Background on this error at: http://sqlalche.me/e/e3q8)\"" 178 | 179 | ``` 180 | 181 | ### Speed Improvements 182 | To improve the speed of write through updates, users should think about adding indexing to their write through database. This index would be created based on the column containing the *redis* key id being replicated. Using the example above, a *person_id* column will be created, regardless of the back-end database chosen for write through. As such, an index on the *person_id* column may be prudent, depending on your data volume and architecture. 183 | 184 | ## Data persistence and availability 185 | To avoid data loss in Redis and the resulting inconsistencies with the target databases, it is recommended to employ and use this recipe only with a highly-available Redis environment. In such environments, the failure of a master node will cause the replica that replaced it to continue the recipe's execution from the point it was stopped. 186 | 187 | Furthermore, Redis' AOF should be used alongside replication to protect against data loss during system-wide failures. 188 | 189 | ## Monitoring the RedisGears function registrations 190 | Use [this](https://github.com/RedisGears/RedisGearsMonitor) to monitor RedisGear's function registrations. 191 | -------------------------------------------------------------------------------- /build/reqpacks/Dockerfile: -------------------------------------------------------------------------------- 1 | 2 | ARG GEARS_VERSION=master 3 | 4 | # OSNICK=bionic|stretch|buster 5 | ARG OSNICK=buster 6 | 7 | # ARCH=x64|arm64v8|arm32v7 8 | ARG ARCH=x64 9 | 10 | #---------------------------------------------------------------------------------------------- 11 | FROM redisfab/redisgears:${GEARS_VERSION}-${ARCH}-${OSNICK} 12 | 13 | WORKDIR /rgsync 14 | 15 | ADD . /rgsync 16 | 17 | RUN ./deps/readies/bin/getpy3 18 | RUN ./build/reqpacks/system-setup.py 19 | 20 | CMD ["--loadmodule", "/var/opt/redislabs/lib/modules/redisgears.so", "Plugin", "/var/opt/redislabs/modules/rg/plugin/gears_python.so"] 21 | -------------------------------------------------------------------------------- /build/reqpacks/build: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | [[ $V == 1 || $VERBOSE == 1 ]] && set -x 4 | [[ $IGNERR == 1 ]] || set -e 5 | 6 | HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" 7 | ROOT=$(cd $HERE/../..; pwd) 8 | export READIES=$ROOT/deps/readies 9 | . $READIES/shibumi/defs 10 | 11 | OSNICK=${OSNICK:-bionic} 12 | ARCH=${ARCH:-x64} 13 | 14 | if [ -z ${CIRCLE_BRANCH} ]; then 15 | branch=`git branch|grep '*'| cut -d ' ' -f 2-` 16 | fi 17 | if [ "${CIRCLE_BRANCH}" == 'master' ]; then 18 | BRSPEC="" 19 | RGSYNC_VERSION=99.99.99 20 | else 21 | RGSYNC_VERSION=`grep version pyproject.toml |cut -d "=" -f 2-2|sed -e 's/"//g'` 22 | BRSPEC=`git rev-list --max-count=1 HEAD` 23 | fi 24 | 25 | if [[ -z $GEARS_VERSION ]]; then 26 | # map rgsync versions to Gears versions 27 | if [[ $RGSYNC_VERSION == 99.99.99 ]]; then 28 | GEARS_VERSION=master 29 | else 30 | GEARS_VERSION=1.2 31 | fi 32 | fi 33 | 34 | echo "RGSYNC_VERSION=${RGSYNC_VERSION//[[:space:]]/}" > $HERE/env 35 | $ROOT/deps/readies/bin/xtx -e BRSPEC $HERE/requirements.txt | sed -e '/^[ \t]*#/d' > $HERE/requirements.final 36 | 37 | cd $ROOT 38 | docker build -t rgsync-reqpacks:${ARCH}-${OSNICK} -f build/reqpacks/Dockerfile \ 39 | --build-arg GEARS_VERSION=${GEARS_VERSION} \ 40 | --build-arg OSNICK=${OSNICK} \ 41 | --build-arg ARCH=${ARCH} \ 42 | . 43 | 44 | cid=$(mktemp /tmp/gears.cid.XXXXXX) 45 | rm -f $cid 46 | docker run -d --cidfile $cid rgsync-reqpacks:${ARCH}-${OSNICK} 47 | did=`cat $cid` 48 | # docker exec ./sbin/wait-for-redis 49 | sleep 2 50 | 51 | ARTIFACTS=$ROOT/bin/artifacts 52 | mkdir -p $ARTIFACTS 53 | 54 | docker exec $did ./build/reqpacks/build-internal 55 | artifact=`docker exec $did cat bin/artifacts/artifact` 56 | renamed=`echo ${artifact}|sed -e 's/ol8/centos8/'|rev|cut -d '/' -f 1|rev` 57 | docker cp $did:$artifact ${ARTIFACTS}/${renamed} 58 | 59 | docker stop $did 60 | rm -f $cid 61 | -------------------------------------------------------------------------------- /build/reqpacks/build-internal: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -xe 4 | 5 | HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" 6 | ROOT=$(cd $HERE/../.. && pwd) 7 | READIES=$ROOT/deps/readies 8 | . $READIES/shibumi/defs 9 | 10 | . $HERE/env 11 | [[ -z $RGSYNC_VERSION ]] && { echo "RGSYNC_VERSION is not defined. Aborting"; exit 1; } 12 | PLATFORM=`$READIES/bin/platform -t` 13 | 14 | $READIES/bin/enable-utf8 15 | source `get_profile_d`/utf8.sh 16 | 17 | touch $HERE/none.py 18 | python3 -m gears_cli run --requirements $HERE/requirements.final $HERE/none.py 19 | 20 | REQS_PATH=$ROOT/bin/artifacts/reqs 21 | rm -rf $REQS_PATH 22 | mkdir -p $REQS_PATH 23 | python3 -m gears_cli export-requirements --all --save-directory $REQS_PATH 24 | 25 | # DONE=false 26 | # until $DONE; do 27 | # read || DONE=true 28 | # if [[ ! -z $REPLY ]]; then 29 | # python3 -m gears_cli export-requirements --save-directory $REQS_PATH --requirement $REPLY 30 | # fi 31 | # done < $HERE/requirements.final 32 | 33 | cd $REQS_PATH 34 | zip $ROOT/bin/artifacts/rgsync-${RGSYNC_VERSION}.${PLATFORM}.zip *.zip 35 | cd .. 36 | rm -rf $REQS_PATH 37 | 38 | $READIES/bin/platform -t > $ROOT/bin/artifacts/platform 39 | echo $ROOT/bin/artifacts/rgsync-${RGSYNC_VERSION}.${PLATFORM}.zip > $ROOT/bin/artifacts/artifact 40 | -------------------------------------------------------------------------------- /build/reqpacks/dockerfile.tmpl: -------------------------------------------------------------------------------- 1 | 2 | ARG GEARS_VERSION=master 3 | 4 | # OSNICK=bionic|stretch|buster 5 | ARG OSNICK=buster 6 | 7 | # ARCH=x64|arm64v8|arm32v7 8 | ARG ARCH=x64 9 | 10 | #---------------------------------------------------------------------------------------------- 11 | FROM redisfab/redisgears:${GEARS_VERSION}-${ARCH}-${OSNICK} 12 | 13 | WORKDIR /rgsync 14 | 15 | ADD . /rgsync 16 | 17 | RUN ./deps/readies/bin/getpy3 18 | RUN ./build/reqpacks/system-setup.py 19 | 20 | CMD ["--loadmodule", "/var/opt/redislabs/lib/modules/redisgears.so", "Plugin", "/var/opt/redislabs/modules/rg/plugin/gears_python.so"] 21 | -------------------------------------------------------------------------------- /build/reqpacks/requirements.txt: -------------------------------------------------------------------------------- 1 | git+https://github.com/RedisGears/rgsync.git{{BRSPEC}} 2 | PyMySQL 3 | cryptography 4 | cx-Oracle 5 | # pysqlite3 6 | cassandra-driver 7 | snowflake-sqlalchemy 8 | redis==3.5.3 9 | redis-py-cluster 10 | pyodbc 11 | pymongo 12 | setuptools>=65.5.1 # not directly required, pinned by Snyk to avoid a vulnerability 13 | -------------------------------------------------------------------------------- /build/reqpacks/system-setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | import os 5 | import argparse 6 | 7 | HERE = os.path.abspath(os.path.dirname(__file__)) 8 | ROOT = os.path.abspath(os.path.join(HERE, "../..")) 9 | READIES = os.path.join(ROOT, "deps/readies") 10 | sys.path.insert(0, READIES) 11 | import paella 12 | 13 | #---------------------------------------------------------------------------------------------- 14 | 15 | class ReqPacksSetup(paella.Setup): 16 | def __init__(self, nop=False): 17 | paella.Setup.__init__(self, nop) 18 | 19 | def common_first(self): 20 | self.install_downloaders() 21 | self.pip_install("wheel virtualenv") 22 | self.pip_install("setuptools --upgrade") 23 | 24 | self.install("git zip unzip libxml2") 25 | self.run(f"{READIES}/bin/enable-utf8") 26 | 27 | def debian_compat(self): 28 | self.run(f"{READIES}/bin/getgcc") 29 | self.install("libsqlite3-dev") 30 | self.install("unixodbc-dev") 31 | 32 | def redhat_compat(self): 33 | self.run(f"{READIES}/bin/getgcc") 34 | self.install("redhat-lsb-core") 35 | if self.os_version[0] >= 8 and self.dist in ['centos', 'ol']: 36 | self.install("sqlite-devel") 37 | else: 38 | self.install("libsqlite3x-devel") 39 | self.install("unixODBC-devel") 40 | 41 | def fedora(self): 42 | self.run(f"{READIES}/bin/getgcc") 43 | 44 | def macos(self): 45 | self.install_gnu_utils() 46 | 47 | def common_last(self): 48 | self.pip_install("gears-cli") 49 | 50 | #---------------------------------------------------------------------------------------------- 51 | 52 | parser = argparse.ArgumentParser(description='Set up system for build.') 53 | parser.add_argument('-n', '--nop', action="store_true", help='no operation') 54 | args = parser.parse_args() 55 | 56 | ReqPacksSetup(nop=args.nop).setup() 57 | -------------------------------------------------------------------------------- /demo/WriteBehindDemo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RedisGears/rgsync/5c5bca64d8fb49c037a2cbb6cd1134b2f5a83275/demo/WriteBehindDemo.gif -------------------------------------------------------------------------------- /example-cql.py: -------------------------------------------------------------------------------- 1 | from WriteBehind import RGWriteBehind 2 | from WriteBehind.Connectors import CqlConnector, CqlConnection 3 | 4 | ''' 5 | Create CQL connection object 6 | ''' 7 | connection = CqlConnection('cassandra', 'cassandra', 'cassandra', 'test') 8 | 9 | ''' 10 | Create CQL person connector 11 | persons - CQL table to put the data 12 | person_id - primary key 13 | ''' 14 | personsConnector = CqlConnector(connection, 'persons', 'person_id') 15 | 16 | personsMappings = { 17 | 'first_name':'first', 18 | 'last_name':'last', 19 | 'age':'age' 20 | } 21 | 22 | RGWriteBehind(GB, keysPrefix='person', mappings=personsMappings, connector=personsConnector, name='PersonsWriteBehind', version='99.99.99') 23 | 24 | RGWriteThrough(GB, keysPrefix='__', mappings=personsMappings, connector=personsConnector, name='PersonsWriteThrough', version='99.99.99') 25 | 26 | ''' 27 | Create CQL cars connector 28 | cars - CQL table to put the data 29 | car_id - primary key 30 | ''' 31 | carConnector = CqlConnector(connection, 'cars', 'car_id') 32 | 33 | carsMappings = { 34 | 'id':'id', 35 | 'color':'color' 36 | } 37 | 38 | RGWriteBehind(GB, keysPrefix='car', mappings=carsMappings, connector=carsConnector, name='CarsWriteBehind', version='99.99.99') 39 | -------------------------------------------------------------------------------- /examples/db2/README.md: -------------------------------------------------------------------------------- 1 | # Setup DB2 2 | 3 | # Requirements 4 | 5 | Note, running the db2 recipe, requires some local libraries on your running redis instance - due to the requirements of the *ibm-db-sa* library, used for communicating with db2. Install the equivalent of *libxml2* (libxml2, libxml2-dev, libxml2-devel) on your redis instance, in order to support this recipe. 6 | 7 | # Running the recipe 8 | Assuming you have RedisGears up and running (see [Quick Start](https://oss.redislabs.com/redisgears/quickstart.html)). Please use gears-cli to send a RedisGears Write-Behind and/or Write-Through recipe for execution. For example, run the sample [DB2](example.py) recipe (contains the mapping of DB2 tables with Redis Hashes and RedisGears registrations) and install its dependencies with the following command: 9 | 10 | ```bash 11 | gears-cli run --host --port --password example.py --requirements requirements.txt 12 | ``` 13 | e.g. 14 | ```bash 15 | > gears-cli run --host localhost --port 14000 example.py --requirements requirements.txt 16 | OK 17 | ``` 18 | 19 | # Test 20 | Using redis-cli perform: 21 | ```bash 22 | redis-cli 23 | > hset emp:1 FirstName foo LastName bar 24 | ``` 25 | 26 | Make sure data reached MsSql server: 27 | -------------------------------------------------------------------------------- /examples/db2/example.py: -------------------------------------------------------------------------------- 1 | from rgsync.Connectors import DB2Connection, DB2Connector 2 | from rgsync import RGWriteBehind, RGWriteThrough 3 | 4 | ''' 5 | Create DB2 connection object 6 | ''' 7 | connection = DB2Connection('user', 'pass', 'host[:port]/dbname') 8 | 9 | ''' 10 | Create DB2 emp connector 11 | ''' 12 | empConnector = DB2Connector(connection, 'emp', 'empno') 13 | 14 | empMappings = { 15 | 'FirstName':'fname', 16 | 'LastName':'lname' 17 | } 18 | 19 | RGWriteBehind(GB, keysPrefix='emp', mappings=empMappings, connector=empConnector, name='empWriteBehind', version='99.99.99') 20 | 21 | RGWriteThrough(GB, keysPrefix='__', mappings=empMappings, connector=empConnector, name='empWriteThrough', version='99.99.99') 22 | -------------------------------------------------------------------------------- /examples/db2/requirements.txt: -------------------------------------------------------------------------------- 1 | rgsync 2 | -------------------------------------------------------------------------------- /examples/mongo/README.md: -------------------------------------------------------------------------------- 1 | # Configuring Mongo write-behind 2 | 3 | Unlike other recipes, this recipe requires a valid redis-server with RedisJSON. 4 | 5 | ## Setting up a Mongo docker 6 | ```bash 7 | docker run -p 27017:27017 --name mongo -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=adminpasswd -e MONGO_INITDB_DATABASE=admin 8 | ``` 9 | 10 | ----------------- 11 | 12 | ## How this works 13 | 14 | A connection is made to Mongo, by the Redis server, running RedisGears. A JSON mapping is created (see below), so that we can update sub-sections of the JSON document. 15 | 16 | The recipe below will write data to a collection called *persons* on the Mongo server. All data stored in *persons* will be part of a JSON document containing a standard id, and a JSON document containing the key *gears* at the top level. This JSON document will contain the data migrated from Redis to Mongo. 17 | 18 | Let's assume the Redis JSON data contains the following: 19 | 20 | ```{'hello': 'world'}``` 21 | 22 | In that case the data would be replicated to Mongo, appearing as below. Note that Mongo will add an *_id* field for its entry. The *person_id* below refers to the key used to store data in Redis. Assuming that example above was stored in Redis (i.e JSON.SET), using the key *person:1*, the following would be the output in Mongo. 23 | 24 | **NOTE**: redisgears reserves the internal key name **redisgears**, so you must ensure that your json hierarchy does not contain a root element with that name. 25 | 26 | ``` 27 | {'_id': ObjectId('617953191b814c4c150bddd4'), 28 | 'person_id': 1, 29 | 'hello': 'world' 30 | ] 31 | 32 | ``` 33 | 34 | ### Connecting to Mongo 35 | 36 | #### Standalong Mongo instance 37 | 38 | The example below illustrates how one can build a connection to Mongo. First, we build a MongoConnection, and the following are the inputs: 39 | 40 | 1. The first field is the *username* in our example below this is **admin** 41 | 2. 42 | 2. The second field is the *password* in our example below this is **adminpassword** 43 | 3. 44 | 3. The third field is the *mongodb connection url* in our example below this is **172.17.0.1:27017/admin**. This means that the user is connecting to the Mongo instance on: 45 | 46 | a. The host with IP address 172.17.0.1 47 | 48 | b. Port 27017 49 | 50 | c. The database in Mongo used for validating authentication. The default is admin, as above, but in your setup this could be anything. 51 | 52 | 4. The [optional] fourth argument is the authentication source. By default we authenticate using the standard Mongo authentication source (admin). For more details on authentication sources see [this link](https://docs.mongodb.com/manual/core/authentication-mechanisms/). 53 | 54 | 55 | ``` 56 | from rgsync.Connectors import MongoConnector, MongoConnection 57 | connection = MongoConnection('admin', 'adminpassword', '172.17.0.1:27017/admin') 58 | jConnector = MongoConnector(connection, 'yourmongodbname', 'persons', 'person_id') 59 | ``` 60 | 61 | #### Connecting to a cluster 62 | 63 | The cluster connection is similar to standalone, except that the MongoConnection object must be initialized differently. *None*s must be passed in for both the username and password, and a **mongodb://** style connection string specified using a variable named *conn_string*. Note: the database must be specified in this instance, as the Connector, still needs to create a connection to the database 64 | 65 | ``` 66 | 67 | from rgsync.Connectors import MongoConnector, MongoConnection 68 | db = 'yourmongodbname' 69 | connection = MongoConnection(None, None, db, conn_string='mongodb://172.17.0.1:27017,172.17.0.5:27017,172.17.0.9:27017') 70 | jConnector = MongoConnector(connection, db, 'persons', 'person_id') 71 | ``` 72 | 73 | ## Examples 74 | 75 | ### Gears Recipe for a single write behind 76 | 77 | This example replicates all data written to Redis whose key is named *person:*, to the Mongo collection named *persons*. The collection name is specified in the instantiation of the MongoConnector below. 78 | 79 | ``` 80 | from rgsync import RGJSONWriteBehind, RGJSONWriteThrough 81 | from rgsync.Connectors import MongoConnector, MongoConnection 82 | 83 | connection = MongoConnection('admin', 'adminpassword', '172.17.0.1:27017/admin') 84 | db = 'yourmongodbname' 85 | 86 | personConnector = MongoConnector(connection, db, 'persons', 'person_id') 87 | 88 | 89 | RGJSONWriteBehind(GB, keysPrefix='person', 90 | connector=personConnector, name='PersonsWriteBehind', 91 | version='99.99.99') 92 | 93 | RGJSONWriteThrough(GB, keysPrefix='__', connector=personConnector, 94 | name='PersonJSONWriteThrough', version='99.99.99') 95 | ``` 96 | 97 | ### Gears recipe writing to multiple collections 98 | 99 | This example recipe builds on the previous case, and introduces as second replication recipe. In this example, anything stored in Redis under the key *person:* (eg: person:1, person:15) will be replicated to the *persons* collection in Mongo. Anything written to Redis, and stored under the key *thing:* (eg: thing:42, thing:450) will be replicated to the *things* collection in Mongo. 100 | 101 | ``` 102 | from rgsync import RGJSONWriteBehind, RGJSONWriteThrough 103 | from rgsync.Connectors import MongoConnector, MongoConnection 104 | 105 | connection = MongoConnection('admin', 'adminpassword', '172.17.0.1:27017/admin') 106 | db = 'yourmongodbname' 107 | 108 | personConnector = MongoConnector(connection, db, 'persons', 'person_id') 109 | 110 | RGJSONWriteBehind(GB, keysPrefix='person', 111 | connector=personConnector, name='PersonsWriteBehind', 112 | version='99.99.99') 113 | 114 | RGJSONWriteThrough(GB, keysPrefix='__', connector=personConnector, 115 | name='PersonJSONWriteThrough', version='99.99.99') 116 | 117 | thingConnector = MongoConnector(connection, db, 'things', 'thing_id') 118 | RGJSONWriteBehind(GB, keysPrefix='thing', 119 | connector=thingConnector, name='ThingWriteBehind', 120 | version='99.99.99') 121 | 122 | RGJSONWriteThrough(GB, keysPrefix='__', connector=thingConnector, 123 | name='ThingJSONWriteThrough', version='99.99.99') 124 | ``` 125 | 126 | ### Data storage examples 127 | 128 | Data should be stored in Redis using the various JSON commands from [RedisJSON](https://redisjson.io). In all cases, initial writes, and updates rely on the same underlying mechanism. 129 | 130 | **Storing data** 131 | 132 | ``` 133 | json.set person:1 . '{"hello": "world"}' 134 | ``` 135 | 136 | **Storing data, then adding more fields** 137 | 138 | ``` 139 | json.set person:1 . '{"hello": "world", "my": ["list", "has", "things"]}' 140 | json.set person:1 . '{"someother": "fieldtoadd"}' 141 | ``` 142 | 143 | **Storing data, then updating** 144 | 145 | ``` 146 | json.set person:1 . '{"hello": "world", "my": ["list", "has", "things"]}' 147 | json.set person:1 . '{"hello": "there!"}' 148 | ``` 149 | 150 | **Storing data, then deleting** 151 | 152 | ``` 153 | json.set person:1 . '{"hello": "world"}' 154 | json.del person:1 155 | ``` 156 | -------------------------------------------------------------------------------- /examples/mongo/example.py: -------------------------------------------------------------------------------- 1 | from rgsync import RGJSONWriteBehind, RGJSONWriteThrough 2 | from rgsync.Connectors import MongoConnector, MongoConnection 3 | ''' 4 | Create Mongo connection object 5 | ''' 6 | connection = MongoConnection('admin', 'admin', '172.17.0.1:27017/admin') 7 | 8 | 9 | ''' 10 | Create Mongo persons connector 11 | ''' 12 | jConnector = MongoConnector(connection, db, 'persons', 'person_id') 13 | 14 | RGJSONWriteBehind(GB, keysPrefix='person', 15 | connector=jConnector, name='PersonsWriteBehind', 16 | version='99.99.99') 17 | 18 | RGJSONWriteThrough(GB, keysPrefix='__', connector=jConnector, 19 | name='JSONWriteThrough', version='99.99.99') 20 | -------------------------------------------------------------------------------- /examples/mongo/requirements.txt: -------------------------------------------------------------------------------- 1 | rgsync 2 | pymongo==3.12.0 -------------------------------------------------------------------------------- /examples/mssql/README.md: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | 3 | Docker compatible [*nix OS](https://en.wikipedia.org/wiki/Unix-like) and Docker installed. 4 |
Download this folder and give execute permission to the scripts i.e.
5 | ```bash 6 | wget -c https://github.com/RedisGears/rgsync/archive/master.zip && unzip master.zip "rgsync-master/examples/mssql/*" && rm master.zip && mv rgsync-master rgsync && cd rgsync/examples/mssql && chmod a+x *.sh 7 | ``` 8 | 9 | ## Setup MSSQL 2017 database in docker 10 | 11 |
Execute [setup_mssql.sh](setup_mssql.sh)
12 | ```bash 13 | > ./setup_mssql.sh 14 | ``` 15 | --- 16 | **NOTE** 17 | 18 | The above script will start a [MSSQL 2017 docker](https://hub.docker.com/layers/microsoft/mssql-server-linux/2017-latest/images/sha256-314918ddaedfedc0345d3191546d800bd7f28bae180541c9b8b45776d322c8c2?context=explore) instance, create RedisGearsTest database and emp table. 19 | 20 | --- 21 | 22 | # Redis OSS Users 23 | Assuming you have RedisGears up and running (see [Quick Start](https://oss.redislabs.com/redisgears/quickstart.html)). Please continue from [Running the recipe](#running-the-recipe). 24 | 25 | 26 | # Redis Enterprise Users 27 | 28 | ## Setup Redis Enterprise cluster and database in docker 29 |
Execute [setupAndcreate_redb.sh](setupAndcreate_redb.sh)
30 | ```bash 31 | > ./setupAndcreate_redb.sh 32 | ``` 33 | --- 34 | **NOTE** 35 | 36 | The above script will create a 3-node Redis Enterprise cluster in docker containers on rg-net network, [Install RedisGears dependencies](https://docs.redislabs.com/latest/modules/redisgears/installing-redisgears/#step-1-install-redisgears-dependencies), [Install RedisGears module](https://docs.redislabs.com/latest/modules/redisgears/installing-redisgears/#step-2-install-the-redisgears-module), [Install MS ODBC driver for MSSQL](https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15#ubuntu17) and [Create a Redis Enterprise database with RedisGears module enabled and verify the installation](https://docs.redislabs.com/latest/modules/redisgears/installing-redisgears/#step-3-create-a-database-and-verify-the-installation). 37 | 38 | --- 39 | 40 | # Running the recipe 41 | Please use gears-cli to send a RedisGears Write-Behind and/or Write-Through recipe for execution. For example, run the sample [MsSql](example.py) recipe (contains the mapping of MsSql tables with Redis Hashes and RedisGears registrations) and install its dependencies with the following command (Redis OSS users, please update the server value to localhost in [example.py](example.py) prior to running this recipe): 42 | 43 | ```bash 44 | gears-cli run --host --port --password example.py --requirements requirements.txt 45 | ``` 46 | e.g. 47 | ```bash 48 | > gears-cli run --host localhost --port 14000 example.py --requirements requirements.txt 49 | OK 50 | ``` 51 | 52 | Check the database log file (`Should also be visible for OSS users in the console.`): 53 | ```bash 54 | > sudo docker exec -it re-node1 bash -c "tail -f /var/opt/redislabs/log/redis-1.log" 55 | 3537:M 02 Nov 2020 17:50:44.339 * GEARS: WRITE_BEHIND - Connect: connecting ConnectionStr=mssql+pyodbc://sa:Redis@123@172.18.0.5:1433/RedisGearsTest?driver=ODBC+Driver+17+for+SQL+Server 56 | 3537:M 02 Nov 2020 17:50:44.402 * GEARS: WRITE_BEHIND - Connect: Connected 57 | 58 | ``` 59 | 60 | # Test 61 | Using redis-cli perform: 62 | ```bash 63 | redis-cli 64 | > hset emp:1 FirstName foo LastName bar 65 | ``` 66 | e.g. 67 | ```bash 68 | > sudo docker exec -it re-node1 bash -c "/opt/redislabs/bin/redis-cli -p 12000 hset emp:1 FirstName foo LastName bar" 69 | (integer) 2 70 | 71 | ``` 72 | 73 | Make sure data reached MsSql server: 74 | ```bash 75 | sudo docker exec -it /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P Redis@123 76 | 1> use RedisGearsTest 77 | 2> go 78 | Changed database context to 'RedisGearsTest'. 79 | 1> select * from emp 80 | 2> go 81 | empno fname lname 82 | ----------- -------------------------------------------------- -------------------------------------------------- 83 | 1 foo bar 84 | 85 | (1 rows affected) 86 | 87 | ``` 88 | -------------------------------------------------------------------------------- /examples/mssql/example.py: -------------------------------------------------------------------------------- 1 | from rgsync.Connectors import MsSqlConnector, MsSqlConnection 2 | from rgsync import RGWriteBehind, RGWriteThrough 3 | 4 | ''' 5 | Create MSSQL connection object 6 | MsSqlConnection('', '', '', '', '', '') 7 | ********* Redis OSS users: please use localhost for value ********* 8 | ''' 9 | connection = MsSqlConnection('sa', 'Redis@123', 'RedisGearsTest', '172.18.0.5', '1433', 'ODBC+Driver+17+for+SQL+Server') 10 | 11 | ''' 12 | Create MSSQL emp connector 13 | MsSqlConnector(, '', '') 14 | ''' 15 | empConnector = MsSqlConnector(connection, 'emp', 'empno') 16 | 17 | empMappings = { 18 | #redis:database 19 | 'FirstName':'fname', 20 | 'LastName':'lname' 21 | } 22 | 23 | RGWriteBehind(GB, keysPrefix='emp', mappings=empMappings, connector=empConnector, name='empWriteBehind', version='99.99.99') 24 | 25 | RGWriteThrough(GB, keysPrefix='__', mappings=empMappings, connector=empConnector, name='empWriteThrough', version='99.99.99') 26 | -------------------------------------------------------------------------------- /examples/mssql/mssql_init.sql: -------------------------------------------------------------------------------- 1 | USE master 2 | GO 3 | -- Create the new database if it does not exist already 4 | IF NOT EXISTS ( 5 | SELECT [name] 6 | FROM sys.databases 7 | WHERE [name] = N'RedisGearsTest' 8 | ) 9 | CREATE DATABASE RedisGearsTest 10 | GO 11 | 12 | -- Create sample emp table 13 | USE [RedisGearsTest] 14 | GO 15 | 16 | SET ANSI_NULLS ON 17 | GO 18 | SET QUOTED_IDENTIFIER ON 19 | GO 20 | CREATE TABLE [dbo].[emp] ( 21 | [empno] int NOT NULL, 22 | [fname] varchar(50), 23 | [lname] varchar(50), 24 | PRIMARY KEY ([empno]) 25 | ) 26 | GO 27 | SELECT * FROM emp 28 | GO 29 | -------------------------------------------------------------------------------- /examples/mssql/requirements.txt: -------------------------------------------------------------------------------- 1 | rgsync 2 | pyodbc 3 | -------------------------------------------------------------------------------- /examples/mssql/setupAndcreate_redb.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Delete bridge network if it already exist 3 | sudo docker network rm rg-net 2>/dev/null 4 | sudo docker kill re-node1;sudo docker rm re-node1; 5 | sudo docker kill re-node2;sudo docker rm re-node2; 6 | sudo docker kill re-node3;sudo docker rm re-node3; 7 | # Uncomment this to pull the newer version of redislabs/redis docker image in case the latest tag has been upgraded 8 | #sudo docker rmi -f $(docker images | grep redislabs | awk '{print $3}') 9 | 10 | # Create a bridge network for RE and MSSQL containers 11 | echo "Creating bridge network..." 12 | sudo docker network create --driver bridge rg-net 13 | # Start 3 docker containers. Each container is a node in the same network 14 | echo "Starting Redis Enterprise as Docker containers..." 15 | sudo docker run -d --cap-add sys_resource -h re-node1 --name re-node1 -p 18443:8443 -p 19443:9443 -p 14000-14005:12000-12005 -p 18070:8070 --network rg-net redislabs/redis:latest 16 | sudo docker run -d --cap-add sys_resource -h re-node2 --name re-node2 -p 28443:8443 -p 29443:9443 -p 12010-12015:12000-12005 -p 28070:8070 --network rg-net redislabs/redis:latest 17 | sudo docker run -d --cap-add sys_resource -h re-node3 --name re-node3 -p 38443:8443 -p 39443:9443 -p 12020-12025:12000-12005 -p 38070:8070 --network rg-net redislabs/redis:latest 18 | # Create Redis Enterprise cluster 19 | echo "Waiting for the servers to start..." 20 | sleep 60 21 | echo "Creating Redis Enterprise cluster and joining nodes..." 22 | sudo docker exec -it --privileged re-node1 "/opt/redislabs/bin/rladmin" cluster create name re-cluster.local username demo@redislabs.com password redislabs 23 | sudo docker exec -it --privileged re-node2 "/opt/redislabs/bin/rladmin" cluster join nodes $(sudo docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' re-node1) username demo@redislabs.com password redislabs 24 | sudo docker exec -it --privileged re-node3 "/opt/redislabs/bin/rladmin" cluster join nodes $(sudo docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' re-node1) username demo@redislabs.com password redislabs 25 | echo "" 26 | # Test the cluster 27 | sudo docker exec -it re-node1 bash -c "/opt/redislabs/bin/rladmin info cluster" 28 | 29 | # Install wget to download RedisGears components 30 | echo "Installing RedisGears and it's prerequisites..." 31 | sudo docker exec --user root -it re-node1 bash -c "apt-get install -y wget" 32 | sudo docker exec --user root -it re-node2 bash -c "apt-get install -y wget" 33 | sudo docker exec --user root -it re-node3 bash -c "apt-get install -y wget" 34 | rm install_gears.sh 35 | tee -a install_gears.sh < /etc/apt/sources.list.d/mssql-release.list 45 | sudo apt-get update -y 46 | echo msodbcsql17 msodbcsql/ACCEPT_EULA boolean true | sudo debconf-set-selections 47 | apt-get install -y msodbcsql17 48 | ACCEPT_EULA=Y apt-get install -y mssql-tools 49 | echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile 50 | echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc 51 | source ~/.bashrc 52 | apt-get install -y unixodbc-dev 53 | EOF 54 | 55 | sudo docker cp install_gears.sh re-node1:/opt/install_gears.sh 56 | sudo docker exec --user root -it re-node1 bash -c "chmod 777 /opt/install_gears.sh" 57 | sudo docker exec --user root -it re-node1 bash -c "/opt/install_gears.sh" 58 | sudo docker cp install_gears.sh re-node2:/opt/install_gears.sh 59 | sudo docker exec --user root -it re-node2 bash -c "chmod 777 /opt/install_gears.sh" 60 | sudo docker exec --user root -it re-node2 bash -c "/opt/install_gears.sh" 61 | sudo docker cp install_gears.sh re-node3:/opt/install_gears.sh 62 | sudo docker exec --user root -it re-node3 bash -c "chmod 777 /opt/install_gears.sh" 63 | sudo docker exec --user root -it re-node3 bash -c "/opt/install_gears.sh" 64 | 65 | echo "Uploading RedisGears module..." 66 | rm upload_rg.sh 67 | tee -a upload_rg.sh < /bin/bash 11 | mysql -u root -p # set password my-secret-pw 12 | CREATE DATABASE test; 13 | CREATE TABLE test.persons (person_id VARCHAR(100) NOT NULL, first VARCHAR(100) NOT NULL, last VARCHAR(100) NOT NULL, age INT NOT NULL, PRIMARY KEY (person_id)); 14 | CREATE USER 'demouser'@'%' IDENTIFIED BY 'Password123!'; 15 | FLUSH PRIVILEGES; 16 | GRANT ALL PRIVILEGES ON test.* to 'demouser'@'%'; 17 | FLUSH PRIVILEGES; 18 | ``` 19 | 20 | # Running the recipe 21 | Assuming you have RedisGears up and running (see [Quick Start](https://oss.redislabs.com/redisgears/quickstart.html)). Please use gears-cli to send a RedisGears Write-Behind and/or Write-Through recipe for execution. For example, run the sample [MySql](example.py) recipe (contains the mapping of MySql tables with Redis Hashes and RedisGears registrations) and install its dependencies with the following command: 22 | 23 | ```bash 24 | gears-cli run --host --port --password example.py --requirements requirements.txt 25 | ``` 26 | 27 | # Test 28 | Using redis-cli perform: 29 | ```bash 30 | redis-cli 31 | > hset person:1 first_name foo last_name bar age 20 32 | ``` 33 | 34 | Make sure data reached MySql server: 35 | ```bash 36 | docker exec -it /bin/bash 37 | mysql -u root -p # set password my-secret-pw 38 | mysql> select * from test.persons; 39 | +-----------+-------+------+-----+ 40 | | person_id | first | last | age | 41 | +-----------+-------+------+-----+ 42 | | 1 | foo | bar | 20 | 43 | +-----------+-------+------+-----+ 44 | 1 row in set (0.00 sec) 45 | 46 | ``` 47 | -------------------------------------------------------------------------------- /examples/mysql/example.py: -------------------------------------------------------------------------------- 1 | from rgsync import RGWriteBehind, RGWriteThrough 2 | from rgsync.Connectors import MySqlConnector, MySqlConnection 3 | 4 | ''' 5 | Create MySQL connection object 6 | ''' 7 | connection = MySqlConnection('demouser', 'Password123!', 'localhost:3306/test') 8 | 9 | ''' 10 | Create MySQL persons connector 11 | ''' 12 | personsConnector = MySqlConnector(connection, 'persons', 'person_id') 13 | 14 | personsMappings = { 15 | 'first_name':'first', 16 | 'last_name':'last', 17 | 'age':'age' 18 | } 19 | 20 | RGWriteBehind(GB, keysPrefix='person', mappings=personsMappings, connector=personsConnector, name='PersonsWriteBehind', version='99.99.99') 21 | 22 | RGWriteThrough(GB, keysPrefix='__', mappings=personsMappings, connector=personsConnector, name='PersonsWriteThrough', version='99.99.99') 23 | -------------------------------------------------------------------------------- /examples/mysql/requirements.txt: -------------------------------------------------------------------------------- 1 | rgsync 2 | PyMySQL 3 | cryptography -------------------------------------------------------------------------------- /examples/postgres/README.md: -------------------------------------------------------------------------------- 1 | # Set up Postgres DB 2 | 3 | ## Setup Postgres docker 4 | ```bash 5 | docker run -p 5432:5432 --name some-postgres -e POSTGRES_ROOT_PASSWORD=my-secret-pw -d postgres:latest 6 | ``` 7 | 8 | ## Create Persons table 9 | 10 | See [Postgres setup scripts](../sbin/setup-postgres). 11 | 12 | # Running the recipe 13 | Assuming you have RedisGears up and running (see [Quick Start](https://oss.redislabs.com/redisgears/quickstart.html)). Please use gears-cli to send a RedisGears Write-Behind and/or Write-Through recipe for execution. For example, run the sample [Postgres](example.py) recipe (contains the mapping of Postgres tables with Redis Hashes and RedisGears registrations) and install its dependencies with the following command: 14 | 15 | ```bash 16 | gears-cli run --host --port --password example.py --requirements requirements.txt 17 | ``` 18 | 19 | As rgsync uses the psycopyg2 driver under the covers, please ensure you have the postgresql client libraries (i.e libpq-dev), or the appropriate binary drivers for your operating system installed. 20 | 21 | # Test 22 | Using redis-cli perform: 23 | ```bash 24 | redis-cli 25 | > hset person:1 first_name foo last_name bar age 20 26 | ``` 27 | -------------------------------------------------------------------------------- /examples/postgres/example.py: -------------------------------------------------------------------------------- 1 | from rgsync import RGWriteBehind, RGWriteThrough 2 | from rgsync.Connectors import PostgresConnector, PostgresConnection 3 | 4 | ''' 5 | Create Postgres connection object 6 | ''' 7 | connection = PostgresConnection('demo', 'Password123!', 'localhost:5432/test') 8 | 9 | ''' 10 | Create Postgres persons connector 11 | ''' 12 | personsConnector = PostgresConnector(connection, 'persons', 'person_id') 13 | 14 | personsMappings = { 15 | 'first_name':'first', 16 | 'last_name':'last', 17 | 'age':'age' 18 | } 19 | 20 | RGWriteBehind(GB, keysPrefix='person', mappings=personsMappings, connector=personsConnector, name='PersonsWriteBehind', version='99.99.99') 21 | 22 | RGWriteThrough(GB, keysPrefix='__', mappings=personsMappings, connector=personsConnector, name='PersonsWriteThrough', version='99.99.99') 23 | -------------------------------------------------------------------------------- /examples/postgres/requirements.txt: -------------------------------------------------------------------------------- 1 | rgsync 2 | psycopg2 3 | cryptography 4 | -------------------------------------------------------------------------------- /examples/redis/README.md: -------------------------------------------------------------------------------- 1 | # Set up Redis Server 2 | To setup a Redis server to replicate data to, start another Redis server on different port (assuming you have Redis installed on the machine) 3 | ```bash 4 | redis-server --port 9001 5 | ``` 6 | 7 | ## Running the recipe 8 | Please use gears-cli to send a RedisGears Write-Behind and/or Write-Through recipe for execution. 9 | For example, run the sample [redis](example-redis-standalone.py) recipe (contains the mapping of primary DB Redis Hashes with secondary DB Redis Hashes and RedisGears registrations) and install its dependencies with the following command: 10 | 11 | ```bash 12 | gears-cli run --host --port --password example-redis-standalone.py --requirements requirements.txt 13 | ``` 14 | 15 | NOTE: Exactly once property is not valid for Redis cluster, because Redis cluster do not support transaction over multiple shards. 16 | 17 | # Test 18 | Using redis-cli perform: 19 | ```bash 20 | redis-cli 21 | 127.0.0.1:6379> hset key:1 bin1 1 bin2 2 bin3 3 bin4 4 bin5 5 22 | (integer) 5 23 | ``` 24 | 25 | Make sure data reached the second Redis server: 26 | ```bash 27 | redis-cli -p 9001 28 | 127.0.0.1:9001> hgetall key:1 29 | 1) "bin1" 30 | 2) "1" 31 | 3) "bin2" 32 | 4) "2" 33 | 5) "bin4" 34 | 6) "4" 35 | 7) "bin3" 36 | 8) "3" 37 | 9) "bin5" 38 | 10) "5" 39 | ``` 40 | -------------------------------------------------------------------------------- /examples/redis/example-redis-cluster.py: -------------------------------------------------------------------------------- 1 | from rgsync import RGWriteBehind, RGWriteThrough 2 | from rgsync.Connectors import RedisConnector, RedisConnection, RedisClusterConnection 3 | 4 | ''' 5 | Create Redis Connection 6 | ''' 7 | cnodes = [{"host": "127.0.0.1", "port": "8001"}, {"host": "127.0.0.1", "port": "8002"}, {"host": "127.0.0.1", "port": "8003"}] 8 | r_conn = RedisClusterConnection(host=None, port=None, cluster_nodes=cnodes) 9 | 10 | 11 | ''' 12 | Create Redis Connector 13 | ''' 14 | 15 | key_connector = RedisConnector(connection=r_conn, newPrefix='key', exactlyOnceTableName=None) 16 | key_mappings = { 17 | 'bin1' : 'bin1', 18 | 'bin2' : 'bin2', 19 | 'bin3' : 'bin3', 20 | 'bin4' : 'bin4', 21 | 'bin5' : 'bin5' 22 | } 23 | RGWriteBehind(GB, keysPrefix='key', mappings=key_mappings, connector=key_connector, name='keyWriteBehind', version='99.99.99', onFailedRetryInterval=60) 24 | 25 | 26 | -------------------------------------------------------------------------------- /examples/redis/example-redis-standalone.py: -------------------------------------------------------------------------------- 1 | from rgsync import RGWriteBehind, RGWriteThrough 2 | from rgsync.Connectors import RedisConnector, RedisConnection, RedisClusterConnection 3 | 4 | ''' 5 | Create Redis Connection 6 | ''' 7 | r_conn = RedisConnection(host='127.0.0.1', port=9001) 8 | 9 | 10 | ''' 11 | Create Redis Connector 12 | ''' 13 | 14 | key_connector = RedisConnector(connection=r_conn, newPrefix='key', exactlyOnceTableName=None) 15 | key_mappings = { 16 | 'bin1' : 'bin1', 17 | 'bin2' : 'bin2', 18 | 'bin3' : 'bin3', 19 | 'bin4' : 'bin4', 20 | 'bin5' : 'bin5' 21 | } 22 | RGWriteBehind(GB, keysPrefix='key', mappings=key_mappings, connector=key_connector, name='keyWriteBehind', version='99.99.99', onFailedRetryInterval=60) 23 | 24 | 25 | -------------------------------------------------------------------------------- /examples/redis/requirements.txt: -------------------------------------------------------------------------------- 1 | rgsync 2 | redis==3.5.3 3 | redis-py-cluster 4 | -------------------------------------------------------------------------------- /examples/snowflake/README.md: -------------------------------------------------------------------------------- 1 | ## Running the recipe 2 | Please use gears-cli to send a RedisGears Write-Behind and/or Write-Through recipe for execution. For example, run the sample [snowflake](example.py) recipe (contains the mapping of snowflake tables with Redis Hashes and RedisGears registrations) and install its dependencies with the following command: 3 | 4 | ```bash 5 | gears-cli --host --port --password example.py --requirements requirements.txt 6 | ``` 7 | -------------------------------------------------------------------------------- /examples/snowflake/example.py: -------------------------------------------------------------------------------- 1 | from rgsync import RGWriteBehind, RGWriteThrough 2 | from rgsync.Connectors import SnowflakeSqlConnector, SnowflakeSqlConnection 3 | 4 | ''' 5 | Create Snowflake connection object 6 | The connection object will be translated to snowflake://:@/ 7 | ''' 8 | connection = SnowflakeSqlConnection('', '', '', '') 9 | 10 | ''' 11 | Create Snowflake person1 connector 12 | persons - Snowflake table to put the data 13 | id - primary key 14 | ''' 15 | personsConnector = SnowflakeSqlConnector(connection, 'person1', 'id') 16 | 17 | personsMappings = { 18 | 'first_name':'first', 19 | 'last_name':'last', 20 | 'age':'age' 21 | } 22 | 23 | RGWriteBehind(GB, keysPrefix='person', mappings=personsMappings, connector=personsConnector, name='PersonsWriteBehind', version='99.99.99') 24 | 25 | RGWriteThrough(GB, keysPrefix='__', mappings=personsMappings, connector=personsConnector, name='PersonsWriteThrough', version='99.99.99') 26 | 27 | ''' 28 | Create Snowflake car connector 29 | car - Snowflake table to put the data 30 | license - primary key 31 | ''' 32 | carsConnector = SnowflakeSqlConnector(connection, 'car', 'license') 33 | 34 | carsMappings = { 35 | 'license':'license', 36 | 'color':'color' 37 | } 38 | 39 | RGWriteBehind(GB, keysPrefix='car', mappings=carsMappings, connector=carsConnector, name='CarsWriteBehind', version='99.99.99') 40 | -------------------------------------------------------------------------------- /examples/snowflake/requirements.txt: -------------------------------------------------------------------------------- 1 | rgsync 2 | snowflake-sqlalchemy 3 | 4 | cryptography>=3.2 # not directly required, pinned by Snyk to avoid a vulnerability -------------------------------------------------------------------------------- /examples/sqlite/README.md: -------------------------------------------------------------------------------- 1 | # Connect the DB 2 | 3 | ## Install SQLite (on ubuntu) 4 | ### Ubuntu 5 | ```bash 6 | sudo apt-get install sqlite3 libsqlite3-dev 7 | ``` 8 | 9 | ### CentOS 10 | ```bash 11 | yum install sqlite 12 | ``` 13 | 14 | ## Create Persons table 15 | Run `sqlite3 /tmp/mydatabase.db` and create the `persons` table with the folowing line: 16 | ```bash 17 | sqlite> CREATE TABLE persons (person_id VARCHAR(100) NOT NULL, first VARCHAR(100) NOT NULL, last VARCHAR(100) NOT NULL, age INT NOT NULL, PRIMARY KEY (person_id)); 18 | ``` 19 | 20 | # Running the recipe 21 | Please use gears-cli to send a RedisGears Write-Behind and/or Write-Through recipe for execution. For example, run the sample [SQLite](example.py) recipe (contains the mapping of sqlite tables with Redis Hashes and RedisGears registrations) and install its dependencies with the following command: 22 | 23 | ```bash 24 | gears-cli run --host --port --password example.py --requirements requirements.txt 25 | ``` 26 | -------------------------------------------------------------------------------- /examples/sqlite/example.py: -------------------------------------------------------------------------------- 1 | from rgsync import RGWriteBehind, RGWriteThrough 2 | from rgsync.Connectors import SQLiteConnector, SQLiteConnection 3 | 4 | ''' 5 | Create MySQL connection object 6 | ''' 7 | connection = SQLiteConnection('/tmp/mydatabase.db') 8 | 9 | ''' 10 | Create MySQL persons connector 11 | persons - MySQL table to put the data 12 | person_id - primary key 13 | ''' 14 | personsConnector = SQLiteConnector(connection, 'persons', 'person_id') 15 | 16 | personsMappings = { 17 | 'first_name':'first', 18 | 'last_name':'last', 19 | 'age':'age' 20 | } 21 | 22 | RGWriteBehind(GB, keysPrefix='person', mappings=personsMappings, connector=personsConnector, name='PersonsWriteBehind', version='99.99.99') 23 | -------------------------------------------------------------------------------- /examples/sqlite/requirements.txt: -------------------------------------------------------------------------------- 1 | rgsync -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "rgsync" 3 | version = "1.2.0" 4 | description = "RedisGears synchronization recipe" 5 | keywords = ["redis", "redisgears", "writebehind"] 6 | authors = ["Redis OSS "] 7 | readme = "README.md" 8 | license = "BSD-3-Clause" 9 | 10 | classifiers = [ 11 | 'Topic :: Database', 12 | 'Programming Language :: Python', 13 | 'Intended Audience :: Developers', 14 | 'Operating System :: OS Independent', 15 | 'Programming Language :: Python :: 3.6', 16 | 'Programming Language :: Python :: 3.7', 17 | 'Programming Language :: Python :: 3.8', 18 | 'Programming Language :: Python :: 3.9', 19 | 'Programming Language :: Python :: 3.10', 20 | 'License :: OSI Approved :: BSD License', 21 | 'Development Status :: 5 - Production/Stable', 22 | ] 23 | 24 | [tool.poetry.dependencies] 25 | python = "^3.6.2" 26 | redis = "^4.2.0" 27 | SQLAlchemy = "1.4.35" 28 | pymongo = "4.1.1" # located here, because it achieves the same goal as sqlalchemy 29 | flynt = "^0.76" 30 | 31 | [tool.poetry.dev-dependencies] 32 | flake8 = "^3.9.2" 33 | bandit = "^1.7.0" 34 | vulture = "^2.3" 35 | tox = "^3.24.0" 36 | tox-poetry = "^0.4.0" 37 | tox-docker = {git = "https://github.com/chayim/tox-docker/", branch="ck-31-privs"} 38 | pytest = "^6.2.0" 39 | flake8-docstrings = "^1.6.0" 40 | mock = "^4.0.3" 41 | black = "^21.7b0" 42 | tox-pyenv = "^1.1.0" 43 | PyMySQL = "^1.0.2" 44 | cryptography = "^3.4.7" 45 | psycopg2-binary = "^2.9.3" 46 | ibm-db = "^3.1.1" 47 | ibm-db-sa = "^0.3.7" 48 | isort = "^5.10.1" 49 | 50 | [tool.pytest.ini_options] 51 | markers = [ 52 | "mysql: mysql backend tests", 53 | "postgres: postgres backend tests", 54 | "sqlite: sqlite backend tests", 55 | "mongo: mongo backend tests", 56 | "db2: db2 backend tests", 57 | ] 58 | 59 | [tool.isort] 60 | profile = "black" 61 | 62 | [build-system] 63 | requires = ["poetry-core>=1.0.6"] 64 | build-backend = "poetry.core.masonry.api" 65 | -------------------------------------------------------------------------------- /rgsync/Connectors/__init__.py: -------------------------------------------------------------------------------- 1 | from .cql_connector import CqlConnection, CqlConnector 2 | from .mongo_connector import MongoConnection, MongoConnector 3 | from .redis_connector import RedisClusterConnection, RedisConnection, RedisConnector 4 | from .simple_hash_connector import SimpleHashConnector 5 | from .sql_connectors import ( 6 | BaseSqlConnection, 7 | BaseSqlConnector, 8 | DB2Connection, 9 | DB2Connector, 10 | MsSqlConnection, 11 | MsSqlConnector, 12 | MySqlConnection, 13 | MySqlConnector, 14 | OracleSqlConnection, 15 | OracleSqlConnector, 16 | PostgresConnection, 17 | PostgresConnector, 18 | SnowflakeSqlConnection, 19 | SnowflakeSqlConnector, 20 | SQLiteConnection, 21 | SQLiteConnector, 22 | ) 23 | 24 | __all__ = [ 25 | "SimpleHashConnector", 26 | "BaseSqlConnection", 27 | "BaseSqlConnector", 28 | "DB2Connector", 29 | "DB2Connection", 30 | "MsSqlConnection", 31 | "MsSqlConnector", 32 | "MySqlConnection", 33 | "MySqlConnector", 34 | "OracleSqlConnection", 35 | "OracleSqlConnector", 36 | "PostgresConnection", 37 | "PostgresConnector", 38 | "SnowflakeSqlConnection", 39 | "SnowflakeSqlConnector", 40 | "SQLiteConnection", 41 | "SQLiteConnector", 42 | "CqlConnector", 43 | "CqlConnection", 44 | "MongoConnector", 45 | "MongoConnection", 46 | "RedisConnector", 47 | "RedisConnection", 48 | "RedisClusterConnection", 49 | ] 50 | -------------------------------------------------------------------------------- /rgsync/Connectors/cql_connector.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from redisgears import getMyHashTag as hashtag 4 | 5 | from rgsync.common import * 6 | 7 | 8 | class CqlConnection: 9 | def __init__(self, user, password, db, keyspace): 10 | self._user = user 11 | self._password = password 12 | self._db = db 13 | self._keyspace = keyspace 14 | 15 | @property 16 | def user(self): 17 | return self._user() if callable(self._user) else self._user 18 | 19 | @property 20 | def password(self): 21 | return self._password() if callable(self._password) else self._password 22 | 23 | @property 24 | def db(self): 25 | return self._db() if callable(self._db) else self._db 26 | 27 | @property 28 | def keyspace(self): 29 | return self._keyspace() if callable(self._keyspace) else self._keyspace 30 | 31 | def _getConnectionStr(self): 32 | return json.dumps( 33 | { 34 | "user": self.user, 35 | "password": self.password, 36 | "db": self.db, 37 | "keyspace": self.keyspace, 38 | } 39 | ) 40 | 41 | def Connect(self): 42 | from cassandra.auth import PlainTextAuthProvider 43 | from cassandra.cluster import Cluster 44 | 45 | ConnectionStr = self._getConnectionStr() 46 | 47 | WriteBehindLog(f"Connect: connecting db={self.db} keyspace={self.keyspace}") 48 | auth_provider = PlainTextAuthProvider( 49 | username=self.user, password=self.password 50 | ) 51 | cluster = Cluster(self.db.split(), auth_provider=auth_provider) 52 | if self.keyspace != "": 53 | session = cluster.connect(self.keyspace) 54 | else: 55 | session = cluster.connect() 56 | WriteBehindLog("Connect: Connected") 57 | return session 58 | 59 | 60 | class CqlConnector: 61 | def __init__(self, connection, tableName, pk, exactlyOnceTableName=None): 62 | self.connection = connection 63 | self.tableName = tableName 64 | self.pk = pk 65 | self.exactlyOnceTableName = exactlyOnceTableName 66 | self.exactlyOnceLastId = None 67 | self.shouldCompareId = True if self.exactlyOnceTableName is not None else False 68 | self.session = None 69 | self.supportedOperations = [OPERATION_DEL_REPLICATE, OPERATION_UPDATE_REPLICATE] 70 | 71 | def PrepereQueries(self, mappings): 72 | def GetUpdateQuery(tableName, mappings, pk): 73 | query = f"update {tableName} set " 74 | fields = [ 75 | f"{val}=?" for kk, val in mappings.items() if not kk.startswith("_") 76 | ] 77 | query += ",".join(fields) 78 | query += f" where {self.pk}=?" 79 | return query 80 | 81 | self.addQuery = GetUpdateQuery(self.tableName, mappings, self.pk) 82 | self.delQuery = f"delete from {self.tableName} where {self.pk}=?" 83 | if self.exactlyOnceTableName is not None: 84 | self.exactlyOnceQuery = GetUpdateQuery( 85 | self.exactlyOnceTableName, {"val", "val"}, "id" 86 | ) 87 | 88 | def TableName(self): 89 | return self.tableName 90 | 91 | def PrimaryKey(self): 92 | return self.pk 93 | 94 | def WriteData(self, data): 95 | if len(data) == 0: 96 | WriteBehindLog("Warning, got an empty batch") 97 | return 98 | query = None 99 | 100 | try: 101 | if not self.session: 102 | self.session = self.connection.Connect() 103 | if self.exactlyOnceTableName is not None: 104 | shardId = f"shard-{hashtag()}" 105 | result = self.session.execute( 106 | f"select val from {self.exactlyOnceTableName} where id=?", 107 | shardId, 108 | ) 109 | res = result.first() 110 | if res is not None: 111 | self.exactlyOnceLastId = str(res["val"]) 112 | else: 113 | self.shouldCompareId = False 114 | except Exception as e: 115 | self.session = None # next time we will reconnect to the database 116 | self.exactlyOnceLastId = None 117 | self.shouldCompareId = ( 118 | True if self.exactlyOnceTableName is not None else False 119 | ) 120 | msg = f'Failed connecting to Cassandra database, error="{str(e)}"' 121 | WriteBehindLog(msg) 122 | raise Exception(msg) from None 123 | 124 | idsToAck = [] 125 | 126 | try: 127 | from cassandra.cluster import BatchStatement 128 | 129 | batch = BatchStatement() 130 | isAddBatch = ( 131 | True 132 | if data[0]["value"][OP_KEY] == OPERATION_UPDATE_REPLICATE 133 | else False 134 | ) 135 | query = self.addQuery if isAddBatch else self.delQuery 136 | stmt = self.session.prepare(query) 137 | lastStreamId = None 138 | for d in data: 139 | x = d["value"] 140 | lastStreamId = d.pop( 141 | "id", None 142 | ) # pop the stream id out of the record, we do not need it 143 | if ( 144 | self.shouldCompareId 145 | and CompareIds(self.exactlyOnceLastId, lastStreamId) >= 0 146 | ): 147 | WriteBehindLog( 148 | f"Skip {lastStreamId} as it was already writen to the backend" 149 | ) 150 | continue 151 | 152 | op = x.pop(OP_KEY, None) 153 | if op not in self.supportedOperations: 154 | msg = "Got unknown operation" 155 | WriteBehindLog(msg) 156 | raise Exception(msg) from None 157 | 158 | self.shouldCompareId = False 159 | if op != OPERATION_UPDATE_REPLICATE: 160 | if isAddBatch: 161 | self.session.execute(batch) 162 | batch = BatchStatement() 163 | isAddBatch = False 164 | query = self.delQuery 165 | else: 166 | if not isAddBatch: 167 | self.session.execute(batch) 168 | batch = BatchStatement() 169 | isAddBatch = True 170 | query = self.addQuery 171 | stmt = self.session.prepare(query) 172 | batch.add(stmt.bind(x)) 173 | if len(batch) > 0: 174 | self.session.execute(batch) 175 | if self.exactlyOnceTableName is not None: 176 | stmt = self.session.prepare(self.exactlyOnceQuery) 177 | self.session.execute(stmt, {"id": shardId, "val": lastStreamId}) 178 | except Exception as e: 179 | self.session = None # next time we will reconnect to the database 180 | self.exactlyOnceLastId = None 181 | self.shouldCompareId = ( 182 | True if self.exactlyOnceTableName is not None else False 183 | ) 184 | msg = 'Got exception when writing to DB, query="%s", error="%s".' % ( 185 | (query if query else "None"), 186 | str(e), 187 | ) 188 | WriteBehindLog(msg) 189 | raise Exception(msg) from None 190 | -------------------------------------------------------------------------------- /rgsync/Connectors/mongo_connector.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from pymongo import DeleteOne, UpdateOne 4 | 5 | from rgsync.common import * 6 | 7 | 8 | class MongoConnection(object): 9 | def __init__(self, user, password, db, authSource="admin", conn_string=None): 10 | self._user = user 11 | self._passwd = password 12 | self._db = db 13 | 14 | # mongo allows one to authenticate against different databases 15 | self._authSource = authSource 16 | self._conn_string = conn_string 17 | 18 | @property 19 | def user(self): 20 | return self._user() if callable(self._user) else self._user 21 | 22 | @property 23 | def passwd(self): 24 | return self._passwd() if callable(self._passwd) else self._passwd 25 | 26 | @property 27 | def db(self): 28 | return self._db() if callable(self._db) else self._db 29 | 30 | @property 31 | def _getConnectionStr(self): 32 | if self._conn_string is not None: 33 | return self._conn_string 34 | 35 | con = "mongodb://{}:{}@{}?authSource={}".format( 36 | self.user, self.passwd, self.db, self._authSource 37 | ) 38 | return con 39 | 40 | def Connect(self): 41 | from pymongo import MongoClient 42 | 43 | WriteBehindLog("Connect: connecting") 44 | client = MongoClient(self._getConnectionStr) 45 | client.server_info() # light connection test 46 | WriteBehindLog("Connect: Connected") 47 | return client 48 | 49 | 50 | class MongoConnector: 51 | def __init__(self, connection, db, tableName, pk, exactlyOnceTableName=None): 52 | self.connection = connection 53 | self.tableName = tableName 54 | self.db = db 55 | self.pk = pk 56 | self.exactlyOnceTableName = exactlyOnceTableName 57 | self.exactlyOnceLastId = None 58 | self.shouldCompareId = True if self.exactlyOnceTableName is not None else False 59 | self.supportedOperations = [OPERATION_DEL_REPLICATE, OPERATION_UPDATE_REPLICATE] 60 | 61 | @property 62 | def collection(self): 63 | return self.connection.Connect()[self.db][self.tableName] 64 | 65 | def TableName(self): 66 | return self.tableName 67 | 68 | def PrimaryKey(self): 69 | return self.pk 70 | 71 | def DeleteQuery(self, mappings): 72 | rr = DeleteOne({self.PrimaryKey(): mappings[self.PrimaryKey()]}) 73 | return rr 74 | 75 | def AddOrUpdateQuery(self, mappings, dataKey): 76 | import json 77 | 78 | query = {k: v for k, v in mappings.items() if not k.find("_") == 0} 79 | # try to decode the nest - only one level deep given the mappings 80 | 81 | update = {} 82 | for k, v in query.items(): 83 | try: 84 | query[k] = json.loads(v.replace("'", '"')) 85 | except Exception as e: 86 | query[k] = v 87 | 88 | # flatten the key, to support partial updates 89 | if k == dataKey: 90 | update = {i: val for i, val in query.pop(k).items()} 91 | break 92 | 93 | query.update(update) 94 | 95 | rr = UpdateOne( 96 | filter={self.PrimaryKey(): mappings[self.PrimaryKey()]}, 97 | update={"$set": query}, 98 | upsert=True, 99 | ) 100 | return rr 101 | 102 | def WriteData(self, data, dataKey): 103 | if len(data) == 0: 104 | WriteBehindLog("Warning, got an empty batch") 105 | return 106 | 107 | query = None 108 | lastStreamId = None 109 | 110 | try: 111 | if self.exactlyOnceTableName is not None: 112 | shardId = f"shard-{hashtag()}" 113 | result = self.collection().find_one({"_id", shardId}) 114 | if result is not None: 115 | self.exactlyOnceLastId = result["_id"] 116 | else: 117 | self.shouldCompareId = False 118 | 119 | except Exception as e: 120 | self.exactlyOnceLastId = None 121 | self.shouldCompareId = False 122 | msg = f'Failed connecting to database, error="{str(e)}"' 123 | WriteBehindLog(msg) 124 | raise Exception(msg) from None 125 | 126 | batch = [] 127 | 128 | for d in data: 129 | x = d["value"] 130 | 131 | lastStreamId = d.pop( 132 | "id", None 133 | ) ## pop the stream id out of the record, we do not need it. 134 | if ( 135 | self.shouldCompareId 136 | and CompareIds(self.exactlyOnceLastId, lastStreamId) >= 0 137 | ): 138 | WriteBehindLog( 139 | f"Skip {lastStreamId} as it was already writen to the backend" 140 | ) 141 | 142 | op = x.pop(OP_KEY, None) 143 | if op not in self.supportedOperations: 144 | msg = "Got unknown operation" 145 | WriteBehindLog(msg) 146 | raise Exception(msg) from None 147 | 148 | self.shouldCompareId = False 149 | if op == OPERATION_DEL_REPLICATE: 150 | batch.append(self.DeleteQuery(x)) 151 | elif op == OPERATION_UPDATE_REPLICATE: 152 | batch.append(self.AddOrUpdateQuery(x, dataKey)) 153 | 154 | try: 155 | if len(batch) > 0: 156 | r = self.collection.bulk_write(batch) 157 | 158 | except Exception as e: 159 | self.exactlyOnceLastId = None 160 | self.shouldCompareId = False 161 | msg = 'Got exception when writing to DB, query="%s", error="%s".' % ( 162 | (query if query else "None"), 163 | str(e), 164 | ) 165 | WriteBehindLog(msg) 166 | raise Exception(msg) from None 167 | -------------------------------------------------------------------------------- /rgsync/Connectors/redis_connector.py: -------------------------------------------------------------------------------- 1 | from redisgears import getMyHashTag as hashtag 2 | 3 | from rgsync.common import * 4 | 5 | 6 | # redis connection class 7 | class RedisConnection: 8 | def __init__(self, host, port, password=None): 9 | self._host = host 10 | self._port = port 11 | self._password = password 12 | 13 | @property 14 | def host(self): 15 | return self._host() if callable(self._host) else self._host 16 | 17 | @property 18 | def port(self): 19 | return self._port() if callable(self._port) else self._port 20 | 21 | @property 22 | def password(self): 23 | return self._password() if callable(self._password) else self._password 24 | 25 | def Connect(self): 26 | from redis.client import Redis 27 | 28 | try: 29 | WriteBehindLog(f"Connect: connecting to {self.host}:{self.port}") 30 | r = Redis( 31 | host=self.host, 32 | port=self.port, 33 | password=self.password, 34 | decode_responses=True, 35 | ) 36 | except Exception as e: 37 | msg = f"Cannot connect to Redis. Exception: {e}" 38 | WriteBehindLog(msg) 39 | raise Exception(msg) from None 40 | return r 41 | 42 | 43 | # redis cluster connection class 44 | class RedisClusterConnection: 45 | def __init__(self, host=None, port=None, cluster_nodes=None, password=None): 46 | self._host = host 47 | self._port = port 48 | self._cluster_nodes = cluster_nodes 49 | self._password = password 50 | 51 | @property 52 | def host(self): 53 | return self._host() if callable(self._host) else self._host 54 | 55 | @property 56 | def port(self): 57 | return self._port() if callable(self._port) else self._port 58 | 59 | @property 60 | def password(self): 61 | return self._password() if callable(self._password) else self._password 62 | 63 | @property 64 | def cluster_nodes(self): 65 | return ( 66 | self._cluster_nodes() 67 | if callable(self._cluster_nodes) 68 | else self._cluster_nodes 69 | ) 70 | 71 | def Connect(self): 72 | from rediscluster.client import RedisCluster 73 | 74 | try: 75 | WriteBehindLog( 76 | "Connect: connecting to {}:{} cluster nodes: {}".format( 77 | self.host, self.port, self.cluster_nodes 78 | ) 79 | ) 80 | rc = RedisCluster( 81 | host=self.host, 82 | port=self.port, 83 | startup_nodes=self.cluster_nodes, 84 | password=self.password, 85 | decode_responses=True, 86 | ) 87 | except Exception as e: 88 | msg = f"Cannot connect to Redis Cluster. Exception: {e}" 89 | WriteBehindLog(msg) 90 | raise Exception(msg) from None 91 | return rc 92 | 93 | 94 | SIMPLE_HASH_BACKEND_PK = "HashBackendPK" 95 | SIMPLE_HASH_BACKEND_TABLE = "HashBackendTable" 96 | 97 | # redis connector class 98 | class RedisConnector: 99 | def __init__(self, connection, newPrefix, exactlyOnceTableName=None): 100 | self.connection = connection 101 | self.session = None 102 | self.new_prefix = newPrefix 103 | self.supportedOperations = [OPERATION_DEL_REPLICATE, OPERATION_UPDATE_REPLICATE] 104 | self.exactlyOnceTableName = exactlyOnceTableName 105 | self.exactlyOnceLastId = None 106 | self.shouldCompareId = True if self.exactlyOnceTableName is not None else False 107 | # Raise eception in case of exactly once property is used in RedisCluster 108 | if (self.exactlyOnceTableName is not None) and isinstance( 109 | self.connection, RedisClusterConnection 110 | ): 111 | msg = "Exactly once property is not valid for Redis cluster" 112 | raise Exception(msg) from None 113 | 114 | def TableName(self): 115 | return SIMPLE_HASH_BACKEND_TABLE 116 | 117 | def PrimaryKey(self): 118 | return SIMPLE_HASH_BACKEND_PK 119 | 120 | def WriteData(self, data): 121 | # return if no data is received to write 122 | if 0 == len(data): 123 | WriteBehindLog("Warning: in connector received empty batch to write") 124 | return 125 | 126 | if not self.session: 127 | self.session = self.connection.Connect() 128 | 129 | # in case of exactly once get last id written 130 | shardId = None 131 | try: 132 | # Get the entry corresponding to shard id in exactly once table 133 | if (self.exactlyOnceTableName is not None) and isinstance( 134 | self.connection, RedisConnection 135 | ): 136 | shardId = f"shard-{hashtag()}" 137 | res = self.session.execute_command( 138 | "HGET", self.exactlyOnceTableName, shardId 139 | ) 140 | if res is not None: 141 | self.exactlyOnceLastId = str(res) 142 | else: 143 | self.shouldCompareId = False 144 | 145 | except Exception as e: 146 | self.session = None # Next time we will connect to database 147 | self.exactlyOnceLastId = None 148 | self.shouldCompareId = ( 149 | True if self.exactlyOnceTableName is not None else False 150 | ) 151 | msg = "Exception occur while getting shard id for exactly once. Exception : {}".format( 152 | e 153 | ) 154 | WriteBehindLog(msg) 155 | raise Exception(msg) from None 156 | 157 | pipe = self.session.pipeline() 158 | try: 159 | # data is list of dictionaries 160 | # iterate over one by one and extract a dictionary and process it 161 | lastStreamId = None 162 | for d in data: 163 | d_val = d["value"] # get value of key 'value' from dictionary 164 | 165 | lastStreamId = d.pop("id", None) # pop the stream id out of the record 166 | if ( 167 | self.shouldCompareId 168 | and CompareIds(self.exactlyOnceLastId, lastStreamId) >= 0 169 | ): 170 | WriteBehindLog( 171 | f"Skip {lastStreamId} as it was already written to the backend" 172 | ) 173 | continue 174 | 175 | self.shouldCompareId = False 176 | 177 | # check operation permission, what gets replicated 178 | op = d_val.pop(OP_KEY, None) # pop the operation key out of the record 179 | if op not in self.supportedOperations: 180 | msg = "Got unknown operation" 181 | raise Exception(msg) from None 182 | 183 | pk = d_val.pop(SIMPLE_HASH_BACKEND_PK) 184 | newKey = f"{self.new_prefix}:{pk}" 185 | 186 | if op != OPERATION_UPDATE_REPLICATE: 187 | # pipeline key to delete 188 | pipe.delete(newKey) 189 | else: 190 | # pipeline key and field-value mapping to set 191 | pipe.hset(newKey, mapping=d_val) 192 | 193 | # make entry for exactly once. In case of Redis cluster exception will be raised already 194 | if (self.exactlyOnceTableName is not None) and isinstance( 195 | self.connection, RedisConnection 196 | ): 197 | l_exact_once_val = {shardId: lastStreamId} 198 | pipe.hset(self.exactlyOnceTableName, mapping=l_exact_once_val) 199 | 200 | # execute pipeline ommands 201 | pipe.execute() 202 | 203 | except Exception as e: 204 | self.session.close() 205 | self.session = None # next time we will reconnect to the database 206 | self.exactlyOnceLastId = None 207 | self.shouldCompareId = ( 208 | True if self.exactlyOnceTableName is not None else False 209 | ) 210 | msg = f"Got exception when writing to DB, Exception : {e}" 211 | WriteBehindLog(msg) 212 | raise Exception(msg) from None 213 | 214 | 215 | #################### 216 | # EOF 217 | #################### 218 | -------------------------------------------------------------------------------- /rgsync/Connectors/simple_hash_connector.py: -------------------------------------------------------------------------------- 1 | from redisgears import executeCommand as execute 2 | 3 | SIMPLE_HASH_BACKEND_PK = "SimpleHashBackendPK" 4 | SIMPLE_HASH_BACKEND_TABLE = "SimpleHashBackendTable" 5 | 6 | 7 | class SimpleHashConnector: 8 | def __init__(self, newPefix): 9 | self.newPefix = newPefix 10 | 11 | def TableName(self): 12 | return SIMPLE_HASH_BACKEND_TABLE 13 | 14 | def PrimaryKey(self): 15 | return SIMPLE_HASH_BACKEND_PK 16 | 17 | def WriteData(self, data): 18 | for e in data: 19 | pk = e.pop(SIMPLE_HASH_BACKEND_PK) 20 | streamId = e.pop("streamId") 21 | newKey = f"{self.newPefix}:{pk}" 22 | d = [[k, v] for k, v in e.items() if not k.startswith("_")] 23 | res = execute("hset", newKey, *sum(d, [])) 24 | if "ERR" in str(res): 25 | raise Exception(res) 26 | -------------------------------------------------------------------------------- /rgsync/Connectors/sql_connectors.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | from redisgears import getMyHashTag as hashtag 4 | 5 | from rgsync.common import * 6 | 7 | 8 | class BaseSqlConnection: 9 | def __init__(self, user, passwd, db): 10 | self._user = user 11 | self._passwd = passwd 12 | self._db = db 13 | 14 | @property 15 | def user(self): 16 | return self._user() if callable(self._user) else self._user 17 | 18 | @property 19 | def passwd(self): 20 | return self._passwd() if callable(self._passwd) else self._passwd 21 | 22 | @property 23 | def db(self): 24 | return self._db() if callable(self._db) else self._db 25 | 26 | def _getConnectionStr(self): 27 | raise Exception("Can not use BaseSqlConnector _getConnectionStr directly") 28 | 29 | def Connect(self): 30 | from sqlalchemy import create_engine 31 | 32 | ConnectionStr = self._getConnectionStr() 33 | 34 | WriteBehindLog("Connect: connecting") 35 | engine = create_engine(ConnectionStr).execution_options(autocommit=True) 36 | conn = engine.connect() 37 | WriteBehindLog("Connect: Connected") 38 | return conn 39 | 40 | 41 | class MySqlConnection(BaseSqlConnection): 42 | def __init__(self, user, passwd, db): 43 | BaseSqlConnection.__init__(self, user, passwd, db) 44 | 45 | def _getConnectionStr(self): 46 | return f"mysql+pymysql://{self.user}:{self.passwd}@{self.db}" 47 | 48 | 49 | class PostgresConnection(BaseSqlConnection): 50 | def __init__(self, user, passwd, db): 51 | BaseSqlConnection.__init__(self, user, passwd, db) 52 | 53 | def _getConnectionStr(self): 54 | return f"postgresql://{self.user}:{self.passwd}@{self.db}" 55 | 56 | 57 | class SQLiteConnection(BaseSqlConnection): 58 | def __init__(self, filePath): 59 | BaseSqlConnection.__init__(self, None, None, None) 60 | self._filePath = filePath 61 | 62 | @property 63 | def filePath(self): 64 | return self._filePath() if callable(self._filePath) else self._filePath 65 | 66 | def _getConnectionStr(self): 67 | return f"sqlite:////{self.filePath}?check_same_thread=False" 68 | 69 | 70 | class OracleSqlConnection(BaseSqlConnection): 71 | def __init__(self, user, passwd, db): 72 | BaseSqlConnection.__init__(self, user, passwd, db) 73 | 74 | def _getConnectionStr(self): 75 | return f"oracle://{self.user}:{self.passwd}@{self.db}" 76 | 77 | 78 | class MsSqlConnection(BaseSqlConnection): 79 | def __init__(self, user, passwd, db, server, port, driver): 80 | BaseSqlConnection.__init__(self, user, passwd, db) 81 | self._server = server 82 | self._port = port 83 | self._driver = driver 84 | 85 | @property 86 | def server(self): 87 | return self._server() if callable(self._server) else self._server 88 | 89 | @property 90 | def port(self): 91 | return self._port() if callable(self._port) else self._port 92 | 93 | @property 94 | def driver(self): 95 | return self._driver() if callable(self._driver) else self._driver 96 | 97 | def _getConnectionStr(self): 98 | return "mssql+pyodbc://{user}:{password}@{server}:{port}/{db}?driver={driver}".format( 99 | user=self.user, 100 | password=self.passwd, 101 | db=self.db, 102 | server=self.server, 103 | port=self.port, 104 | driver=self.driver, 105 | ) 106 | 107 | 108 | class SnowflakeSqlConnection(BaseSqlConnection): 109 | def __init__(self, user, passwd, db, account): 110 | BaseSqlConnection.__init__(self, user, passwd, db) 111 | self._account = account 112 | 113 | @property 114 | def account(self): 115 | return self._account() if callable(self._account) else self._account 116 | 117 | def _getConnectionStr(self): 118 | return f"snowflake://{self.user}:{self.passwd}@{self.account}/{self.db}" 119 | 120 | 121 | class DB2Connection(BaseSqlConnection): 122 | def __init__(self, user, passwd, db): 123 | BaseSqlConnection.__init__(self, user, passwd, db) 124 | 125 | def _getConnectionStr(self): 126 | return f"db2://{self.user}:{self.passwd}@{self.db}" 127 | 128 | 129 | class DB2Connection(BaseSqlConnection): 130 | def __init__(self, user, passwd, db): 131 | BaseSqlConnection.__init__(self, user, passwd, db) 132 | 133 | def _getConnectionStr(self): 134 | return f"db2://{self.user}:{self.passwd}@{self.db}" 135 | 136 | 137 | class BaseSqlConnector: 138 | def __init__(self, connection, tableName, pk, exactlyOnceTableName=None): 139 | self.connection = connection 140 | self.tableName = tableName 141 | self.pk = pk 142 | self.exactlyOnceTableName = exactlyOnceTableName 143 | self.exactlyOnceLastId = None 144 | self.shouldCompareId = True if self.exactlyOnceTableName is not None else False 145 | self.conn = None 146 | self.supportedOperations = [OPERATION_DEL_REPLICATE, OPERATION_UPDATE_REPLICATE] 147 | 148 | def PrepereQueries(self, mappings): 149 | raise Exception("Can not use BaseSqlConnector PrepereQueries directly") 150 | 151 | def TableName(self): 152 | return self.tableName 153 | 154 | def PrimaryKey(self): 155 | return self.pk 156 | 157 | def WriteData(self, data): 158 | if len(data) == 0: 159 | WriteBehindLog("Warning, got an empty batch") 160 | return 161 | query = None 162 | 163 | try: 164 | if not self.conn: 165 | from sqlalchemy.sql import text 166 | 167 | self.sqlText = text 168 | self.conn = self.connection.Connect() 169 | if self.exactlyOnceTableName is not None: 170 | shardId = f"shard-{hashtag()}" 171 | result = self.conn.execute( 172 | self.sqlText( 173 | f"select val from {self.exactlyOnceTableName} where id=:id" 174 | ), 175 | {"id": shardId}, 176 | ) 177 | res = result.first() 178 | if res is not None: 179 | self.exactlyOnceLastId = str(res["val"]) 180 | else: 181 | self.shouldCompareId = False 182 | except Exception as e: 183 | self.conn = None # next time we will reconnect to the database 184 | self.exactlyOnceLastId = None 185 | self.shouldCompareId = ( 186 | True if self.exactlyOnceTableName is not None else False 187 | ) 188 | msg = f'Failed connecting to SQL database, error="{str(e)}"' 189 | WriteBehindLog(msg) 190 | raise Exception(msg) from None 191 | 192 | idsToAck = [] 193 | 194 | trans = self.conn.begin() 195 | try: 196 | batch = [] 197 | isAddBatch = ( 198 | True 199 | if data[0]["value"][OP_KEY] == OPERATION_UPDATE_REPLICATE 200 | else False 201 | ) 202 | query = self.addQuery if isAddBatch else self.delQuery 203 | lastStreamId = None 204 | for d in data: 205 | x = d["value"] 206 | lastStreamId = d.pop( 207 | "id", None 208 | ) ## pop the stream id out of the record, we do not need it. 209 | if ( 210 | self.shouldCompareId 211 | and CompareIds(self.exactlyOnceLastId, lastStreamId) >= 0 212 | ): 213 | WriteBehindLog( 214 | f"Skip {lastStreamId} as it was already writen to the backend" 215 | ) 216 | continue 217 | 218 | op = x.pop(OP_KEY, None) 219 | if op not in self.supportedOperations: 220 | msg = "Got unknown operation" 221 | WriteBehindLog(msg) 222 | raise Exception(msg) from None 223 | 224 | self.shouldCompareId = False 225 | if ( 226 | op != OPERATION_UPDATE_REPLICATE 227 | ): # we have only key name, it means that the key was deleted 228 | if isAddBatch: 229 | self.conn.execute(self.sqlText(query), batch) 230 | batch = [] 231 | isAddBatch = False 232 | query = self.delQuery 233 | batch.append(x) 234 | else: 235 | if not isAddBatch: 236 | self.conn.execute(self.sqlText(query), batch) 237 | batch = [] 238 | isAddBatch = True 239 | query = self.addQuery 240 | batch.append(x) 241 | if len(batch) > 0: 242 | self.conn.execute(self.sqlText(query), batch) 243 | if self.exactlyOnceTableName is not None: 244 | self.conn.execute( 245 | self.sqlText(self.exactlyOnceQuery), 246 | {"id": shardId, "val": lastStreamId}, 247 | ) 248 | trans.commit() 249 | except Exception as e: 250 | try: 251 | trans.rollback() 252 | except Exception as e: 253 | WriteBehindLog("Failed rollback transaction") 254 | self.conn = None # next time we will reconnect to the database 255 | self.exactlyOnceLastId = None 256 | self.shouldCompareId = ( 257 | True if self.exactlyOnceTableName is not None else False 258 | ) 259 | msg = 'Got exception when writing to DB, query="%s", error="%s".' % ( 260 | (query if query else "None"), 261 | str(e), 262 | ) 263 | WriteBehindLog(msg) 264 | raise Exception(msg) from None 265 | 266 | 267 | class MySqlConnector(BaseSqlConnector): 268 | def __init__(self, connection, tableName, pk, exactlyOnceTableName=None): 269 | BaseSqlConnector.__init__(self, connection, tableName, pk, exactlyOnceTableName) 270 | 271 | def PrepereQueries(self, mappings): 272 | def GetUpdateQuery(tableName, mappings, pk): 273 | query = f"INSERT INTO {tableName}" 274 | values = [val for kk, val in mappings.items() if not kk.startswith("_")] 275 | values = [pk] + values 276 | values.sort() 277 | query = "%s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s" % ( 278 | query, 279 | ",".join(values), 280 | ",".join([":%s" % a for a in values]), 281 | ",".join(["%s=values(%s)" % (a, a) for a in values]), 282 | ) 283 | 284 | return query 285 | 286 | self.addQuery = GetUpdateQuery(self.tableName, mappings, self.pk) 287 | self.delQuery = f"delete from {self.tableName} where {self.pk}=:{self.pk}" 288 | if self.exactlyOnceTableName is not None: 289 | self.exactlyOnceQuery = GetUpdateQuery( 290 | self.exactlyOnceTableName, {"val", "val"}, "id" 291 | ) 292 | 293 | 294 | class PostgresConnector(BaseSqlConnector): 295 | def __init__(self, connection, tableName, pk, exactlyOnceTableName=None): 296 | BaseSqlConnector.__init__(self, connection, tableName, pk, exactlyOnceTableName) 297 | 298 | def PrepereQueries(self, mappings): 299 | def GetUpdateQuery(tableName, mappings, pk): 300 | 301 | # OrderedDicts mean the same results each time 302 | ordered_mappings = OrderedDict(mappings) 303 | cols = ",".join(ordered_mappings.values()) 304 | values = [ 305 | f":{val}" 306 | for kk, val in ordered_mappings.items() 307 | if not kk.startswith("_") 308 | ] 309 | values = list(values) + [":" + self.pk] 310 | 311 | # prepare statement 312 | value_stmt = ",".join(v for v in values) 313 | update_stmts = [ 314 | f"{v}=excluded.{v}" 315 | for v in ordered_mappings.values() 316 | if not v.startswith("_") 317 | ] 318 | query = f"""INSERT INTO {tableName} ({cols},{pk}) 319 | VALUES ({value_stmt}) 320 | ON CONFLICT({pk}) DO UPDATE 321 | SET 322 | {', '.join(update_stmts)}""" 323 | return query 324 | 325 | self.addQuery = GetUpdateQuery(self.tableName, mappings, self.pk) 326 | self.delQuery = f"delete from {self.tableName} where {self.pk}=:{self.pk}" 327 | if self.exactlyOnceTableName is not None: 328 | self.exactlyOnceQuery = GetUpdateQuery( 329 | self.exactlyOnceTableName, {"val", "val"}, "id" 330 | ) 331 | 332 | 333 | class SQLiteConnector(BaseSqlConnector): 334 | def __init__(self, connection, tableName, pk, exactlyOnceTableName=None): 335 | BaseSqlConnector.__init__(self, connection, tableName, pk, exactlyOnceTableName) 336 | 337 | def PrepereQueries(self, mappings): 338 | def GetUpdateQuery(tableName, mappings, pk): 339 | query = f"INSERT OR REPLACE INTO {tableName}" 340 | values = [val for kk, val in mappings.items() if not kk.startswith("_")] 341 | values = [pk] + values 342 | values.sort() 343 | query = "%s(%s) values(%s)" % ( 344 | query, 345 | ",".join(values), 346 | ",".join([":%s" % a for a in values]), 347 | ) 348 | return query 349 | 350 | self.addQuery = GetUpdateQuery(self.tableName, mappings, self.pk) 351 | self.delQuery = f"delete from {self.tableName} where {self.pk}=:{self.pk}" 352 | if self.exactlyOnceTableName is not None: 353 | self.exactlyOnceQuery = GetUpdateQuery( 354 | self.exactlyOnceTableName, {"val", "val"}, "id" 355 | ) 356 | 357 | 358 | class OracleSqlConnector(BaseSqlConnector): 359 | def __init__(self, connection, tableName, pk, exactlyOnceTableName=None): 360 | BaseSqlConnector.__init__(self, connection, tableName, pk, exactlyOnceTableName) 361 | 362 | def PrepereQueries(self, mappings): 363 | values = [val for kk, val in mappings.items() if not kk.startswith("_")] 364 | values_with_pkey = [self.pk] + values 365 | 366 | def GetUpdateQuery(table, pkey, values_with_pkey, values): 367 | merge_into = ( 368 | "MERGE INTO %s d USING (SELECT 1 FROM DUAL) ON (d.%s = :%s)" 369 | % (table, pkey, pkey) 370 | ) 371 | not_matched = "WHEN NOT MATCHED THEN INSERT (%s) VALUES (%s)" % ( 372 | ",".join(values_with_pkey), 373 | ",".join([":%s" % a for a in values_with_pkey]), 374 | ) 375 | matched = "WHEN MATCHED THEN UPDATE SET %s" % ( 376 | ",".join(["%s=:%s" % (a, a) for a in values]) 377 | ) 378 | query = f"{merge_into} {not_matched} {matched}" 379 | return query 380 | 381 | self.addQuery = GetUpdateQuery( 382 | self.tableName, self.pk, values_with_pkey, values 383 | ) 384 | self.delQuery = f"delete from {self.tableName} where {self.pk}=:{self.pk}" 385 | if self.exactlyOnceTableName is not None: 386 | self.exactlyOnceQuery = GetUpdateQuery( 387 | self.exactlyOnceTableName, "id", ["id", "val"], ["val"] 388 | ) 389 | 390 | 391 | class MsSqlConnector(BaseSqlConnector): 392 | def __init__(self, connection, tableName, pk, exactlyOnceTableName=None): 393 | BaseSqlConnector.__init__(self, connection, tableName, pk, exactlyOnceTableName) 394 | 395 | def PrepereQueries(self, mappings): 396 | values = [val for kk, val in mappings.items() if not kk.startswith("_")] 397 | values_with_pkey = [self.pk] + values 398 | 399 | def GetUpdateQuery(tableName, mappings, pk): 400 | merge_into = ( 401 | "MERGE %s AS Target USING (VALUES (:%s)) AS Source (key1) ON (Target.%s = Source.key1)" 402 | % (tableName, pk, pk) 403 | ) 404 | not_matched = "WHEN NOT MATCHED BY TARGET THEN INSERT (%s) VALUES (%s)" % ( 405 | ",".join(values_with_pkey), 406 | ",".join([":%s" % a for a in values_with_pkey]), 407 | ) 408 | matched = "WHEN MATCHED THEN UPDATE SET %s" % ( 409 | ",".join(["Target.%s=:%s" % (a, a) for a in values]) 410 | ) 411 | query = f"{merge_into} {not_matched} {matched};" 412 | return query 413 | 414 | self.addQuery = GetUpdateQuery(self.tableName, mappings, self.pk) 415 | self.delQuery = f"delete from {self.tableName} where {self.pk}=:{self.pk}" 416 | if self.exactlyOnceTableName is not None: 417 | self.exactlyOnceQuery = GetUpdateQuery( 418 | self.exactlyOnceTableName, {"val", "val"}, "id" 419 | ) 420 | 421 | 422 | class SnowflakeSqlConnector(OracleSqlConnector): 423 | def __init__(self, connection, tableName, pk, exactlyOnceTableName=None): 424 | OracleSqlConnector.__init__( 425 | self, connection, tableName, pk, exactlyOnceTableName 426 | ) 427 | 428 | 429 | class DB2Connector(BaseSqlConnector): 430 | def __init__(self, connection, tableName, pk, exactlyOnceTableName=None): 431 | BaseSqlConnector.__init__(self, connection, tableName, pk, exactlyOnceTableName) 432 | 433 | def PrepereQueries(self, mappings): 434 | values = [val for kk, val in mappings.items() if not kk.startswith("_")] 435 | values_with_pkey = [self.pk] + values 436 | 437 | def GetUpdateQuery(table, pkey, values_with_pkey, values): 438 | merge_into = "MERGE INTO %s d USING (VALUES 1) ON (d.%s = :%s)" % ( 439 | table, 440 | pkey, 441 | pkey, 442 | ) 443 | not_matched = "WHEN NOT MATCHED THEN INSERT (%s) VALUES (%s)" % ( 444 | ",".join(values_with_pkey), 445 | ",".join([":%s" % a for a in values_with_pkey]), 446 | ) 447 | matched = "WHEN MATCHED THEN UPDATE SET %s" % ( 448 | ",".join(["%s=:%s" % (a, a) for a in values]) 449 | ) 450 | query = f"{merge_into} {not_matched} {matched}" 451 | return query 452 | 453 | self.addQuery = GetUpdateQuery( 454 | self.tableName, self.pk, values_with_pkey, values 455 | ) 456 | self.delQuery = f"delete from {self.tableName} where {self.pk}=:{self.pk}" 457 | if self.exactlyOnceTableName is not None: 458 | self.exactlyOnceQuery = GetUpdateQuery( 459 | self.exactlyOnceTableName, "id", ["id", "val"], ["val"] 460 | ) 461 | -------------------------------------------------------------------------------- /rgsync/__init__.py: -------------------------------------------------------------------------------- 1 | from .redis_gears_write_behind import ( 2 | RGJSONWriteBehind, 3 | RGJSONWriteThrough, 4 | RGWriteBehind, 5 | RGWriteThrough, 6 | ) 7 | 8 | __all__ = [ 9 | "RGWriteBehind", 10 | "RGWriteThrough", 11 | "RGJSONWriteBehind", 12 | "RGJSONWriteThrough", 13 | ] 14 | -------------------------------------------------------------------------------- /rgsync/common.py: -------------------------------------------------------------------------------- 1 | from redisgears import getMyHashTag as hashtag 2 | from redisgears import log 3 | 4 | NAME = "WRITE_BEHIND" 5 | ORIGINAL_KEY = "_original_key" 6 | UUID_KEY = "_uuid" 7 | OP_KEY = "#" 8 | 9 | OPERATION_DEL_REPLICATE = "~" 10 | OPERATION_DEL_NOREPLICATE = "-" 11 | OPERATION_UPDATE_REPLICATE = "=" 12 | OPERATION_UPDATE_NOREPLICATE = "+" 13 | OPERATIONS = [ 14 | OPERATION_DEL_REPLICATE, 15 | OPERATION_DEL_NOREPLICATE, 16 | OPERATION_UPDATE_REPLICATE, 17 | OPERATION_UPDATE_NOREPLICATE, 18 | ] 19 | defaultOperation = OPERATION_UPDATE_REPLICATE 20 | 21 | 22 | def WriteBehindLog(msg, prefix=f"{NAME} - ", logLevel="notice"): 23 | msg = prefix + msg 24 | log(msg, level=logLevel) 25 | 26 | 27 | def WriteBehindDebug(msg): 28 | WriteBehindLog(msg, logLevel="debug") 29 | 30 | 31 | def CreateGetStreamNameCallback(uid): 32 | def GetStreamName(tableName): 33 | return "_%s-stream-%s-{%s}" % (tableName, uid, hashtag()) 34 | 35 | return GetStreamName 36 | 37 | 38 | def CompareIds(id1, id2): 39 | id1_time, id1_num = [int(a) for a in id1.split("-")] 40 | id2_time, id2_num = [int(a) for a in id2.split("-")] 41 | if id1_time > id2_time: 42 | return 1 43 | if id1_time < id2_time: 44 | return -1 45 | 46 | if id1_num > id2_num: 47 | return 1 48 | if id1_num < id2_num: 49 | return -1 50 | 51 | return 0 52 | -------------------------------------------------------------------------------- /rgsync/redis_gears_write_behind.py: -------------------------------------------------------------------------------- 1 | import json 2 | import uuid 3 | 4 | from redisgears import executeCommand as execute 5 | 6 | from rgsync.common import * 7 | 8 | ackExpireSeconds = 3600 9 | 10 | 11 | def SafeDeleteKey(key): 12 | """ 13 | Deleting a key by first renaming it so we will not trigger another execution 14 | If key does not exists we will get an execution and ignore it 15 | """ 16 | try: 17 | newKey = "__{%s}__" % key 18 | execute("RENAME", key, newKey) 19 | execute("DEL", newKey) 20 | except Exception: 21 | pass 22 | 23 | 24 | def ValidateHash(r): 25 | key = r["key"] 26 | value = r["value"] 27 | 28 | if value == None: 29 | # key without value consider delete 30 | value = {OP_KEY: OPERATION_DEL_REPLICATE} 31 | r["value"] = value 32 | else: 33 | # make sure its a hash 34 | if not (isinstance(r["value"], dict)): 35 | msg = 'Got a none hash value, key="%s" value="%s"' % ( 36 | str(r["key"]), 37 | str(r["value"] if "value" in r.keys() else "None"), 38 | ) 39 | WriteBehindLog(msg) 40 | raise Exception(msg) 41 | if OP_KEY not in value.keys(): 42 | value[OP_KEY] = defaultOperation 43 | else: 44 | # we need to delete the operation key for the hash 45 | execute("hdel", key, OP_KEY) 46 | 47 | op = value[OP_KEY] 48 | if len(op) == 0: 49 | msg = "Got no operation" 50 | WriteBehindLog(msg) 51 | raise Exception(msg) 52 | 53 | operation = op[0] 54 | 55 | if operation not in OPERATIONS: 56 | msg = f'Got unknown operations "{operation}"' 57 | WriteBehindLog(msg) 58 | raise Exception(msg) 59 | 60 | # lets extrac uuid to ack on 61 | uuid = op[1:] 62 | value[UUID_KEY] = uuid if uuid != "" else None 63 | value[OP_KEY] = operation 64 | 65 | r["value"] = value 66 | 67 | return True 68 | 69 | 70 | def ValidateJSONHash(r): 71 | key = r["key"] 72 | exists = execute("EXISTS", key) 73 | if exists == 1: 74 | r["value"] = {"sync_data": execute("JSON.GET", key)} 75 | if r["value"] == None: 76 | r["value"] = {OP_KEY: OPERATION_DEL_REPLICATE} 77 | r["value"][OP_KEY] = defaultOperation 78 | else: 79 | r["value"] = {OP_KEY: OPERATION_DEL_REPLICATE} 80 | value = r["value"] 81 | 82 | operation = value[OP_KEY][0] 83 | 84 | if operation not in OPERATIONS: 85 | msg = f'Got unknown operations "{operation}"' 86 | WriteBehindLog(msg) 87 | raise Exception(msg) 88 | 89 | # lets extrac uuid to ack on 90 | uuid = value[OP_KEY][1:] 91 | value[UUID_KEY] = uuid if uuid != "" else None 92 | value[OP_KEY] = operation 93 | r["value"] = value 94 | 95 | return r 96 | 97 | 98 | def DeleteHashIfNeeded(r): 99 | key = r["key"] 100 | operation = r["value"][OP_KEY] 101 | if operation == OPERATION_DEL_REPLICATE: 102 | SafeDeleteKey(key) 103 | 104 | 105 | def ShouldProcessHash(r): 106 | key = r["key"] 107 | value = r["value"] 108 | uuid = value[UUID_KEY] 109 | operation = value[OP_KEY] 110 | res = True 111 | 112 | if operation == OPERATION_DEL_NOREPLICATE: 113 | # we need to just delete the key but delete it directly will cause 114 | # key unwanted key space notification so we need to rename it first 115 | SafeDeleteKey(key) 116 | res = False 117 | 118 | if operation == OPERATION_UPDATE_NOREPLICATE: 119 | res = False 120 | 121 | if not res and uuid != "": 122 | # no replication to connector is needed but ack is require 123 | idToAck = "{%s}%s" % (key, uuid) 124 | execute("XADD", idToAck, "*", "status", "done") 125 | execute("EXPIRE", idToAck, ackExpireSeconds) 126 | 127 | return res 128 | 129 | 130 | def RegistrationArrToDict(registration, depth): 131 | if depth >= 2: 132 | return registration 133 | if type(registration) is not list: 134 | return registration 135 | d = {} 136 | for i in range(0, len(registration), 2): 137 | d[registration[i]] = RegistrationArrToDict(registration[i + 1], depth + 1) 138 | return d 139 | 140 | 141 | def CompareVersions(v1, v2): 142 | # None version is less then all version 143 | if v1 is None: 144 | return -1 145 | if v2 is None: 146 | return 1 147 | 148 | if v1 == "99.99.99": 149 | return 1 150 | if v2 == "99.99.99": 151 | return -1 152 | 153 | v1_major, v1_minor, v1_patch = v1.split(".") 154 | v2_major, v2_minor, v2_patch = v2.split(".") 155 | 156 | if int(v1_major) > int(v2_major): 157 | return 1 158 | elif int(v1_major) < int(v2_major): 159 | return -1 160 | 161 | if int(v1_minor) > int(v2_minor): 162 | return 1 163 | elif int(v1_minor) < int(v2_minor): 164 | return -1 165 | 166 | if int(v1_patch) > int(v2_patch): 167 | return 1 168 | elif int(v1_patch) < int(v2_patch): 169 | return -1 170 | 171 | return 0 172 | 173 | 174 | def UnregisterOldVersions(name, version): 175 | WriteBehindLog(f"Unregistering old versions of {name}") 176 | registrations = execute("rg.dumpregistrations") 177 | for registration in registrations: 178 | registrationDict = RegistrationArrToDict(registration, 0) 179 | descStr = registrationDict["desc"] 180 | try: 181 | desc = json.loads(descStr) 182 | except Exception as e: 183 | continue 184 | if "name" in desc.keys() and name in desc["name"]: 185 | WriteBehindLog( 186 | "Version auto upgrade is not atomic, make sure to use it when there is not traffic to the database (otherwise you might lose events).", 187 | logLevel="warning", 188 | ) 189 | if "version" not in desc.keys(): 190 | execute("rg.unregister", registrationDict["id"]) 191 | WriteBehindLog(f"Unregistered {registrationDict['id']}") 192 | continue 193 | v = desc["version"] 194 | if CompareVersions(version, v) > 0: 195 | execute("rg.unregister", registrationDict["id"]) 196 | WriteBehindLog(f"Unregistered {registrationDict['id']}") 197 | else: 198 | raise Exception( 199 | "Found a version which is greater or equals current version, aborting." 200 | ) 201 | WriteBehindLog("Unregistered old versions") 202 | 203 | 204 | def CreateAddToStreamFunction(self): 205 | def func(r): 206 | data = [] 207 | data.append([ORIGINAL_KEY, r["key"]]) 208 | data.append([self.connector.PrimaryKey(), r["key"].split(":")[1]]) 209 | if "value" in r.keys(): 210 | value = r["value"] 211 | uuid = value.pop(UUID_KEY, None) 212 | op = value[OP_KEY] 213 | data.append([OP_KEY, op]) 214 | keys = value.keys() 215 | if uuid is not None: 216 | data.append([UUID_KEY, uuid]) 217 | if op == OPERATION_UPDATE_REPLICATE: 218 | for kInHash, kInDB in self.mappings.items(): 219 | if kInHash.startswith("_"): 220 | continue 221 | if kInHash not in keys: 222 | msg = "AddToStream: Could not find %s in hash %s" % ( 223 | kInHash, 224 | r["key"], 225 | ) 226 | WriteBehindLog(msg) 227 | raise Exception(msg) 228 | data.append([kInDB, value[kInHash]]) 229 | execute( 230 | "xadd", self.GetStreamName(self.connector.TableName()), "*", *sum(data, []) 231 | ) 232 | 233 | return func 234 | 235 | 236 | def CreateWriteDataFunction(connector, dataKey=None): 237 | def func(data): 238 | idsToAck = [] 239 | for d in data: 240 | originalKey = d["value"].pop(ORIGINAL_KEY, None) 241 | uuid = d["value"].pop(UUID_KEY, None) 242 | if uuid is not None and uuid != "": 243 | idsToAck.append("{%s}%s" % (originalKey, uuid)) 244 | 245 | # specifically, to not updating all the old WriteData calls 246 | # due to JSON 247 | if dataKey is None: 248 | connector.WriteData(data) 249 | else: 250 | connector.WriteData(data, dataKey) 251 | 252 | for idToAck in idsToAck: 253 | execute("XADD", idToAck, "*", "status", "done") 254 | execute("EXPIRE", idToAck, ackExpireSeconds) 255 | 256 | return func 257 | 258 | 259 | class RGWriteBase: 260 | def __init__(self, mappings, connector, name, version=None): 261 | UnregisterOldVersions(name, version) 262 | 263 | self.connector = connector 264 | self.mappings = mappings 265 | 266 | try: 267 | self.connector.PrepereQueries(self.mappings) 268 | except Exception as e: 269 | # cases like mongo, that don't implement this, silence the warning 270 | if "object has no attribute 'PrepereQueries'" in str(e): 271 | return 272 | WriteBehindLog(f'Skip calling PrepereQueries of connector, err="{str(e)}"') 273 | 274 | 275 | def DeleteKeyIfNeeded(r): 276 | if r["value"][OP_KEY] == OPERATION_DEL_REPLICATE: 277 | # we need to just delete the key but delete it directly will cause 278 | # key unwanted key space notification so we need to rename it first 279 | SafeDeleteKey(r["key"]) 280 | 281 | 282 | def PrepareRecord(r): 283 | key = r["key"] 284 | value = r["value"] 285 | 286 | realKey = key.split("{")[1].split("}")[0] 287 | 288 | realVal = execute("hgetall", realKey) 289 | realVal = {realVal[i]: realVal[i + 1] for i in range(0, len(realVal), 2)} 290 | 291 | realVal.update(value) 292 | 293 | # delete temporary key 294 | execute("del", key) 295 | 296 | return {"key": realKey, "value": realVal} 297 | 298 | 299 | def TryWriteToTarget(self): 300 | func = CreateWriteDataFunction(self.connector) 301 | 302 | def f(r): 303 | key = r["key"] 304 | value = r["value"] 305 | keys = value.keys() 306 | uuid = value.pop(UUID_KEY, None) 307 | idToAck = "{%s}%s" % (r["key"], uuid) 308 | try: 309 | operation = value[OP_KEY] 310 | mappedValue = {} 311 | mappedValue[ORIGINAL_KEY] = key 312 | mappedValue[self.connector.PrimaryKey()] = key.split(":")[1] 313 | mappedValue[UUID_KEY] = uuid 314 | mappedValue[OP_KEY] = operation 315 | if operation == OPERATION_UPDATE_REPLICATE: 316 | for kInHash, kInDB in self.mappings.items(): 317 | if kInHash.startswith("_"): 318 | continue 319 | if kInHash not in keys: 320 | msg = f"Could not find {kInHash} in hash {r['key']}" 321 | WriteBehindLog(msg) 322 | raise Exception(msg) 323 | mappedValue[kInDB] = value[kInHash] 324 | func([{"value": mappedValue}]) 325 | except Exception as e: 326 | WriteBehindLog(f"Failed writing data to the database, error='{str(e)}'") 327 | # lets update the ack stream to failure 328 | if uuid is not None and uuid != "": 329 | execute("XADD", idToAck, "*", "status", "failed", "error", str(e)) 330 | execute("EXPIRE", idToAck, ackExpireSeconds) 331 | return False 332 | return True 333 | 334 | return f 335 | 336 | 337 | def UpdateHash(r): 338 | key = r["key"] 339 | value = r["value"] 340 | operation = value.pop(OP_KEY, None) 341 | uuid_key = value.pop(UUID_KEY, None) 342 | if operation == OPERATION_DEL_REPLICATE or operation == OPERATION_DEL_NOREPLICATE: 343 | SafeDeleteKey(key) 344 | elif operation == OPERATION_UPDATE_REPLICATE or OPERATION_UPDATE_NOREPLICATE: 345 | # we need to write to temp key and then rename so we will not 346 | # trigger another execution 347 | tempKeyName = "temp-{%s}" % key 348 | elemets = [] 349 | for k, v in value.items(): 350 | elemets.append(k) 351 | elemets.append(v) 352 | execute("hset", tempKeyName, *elemets) 353 | execute("rename", tempKeyName, key) 354 | else: 355 | msg = "Unknown operation" 356 | WriteBehindLog(msg) 357 | raise Exception(msg) 358 | 359 | 360 | def WriteNoReplicate(r): 361 | if ShouldProcessHash(r): 362 | # return true means hash should be replicate and we need to 363 | # continue processing it 364 | return True 365 | # No need to replicate hash, just write it correctly to redis 366 | operation = r["value"][OP_KEY] 367 | if operation == OPERATION_UPDATE_NOREPLICATE: 368 | UpdateHash(r) 369 | elif operation == OPERATION_DEL_NOREPLICATE: 370 | # OPERATION_DEL_NOREPLICATE was handled by ShouldProcessHash function 371 | pass 372 | else: 373 | msg = "Unknown operation" 374 | WriteBehindLog(msg) 375 | raise Exception(msg) 376 | return False 377 | 378 | 379 | class RGWriteBehind(RGWriteBase): 380 | def __init__( 381 | self, 382 | GB, 383 | keysPrefix, 384 | mappings, 385 | connector, 386 | name, 387 | version=None, 388 | onFailedRetryInterval=5, 389 | batch=100, 390 | duration=100, 391 | transform=lambda r: r, 392 | eventTypes=["hset", "hmset", "del", "change"], 393 | ): 394 | """ 395 | Register a write behind execution to redis gears 396 | 397 | GB - The Gears builder object 398 | 399 | keysPrefix - Prefix on keys to register on 400 | 401 | mappings - a dictionary in the following format 402 | { 403 | 'name-on-redis-hash1':'name-on-connector-table1', 404 | 'name-on-redis-hash2':'name-on-connector-table2', 405 | . 406 | . 407 | . 408 | } 409 | 410 | connector - a connector object that implements the following methods 411 | 1. TableName() - returns the name of the table to write the data to 412 | 2. PrimaryKey() - returns the name of the public key of the relevant table 413 | 3. PrepereQueries(mappings) - will be called at start to allow the connector to 414 | prepare the queries. This function is not mandatory and will be called only 415 | if exists. 416 | 4. WriteData(data) - 417 | data is a list of dictionaries of the following format 418 | 419 | { 420 | 'streamId':'value' 421 | 'name-of-column':'value-of-column', 422 | 'name-of-column':'value-of-column', 423 | . 424 | . 425 | 426 | } 427 | 428 | The streamId is a unique id of the dictionary and can be used by the 429 | connector to achieve exactly once property. The idea is to write the 430 | last streamId of a batch into another table. When new connection 431 | established, this streamId should be read from the database and 432 | data with lower stream id should be ignored 433 | The stream id is in a format of '-' so there 434 | is a total order between all streamIds 435 | 436 | The WriteData function should write all the entries in the list to the database 437 | and return. On error it should raise exception. 438 | 439 | This function should ignore keys that starts with '_' 440 | 441 | name - The name of the created registration. This name will be used to find old version 442 | and remove them. 443 | 444 | version - The version to set to the new created registration. Old versions with the same 445 | name will be removed. 99.99.99 is greater then any other version (even from itself). 446 | 447 | batch - the batch size on which data will be writen to target 448 | 449 | duration - interval in ms in which data will be writen to target even if batch size did not reached 450 | 451 | onFailedRetryInterval - Interval on which to performe retry on failure. 452 | 453 | transform - A function that accepts as input a redis record and returns a hash 454 | 455 | eventTypes - The events for which to trigger 456 | """ 457 | UUID = str(uuid.uuid4()) 458 | self.GetStreamName = CreateGetStreamNameCallback(UUID) 459 | 460 | RGWriteBase.__init__(self, mappings, connector, name, version) 461 | 462 | ## create the execution to write each changed key to stream 463 | descJson = { 464 | "name": f"{name}.KeysReader", 465 | "version": version, 466 | "desc": f"add each changed key with prefix {keysPrefix}:* to Stream", 467 | } 468 | GB("KeysReader", desc=json.dumps(descJson)).map(transform).filter( 469 | ValidateHash 470 | ).filter(ShouldProcessHash).foreach(DeleteHashIfNeeded).foreach( 471 | CreateAddToStreamFunction(self) 472 | ).register( 473 | mode="sync", 474 | prefix=f"{keysPrefix}:*", 475 | eventTypes=eventTypes, 476 | convertToStr=False, 477 | ) 478 | 479 | ## create the execution to write each key from stream to DB 480 | descJson = { 481 | "name": f"{name}.StreamReader", 482 | "version": version, 483 | "desc": "read from stream and write to DB table %s" 484 | % self.connector.TableName(), 485 | } 486 | GB("StreamReader", desc=json.dumps(descJson)).aggregate( 487 | [], lambda a, r: a + [r], lambda a, r: a + r 488 | ).foreach(CreateWriteDataFunction(self.connector)).count().register( 489 | prefix=f"_{self.connector.TableName()}-stream-{UUID}-*", 490 | mode="async_local", 491 | batch=batch, 492 | duration=duration, 493 | onFailedPolicy="retry", 494 | onFailedRetryInterval=onFailedRetryInterval, 495 | convertToStr=False, 496 | ) 497 | 498 | 499 | class RGWriteThrough(RGWriteBase): 500 | def __init__(self, GB, keysPrefix, mappings, connector, name, version=None): 501 | RGWriteBase.__init__(self, mappings, connector, name, version) 502 | 503 | ## create the execution to write each changed key to database 504 | descJson = { 505 | "name": f"{name}.KeysReader", 506 | "version": version, 507 | "desc": "write each changed key directly to databse", 508 | } 509 | GB("KeysReader", desc=json.dumps(descJson)).map(PrepareRecord).filter( 510 | ValidateHash 511 | ).filter(WriteNoReplicate).filter(TryWriteToTarget(self)).foreach( 512 | UpdateHash 513 | ).register( 514 | mode="sync", 515 | prefix=f"{keysPrefix}*", 516 | eventTypes=["hset", "hmset"], 517 | convertToStr=False, 518 | ) 519 | 520 | 521 | GEARSDATAKEY = "redisgears" 522 | 523 | 524 | class RGJSONWriteBehind(RGWriteBase): 525 | # JSONWrite Behind 526 | # The big deal is that: 527 | # 1. It calls ValidateJSONHash instead of ValidateHash 528 | # 2. The init requires a data key, in order to go through the sub map and update 529 | # within the JSON document. 530 | def __init__( 531 | self, 532 | GB, 533 | keysPrefix, 534 | connector, 535 | name, 536 | version=None, 537 | onFailedRetryInterval=5, 538 | batch=100, 539 | duration=100, 540 | eventTypes=[ 541 | "json.set", 542 | "json.del", 543 | "json.strappend", 544 | "json.arrinsert", 545 | "json.arrappend", 546 | "json.arrtrim", 547 | "json.arrpop", 548 | "change", 549 | "del", 550 | ], 551 | dataKey=GEARSDATAKEY, 552 | ): 553 | 554 | mappings = {"sync_data": dataKey} 555 | UUID = str(uuid.uuid4()) 556 | self.GetStreamName = CreateGetStreamNameCallback(UUID) 557 | 558 | RGWriteBase.__init__(self, mappings, connector, name, version) 559 | 560 | # ## create the execution to write each changed key to stream 561 | descJson = { 562 | "name": f"{name}.KeysReader", 563 | "version": version, 564 | "desc": f"add each changed key with prefix {keysPrefix}:* to Stream", 565 | } 566 | 567 | GB("KeysReader", desc=json.dumps(descJson)).filter(ValidateJSONHash).filter( 568 | ShouldProcessHash 569 | ).foreach(DeleteHashIfNeeded).foreach(CreateAddToStreamFunction(self)).register( 570 | mode="sync", prefix=f"{keysPrefix}:*", eventTypes=eventTypes 571 | ) 572 | 573 | # ## create the execution to write each key from stream to DB 574 | descJson = { 575 | "name": f"{name}.StreamReader", 576 | "version": version, 577 | "desc": "read from stream and write to DB table %s" 578 | % self.connector.TableName(), 579 | } 580 | GB("StreamReader", desc=json.dumps(descJson)).aggregate( 581 | [], lambda a, r: a + [r], lambda a, r: a + r 582 | ).foreach(CreateWriteDataFunction(self.connector, dataKey)).count().register( 583 | prefix=f"_{self.connector.TableName()}-stream-{UUID}-*", 584 | mode="async_local", 585 | batch=batch, 586 | duration=duration, 587 | onFailedPolicy="retry", 588 | onFailedRetryInterval=onFailedRetryInterval, 589 | ) 590 | 591 | 592 | class RGJSONWriteThrough(RGWriteBase): 593 | def __init__( 594 | self, GB, keysPrefix, connector, name, version=None, dataKey=GEARSDATAKEY 595 | ): 596 | mappings = {"sync_data": dataKey} 597 | RGWriteBase.__init__(self, mappings, connector, name, version) 598 | 599 | ## create the execution to write each changed key to database 600 | descJson = { 601 | "name": f"{name}.KeysReader", 602 | "version": version, 603 | "desc": "write each changed key directly to databse", 604 | } 605 | GB("KeysReader", desc=json.dumps(descJson)).map(PrepareRecord).filter( 606 | ValidateJSONHash 607 | ).filter(WriteNoReplicate).filter(TryWriteToTarget(self)).foreach( 608 | UpdateHash 609 | ).register( 610 | mode="sync", 611 | prefix=f"{keysPrefix}*", 612 | eventTypes=[ 613 | "json.set", 614 | "json.del", 615 | "json.strappend", 616 | "json.arrinsert", 617 | "json.arrappend", 618 | "json.arrtrim", 619 | "json.arrpop", 620 | "change", 621 | "del", 622 | ], 623 | ) 624 | -------------------------------------------------------------------------------- /sbin/db2wait.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | for i in `seq 1 10`; do 4 | docker logs db2|grep "Setup has completed" 5 | if [ $? -eq 0 ]; then 6 | exit 0 7 | fi 8 | sleep 60 9 | done 10 | docker logs db2 11 | exit 1 12 | -------------------------------------------------------------------------------- /sbin/deploy-artifacts: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" 4 | ROOT=$(cd $HERE/..; pwd) 5 | 6 | S3_DIR=s3://redismodules/rgsync/ 7 | 8 | trim() { 9 | local s2 s="$*" 10 | until s2="${s#[[:space:]]}"; [ "$s2" = "$s" ]; do s="$s2"; done 11 | until s2="${s%[[:space:]]}"; [ "$s2" = "$s" ]; do s="$s2"; done 12 | echo "$s" 13 | } 14 | 15 | export AWS_ACCESS_KEY_ID=$(trim "$AWS_ACCESS_KEY_ID") 16 | export AWS_SECRET_ACCESS_KEY=$(trim "$AWS_SECRET_ACCESS_KEY") 17 | 18 | for f in $ROOT/bin/artifacts/*.zip; do 19 | aws s3 cp $f $S3_DIR --acl public-read 20 | done 21 | -------------------------------------------------------------------------------- /sbin/setup-gears: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ex 4 | 5 | VERSION=${VERSION:-master} 6 | PLATFORM=${PLATFORM:-linux-bionic-x64} 7 | 8 | S3_URL=http://redismodules.s3.amazonaws.com/redisgears/snapshots 9 | 10 | HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" 11 | 12 | d=$(mktemp -d /tmp/gears.XXXXXX) 13 | cd $d 14 | 15 | mkdir -p /var/opt/redislabs/modules/rg 16 | 17 | wget -O gears.zip $S3_URL/redisgears.${PLATFORM}.${VERSION}.zip 18 | unzip gears.zip 19 | mv redisgears.so /var/opt/redislabs/modules/rg/ 20 | 21 | wget -O deps.tgz $S3_URL/redisgears-python.${PLATFORM}.${VERSION}.tgz 22 | tar -xzf deps.tgz -C /var/opt/redislabs/modules/rg 23 | 24 | cd $HERE 25 | rm -rf $d 26 | -------------------------------------------------------------------------------- /sbin/system-setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | import os 5 | import argparse 6 | 7 | HERE = os.path.abspath(os.path.dirname(__file__)) 8 | ROOT = os.path.abspath(os.path.join(HERE, "..")) 9 | READIES = os.path.join(ROOT, "deps/readies") 10 | sys.path.insert(0, READIES) 11 | import paella 12 | 13 | #---------------------------------------------------------------------------------------------- 14 | 15 | class RGSyncSetup(paella.Setup): 16 | def __init__(self, nop=False): 17 | paella.Setup.__init__(self, nop) 18 | 19 | def common_first(self): 20 | self.install_downloaders() 21 | self.pip_install("wheel virtualenv") 22 | self.pip_install("setuptools --upgrade") 23 | 24 | self.pip_install(f"-r {READIES}/paella/requirements.txt") 25 | self.install("git zip unzip") 26 | 27 | def debian_compat(self): 28 | if self.osnick == 'bionic': 29 | self.install("mysql-server") 30 | 31 | def redhat_compat(self): 32 | self.install("redhat-lsb-core") 33 | self.run(f"{READIES}/bin/enable-utf8") 34 | self.run("yum reinstall -y glibc-common") 35 | 36 | def fedora(self): 37 | pass 38 | 39 | def macos(self): 40 | self.install_gnu_utils() 41 | 42 | def common_last(self): 43 | self.pip_install("--no-cache-dir git+https://github.com/Grokzen/redis-py-cluster.git@master") 44 | self.pip_install("--no-cache-dir git+https://github.com/RedisLabsModules/RLTest.git@master") 45 | self.pip_install("git+https://github.com/RedisGears/gears-cli.git") 46 | 47 | #---------------------------------------------------------------------------------------------- 48 | 49 | parser = argparse.ArgumentParser(description='Set up system for build.') 50 | parser.add_argument('-n', '--nop', action="store_true", help='no operation') 51 | args = parser.parse_args() 52 | 53 | RGSyncSetup(nop=args.nop).setup() 54 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import toml 4 | 5 | 6 | def find_package(): 7 | """Find the appropriate package for installation.""" 8 | 9 | # build the path to the built rgsync, as it is in the docker 10 | ll = toml.load("pyproject.toml") 11 | version = ll["tool"]["poetry"]["version"] 12 | rgsync_pkg = f"rgsync-{version}-py3-none-any.whl" 13 | 14 | # determine whether or not we're running in a docker 15 | in_docker = False 16 | if os.path.isfile("/.dockerenv") or os.environ.get("IN_DOCKER", None) is not None: 17 | in_docker = True 18 | 19 | # install package 20 | if in_docker: 21 | pkg = os.path.join("/build", "dist", rgsync_pkg) 22 | else: 23 | if os.path.join(os.getcwd(), "dist", rgsync_pkg): 24 | pkg = os.path.join(os.getcwd(), "dist", rgsync_pkg) 25 | else: 26 | pkg = "rgsync" 27 | 28 | return pkg 29 | 30 | 31 | def to_utf(d): 32 | # if isinstance(d, str): 33 | # return d.encode('utf-8') 34 | if isinstance(d, bytes): 35 | return d.decode() 36 | if isinstance(d, dict): 37 | return {to_utf(k): to_utf(v) for k, v in d.items()} 38 | if isinstance(d, list): 39 | return [to_utf(x) for x in d] 40 | return d 41 | -------------------------------------------------------------------------------- /tests/init-mongo.js: -------------------------------------------------------------------------------- 1 | db.auth(_getEnv("MONGO_INITDB_ROOT_USERNAME"), _getEnv("MONGO_INITDB_ROOT_PASSWORD")); 2 | 3 | db = db.getSiblingDB(_getEnv("MONGO_DB")); 4 | 5 | db.createUser({ 6 | user: _getEnv("MONGO_INITDB_ROOT_USERNAME"), 7 | pwd: _getEnv("MONGO_INITDB_ROOT_PASSWORD"), 8 | roles: [ 9 | { 10 | role: 'root', 11 | db: 'admin', 12 | }, 13 | ], 14 | }); 15 | -------------------------------------------------------------------------------- /tests/test_mongowritebehind.py: -------------------------------------------------------------------------------- 1 | import json 2 | import random 3 | import string 4 | import time 5 | 6 | import pytest 7 | import tox 8 | 9 | # from RLTest import Env 10 | from pymongo import MongoClient 11 | from redis import Redis 12 | 13 | from tests import find_package 14 | 15 | 16 | @pytest.mark.mongo 17 | class TestMongoJSON: 18 | def teardown_method(self): 19 | self.dbconn.drop_database(self.DBNAME) 20 | self.env.flushall() 21 | 22 | @classmethod 23 | def setup_class(cls): 24 | cls.env = Redis(decode_responses=True) 25 | 26 | pkg = find_package() 27 | 28 | # connection info 29 | r = tox.config.parseconfig(open("tox.ini").read()) 30 | docker = r._docker_container_configs["mongo"]["environment"] 31 | dbuser = docker["MONGO_INITDB_ROOT_USERNAME"] 32 | dbpasswd = docker["MONGO_INITDB_ROOT_PASSWORD"] 33 | db = docker["MONGO_DB"] 34 | 35 | con = f"mongodb://{dbuser}:{dbpasswd}@172.17.0.1:27017/{db}?authSource=admin" 36 | 37 | script = """ 38 | from rgsync import RGJSONWriteBehind, RGJSONWriteThrough 39 | from rgsync.Connectors import MongoConnector, MongoConnection 40 | 41 | connection = MongoConnection('%s', '%s', '172.17.0.1:27017/%s') 42 | db = '%s' 43 | 44 | jConnector = MongoConnector(connection, db, 'persons', 'person_id') 45 | 46 | RGJSONWriteBehind(GB, keysPrefix='person', 47 | connector=jConnector, name='PersonsWriteBehind', 48 | version='99.99.99') 49 | 50 | RGJSONWriteThrough(GB, keysPrefix='__', connector=jConnector, 51 | name='JSONWriteThrough', version='99.99.99') 52 | """ % ( 53 | dbuser, 54 | dbpasswd, 55 | db, 56 | db, 57 | ) 58 | cls.env.execute_command("RG.PYEXECUTE", script, "REQUIREMENTS", pkg, "pymongo") 59 | 60 | e = MongoClient(con) 61 | 62 | # # tables are only created upon data use - so this is our equivalent 63 | # # for mongo 64 | assert "version" in e.server_info().keys() 65 | cls.dbconn = e 66 | cls.DBNAME = db 67 | 68 | def _sampledata(self): 69 | d = {"some": "value", "and another": ["set", "of", "values"]} 70 | return d 71 | 72 | def _base_writebehind_validation(self): 73 | self.env.execute_command( 74 | "json.set", "person:1", ".", json.dumps(self._sampledata()) 75 | ) 76 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 77 | count = 0 78 | while len(result) == 0: 79 | time.sleep(0.1) 80 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 81 | if count == 10: 82 | assert False == True, "Failed writing data to mongo" 83 | break 84 | count += 1 85 | 86 | assert "gears" not in result[0].keys() 87 | assert 1 == int(result[0]["person_id"]) 88 | assert "value" == result[0]["some"] 89 | assert ["set", "of", "values"] == result[0]["and another"] 90 | 91 | def testSimpleWriteBehind(self): 92 | self._base_writebehind_validation() 93 | 94 | self.env.execute_command("json.del", "person:1") 95 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 96 | count = 0 97 | while len(result) != 0: 98 | time.sleep(0.1) 99 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 100 | if count == 10: 101 | assert False == True, "Failed deleting data from mongo" 102 | break 103 | count += 1 104 | 105 | def testGiantWriteBehind(self): 106 | large_blob = { 107 | "firstName": "Just", 108 | "lastName": "Aperson", 109 | "age": 24, 110 | "address": { 111 | "streetAddress": "123 Fake Street", 112 | "city": "Springfield", 113 | "state": "IL", 114 | "postalCode": "123456", 115 | }, 116 | "phoneNumbers": [{"type": "home", "number": "1234567890"}], 117 | "GlossTerm": "Standard Generalized Markup Language", 118 | "Acronym": "SGML", 119 | "Abbrev": "ISO 8879:1986", 120 | "GlossDef": { 121 | "para": "A meta-markup language, used to create markup languages such as DocBook.", 122 | "GlossSeeAlso": ["GML", "XML"], 123 | }, 124 | "GlossSee": "markup", 125 | } 126 | 127 | for i in range(1, 255): 128 | key = "".join(random.choices(string.ascii_uppercase + string.digits, k=15)) 129 | val = "".join(random.choices(string.ascii_uppercase + string.digits, k=20)) 130 | large_blob[key] = val 131 | 132 | self.env.execute_command("json.set", "person:1", ".", json.dumps(large_blob)) 133 | 134 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 135 | count = 0 136 | while len(result) == 0: 137 | time.sleep(0.1) 138 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 139 | if count == 10: 140 | assert False == True, "Failed writing data to mongo" 141 | break 142 | count += 1 143 | 144 | for key in large_blob: 145 | assert key in result[0].keys() 146 | assert result[0][key] == large_blob[key] 147 | 148 | def testStraightDelete(self): 149 | self._base_writebehind_validation() 150 | self.env.execute_command("del", "person:1") 151 | 152 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 153 | count = 0 154 | while len(result) != 0: 155 | time.sleep(0.1) 156 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 157 | if count == 10: 158 | assert False == True, "Failed deleting data from mongo" 159 | break 160 | count += 1 161 | 162 | def testSimpleWriteThroughPartialUpdate(self): 163 | self._base_writebehind_validation() 164 | 165 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 166 | 167 | ud = {"some": "not a value!"} 168 | self.env.execute_command("json.set", "person:1", ".", json.dumps(ud)) 169 | 170 | # need replication time 171 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 172 | count = 0 173 | while count != 10: 174 | time.sleep(0.1) 175 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 176 | if result[0]["some"] == "not a value!": 177 | break 178 | else: 179 | count += 1 180 | 181 | if count == 10: 182 | assert False == True, "Failed to update sub value!" 183 | 184 | assert result[0]["person_id"] == "1" 185 | 186 | def testUpdatingWithFieldsNotInMap(self): 187 | self._base_writebehind_validation() 188 | 189 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 190 | 191 | ud = {"somerandomthing": "this too is random!"} 192 | self.env.execute_command("json.set", "person:1", ".", json.dumps(ud)) 193 | 194 | # need replication time 195 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 196 | count = 0 197 | while count != 10: 198 | time.sleep(0.1) 199 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 200 | if "somerandomthing" not in result[0].keys(): 201 | count += 1 202 | else: 203 | assert result[0]["somerandomthing"] == "this too is random!" 204 | break 205 | 206 | if count == 10: 207 | assert False == True, "Failed to update sub value!" 208 | 209 | assert result[0]["person_id"] == "1" 210 | 211 | 212 | @pytest.mark.mongo 213 | class TestMongoConnString(TestMongoJSON): 214 | """Mongo tests, using a connection string for the database side.""" 215 | 216 | @classmethod 217 | def setup_class(cls): 218 | cls.env = Redis(decode_responses=True) 219 | 220 | pkg = find_package() 221 | 222 | # connection info 223 | r = tox.config.parseconfig(open("tox.ini").read()) 224 | docker = r._docker_container_configs["mongo"]["environment"] 225 | dbuser = docker["MONGO_INITDB_ROOT_USERNAME"] 226 | dbpasswd = docker["MONGO_INITDB_ROOT_PASSWORD"] 227 | db = docker["MONGO_DB"] 228 | 229 | con = f"mongodb://{dbuser}:{dbpasswd}@172.17.0.1:27017/{db}?authSource=admin" 230 | 231 | script = f""" 232 | from rgsync import RGJSONWriteBehind, RGJSONWriteThrough 233 | from rgsync.Connectors import MongoConnector, MongoConnection 234 | 235 | db = '{db}' 236 | conn_string = '{con}' 237 | connection = MongoConnection(None, None, db, None, conn_string) 238 | 239 | jConnector = MongoConnector(connection, db, 'persons', 'person_id') 240 | 241 | RGJSONWriteBehind(GB, keysPrefix='person', 242 | connector=jConnector, name='PersonsWriteBehind', 243 | version='99.99.99') 244 | 245 | RGJSONWriteThrough(GB, keysPrefix='__', connector=jConnector, 246 | name='JSONWriteThrough', version='99.99.99') 247 | """ 248 | cls.env.execute_command("RG.PYEXECUTE", script, "REQUIREMENTS", pkg, "pymongo") 249 | 250 | e = MongoClient(con) 251 | 252 | # # tables are only created upon data use - so this is our equivalent 253 | # # for mongo 254 | assert "version" in e.server_info().keys() 255 | cls.dbconn = e 256 | cls.DBNAME = db 257 | 258 | 259 | @pytest.mark.mongo 260 | class TestMongoJSONDualKeys: 261 | def teardown_method(self): 262 | self.dbconn.drop_database(self.DBNAME) 263 | self.env.flushall() 264 | 265 | @classmethod 266 | def setup_class(cls): 267 | cls.env = Redis(decode_responses=True) 268 | 269 | pkg = find_package() 270 | 271 | # connection info 272 | r = tox.config.parseconfig(open("tox.ini").read()) 273 | docker = r._docker_container_configs["mongo"]["environment"] 274 | dbuser = docker["MONGO_INITDB_ROOT_USERNAME"] 275 | dbpasswd = docker["MONGO_INITDB_ROOT_PASSWORD"] 276 | db = docker["MONGO_DB"] 277 | 278 | con = f"mongodb://{dbuser}:{dbpasswd}@172.17.0.1:27017/{db}?authSource=admin" 279 | 280 | script = """ 281 | from rgsync import RGJSONWriteBehind, RGJSONWriteThrough 282 | from rgsync.Connectors import MongoConnector, MongoConnection 283 | 284 | connection = MongoConnection('%s', '%s', '172.17.0.1:27017/%s') 285 | db = '%s' 286 | 287 | jConnector = MongoConnector(connection, db, 'persons', 'person_id') 288 | 289 | RGJSONWriteBehind(GB, keysPrefix='person', 290 | connector=jConnector, name='PersonsWriteBehind', 291 | version='99.99.99') 292 | 293 | RGJSONWriteThrough(GB, keysPrefix='__', connector=jConnector, 294 | name='JSONWriteThrough', version='99.99.99') 295 | 296 | secondConnector = MongoConnector(connection, db, 'secondthings', 'thing_id') 297 | RGJSONWriteBehind(GB, keysPrefix='thing', 298 | connector=secondConnector, name='SecondThingWriteBehind', 299 | version='99.99.99') 300 | 301 | RGJSONWriteThrough(GB, keysPrefix='__', connector=secondConnector, 302 | name='SecondJSONWriteThrough', version='99.99.99') 303 | 304 | """ % ( 305 | dbuser, 306 | dbpasswd, 307 | db, 308 | db, 309 | ) 310 | cls.env.execute_command("RG.PYEXECUTE", script, "REQUIREMENTS", pkg, "pymongo") 311 | 312 | e = MongoClient(con) 313 | 314 | # # tables are only created upon data use - so this is our equivalent 315 | # # for mongo 316 | assert "version" in e.server_info().keys() 317 | cls.dbconn = e 318 | cls.DBNAME = db 319 | 320 | def _sampledata(self): 321 | d = {"some": "value", "and another": ["set", "of", "values"]} 322 | return d 323 | 324 | def testSimpleWriteBehind(self): 325 | self.env.execute_command( 326 | "json.set", "person:1", ".", json.dumps(self._sampledata()) 327 | ) 328 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 329 | while len(result) == 0: 330 | time.sleep(0.1) 331 | result = list(self.dbconn[self.DBNAME]["persons"].find()) 332 | 333 | assert "gears" not in result[0].keys() 334 | assert 1 == int(result[0]["person_id"]) 335 | assert "value" == result[0]["some"] 336 | assert ["set", "of", "values"] == result[0]["and another"] 337 | 338 | ddd = {"hello": "there", "myname": "is simon!", "well": ["is", "that", "fun"]} 339 | self.env.execute_command("json.set", "thing:1", ".", json.dumps(ddd)) 340 | result = list(self.dbconn[self.DBNAME]["secondthings"].find()) 341 | while len(result) == 0: 342 | time.sleep(0.1) 343 | result = list(self.dbconn[self.DBNAME]["secondthings"].find()) 344 | 345 | assert "gears" not in result[0].keys() 346 | assert 1 == result[0]["thing_id"] 347 | assert "there" == result[0]["hello"] 348 | assert ["is", "that", "fun"] == result[0]["well"] 349 | 350 | 351 | class TestMongoWithConnectionString(TestMongoJSON): 352 | @classmethod 353 | def setup_class(cls): 354 | cls.env = Redis(decode_responses=True) 355 | 356 | pkg = find_package() 357 | 358 | # connection info 359 | r = tox.config.parseconfig(open("tox.ini").read()) 360 | docker = r._docker_container_configs["mongo"]["environment"] 361 | dbuser = docker["MONGO_INITDB_ROOT_USERNAME"] 362 | dbpasswd = docker["MONGO_INITDB_ROOT_PASSWORD"] 363 | db = docker["MONGO_DB"] 364 | 365 | con = f"mongodb://{dbuser}:{dbpasswd}@172.17.0.1:27017/" 366 | script = f""" 367 | from rgsync import RGJSONWriteBehind, RGJSONWriteThrough 368 | from rgsync.Connectors import MongoConnector, MongoConnection 369 | 370 | db = '{db}' 371 | con = "{con}" 372 | 373 | connection = MongoConnection(None, None, db, conn_string=con) 374 | 375 | jConnector = MongoConnector(connection, db, 'persons', 'person_id') 376 | 377 | RGJSONWriteBehind(GB, keysPrefix='person', 378 | connector=jConnector, name='PersonsWriteBehind', 379 | version='99.99.99') 380 | 381 | RGJSONWriteThrough(GB, keysPrefix='__', connector=jConnector, 382 | name='JSONWriteThrough', version='99.99.99') 383 | """ 384 | print(script) 385 | cls.env.execute_command("RG.PYEXECUTE", script, "REQUIREMENTS", pkg, "pymongo") 386 | 387 | e = MongoClient(con) 388 | 389 | # # tables are only created upon data use - so this is our equivalent 390 | # # for mongo 391 | assert "version" in e.server_info().keys() 392 | cls.dbconn = e 393 | cls.DBNAME = db 394 | -------------------------------------------------------------------------------- /tests/test_sqlwritebehind.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | import pytest 4 | import tox 5 | from redis import Redis 6 | from sqlalchemy import create_engine 7 | from sqlalchemy.sql import text 8 | 9 | from tests import find_package, to_utf 10 | 11 | 12 | class BaseSQLTest: 13 | @classmethod 14 | def setup_class(cls): 15 | cls.env = Redis(decode_responses=True) 16 | 17 | pkg = find_package() 18 | creds = cls.credentials(cls) 19 | cls.run_install_script(cls, pkg, **creds) 20 | 21 | table_create = """ 22 | CREATE TABLE persons ( 23 | person_id VARCHAR(100) NOT NULL, 24 | first VARCHAR(100) NOT NULL, last VARCHAR(100) NOT NULL, 25 | age INT NOT NULL, 26 | PRIMARY KEY (person_id) 27 | ); 28 | """ 29 | 30 | e = create_engine(cls.connection(cls, **creds)).execution_options( 31 | autocommit=True 32 | ) 33 | cls.dbconn = e.connect() 34 | cls.dbconn.execute(text("DROP TABLE IF EXISTS persons")) 35 | cls.dbconn.execute(text(table_create)) 36 | 37 | @classmethod 38 | def teardown_class(cls): 39 | cls.dbconn.execute(text("DROP TABLE IF EXISTS persons")) 40 | cls.env.flushall() 41 | 42 | def testSimpleWriteBehind(self): 43 | self.env.execute_command("flushall") 44 | self.env.execute_command( 45 | "hset", "person:1", "first_name", "foo", "last_name", "bar", "age", "22" 46 | ) 47 | result = self.dbconn.execute(text("select * from persons")) 48 | count = 0 49 | while result.rowcount in [0, -1]: 50 | time.sleep(0.3) 51 | result = self.dbconn.execute(text("select * from persons")) 52 | count += 1 53 | if count == 10: 54 | break 55 | res = result.fetchone() 56 | assert res == ("1", "foo", "bar", 22) 57 | 58 | self.env.execute_command("del", "person:1") 59 | result = self.dbconn.execute(text("select * from persons")) 60 | count = 0 61 | while result.rowcount > 0: 62 | time.sleep(0.1) 63 | result = self.dbconn.execute(text("select * from persons")) 64 | if count == 10: 65 | assert True == False, "Failed on deleting data from the target" 66 | break 67 | count += 1 68 | 69 | def testWriteBehindAck(self): 70 | self.env.execute_command("flushall") 71 | self.env.execute_command( 72 | "hset", 73 | "person:1", 74 | "first_name", 75 | "foo", 76 | "last_name", 77 | "bar", 78 | "age", 79 | "22", 80 | "#", 81 | "=1", 82 | ) 83 | res = None 84 | count = 0 85 | while res is None: 86 | res = self.env.execute_command("XREAD BLOCK 200 STREAMS {person:1}1 0-0") 87 | if count == 10: 88 | assert True == False, "Failed on deleting data from the target" 89 | break 90 | count += 1 91 | assert res[0][1][0][1] == to_utf(["status", "done"]) 92 | 93 | result = self.dbconn.execute(text("select * from persons")) 94 | res = result.fetchone() 95 | assert res == ("1", "foo", "bar", 22) 96 | 97 | result = self.dbconn.execute(text("select * from persons")) 98 | res = result.fetchone() 99 | assert res == ("1", "foo", "bar", 22) 100 | 101 | # delete from database 102 | self.env.execute_command("hset", "person:1", "#", "~2") 103 | res = None 104 | count = 0 105 | while res is None: 106 | res = self.env.execute_command("XREAD BLOCK 200 STREAMS {person:1}2 0-0") 107 | if count == 10: 108 | assert True == False, "Failed on deleting data from the target" 109 | break 110 | count += 1 111 | assert res[0][1][0][1] == to_utf(["status", "done"]) 112 | assert self.env.execute_command("hgetall", "person:1") == {} 113 | result = self.dbconn.execute(text("select * from persons")) 114 | assert result.rowcount in [0, -1] 115 | 116 | def testWriteBehindOperations(self): 117 | self.env.execute_command("flushall") 118 | 119 | # write a hash and not replicate 120 | self.env.execute_command( 121 | "hset", 122 | "person:1", 123 | "first_name", 124 | "foo", 125 | "last_name", 126 | "bar", 127 | "age", 128 | "22", 129 | "#", 130 | "+", 131 | ) 132 | self.env.execute_command( 133 | "hset", 134 | "person:1", 135 | "first_name", 136 | "foo", 137 | "last_name", 138 | "bar", 139 | "age", 140 | "22", 141 | "#", 142 | "+1", 143 | ) 144 | res = self.env.execute_command("XREAD BLOCK 200 STREAMS {person:1}1 0-0") 145 | assert res[0][1][0][1] == to_utf(["status", "done"]) 146 | 147 | assert self.env.execute_command("hgetall", "person:1") == to_utf( 148 | {"first_name": "foo", "last_name": "bar", "age": "22"} 149 | ) 150 | 151 | # make sure data is not in the database 152 | result = self.dbconn.execute(text("select * from persons")) 153 | assert result.rowcount in [0, -1] 154 | 155 | # rewrite data with replicate 156 | self.env.execute_command( 157 | "hset", 158 | "person:1", 159 | "first_name", 160 | "foo", 161 | "last_name", 162 | "bar", 163 | "age", 164 | "22", 165 | "#", 166 | "=2", 167 | ) 168 | res = None 169 | count = 0 170 | while res is None: 171 | res = self.env.execute_command("XREAD BLOCK 200 STREAMS {person:1}2 0-0") 172 | if count == 10: 173 | assert True == False, "Failed on deleting data from the target" 174 | break 175 | count += 1 176 | assert res[0][1][0][1] == to_utf(["status", "done"]) 177 | 178 | result = self.dbconn.execute(text("select * from persons")) 179 | res = result.fetchone() 180 | assert res == ("1", "foo", "bar", 22) 181 | 182 | # delete data without replicate 183 | self.env.execute_command("hset", "person:1", "#", "-") 184 | self.env.execute_command("hset", "person:1", "#", "-3") 185 | res = self.env.execute_command("XREAD BLOCK 200 STREAMS {person:1}3 0-0") 186 | assert res[0][1][0][1] == to_utf(["status", "done"]) 187 | 188 | assert self.env.execute_command("hgetall", "person:1") == {} 189 | 190 | # make sure data is still in the dabase 191 | result = self.dbconn.execute(text("select * from persons")) 192 | res = result.fetchone() 193 | assert res == ("1", "foo", "bar", 22) 194 | 195 | # rewrite a hash and not replicate 196 | self.env.execute_command( 197 | "hset", 198 | "person:1", 199 | "first_name", 200 | "foo", 201 | "last_name", 202 | "bar", 203 | "age", 204 | "22", 205 | "#", 206 | "+", 207 | ) 208 | assert self.env.execute_command("hgetall", "person:1") == to_utf( 209 | {"first_name": "foo", "last_name": "bar", "age": "22"} 210 | ) 211 | 212 | # delete data with replicate and make sure its deleted from database and from redis 213 | self.env.execute_command("hset", "person:1", "#", "~") 214 | result = self.dbconn.execute(text("select * from persons")) 215 | count = 0 216 | while result.rowcount > 0: 217 | time.sleep(0.1) 218 | result = self.dbconn.execute(text("select * from persons")) 219 | if count == 10: 220 | assert True == False, "Failed on deleting data from the target" 221 | break 222 | count += 1 223 | assert self.env.execute_command("hgetall", "person:1") == {} 224 | 225 | def testSimpleWriteThrough(self): 226 | self.env.execute_command("flushall") 227 | 228 | self.env.execute_command( 229 | "hset __{person:1} first_name foo last_name bar age 20" 230 | ) 231 | 232 | # make sure data is in the dabase 233 | result = self.dbconn.execute(text("select * from persons")) 234 | res = result.fetchone() 235 | assert res == ("1", "foo", "bar", 20) 236 | 237 | assert self.env.execute_command("hgetall", "person:1") == to_utf( 238 | {"first_name": "foo", "last_name": "bar", "age": "20"} 239 | ) 240 | 241 | self.env.execute_command("hset __{person:1} # ~") 242 | 243 | # make sure data is deleted from the database 244 | result = self.dbconn.execute(text("select * from persons")) 245 | assert result.rowcount in [0, -1] 246 | 247 | assert self.env.execute_command("hgetall", "person:1") == {} 248 | 249 | def testSimpleWriteThroughPartialUpdate(self): 250 | self.env.execute_command("flushall") 251 | 252 | self.env.execute_command( 253 | "hset __{person:1} first_name foo last_name bar age 20" 254 | ) 255 | 256 | # make sure data is in the dabase 257 | result = self.dbconn.execute(text("select * from persons")) 258 | res = result.fetchone() 259 | assert res == ("1", "foo", "bar", 20) 260 | 261 | assert self.env.execute_command("hgetall", "person:1") == to_utf( 262 | {"first_name": "foo", "last_name": "bar", "age": "20"} 263 | ) 264 | 265 | self.env.execute_command("hset __{person:1} first_name foo1") 266 | 267 | # make sure data is in the dabase 268 | result = self.dbconn.execute(text("select * from persons")) 269 | res = result.fetchone() 270 | assert res == ("1", "foo1", "bar", 20) 271 | 272 | assert self.env.execute_command("hgetall", "person:1") == to_utf( 273 | {"first_name": "foo1", "last_name": "bar", "age": "20"} 274 | ) 275 | 276 | self.env.execute_command("hset __{person:1} # ~") 277 | 278 | # make sure data is deleted from the database 279 | result = self.dbconn.execute(text("select * from persons")) 280 | assert result.rowcount in [0, -1] 281 | 282 | assert self.env.execute_command("hgetall", "person:1") == {} 283 | 284 | def testWriteThroughNoReplicate(self): 285 | self.env.execute_command("flushall") 286 | 287 | self.env.execute_command( 288 | "hset __{person:1} first_name foo last_name bar age 20 # +" 289 | ) 290 | 291 | # make sure data is deleted from the database 292 | result = self.dbconn.execute(text("select * from persons")) 293 | assert result.rowcount in [0, -1] 294 | 295 | assert self.env.execute_command("hgetall", "person:1") == to_utf( 296 | {"first_name": "foo", "last_name": "bar", "age": "20"} 297 | ) 298 | 299 | def testDelThroughNoReplicate(self): 300 | self.env.execute_command("flushall") 301 | 302 | self.env.execute_command( 303 | "hset __{person:1} first_name foo last_name bar age 20" 304 | ) 305 | 306 | # make sure data is in the dabase 307 | result = self.dbconn.execute(text("select * from persons")) 308 | res = result.fetchone() 309 | assert res == ("1", "foo", "bar", 20) 310 | 311 | assert self.env.execute_command("hgetall", "person:1") == to_utf( 312 | {"first_name": "foo", "last_name": "bar", "age": "20"} 313 | ) 314 | 315 | self.env.execute_command("hset __{person:1} # -") 316 | 317 | # make sure data was deleted from redis but not from the target 318 | assert self.env.execute_command("hgetall", "person:1") == {} 319 | result = self.dbconn.execute(text("select * from persons")) 320 | res = result.fetchone() 321 | assert res == ("1", "foo", "bar", 20) 322 | 323 | self.env.execute_command("hset __{person:1} # ~") 324 | 325 | # make sure data was deleted from target as well 326 | result = self.dbconn.execute(text("select * from persons")) 327 | assert result.rowcount in [0, -1] 328 | 329 | def testWriteTroughAckStream(self): 330 | self.env.execute_command("flushall") 331 | 332 | self.env.execute_command( 333 | "hset __{person:1} first_name foo last_name bar age 20 # =1" 334 | ) 335 | 336 | res = self.env.execute_command("XREAD BLOCK 200 STREAMS {person:1}1 0-0") 337 | assert res[0][1][0][1] == to_utf(["status", "done"]) 338 | 339 | # make sure data is in the dabase 340 | result = self.dbconn.execute(text("select * from persons")) 341 | res = result.fetchone() 342 | assert res == ("1", "foo", "bar", 20) 343 | 344 | # make sure data is in redis 345 | assert self.env.execute_command("hgetall", "person:1") == to_utf( 346 | {"first_name": "foo", "last_name": "bar", "age": "20"} 347 | ) 348 | 349 | self.env.execute_command( 350 | "hset __{person:1} first_name foo last_name bar age 20 # ~2" 351 | ) 352 | 353 | res = self.env.execute_command("XREAD BLOCK 200 STREAMS {person:1}2 0-0") 354 | assert res[0][1][0][1] == to_utf(["status", "done"]) 355 | 356 | # make sure data is deleted from the database 357 | result = self.dbconn.execute(text("select * from persons")) 358 | assert result.rowcount in [0, -1] 359 | 360 | assert self.env.execute_command("hgetall", "person:1") == {} 361 | 362 | def testWriteTroughAckStreamNoReplicate(self): 363 | self.env.execute_command("flushall") 364 | 365 | self.env.execute_command( 366 | "hset __{person:1} first_name foo last_name bar age 20 # +1" 367 | ) 368 | 369 | res = self.env.execute_command("XREAD BLOCK 200 STREAMS {person:1}1 0-0") 370 | assert res[0][1][0][1] == to_utf(["status", "done"]) 371 | 372 | # make sure data is not in the target 373 | result = self.dbconn.execute(text("select * from persons")) 374 | assert result.rowcount in [0, -1] 375 | 376 | # make sure data is in redis 377 | assert self.env.execute_command("hgetall", "person:1") == to_utf( 378 | {"first_name": "foo", "last_name": "bar", "age": "20"} 379 | ) 380 | 381 | self.env.execute_command( 382 | "hset __{person:1} first_name foo last_name bar age 20 # -2" 383 | ) 384 | 385 | res = self.env.execute_command("XREAD BLOCK 200 STREAMS {person:1}2 0-0") 386 | assert res[0][1][0][1] == to_utf(["status", "done"]) 387 | 388 | # make sure data is deleted from redis 389 | assert self.env.execute_command("hgetall", "person:1") == {} 390 | 391 | 392 | @pytest.mark.postgres 393 | class TestPostgresql(BaseSQLTest): 394 | def credentials(self): 395 | r = tox.config.parseconfig(open("tox.ini").read()) 396 | docker = r._docker_container_configs["postgres"]["environment"] 397 | dbuser = docker["POSTGRES_USER"] 398 | dbpasswd = docker["POSTGRES_PASSWORD"] 399 | db = docker["POSTGRES_DB"] 400 | 401 | return {"dbuser": dbuser, "dbpasswd": dbpasswd, "db": db} 402 | 403 | def connection(self, **kwargs): 404 | 405 | con = "postgresql://{user}:{password}@172.17.0.1:5432/{db}".format( 406 | user=kwargs["dbuser"], 407 | password=kwargs["dbpasswd"], 408 | db=kwargs["db"], 409 | ) 410 | return con 411 | 412 | def run_install_script(self, pkg, **kwargs): 413 | script = """ 414 | from rgsync import RGWriteBehind, RGWriteThrough 415 | from rgsync.Connectors import PostgresConnector, PostgresConnection 416 | 417 | connection = PostgresConnection('%s', '%s', '172.17.0.1:5432/%s') 418 | personsConnector = PostgresConnector(connection, 'persons', 'person_id') 419 | 420 | personsMappings = { 421 | 'first_name':'first', 422 | 'last_name':'last', 423 | 'age':'age' 424 | } 425 | 426 | RGWriteBehind(GB, keysPrefix='person', mappings=personsMappings, connector=personsConnector, name='PersonsWriteBehind', version='99.99.99') 427 | RGWriteThrough(GB, keysPrefix='__', mappings=personsMappings, connector=personsConnector, name='PersonsWriteThrough', version='99.99.99') 428 | """ % ( 429 | kwargs["dbuser"], 430 | kwargs["dbpasswd"], 431 | kwargs["db"], 432 | ) 433 | self.env.execute_command( 434 | "RG.PYEXECUTE", script, "REQUIREMENTS", pkg, "psycopg2-binary" 435 | ) 436 | 437 | 438 | @pytest.mark.mysql 439 | class TestMysql(BaseSQLTest): 440 | def credentials(self): 441 | r = tox.config.parseconfig(open("tox.ini").read()) 442 | docker = r._docker_container_configs["mysql"]["environment"] 443 | dbuser = docker["MYSQL_USER"] 444 | dbpasswd = docker["MYSQL_PASSWORD"] 445 | db = docker["MYSQL_DATABASE"] 446 | 447 | return {"dbuser": dbuser, "dbpasswd": dbpasswd, "db": db} 448 | 449 | def connection(self, **kwargs): 450 | 451 | # connection info 452 | 453 | con = "mysql+pymysql://{user}:{password}@172.17.0.1:3306/{db}".format( 454 | user=kwargs["dbuser"], 455 | password=kwargs["dbpasswd"], 456 | db=kwargs["db"], 457 | ) 458 | 459 | return con 460 | 461 | def run_install_script(self, pkg, **kwargs): 462 | # initial gears setup 463 | script = """ 464 | from rgsync import RGWriteBehind, RGWriteThrough 465 | from rgsync.Connectors import MySqlConnector, MySqlConnection 466 | 467 | connection = MySqlConnection('%s', '%s', '172.17.0.1:3306/%s') 468 | 469 | personsConnector = MySqlConnector(connection, 'persons', 'person_id') 470 | 471 | personsMappings = { 472 | 'first_name':'first', 473 | 'last_name':'last', 474 | 'age':'age' 475 | } 476 | 477 | RGWriteBehind(GB, keysPrefix='person', mappings=personsMappings, connector=personsConnector, name='PersonsWriteBehind', version='99.99.99') 478 | 479 | RGWriteThrough(GB, keysPrefix='__', mappings=personsMappings, connector=personsConnector, name='PersonsWriteThrough', version='99.99.99') 480 | """ % ( 481 | kwargs["dbuser"], 482 | kwargs["dbpasswd"], 483 | kwargs["db"], 484 | ) 485 | self.env.execute_command( 486 | "RG.PYEXECUTE", script, "REQUIREMENTS", pkg, "pymysql[rsa]" 487 | ) 488 | 489 | 490 | @pytest.mark.db2 491 | class TestDB2(BaseSQLTest): 492 | def credentials(self): 493 | r = tox.config.parseconfig(open("tox.ini").read()) 494 | docker = r._docker_container_configs["db2"]["environment"] 495 | dbuser = docker["DB2INSTANCE"] 496 | dbpasswd = docker["DB2INST1_PASSWORD"] 497 | db = docker["DBNAME"] 498 | 499 | return {"dbuser": dbuser, "dbpasswd": dbpasswd, "db": db} 500 | 501 | def connection(self, **kwargs): 502 | 503 | con = f"db2://{kwargs['dbuser']}:{kwargs['dbpasswd']}@172.17.0.1:50000/{kwargs['db']}" 504 | return con 505 | 506 | def run_install_script(self, pkg, **kwargs): 507 | script = """ 508 | from rgsync import RGWriteBehind, RGWriteThrough 509 | from rgsync.Connectors import DB2Connector, DB2Connection 510 | 511 | connection = DB2Connection('%s', '%s', '172.17.0.1:50000/%s') 512 | personsConnector = DB2Connector(connection, 'persons', 'person_id') 513 | 514 | personsMappings = { 515 | 'first_name':'first', 516 | 'last_name':'last', 517 | 'age':'age' 518 | } 519 | 520 | RGWriteBehind(GB, keysPrefix='person', mappings=personsMappings, connector=personsConnector, name='PersonsWriteBehind', version='99.99.99') 521 | RGWriteThrough(GB, keysPrefix='__', mappings=personsMappings, connector=personsConnector, name='PersonsWriteThrough', version='99.99.99') 522 | """ % ( 523 | kwargs["dbuser"], 524 | kwargs["dbpasswd"], 525 | kwargs["db"], 526 | ) 527 | self.env.execute_command( 528 | "RG.PYEXECUTE", script, "REQUIREMENTS", pkg, "ibm-db-sa" 529 | ) 530 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | addopts = -s 3 | markers = 4 | mysql: mysql backend tests 5 | postgres: postgres backend tests 6 | sqlite: sqlite backend tests 7 | mongo: mongo backend tests 8 | db2: db2 backend tests 9 | 10 | [tox] 11 | minversion=3.2.4 12 | envlist=mysql, postgres, mongo, db2, linters 13 | 14 | # for variable reuse 15 | [main] 16 | dbuser = admin 17 | dbpasswd = adminpass 18 | db = rgsync 19 | 20 | [docker:db2] 21 | image = ibmcom/db2 22 | container_name = db2 23 | privileged = true 24 | ports = 25 | 50000:50000/tcp 26 | 55000:55000/tcp 27 | environment = 28 | LICENSE=accept 29 | DB2INSTANCE={[main]dbuser} 30 | DB2INST1_PASSWORD={[main]dbpasswd} 31 | DBNAME={[main]db} 32 | 33 | [docker:mysql] 34 | image = mysql:8 35 | healthcheck_cmd = sleep 10 36 | ports = 37 | 3306:3306/tcp 38 | environment = 39 | MYSQL_ROOT_PASSWORD=adminadmin 40 | MYSQL_USER={[main]dbuser} 41 | MYSQL_PASSWORD={[main]dbpasswd} 42 | MYSQL_DATABASE={[main]db} 43 | 44 | # tests, setup, and an init script for mongo use these variables 45 | # if you edit this, edit tests/init-mongo.js as well 46 | [docker:mongo] 47 | name = mongo 48 | image = mongo:4 49 | ports = 50 | 27017:27017/tcp 51 | environment = 52 | MONGO_INITDB_ROOT_USERNAME={[main]dbuser} 53 | MONGO_INITDB_ROOT_PASSWORD={[main]dbpasswd} 54 | MONGO_INITDB_DATABASE=admin 55 | MONGO_DB={[main]db} 56 | volumes = 57 | bind:ro:{toxinidir}/tests/init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js 58 | 59 | [docker:redisgears] 60 | name = redisgears 61 | image = redislabs/redismod:edge 62 | volumes = 63 | bind:rw:{toxinidir}:/build 64 | ports = 65 | 6379:6379/tcp 66 | 67 | [docker:postgres] 68 | image = postgres:13 69 | healthcheck_cmd = sleep 15 70 | ports = 71 | 5432:5432/tcp 72 | environment = 73 | POSTGRES_USER={[main]dbuser} 74 | POSTGRES_PASSWORD={[main]dbpasswd} 75 | POSTGRES_DB={[main]db} 76 | 77 | [flake8] 78 | max-complexity = 10 79 | filename = ./rgsync/** 80 | ignore = W292, E501 81 | exclude = src/conftest.py 82 | show-source = true 83 | 84 | [testenv] 85 | allowlist_externals = 86 | rm 87 | poetry 88 | docker = 89 | {envname} 90 | redisgears 91 | setenv = 92 | IN_DOCKER = 1 93 | commands_pre = 94 | rm -rf dist 95 | poetry build 96 | commands = 97 | pytest -m {envname} -s 98 | 99 | [testenv:postgres] 100 | 101 | [testenv:mysql] 102 | 103 | [testenv:mongo] 104 | 105 | [testenv:db2] 106 | commands = 107 | docker exec redisgears apt-get update --fix-missing 108 | docker exec redisgears apt-get install -y gcc vim procps libxml2 109 | sh {toxinidir}/sbin/db2wait.sh 110 | pytest -m {envname} -s 111 | 112 | [testenv:sqlite] 113 | allowlist_externals = 114 | rm 115 | poetry 116 | docker = 117 | redisgears 118 | setenv = 119 | IN_DOCKER = 1 120 | commands_pre = 121 | rm -rf dist 122 | poetry build 123 | commands = 124 | apt update -y 125 | apt install -y sqlite3 126 | 127 | [testenv:linters] 128 | deps_files = dev_requirements.txt 129 | docker = 130 | commands = 131 | black --target-version py36 --check --diff rgsync tests 132 | isort --check-only --diff rgsync tests 133 | vulture rgsync --min-confidence 80 134 | flynt --fail-on-change --dry-run rgsync tests 135 | skipsdist = true 136 | skip_install = true 137 | --------------------------------------------------------------------------------