diff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml index 1ebf5c8ac6..d0f857877a 100644 --- a/.github/workflows/smoke-tests.yml +++ b/.github/workflows/smoke-tests.yml @@ -229,7 +229,8 @@ jobs: test: [ stubtest, doctest, - code-examples + ce-code-examples, + ee-code-examples ] fail-fast: false needs: [ @@ -261,22 +262,33 @@ jobs: - name: Install client run: pip install ./*.whl - - if: ${{ matrix.test == 'doctest' || matrix.test == 'code-examples' }} + - if: ${{ matrix.test == 'doctest' || endsWith(matrix.test, 'code-examples') }} uses: aerospike/shared-workflows/.github/actions/setup-aerospike-server@bd168dedaa4fc0b17a560541779d815540eded2d # v3.7.0 with: num-nodes: 1 oidc-provider: ${{ vars.OIDC_PROVIDER_NAME }} oidc-audience: ${{ vars.OIDC_AUDIENCE }} server-tag: ${{ matrix.test == 'code-examples' && '8.1.3.0-35-20260629033923' || needs.get-env-vars.outputs.server-tag }} - server-container-repo: database-docker-virtual/aerospike-server - config-file: ./.github/workflows/aerospike-ce.conf - - - if: ${{ matrix.test == 'code-examples' }} - # We cannot run this module with the cwd being string_ops - # Otherwise we will get relative import errors - # https://stackoverflow.com/a/47030746 - run: python3 -m string_ops.run_all_examples - working-directory: examples + server-container-repo: database-docker-virtual/aerospike-server${{ matrix.test == 'ee-code-examples' && '-enterprise' || '' }} + config-file: ${{ (matrix.test == 'doctest' || matrix.test == 'ce-code-examples') && './.github/workflows/aerospike-ce.conf' || '' }} + enable-security: ${{ matrix.test == 'ee-code-examples' }} + + - name: Run canonical code examples + if: ${{ endsWith(matrix.test, 'code-examples') }} + run: | + # This is required for the TTL code example + run_tools=( + docker run --rm --network host aerospike/aerospike-tools asinfo -v + ) + + if [[ ${{ matrix.test == 'ce-code-examples' }} == true ]]; then + "${run_tools[@]}" "set-config:context=namespace;id=test;nsup-period=1" + "${run_tools[@]}" "set-config:context=namespace;namespace=test;default-ttl=10S" + fi + + python3 -m examples.run_all_examples "$SERVER_EDITION" + env: + SERVER_EDITION: ${{ matrix.test == 'ce-code-examples' && 'CE' || 'EE' }} - name: Install test dependencies if: ${{ matrix.test == 'doctest' }} diff --git a/README.rst b/README.rst index a8a0f89398..837feb18da 100644 --- a/README.rst +++ b/README.rst @@ -94,12 +94,15 @@ Examples Example applications are provided in the `examples directory of the GitHub repository `__ -For examples, to run the ``kvs.py``: +For examples, to run all code examples: :: - python examples/client/kvs.py + python3 -m examples.run_all_examples +To run a specific code example from ``examples/client/kvs.py``: + + python3 -m examples.run_all_examples KVS Benchmarks ---------- diff --git a/examples/__init__.py b/examples/__init__.py new file mode 100644 index 0000000000..250d0c9cd1 --- /dev/null +++ b/examples/__init__.py @@ -0,0 +1,65 @@ +import aerospike +import os + + +class Example: + def __init__( + self, + host: str = "127.0.0.1", + port: int = 3000, + user: str = None, + password: str = None, + namespace: str = "test", + set_name: str = "demo", + extra_config: dict = {} + ): + self.config = { + "hosts": [(host, port)], + "user": user, + "password": password + } + self.config |= extra_config + client = aerospike.client(self.config) + + self.client = client + self.namespace = namespace + self.set_name = set_name + self.user_key = "docreadkey" + self.key = (self.namespace, self.set_name, self.user_key) + self.non_existent_key = (self.namespace, self.set_name, "nonexistent") + self.BIN_NAME = "a" + + def cleanup(self): + self.client.close() + +class UDFExample(Example): + def __init__(self): + extra_config = { + 'lua': { + 'user_path': os.path.dirname(__file__) + "/client/" + } + } + super().__init__(extra_config=extra_config) + +class ExampleWithIndex(Example): + INDEX_NAME = "index_name" + def __init__(self): + super().__init__() + + self.client.index_single_value_create(self.namespace, self.set_name, self.BIN_NAME, aerospike.INDEX_INTEGER, self.INDEX_NAME) + + def cleanup(self): + self.client.index_remove(self.namespace, self.INDEX_NAME) + + super().cleanup() + +class ExampleWithRecord(Example): + def __init__(self): + super().__init__() + + self.client.put(self.key, bins={self.BIN_NAME: 1}) + + def cleanup(self): + self.client.remove(self.key) + + super().cleanup() diff --git a/examples/admin/change_password.py b/examples/admin/change_password.py deleted file mode 100644 index d5cc6a33a7..0000000000 --- a/examples/admin/change_password.py +++ /dev/null @@ -1,127 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys -from aerospike.exception import * - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - user = "foo-example" - password = "foobar" - try: - client_new = aerospike.client(config).connect(user, "bar") - except ClientError: - print("User might not be created or node may be down. In case of non-existent user run create_user.py first") - client.close() - sys.exit() - status = client_new.admin_change_password(user, password) - client_new.close() - - print("Status of changing password is: %d" % status) - print("OK, password changed for 1 user") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception, eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/create_role.py b/examples/admin/create_role.py deleted file mode 100644 index 26c0ac3c78..0000000000 --- a/examples/admin/create_role.py +++ /dev/null @@ -1,119 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - role = "example_foo" - privileges = [{"code": aerospike.PRIV_READ}, {"code": aerospike.PRIV_USER_ADMIN}] - - client.admin_create_role(role, privileges, policy) - - print("OK, 1 new role created") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception, eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/create_user.py b/examples/admin/create_user.py deleted file mode 100644 index 00006500f3..0000000000 --- a/examples/admin/create_user.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - user = "foo-example" - password = "bar" - roles = ["read-write", "read"] - roles_size = len(roles) - - client.admin_create_user(user, password, roles, policy) - - print("OK, 1 new user created") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/drop_role.py b/examples/admin/drop_role.py deleted file mode 100644 index 60a1bf95a1..0000000000 --- a/examples/admin/drop_role.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - role = "example_foo" - - client.admin_drop_role(role, policy) - - print("OK, 1 role dropped") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception, eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/drop_user.py b/examples/admin/drop_user.py deleted file mode 100644 index cba66d61e2..0000000000 --- a/examples/admin/drop_user.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - user = "foo-example" - - client.admin_drop_user(user, policy) - - print("OK, 1 user dropped") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception, eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/grant_privileges.py b/examples/admin/grant_privileges.py deleted file mode 100644 index fbde412653..0000000000 --- a/examples/admin/grant_privileges.py +++ /dev/null @@ -1,120 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - role = "example_foo" - privileges = [{"code": aerospike.PRIV_SYS_ADMIN}] - - client.admin_grant_privileges(role, privileges) - - print("OK, new privileges granted to 1 role") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - print("In case of invalid role first create role by running create_role.py") - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception, eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/grant_roles.py b/examples/admin/grant_roles.py deleted file mode 100644 index 2eee99558f..0000000000 --- a/examples/admin/grant_roles.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - user = "foo-example" - roles = ["read-write", "user-admin"] - roles_size = len(roles) - - client.admin_grant_roles(user, roles) - - print("OK, new roles granted to 1 user") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - print("In case of invalid user first create user by running create_user.py") - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception, eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/query_role.py b/examples/admin/query_role.py deleted file mode 100644 index 7f0de7185f..0000000000 --- a/examples/admin/query_role.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - role = "example_foo" - - privileges = client.admin_query_role(role, policy) - - print(privileges) - print("---") - print("OK, Privileges retrieved for one role") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - print("In case of invalid role, first create role using create_role.py") - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/query_roles.py b/examples/admin/query_roles.py deleted file mode 100644 index e524be6f71..0000000000 --- a/examples/admin/query_roles.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - - roles = client.admin_query_roles(policy) - print(roles) - print("---") - print("OK, All roles retrieved") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/query_user.py b/examples/admin/query_user.py deleted file mode 100644 index 0534792948..0000000000 --- a/examples/admin/query_user.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [(options.host, options.port)] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - - roles = client.admin_query_user(options.username, policy) - - print(roles) - print("---") - print("OK, Roles retrieved for 1 user") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - print("In case of invalid user first create user by running create_user.py") - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/query_user_info.py b/examples/admin/query_user_info.py deleted file mode 100644 index 331772e07b..0000000000 --- a/examples/admin/query_user_info.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [(options.host, options.port)] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - - roles = client.admin_query_user_info(options.username, policy) - - print(roles) - print("---") - print("OK, Roles retrieved for 1 user") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - print("In case of invalid user first create user by running create_user.py") - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/query_users.py b/examples/admin/query_users.py deleted file mode 100644 index eba5104f2f..0000000000 --- a/examples/admin/query_users.py +++ /dev/null @@ -1,120 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [(options.host, options.port)] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - - user_roles = client.admin_query_users(policy) - - print(user_roles) - print("---") - print("OK, All users retrieved") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/query_users_info.py b/examples/admin/query_users_info.py deleted file mode 100644 index bd5fff2308..0000000000 --- a/examples/admin/query_users_info.py +++ /dev/null @@ -1,120 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [(options.host, options.port)] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - - user_roles = client.admin_query_users_info(policy) - - print(user_roles) - print("---") - print("OK, All users retrieved") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/revoke_privileges.py b/examples/admin/revoke_privileges.py deleted file mode 100644 index 2434af064e..0000000000 --- a/examples/admin/revoke_privileges.py +++ /dev/null @@ -1,120 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - role = "example_foo" - privileges = [{"code": aerospike.PRIV_SYS_ADMIN}] - - client.admin_revoke_privileges(role, privileges, policy) - - print("OK, privileges revoked from 1 role") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - print("In case of invalid role first create roles using create_role.py") - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception, eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/revoke_roles.py b/examples/admin/revoke_roles.py deleted file mode 100644 index f43b4300ce..0000000000 --- a/examples/admin/revoke_roles.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - user = "foo-example" - roles = ["user-admin", "read"] - roles_size = len(roles) - - client.admin_revoke_roles(user, roles, policy) - - print("OK, roles revoked from 1 user") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - print("In case of invalid user first create user using create_user.py") - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception, eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/admin/set_password.py b/examples/admin/set_password.py deleted file mode 100644 index 4003ec1106..0000000000 --- a/examples/admin/set_password.py +++ /dev/null @@ -1,120 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################################ -# Options Parsing -################################################################################ - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if options.username == None or options.password == None: - optparser.print_help() - print() - sys.exit(1) - -################################################################################ -# Client Configuration -################################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -################################################################################ -# Application -################################################################################ - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect(options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - policy = {} - user = "foo-example" - password = "bar" - - client.admin_set_password(user, password, policy) - - print("OK, password set for 1 user") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - print("In case of invalid user first create user using create_user.py") - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception, eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -################################################################################ -# Exit -################################################################################ - -sys.exit(exitCode) diff --git a/examples/client/__init__.py b/examples/client/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/examples/client/admin/__init__.py b/examples/client/admin/__init__.py new file mode 100644 index 0000000000..e25e9243b6 --- /dev/null +++ b/examples/client/admin/__init__.py @@ -0,0 +1,6 @@ +from ... import Example + + +class AdminExample(Example): + def __init__(self): + super().__init__(user="admin", password="admin") diff --git a/examples/client/admin/change_password.py b/examples/client/admin/change_password.py new file mode 100644 index 0000000000..a5278250bf --- /dev/null +++ b/examples/client/admin/change_password.py @@ -0,0 +1,33 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + + + +from .create_user import CreateUser +import aerospike + + +class ChangePassword(CreateUser): + def run(self): + super().run() + + config2 = self.config.copy() + config2["user"] = self.user + config2["password"] = self.password + client2 = aerospike.client(config2) + + status = client2.admin_change_password(self.user, self.password) + print("Status of changing password is: %d" % status) diff --git a/examples/client/admin/create_role.py b/examples/client/admin/create_role.py new file mode 100644 index 0000000000..e891dd5b6b --- /dev/null +++ b/examples/client/admin/create_role.py @@ -0,0 +1,36 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + + +import aerospike +from . import AdminExample +import time + + +class CreateRole(AdminExample): + def run(self): + policy = {} + self.role = "example_foo" + privileges = [{"code": aerospike.PRIV_READ}, {"code": aerospike.PRIV_USER_ADMIN}] + + self.client.admin_create_role(self.role, privileges, policy) + time.sleep(3) + + print("OK, 1 new role created") + + def cleanup(self): + self.client.admin_drop_role(self.role) + time.sleep(3) diff --git a/examples/client/admin/create_user.py b/examples/client/admin/create_user.py new file mode 100644 index 0000000000..1e1655766c --- /dev/null +++ b/examples/client/admin/create_user.py @@ -0,0 +1,36 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + + +from . import AdminExample +import time + +class CreateUser(AdminExample): + def run(self): + policy = {} + self.user = "foo-example" + self.password = "foobar" + roles = ["read-write", "read"] + + self.client.admin_create_user(self.user, self.password, roles, policy) + time.sleep(3) + + print("OK, 1 new user created") + + def cleanup(self): + self.client.admin_drop_user(self.user) + time.sleep(3) + super().cleanup() diff --git a/examples/client/admin/drop_role.py b/examples/client/admin/drop_role.py new file mode 100644 index 0000000000..962e9d8d2c --- /dev/null +++ b/examples/client/admin/drop_role.py @@ -0,0 +1,33 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + + +from .create_role import CreateRole +from . import AdminExample +import time + + +class DropRole(CreateRole): + def run(self): + super().run() + policy = {} + + self.client.admin_drop_role(self.role, policy) + time.sleep(3) + print("OK, 1 role dropped") + + def cleanup(self): + AdminExample.cleanup(self) diff --git a/examples/client/admin/drop_user.py b/examples/client/admin/drop_user.py new file mode 100644 index 0000000000..2b0bb7516e --- /dev/null +++ b/examples/client/admin/drop_user.py @@ -0,0 +1,33 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + + +from .create_user import CreateUser, AdminExample +import time + + +class DropUser(CreateUser): + def run(self): + super().run() + policy = {} + + self.client.admin_drop_user(self.user, policy) + time.sleep(3) + + print("OK, 1 user dropped") + + def cleanup(self): + AdminExample.cleanup(self) diff --git a/examples/client/admin/grant_privileges.py b/examples/client/admin/grant_privileges.py new file mode 100644 index 0000000000..bbab3850e2 --- /dev/null +++ b/examples/client/admin/grant_privileges.py @@ -0,0 +1,30 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + +from .create_role import CreateRole +import aerospike +import time + + +class GrantPrivileges(CreateRole): + def run(self): + super().run() + privileges = [{"code": aerospike.PRIV_SYS_ADMIN}] + + self.client.admin_grant_privileges(self.role, privileges) + time.sleep(3) + + print("OK, new privileges granted to 1 role") diff --git a/examples/client/admin/grant_roles.py b/examples/client/admin/grant_roles.py new file mode 100644 index 0000000000..5190d0a448 --- /dev/null +++ b/examples/client/admin/grant_roles.py @@ -0,0 +1,26 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + +from .create_user import CreateUser +import time + + +class GrantRoles(CreateUser): + def run(self): + super().run() + self.roles = ["read-write", "user-admin"] + self.client.admin_grant_roles(self.user, self.roles) + time.sleep(3) diff --git a/examples/client/admin/query_role.py b/examples/client/admin/query_role.py new file mode 100644 index 0000000000..89f545ffd5 --- /dev/null +++ b/examples/client/admin/query_role.py @@ -0,0 +1,25 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ +from .create_role import CreateRole +import time + + +class QueryRole(CreateRole): + def run(self): + super().run() + policy = {} + privileges = self.client.admin_query_role(self.role, policy) + print(privileges) diff --git a/examples/client/admin/query_roles.py b/examples/client/admin/query_roles.py new file mode 100644 index 0000000000..2b00d8bddb --- /dev/null +++ b/examples/client/admin/query_roles.py @@ -0,0 +1,25 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + +from . import AdminExample + + +class QueryRoles(AdminExample): + def run(self): + policy = {} + + roles = self.client.admin_query_roles(policy) + print(roles) diff --git a/examples/client/admin/query_user_info.py b/examples/client/admin/query_user_info.py new file mode 100644 index 0000000000..24342c5500 --- /dev/null +++ b/examples/client/admin/query_user_info.py @@ -0,0 +1,26 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + +from .create_user import CreateUser + + +class QueryUserInfo(CreateUser): + def run(self): + super().run() + policy = {} + + user = self.client.admin_query_user_info(self.user, policy) + print(user) diff --git a/examples/client/admin/query_users_info.py b/examples/client/admin/query_users_info.py new file mode 100644 index 0000000000..8e3d93dc56 --- /dev/null +++ b/examples/client/admin/query_users_info.py @@ -0,0 +1,26 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + +from .create_user import CreateUser + + +class QueryUsersInfo(CreateUser): + def run(self): + super().run() + policy = {} + + users = self.client.admin_query_users_info(policy) + print(users) diff --git a/examples/client/admin/revoke_privileges.py b/examples/client/admin/revoke_privileges.py new file mode 100644 index 0000000000..2d6e011a3a --- /dev/null +++ b/examples/client/admin/revoke_privileges.py @@ -0,0 +1,28 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ +from .create_role import CreateRole +import aerospike +import time + + +class RevokePrivileges(CreateRole): + def run(self): + super().run() + policy = {} + privileges = [{"code": aerospike.PRIV_SYS_ADMIN}] + + self.client.admin_revoke_privileges(self.role, privileges, policy) + time.sleep(3) diff --git a/examples/client/admin/revoke_roles.py b/examples/client/admin/revoke_roles.py new file mode 100644 index 0000000000..8473bf0b85 --- /dev/null +++ b/examples/client/admin/revoke_roles.py @@ -0,0 +1,26 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + +from .grant_roles import GrantRoles +import time + + +class RevokeRoles(GrantRoles): + def run(self): + super().run() + policy = {} + self.client.admin_revoke_roles(self.user, self.roles, policy) + time.sleep(3) diff --git a/examples/client/admin/set_password.py b/examples/client/admin/set_password.py new file mode 100644 index 0000000000..3a48e855eb --- /dev/null +++ b/examples/client/admin/set_password.py @@ -0,0 +1,29 @@ +################################################################################ +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + + +from .create_user import CreateUser +import time + + +class SetPassword(CreateUser): + def run(self): + super().run() + policy = {} + password = "bar" + + self.client.admin_set_password(self.user, password, policy) + time.sleep(3) diff --git a/examples/client/aggregate.py b/examples/client/aggregate.py index f5a74bcd89..1a43a51988 100644 --- a/examples/client/aggregate.py +++ b/examples/client/aggregate.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,186 +16,39 @@ ########################################################################## -from __future__ import print_function -import aerospike -import json -import re -import sys import os.path -from optparse import OptionParser from aerospike import predicates as p +from .. import ExampleWithIndex, UDFExample -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options] where module function [args...]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-b", "--bins", dest="bins", type="string", action="append", - help="Bins to select from each record.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) < 3: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)], - 'lua': { - 'user_path': os.path.dirname(__file__) - } -} - -########################################################################## -# Application -########################################################################## +class Aggregate(ExampleWithIndex, UDFExample): + def run(self): + predicates = [ + p.equals(self.BIN_NAME, 1), + p.between(self.BIN_NAME, 1, 3) + ] -exitCode = 0 + for predicate in predicates: + # If predicate is provided, then perform a query + query = self.client.query(self.namespace, self.set_name) + query.where(predicate) + BINS = [self.BIN_NAME] + query.select(*BINS) + MODULE = "stream_example" + FUNCTION = "count" + ARGS = [] + query.apply(MODULE, FUNCTION, ARGS) -def parse_arg(s): - try: - return json.loads(s) - except ValueError: - return s + results = [] -try: + # callback to be called for each record read + def callback(result): + results.append(result) + print(result) - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - re_bin = "(.{1,14})" - re_str_eq = "\s+=\s*(?:(?:\"(.*)\")|(?:\'(.*)\'))" - re_int_eq = "\s+=\s*(\d+)" - re_int_rg = "\s+between\s+\(\s*(\d+)\s*,\s*(\d+)\s*\)" - re_w = re.compile("%s(?:%s|%s|%s)" % - (re_bin, re_str_eq, re_int_eq, re_int_rg)) - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - - args.reverse() - where = args.pop() - module = args.pop() - function = args.pop() - - # If predicate is provided, then perform a query - q = client.query(namespace, set) - w = re_w.match(where) - if w is not None: - if w.group(2): - b = w.group(1) - v = w.group(2) - q.where(p.equals(b, v)) - elif w.group(3): - b = w.group(1) - v = w.group(3) - q.where(p.equals(b, v)) - elif w.group(4): - b = w.group(1) - v = int(w.group(4)) - q.where(p.equals(b, v)) - elif w.group(5) and w.group(6): - b = w.group(1) - l = int(w.group(5)) - u = int(w.group(6)) - q.where(p.between(b, l, u)) - - if options.bins and len(options.bins) > 0: - # project specified bins - q.select(*options.bins) - - args.reverse() - argl = list(map(parse_arg, args)) - print("argl == ", argl) - q.apply(module, function, *argl) - - results = [] - - # callback to be called for each record read - def callback(result): - results.append(result) - print(result) - - # invoke the operations, and for each record invoke the callback - q.foreach(callback) - - print("---") - if len(results) == 1: - print("OK, 1 result found.") - else: - print("OK, %d results found." % len(results)) - - except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - - -########################################################################## -# Exit -########################################################################## + # invoke the operations, and for each record invoke the callback + query.foreach(callback) -sys.exit(exitCode) + print(len(results)) diff --git a/examples/client/append.py b/examples/client/append.py index f76144b620..446cacbd1b 100644 --- a/examples/client/append.py +++ b/examples/client/append.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,146 +16,16 @@ ########################################################################## -from __future__ import print_function -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--gen", dest="gen", type="int", default=10, metavar="", - help="Generation of the record being written.") - -optparser.add_option( - "--ttl", dest="ttl", type="int", default=1000, metavar="", - help="TTL of the record being written.") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: +from .. import Example - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - key = args.pop() +class Append(Example): + def run(self): record = { 'example_name': 'John', - 'example_age': 1 } + self.client.put(self.key, record) - meta = {} - if (options.gen): - meta['gen'] = options.gen - if (options.ttl): - meta['ttl'] = options.ttl - policy = None - - # invoke operation - - client.put((namespace, set, key), record, meta, policy) - - print(record) - print("---") - print("OK, 1 record written.") - - client.append( - (namespace, set, key), "example_name", " Smith", meta, policy) - (key, meta, bins) = client.get((namespace, set, key)) - + self.client.append(self.key, "example_name", " Smith") + _, _, bins = self.client.get(self.key) print(bins) - print("---") - print("OK, 1 record appended.") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/apply.py b/examples/client/apply.py index e497a5fe7a..ae7e1e65ed 100644 --- a/examples/client/apply.py +++ b/examples/client/apply.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,139 +16,16 @@ ########################################################################## -from __future__ import print_function -import aerospike -import json -import sys - -from optparse import OptionParser - -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options] key module function [args...]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") +from .. import ExampleWithRecord, UDFExample -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") +class Apply(ExampleWithRecord, UDFExample): + def run(self): + self.client.udf_put("./examples/client/simple.lua") -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--gen", dest="gen", type="int", default=None, metavar="", - help="Generation of the record being written.") - -optparser.add_option( - "--ttl", dest="ttl", type="int", default=None, metavar="", - help="TTL of the record being written.") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) < 3: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - - -def parse_arg(s): - try: - return json.loads(s) - except ValueError: - return s - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - - args.reverse() - key = args.pop() - module = args.pop() - function = args.pop() - - # invoke operation - args.reverse() - argl = list(map(parse_arg, args)) - res = client.apply((namespace, set, key), module, function, argl) + module = "simple" + function = "add" + args = [1, 2] + res = self.client.apply(self.key, module, function, args) print(res) - print("---") - print("OK, 1 UDF applied.") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/batch_read.py b/examples/client/batch_read.py new file mode 100644 index 0000000000..9fc46cb45e --- /dev/null +++ b/examples/client/batch_read.py @@ -0,0 +1,45 @@ + +########################################################################## +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +########################################################################## + + +from aerospike_helpers.batch.records import BatchRecords +from .. import ExampleWithRecord + + +class BatchRead(ExampleWithRecord): + def show_records(self, records: BatchRecords): + print(f"{len(records.batch_records)} records were found") + for br in records.batch_records: + pk = br.key + print("Record with digest", pk[3], "has result code", br.result, "with record", br.record) + + def run(self): + # Get records + keys = [self.key, self.non_existent_key] + print("All bins should be returned") + records = self.client.batch_read(keys) + self.show_records(records) + + # Select bins + print("\"a\" should be filtered out") + records = self.client.batch_read(keys, bins=["b"]) + self.show_records(records) + + # Verify existence of records + print("Bins should not be returned") + records = self.client.batch_read(keys, bins=[]) + self.show_records(records) diff --git a/examples/client/bin_ops.py b/examples/client/bin_ops.py index 35826bfb3d..e4a624262f 100644 --- a/examples/client/bin_ops.py +++ b/examples/client/bin_ops.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,124 +14,59 @@ # See the License for the specific language governing permissions and # limitations under the License. ########################################################################## +from .. import Example -from __future__ import print_function import aerospike +from aerospike_helpers.operations import operations import pprint -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Application -########################################################################## -exitCode = 0 -try: - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - config = {'hosts': [(options.host, options.port)]} - client = aerospike.client(config).connect( - options.username, options.password) - # ---------------------------------------------------------------------------- - # Perform Operations - # ---------------------------------------------------------------------------- - - try: +class BinOps(Example): + def run(self): pp = pprint.PrettyPrinter(indent=2) - client.put(('test', 'cats', 'mr. peppy'), {'breed': 'persian'}, + key = ('test', 'cats', 'mr. peppy') + + self.client.put(key, {'breed': 'persian'}, policy={'exists': aerospike.POLICY_EXISTS_CREATE_OR_REPLACE, - 'key': aerospike.POLICY_KEY_DIGEST}, - meta={'ttl': 120}) - (key, meta, bins) = client.get(('test', 'cats', 'mr. peppy')) + 'key': aerospike.POLICY_KEY_DIGEST, 'ttl': 120}) + (key, meta, bins) = self.client.get(key) + print("Before:", bins) - client.increment( - key, 'lives', -1, {'gen': 2, 'ttl': 1000}, policy={'total_timeout': 1500}) - (key, meta, bins) = client.get(key) + self.client.increment( + key, 'lives', -1, {'gen': 2}, policy={'total_timeout': 1500, 'ttl': 1000}) + (key, meta, bins) = self.client.get(key) + print("After:", bins) # the key we got back when we fetched the record with get() is useable # as-is because it contains the record's digest - client.increment(key, 'lives', -1) - (key, meta, bins) = client.get(key) + self.client.increment(key, 'lives', -1) + (key, meta, bins) = self.client.get(key) + # kitty lost a life, unfortunately print("Poor Kitty:", bins) - client.put(key, {'owner': 'Fry'}) - client.prepend(key, 'owner', 'Philip J. ') - client.append(key, 'owner', ' Esq.') + self.client.put(key, {'owner': 'Fry'}) + self.client.prepend(key, 'owner', 'Philip J. ') + self.client.append(key, 'owner', ' Esq.') + # kitty loses another life, gains a color, all as part of a record # multi-op - ops = [{'bin': 'color', 'op': aerospike.OPERATOR_WRITE, 'val': 'smoke'}, - {'bin': 'lives', 'op': aerospike.OPERATOR_INCR, 'val': -1}, - {'bin': 'ailments', 'op': aerospike.OPERATOR_READ}, - {'bin': 'lives', 'op': aerospike.OPERATOR_READ}] - (key, meta, bins) = client.operate(key, ops) + ops = [ + operations.write(bin_name="color", write_item="smoke"), + operations.increment(bin_name="lives", amount=-1), + operations.read("ailments"), + operations.read("lives") + ] + (key, meta, bins) = self.client.operate(key, ops) print("After calling operate(), kitty is down to", bins['lives'], "lives") pp.pprint(bins) # display the record as it is after all the operations - (key, meta, bins) = client.get(key) + (key, meta, bins) = self.client.get(key) print("\nRecord\n======\nKey\n---") pp.pprint(key) print("Meta\n----") pp.pprint(meta) print("Bins\n----") pp.pprint(bins) - - except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/client_big_list.py b/examples/client/client_big_list.py index c5fc2f7e6f..506945aaaa 100644 --- a/examples/client/client_big_list.py +++ b/examples/client/client_big_list.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- ########################################################################## -# Copyright 2018 Aerospike, Inc. +# Copyright 2018-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,11 +14,12 @@ # limitations under the License. ########################################################################## -from __future__ import print_function import argparse +from .. import Example import aerospike from aerospike import exception as as_exceptions +from aerospike_helpers.operations import list_operations, operations ''' This provides a rough implementation of an expandable list for Aerospike It utilizes a metadata record to provide information about associated subrecords. @@ -65,7 +65,7 @@ class ASMetadataRecordTooLarge(Exception): pass -class ClientSideBigList(object): +class ClientSideBigList: ''' Abstraction around an unbounded size list for Aerospike. Relies on a top level record containing metadata about subrecords. When a subrecord fills up, a new subrecord is created @@ -172,7 +172,7 @@ def get_all_entries(self, extended_search=False): ) keys.append(key) - subrecords = self.client.get_many(keys) + subrecords = self.client.batch_read(keys) entries = self._get_items_from_subrecords(subrecords) # Try to get subrecords beyond the listed amount. @@ -243,8 +243,11 @@ def _create_or_update_subrecord(self, item, subrecord_number, generation, retrie subrecord_userkey = self._make_user_key(subrecord_number) subrecord_record_key = (self.ns, self.set, subrecord_userkey) try: - self.client.list_append( - subrecord_record_key, self.subrecord_list_bin, item) + ops = [ + list_operations.list_append(self.subrecord_list_bin, item) + ] + self.client.operate( + subrecord_record_key, ops) except as_exceptions.RecordTooBig as e: if retries_remaining == 0: raise e @@ -260,7 +263,10 @@ def _update_metadata_record(self, generation): update_policy = {'gen': aerospike.POLICY_GEN_EQ} meta = {'gen': generation} try: - self.client.increment(self.metadata_key, self.subrecourd_count_name, 1, meta=meta, policy=update_policy) + ops = [ + operations.increment(self.subrecourd_count_name, 1) + ] + self.client.operate(self.metadata_key, ops, meta=meta, policy=update_policy) except as_exceptions.RecordTooBig: raise ASMetadataRecordTooLarge except as_exceptions.RecordGenerationError: @@ -286,7 +292,8 @@ def _get_items_from_subrecords(self, subrecords): entries = [] # If a subrecord was included in the header of the top level record, but the matching subrecord # was not found, ignore it. - for _, _, sr_bins in subrecords: + for br in subrecords.batch_records: + sr_bins = br.record[2] if sr_bins: entries.extend(sr_bins[self.subrecord_list_bin]) return entries @@ -314,61 +321,32 @@ def sr_iter(): # Instantiate the generator and return it. return sr_iter() +class ClientSideBigListExample(Example): + def run(self): + ''' + Simple tests demonstrating the functionality. + If the database is set up with a small enough write block-size, several subrecords + will be created. + ''' + item_count = 1000 -def main(): - ''' - Simple tests demonstrating the functionality. - If the database is set up with a small enough write block-size, several subrecords - will be created. - ''' - - optparser = argparse.ArgumentParser() - - optparser.add_argument( - "--host", type=str, default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - - optparser.add_argument( - "--port", type=int, default=3000, metavar="", - help="Port of the Aerospike server.") - - optparser.add_argument( - "--namespace", type=str, default="test", metavar="", - help="Namespace to use for this example") - - optparser.add_argument( - "-s", "--set", type=str, default="demo", metavar="", - help="Set to use for this example") - - optparser.add_argument( - "-i", "--items", type=int, default=1000, metavar="", - help="Number of items to store into the big list") - - options = optparser.parse_args() - print(options) - - client = aerospike.client({'hosts': [('localhost', 3000)]}).connect() - ldt = ClientSideBigList(client, 'person1_friends') - - for i in range(options.items): - # Store a reasonably large item - ldt.add_item('friend{}'.format(i) * 100) - - print("Stored {} items".format(options.items)) + ldt = ClientSideBigList(self.client, 'person1_friends') - items = ldt.get_all_entries() - _, _, bins = ldt.get_metadata_record() - print(bins) - print("Known subrecord count is: {}".format(bins['sr_count'])) - print("Fetched {} items:".format(len(items))) + for i in range(item_count): + # Store a reasonably large item + ldt.add_item('friend{}'.format(i) * 100) - count = 0 - for sr in ldt.subrecord_iterator(): - if sr: - count = count + 1 + print("Stored {} items".format(item_count)) - print("Records yielded: {}".format(count)) + items = ldt.get_all_entries() + _, _, bins = ldt.get_metadata_record() + print(bins) + print("Known subrecord count is: {}".format(bins['sr_count'])) + print("Fetched {} items:".format(len(items))) + count = 0 + for sr in ldt.subrecord_iterator(): + if sr: + count = count + 1 -if __name__ == '__main__': - main() + print("Records yielded: {}".format(count)) diff --git a/examples/client/delete.py b/examples/client/delete.py index 3bb9677a4d..c59411d5cb 100644 --- a/examples/client/delete.py +++ b/examples/client/delete.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,134 +15,19 @@ # limitations under the License. ########################################################################## -import asyncio -import sys -import aerospike -import array - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", default="ram", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", default="ram", metavar="", - help="Password to connect to database.") +from aerospike import exception as e +from .. import ExampleWithRecord -optparser.add_option( - "-h", "--host", dest="host", type="string", default="as-s1.as-network.com", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--timeout", dest="timeout", type="int", default=1000, metavar="", - help="Client timeout") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Namespace of database.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Set to use within namespace of database.") - -optparser.add_option( - "-c", "--test_count", dest="test_count", type="int", default=128, metavar="", - help="Number of test cases to run.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## -config = { - 'hosts': [(options.host, options.port)], - 'policies': { - 'total_timeout': options.timeout - } -} +class Delete(ExampleWithRecord): + def run(self): + self.client.remove(self.key) -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - test_count = options.test_count - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - policy = { - 'total_timeout': options.timeout - } - meta = None - print(f"IO test count:{test_count}") - def delete(namespace, set, test_count): - for i in range(0, test_count): - key = {'ns': namespace, \ - 'set':set, \ - 'key': str(i), \ - 'digest': aerospike.calc_digest(namespace, set, str(i))} - - policy = None - - client.remove(key) - - - delete(namespace, set, test_count) - print(f"Deleted {test_count} records") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - rc = 1 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## + try: + self.client.remove(self.key) + except e.RecordNotFound: + print(f"Could not find {self.key}") -sys.exit(exitCode) + # Override default destructor + def cleanup(self): + pass diff --git a/examples/client/exists.py b/examples/client/exists.py index 9dfd67d8e1..bd1cea5267 100644 --- a/examples/client/exists.py +++ b/examples/client/exists.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,117 +15,13 @@ # limitations under the License. ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: +from .. import ExampleWithRecord - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - client = aerospike.client(config).connect( - options.username, options.password) - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - key = args.pop() - (key, metadata) = client.exists((namespace, set, key)) - if metadata is not None: - print(key, metadata) - print("---") - print("OK, 1 record found.") - else: - print('error: Not Found.', file=sys.stderr) - exitCode = 1 - - except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## +class Exists(ExampleWithRecord): + def run(self): + key, metadata = self.client.exists(self.key) + print(key, metadata) -sys.exit(exitCode) + key, metadata = self.client.exists(self.non_existent_key) + print(key, metadata) diff --git a/examples/client/exists_many.py b/examples/client/exists_many.py deleted file mode 100644 index 5f597b3afb..0000000000 --- a/examples/client/exists_many.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -########################################################################## -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -########################################################################## - - -from __future__ import print_function -import aerospike -import sys - -from optparse import OptionParser - - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-k", "--keys", dest="keys", type="string", default="", metavar="", - help="Keys to be accessed in the database server. Should be specified as 'name','name1','name2' etc") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - # args.pop() - - keys = options.keys.split(',') - keylist = [] - for key in keys: - individualkey = (namespace, set, key) - keylist.append(individualkey) - - records = client.exists_many(keylist) - - if records != None: - print(records) - print("---") - print("OK, %d records found." % len(records)) - else: - print('error: Not Found.', file=sys.stderr) - exitCode = 1 - - except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/get.py b/examples/client/get.py index c4ae106efb..8e85ccaa85 100644 --- a/examples/client/get.py +++ b/examples/client/get.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,148 +15,13 @@ # limitations under the License. ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") +from .. import ExampleWithRecord -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--timeout", dest="timeout", type="int", default=1000, metavar="", - help="Client timeout") - -optparser.add_option( - "--read-timeout", dest="read_timeout", type="int", default=1000, metavar="", - help="Client read timeout") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--no-key", dest="nokey", action="store_true", - help="Do not return the key") - -optparser.add_option( - "--no-metadata", dest="nometadata", action="store_true", - help="Do not return the metadata") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)], - 'policies': { - 'total_timeout': options.timeout - } -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - key = args.pop() +class Get(ExampleWithRecord): + def run(self): policy = { - 'total_timeout': options.read_timeout + 'total_timeout': 300 } - - (key, metadata, record) = client.get((namespace, set, key), policy) - - if metadata is not None: - if options.nometadata and options.nokey: - print(record) - elif options.nometadata: - print(key, record) - elif options.nokey: - print(metadata, record) - else: - print(key, metadata, record) - print("---") - print("OK, 1 record found.") - else: - print('error: Not Found.', file=sys.stderr) - exitCode = 1 - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) + record = self.client.get(self.key, policy) + print(record) diff --git a/examples/client/get_async.py b/examples/client/get_async.py deleted file mode 100644 index 693496a98f..0000000000 --- a/examples/client/get_async.py +++ /dev/null @@ -1,159 +0,0 @@ -# -*- coding: utf-8 -*- -########################################################################## -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -########################################################################## - -import asyncio -import sys -import aerospike -import time -from aerospike_helpers.awaitable import io - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", default="ram", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", default="ram", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="as-s1.as-network.com", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--timeout", dest="timeout", type="int", default=1000, metavar="", - help="Client timeout") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Namespace of database.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Set to use within namespace of database.") - -optparser.add_option( - "-c", "--test_count", dest="test_count", type="int", default=128, metavar="", - help="Number of async IO to spawn.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)], - 'policies': { - 'total_timeout': options.timeout - } -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - print(f"Connecting to {options.host}:{options.port} with {options.username}:{options.password}") - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - io_results = {} - test_count = options.test_count - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - policy = { - 'total_timeout': options.timeout - } - meta = None - - print(f"IO async test count:{test_count}") - - async def async_io(namespace, set, i): - key = (namespace, \ - set, \ - str(i), \ - client.get_key_digest(namespace, set, str(i))) - context = {'result': {}} - io_results[key[2]] = context - result = None - try: - result = await io.get(client, key, policy) - except Exception as eargs: - print(f"error: {eargs.code}, {eargs.msg}, {eargs.file}, {eargs.line}") - print(result) - io_results[key[2]]['result'] = result - async def main(): - func_list = [] - for i in range(test_count): - func_list.append(async_io(namespace, set, i)) - await asyncio.gather(*func_list) - asyncio.get_event_loop().run_until_complete(main()) - print(io_results) - print(f"get_async completed with returning {len(io_results)} records") - except Exception as e: - print(f"error: {0} ".format(e), file=sys.stderr) - rc = 1 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/get_key_digest.py b/examples/client/get_key_digest.py index 0153092d61..b307e1e70f 100644 --- a/examples/client/get_key_digest.py +++ b/examples/client/get_key_digest.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,120 +16,11 @@ ########################################################################## -from __future__ import print_function - +from .. import ExampleWithRecord import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--timeout", dest="timeout", type="int", default=1000, metavar="", - help="Client timeout") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)], - 'policies': { - 'read': {'total_timeout': options.timeout} - } -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - key = args.pop(0) - - digest = aerospike.calc_digest(namespace, set, key) - print("---") - print("Digest is: ", digest) - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## -sys.exit(exitCode) +class CalcDigest(ExampleWithRecord): + def run(self): + digest = aerospike.calc_digest(self.namespace, self.set_name, self.user_key) + print(digest) diff --git a/examples/client/get_many.py b/examples/client/get_many.py deleted file mode 100644 index c2a1f8f512..0000000000 --- a/examples/client/get_many.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -########################################################################## -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -########################################################################## - - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-k", "--keys", dest="keys", type="string", default="", metavar="", - help="Keys to be accessed in the database server. Should be specified as 'name','name1','name2' etc") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - # args.pop() - - keys = options.keys.split(',') - keylist = [] - for key in keys: - individualkey = (namespace, set, key) - keylist.append(individualkey) - - records = client.get_many(keylist) - - if records is not None: - print(records) - print("---") - print("OK, %d records found." % len(records)) - else: - print('error: Not Found.', file=sys.stderr) - exitCode = 1 - - except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/get_nodes.py b/examples/client/get_nodes.py index 6171e5bc2c..114a361145 100644 --- a/examples/client/get_nodes.py +++ b/examples/client/get_nodes.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,102 +16,10 @@ ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) +from .. import Example - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - response = client.get_nodes() - - if response is not None: - print(response) - print("---") - else: - print('error: Not Found.', file=sys.stderr) - exitCode = 1 - - except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## -sys.exit(exitCode) +class GetNodes(Example): + def run(self): + response = self.client.get_nodes() + print(response) diff --git a/examples/client/increment.py b/examples/client/increment.py index 303fa11615..9d3c664272 100644 --- a/examples/client/increment.py +++ b/examples/client/increment.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,150 +16,27 @@ ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--gen", dest="gen", type="int", default=10, metavar="", - help="Generation of the record being written.") - -optparser.add_option( - "--ttl", dest="ttl", type="int", default=1000, metavar="", - help="TTL of the record being written.") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- +from .. import ExampleWithRecord - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - key = args.pop() +class Increment(ExampleWithRecord): + def run(self): record = { - 'example_name': 'John', 'example_age': 1 } - meta = {'ttl': options.ttl, 'gen': options.gen} - policy = None - # invoke operation - client.put((namespace, set, key), record, meta, policy) - - print("---") - print("OK, 1 record written.") + self.client.put(self.key, record) - (returnedkey, meta, bins) = client.get((namespace, set, key)) + _, _, bins = self.client.get(self.key) - print("---") print("Before increment operation") print(bins) - client.increment((namespace, set, key), "example_age", 5, meta, policy) - print("---") - print("OK, 1 record touched.") + self.client.increment(self.key, "example_age", 5) - (returnedkey, meta, bins) = client.get((namespace, set, key)) + _, _, bins = self.client.get(self.key) - print("---") print("After increment operation") print(bins) - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/index_create.py b/examples/client/index_create.py index 8968a8ba9c..c15ab61124 100644 --- a/examples/client/index_create.py +++ b/examples/client/index_create.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,127 +15,14 @@ # limitations under the License. ########################################################################## - -from __future__ import print_function - +from .. import Example import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] bin index_name" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-t", "--type", dest="type", type="string", default="string", metavar="", - help="The type of index to create") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) -if len(args) != 2: - optparser.print_help() - print() - sys.exit(1) -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - args.reverse() +class IndexCreate(Example): + def run(self): policy = {} - namespace = options.namespace - set = options.set - type = options.type - bin = args.pop() - index_name = args.pop() - - if type == 'string': - client.index_string_create(namespace, set, bin, index_name, policy) - print("OK, 1 Secondary Index Created ") - elif type == 'integer': - client.index_integer_create( - namespace, set, bin, index_name, policy) - print("OK, 1 Secondary Index Created ") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## + self.client.index_single_value_create(self.namespace, self.set_name, self.BIN_NAME, aerospike.INDEX_INTEGER, "index_name", policy) -sys.exit(exitCode) + def cleanup(self): + self.client.index_remove(self.namespace, "index_name") diff --git a/examples/client/index_remove.py b/examples/client/index_remove.py index 8f245adb82..0808045dd6 100644 --- a/examples/client/index_remove.py +++ b/examples/client/index_remove.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,109 +16,13 @@ ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] bin index_name" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") +from .. import ExampleWithIndex -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: +class IndexRemove(ExampleWithIndex): + def run(self): policy = {} - namespace = options.namespace - index_name = args.pop() - - client.index_remove(namespace, index_name, policy) - print("OK, 1 Integer Secondary Index Removed ") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## + self.client.index_remove(self.namespace, self.INDEX_NAME, policy) -sys.exit(exitCode) + def cleanup(self): + super().cleanup() diff --git a/examples/client/info.py b/examples/client/info.py index 52acf0f8de..329263e5cf 100644 --- a/examples/client/info.py +++ b/examples/client/info.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,119 +16,36 @@ ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] [REQUEST]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## +from .. import Example -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: +class Info(Example): + def run(self): + # Default info request request = "statistics" - if len(args) > 0: - request = ' '.join(args) - - for node, (err, res) in list(client.info_all(request).items()): - if res is not None: - res = res.strip() - if len(res) > 0: - entries = res.split(';') - if len(entries) > 1: - print("{0}:".format(node)) - for entry in entries: - entry = entry.strip() - if len(entry) > 0: - count = 0 - if "=" in entry: - (name, value) = entry.split('=') - if count > 0: - print( - " {0}: {1}".format(name, value)) - else: - print( - " - {0}: {1}".format(name, value)) - count += 1 - else: - print("{0}: {1}".format(node, res)) - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## -sys.exit(exitCode) + # TODO: needs review + response = self.client.info_all(request) + for node, (_, res) in response.items(): + if res is None: + continue + + res = res.strip() + if len(res) == 0: + continue + + entries = res.split(';') + if len(entries) <= 1: + print("{0}: {1}".format(node, res)) + + print("{0}:".format(node)) + for entry in entries: + entry = entry.strip() + if len(entry) == 0: + continue + if "=" not in entry: + continue + + (name, value) = entry.split('=') + print(" - {0}: {1}".format(name, value)) diff --git a/examples/client/is_connected.py b/examples/client/is_connected.py index 2991c83117..8d767606c9 100644 --- a/examples/client/is_connected.py +++ b/examples/client/is_connected.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,119 +14,12 @@ # See the License for the specific language governing permissions and # limitations under the License. ########################################################################## +from .. import Example -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 0: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - if client.is_connected() == True: - print("Connected to Aerospike DB.") - - except Exception as xxx_todo_changeme: - (code, msg, file, line) = xxx_todo_changeme.args - if code == 1: - print("error: Connect failed") - else: - print( - "error: {0}".format((code, msg, file, line)), file=sys.stderr) - rc = 1 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## +class IsConnected(Example): + def run(self): + print(self.client.is_connected()) -sys.exit(exitCode) + self.client.close() + print(self.client.is_connected()) diff --git a/examples/client/kvs.py b/examples/client/kvs.py index 251c944ff9..ffa651f9c7 100644 --- a/examples/client/kvs.py +++ b/examples/client/kvs.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,70 +16,11 @@ ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - config = {'hosts': [(options.host, options.port)]} - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: +from .. import UDFExample +class KVS(UDFExample): + def run(self): print( '########################################################################') print('PUT') @@ -96,7 +37,8 @@ 'm': {'a': 2, 'b': 4, 'c': 8, 'd': 16} } print(rec) - client.put(('test', 'demo', str(i)), rec) + KEY = ('test', 'demo', str(i)) + self.client.put(KEY, rec) print( '########################################################################') @@ -105,7 +47,8 @@ '########################################################################') for i in range(1, 1000): - (key, metadata) = client.exists(('test', 'demo', str(i))) + KEY = ('test', 'demo', str(i)) + (key, metadata) = self.client.exists(KEY) print(key, metadata) print( @@ -115,7 +58,8 @@ '########################################################################') for i in range(1, 1000): - (key, metadata, record) = client.get(('test', 'demo', str(i))) + KEY = ('test', 'demo', str(i)) + (key, metadata, record) = self.client.get(KEY) print(key, metadata, record) print( @@ -124,11 +68,11 @@ print( '########################################################################') - client.udf_put('simple.lua') + self.client.udf_put('./examples/client/simple.lua') for i in range(1, 1000): key = ('test', 'demo', 'key{0}'.format(i)) - val1 = client.apply(key, 'simple', 'concat', ['a', 30000]) + val1 = self.client.apply(key, 'simple', 'concat', ['a', 30000]) print(val1) print( @@ -138,24 +82,5 @@ '########################################################################') for i in range(1, 1000): - client.remove(('test', 'demo', str(i))) - - except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) + KEY = ('test', 'demo', str(i)) + self.client.remove(KEY) diff --git a/examples/client/multi_thread.py b/examples/client/multi_thread.py index 43f3885687..56e15edc33 100644 --- a/examples/client/multi_thread.py +++ b/examples/client/multi_thread.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,7 +15,6 @@ # limitations under the License. ########################################################################## -from __future__ import print_function import aerospike import sys @@ -23,136 +22,79 @@ import time import threading -from optparse import OptionParser +from .. import Example from aerospike import exception as e -########################################################################## -# Options Parsing -########################################################################## -usage = "usage: %prog [options]" +class Multithread(Example): -optparser = OptionParser(usage=usage, add_help_option=False) + numKeys = 10000 + numReads = 100000 + fNames = ('Jimmy', 'Johnny', 'Sammy', 'Sally', 'Sandy', 'Mandy', 'Billy') + lNames = ('Bama', 'Mama', 'Sama', 'Lama', 'Cama', 'Rama', 'Tama') + numThreads = 5 -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") + def writeWork(self, nKeys): + t0 = float(time.time()) -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") + for x in range(0, nKeys): + kstr = 'k' + str(x) + key = (self.namespace, self.set_name, kstr) -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", - metavar="
", - help="Address of Aerospike server.") + try: + # Write a record + self.client.put(key, { + 'name': random.choice(self.fNames) + ' ' + random.choice(self.lNames), + 'age': random.randint(10, 100), + 'value': x + }) + except Exception as e: + print('write error {0}'.format(e)) -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") + if x % 1000 == 0 and x > 0: + print('Wrote {0} records at T = {1:.2f} sec'.format( + x, float(time.time()) - t0)) -(options, args) = optparser.parse_args() + print('Wrote {0} records at T = {1:.2f} sec'.format( + nKeys, float(time.time()) - t0)) -if options.help: - optparser.print_help() - print() - sys.exit(1) -########################################################################## -# Client Configuration -########################################################################## + def readWork(self, nReads, thrName): + print('Thread #{0} is starting to read {1} records'.format( + thrName, nReads)) -config = { - 'hosts': [(options.host, options.port)], - 'lua': {'user_path': '.'} -} + # Read records + t0 = float(time.time()) -########################################################################## -# Application -########################################################################## + for x in range(0, nReads): + kstr = 'k' + str(random.randrange(0, self.numKeys)) + key = (self.namespace, self.set_name, kstr) + try: + (key, _, _) = self.client.get(key) + except aerospike.exception.ClientError as e: + print('Aerospike Error: {0} [{1}]'.format(e.msg, e.code)) + return None + + if x % 10000 == 0 and x > 0: + print('Thread #{0} : Read {1} records at T = {2:.2f} sec'.format( + thrName, x, float(time.time()) - t0)) + print('Thread #{0} : Read {1} records at T = {2:.2f} sec'.format( + thrName, nReads, float(time.time()) - t0)) + + + def run(self): + print('Writing data into Aerospike DB') + self.writeWork(self.numKeys) + + print('Reading data from Aerospike DB using {0} threads'.format(self.numThreads)) + t = [] + + for i in range(self.numThreads): + thread = threading.Thread(target=self.readWork, + args=(self.numReads // self.numThreads, str(i))) + thread.start() + t.append(thread) -try: - client = aerospike.client(config).connect( - options.username, options.password) -except e.ClientError as exception: - print('Error: {0} [{1}]'.format(exception.msg, exception.code)) - sys.exit(1) - -namespace = 'test' -testSet = 'test' -numKeys = 10000 -numReads = 1000000 -fNames = ('Jimmy', 'Johnny', 'Sammy', 'Sally', 'Sandy', 'Mandy', 'Billy') -lNames = ('Bama', 'Mama', 'Sama', 'Lama', 'Cama', 'Rama', 'Tama') -numThreads = 5 - - -def writeWork(nKeys): - t0 = float(time.time()) - - for x in range(0, nKeys): - kstr = 'k' + str(x) - key = (namespace, testSet, kstr) - - try: - # Write a record - client.put(key, { - 'name': random.choice(fNames) + ' ' + random.choice(lNames), - 'age': random.randint(10, 100), - 'value': x - }) - except Exception as e: - print('write error {0}'.format(e)) - - if x % 1000 == 0 and x > 0: - print('Wrote {0} records at T = {1:.2f} sec'.format( - x, float(time.time()) - t0)) - - print('Wrote {0} records at T = {1:.2f} sec'.format( - nKeys, float(time.time()) - t0)) - - -def readWork(nReads, thrName): - print('Thread #{0} is starting to read {1} records'.format( - thrName, nReads)) - - # Read records - t0 = float(time.time()) - - for x in range(0, nReads): - kstr = 'k' + str(random.randrange(0, numKeys)) - key = (namespace, testSet, kstr) - try: - (key, _, _) = client.get(key) - except aerospike.exception.ClientError as e: - print('Aerospike Error: {0} [{1}]'.format(e.msg, e.code)) - return None - - if x % 10000 == 0 and x > 0: - print('Thread #{0} : Read {1} records at T = {2:.2f} sec'.format( - thrName, x, float(time.time()) - t0)) - print('Thread #{0} : Read {1} records at T = {2:.2f} sec'.format( - thrName, nReads, float(time.time()) - t0)) - - -print('Writing data into Aerospike DB') -writeWork(numKeys) - -print('Reading data from Aerospike DB using {0} threads'.format(numThreads)) -t = [] - -for i in range(numThreads): - thread = threading.Thread(target=readWork, - args=(numReads // numThreads, str(i))) - thread.start() - t.append(thread) - -for i in range(numThreads): - t[i].join() - -print('Finished. Closing Aerospike connection.') -client.close() + for i in range(self.numThreads): + t[i].join() diff --git a/examples/client/operate.py b/examples/client/operate.py index 999280ddda..76ddaf5f82 100644 --- a/examples/client/operate.py +++ b/examples/client/operate.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,160 +15,30 @@ # limitations under the License. ########################################################################## -from __future__ import print_function -import sys -from optparse import OptionParser +from .. import Example -import aerospike from aerospike_helpers.operations import operations as op_helpers -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--gen", dest="gen", type="int", default=10, metavar="", - help="Generation of the record being written.") - -optparser.add_option( - "--ttl", dest="ttl", type="int", default=1000, metavar="", - help="TTL of the record being written.") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - setname = options.set if options.set and options.set != 'None' else None - key = args.pop() - record_key = (namespace, setname, key) - +class Operate(Example): + def run(self): record = { 'example_name': 'John', 'example_age': 1 } - meta = {'ttl': options.ttl, 'gen': options.gen} - policy = None - - # invoke operation - - client.put(record_key, record, meta, policy) - - print("---") - print("OK, 1 record written.") + self.client.put(self.key, record) - _, _, bins = client.get(record_key) + _, _, bins = self.client.get(self.key) + print("Before operation:", bins) - print("---") - print("Before operate operation") - print(bins) - - operation_list = [ + ops = [ op_helpers.prepend("example_name", "Mr "), op_helpers.increment("example_age", 3), op_helpers.read("example_name") ] + _, _, bins = self.client.operate(self.key, ops) + print("Record returned by operate():", bins) - _, _, bins = client.operate( - record_key, operation_list, meta, policy) - print("---") - print("Record returned on operate completion") - print(bins) - - _, _, bins = client.get(record_key) - - print("---") - print("After operate operation") - print(bins) - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) + _, _, bins = self.client.get(self.key) + print("After operation:", bins) diff --git a/examples/client/prepend.py b/examples/client/prepend.py index cb14c0265e..bbea7048de 100644 --- a/examples/client/prepend.py +++ b/examples/client/prepend.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,143 +15,17 @@ # limitations under the License. ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--gen", dest="gen", type="int", default=10, metavar="", - help="Generation of the record being written.") - -optparser.add_option( - "--ttl", dest="ttl", type="int", default=1000, metavar="", - help="TTL of the record being written.") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 +from .. import Example -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - key = args.pop() +class Prepend(Example): + def run(self): record = { 'example_name': 'John', - 'example_age': 1 } - meta = {'ttl': options.ttl, 'gen': options.gen} - policy = None - - # invoke operation - - client.put((namespace, set, key), record, meta, policy) - - print(record) - print("---") - print("OK, 1 record written.") - - client.prepend( - (namespace, set, key), "example_name", "Mr ", meta, policy) - (key, meta, bins) = client.get((namespace, set, key)) + self.client.put(self.key, record) + self.client.prepend(self.key, "example_name", "Mr ") + _, _, bins = self.client.get(self.key) print(bins) - print("---") - print("OK, 1 record prepended.") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/put.py b/examples/client/put.py index 17eea90085..7edc9c1dd4 100644 --- a/examples/client/put.py +++ b/examples/client/put.py @@ -1,6 +1,8 @@ -# -*- coding: utf-8 -*- +from .. import Example + + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,99 +18,8 @@ ########################################################################## -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--gen", dest="gen", type="int", default=5, metavar="", - help="Generation of the record being written.") - -optparser.add_option( - "--ttl", dest="ttl", type="int", default=1000, metavar="", - help="TTL of the record being written.") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) == 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - key = args.pop() - +class Put(Example): + def run(self): record = { 'i': 123, 'f': 3.1415, @@ -120,32 +31,4 @@ 'l': [123, 'abc', '안녕하세요', ['x', 'y', 'z'], {'x': 1, 'y': 2, 'z': 3}], 'm': {'i': 123, 's': 'abc', 'u': '안녕하세요', 'l': ['x', 'y', 'z'], 'd': {'x': 1, 'y': 2, 'z': 3}} } - - meta = {'ttl': options.ttl, 'gen': options.gen} - policy = None - # invoke operation - client.put((namespace, set, key), record, meta, policy) - - print(record) - print("---") - print("OK, 1 record written.") - - except Exception as e: - #print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - #print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) + self.client.put(self.key, record) diff --git a/examples/client/put_async.py b/examples/client/put_async.py deleted file mode 100644 index 907ba80598..0000000000 --- a/examples/client/put_async.py +++ /dev/null @@ -1,169 +0,0 @@ -# -*- coding: utf-8 -*- -########################################################################## -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -########################################################################## - -import asyncio -import sys -import aerospike -import time -from aerospike_helpers.awaitable import io - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", default="ram", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", default="ram", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="as-s1.as-network.com", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--timeout", dest="timeout", type="int", default=1000, metavar="", - help="Client timeout") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Namespace of database.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Set to use within namespace of database.") - -optparser.add_option( - "-c", "--test_count", dest="test_count", type="int", default=128, metavar="", - help="Number of async IO to spawn.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)], - 'policies': { - 'total_timeout': options.timeout - } -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - print(f"Connecting to {options.host}:{options.port} with {options.username}:{options.password}") - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - io_results = {} - test_count = options.test_count - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - policy = { - 'total_timeout': options.timeout - } - meta = None - - print(f"IO async test count:{test_count}") - - async def async_io(namespace, set, i): - futures = [] - key = (namespace, \ - set, \ - str(i), \ - client.get_key_digest(namespace, set, str(i))) - record = { - 'i': i, - 'f': 3.1415, - 's': 'abc', - 'u': '안녕하세요', - #'b': bytearray(['d','e','f']), - 'l': [i, 'abc', 'வணக்கம்', ['x', 'y', 'z'], {'x': 1, 'y': 2, 'z': 3}], - 'm': {'i': i, 's': 'abc', 'u': 'ஊத்தாப்பம்', 'l': ['x', 'y', 'z'], 'd': {'x': 1, 'y': 2, 'z': 3}} - } - context = {'state': 0, 'result': {}} - io_results[key[2]] = context - result = None - try: - result = await io.put(client, key, record, meta, policy) - except Exception as eargs: - print(f"error: {eargs.code}, {eargs.msg}, {eargs.file}, {eargs.line}") - pass - io_results[key[2]]['result'] = result - async def main(): - func_list = [] - for i in range(test_count): - func_list.append(async_io(namespace, set, i)) - await asyncio.gather(*func_list) - asyncio.get_event_loop().run_until_complete(main()) - print(f"put_async completed with returning {len(io_results)} records") - #print(io_results) - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - rc = 1 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/query.py b/examples/client/query.py index 42730d5fda..d90da053e5 100644 --- a/examples/client/query.py +++ b/examples/client/query.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,214 +15,32 @@ # limitations under the License. ########################################################################## -from __future__ import print_function -import aerospike -import re -import sys import os.path -from optparse import OptionParser from aerospike import predicates as p +from .. import UDFExample -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options] [where]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-m", "--module", dest="module", type="string", - help="UDF Module.") -optparser.add_option( - "-f", "--function", dest="function", type="string", - help="UDF Function.") +class Query(UDFExample): + def run(self): + self.client.udf_put("./examples/client/stream_example.lua") -optparser.add_option( - "-a", "--arg", dest="arguments", action="append", type="string", - help="UDF Arguments.") + query = self.client.query(self.namespace, self.set_name) -optparser.add_option( - "-b", "--bins", dest="bins", type="string", action="append", - help="Bins to select from each record.") - -optparser.add_option( - "--show-key", dest="show_key", action="store_true", - help="If set, displays the key/digest.") - -optparser.add_option( - "--show-meta", dest="show_meta", action="store_true", - help="If set, displays the metadata.") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) > 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)], - 'lua': { - 'user_path': os.path.dirname(__file__) - } -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - re_bin = "(.{1,14})" - re_str_eq = "\s+=\s*(?:(?:\"(.*)\")|(?:\'(.*)\'))" - re_int_eq = "\s+=\s*(\d+)" - re_int_rg = "\s+between\s+\(\s*(\d+)\s*,\s*(\d+)\s*\)" - re_w = re.compile("%s(?:%s|%s|%s)" % - (re_bin, re_str_eq, re_int_eq, re_int_rg)) - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - - q = None - - if len(args) == 1: - - w = re_w.match(args[0]) - if w is not None: - - # If predicate is provided, then perform a query - q = client.query(namespace, set) - - if w.group(2): - b = w.group(1) - v = w.group(2) - q.where(p.equals(b, v)) - elif w.group(3): - b = w.group(1) - v = w.group(3) - q.where(p.equals(b, v)) - elif w.group(4): - b = w.group(1) - v = int(w.group(4)) - q.where(p.equals(b, v)) - elif w.group(5) and w.group(6): - b = w.group(1) - l = int(w.group(5)) - u = int(w.group(6)) - q.where(p.between(b, l, u)) - - if q is None: - # If predicate not provided, then perform a scan - q = client.scan(namespace, set) - - if options.bins and len(options.bins) > 0: - # project specified bins - q.select(*options.bins) - - if options.module and options.function: - if options.arguments: - q.apply(options.module, options.function, *options.arguments) - else: - q.apply(options.module, options.function) + query.select(self.BIN_NAME) + MODULE = "stream_example" + FUNCTION = "count" + ARGS = [] + query.apply(MODULE, FUNCTION, ARGS) results = [] # callback to be called for each record read - def callback(input_tuple): - (key, meta, rec) = input_tuple - results.append((key, meta, rec)) - if options.show_key and options.show_meta: - print(key, meta, rec) - elif options.show_key: - print(key, rec) - elif options.show_meta: - print(meta, rec) - else: - print(rec) + def callback(result): + results.append(result) # invoke the operations, and for each record invoke the callback - q.foreach(callback) - - print("---") - if len(results) == 1: - print("OK, 1 result found.") - else: - print("OK, %d results found." % len(results)) - - except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - - -########################################################################## -# Exit -########################################################################## + query.foreach(callback) -sys.exit(exitCode) + print(len(results)) diff --git a/examples/client/query_apply.py b/examples/client/query_apply.py index 1febe7127c..9d89ba28c7 100644 --- a/examples/client/query_apply.py +++ b/examples/client/query_apply.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,197 +15,36 @@ # limitations under the License. ########################################################################## -from __future__ import print_function import aerospike -import json -import re -import sys import os.path -from optparse import OptionParser from aerospike import predicates as p -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options] [where]" - - -def query_callback(option, opt, value, parser): - setattr(parser.values, option.dest, value.split(',')) - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") -optparser.add_option( - "-m", "--module", dest="module", type="string", - help="UDF Module.") +from .. import ExampleWithIndex, UDFExample -optparser.add_option( - "-f", "--function", dest="function", type="string", - help="UDF Function.") -optparser.add_option( - "-a", "--arg", dest="arguments", type="string", action="callback", - callback=query_callback, help="UDF Arguments.") +class QueryApply(ExampleWithIndex, UDFExample): + def run(self): + predicates = [ + p.equals(self.BIN_NAME, 1), + # p.equals(BIN, "a"), + # p.between(BIN, 1, 3) + ] -optparser.add_option( - "-b", "--bins", dest="bins", type="string", action="append", - help="Bins to select from each record.") + for predicate in predicates: + MODULE = "stream_example" + FUNCTION = "count" + ARGS = [] + query_id = self.client.query_apply(self.namespace, self.set_name, predicate, MODULE, FUNCTION, ARGS) -optparser.add_option( - "--show-key", dest="show_key", action="store_true", - help="If set, displays the key/digest.") - -optparser.add_option( - "--show-meta", dest="show_meta", action="store_true", - help="If set, displays the metadata.") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) > 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)], - 'lua': { - 'user_path': os.path.dirname(__file__) - } -} - -########################################################################## -# Application -########################################################################## + while True: + response = self.client.job_info(query_id, aerospike.JOB_QUERY) + if response['status'] == aerospike.JOB_STATUS_COMPLETED: + break -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect() - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - query_id = 0 - re_bin = "(.{1,14})" - re_str_eq = "\s+=\s*(?:(?:\"(.*)\")|(?:\'(.*)\'))" - re_int_eq = "\s+=\s*(\d+)" - re_int_rg = "\s+between\s+\(\s*(\d+)\s*,\s*(\d+)\s*\)" - re_w = re.compile("%s(?:%s|%s|%s)" % - (re_bin, re_str_eq, re_int_eq, re_int_rg)) - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - - q = None - - for i, param in enumerate(options.arguments): - if param.isdigit(): - options.arguments[i] = int(param) - - if len(args) == 1: - w = re_w.match(args[0]) - if w is not None: - - # If predicate is provided, then perform a query - - if w.group(2): - b = w.group(1) - v = w.group(2) - query_id = client.query_apply(options.namespace, - options.set, p.equals( - b, v), options.module, - options.function, options.arguments) - elif w.group(3): - b = w.group(1) - v = w.group(3) - query_id = client.query_apply(options.namespace, - options.set, p.equals( - b, v), options.module, - options.function, options.arguments) - elif w.group(4): - b = w.group(1) - v = int(w.group(4)) - query_id = client.query_apply(options.namespace, - options.set, p.equals( - b, v), options.module, - options.function, options.arguments) - elif w.group(5) and w.group(6): - b = w.group(1) - l = int(w.group(5)) - u = int(w.group(6)) - query_id = client.query_apply(options.namespace, - options.set, p.between( - b, l, u), options.module, - options.function, options.arguments) - - while True: - response = client.job_info(query_id, aerospike.JOB_QUERY) if response['status'] == aerospike.JOB_STATUS_COMPLETED: - break - - if response['status'] == aerospike.JOB_STATUS_COMPLETED: - print("Background query is successful") - else: - print("Query_apply failed") - - except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) + print("Background query is successful") + else: + print("Query_apply failed") diff --git a/examples/client/query_partition.py b/examples/client/query_partition.py new file mode 100644 index 0000000000..57f81cb7bc --- /dev/null +++ b/examples/client/query_partition.py @@ -0,0 +1,68 @@ + +########################################################################## +# Copyright 2013-2026 Aerospike, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +########################################################################## + +from .. import Example + + +class QueryPartition(Example): + def run(self): + query = self.client.query(self.namespace, self.set_name) + + query_policy = None + + STARTING_PARTITION = 1000 + query_policy = {'partition_filter': {'begin': STARTING_PARTITION, 'count': 1}} + + records = [] + + # callback to be called for each record read + def callback(part_id, input_tuple): + print(part_id) + (_, _, record) = input_tuple + records.append(record) + print(record) + + self.client.truncate(self.namespace, self.set_name, 0) + + # invoke the operations, and for each record invoke the callback + query.foreach(callback, query_policy) + existing_count = len(records) + if existing_count > 0: + print(f"{existing_count} records already exist in partition: {STARTING_PARTITION}.") + + count = 0 + for i in range(1, 80000): + rec_partition = self.client.get_key_partition_id(self.namespace, self.set_name, str(i)) + + if rec_partition == STARTING_PARTITION: # and not client.exists(('test', 'demo', str(i))): + + count += 1 + rec = { + 'i': i, + 's': 'xyz', + 'l': [2, 4, 8, 16, 32, None, 128, 256], + 'm': {'partition': rec_partition, 'b': 4, 'c': 8, 'd': 16} + } + self.client.put((self.namespace, self.set_name, str(i)), rec) + + records.clear() + # invoke the operations, and for each record invoke the callback + query.foreach(callback, query_policy) + + print("---") + print(f"{count} records are put into partition: {STARTING_PARTITION}.") + print(f"{len(records)} records are found in partition: {STARTING_PARTITION}.") diff --git a/examples/client/remove.py b/examples/client/remove.py deleted file mode 100644 index d6efe0eab6..0000000000 --- a/examples/client/remove.py +++ /dev/null @@ -1,133 +0,0 @@ -# -*- coding: utf-8 -*- -########################################################################## -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -########################################################################## - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -############################################################################### -# Client Configuration -############################################################################### - -config = { - 'hosts': [(options.host, options.port)] -} - - -############################################################################### -# Application -############################################################################### - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - key = args.pop() - - client.remove((namespace, set, key)) - - print("OK, 1 record removed.") - - except Exception as eargs: - (code, msg, file, line) = eargs - if code == 602: - print("error: Record not found") - else: - print( - "error: {0}".format((code, msg, file, line)), file=sys.stderr) - rc = 1 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/remove_bin.py b/examples/client/remove_bin.py index 4adc8dd090..deec979232 100644 --- a/examples/client/remove_bin.py +++ b/examples/client/remove_bin.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,119 +15,17 @@ # limitations under the License. ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] key bin_names" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") +from .. import ExampleWithRecord -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) < 2: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## -config = { - 'hosts': [(options.host, options.port)] -} +class RemoveBin(ExampleWithRecord): + def run(self): + bin_names = [self.BIN_NAME] -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - - pk = args.pop(0) - bin_names = args - status = client.remove_bin((namespace, set, pk), bin_names) - print("Status of bin removal is: %d" % (status)) - print("OK, bins removed from the record at", (namespace, set, pk)) - - except Exception as exception: - if exception.code == 602: - print("error: Record not found") - else: - print("error: {0}".format( - (exception.code, exception.msg, file, exception.line)), file=sys.stderr) - rc = 1 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## + retval = self.client.remove_bin(self.key, bin_names) + print("Status of bin removal is: %d" % (retval)) -sys.exit(exitCode) + def cleanup(self): + pass diff --git a/examples/client/scan.py b/examples/client/scan.py index 146a08d6e8..349e9fd99a 100644 --- a/examples/client/scan.py +++ b/examples/client/scan.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,97 +15,16 @@ # limitations under the License. ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") +from .. import Example -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") +class Scan(Example): + def run(self): + s = self.client.scan(self.namespace, self.set_name) -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-b", "--bins", dest="bins", type="string", action="append", - help="Bins to select from each record.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - - s = client.scan(namespace, set) - - if options.bins and len(options.bins) > 0: - # project specified bins - s.select(*options.bins) + bins = [self.BIN_NAME] + # project specified bins + s.select(*bins) records = [] @@ -118,28 +37,4 @@ def callback(input_tuple): # invoke the operations, and for each record invoke the callback s.foreach(callback) - print("---") - if len(records) == 1: - print("OK, 1 record found.") - else: - print("OK, %d records found." % len(records)) - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - rc = 1 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) + print("OK, %d records found." % len(records)) diff --git a/examples/client/scan_apply.py b/examples/client/scan_apply.py index fc7151d937..f2affe6ee6 100644 --- a/examples/client/scan_apply.py +++ b/examples/client/scan_apply.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,135 +15,24 @@ # limitations under the License. ########################################################################## -from __future__ import print_function import aerospike -import json -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] module function [args...]" - - -def scan_callback(option, opt, value, parser): - setattr(parser.values, option.dest, value.split(',')) - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-m", "--module", dest="module", type="string", - help="UDF Module.") - -optparser.add_option( - "-f", "--function", dest="function", type="string", - help="UDF Function.") - -optparser.add_option( - "-a", "--arg", dest="arguments", type="string", action="callback", - callback=scan_callback, help="UDF Arguments.") - -optparser.add_option( - "-b", "--bins", dest="bins", type="string", action="append", - help="Bins to select from each record.") - -(options, args) = optparser.parse_args() -if options.help: - optparser.print_help() - print() - sys.exit(1) -if len(args) > 0: - optparser.print_help() - print() - sys.exit(1) -############################################################################### -# Client Configuration -############################################################################### +from .. import UDFExample -config = { - 'hosts': [(options.host, options.port)] -} -############################################################################### -# Application -############################################################################### - -exitCode = 0 - - -def parse_arg(s): - try: - return json.loads(s) - except ValueError: - return s - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - - args.reverse() - - module = options.module - function = options.function - - for i, param in enumerate(options.arguments): - if param.isdigit(): - options.arguments[i] = int(param) +class ScanApply(UDFExample): + def run(self): + MODULE = "stream_example" + FUNCTION = "count" policy = {} - scan_id = client.scan_apply( - namespace, set, module, function, options.arguments, policy) + scan_id = self.client.scan_apply( + self.namespace, self.set_name, MODULE, FUNCTION, [], policy) while True: - response = client.job_info(scan_id, aerospike.JOB_SCAN) + response = self.client.job_info(scan_id, aerospike.JOB_SCAN) if response['status'] == aerospike.JOB_STATUS_COMPLETED: break @@ -151,23 +40,3 @@ def parse_arg(s): print("Background scan is successful") else: print("Scan_apply failed") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - rc = 1 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/scan_partition.py b/examples/client/scan_partition.py deleted file mode 100644 index 00870b9509..0000000000 --- a/examples/client/scan_partition.py +++ /dev/null @@ -1,170 +0,0 @@ -# -*- coding: utf-8 -*- -########################################################################## -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -########################################################################## - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-i", "--partition_id", dest="partition", type="int", default=0, - help="Partition id from where to scan.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - - s = client.scan(namespace, set) - - partition_policy = None - - if options.partition > 0: - # project specified bins - partition_policy = {'partition_filter': {'begin': options.partition, 'count': 1}} - print(f'partition_id: {options.partition}') - - records = [] - - # callback to be called for each record read - def callback(input_tuple): - (_, _, record) = input_tuple - records.append(record) - print(record) - - client.truncate('test', "demo", 0) - - # invoke the operations, and for each record invoke the callback - s.foreach(callback, partition_policy) - existing_count = len(records) - if existing_count > 0: - print(f"{existing_count} records are exist already in partition:{options.partition}.") - - count = 0 - for i in range(1, 80000): - rec_partition = client.get_key_partition_id('test', 'demo', str(i)) - - if rec_partition == options.partition: # and not client.exists(('test', 'demo', str(i))): - - count = count + 1 - rec = { - 'i': i, - 's': 'xyz', - 'l': [2, 4, 8, 16, 32, None, 128, 256], - 'm': {'partition': rec_partition, 'b': 4, 'c': 8, 'd': 16} - } - client.put(('test', 'demo', str(i)), rec) - - records.clear() - # invoke the operations, and for each record invoke the callback - s.foreach(callback, partition_policy) - - print("---") - print(f"{count} records are put into partition:{options.partition}.") - print(f"{len(records)} records are found in partition:{options.partition}.") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - rc = 1 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/select_many.py b/examples/client/select_many.py deleted file mode 100644 index 63eef3814c..0000000000 --- a/examples/client/select_many.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -########################################################################## -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -########################################################################## - - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-k", "--keys", dest="keys", type="string", default="", metavar="", - help="Keys to be accessed in the database server. Should be specified as 'name','name1','name2' etc") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - # args.pop() - - keys = options.keys.split(',') - keylist = [] - for key in keys: - individualkey = (namespace, set, key) - keylist.append(individualkey) - - records = client.select_many(keylist, ['i', 'd']) - - if records is not None: - print(records) - print("---") - print("OK, %d records found." % len(records)) - else: - print('error: Not Found.', file=sys.stderr) - exitCode = 1 - - except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/select_record.py b/examples/client/select_record.py index aab0780369..221824f635 100644 --- a/examples/client/select_record.py +++ b/examples/client/select_record.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,138 +15,16 @@ # limitations under the License. ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] key bin [bin ...]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--no-key", dest="nokey", action="store_true", - help="Do not return the key") - -optparser.add_option( - "--no-metadata", dest="nometadata", action="store_true", - help="Do not return the metadata") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) < 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - client = aerospike.client(config).connect( - options.username, options.password) +from .. import ExampleWithRecord - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - try: - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - key = args.pop(0) +class SelectRecord(ExampleWithRecord): + def run(self): + bins = [self.BIN_NAME] policy = None + (key, metadata, record) = self.client.select(self.key, bins, policy) - print(args) - - (key, metadata, record) = client.select( - (namespace, set, key), args, policy) - - if metadata is not None: - if options.nometadata and options.nokey: - print(record) - elif options.nometadata: - print(key, record) - elif options.nokey: - print(metadata, record) - else: - print(key, metadata, record) - print("---") - print("OK, 1 record found.") - else: - print('error: Not Found.', file=sys.stderr) - exitCode = 1 - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) + print(key) + print(metadata) + print(record) diff --git a/examples/client/simple.lua b/examples/client/simple.lua index 972aaa33bd..76bfa1d111 100644 --- a/examples/client/simple.lua +++ b/examples/client/simple.lua @@ -1,6 +1,6 @@ -------------------------------------------------------------------------------- -- --- Copyright 2013-2021 Aerospike, Inc. +-- Copyright 2013-2026 Aerospike, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. diff --git a/examples/client/touch.py b/examples/client/touch.py index ae16eb1834..b0ea45b47c 100644 --- a/examples/client/touch.py +++ b/examples/client/touch.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,151 +15,22 @@ # limitations under the License. ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--gen", dest="gen", type="int", default=10, metavar="", - help="Generation of the record being written.") - -optparser.add_option( - "--ttl", dest="ttl", type="int", default=1000, metavar="", - help="TTL of the record being written.") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - key = args.pop() - - record = { - 'example_name': 'John', - 'example_age': 1 - } - meta = {'ttl': options.ttl, 'gen': options.gen} - policy = None +from .. import ExampleWithRecord - # invoke operation - client.put((namespace, set, key), record, meta, policy) +class Touch(ExampleWithRecord): + def run(self): + _, meta = self.client.exists(self.key) - print(record) print("---") - print("OK, 1 record written.") - - (returnedkey, meta) = client.exists((namespace, set, key)) - - print("---") - print("Ttl before touch operation") + print("TTL before touch operation") print(meta) - client.touch((namespace, set, key), options.ttl + 1000, meta, policy) - print("---") - print("OK, 1 record touched.") + self.client.touch(self.key, meta["ttl"] + 1000) - (returnedkey, meta) = client.exists((namespace, set, key)) + _, meta = self.client.exists(self.key) print("---") - print("Ttl after touch operation") + print("TTL after touch operation") print(meta) - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/ttl.py b/examples/client/ttl.py index 1e2638c118..81ad9ae2c6 100644 --- a/examples/client/ttl.py +++ b/examples/client/ttl.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,12 +20,7 @@ # We will write records that expire BEFORE the default namespace TTL, # we will write records that expire with the default TTL, and we'll # write records that NEVER expire. -# -# NOTE: -# This test is meant to run on an Aerospike 2.x or 3.x server, so the -# records that it writes have only primitive types for bin values. -from __future__ import print_function import aerospike import sys @@ -33,331 +28,61 @@ import re import time -from optparse import OptionParser from aerospike import exception as e -########################################################################## -# Option Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# CONSTANTS -########################################################################## - TTL_DEFAULT = 10 -TTL_MAX = 20 -TTL_NO_EXPIRE = -1 - +# TODO: include instructions to have docker commands to set up server instead of through python # Define the Namespace Supervisor parms -- setting the period very short # so that we know it will have visited all of our records before we look # at them at each TTL interval. -PARAMS_SERVICE = [[('nsup-period', 1)]] +# PARAMS_SERVICE = [[('nsup-period', 1)]] # Define the default Namespace Time To Live at 10 seconds. We will write # some records that expire EARLY (5 seconds), some records that expire at # the default (10 seconds), some that expire LATE (15 seconds) and some # that NEVER expire. -# We set MAX ttl to 20 to check that our flag (0xFFFFFFFF) is allowed in -# and does not trigger the "greater than max ttl" warning. -# Also, we'll check that one of our records DOES trigger the Max TTL warning -# with a TTL of greater than 20. -PARAMS_NAMESPACE = [[('default-ttl', TTL_DEFAULT), ('max-ttl', TTL_MAX)]] +# PARAMS_NAMESPACE = [[('default-ttl', TTL_DEFAULT)]] -# Write Policy names and related values -AS_POLICY_W_TIMEOUT = "timeout" -AS_POLICY_W_RETRY = "retry" -AS_POLICY_RETRY_UNDEF = 0 # Use Default value -AS_POLICY_RETRY_NONE = 1 # No retry -AS_POLICY_RETRY_ONCE = 2 # Retry Once - -AS_POLICY_W_KEY = "key" -AS_POLICY_KEY_UNDEF = 0 # If set, then the value will default to either -# as_config.policies.key or `AS_POLICY_KEY_DEFAULT`. -AS_POLICY_KEY_DIGEST = 1 # Send the digest value of the key. -AS_POLICY_KEY_SEND = 2 # Send the key, but do not store it. -AS_POLICY_KEY_STORE = 3 # Store the key (NOT YET IMPLEMENTED) - -AS_POLICY_W_GEN = "generation" -AS_POLICY_GEN_UNDEF = 0 # Use default value -AS_POLICY_GEN_IGNORE = 1 # Write a record, regardless of generation. -AS_POLICY_GEN_EQ = 2 # Write a record, ONLY if generations are equal -AS_POLICY_GEN_GT = 3 # Write a record, ONLY if local generation is -# greater-than remote generation. -AS_POLICY_GEN_DUP = 4 # Write a record creating a duplicate, ONLY if -# the generation collides (?) - -AS_POLICY_W_EXISTS = "exists" -AS_POLICY_EXISTS_UNDEF = 0 # Use default value -AS_POLICY_EXISTS_IGNORE = 1 # Write the record, regardless of existence. -AS_POLICY_EXISTS_CREATE = 2 # Create a record, ONLY if it doesn't exist. -# Update a record, ONLY if it exist (NOT YET IMPL). -AS_POLICY_EXISTS_UPDATE = 3 - -# Setup write policy -wr_policy = { - AS_POLICY_W_TIMEOUT: 5000, - AS_POLICY_W_RETRY: AS_POLICY_RETRY_NONE, - AS_POLICY_W_KEY: AS_POLICY_KEY_DIGEST, - AS_POLICY_W_GEN: AS_POLICY_GEN_IGNORE, - AS_POLICY_W_EXISTS: AS_POLICY_EXISTS_IGNORE -} - -BASE_KEY_RANGE = list(range(1, 11)) - -SPECIAL_KEYS = { - 20: {'ttl': 5, - 'desc': '5 sec TTL'}, - 40: {'ttl': 15, - 'desc': '15 sec TTL'}, - 60: {'ttl': TTL_NO_EXPIRE, - 'desc': 'NO_EXPIRE TTL'}, - 80: {'ttl': TTL_MAX + 1, - 'desc': 'Larger than MAX TTL'} -} - -KEYS = BASE_KEY_RANGE + list(SPECIAL_KEYS.keys()) - -########################################################################## -# Connect to Cluster -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] +USER_KEYS_TO_TTL = { + 5: 5, + 15: 15, + "ns_default": aerospike.TTL_NAMESPACE_DEFAULT, + "dont_expire": aerospike.TTL_NEVER_EXPIRE, } -print('Connect to Server: ', config) -client = aerospike.client(config).connect(options.username, options.password) - -########################################################################## -# Perform Operation -########################################################################## - - -def test_params_for_stanza(p, contx, is_namespace): - for t in p: - if is_namespace: - info_code = "set-config:context=namespace;id=" + \ - contx + ";" + t[0] + "=" + str(t[1]) - else: - info_code = "set-config:context=" + \ - contx + ";" + t[0] + "=" + str(t[1]) - try: - v = list(client.info_all(info_code).items()) - res = v[0][1][1] - if res != "ok\n": - print( - "setting {0} to {1} failed. Got result({2})".format(t[0], t[1], res)) - sys.exit(1) - else: - print("setting {0} to {1} succeeded".format(t[0], t[1])) - except: - print("error: info_code({0}) result({1})".format(info_code, v)) - - -def print_header(header, message=None): - print() - print(''.ljust(80, '=')) - print(header) - print(message) if message else None - print(''.ljust(80, '-')) - - -def print_record(xxx_todo_changeme, prefix=''): - (key, meta, record) = xxx_todo_changeme - print("%s%-4d %-4s %-8s %s" % ( - prefix, - int(key[2] or 0), - meta.get('gen') if meta and 'gen' in meta else '-', - meta.get('ttl') if meta and 'ttl' in meta else '-', - record if record else '-' - )) - - -def print_records(records, prefix=''): - header = "%s---- ---- -------- " % prefix - header = header.ljust(80, '-') - print() - print("%s%-4s %-4s %-8s %s" % (prefix, "key", "gen", "ttl", "record")) - print(header) - [print_record(r, prefix) for r in records] - - -def print_histogram(prefix=''): - request = ''.join(["hist-dump:ns=", options.namespace, ";hist=ttl"]) - - header = "%sHISTOGRAM (%s)" % (prefix, request) - border = prefix.ljust(80, '-') - - print() - print(header) - print(border) - for _, (error, response) in list(client.info(request).items()): - if error: - print('%serror: %s' % (prefix, error)) - else: - for line in textwrap.wrap(response, 80 - len(prefix)): - print("%s%s" % (prefix, line)) - - -def check_records(start, wait=0, message=None): - - if wait: - time.sleep(wait) - - stop = time.time() - duration = int(stop - start) - - print_header('CHECK :: wait=%s duration=%s' % (wait, duration), message) - - try: - print_records( - [client.get((options.namespace, options.set, k)) for k in KEYS], ' ') - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - - print_histogram(' ') - - -def delete_records(): - try: - for key in KEYS: - # first remove the existing record - client.remove((options.namespace, options.set, key)) - except e.RecordNotFound: - print("Record not found") - except Exception as err: - if err[0] != 2: - print("delete_records() error: {0}".format( - err[0]), file=sys.stderr) - sys.exit(1) - - -def write_records(): - - try: - for key in KEYS: - ttl = SPECIAL_KEYS[key]['ttl'] if key in SPECIAL_KEYS else None - - rec = {} - rec['key'] = key - rec['ttl'] = ttl if ttl else TTL_DEFAULT - rec['desc'] = SPECIAL_KEYS[key][ - 'desc'] if key in SPECIAL_KEYS else 'default TTL' - - try: - # write a new record - # ttl=None is equivalent to not setting a ttl - print("writing key :=", key) - client.put( - (options.namespace, options.set, key), rec, {'ttl': ttl}) - - except Exception as e: - ttlVal = int(ttl or 0) - if ttlVal > TTL_MAX: - print('error: (correct) failed to write record with TTL(%d) > TTL_MAX(%d)' % ( - ttlVal, TTL_MAX)) - else: - print('error: failed to write record with TTL = %d ' % - ttlVal) - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - sys.exit(1) - -########################################################################## -# CONFIGURE SERVER -########################################################################## - -print_header("CONFIGURE THE SERVER") - -# Now go off and set the params -print('Set Parameters for Service') -for p in PARAMS_SERVICE: - test_params_for_stanza(p, "service", False) - time.sleep(1) -print("service parameters passed") - -print("getting initial ttl values") -info = client.info_all("namespace/" + options.namespace) -default_ttl = 0 -max_ttl = 0 -for key, value in list(info.items()): - array_of_items = re.split(';|=', value[1]) - i = 0 - for item in array_of_items: - i = i + 1 - if item == "default-ttl": - default_ttl = array_of_items[i] - if item == "max-ttl": - max_ttl = array_of_items[i] - -print('Set Parameters for Namespace') -for p in PARAMS_NAMESPACE: - test_params_for_stanza(p, options.namespace, True) - time.sleep(1) -print("namespace parameters passed") - -########################################################################## -# CHECK RECORDS ON INTERVALS -########################################################################## - -start = time.time() - -delete_records() -check_records(start, 0, 'Clean state') - -write_records() - -check_records(start, 0, 'Initial state') -check_records(start, 2, 'Expect all records with TTL-2') -check_records(start, 6, 'Expect all records with TTL<=5 to be gone') -check_records(start, 3, 'Expect all records with TTL<=10 to be gone') -check_records(start, 6, 'Expect all records to be gone, except NO_EXPIRE') -client.remove((options.namespace, options.set, 60)) - -PARAMS_NAMESPACE = [[('default-ttl', default_ttl), ('max-ttl', max_ttl)]] -print('Reset Parameters for Namespace') -for p in PARAMS_NAMESPACE: - test_params_for_stanza(p, options.namespace, True) - time.sleep(1) +from .. import Example + +class TTL(Example): + def run(self): + self.KEYS = [(self.namespace, self.set_name, key) for key in USER_KEYS_TO_TTL] + self.time_elapsed = 0 + self.write_records() + self.check_records(0, 'Initial state') + self.check_records(2, 'Expect all records with TTL<=2 to be gone.') + self.check_records(6, 'Expect all records with TTL<=5 to be gone') + self.check_records(3, 'Expect all records with TTL<=10 to be gone') + self.check_records(6, 'Expect all records to be gone, except NO_EXPIRE') + + def cleanup(self): + self.client.batch_remove(self.KEYS) + super().cleanup() + + def check_records(self, wait=0, message=None): + if wait: + time.sleep(wait) + print(f"Waited {wait} seconds") + self.time_elapsed += wait + + print(f"Total elapsed time is {self.time_elapsed}. {message}") + brs = self.client.batch_read(self.KEYS) + for br in brs.batch_records: + print(f"Server returned error code {br.result} for record with ttl of {br.key[2]}") + + + def write_records(self): + for key in self.KEYS: + print("writing key :=", key) + user_key = key[2] + self.client.put(key, {self.BIN_NAME: 1}, policy={"ttl": USER_KEYS_TO_TTL[user_key]}) diff --git a/examples/client/udf_get.py b/examples/client/udf_get.py index 684bb8db71..da8616acc7 100644 --- a/examples/client/udf_get.py +++ b/examples/client/udf_get.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,108 +15,18 @@ # limitations under the License. ########################################################################## -from __future__ import print_function - +from .. import UDFExample import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] module" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - - module = args.pop() +class UDFGet(UDFExample): + def run(self): + # TODO: configurable + module = "./examples/client/example.lua" language = aerospike.UDF_TYPE_LUA policy = {} - client.udf_put(module, language, policy) - udf_contents = client.udf_get(module, language, policy) + self.client.udf_put(module, language, policy) + udf_contents = self.client.udf_get(module, language, policy) print("Module contents : ") print(udf_contents) - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/udf_list.py b/examples/client/udf_list.py index fc2f8b0fff..cb5d0ab66b 100644 --- a/examples/client/udf_list.py +++ b/examples/client/udf_list.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,98 +15,11 @@ # limitations under the License. ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- +from .. import Example - try: +class UDFList(Example): + def run(self): policy = {} - - llist = client.udf_list(policy) + llist = self.client.udf_list(policy) print(llist) - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) diff --git a/examples/client/udf_put.py b/examples/client/udf_put.py index c2d86530c0..9f3fa04c90 100644 --- a/examples/client/udf_put.py +++ b/examples/client/udf_put.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,105 +15,16 @@ # limitations under the License. ########################################################################## -from __future__ import print_function +from .. import UDFExample import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] filename" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: +class UDFPut(UDFExample): + def run(self): policy = {} - filename = args.pop() - udf_type = 0 # 0 for LUA - - client.udf_put(filename, udf_type, policy) - print("OK, 1 new UDF registered") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## + # TODO + # filename = args.pop() + filename = "./examples/client/example.lua" -sys.exit(exitCode) + self.client.udf_put(filename, aerospike.UDF_TYPE_LUA, policy) diff --git a/examples/client/udf_remove.py b/examples/client/udf_remove.py index 18ef2e513d..040a4a1511 100644 --- a/examples/client/udf_remove.py +++ b/examples/client/udf_remove.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,103 +15,16 @@ # limitations under the License. ########################################################################## -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options] module" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") - -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Client Configuration -########################################################################## - -config = { - 'hosts': [(options.host, options.port)] -} - -########################################################################## -# Application -########################################################################## - -exitCode = 0 - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - client = aerospike.client(config).connect( - options.username, options.password) - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- +from .. import Example +from aerospike import exception as e - try: - - module = args.pop() - - client.udf_remove(module) - print("OK, 1 UDF de-registered") - - except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except Exception as eargs: - print("error: {0}".format(eargs), file=sys.stderr) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## +class UDFRemove(Example): + def run(self): + module = "example.lua" + self.client.udf_remove(module) -sys.exit(exitCode) + try: + self.client.udf_remove(module) + except e.UDFNotFound: + print("Already removed UDF.") diff --git a/examples/client/unicode_smiles.py b/examples/client/unicode_smiles.py index bcc13959ef..6d4d933328 100644 --- a/examples/client/unicode_smiles.py +++ b/examples/client/unicode_smiles.py @@ -1,6 +1,6 @@ -# -*- coding: utf-8 -*- + ########################################################################## -# Copyright 2013-2021 Aerospike, Inc. +# Copyright 2013-2026 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,103 +16,28 @@ ########################################################################## -from __future__ import print_function +from .. import Example import aerospike -import sys - -from optparse import OptionParser -from aerospike import exception as e - -########################################################################## -# Options Parsing -########################################################################## - -usage = "usage: %prog [options]" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-U", "--username", dest="username", type="string", metavar="", - help="Username to connect to database.") +from aerospike_helpers.operations import operations -optparser.add_option( - "-P", "--password", dest="password", type="string", metavar="", - help="Password to connect to database.") -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") +class UnicodeSmiles(Example): + def run(self): + smile = "smilé" + # TODO: configurable + read_timeout = 1000 -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--timeout", dest="timeout", type="int", default=1000, metavar="", - help="Client timeout") - -optparser.add_option( - "--read-timeout", dest="read_timeout", type="int", default=1000, metavar="", - help="Client read timeout") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -########################################################################## -# Application -########################################################################## - -try: - - # ---------------------------------------------------------------------------- - # Connect to Cluster - # ---------------------------------------------------------------------------- - - config = { - 'hosts': [(options.host, options.port)], - 'policies': { - 'total_timeout': options.timeout - } - } - client = aerospike.client(config).connect( - options.username, options.password) - - # ---------------------------------------------------------------------------- - # Perform Operation - # ---------------------------------------------------------------------------- - - try: - namespace = options.namespace if options.namespace and options.namespace != 'None' else None - set = options.set if options.set and options.set != 'None' else None - smile = u"smilé" - - key = (namespace, set, smile) + key = (self.namespace, self.set_name, smile) bins = {'smiley': smile, 'smile_count': 1, 'mood': 'happy'} print("Storing ", bins, "at a record identified by the tuple", key) # overwrite the record if it exists, otherwise create it - client.put(key, bins, + self.client.put(key, bins, policy={'exists': aerospike.POLICY_EXISTS_CREATE_OR_REPLACE, 'key': aerospike.POLICY_KEY_SEND}) print("Retrieving the record from the server for comparison") - (key, meta, record) = client.get( - key, policy={'total_timeout': options.read_timeout}) + (key, meta, record) = self.client.get( + key, policy={'total_timeout': read_timeout}) print("The value of the 'smiley' bin is", record['smiley'], "\n") print("By the way, this record has been written", meta['gen'], "times") future_gen = str(int(meta['gen']) + 2) @@ -122,8 +47,8 @@ # add a dictionary under a bin named 'data' bins = {'data': {'smiley_key': smile, smile: 'this is a smiley '}} print("Storing ", bins, "at the record", key) - client.put(key, bins) - (key, metadata, bins) = client.get(key) + self.client.put(key, bins) + (key, metadata, bins) = self.client.get(key) print("The value of the 'smiley_key' of the 'data' bin is", bins['data']['smiley_key'], "\n") # print("The value of the", smile, " key is:", @@ -132,63 +57,43 @@ # append to the value of the smile key print("Before appending, the value of the 'mood' key is:", bins['mood']) - client.append(key, 'mood', smile) - (key, metadata, bins) = client.get(key) + self.client.append(key, 'mood', smile) + (key, metadata, bins) = self.client.get(key) print("After appending, the value of the 'mood' key is:", bins['mood'], "\n") # prepend to the value of the smile key print("Before prepending, the value of the 'mood' key is:", bins['mood']) - client.prepend(key, 'mood', smile) - (key, metadata, bins) = client.get(key) + self.client.prepend(key, 'mood', smile) + (key, metadata, bins) = self.client.get(key) print("After prepending, the value of the 'mood' key is:", bins['mood'], "\n") # multiple operations on the record using the operate() method - ops = [{'bin': 'smiley', 'op': aerospike.OPERATOR_APPEND, 'val': smile}, - {'bin': 'smile_count', 'op': aerospike.OPERATOR_INCR, 'val': 5}, - {'bin': 'smiley', 'op': aerospike.OPERATOR_READ}] + ops = [ + operations.append(bin_name="smiley", append_item=smile), + operations.increment(bin_name="smile_count", amount=5), + operations.read(bin_name="smiley"), + ] print("Setting the following multiops on the same record\n", ops) - (key, meta, bins) = client.operate(key, ops) + (key, meta, bins) = self.client.operate(key, ops) print("The value of the 'smiley' bin is", bins['smiley'], "\n") print("Displaying the key, metadata, and bins of the record") - (key, meta, bins) = client.get(key) + (key, meta, bins) = self.client.get(key) print(key) print(meta) print(bins, "\n") - client.remove(key) + self.client.remove(key) # example of a bytearray primary key print("Save a new record with a bytearray primary key") smiley_pk = smile.encode("utf-8") - client.put((namespace, set, smiley_pk), {'smiley': smile, 'smiley_pk': + self.client.put((self.namespace, self.set_name, smiley_pk), {'smiley': smile, 'smiley_pk': smiley_pk}) print("Display the bins of a record with a bytearray key") - (key, meta, bins) = client.get((namespace, set, smiley_pk)) + (key, meta, bins) = self.client.get((self.namespace, self.set_name, smiley_pk)) print(bins) print("The value of the 'smiley_pk' bin is", bins['smiley_pk'], "\n") - client.remove(key) - exitCode = 0 - except Exception as exception: - print("error: {0}".format(exception), file=sys.stderr) - exitCode = 2 - - # ---------------------------------------------------------------------------- - # Close Connection to Cluster - # ---------------------------------------------------------------------------- - - client.close() - -except e.ClientError as exception: - print("Error: {0} [{1}]".format(exception.msg, exception.code)) - exitCode = 3 - -########################################################################## -# Exit -########################################################################## - -sys.exit(exitCode) - -# + self.client.remove(key) diff --git a/examples/deprecated/exists.py b/examples/deprecated/exists.py deleted file mode 100644 index 364254eb09..0000000000 --- a/examples/deprecated/exists.py +++ /dev/null @@ -1,108 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################ -# Option Parsing -################################################################ - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -################################################################ -# Connect to Cluster -################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -client = aerospike.client(config).connect() - -################################################################ -# Perform Operation -################################################################ - -rc = 0 -key = args.pop() - -try: - - (key, metadata) = client.key(options.namespace, options.set, key).exists() - - if metadata != None: - print(metadata) - print("---") - print("OK, 1 record found.") - else: - print('error: Not Found.', file=sys.stderr) - rc = 1 - -except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - rc = 1 - -################################################################ -# Close Connection to Cluster -################################################################ - -client.close() - -################################################################ -# Exit -################################################################ - -sys.exit(rc) diff --git a/examples/deprecated/get.py b/examples/deprecated/get.py deleted file mode 100644 index 6adcffae01..0000000000 --- a/examples/deprecated/get.py +++ /dev/null @@ -1,108 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################ -# Option Parsing -################################################################ - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -################################################################ -# Connect to Cluster -################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -client = aerospike.client(config).connect() - -################################################################ -# Perform Operation -################################################################ - -rc = 0 -key = args.pop() - -try: - (key, metadata, record) = client.key(options.namespace, options.set, key).get() - - if metadata != None: - print(metadata) - print(record) - print("---") - print("OK, 1 record found.") - else: - print('error: Not Found.', file=sys.stderr) - rc = 1 - -except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - rc = 1 - -################################################################ -# Close Connection to Cluster -################################################################ - -client.close() - -################################################################ -# Exit -################################################################ - -sys.exit(rc) diff --git a/examples/deprecated/put.py b/examples/deprecated/put.py deleted file mode 100644 index 65cbc43736..0000000000 --- a/examples/deprecated/put.py +++ /dev/null @@ -1,126 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################ -# Option Parsing -################################################################ - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "--gen", dest="gen", type="int", default=10, metavar="", - help="Generation of the record being written.") - -optparser.add_option( - "--ttl", dest="ttl", type="int", default=1000, metavar="", - help="TTL of the record being written.") - - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -################################################################ -# Connect to Cluster -################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -client = aerospike.client(config).connect() - -################################################################ -# Perform Operation -################################################################ - -rc = 0 -key = args.pop() - -record = { - 'i': 123, - 's': 'abc', - # 'b': bytearray(['d','e','f']), - # 'l': [123, 'abc', bytearray(['d','e','f']), ['x', 'y', 'z'], {'x': 1, 'y': 2, 'z': 3}], - # 'm': {'i': 123, 's': 'abc', 'b': bytearray(['d','e','f']), 'l': ['x', 'y', 'z'], 'd': {'x': 1, 'y': 2, 'z': 3}} - 'l': [123, 'abc', ['x', 'y', 'z'], {'x': 1, 'y': 2, 'z': 3}], - 'm': {'i': 123, 's': 'abc', 'l': ['x', 'y', 'z'], 'd': {'x': 1, 'y': 2, 'z': 3}} -} - -try: - meta = {'ttl': options.ttl, 'gen': options.gen} - # meta = None - # policy = { 'gen': 0 } - policy = None - client.key(options.namespace, options.set, key).put(record, meta) - - print(record) - print("---") - print("OK, 1 record written.") - -except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - rc = 1 - -################################################################ -# Close Connection to Cluster -################################################################ - -client.close() - -################################################################ -# Exit -################################################################ - -sys.exit(rc) diff --git a/examples/deprecated/remove.py b/examples/deprecated/remove.py deleted file mode 100644 index 9d66c68e90..0000000000 --- a/examples/deprecated/remove.py +++ /dev/null @@ -1,100 +0,0 @@ -# -*- coding: utf-8 -*- -################################################################################ -# Copyright 2013-2021 Aerospike, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -################################################################################ - -from __future__ import print_function - -import aerospike -import sys - -from optparse import OptionParser - -################################################################ -# Option Parsing -################################################################ - -usage = "usage: %prog [options] key" - -optparser = OptionParser(usage=usage, add_help_option=False) - -optparser.add_option( - "--help", dest="help", action="store_true", - help="Displays this message.") - -optparser.add_option( - "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="
", - help="Address of Aerospike server.") - -optparser.add_option( - "-p", "--port", dest="port", type="int", default=3000, metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-n", "--namespace", dest="namespace", type="string", default="test", metavar="", - help="Port of the Aerospike server.") - -optparser.add_option( - "-s", "--set", dest="set", type="string", default="demo", metavar="", - help="Port of the Aerospike server.") - -(options, args) = optparser.parse_args() - -if options.help: - optparser.print_help() - print() - sys.exit(1) - -if len(args) != 1: - optparser.print_help() - print() - sys.exit(1) - -################################################################ -# Connect to Cluster -################################################################ - -config = { - 'hosts': [ (options.host, options.port) ] -} - -client = aerospike.client(config).connect() - -################################################################ -# Perform Operation -################################################################ - -rc = 0 -key = args.pop() - -try: - client.key(options.namespace, options.set, key).remove() - print("OK, 1 record removed.") - -except Exception as e: - print("error: {0}".format(e), file=sys.stderr) - rc = 1 - -################################################################ -# Close Connection to Cluster -################################################################ - -client.close() - -################################################################ -# Exit -################################################################ - -sys.exit(rc) diff --git a/examples/run_all_examples.py b/examples/run_all_examples.py new file mode 100644 index 0000000000..c61b420c58 --- /dev/null +++ b/examples/run_all_examples.py @@ -0,0 +1,63 @@ +import pkgutil +import importlib +import inspect +import os +import sys + +def run_examples_in(modules: list[str], class_name: str | None = None): + example_classes: list[type] = [] + + dir_containing_this_module = os.path.dirname(os.path.abspath(__file__)) + + for folder in modules: + all_packages = pkgutil.walk_packages([ + dir_containing_this_module + "/" + folder.replace(".", "/"), + ]) + for package in all_packages: + print(package) + module = importlib.import_module("." + package.name, ".examples." + folder) + for name, obj in inspect.getmembers(module, inspect.isclass): + if obj.__module__ != module.__name__: + continue + # TODO - comparing the same class imported two different ways fails + # There might a better way to do this + if "Example" not in [obj.__name__ for obj in obj.__mro__]: + continue + if not hasattr(obj, "run") or not callable(getattr(obj, "run")): + # Some classes that inherit from Example base class are "abstract" classes + continue + + # Now we know this class is a valid example + # TODO: there's probably a way to get a specific class example in O(1) instead of O(n) + if class_name and name != class_name: + continue + + print("Class found:", obj) + example_classes.append(obj) + + print("Running examples...") + for cls in example_classes: + print(cls) + print() + + example = cls() + try: + example.run() + finally: + example.cleanup() + +if len(sys.argv) < 2: + print("Missing arguments: EE/CE") + exit(1) + +if sys.argv[1] == "CE": + modules = [ + "client", + "string_ops" + ] +else: + modules = [ + "client.admin" + ] + +run_examples_in(modules) diff --git a/examples/string_ops/__init__.py b/examples/string_ops/__init__.py index 89b3d4f7d7..e69de29bb2 100644 --- a/examples/string_ops/__init__.py +++ b/examples/string_ops/__init__.py @@ -1,14 +0,0 @@ -import aerospike - - -class Example: - def __init__(self): - config = { - "hosts": [("127.0.0.1", 3000)] - } - client = aerospike.client(config) - - self.client = client - - def __del__(self): - self.client.close() diff --git a/examples/string_ops/customer_experience/__init__.py b/examples/string_ops/customer_experience/__init__.py index 693114a7c3..0f2eae339a 100644 --- a/examples/string_ops/customer_experience/__init__.py +++ b/examples/string_ops/customer_experience/__init__.py @@ -1,4 +1,4 @@ -from .. import Example +from ... import Example class CustomerExperienceExample(Example): def __init__(self): @@ -10,6 +10,6 @@ def __init__(self): self.client.put(self.key, bins={"email": ORIG_EMAIL}) - def __del__(self): + def cleanup(self): self.client.remove(self.key) - super().__del__() + super().cleanup() diff --git a/examples/string_ops/quickstart/string_expressions.py b/examples/string_ops/quickstart/string_expressions.py index 1e9a3891aa..833ed81920 100644 --- a/examples/string_ops/quickstart/string_expressions.py +++ b/examples/string_ops/quickstart/string_expressions.py @@ -1,4 +1,4 @@ -from .. import Example +from ... import Example from aerospike_helpers import expressions as exp from aerospike_helpers.operations import expression_operations as expr_ops diff --git a/examples/string_ops/quickstart/string_ops.py b/examples/string_ops/quickstart/string_ops.py index 37afbf3de9..143881cdba 100644 --- a/examples/string_ops/quickstart/string_ops.py +++ b/examples/string_ops/quickstart/string_ops.py @@ -1,4 +1,4 @@ -from .. import Example +from ... import Example from aerospike_helpers.operations import string_operations as so class StringOps(Example): diff --git a/examples/string_ops/run_all_examples.py b/examples/string_ops/run_all_examples.py deleted file mode 100644 index 2a3ddaa65f..0000000000 --- a/examples/string_ops/run_all_examples.py +++ /dev/null @@ -1,18 +0,0 @@ -from .customer_experience.email_normalization_old import EmailNormalizationOld -from .customer_experience.email_normalization_new import EmailNormalizationNew -from .customer_experience.partial_extraction_old import PartialExtractionOld -from .customer_experience.partial_extraction_new import PartialExtractionNew -from .quickstart.string_expressions import StringExpressions -from .quickstart.string_ops import StringOps - -example_classes = [ - EmailNormalizationOld, - EmailNormalizationNew, - PartialExtractionNew, - PartialExtractionOld, - StringExpressions, - StringOps -] - -for cls in example_classes: - example = cls().run()