├── test ├── __init__.py ├── auth │ ├── __init__.py │ └── test_token_refresh.py ├── test_provisioner.py ├── test_splunk_cloud.py ├── test_gateway.py ├── test_forwarders.py ├── test_ingest.py ├── test_event_batcher.py ├── test_search_retry.py ├── test_catalog.py ├── test_appregistry.py ├── data │ └── ml │ │ └── iris.csv ├── test_identity.py ├── test_search.py ├── test_kvstore.py └── fixtures.py ├── splunk_sdk ├── gateway │ ├── __init__.py │ ├── results.py │ └── client.py ├── __version__.py ├── common │ ├── __init__.py │ ├── context.py │ └── sscmodel.py ├── auth │ └── __init__.py ├── search │ ├── search_helper.py │ ├── v2beta1 │ │ └── __init__.py │ ├── __init__.py │ ├── v2 │ │ └── __init__.py │ └── v3alpha1 │ │ └── __init__.py ├── __init__.py ├── base_service.py ├── forwarders │ ├── __init__.py │ └── v2beta1 │ │ ├── __init__.py │ │ ├── gen_splunk_forwarder_service_api.py │ │ └── openapi.yaml ├── provisioner │ ├── __init__.py │ └── v1beta1 │ │ ├── __init__.py │ │ └── gen_provisioner_api.py ├── kvstore │ ├── __init__.py │ └── v1beta1 │ │ └── __init__.py ├── action │ ├── v2alpha1 │ │ ├── __init__.py │ │ └── gen_action_service_api.py │ ├── __init__.py │ └── v1beta2 │ │ ├── __init__.py │ │ └── gen_action_service_api.py ├── ingest │ ├── __init__.py │ ├── v1beta2 │ │ ├── __init__.py │ │ └── gen_ingest_api_api.py │ └── ingest_event_batcher.py ├── collect │ ├── __init__.py │ └── v1beta1 │ │ └── __init__.py ├── app_registry │ ├── __init__.py │ └── v1beta2 │ │ └── __init__.py ├── identity │ ├── v2beta1 │ │ └── __init__.py │ ├── v3alpha1 │ │ └── __init__.py │ ├── __init__.py │ └── v3 │ │ └── __init__.py ├── ml │ ├── __init__.py │ └── v2beta1 │ │ └── __init__.py ├── streams │ ├── v4alpha1 │ │ └── __init__.py │ ├── __init__.py │ ├── v3beta1 │ │ └── __init__.py │ └── v2beta1 │ │ └── __init__.py ├── splunk_cloud.py └── catalog │ ├── v2alpha2 │ └── __init__.py │ ├── __init__.py │ └── v2beta1 │ └── __init__.py ├── scripts ├── test_specific.sh ├── generate_docs.sh ├── copy_generated_files.sh ├── publish_docs.sh └── prerelease.sh ├── docs-requirements.txt ├── .gitlab-ci.yml ├── requirements.txt ├── docs └── docs.manifest.json ├── .gitignore ├── copyright.txt ├── sonar-project.properties ├── example_sdkrc ├── Makefile ├── tox.ini ├── CONTRIBUTING.md ├── setup.py ├── THIRD-PARTY-CREDITS.md └── README.md /test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/auth/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /splunk_sdk/gateway/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /splunk_sdk/__version__.py: -------------------------------------------------------------------------------- 1 | __version__ = "12.0.0-beta6" 2 | -------------------------------------------------------------------------------- /scripts/test_specific.sh: -------------------------------------------------------------------------------- 1 | echo "To run a specific test:" 2 | echo " pipenv run tox -e py38 [test_file_path]::[test_name]" 3 | -------------------------------------------------------------------------------- /splunk_sdk/common/__init__.py: -------------------------------------------------------------------------------- 1 | from splunk_sdk.common.context import Context 2 | 3 | REQUESTS_HOOK_NAME_RESPONSE = 'response' 4 | -------------------------------------------------------------------------------- /docs-requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2019.3.9 2 | chardet==3.0.4 3 | idna==2.8 4 | requests==2.25.1 5 | urllib3==1.26.5 6 | Jinja2==2.11.3 7 | MarkupSafe==1.1.1 -------------------------------------------------------------------------------- /splunk_sdk/auth/__init__.py: -------------------------------------------------------------------------------- 1 | from splunk_sdk.auth.auth_manager import AuthManager, PKCEAuthManager, ClientAuthManager, TokenAuthManager, \ 2 | ServicePrincipalAuthManager 3 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | include: 2 | - project: 'devplat-pr-32/gitlab-central' 3 | ref: 'a7706cb79829dbf3719b85e95abb3a4b5834878c' 4 | file: '/splunk-cloud-sdk-python/.gitlab-ci.yml' 5 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==1.4.0 2 | certifi==2021.5.30 3 | cffi==1.14.6 4 | chardet==4.0.0 5 | idna==2.10 6 | pycparser==2.20 7 | PyJWT==1.7.1 8 | requests==2.25.1 9 | six==1.16.0 10 | urllib3==1.26.6 11 | cryptography==2.6.1 12 | -------------------------------------------------------------------------------- /docs/docs.manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "category": "sdks", 3 | "name": "Splunk Cloud SDK for Python", 4 | "description": "A SDK in Python for making requests to Splunk Cloud hosted services.", 5 | "package": "@splunk/splunk-cloud-sdk-python" 6 | } 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .venv 3 | *.env 4 | .idea 5 | .vscode 6 | .cache 7 | .context 8 | .coverage 9 | .settings 10 | .sdkrc 11 | .pytest_cache 12 | .tox 13 | config.yaml 14 | coverage.xml 15 | dist/ 16 | splunk_cloud_sdk_python.egg-info/ 17 | splunk_cloud_sdk.egg-info/ 18 | sdkrc 19 | sdkrc.encrypted 20 | .python-version 21 | build/ 22 | docs/README.md 23 | docs/package.json 24 | docs/pkg/ 25 | docs/node_modules/ 26 | .eggs 27 | .env 28 | *.DS_Store -------------------------------------------------------------------------------- /splunk_sdk/search/search_helper.py: -------------------------------------------------------------------------------- 1 | from asyncio import sleep 2 | 3 | 4 | # TODO: when doc-ing, note that poll_interval is seconds, not ms 5 | async def wait_for_job(get_job_func, job_id, poll_interval=0.5): 6 | done = False 7 | job = None 8 | while not done: 9 | job = get_job_func(job_id) 10 | done = job.status in ('done', 'failed') 11 | if not done: 12 | await sleep(poll_interval) 13 | return job 14 | -------------------------------------------------------------------------------- /copyright.txt: -------------------------------------------------------------------------------- 1 | Copyright © 2019 Splunk, Inc. 2 | Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | not use this file except in compliance with the License. You may obtain 4 | a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | Unless required by applicable law or agreed to in writing, software 6 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | License for the specific language governing permissions and limitations 9 | under the License. 10 | -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | # unique project key, usually your project name 2 | sonar.projectKey=splunk-cloud-sdk-python 3 | # define the files not to analyze for scanning 4 | sonar.exclusions=**/*.yaml 5 | # define the directories to scan 6 | sonar.sources=splunk_sdk 7 | # define the language 8 | sonar.language=py 9 | # The file that the sonarqube scanner imports for coverage differs per language, 10 | # please refer to sonarqube docs on how to configure the path for your language 11 | # https://docs.sonarqube.org/display/PLUG/SonarSource+Plugins 12 | # For Python: https://docs.sonarqube.org/latest/analysis/languages/python/ 13 | sonar.python.coverage.reportPaths=coverage/coverage.xml -------------------------------------------------------------------------------- /splunk_sdk/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # Copyright © 2019 Splunk, Inc. 4 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 5 | # not use this file except in compliance with the License. You may obtain 6 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations 11 | # under the License. 12 | 13 | from splunk_sdk.common import Context 14 | from splunk_sdk.__version__ import __version__ 15 | -------------------------------------------------------------------------------- /example_sdkrc: -------------------------------------------------------------------------------- 1 | # SPLUNK HOSTS, TENANT, REGION 2 | export SPLUNK_AUTH_HOST_2= 3 | export SPLUNK_DEBUG= 4 | export SPLUNK_HOST_2= 5 | export SPLUNK_REGION= 6 | export SPLUNK_TENANT_2= 7 | 8 | # PKCE FLOW 9 | export SPLUNK_APP_CLIENT_ID_2= 10 | export TEST_USERNAME= 11 | export TEST_PASSWORD= 12 | 13 | # CLIENT CREDENTIAL FLOW 14 | export SPLUNK_APP_CLIENT_CRED_ID_2= 15 | export SPLUNK_APP_CLIENT_CRED_SECRET_2= 16 | 17 | # SERVICE PRINCIPAL FLOW 18 | export SPLUNK_APP_PRINCIPAL_NAME_2= 19 | export SPLUNK_APP_PRINCIPAL_PRIVATE_KEY= 20 | export SPLUNK_APP_PRINCIPAL_KEY_ID= 21 | export SPLUNK_APP_PRINCIPAL_KEY_ALG= 22 | -------------------------------------------------------------------------------- /scripts/generate_docs.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | rm -rf docs/splunk_sdk 4 | rm docs/README.md 5 | 6 | pdoc --output-dir docs splunk_sdk 7 | 8 | cd docs/splunk_sdk 9 | 10 | DOC_INDEX=" 11 | 12 | # github.com/splunk/splunk-cloud-sdk-python 13 | 14 | ## Packages 15 | 16 | " 17 | 18 | # generate md for directory modules under splunk_sdk 19 | for module in $(ls); do 20 | for spec_version in $(ls $module); do 21 | if [[ "$spec_version" == "index.md" ]]; then 22 | continue 23 | fi 24 | 25 | for file_name in $(ls $module/$spec_version); do 26 | if [[ "$file_name" == "index.md" ]]; then 27 | continue 28 | fi 29 | DOC_INDEX+="* [$module/$spec_version/$file_name](splunk_sdk/$module/$spec_version/$file_name) 30 | " 31 | done 32 | done 33 | done 34 | 35 | echo "$DOC_INDEX" >../../docs/README.md 36 | -------------------------------------------------------------------------------- /test/auth/test_token_refresh.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from splunk_sdk.base_client import BaseClient 4 | from splunk_sdk.identity import Identity as IdentityAndAccessControl 5 | from test.fixtures import get_test_client as test_client 6 | 7 | 8 | @pytest.mark.usefixtures("test_client") # NOQA 9 | def test_crud_groups(test_client: BaseClient): 10 | identity = IdentityAndAccessControl(test_client) 11 | result = identity.validate_token() 12 | assert(result.response.status_code == 200) 13 | original_token = test_client.auth_manager.context.access_token 14 | test_client.auth_manager.context.expires_in = 20 15 | result = identity.validate_token() 16 | assert(result.response.status_code == 200) 17 | assert(original_token != test_client.auth_manager.context.access_token) 18 | assert(test_client.auth_manager.context.expires_in > 20) 19 | -------------------------------------------------------------------------------- /splunk_sdk/base_service.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # Copyright © 2019 Splunk, Inc. 4 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 5 | # not use this file except in compliance with the License. You may obtain 6 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations 11 | # under the License. 12 | 13 | class BaseService(object): 14 | """ 15 | The BaseService class is a base class for all Splunk Cloud services. 16 | """ 17 | 18 | def __init__(self, client): 19 | self.base_client = client 20 | -------------------------------------------------------------------------------- /splunk_sdk/forwarders/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Splunk Forwarder Service 23 | 24 | Send data from a Splunk forwarder to the Splunk Forwarder service in Splunk Cloud Services. 25 | 26 | OpenAPI spec version: v2beta1.4 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.forwarders.v2beta1.gen_splunk_forwarder_service_api import SplunkForwarderService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.forwarders.v2beta1.gen_models import Certificate, \ 38 | CertificateInfo, \ 39 | Error 40 | -------------------------------------------------------------------------------- /splunk_sdk/forwarders/v2beta1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Splunk Forwarder Service 23 | 24 | Send data from a Splunk forwarder to the Splunk Forwarder service in Splunk Cloud Services. 25 | 26 | OpenAPI spec version: v2beta1.4 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.forwarders.v2beta1.gen_splunk_forwarder_service_api import SplunkForwarderService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.forwarders.v2beta1.gen_models import Certificate, \ 38 | CertificateInfo, \ 39 | Error 40 | -------------------------------------------------------------------------------- /splunk_sdk/provisioner/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Provisioner 23 | 24 | With the Provisioner service in Splunk Cloud Services, you can provision and manage tenants. 25 | 26 | OpenAPI spec version: v1beta1.4 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.provisioner.v1beta1.gen_provisioner_api import Provisioner 35 | 36 | # import models into sdk package 37 | from splunk_sdk.provisioner.v1beta1.gen_models import Error, \ 38 | InviteBody, \ 39 | InviteInfoErrorsItems, \ 40 | InviteInfo, \ 41 | TenantInfo, \ 42 | UpdateInviteBody 43 | -------------------------------------------------------------------------------- /splunk_sdk/provisioner/v1beta1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Provisioner 23 | 24 | With the Provisioner service in Splunk Cloud Services, you can provision and manage tenants. 25 | 26 | OpenAPI spec version: v1beta1.4 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.provisioner.v1beta1.gen_provisioner_api import Provisioner 35 | 36 | # import models into sdk package 37 | from splunk_sdk.provisioner.v1beta1.gen_models import Error, \ 38 | InviteBody, \ 39 | InviteInfoErrorsItems, \ 40 | InviteInfo, \ 41 | TenantInfo, \ 42 | UpdateInviteBody 43 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # SPEC_REPO format: // 2 | SPEC_REPO_URL_WITH_AUTH := https://$(SPEC_REPO_USERNAME):$(SPEC_REPO_PASSWORD)@$(SPEC_REPO) 3 | SPEC_REPO_BRANCH_OR_COMMIT := $(if $(SPEC_REPO_BRANCH_OR_COMMIT),$(SPEC_REPO_BRANCH_OR_COMMIT),master) 4 | TMPDIR = $(PWD)/tmp/out 5 | 6 | .PHONY: generate test package deploy 7 | 8 | generate: 9 | docker run -e LANGUAGES=python \ 10 | -e SPEC_REPO_URL=$(SPEC_REPO_URL_WITH_AUTH) \ 11 | -e SPEC_REPO_BRANCH_OR_COMMIT=$(SPEC_REPO_BRANCH_OR_COMMIT) \ 12 | -e SERVICES="app-registry identity ingest catalog collect provisioner action kvstore search ml forwarders streams" \ 13 | -v $(TMPDIR):/opt/generated \ 14 | scpcodegen:latest \ 15 | generate 16 | scripts/copy_generated_files.sh $(TMPDIR) 17 | rm -rf $(TMPDIR) 18 | 19 | pep: 20 | tox -e pep8 21 | 22 | update_dependencies: 23 | pip3 freeze > requirements.txt 24 | 25 | test: test_integration 26 | 27 | test_integration: 28 | tox -e py38 29 | 30 | test_specific: 31 | sh ./scripts/test_specific.sh 32 | 33 | package: 34 | python setup.py sdist bdist_wheel 35 | 36 | prerelease: 37 | sh ./scripts/prerelease.sh 38 | 39 | deploy: package 40 | pip install twine 41 | # echo "Uploading to internal pypi ..." 42 | # twine upload -s -u "$(SPLUNK_PYPI_USERNAME)" -p "$(SPLUNK_PYPI_PASSWORD)" --repository-url "$(SPLUNK_PYPI_REPO)" dist/* 43 | ifdef UPLOAD_TO_PYPI 44 | echo "Uploading to public pypi ..." 45 | twine upload -s -u "$(PYPI_USERNAME)" -p "$(PYPI_PASSWORD)" dist/* 46 | endif 47 | -------------------------------------------------------------------------------- /test/test_provisioner.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | import os 12 | import pytest 13 | 14 | from splunk_sdk.base_client import BaseClient, HTTPError 15 | from splunk_sdk.provisioner import Provisioner 16 | from test.fixtures import get_test_client_provisioner as test_client # NOQ 17 | 18 | @pytest.mark.usefixtures("test_client") # NOQA 19 | def test_get_tenant(test_client: BaseClient): 20 | provisioner = Provisioner(test_client) 21 | tenant_name = os.environ.get("SPLUNK_TENANT_2") 22 | tenant = provisioner.get_tenant(tenant_name) 23 | assert(tenant.name == tenant_name) 24 | 25 | 26 | @pytest.mark.usefixtures("test_client") # NOQA 27 | def test_list_tenants(test_client: BaseClient): 28 | provisioner = Provisioner(test_client) 29 | tenant_name = os.environ.get("SPLUNK_TENANT_2") 30 | tenants = provisioner.list_tenants() 31 | [t] = [t for t in tenants if t.name == tenant_name] 32 | assert(t.name == tenant_name) 33 | -------------------------------------------------------------------------------- /splunk_sdk/kvstore/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: KV Store API 23 | 24 | With the Splunk Cloud KV store service in Splunk Cloud Services, you can save and retrieve data within your Splunk Cloud apps, enabling you to manage and maintain state in your application. 25 | 26 | OpenAPI spec version: v1beta1.2 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.kvstore.v1beta1.gen_kv_store_api_api import KVStoreAPI 35 | 36 | # import models into sdk package 37 | from splunk_sdk.kvstore.v1beta1.gen_models import ErrorResponse, \ 38 | IndexFieldDefinition, \ 39 | IndexDefinition, \ 40 | IndexDescription, \ 41 | PingResponse, \ 42 | Record 43 | -------------------------------------------------------------------------------- /splunk_sdk/kvstore/v1beta1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: KV Store API 23 | 24 | With the Splunk Cloud KV store service in Splunk Cloud Services, you can save and retrieve data within your Splunk Cloud apps, enabling you to manage and maintain state in your application. 25 | 26 | OpenAPI spec version: v1beta1.2 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.kvstore.v1beta1.gen_kv_store_api_api import KVStoreAPI 35 | 36 | # import models into sdk package 37 | from splunk_sdk.kvstore.v1beta1.gen_models import ErrorResponse, \ 38 | IndexFieldDefinition, \ 39 | IndexDefinition, \ 40 | IndexDescription, \ 41 | PingResponse, \ 42 | Record 43 | -------------------------------------------------------------------------------- /test/test_splunk_cloud.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | import pytest 12 | 13 | 14 | from test.fixtures import get_test_client as test_client # NOQA 15 | 16 | from splunk_sdk.base_client import BaseClient 17 | from splunk_sdk.splunk_cloud import SplunkCloud 18 | 19 | 20 | @pytest.mark.usefixtures("test_client") # NOQA 21 | def test_splunk_cloud_instance(test_client: BaseClient): 22 | sc = SplunkCloud(test_client.context, test_client.auth_manager) 23 | assert (sc is not None) 24 | assert (sc.action is not None) 25 | assert (sc.app_registry is not None) 26 | assert (sc.catalog is not None) 27 | assert (sc.collect is not None) 28 | assert (sc.forwarders is not None) 29 | assert (sc.gateway is not None) 30 | assert (sc.identity is not None) 31 | assert (sc.ingest is not None) 32 | assert (sc.kvstore is not None) 33 | assert (sc.provisioner is not None) 34 | assert (sc.search is not None) 35 | assert (sc.streams is not None) 36 | assert (sc.ml is not None) 37 | -------------------------------------------------------------------------------- /splunk_sdk/gateway/results.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | 12 | class Spec(object): 13 | """The Spec class TODO DOCS.""" 14 | 15 | def __init__(self, name=None, links=None): 16 | self._name = name 17 | self._links = links 18 | 19 | if self._links: 20 | self._json = links['json'] 21 | self._yaml = links['yaml'] 22 | 23 | @property 24 | def name(self): 25 | return self._name 26 | 27 | @name.setter 28 | def name(self, name): 29 | self._name = name 30 | 31 | @property 32 | def links(self): 33 | return self._links 34 | 35 | @links.setter 36 | def links(self, links): 37 | self._links = links 38 | 39 | @property 40 | def json(self): 41 | return self._json 42 | 43 | @json.setter 44 | def json(self, json): 45 | self._json = json 46 | 47 | @property 48 | def yaml(self): 49 | return self._yaml 50 | 51 | @yaml.setter 52 | def yaml(self, yaml): 53 | self._yaml = yaml 54 | -------------------------------------------------------------------------------- /splunk_sdk/action/v2alpha1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Action Service 23 | 24 | With the Splunk Cloud Action service, you can receive incoming trigger events and use pre-defined action templates to turn these events into meaningful actions. 25 | 26 | OpenAPI spec version: v2alpha1.12 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.action.v2alpha1.gen_action_service_api import ActionService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.action.v2alpha1.gen_models import Action, \ 38 | ActionKind, \ 39 | ActionMutable, \ 40 | AppMessageAction, \ 41 | EmailAction, \ 42 | EmailActionMutable, \ 43 | PublicWebhookKey, \ 44 | ServiceError, \ 45 | WebhookAction, \ 46 | WebhookActionMutable 47 | -------------------------------------------------------------------------------- /scripts/copy_generated_files.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # 4 | # copy_generated_files.sh 5 | # 6 | # e.g. copy_generated_files.sh /sdk-codegen/generated/python/ /splunk-cloud-sdk-python/splunk_sdk/ 7 | 8 | set -x 9 | 10 | sourcedir=$1 11 | targetdir=$2 12 | 13 | tmpdir="/tmp/splunk_sdk" 14 | 15 | # copy generated files to tmpdir for processing 16 | rm -rf ${tmpdir} 17 | mkdir -p ${tmpdir} 18 | cd ${tmpdir} 19 | cp -r ${sourcedir} . 20 | 21 | # work around a problem in codegen 22 | mv "${tmpdir}/app-registry" "${tmpdir}/app_registry" 23 | 24 | # move files into the appropriate module 25 | for svc in $(ls); 26 | do 27 | cd ${tmpdir}/${svc} 28 | for ver in $(ls); 29 | do 30 | cp -r "${tmpdir}/${svc}/${ver}/splunk_sdk/${svc}/" "${tmpdir}/${svc}/${ver}/" 31 | 32 | # delete the redundant dir 33 | rm -rf "${tmpdir}/${svc}/${ver}/splunk_sdk/" 34 | 35 | # Note: The '(recommended version)' is declared in the comments of the __init__.py by the codegen project. 36 | # The version is published in the openapi spec that is maintained by each individual service team. 37 | # This is how the default version is determined. 38 | default_version=$(cat "${tmpdir}/${svc}/${ver}/__init__.py" | grep "(recommended default)") 39 | if [[ ! -z "${default_version}" ]]; then 40 | 41 | # set the recommend version 42 | cp "${tmpdir}/${svc}/${ver}/__init__.py" "${tmpdir}/${svc}/" 43 | fi 44 | done 45 | done 46 | 47 | # copy generated files to target directory 48 | cp -r ${tmpdir}/ ${targetdir} -------------------------------------------------------------------------------- /splunk_sdk/ingest/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Ingest API 23 | 24 | Use the Ingest service in Splunk Cloud Services to send event and metrics data, or upload a static file, to Splunk Cloud Services. 25 | 26 | OpenAPI spec version: v1beta2.32 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.ingest.v1beta2.gen_ingest_api_api import IngestAPI 35 | 36 | # import models into sdk package 37 | from splunk_sdk.ingest.v1beta2.gen_models import Error, \ 38 | Event, \ 39 | FileUploadDetails, \ 40 | HECTokenAccessResponse, \ 41 | HECTokenCreateRequest, \ 42 | HECTokenCreateResponse, \ 43 | HECTokenUpdateRequest, \ 44 | HTTPResponse, \ 45 | Metric, \ 46 | MetricAttribute, \ 47 | MetricEvent, \ 48 | UploadSuccessResponse 49 | -------------------------------------------------------------------------------- /splunk_sdk/ingest/v1beta2/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Ingest API 23 | 24 | Use the Ingest service in Splunk Cloud Services to send event and metrics data, or upload a static file, to Splunk Cloud Services. 25 | 26 | OpenAPI spec version: v1beta2.32 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.ingest.v1beta2.gen_ingest_api_api import IngestAPI 35 | 36 | # import models into sdk package 37 | from splunk_sdk.ingest.v1beta2.gen_models import Error, \ 38 | Event, \ 39 | FileUploadDetails, \ 40 | HECTokenAccessResponse, \ 41 | HECTokenCreateRequest, \ 42 | HECTokenCreateResponse, \ 43 | HECTokenUpdateRequest, \ 44 | HTTPResponse, \ 45 | Metric, \ 46 | MetricAttribute, \ 47 | MetricEvent, \ 48 | UploadSuccessResponse 49 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py38, pep8, docs, docs-publish 3 | minversion = 2.0 4 | 5 | [testenv] 6 | deps = -r{toxinidir}/requirements.txt # project dependencies 7 | coverage==5.5 # testing-specific should be put here and below 8 | pytest==6.2.5 9 | flake8==3.9.2 10 | 11 | passenv = SPLUNK_AUTH_HOST_2 12 | SPLUNK_HOST_2 13 | SPLUNK_APP_CLIENT_ID_2 14 | TEST_USERNAME 15 | TEST_PASSWORD 16 | SPLUNK_TENANT_2 17 | SPLUNK_APP_CLIENT_CRED_ID_2 18 | SPLUNK_APP_CLIENT_CRED_SECRET_2 19 | SPLUNK_REGION 20 | SPLUNK_DEBUG 21 | SPLUNK_APP_PRINCIPAL_NAME_2 22 | SPLUNK_APP_PRINCIPAL_PRIVATE_KEY 23 | SPLUNK_APP_PRINCIPAL_KEY_ID 24 | SPLUNK_APP_PRINCIPAL_KEY_ALG 25 | ARTIFACT_USERNAME 26 | ARTIFACT_PASSWORD 27 | ARTIFACTORY_NPM_REGISTRY 28 | CI 29 | DYLD_FALLBACK_LIBRARY_PATH 30 | 31 | basepython = python3 32 | 33 | commands = coverage erase 34 | coverage run {envbindir}/pytest --tb=short {posargs} 35 | coverage report --include="*splunk_sdk*" --omit="*test*" 36 | coverage xml -i 37 | 38 | [testenv:docs] 39 | deps = -r{toxinidir}/docs-requirements.txt 40 | 41 | commands = pip3 install pdoc3 42 | {toxinidir}/scripts/generate_docs.sh 43 | 44 | [testenv:docs-publish] 45 | commands = {toxinidir}/scripts/publish_docs.sh 46 | 47 | [testenv:pep8] 48 | basepython = python3 49 | commands = flake8 50 | 51 | [flake8] 52 | enable-extensions = H106,H203,H904 53 | ignore = H202,H405,H501,F811,E501,E301,E303,W391,E266,E302,F401,W291 54 | show-source = True 55 | exclude=.venv,venv,.git,.tox,dist,doc,*lib/python*,*egg,build 56 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | 4 | ## Issues and bug reports 5 | 6 | If you see unexpected behavior with this project, please [create an issue on GitHub](/issues) with the following information: 7 | 8 | - A title and a clear description of the issue. 9 | - The project version (for example "0.1.4"). 10 | - The framework version (for example "Python 3.7.2"). 11 | 12 | If possible, include the following to help us reproduce the issue: 13 | - A code sample that demonstrates the issue. 14 | - Any unit test cases that show how the expected behavior is not occurring. 15 | - An executable test case. 16 | 17 | If you have a question about Splunk, see [Splunk Answers](https://answers.splunk.com). 18 | 19 | ## Development 20 | 21 | Configure your development environment as described in the project [README](/blob/master/README.md). 22 | 23 | ## Submit a pull request 24 | 25 | 1. Fill out the [Splunk Contribution Agreement](https://www.splunk.com/goto/contributions). 26 | 2. Create a new branch. For example: 27 | 28 | ``` 29 | git checkout -b my-branch develop 30 | ``` 31 | 32 | 3. Make code changes in your branch with tests. 33 | 4. Commit your changes. 34 | 5. Push your branch to GitHub. 35 | 36 | ``` 37 | git push origin my-branch 38 | ``` 39 | 40 | 6. In GitHub, create a pull request that targets the **develop** branch. CI tests are run automatically. 41 | 7. After the pull request is merged, delete your branch. 42 | 8. Pull changes from the **develop** branch. 43 | 44 | ``` 45 | git checkout develop 46 | git pull develop 47 | ``` 48 | 49 | ## Contact us 50 | 51 | If you have questions, reach out to us on [Slack](https://splunkdevplatform.slack.com) in the **#sdc** channel or email us at _sdcbeta@splunk.com_. -------------------------------------------------------------------------------- /splunk_sdk/action/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Action Service 23 | 24 | With the Action service in Splunk Cloud Services, you can receive incoming trigger events and use pre-defined action templates to turn these events into meaningful actions. 25 | 26 | OpenAPI spec version: v1beta2.12 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.action.v1beta2.gen_action_service_api import ActionService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.action.v1beta2.gen_models import Action, \ 38 | ActionKind, \ 39 | ActionMutable, \ 40 | StatusState, \ 41 | ActionResult, \ 42 | ActionResultEmailDetail, \ 43 | EmailAction, \ 44 | EmailActionMutable, \ 45 | PublicWebhookKey, \ 46 | ServiceError, \ 47 | TriggerEventActionMetadata, \ 48 | TriggerEventKind, \ 49 | TriggerEvent, \ 50 | WebhookAction, \ 51 | WebhookActionMutable 52 | -------------------------------------------------------------------------------- /splunk_sdk/collect/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2021 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Collect Service 23 | 24 | With the Collect service in Splunk Cloud Services, you can manage how data collection jobs ingest event and metric data. 25 | 26 | OpenAPI spec version: v1beta1.8 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.collect.v1beta1.gen_collect_service_api import CollectService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.collect.v1beta1.gen_models import BaseJob, \ 38 | ScalePolicy, \ 39 | StaticScale, \ 40 | DeleteJobsResponse, \ 41 | Error, \ 42 | EventExtraField, \ 43 | Execution, \ 44 | ExecutionConflictError, \ 45 | ExecutionPatch, \ 46 | Job, \ 47 | JobPatch, \ 48 | JobsPatch, \ 49 | ListJobsResponse, \ 50 | Metadata, \ 51 | PatchJobResult, \ 52 | PatchJobsResponse, \ 53 | SingleExecutionResponse, \ 54 | SingleJobResponse 55 | -------------------------------------------------------------------------------- /splunk_sdk/collect/v1beta1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2021 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Collect Service 23 | 24 | With the Collect service in Splunk Cloud Services, you can manage how data collection jobs ingest event and metric data. 25 | 26 | OpenAPI spec version: v1beta1.8 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.collect.v1beta1.gen_collect_service_api import CollectService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.collect.v1beta1.gen_models import BaseJob, \ 38 | ScalePolicy, \ 39 | StaticScale, \ 40 | DeleteJobsResponse, \ 41 | Error, \ 42 | EventExtraField, \ 43 | Execution, \ 44 | ExecutionConflictError, \ 45 | ExecutionPatch, \ 46 | Job, \ 47 | JobPatch, \ 48 | JobsPatch, \ 49 | ListJobsResponse, \ 50 | Metadata, \ 51 | PatchJobResult, \ 52 | PatchJobsResponse, \ 53 | SingleExecutionResponse, \ 54 | SingleJobResponse 55 | -------------------------------------------------------------------------------- /splunk_sdk/action/v1beta2/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Action Service 23 | 24 | With the Action service in Splunk Cloud Services, you can receive incoming trigger events and use pre-defined action templates to turn these events into meaningful actions. 25 | 26 | OpenAPI spec version: v1beta2.12 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.action.v1beta2.gen_action_service_api import ActionService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.action.v1beta2.gen_models import Action, \ 38 | ActionKind, \ 39 | ActionMutable, \ 40 | StatusState, \ 41 | ActionResult, \ 42 | ActionResultEmailDetail, \ 43 | EmailAction, \ 44 | EmailActionMutable, \ 45 | PublicWebhookKey, \ 46 | ServiceError, \ 47 | TriggerEventActionMetadata, \ 48 | TriggerEventKind, \ 49 | TriggerEvent, \ 50 | WebhookAction, \ 51 | WebhookActionMutable 52 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # Copyright © 2019 Splunk, Inc. 4 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 5 | # not use this file except in compliance with the License. You may obtain 6 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations 11 | # under the License. 12 | 13 | from setuptools import setup, find_packages 14 | from splunk_sdk import __version__ 15 | 16 | install_requires = ['requests>=2.25.1,<2.26.1', 17 | 'urllib3>=1.26.5,<1.26.7', 18 | 'pyjwt>=1.7.1,<1.8.0', 19 | 'cryptography>=2.6.1,<2.7.0', 20 | ] 21 | 22 | setup( 23 | name='splunk-cloud-sdk', 24 | version=__version__, 25 | description='SDK for the Splunk Developer Cloud platform', 26 | author='Splunk', 27 | author_email='dev@splunk.com', 28 | license='MIT', 29 | classifiers=['Development Status :: 3 - Alpha', ], 30 | keywords='', 31 | packages=find_packages(exclude=['test']), 32 | install_requires=install_requires, 33 | setup_requires=[ 34 | 'setuptools', 35 | 'setuptools-git', 36 | 'wheel' 37 | ], 38 | extras_require={ 39 | 'dev': ['pep8>=1.7.1,<2', 40 | 'sphinx >= 2.0.1,<3', 41 | 'sphinxcontrib-apidoc>=0.3.0', 42 | ], 43 | 'test': ['coverage>=4.5.3,<5', 44 | 'flake8>=3.7.7,<4', 45 | 'pytest>=4.4.0,<5', 46 | ], 47 | }, 48 | ) 49 | -------------------------------------------------------------------------------- /splunk_sdk/app_registry/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: App Registry 23 | 24 | With the App Registry service in Splunk Cloud Services, you can create, update, and manage your apps. 25 | 26 | OpenAPI spec version: v1beta2.0 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.app_registry.v1beta2.gen_app_registry_api import AppRegistry 35 | 36 | # import models into sdk package 37 | from splunk_sdk.app_registry.v1beta2.gen_models import AppName, \ 38 | AppResourceKind, \ 39 | AppResponseCreateUpdate, \ 40 | AppResponseGetList, \ 41 | CreateAppRequest, \ 42 | Error, \ 43 | Key, \ 44 | NativeAppFromAppResponseCreateUpdate, \ 45 | NativeAppFromAppResponseGetList, \ 46 | NativeAppPOST, \ 47 | ServiceAppFromAppResponseCreateUpdate, \ 48 | ServiceAppFromAppResponseGetList, \ 49 | ServiceAppPOST, \ 50 | Subscription, \ 51 | UpdateAppRequest, \ 52 | WebAppFromAppResponseCreateUpdate, \ 53 | WebAppFromAppResponseGetList 54 | -------------------------------------------------------------------------------- /splunk_sdk/app_registry/v1beta2/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: App Registry 23 | 24 | With the App Registry service in Splunk Cloud Services, you can create, update, and manage your apps. 25 | 26 | OpenAPI spec version: v1beta2.0 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.app_registry.v1beta2.gen_app_registry_api import AppRegistry 35 | 36 | # import models into sdk package 37 | from splunk_sdk.app_registry.v1beta2.gen_models import AppName, \ 38 | AppResourceKind, \ 39 | AppResponseCreateUpdate, \ 40 | AppResponseGetList, \ 41 | CreateAppRequest, \ 42 | Error, \ 43 | Key, \ 44 | NativeAppFromAppResponseCreateUpdate, \ 45 | NativeAppFromAppResponseGetList, \ 46 | NativeAppPOST, \ 47 | ServiceAppFromAppResponseCreateUpdate, \ 48 | ServiceAppFromAppResponseGetList, \ 49 | ServiceAppPOST, \ 50 | Subscription, \ 51 | UpdateAppRequest, \ 52 | WebAppFromAppResponseCreateUpdate, \ 53 | WebAppFromAppResponseGetList 54 | -------------------------------------------------------------------------------- /splunk_sdk/search/v2beta1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Splunk Search service 23 | 24 | Use the Search service in Splunk Cloud Services to dispatch, review, and manage searches and search jobs. You can finalize or cancel jobs, retrieve search results, and request search-related configurations from the Metadata Catalog service in Splunk Cloud Services. 25 | 26 | OpenAPI spec version: v2beta1.1 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.search.v2beta1.gen_splunk_search_service_api import SplunkSearchService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.search.v2beta1.gen_models import Message, \ 38 | QueryParameters, \ 39 | SearchStatus, \ 40 | DeleteSearchJob, \ 41 | SingleFieldSummary, \ 42 | SingleValueMode, \ 43 | FieldsSummary, \ 44 | ListPreviewResultsResponseFields, \ 45 | ListPreviewResultsResponse, \ 46 | ListSearchResultsResponse, \ 47 | SearchJob, \ 48 | SingleTimeBucket, \ 49 | TimeBucketsSummary, \ 50 | UpdateJob 51 | -------------------------------------------------------------------------------- /splunk_sdk/common/context.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | 12 | class Context(object): 13 | """ 14 | A Context exists to configure the SDK's behavior. The one setting that needs to be made in almost every instance is 15 | defining the tenant that should be made for subsequent requests. This Context is then passed in to create a 16 | service instance or a SplunkCloud instance: 17 | 18 | Example: 19 | client = SplunkCloud(Context(tenant="mytenant"), authManager) 20 | client.identity.validate() 21 | 22 | Configure tenant_scoped of bool type to True if the hostnames are scoped to a specific tenant/region to support 23 | multi-cell environments, currently defaults to False 24 | Configure Region as the name of the region that the tenant is contained in 25 | } 26 | """ 27 | 28 | DEFAULT_API_HOST = "api.scp.splunk.com" 29 | DEFAULT_HOST = DEFAULT_API_HOST 30 | 31 | def __init__(self, host=DEFAULT_HOST, api_host=DEFAULT_API_HOST, 32 | port=None, scheme="https", tenant='system', tenant_scoped=False, region=None, debug=False): 33 | self.host = host 34 | self.api_host = api_host 35 | self.port = port 36 | self.scheme = scheme 37 | self.tenant = tenant 38 | self.debug = debug 39 | self.tenant_scoped = tenant_scoped 40 | self.region = region 41 | -------------------------------------------------------------------------------- /THIRD-PARTY-CREDITS.md: -------------------------------------------------------------------------------- 1 | # Third-party software credits 2 | The Splunk Developer Cloud SDK for Python contains some libraries that were written by others, and are being redistributed as part of the SDK, under their respective open source licenses. We want to thank the contributors to these projects: 3 | 4 | ## Runtime Dependencies 5 | 6 | ### requests 7 | [https://pypi.org/project/requests/](https://pypi.org/project/requests/) 8 | 9 | requests version 2.25.1 10 | 11 | License: Apache Software License (Apache 2.0) 12 | 13 | ### urllib3 14 | [https://pypi.org/project/urllib3/](https://pypi.org/project/urllib3/) 15 | 16 | urllib3 version 1.25.2 17 | 18 | License: MIT License (MIT) 19 | 20 | ### PyJWT 21 | [https://pypi.org/project/PyJWT/](https://pypi.org/project/PyJWT/) 22 | 23 | PyJWT version 2.1.0 24 | 25 | License: MIT License (MIT) 26 | 27 | ### cryptography 28 | [https://pypi.org/project/cryptography/](https://pypi.org/project/cryptography/) 29 | 30 | cryptography version 2.6.1 31 | 32 | License: Apache Software License (Apache 2.0) 33 | 34 | 35 | ## Test Dependencies 36 | 37 | 38 | ### pep8 39 | [https://pypi.org/project/pep8/](https://pypi.org/project/pep8/) 40 | 41 | pep8 version 1.7.1 42 | 43 | License: MIT License (Expat license) 44 | 45 | 46 | ### flake8 47 | [https://pypi.org/project/flake8/](https://pypi.org/project/flake8/) 48 | 49 | flake8 version 3.7.7 50 | 51 | License: MIT License (MIT) 52 | 53 | 54 | ## Build Dependencies 55 | 56 | ### coverage 57 | [https://pypi.org/project/coverage/](https://pypi.org/project/coverage/) 58 | 59 | coverage version 4.5.3 60 | 61 | License: Apache Software License (Apache 2.0) 62 | 63 | ### pytest 64 | [https://pypi.org/project/pytest/](https://pypi.org/project/pytest/) 65 | 66 | pytest version 4.4.0 67 | 68 | License: MIT License (MIT license) 69 | 70 | ### pytest-asyncio 71 | [https://pypi.org/project/pytest-asyncio/](https://pypi.org/project/pytest-asyncio/) 72 | 73 | pytest-asyncio version 0.1.0 74 | 75 | License: Apache Software License (Apache 2.0) -------------------------------------------------------------------------------- /splunk_sdk/gateway/client.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | from splunk_sdk.base_client import handle_response 12 | from splunk_sdk.base_service import BaseService 13 | 14 | from splunk_sdk.gateway.results import Spec 15 | 16 | GATEWAY_SPECS = '/urls.json' 17 | 18 | 19 | class Gateway(BaseService): 20 | """The Gateway class TODO DOCS.""" 21 | 22 | def __init__(self, base_client): 23 | super().__init__(base_client) 24 | 25 | def list_specs(self): 26 | """Returns a raw response.""" 27 | url = self.base_client.build_url(GATEWAY_SPECS, omit_tenant=True) 28 | response = self.base_client.get(url) 29 | return handle_response(response, Spec, key='urls') 30 | 31 | def get_service_names(self): 32 | """Returns all Splunk Cloud service names.""" 33 | return [spec.name for spec in self.list_specs()] 34 | 35 | def get_spec_url(self, name, link='yaml3'): 36 | """Return the API specification URL for a given service name.""" 37 | specs = self.list_specs() 38 | for s in specs: 39 | if name == s.name: 40 | return self.base_client.build_url(s.links[link], 41 | omit_tenant=True) 42 | 43 | def get_spec(self, name, link='yaml3'): 44 | """Downloads the API specification file for a given service name.""" 45 | # TODO(dan): need to set accept header 46 | return self.base_client.get(self.get_spec_url(name, link=link)) 47 | -------------------------------------------------------------------------------- /splunk_sdk/identity/v2beta1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Identity 23 | 24 | With the Identity service in Splunk Cloud Services, you can authenticate and authorize Splunk Cloud Services users. 25 | 26 | OpenAPI spec version: v2beta1.23 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.identity.v2beta1.gen_identity_api import Identity 35 | 36 | # import models into sdk package 37 | from splunk_sdk.identity.v2beta1.gen_models import AddGroupMemberBody, \ 38 | AddGroupRoleBody, \ 39 | AddMemberBody, \ 40 | CreateGroupBody, \ 41 | PrincipalKind, \ 42 | Credential, \ 43 | ECJwk, \ 44 | CreatePrincipalProfile, \ 45 | CreatePrincipalBody, \ 46 | CreateRoleBody, \ 47 | Group, \ 48 | GroupMember, \ 49 | GroupRole, \ 50 | IdentityProviderBodyConfig, \ 51 | IdentityProviderBody, \ 52 | IdentityProviderConfigBodyConfig, \ 53 | IdentityProviderConfigBody, \ 54 | PrincipalProfile, \ 55 | Member, \ 56 | PermissionString, \ 57 | Principal, \ 58 | PrincipalPublicKey, \ 59 | PrincipalPublicKeyStatusBody, \ 60 | Role, \ 61 | RolePermission, \ 62 | TenantStatus, \ 63 | Tenant, \ 64 | ValidateInfo 65 | -------------------------------------------------------------------------------- /splunk_sdk/common/sscmodel.py: -------------------------------------------------------------------------------- 1 | import json 2 | from abc import ABC, abstractmethod 3 | import datetime 4 | from typing import Optional 5 | 6 | from requests import Request, Response 7 | 8 | 9 | class SSCModel(ABC): 10 | """ 11 | Base class for all SSC model objects. Allow access to raw response and handle the serialization 12 | and deserialization of the model objects. 13 | """ 14 | 15 | def __init__(self): 16 | self._response = None 17 | 18 | @abstractmethod 19 | def to_dict(self) -> dict: 20 | pass 21 | 22 | @property 23 | def response(self) -> Optional[Response]: 24 | """ 25 | :return: the raw HTTP response from the service call. Will return None if the model was not created from a call. 26 | """ 27 | return self._response 28 | 29 | @response.setter 30 | def response(self, response: Response): 31 | self._response = response 32 | 33 | def to_json(self) -> str: 34 | return json.dumps(self.to_dict(), default=lambda o: o.to_dict()) 35 | 36 | def _parse_date(self, datestr: datetime): 37 | return datestr 38 | 39 | def to_str(self): 40 | """Returns the string representation of the model""" 41 | return self.to_json() 42 | 43 | def __repr__(self): 44 | """For `print` and `pprint`""" 45 | return self.to_str() 46 | 47 | def __eq__(self, other): 48 | """Returns true if both objects are equal""" 49 | if not isinstance(other, self.__class__): 50 | return False 51 | 52 | return self.__dict__ == other.__dict__ 53 | 54 | def __ne__(self, other): 55 | """Returns true if both objects are not equal""" 56 | return not self == other 57 | 58 | def reprJSON(self): 59 | return self.to_dict() 60 | 61 | 62 | class SSCVoidModel(SSCModel): 63 | """ 64 | SSCVoidModel is here simply to allow access to the underlying raw response if needed. 65 | """ 66 | 67 | def __init__(self, response: Response): 68 | self._response = response 69 | 70 | def to_dict(self) -> dict: 71 | return {} 72 | -------------------------------------------------------------------------------- /test/test_gateway.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | import re 11 | 12 | import pytest 13 | from test.fixtures import get_test_client as test_client # NOQA 14 | from splunk_sdk.gateway.client import Gateway 15 | 16 | ACTION_URI = r"""https://region-(?P[\w]+).(?P[\w.]+)/system/action/specs/v\d+(?:(?:alpha|beta)\d+(?:\.\d+)?)/openapi.yaml""" 17 | 18 | 19 | @pytest.mark.usefixtures("test_client") # NOQA 20 | def test_list_specs(test_client): 21 | # Get the specs from the api gateway 22 | gateway = Gateway(test_client) 23 | specs = gateway.list_specs() 24 | assert(len(specs) > 0) 25 | 26 | 27 | @pytest.mark.usefixtures("test_client") # NOQA 28 | def test_get_service_names(test_client): 29 | # Get the service names from the api gateway 30 | gateway = Gateway(test_client) 31 | names = gateway.get_service_names() 32 | assert(len(names) > 0) 33 | 34 | 35 | @pytest.mark.usefixtures("test_client") # NOQA 36 | def test_get_spec_url(test_client): 37 | # Get the spec url from the app gateway 38 | gateway = Gateway(test_client) 39 | spec = gateway.get_spec_url('action') 40 | 41 | match = re.match(ACTION_URI, spec) 42 | assert match is not None 43 | assert(match.group('host') == gateway.base_client.context.api_host) 44 | assert(match.group('region') == gateway.base_client.context.region) 45 | 46 | 47 | @pytest.mark.usefixtures("test_client") # NOQA 48 | def test_get_spec(test_client): 49 | # Download the spec from the api gateway 50 | gateway = Gateway(test_client) 51 | spec = gateway.get_spec('action') 52 | print(spec) 53 | assert(spec is not None) 54 | -------------------------------------------------------------------------------- /splunk_sdk/identity/v3alpha1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Identity 23 | 24 | With the Identity service in Splunk Cloud Services, you can authenticate and authorize Splunk Cloud Services users. 25 | 26 | OpenAPI spec version: v3alpha1.5 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.identity.v3alpha1.gen_identity_api import Identity 35 | 36 | # import models into sdk package 37 | from splunk_sdk.identity.v3alpha1.gen_models import AddGroupMemberBody, \ 38 | AddGroupRoleBody, \ 39 | AddMemberBody, \ 40 | AddRolePermissionBody, \ 41 | CreateGroupBody, \ 42 | CreateRoleBody, \ 43 | CreateSamlClientBody, \ 44 | ECJwk, \ 45 | EcMetadataStack, \ 46 | EcMetadata, \ 47 | Group, \ 48 | GroupList, \ 49 | GroupMember, \ 50 | GroupMemberList, \ 51 | GroupRole, \ 52 | GroupRoleList, \ 53 | IdentityProviderBodyConfig, \ 54 | IdentityProviderBody, \ 55 | IdentityProviderConfigBodyConfig, \ 56 | IdentityProviderConfigBody, \ 57 | PrincipalProfile, \ 58 | Member, \ 59 | MemberList, \ 60 | PermissionList, \ 61 | PrincipalKind, \ 62 | Principal, \ 63 | PrincipalList, \ 64 | PrincipalPublicKey, \ 65 | PrincipalPublicKeyStatusBody, \ 66 | ResetPasswordBody, \ 67 | Role, \ 68 | RoleList, \ 69 | RolePermission, \ 70 | RolePermissionList, \ 71 | SamlClient, \ 72 | TenantStatus, \ 73 | Tenant, \ 74 | UpdatePasswordBody, \ 75 | UpdateSamlClientBody, \ 76 | ValidateInfo 77 | -------------------------------------------------------------------------------- /test/test_forwarders.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | import pytest 12 | 13 | from splunk_sdk.base_client import BaseClient 14 | from splunk_sdk.forwarders import SplunkForwarderService, Certificate 15 | from test.fixtures import get_test_client as test_client # NOQA 16 | 17 | 18 | PEM = '''-----BEGIN CERTIFICATE----- 19 | MIIC1TCCAb2gAwIBAgIJAIOAwz2qyz1FMA0GCSqGSIb3DQEBCwUAMBoxGDAWBgNV 20 | BAMMD3d3dy5leGFtcGxlLmNvbTAeFw0yMTA4MjcxOTAwNTVaFw0yNjA4MjYxOTAw 21 | NTVaMBoxGDAWBgNVBAMMD3d3dy5leGFtcGxlLmNvbTCCASIwDQYJKoZIhvcNAQEB 22 | BQADggEPADCCAQoCggEBANHY9Uc+AJL17z6GkJ9VoiPU0TDF3+rVjp2CLxcc2Upt 23 | BgX//F+MFNwY6bK3HEXE3AQPvuOtp7FQQYX+2BgLQwMiyKThKg5V4KcmsDR3zvqQ 24 | Rdrd4lXm5KAt8kLSF+VFFO+Fm0eJG7fQgERsBFuyHg16511dh1JC2cAu6E2IaFw2 25 | nUWyYsvjKCl3hcPqvmVl8MIFexhPw7cyUlq68PyEgYpDXzfgE1DIiu1BGQ5z/UZ2 26 | XzBTQKg7/+iVfdMjftYbRqLk3MKwaM0yuohVBLkkBKuY8H+93G4qizYGAs+Ae5Hi 27 | EYPUkkmQMYfOXhSF7cV2aDPcCAY9oJWDaQNBk3rx4v8CAwEAAaMeMBwwGgYDVR0R 28 | BBMwEYIPd3d3LmV4YW1wbGUuY29tMA0GCSqGSIb3DQEBCwUAA4IBAQC5mqAoFR1t 29 | tYR558EYxn91VVmFFeUdXtAbkWQ6LLLQPTbWz8bQW5qoj9mYF7r2AAKnJvJoAtUX 30 | ZYfVlHhEenGG9x8U/he/4L8IubHySMrksmoGVC5vS/0ecSD0pjObcNa6ZZH+ELbf 31 | O1Fm1vP/QzOZeQoH2C4tdtDNXS9JV0F4ZGOHQALEBNkO5CfOVXd3YhmGGLFxkgjs 32 | I135CtslJTR3+GpPHg44/Lo7VvwuSp0gJIzgLayM8Hcb7fKpZ0D2FsRkc4dDIwuR 33 | wDYojnaUIAuni1Dd8oguYvm5+S56XOOO9BNDorxNzqqHuwEsqszG86VBEkMAB5v+ 34 | AQ86ecyUH90A 35 | -----END CERTIFICATE----- 36 | ''' 37 | 38 | @pytest.mark.usefixtures("test_client") # NOQA 39 | def test_cert_crud(test_client: BaseClient): 40 | forwarders = SplunkForwarderService(test_client) 41 | forwarders.delete_certificates() 42 | 43 | certs = forwarders.list_certificates() 44 | current_cert_count = len(certs) 45 | 46 | forwarders.add_certificate(Certificate(pem=PEM)) 47 | 48 | certs = forwarders.list_certificates() 49 | assert(len(certs) == current_cert_count + 1) 50 | 51 | forwarders.delete_certificates() 52 | certs = forwarders.list_certificates() 53 | assert(len(certs) == 0) 54 | -------------------------------------------------------------------------------- /splunk_sdk/identity/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Identity 23 | 24 | With the Identity service in Splunk Cloud Services, you can authenticate and authorize Splunk Cloud Services users. 25 | 26 | OpenAPI spec version: v3.6 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.identity.v3.gen_identity_api import Identity 35 | 36 | # import models into sdk package 37 | from splunk_sdk.identity.v3.gen_models import AddGroupMemberBody, \ 38 | AddGroupRoleBody, \ 39 | AddMemberBody, \ 40 | AddRolePermissionBody, \ 41 | CreateGroupBody, \ 42 | PrincipalKind, \ 43 | Credential, \ 44 | ECJwk, \ 45 | CreatePrincipalProfile, \ 46 | CreatePrincipalBody, \ 47 | CreateRoleBody, \ 48 | CreateSamlClientBody, \ 49 | EcMetadataStack, \ 50 | EcMetadata, \ 51 | Group, \ 52 | GroupList, \ 53 | GroupMember, \ 54 | GroupMemberList, \ 55 | GroupRole, \ 56 | GroupRoleList, \ 57 | IdentityProviderBodyConfig, \ 58 | IdentityProviderBodyJit, \ 59 | IdentityProviderBody, \ 60 | IdentityProviderConfigBodyConfig, \ 61 | IdentityProviderConfigBodyJit, \ 62 | IdentityProviderConfigBody, \ 63 | PrincipalProfile, \ 64 | Member, \ 65 | MemberList, \ 66 | PermissionList, \ 67 | Principal, \ 68 | PrincipalList, \ 69 | PrincipalPublicKey, \ 70 | PrincipalPublicKeyStatusBody, \ 71 | ResetPasswordBody, \ 72 | Role, \ 73 | RoleList, \ 74 | RolePermission, \ 75 | RolePermissionList, \ 76 | SamlClient, \ 77 | TenantStatus, \ 78 | Tenant, \ 79 | UpdateGroupBody, \ 80 | UpdatePasswordBody, \ 81 | UpdateRoleBody, \ 82 | UpdateSamlClientBody, \ 83 | ValidateInfo 84 | -------------------------------------------------------------------------------- /splunk_sdk/identity/v3/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Identity 23 | 24 | With the Identity service in Splunk Cloud Services, you can authenticate and authorize Splunk Cloud Services users. 25 | 26 | OpenAPI spec version: v3.6 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.identity.v3.gen_identity_api import Identity 35 | 36 | # import models into sdk package 37 | from splunk_sdk.identity.v3.gen_models import AddGroupMemberBody, \ 38 | AddGroupRoleBody, \ 39 | AddMemberBody, \ 40 | AddRolePermissionBody, \ 41 | CreateGroupBody, \ 42 | PrincipalKind, \ 43 | Credential, \ 44 | ECJwk, \ 45 | CreatePrincipalProfile, \ 46 | CreatePrincipalBody, \ 47 | CreateRoleBody, \ 48 | CreateSamlClientBody, \ 49 | EcMetadataStack, \ 50 | EcMetadata, \ 51 | Group, \ 52 | GroupList, \ 53 | GroupMember, \ 54 | GroupMemberList, \ 55 | GroupRole, \ 56 | GroupRoleList, \ 57 | IdentityProviderBodyConfig, \ 58 | IdentityProviderBodyJit, \ 59 | IdentityProviderBody, \ 60 | IdentityProviderConfigBodyConfig, \ 61 | IdentityProviderConfigBodyJit, \ 62 | IdentityProviderConfigBody, \ 63 | PrincipalProfile, \ 64 | Member, \ 65 | MemberList, \ 66 | PermissionList, \ 67 | Principal, \ 68 | PrincipalList, \ 69 | PrincipalPublicKey, \ 70 | PrincipalPublicKeyStatusBody, \ 71 | ResetPasswordBody, \ 72 | Role, \ 73 | RoleList, \ 74 | RolePermission, \ 75 | RolePermissionList, \ 76 | SamlClient, \ 77 | TenantStatus, \ 78 | Tenant, \ 79 | UpdateGroupBody, \ 80 | UpdatePasswordBody, \ 81 | UpdateRoleBody, \ 82 | UpdateSamlClientBody, \ 83 | ValidateInfo 84 | -------------------------------------------------------------------------------- /splunk_sdk/search/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Splunk Search service 23 | 24 | Use the Search service in Splunk Cloud Services to dispatch, review, and manage searches and search jobs. You can finalize or cancel jobs, retrieve search results, and request search-related configurations from the Metadata Catalog service in Splunk Cloud Services. 25 | 26 | OpenAPI spec version: v2 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.search.v2.gen_splunk_search_service_api import SplunkSearchService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.search.v2.gen_models import Dataset, \ 38 | DatasetPATCH, \ 39 | FieldPOST, \ 40 | FieldDataType, \ 41 | FieldType, \ 42 | FieldPrevalence, \ 43 | DatasetPOST, \ 44 | Message, \ 45 | QueryParameters, \ 46 | SearchStatus, \ 47 | DeleteSearchJob, \ 48 | FederatedConnection, \ 49 | FederatedConnectionInput, \ 50 | FederatedDataset, \ 51 | FederatedDatasetKind, \ 52 | FederatedDatasetPATCH, \ 53 | SingleFieldSummary, \ 54 | SingleValueMode, \ 55 | FieldsSummary, \ 56 | IndexDataset, \ 57 | IndexDatasetKind, \ 58 | IndexDatasetPATCH, \ 59 | KVCollectionDataset, \ 60 | KVCollectionDatasetKind, \ 61 | KVCollectionDatasetPATCH, \ 62 | ListDatasets, \ 63 | ListPreviewResultsResponseFields, \ 64 | ListPreviewResultsResponse, \ 65 | ListSearchResultsResponse, \ 66 | LookupDatasetExternalKind, \ 67 | LookupDataset, \ 68 | LookupDatasetKind, \ 69 | LookupDatasetPATCH, \ 70 | MetricDataset, \ 71 | MetricDatasetKind, \ 72 | MetricDatasetPATCH, \ 73 | SearchJob, \ 74 | SingleTimeBucket, \ 75 | TimeBucketsSummary, \ 76 | UpdateJob 77 | -------------------------------------------------------------------------------- /splunk_sdk/search/v2/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Splunk Search service 23 | 24 | Use the Search service in Splunk Cloud Services to dispatch, review, and manage searches and search jobs. You can finalize or cancel jobs, retrieve search results, and request search-related configurations from the Metadata Catalog service in Splunk Cloud Services. 25 | 26 | OpenAPI spec version: v2 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.search.v2.gen_splunk_search_service_api import SplunkSearchService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.search.v2.gen_models import Dataset, \ 38 | DatasetPATCH, \ 39 | FieldPOST, \ 40 | FieldDataType, \ 41 | FieldType, \ 42 | FieldPrevalence, \ 43 | DatasetPOST, \ 44 | Message, \ 45 | QueryParameters, \ 46 | SearchStatus, \ 47 | DeleteSearchJob, \ 48 | FederatedConnection, \ 49 | FederatedConnectionInput, \ 50 | FederatedDataset, \ 51 | FederatedDatasetKind, \ 52 | FederatedDatasetPATCH, \ 53 | SingleFieldSummary, \ 54 | SingleValueMode, \ 55 | FieldsSummary, \ 56 | IndexDataset, \ 57 | IndexDatasetKind, \ 58 | IndexDatasetPATCH, \ 59 | KVCollectionDataset, \ 60 | KVCollectionDatasetKind, \ 61 | KVCollectionDatasetPATCH, \ 62 | ListDatasets, \ 63 | ListPreviewResultsResponseFields, \ 64 | ListPreviewResultsResponse, \ 65 | ListSearchResultsResponse, \ 66 | LookupDatasetExternalKind, \ 67 | LookupDataset, \ 68 | LookupDatasetKind, \ 69 | LookupDatasetPATCH, \ 70 | MetricDataset, \ 71 | MetricDatasetKind, \ 72 | MetricDatasetPATCH, \ 73 | SearchJob, \ 74 | SingleTimeBucket, \ 75 | TimeBucketsSummary, \ 76 | UpdateJob 77 | -------------------------------------------------------------------------------- /splunk_sdk/ml/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2020 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Machine Learning 23 | 24 | Use the Machine Learning service in Splunk Cloud Services to deliver resource intensive machine learning workloads. The Machine Learning service covers model experimentation, training, inference, validation, scoring, and serving. 25 | 26 | OpenAPI spec version: v2beta1.1 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.ml.v2beta1.gen_machine_learning_api import MachineLearning 35 | 36 | # import models into sdk package 37 | from splunk_sdk.ml.v2beta1.gen_models import WorkflowValidationOption, \ 38 | CrossValidation, \ 39 | DeploymentSpec, \ 40 | Error, \ 41 | OutputDataDestination, \ 42 | Events, \ 43 | ExecutorErrors, \ 44 | ExecutorLogs, \ 45 | Fields, \ 46 | Task, \ 47 | FitTask, \ 48 | InputDataSource, \ 49 | InputData, \ 50 | InputStreamSource, \ 51 | InputStream, \ 52 | KafkaInput, \ 53 | OutputStreamDestination, \ 54 | KafkaOutput, \ 55 | OutputData, \ 56 | OutputStream, \ 57 | RawData, \ 58 | SPL, \ 59 | ScoreReport, \ 60 | Score, \ 61 | TaskSummary, \ 62 | WorkflowValidationScore, \ 63 | TrainTestScore, \ 64 | TrainTestSplit, \ 65 | Workflow, \ 66 | WorkflowBuildValidationOption, \ 67 | WorkflowBuildValidationScore, \ 68 | WorkflowBuild, \ 69 | WorkflowManagerErrors, \ 70 | WorkflowBuildError, \ 71 | WorkflowManagerLogs, \ 72 | WorkflowBuildLog, \ 73 | WorkflowDeployment, \ 74 | WorkflowDeploymentError, \ 75 | WorkflowDeploymentLog, \ 76 | WorkflowInference, \ 77 | WorkflowRun, \ 78 | WorkflowRunError, \ 79 | WorkflowRunLog, \ 80 | WorkflowStreamDeployment, \ 81 | WorkflowsGetResponse 82 | -------------------------------------------------------------------------------- /splunk_sdk/ml/v2beta1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2020 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Machine Learning 23 | 24 | Use the Machine Learning service in Splunk Cloud Services to deliver resource intensive machine learning workloads. The Machine Learning service covers model experimentation, training, inference, validation, scoring, and serving. 25 | 26 | OpenAPI spec version: v2beta1.1 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.ml.v2beta1.gen_machine_learning_api import MachineLearning 35 | 36 | # import models into sdk package 37 | from splunk_sdk.ml.v2beta1.gen_models import WorkflowValidationOption, \ 38 | CrossValidation, \ 39 | DeploymentSpec, \ 40 | Error, \ 41 | OutputDataDestination, \ 42 | Events, \ 43 | ExecutorErrors, \ 44 | ExecutorLogs, \ 45 | Fields, \ 46 | Task, \ 47 | FitTask, \ 48 | InputDataSource, \ 49 | InputData, \ 50 | InputStreamSource, \ 51 | InputStream, \ 52 | KafkaInput, \ 53 | OutputStreamDestination, \ 54 | KafkaOutput, \ 55 | OutputData, \ 56 | OutputStream, \ 57 | RawData, \ 58 | SPL, \ 59 | ScoreReport, \ 60 | Score, \ 61 | TaskSummary, \ 62 | WorkflowValidationScore, \ 63 | TrainTestScore, \ 64 | TrainTestSplit, \ 65 | Workflow, \ 66 | WorkflowBuildValidationOption, \ 67 | WorkflowBuildValidationScore, \ 68 | WorkflowBuild, \ 69 | WorkflowManagerErrors, \ 70 | WorkflowBuildError, \ 71 | WorkflowManagerLogs, \ 72 | WorkflowBuildLog, \ 73 | WorkflowDeployment, \ 74 | WorkflowDeploymentError, \ 75 | WorkflowDeploymentLog, \ 76 | WorkflowInference, \ 77 | WorkflowRun, \ 78 | WorkflowRunError, \ 79 | WorkflowRunLog, \ 80 | WorkflowStreamDeployment, \ 81 | WorkflowsGetResponse 82 | -------------------------------------------------------------------------------- /splunk_sdk/search/v3alpha1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Splunk Search service 23 | 24 | Use the Search service in Splunk Cloud Services to dispatch, review, and manage searches and search jobs. You can finalize or cancel jobs, retrieve search results, and request search-related configurations from the Metadata Catalog service in Splunk Cloud Services. 25 | 26 | OpenAPI spec version: v3alpha1 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.search.v3alpha1.gen_splunk_search_service_api import SplunkSearchService 35 | 36 | # import models into sdk package 37 | from splunk_sdk.search.v3alpha1.gen_models import Dataset, \ 38 | DatasetPATCH, \ 39 | FieldPOST, \ 40 | FieldDataType, \ 41 | FieldType, \ 42 | FieldPrevalence, \ 43 | DatasetPOST, \ 44 | Message, \ 45 | QueryParameters, \ 46 | SearchStatus, \ 47 | DeleteSearchJob, \ 48 | FederatedConnection, \ 49 | FederatedConnectionInput, \ 50 | FederatedDataset, \ 51 | FederatedDatasetKind, \ 52 | FederatedDatasetPATCH, \ 53 | SingleFieldSummary, \ 54 | SingleValueMode, \ 55 | FieldsSummary, \ 56 | IndexDataset, \ 57 | IndexDatasetKind, \ 58 | IndexDatasetPATCH, \ 59 | KVCollectionDataset, \ 60 | KVCollectionDatasetKind, \ 61 | KVCollectionDatasetPATCH, \ 62 | ListDatasets, \ 63 | Module, \ 64 | ListModules, \ 65 | ListPreviewResultsResponseFields, \ 66 | ListPreviewResultsResponse, \ 67 | ListSearchResultsResponse, \ 68 | LookupDatasetExternalKind, \ 69 | LookupDataset, \ 70 | LookupDatasetKind, \ 71 | LookupDatasetPATCH, \ 72 | MetricDataset, \ 73 | MetricDatasetKind, \ 74 | MetricDatasetPATCH, \ 75 | SearchJob, \ 76 | SingleStatementQueryParameters, \ 77 | SearchModule, \ 78 | SingleTimeBucket, \ 79 | TimeBucketsSummary, \ 80 | UpdateJob 81 | -------------------------------------------------------------------------------- /splunk_sdk/streams/v4alpha1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Data Stream Processing REST API 23 | 24 | Use the Streams service to perform create, read, update, and delete (CRUD) operations on your data pipeline. The Streams service also has metrics and preview session endpoints and gives you full control over your data pipeline. 25 | 26 | OpenAPI spec version: v4alpha1.1 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.streams.v4alpha1.gen_data_stream_processing_rest_api_api import DataStreamProcessingRESTAPI 35 | 36 | # import models into sdk package 37 | from splunk_sdk.streams.v4alpha1.gen_models import ActivatePipelineRequest, \ 38 | ArgumentModel, \ 39 | AutopilotActivationDeactivationResponse, \ 40 | ConnectionPatchRequest, \ 41 | ConnectionPutRequest, \ 42 | ConnectionRequest, \ 43 | Source, \ 44 | ConnectionVersionResponse, \ 45 | ConnectionResponse, \ 46 | ConnectionSaveResponse, \ 47 | ConnectorResponse, \ 48 | DeactivatePipelineRequest, \ 49 | Pipeline, \ 50 | PipelineEdge, \ 51 | PipelineNode, \ 52 | PipelineMigrationInfo, \ 53 | DecompileRequest, \ 54 | DecompileResponse, \ 55 | ErrorResponse, \ 56 | UploadFileResponse, \ 57 | FilesMetaDataResponse, \ 58 | FunctionModel, \ 59 | GetInputSchemaRequest, \ 60 | GetOutputSchemaRequest, \ 61 | LookupTableResponse, \ 62 | NodeMetrics, \ 63 | MetricsResponse, \ 64 | PaginatedResponseOfConnectionResponse, \ 65 | PaginatedResponseOfConnectorResponse, \ 66 | PipelineResponseV4, \ 67 | UpdateError, \ 68 | PaginatedResponseOfPipelineResponseV4, \ 69 | TemplateResponse, \ 70 | PaginatedResponseOfTemplateResponse, \ 71 | PipelinePatchRequest, \ 72 | PipelineRequest, \ 73 | PreviewNode, \ 74 | RuleMetrics, \ 75 | PreviewData, \ 76 | PreviewSessionStartRequest, \ 77 | PreviewStartResponse, \ 78 | PreviewState, \ 79 | RegistryModel, \ 80 | SplCompileRequest, \ 81 | TemplatePatchRequest, \ 82 | TemplatePutRequest, \ 83 | TemplateRequest, \ 84 | UplType, \ 85 | ValidateConnectionRequest, \ 86 | ValidateRequest, \ 87 | ValidateResponse 88 | -------------------------------------------------------------------------------- /test/test_ingest.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | import os.path 11 | 12 | import pytest 13 | 14 | from splunk_sdk.base_client import HTTPError 15 | from splunk_sdk.ingest import IngestAPI, Event, HTTPResponse, Metric, \ 16 | MetricAttribute, MetricEvent 17 | from test.fixtures import get_test_client as test_client # NOQA 18 | 19 | FILE_TO_UPLOAD = os.path.join(os.path.abspath(os.path.dirname(__file__)), 20 | "data/ml/iris.csv") 21 | 22 | @pytest.mark.usefixtures("test_client") # NOQA 23 | def test_post_events(test_client): 24 | ingest = IngestAPI(test_client) 25 | 26 | event_data = Event(body='event1', host='host1', source='source1', sourcetype='sourcetype1', 27 | attributes={'data': 'data1'}, timestamp=1533671808138) 28 | event_list = [event_data] 29 | event_response = ingest.post_events(event_list) 30 | 31 | assert (isinstance(event_response, HTTPResponse)) 32 | assert (event_response.code == 'SUCCESS') 33 | 34 | 35 | @pytest.mark.usefixtures("test_client") # NOQA 36 | def test_post_metrics(test_client): 37 | ingest = IngestAPI(test_client) 38 | 39 | metrics = Metric('CPU', value=5.5, dimensions={'data': 'data1'}, unit='units') 40 | metrics_list = [metrics] 41 | met_attr = MetricAttribute(default_type='data1', default_dimensions={'dimension': 'dValue'}, default_unit='data2') 42 | metrics_data = MetricEvent(metrics_list, host='host1', source='source1', 43 | sourcetype='sourcetype1', timestamp=1533671808138, 44 | attributes=met_attr) 45 | metrics_data_list = [metrics_data] 46 | metrics_response = ingest.post_metrics(metrics_data_list) 47 | 48 | assert (isinstance(metrics_response, HTTPResponse)) 49 | assert (metrics_response.code == 'SUCCESS') 50 | 51 | 52 | @pytest.mark.usefixtures("test_client") # NOQA 53 | def test_post_events_bad_request(test_client): 54 | ingest = IngestAPI(test_client) 55 | event_list = [] 56 | error_str = 'Empty array was provided as input' 57 | try: 58 | ingest.post_events(event_list) 59 | except HTTPError as error: 60 | assert (error.http_status_code == 400) 61 | assert (error.code == 'INVALID_DATA') 62 | assert (error.details == error_str) 63 | 64 | 65 | @pytest.mark.usefixtures("test_client") 66 | def test_post_file(test_client): 67 | ingest = IngestAPI(test_client) 68 | resp = ingest.upload_files(FILE_TO_UPLOAD) 69 | assert (resp.code == "SUCCESS") 70 | -------------------------------------------------------------------------------- /splunk_sdk/splunk_cloud.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # Copyright © 2019 Splunk, Inc. 4 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 5 | # not use this file except in compliance with the License. You may obtain 6 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations 11 | # under the License. 12 | 13 | from splunk_sdk.app_registry import AppRegistry 14 | from splunk_sdk.action import ActionService 15 | from splunk_sdk.auth.auth_manager import AuthManager 16 | from splunk_sdk.base_client import get_client 17 | from splunk_sdk.catalog import MetadataCatalog 18 | from splunk_sdk.collect import CollectService 19 | from splunk_sdk.common.context import Context 20 | from splunk_sdk.kvstore import KVStoreAPI as KVStore 21 | from splunk_sdk.ingest import IngestAPI 22 | from splunk_sdk.gateway.client import Gateway 23 | from splunk_sdk.provisioner import Provisioner 24 | from splunk_sdk.search import SplunkSearchService as Search 25 | from splunk_sdk.streams import DataStreamProcessingRESTAPI as Streams 26 | from splunk_sdk.identity import Identity 27 | from splunk_sdk.forwarders import SplunkForwarderService as Forwarders 28 | from splunk_sdk.ml import MachineLearning 29 | 30 | 31 | class SplunkCloud(object): 32 | """ 33 | The SplunkCloud class ties all of the Splunk Cloud services together. 34 | Use this class to get started with the Splunk Cloud Platform. 35 | 36 | To create the client, provide a `Context` object with your tenant and an `AuthManager` 37 | object containing the appropriate app credentials. 38 | """ 39 | 40 | def __init__(self, context: Context, auth_manager: AuthManager, requests_hooks=None): 41 | """ 42 | Creates a new instance of the SplunkCloud class 43 | :param context: a Context object that configures the behavior of the client. Setting 'tenant' will be 44 | required in almost all circumstances 45 | :param auth_manager: A subclass of AuthManager that contains credentials for connecting to the Splunk Developer 46 | Cloud. 47 | """ 48 | self.base_client = get_client(context, auth_manager, requests_hooks=requests_hooks) 49 | 50 | '''supported services''' 51 | self.action = ActionService(self.base_client) 52 | self.app_registry = AppRegistry(self.base_client) 53 | self.catalog = MetadataCatalog(self.base_client) 54 | self.collect = CollectService(self.base_client) 55 | self.forwarders = Forwarders(self.base_client) 56 | self.gateway = Gateway(self.base_client) 57 | self.identity = Identity(self.base_client) 58 | self.ingest = IngestAPI(self.base_client) 59 | self.kvstore = KVStore(self.base_client) 60 | self.provisioner = Provisioner(self.base_client) 61 | self.search = Search(self.base_client) 62 | self.streams = Streams(self.base_client) 63 | self.ml = MachineLearning(self.base_client) 64 | -------------------------------------------------------------------------------- /splunk_sdk/streams/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Data Stream Processing REST API 23 | 24 | Use the Streams service to perform create, read, update, and delete (CRUD) operations on your data pipeline. The Streams service also has metrics and preview session endpoints and gives you full control over your data pipeline. 25 | 26 | OpenAPI spec version: v3beta1.1 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.streams.v3beta1.gen_data_stream_processing_rest_api_api import DataStreamProcessingRESTAPI 35 | 36 | # import models into sdk package 37 | from splunk_sdk.streams.v3beta1.gen_models import ActivatePipelineRequest, \ 38 | ArgumentModel, \ 39 | ConnectionPatchRequest, \ 40 | ConnectionPutRequest, \ 41 | ConnectionRequest, \ 42 | Source, \ 43 | ConnectionVersionResponse, \ 44 | ConnectionResponse, \ 45 | ConnectionSaveResponse, \ 46 | ConnectorResponse, \ 47 | DeactivatePipelineRequest, \ 48 | Pipeline, \ 49 | PipelineEdge, \ 50 | PipelineNode, \ 51 | PipelineMigrationInfo, \ 52 | DecompileRequest, \ 53 | DecompileResponse, \ 54 | ErrorResponse, \ 55 | UploadFileResponse, \ 56 | FilesMetaDataResponse, \ 57 | FunctionModel, \ 58 | GetInputSchemaRequest, \ 59 | GetOutputSchemaRequest, \ 60 | LookupTableResponse, \ 61 | NodeMetrics, \ 62 | MetricsResponse, \ 63 | PaginatedResponseOfConnectionResponse, \ 64 | PaginatedResponseOfConnectorResponse, \ 65 | PipelineJobStatus, \ 66 | PaginatedResponseOfPipelineJobStatus, \ 67 | PipelineResponse, \ 68 | PaginatedResponseOfPipelineResponse, \ 69 | TemplateResponse, \ 70 | PaginatedResponseOfTemplateResponse, \ 71 | PipelinePatchRequest, \ 72 | PipelineReactivateResponse, \ 73 | PipelineReactivateResponseAsync, \ 74 | PipelineReactivationStatus, \ 75 | PipelineRequest, \ 76 | PreviewNode, \ 77 | RuleMetrics, \ 78 | PreviewData, \ 79 | PreviewSessionStartRequest, \ 80 | PreviewStartResponse, \ 81 | PreviewState, \ 82 | ReactivatePipelineRequest, \ 83 | RegistryModel, \ 84 | Response, \ 85 | SplCompileRequest, \ 86 | TemplatePatchRequest, \ 87 | TemplatePutRequest, \ 88 | TemplateRequest, \ 89 | UpgradePipelineRequest, \ 90 | UplType, \ 91 | ValidateConnectionRequest, \ 92 | ValidateRequest, \ 93 | ValidateResponse 94 | -------------------------------------------------------------------------------- /splunk_sdk/streams/v3beta1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Data Stream Processing REST API 23 | 24 | Use the Streams service to perform create, read, update, and delete (CRUD) operations on your data pipeline. The Streams service also has metrics and preview session endpoints and gives you full control over your data pipeline. 25 | 26 | OpenAPI spec version: v3beta1.1 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.streams.v3beta1.gen_data_stream_processing_rest_api_api import DataStreamProcessingRESTAPI 35 | 36 | # import models into sdk package 37 | from splunk_sdk.streams.v3beta1.gen_models import ActivatePipelineRequest, \ 38 | ArgumentModel, \ 39 | ConnectionPatchRequest, \ 40 | ConnectionPutRequest, \ 41 | ConnectionRequest, \ 42 | Source, \ 43 | ConnectionVersionResponse, \ 44 | ConnectionResponse, \ 45 | ConnectionSaveResponse, \ 46 | ConnectorResponse, \ 47 | DeactivatePipelineRequest, \ 48 | Pipeline, \ 49 | PipelineEdge, \ 50 | PipelineNode, \ 51 | PipelineMigrationInfo, \ 52 | DecompileRequest, \ 53 | DecompileResponse, \ 54 | ErrorResponse, \ 55 | UploadFileResponse, \ 56 | FilesMetaDataResponse, \ 57 | FunctionModel, \ 58 | GetInputSchemaRequest, \ 59 | GetOutputSchemaRequest, \ 60 | LookupTableResponse, \ 61 | NodeMetrics, \ 62 | MetricsResponse, \ 63 | PaginatedResponseOfConnectionResponse, \ 64 | PaginatedResponseOfConnectorResponse, \ 65 | PipelineJobStatus, \ 66 | PaginatedResponseOfPipelineJobStatus, \ 67 | PipelineResponse, \ 68 | PaginatedResponseOfPipelineResponse, \ 69 | TemplateResponse, \ 70 | PaginatedResponseOfTemplateResponse, \ 71 | PipelinePatchRequest, \ 72 | PipelineReactivateResponse, \ 73 | PipelineReactivateResponseAsync, \ 74 | PipelineReactivationStatus, \ 75 | PipelineRequest, \ 76 | PreviewNode, \ 77 | RuleMetrics, \ 78 | PreviewData, \ 79 | PreviewSessionStartRequest, \ 80 | PreviewStartResponse, \ 81 | PreviewState, \ 82 | ReactivatePipelineRequest, \ 83 | RegistryModel, \ 84 | Response, \ 85 | SplCompileRequest, \ 86 | TemplatePatchRequest, \ 87 | TemplatePutRequest, \ 88 | TemplateRequest, \ 89 | UpgradePipelineRequest, \ 90 | UplType, \ 91 | ValidateConnectionRequest, \ 92 | ValidateRequest, \ 93 | ValidateResponse 94 | -------------------------------------------------------------------------------- /splunk_sdk/streams/v2beta1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Data Stream Processing REST API 23 | 24 | Use the Streams service to perform create, read, update, and delete (CRUD) operations on your data pipeline. The Streams service also has metrics and preview session endpoints and gives you full control over your data pipeline. 25 | 26 | OpenAPI spec version: v2beta1.4 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.streams.v2beta1.gen_data_stream_processing_rest_api_api import DataStreamProcessingRESTAPI 35 | 36 | # import models into sdk package 37 | from splunk_sdk.streams.v2beta1.gen_models import ActivatePipelineRequest, \ 38 | ConnectionPatchRequest, \ 39 | ConnectionPutRequest, \ 40 | ConnectionRequest, \ 41 | Source, \ 42 | ConnectionVersionResponse, \ 43 | ConnectionResponse, \ 44 | ConnectionSaveResponse, \ 45 | ConnectorResponse, \ 46 | DeactivatePipelineRequest, \ 47 | DslCompilationRequest, \ 48 | UplPipeline, \ 49 | UplEdge, \ 50 | UplNode, \ 51 | PipelineMigrationInfo, \ 52 | GetInputSchemaRequest, \ 53 | GetOutputSchemaRequest, \ 54 | GroupArgumentsNode, \ 55 | GroupExpandRequest, \ 56 | GroupFunctionArgsNode, \ 57 | GroupFunctionArgsMappingNode, \ 58 | GroupFunctionArguments, \ 59 | GroupFunctionMappings, \ 60 | GroupPatchRequest, \ 61 | GroupPutRequest, \ 62 | GroupRequest, \ 63 | GroupResponse, \ 64 | NodeMetrics, \ 65 | MetricsResponse, \ 66 | PaginatedResponseOfConnectionResponse, \ 67 | PaginatedResponseOfConnectorResponse, \ 68 | PipelineJobStatus, \ 69 | PaginatedResponseOfPipelineJobStatus, \ 70 | PipelineResponse, \ 71 | PaginatedResponseOfPipelineResponse, \ 72 | TemplateResponse, \ 73 | PaginatedResponseOfTemplateResponse, \ 74 | PipelineDeleteResponse, \ 75 | PipelinePatchRequest, \ 76 | PipelineReactivateResponse, \ 77 | PipelineRequest, \ 78 | PipelinesMergeRequest, \ 79 | PreviewNode, \ 80 | PreviewData, \ 81 | PreviewSessionStartRequest, \ 82 | PreviewStartResponse, \ 83 | PreviewState, \ 84 | ReactivatePipelineRequest, \ 85 | Response, \ 86 | SplCompileRequest, \ 87 | TemplatePatchRequest, \ 88 | TemplatePutRequest, \ 89 | TemplateRequest, \ 90 | UplArgument, \ 91 | UplCategory, \ 92 | UplFunction, \ 93 | UplType, \ 94 | UplRegistry, \ 95 | ValidateRequest, \ 96 | ValidateResponse 97 | -------------------------------------------------------------------------------- /scripts/publish_docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #################################################################################################### 4 | # Check for required env vars 5 | #################################################################################################### 6 | if [[ "${CI}" != "true" ]] ; then 7 | echo "Exiting: $0 can only be run from the CI system." 8 | exit 1 9 | fi 10 | if [[ -z "${ARTIFACT_USERNAME}" ]] ; then 11 | echo "ARTIFACT_USERNAME must be set, exiting ..." 12 | exit 1 13 | fi 14 | if [[ -z "${ARTIFACT_PASSWORD}" ]] ; then 15 | echo "ARTIFACT_PASSWORD must be set, exiting ..." 16 | exit 1 17 | fi 18 | if [[ -z "${ARTIFACTORY_NPM_REGISTRY}" ]] ; then 19 | echo "ARTIFACTORY_NPM_REGISTRY must be set, exiting ..." 20 | exit 1 21 | fi 22 | 23 | #################################################################################################### 24 | # Set platform-specific sed extended syntax flag 25 | #################################################################################################### 26 | if [[ "$(uname)" == "Darwin" ]] ; then 27 | # MacOS 28 | SED_FLG="-E" 29 | else 30 | # Linux 31 | SED_FLG="-r" 32 | fi 33 | 34 | # Go to project root splunk-cloud-sdk-python 35 | cd "$(dirname "$0")/.." 36 | 37 | #################################################################################################### 38 | # Get release version from splunk_sdk/__version__.py 39 | #################################################################################################### 40 | NEW_VERSION=$(cat splunk_sdk/__version__.py | sed ${SED_FLG} 's/__version__ = //g' | sed 's/"//g') 41 | if [[ -z "${NEW_VERSION}" ]] ; then 42 | echo "error setting NEW_VERSION from splunk_sdk/__version__.py, version must be set to match: __version__ = \"([0-9]+\.[0-9]+\.[0-9]+.*)\" (e.g. __version__ = \"1.0.0b5\") but format found is:\n\n$(cat splunk_sdk/__version__.py)\n\n..." 43 | exit 1 44 | fi 45 | 46 | echo "Publishing docs for v${NEW_VERSION} ..." 47 | 48 | # Run from project root 49 | cd "scripts/" 50 | ##################################################################################################### 51 | ## Write a package.json file, this is needed by @splunk/cicd-tools even though this isn't js 52 | ##################################################################################################### 53 | rm package.json 54 | PACKAGE_JSON="{ 55 | \"name\": \"@splunk/splunk-cloud-sdk-python\", 56 | \"version\": \"${NEW_VERSION}\", 57 | \"description\": \"Splunk Cloud SDK for Python\" 58 | }" 59 | echo ${PACKAGE_JSON} > package.json 60 | rm -rf build/ 61 | ##################################################################################################### 62 | ## Install @splunk/cicd-tools from artifactory 63 | ##################################################################################################### 64 | npm add --no-save @splunk/cicd-tools --registry "${ARTIFACTORY_NPM_REGISTRY}" 65 | ##################################################################################################### 66 | ## Publish docs to artifactory with @splunk/cicd-tools/cicd-publish-docs 67 | ##################################################################################################### 68 | npx cicd-publish-docs --force ../docs/ 69 | echo "Docs built and packaged into $(dirname "$0")/build" -------------------------------------------------------------------------------- /test/test_event_batcher.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | 12 | import csv 13 | import json 14 | import os 15 | import pytest 16 | import logging 17 | 18 | from splunk_sdk.ingest import IngestAPI, HTTPResponse 19 | from splunk_sdk.ingest.ingest_event_batcher import EventBatcher, \ 20 | DEFAULT_BATCH_SIZE, Event 21 | from test.fixtures import get_test_client as test_client # NOQA 22 | 23 | BATCH_COUNT = 50 24 | SOURCE = 'pythonsdk-tests' 25 | SOURCETYPE = 'json' 26 | 27 | logger = logging.getLogger(__name__) 28 | 29 | def _parse_csv(file): 30 | events = [] 31 | with open(file) as f: 32 | reader = csv.reader(f) 33 | headers = next(reader, None) 34 | for row in reader: 35 | # v needs to be tested for a float or string 36 | data = {} 37 | for k, v in zip(headers, row): 38 | try: 39 | v = float(v) 40 | except ValueError: 41 | pass 42 | data[k] = v 43 | payload = json.dumps(data) 44 | events.append(Event(body=payload, sourcetype=SOURCETYPE, 45 | source=SOURCE, attributes={'index': 'main'})) 46 | return events 47 | 48 | 49 | EVENTS = _parse_csv(os.path.join(os.path.abspath(os.path.dirname(__file__)), "data/ml/iris.csv")) 50 | 51 | 52 | def _response_handler(func, data): 53 | """This is an example callback function that allows for custom error 54 | handling 55 | 56 | :param func: The ingest.post_events method 57 | :param data: The batch of events to send 58 | :return: 59 | """ 60 | resp = func(data) 61 | if resp is not None: 62 | assert (isinstance(resp, HTTPResponse)) 63 | if resp.code != "SUCCESS": 64 | logger.error("Error encountered in %s" % data) 65 | pytest.xfail(resp.code) 66 | # throw new Exception so caller can stop or reset batcher 67 | raise Exception(resp.code) 68 | 69 | 70 | def _error_handler(e: Exception): 71 | logger.error(e) 72 | pytest.fail() 73 | # rethrow so caller can stop the batcher 74 | raise e 75 | 76 | 77 | @pytest.mark.usefixtures("test_client") # NOQA 78 | def test_post_events(test_client): 79 | ingest = IngestAPI(test_client) 80 | batcher = EventBatcher(ingest_service=ingest, 81 | batch_size=DEFAULT_BATCH_SIZE, 82 | batch_count=BATCH_COUNT, 83 | batch_dispatch_handler=_response_handler) 84 | assert (batcher is not None) 85 | 86 | for e in EVENTS: 87 | try: 88 | assert(len(batcher.queue) <= BATCH_COUNT) 89 | batcher.add(e) 90 | except Exception: 91 | batcher.stop() 92 | 93 | # kill the timer 94 | batcher.stop() 95 | 96 | assert (len(batcher.queue) == 0) 97 | -------------------------------------------------------------------------------- /test/test_search_retry.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | import pytest 12 | from concurrent.futures import ThreadPoolExecutor as PoolExecutor 13 | from splunk_sdk.base_client import HTTPError 14 | from test.fixtures import get_test_client as test_client # NOQA 15 | from test.fixtures import get_test_client_default_retry as test_client_default_retry # NOQA 16 | from test.fixtures import get_test_client_custom_retry as test_client_custom_retry # NOQA 17 | from test.fixtures import get_test_client_retry_false as test_client_retry_false # NOQA 18 | 19 | 20 | from splunk_sdk.search import SplunkSearchService as Search 21 | from splunk_sdk.search import SearchJob 22 | 23 | import itertools 24 | 25 | # Use pre-baked events so that number of events and format are fixed 26 | STANDARD_QUERY = ''' 27 | from [ 28 | {"name": "event1"}, 29 | {"name": "event2"}, 30 | {"name": "event3"}, 31 | {"name": "event4"}, 32 | {"name": "event5"} 33 | ] 34 | ''' 35 | def execute_search_job(expect_error, search_job, search_client): 36 | # TODO: For now forcing expect_error to be true, we need to stop 37 | # test retry handling without overloading our tenant with searches, 38 | # this is causing our non-429 tests to return with 429 39 | expect_error = True 40 | try: 41 | job = search_client.create_job(search_job=search_job) 42 | print("NAME") 43 | print(job.name) 44 | assert(job is not None) 45 | except HTTPError as error: 46 | got_error = True 47 | if expect_error is True: 48 | assert(error.code == "too_many_requests") 49 | assert (error.http_status_code == 429) 50 | else: 51 | assert(got_error == expect_error) 52 | 53 | 54 | @pytest.mark.usefixtures("test_client_default_retry") # NOQA 55 | def test_create_job_default_retry(test_client_default_retry): 56 | search_client = Search(test_client_default_retry) 57 | search_job = SearchJob(query=STANDARD_QUERY) 58 | with PoolExecutor(max_workers=10) as executor: 59 | for _ in executor.map(execute_search_job, itertools.repeat(False), itertools.repeat(search_job, 29), itertools.repeat(search_client)): 60 | pass 61 | 62 | @pytest.mark.usefixtures("test_client_custom_retry") # NOQA 63 | def test_create_job_custom_retry(test_client_custom_retry): 64 | search_client = Search(test_client_custom_retry) 65 | search_job = SearchJob(query=STANDARD_QUERY) 66 | with PoolExecutor(max_workers=10) as executor: 67 | for _ in executor.map(execute_search_job, itertools.repeat(False), itertools.repeat(search_job, 27), itertools.repeat(search_client)): 68 | pass 69 | 70 | @pytest.mark.usefixtures("test_client") # NOQA 71 | def test_create_job_no_retry_expect_429(test_client): 72 | search_client = Search(test_client) 73 | search_job = SearchJob(query=STANDARD_QUERY) 74 | with PoolExecutor(max_workers=10) as executor: 75 | for _ in executor.map(execute_search_job, itertools.repeat(True), itertools.repeat(search_job, 28), itertools.repeat(search_client)): 76 | pass 77 | 78 | @pytest.mark.usefixtures("test_client_retry_false") # NOQA 79 | def test_create_job_retry_enabled_false(test_client_retry_false): 80 | search_client = Search(test_client_retry_false) 81 | search_job = SearchJob(query=STANDARD_QUERY) 82 | with PoolExecutor(max_workers=10) as executor: 83 | for _ in executor.map(execute_search_job, itertools.repeat(True), itertools.repeat(search_job, 28), itertools.repeat(search_client)): 84 | pass 85 | -------------------------------------------------------------------------------- /splunk_sdk/catalog/v2alpha2/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Metadata Catalog 23 | 24 | With the Metadata Catalog you can create and manage knowledge objects such as datasets, fields, rules, actions, dashboards, and workflows. 25 | 26 | OpenAPI spec version: v2alpha2.6 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.catalog.v2alpha2.gen_metadata_catalog_api import MetadataCatalog 35 | 36 | # import models into sdk package 37 | from splunk_sdk.catalog.v2alpha2.gen_models import Action, \ 38 | ActionPATCH, \ 39 | ActionPOST, \ 40 | AliasActionFromAction, \ 41 | AliasActionFromActionPOST, \ 42 | AliasActionKind, \ 43 | AliasActionPATCH, \ 44 | AliasActionPOST, \ 45 | Annotation, \ 46 | AnnotationPOST, \ 47 | AutoKVActionFromAction, \ 48 | AutoKVActionFromActionPOST, \ 49 | AutoKVActionKind, \ 50 | AutoKVActionPATCH, \ 51 | AutoKVActionPOST, \ 52 | Dashboard, \ 53 | DashboardPATCH, \ 54 | DashboardPOST, \ 55 | Dataset, \ 56 | DatasetImportedBy, \ 57 | DatasetPATCH, \ 58 | FieldPOST, \ 59 | FieldDataType, \ 60 | FieldType, \ 61 | FieldPrevalence, \ 62 | DatasetPOST, \ 63 | EvalActionFromAction, \ 64 | EvalActionFromActionPOST, \ 65 | EvalActionKind, \ 66 | EvalActionPATCH, \ 67 | EvalActionPOST, \ 68 | Field, \ 69 | FieldPATCH, \ 70 | ImportDataset, \ 71 | ImportDatasetPOST, \ 72 | ImportDatasetKind, \ 73 | ImportDatasetByIdPOST, \ 74 | ImportDatasetByNamePOST, \ 75 | ImportDatasetPATCH, \ 76 | IndexDataset, \ 77 | IndexDatasetKind, \ 78 | IndexDatasetPATCH, \ 79 | IndexDatasetPOST, \ 80 | JobDatasetPropertiesTimelineMetadata, \ 81 | JobDatasetPropertiesTimelineMetadataAuto, \ 82 | JobDatasetEventSummaryAvailableStatus, \ 83 | JobDatasetFieldSummaryAvailableStatus, \ 84 | JobDatasetTimeBucketsAvailableStatus, \ 85 | JobDataset, \ 86 | JobDatasetKind, \ 87 | KVCollectionDataset, \ 88 | KVCollectionDatasetKind, \ 89 | KVCollectionDatasetPATCH, \ 90 | KVCollectionDatasetPOST, \ 91 | LookupActionFromAction, \ 92 | LookupActionFromActionPOST, \ 93 | LookupActionKind, \ 94 | LookupActionPATCH, \ 95 | LookupActionPOST, \ 96 | LookupDatasetExternalKind, \ 97 | LookupDataset, \ 98 | LookupDatasetKind, \ 99 | LookupDatasetPATCH, \ 100 | LookupDatasetPOST, \ 101 | MetricDataset, \ 102 | MetricDatasetKind, \ 103 | MetricDatasetPATCH, \ 104 | MetricDatasetPOST, \ 105 | Module, \ 106 | RegexActionFromAction, \ 107 | RegexActionFromActionPOST, \ 108 | RegexActionKind, \ 109 | RegexActionPATCH, \ 110 | RegexActionPOST, \ 111 | RelationshipField, \ 112 | RelationshipFieldKind, \ 113 | RelationshipKind, \ 114 | Relationship, \ 115 | RelationshipFieldPOST, \ 116 | RelationshipPATCH, \ 117 | RelationshipPOST, \ 118 | Rule, \ 119 | RulePATCH, \ 120 | RulePOST, \ 121 | Task, \ 122 | TaskPOST, \ 123 | ViewDataset, \ 124 | ViewDatasetKind, \ 125 | ViewDatasetPATCH, \ 126 | ViewDatasetPOST, \ 127 | Workflow, \ 128 | WorkflowBuild, \ 129 | WorkflowBuildPATCH, \ 130 | WorkflowBuildPOST, \ 131 | WorkflowPATCH, \ 132 | WorkflowPOST, \ 133 | WorkflowRun, \ 134 | WorkflowRunPATCH, \ 135 | WorkflowRunPOST 136 | -------------------------------------------------------------------------------- /splunk_sdk/catalog/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Search Catalog service 23 | 24 | With the Metadata Catalog in Splunk Cloud Services you can create and manage knowledge objects such as datasets, fields, rules, actions, and dashboards. 25 | 26 | OpenAPI spec version: v2beta1.4 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.catalog.v2beta1.gen_metadata_catalog_api import MetadataCatalog 35 | 36 | # import models into sdk package 37 | from splunk_sdk.catalog.v2beta1.gen_models import Action, \ 38 | ActionPATCH, \ 39 | ActionPOST, \ 40 | AliasAction, \ 41 | AliasActionKind, \ 42 | AliasActionPATCH, \ 43 | AliasActionPOST, \ 44 | Annotation, \ 45 | AnnotationPOST, \ 46 | AutoKVAction, \ 47 | AutoKVActionKind, \ 48 | AutoKVActionPATCH, \ 49 | AutoKVActionPOST, \ 50 | DatasetGet, \ 51 | CatalogDataset, \ 52 | CatalogDatasetKind, \ 53 | Dashboard, \ 54 | DashboardPATCH, \ 55 | DashboardPOST, \ 56 | Dataset, \ 57 | DatasetImportedBy, \ 58 | DatasetPATCH, \ 59 | FieldPOST, \ 60 | FieldDataType, \ 61 | FieldType, \ 62 | FieldPrevalence, \ 63 | DatasetPOST, \ 64 | EvalAction, \ 65 | EvalActionKind, \ 66 | EvalActionPATCH, \ 67 | EvalActionPOST, \ 68 | FederatedDatasetFromDataset, \ 69 | FederatedDatasetFromDatasetGet, \ 70 | FederatedDatasetKind, \ 71 | FederatedDatasetPATCH, \ 72 | FederatedDatasetPOST, \ 73 | Field, \ 74 | FieldPATCH, \ 75 | ImportDatasetPOST, \ 76 | ImportDatasetKind, \ 77 | ImportDatasetByIdPOST, \ 78 | ImportDatasetByNamePOST, \ 79 | ImportDatasetFromDataset, \ 80 | ImportDatasetFromDatasetGet, \ 81 | ImportDatasetPATCH, \ 82 | IndexDatasetFromDataset, \ 83 | IndexDatasetFromDatasetGet, \ 84 | IndexDatasetKind, \ 85 | IndexDatasetPATCH, \ 86 | IndexDatasetPOST, \ 87 | JobDatasetEventSummaryAvailableStatus, \ 88 | JobDatasetFieldSummaryAvailableStatus, \ 89 | JobDatasetPropertiesTimelineMetadata, \ 90 | JobDatasetPropertiesTimelineMetadataAuto, \ 91 | JobDatasetTimeBucketsAvailableStatus, \ 92 | JobDatasetGET, \ 93 | JobDatasetKind, \ 94 | KVCollectionDatasetFromDataset, \ 95 | KVCollectionDatasetFromDatasetGet, \ 96 | KVCollectionDatasetKind, \ 97 | KVCollectionDatasetPATCH, \ 98 | KVCollectionDatasetPOST, \ 99 | LookupAction, \ 100 | LookupActionKind, \ 101 | LookupActionPATCH, \ 102 | LookupActionPOST, \ 103 | LookupDatasetExternalKind, \ 104 | LookupDatasetFromDataset, \ 105 | LookupDatasetFromDatasetGet, \ 106 | LookupDatasetKind, \ 107 | LookupDatasetPATCH, \ 108 | LookupDatasetPOST, \ 109 | MetricDatasetFromDataset, \ 110 | MetricDatasetFromDatasetGet, \ 111 | MetricDatasetKind, \ 112 | MetricDatasetPATCH, \ 113 | MetricDatasetPOST, \ 114 | Module, \ 115 | RegexAction, \ 116 | RegexActionKind, \ 117 | RegexActionPATCH, \ 118 | RegexActionPOST, \ 119 | RelationshipField, \ 120 | RelationshipFieldKind, \ 121 | RelationshipKind, \ 122 | Relationship, \ 123 | RelationshipFieldPOST, \ 124 | RelationshipPATCH, \ 125 | RelationshipPOST, \ 126 | Rule, \ 127 | RulePATCH, \ 128 | RulePOST, \ 129 | Splv1sinkDataset, \ 130 | Splv1sinkDatasetKind, \ 131 | ViewDatasetFromDataset, \ 132 | ViewDatasetFromDatasetGet, \ 133 | ViewDatasetKind, \ 134 | ViewDatasetPATCH, \ 135 | ViewDatasetPOST 136 | -------------------------------------------------------------------------------- /splunk_sdk/catalog/v2beta1/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # flake8: noqa 4 | 5 | # Copyright © 2022 Splunk, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 8 | # not use this file except in compliance with the License. You may obtain 9 | # a copy of the License at 10 | # 11 | # [http://www.apache.org/licenses/LICENSE-2.0] 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 15 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 16 | # License for the specific language governing permissions and limitations 17 | # under the License. 18 | 19 | ############# This file is auto-generated. Do not edit! ############# 20 | 21 | """ 22 | SDC Service: Search Catalog service 23 | 24 | With the Metadata Catalog in Splunk Cloud Services you can create and manage knowledge objects such as datasets, fields, rules, actions, and dashboards. 25 | 26 | OpenAPI spec version: v2beta1.4 (recommended default) 27 | Generated by: https://openapi-generator.tech 28 | """ 29 | 30 | 31 | __version__ = "1.0.0" 32 | 33 | # import apis into sdk package 34 | from splunk_sdk.catalog.v2beta1.gen_metadata_catalog_api import MetadataCatalog 35 | 36 | # import models into sdk package 37 | from splunk_sdk.catalog.v2beta1.gen_models import Action, \ 38 | ActionPATCH, \ 39 | ActionPOST, \ 40 | AliasAction, \ 41 | AliasActionKind, \ 42 | AliasActionPATCH, \ 43 | AliasActionPOST, \ 44 | Annotation, \ 45 | AnnotationPOST, \ 46 | AutoKVAction, \ 47 | AutoKVActionKind, \ 48 | AutoKVActionPATCH, \ 49 | AutoKVActionPOST, \ 50 | DatasetGet, \ 51 | CatalogDataset, \ 52 | CatalogDatasetKind, \ 53 | Dashboard, \ 54 | DashboardPATCH, \ 55 | DashboardPOST, \ 56 | Dataset, \ 57 | DatasetImportedBy, \ 58 | DatasetPATCH, \ 59 | FieldPOST, \ 60 | FieldDataType, \ 61 | FieldType, \ 62 | FieldPrevalence, \ 63 | DatasetPOST, \ 64 | EvalAction, \ 65 | EvalActionKind, \ 66 | EvalActionPATCH, \ 67 | EvalActionPOST, \ 68 | FederatedDatasetFromDataset, \ 69 | FederatedDatasetFromDatasetGet, \ 70 | FederatedDatasetKind, \ 71 | FederatedDatasetPATCH, \ 72 | FederatedDatasetPOST, \ 73 | Field, \ 74 | FieldPATCH, \ 75 | ImportDatasetPOST, \ 76 | ImportDatasetKind, \ 77 | ImportDatasetByIdPOST, \ 78 | ImportDatasetByNamePOST, \ 79 | ImportDatasetFromDataset, \ 80 | ImportDatasetFromDatasetGet, \ 81 | ImportDatasetPATCH, \ 82 | IndexDatasetFromDataset, \ 83 | IndexDatasetFromDatasetGet, \ 84 | IndexDatasetKind, \ 85 | IndexDatasetPATCH, \ 86 | IndexDatasetPOST, \ 87 | JobDatasetEventSummaryAvailableStatus, \ 88 | JobDatasetFieldSummaryAvailableStatus, \ 89 | JobDatasetPropertiesTimelineMetadata, \ 90 | JobDatasetPropertiesTimelineMetadataAuto, \ 91 | JobDatasetTimeBucketsAvailableStatus, \ 92 | JobDatasetGET, \ 93 | JobDatasetKind, \ 94 | KVCollectionDatasetFromDataset, \ 95 | KVCollectionDatasetFromDatasetGet, \ 96 | KVCollectionDatasetKind, \ 97 | KVCollectionDatasetPATCH, \ 98 | KVCollectionDatasetPOST, \ 99 | LookupAction, \ 100 | LookupActionKind, \ 101 | LookupActionPATCH, \ 102 | LookupActionPOST, \ 103 | LookupDatasetExternalKind, \ 104 | LookupDatasetFromDataset, \ 105 | LookupDatasetFromDatasetGet, \ 106 | LookupDatasetKind, \ 107 | LookupDatasetPATCH, \ 108 | LookupDatasetPOST, \ 109 | MetricDatasetFromDataset, \ 110 | MetricDatasetFromDatasetGet, \ 111 | MetricDatasetKind, \ 112 | MetricDatasetPATCH, \ 113 | MetricDatasetPOST, \ 114 | Module, \ 115 | RegexAction, \ 116 | RegexActionKind, \ 117 | RegexActionPATCH, \ 118 | RegexActionPOST, \ 119 | RelationshipField, \ 120 | RelationshipFieldKind, \ 121 | RelationshipKind, \ 122 | Relationship, \ 123 | RelationshipFieldPOST, \ 124 | RelationshipPATCH, \ 125 | RelationshipPOST, \ 126 | Rule, \ 127 | RulePATCH, \ 128 | RulePOST, \ 129 | Splv1sinkDataset, \ 130 | Splv1sinkDatasetKind, \ 131 | ViewDatasetFromDataset, \ 132 | ViewDatasetFromDatasetGet, \ 133 | ViewDatasetKind, \ 134 | ViewDatasetPATCH, \ 135 | ViewDatasetPOST 136 | -------------------------------------------------------------------------------- /splunk_sdk/forwarders/v2beta1/gen_splunk_forwarder_service_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # Copyright © 2022 Splunk, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 6 | # not use this file except in compliance with the License. You may obtain 7 | # a copy of the License at 8 | # 9 | # [http://www.apache.org/licenses/LICENSE-2.0] 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations 15 | # under the License. 16 | 17 | ############# This file is auto-generated. Do not edit! ############# 18 | 19 | """ 20 | SDC Service: Splunk Forwarder Service 21 | 22 | Send data from a Splunk forwarder to the Splunk Forwarder service in Splunk Cloud Services. 23 | 24 | OpenAPI spec version: v2beta1.4 (recommended default) 25 | Generated by: https://openapi-generator.tech 26 | """ 27 | 28 | 29 | from requests import Response 30 | from string import Template 31 | from typing import List, Dict 32 | 33 | from splunk_sdk.base_client import handle_response 34 | from splunk_sdk.base_service import BaseService 35 | from splunk_sdk.common.sscmodel import SSCModel, SSCVoidModel 36 | 37 | from splunk_sdk.forwarders.v2beta1.gen_models import Certificate 38 | from splunk_sdk.forwarders.v2beta1.gen_models import CertificateInfo 39 | from splunk_sdk.forwarders.v2beta1.gen_models import Error 40 | 41 | 42 | class SplunkForwarderService(BaseService): 43 | """ 44 | Splunk Forwarder Service 45 | Version: v2beta1.4 46 | Send data from a Splunk forwarder to the Splunk Forwarder service in Splunk Cloud Services. 47 | """ 48 | 49 | def __init__(self, base_client): 50 | super().__init__(base_client) 51 | 52 | def add_certificate(self, certificate: Certificate = None, query_params: Dict[str, object] = None) -> CertificateInfo: 53 | """ 54 | Adds a certificate to a vacant slot on a tenant. 55 | """ 56 | if query_params is None: 57 | query_params = {} 58 | 59 | path_params = { 60 | } 61 | 62 | path = Template("/forwarders/v2beta1/certificates").substitute(path_params) 63 | url = self.base_client.build_url(path) 64 | data = certificate.to_dict() 65 | response = self.base_client.post(url, json=data, params=query_params) 66 | return handle_response(response, CertificateInfo) 67 | 68 | def delete_certificate(self, slot: str, query_params: Dict[str, object] = None) -> SSCVoidModel: 69 | """ 70 | Removes a certificate on a particular slot on a tenant. 71 | """ 72 | if query_params is None: 73 | query_params = {} 74 | 75 | path_params = { 76 | "slot": slot, 77 | } 78 | 79 | path = Template("/forwarders/v2beta1/certificates/${slot}").substitute(path_params) 80 | url = self.base_client.build_url(path) 81 | response = self.base_client.delete(url, params=query_params) 82 | return handle_response(response, ) 83 | 84 | def delete_certificates(self, query_params: Dict[str, object] = None) -> SSCVoidModel: 85 | """ 86 | Removes all certificates on a tenant. 87 | """ 88 | if query_params is None: 89 | query_params = {} 90 | 91 | path_params = { 92 | } 93 | 94 | path = Template("/forwarders/v2beta1/certificates").substitute(path_params) 95 | url = self.base_client.build_url(path) 96 | response = self.base_client.delete(url, params=query_params) 97 | return handle_response(response, ) 98 | 99 | def list_certificates(self, query_params: Dict[str, object] = None) -> List[CertificateInfo]: 100 | """ 101 | Returns a list of all certificates for a tenant. 102 | """ 103 | if query_params is None: 104 | query_params = {} 105 | 106 | path_params = { 107 | } 108 | 109 | path = Template("/forwarders/v2beta1/certificates").substitute(path_params) 110 | url = self.base_client.build_url(path) 111 | response = self.base_client.get(url, params=query_params) 112 | return handle_response(response, CertificateInfo) 113 | 114 | 115 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Splunk Cloud Services SDK for Python 2 | 3 | The Splunk Cloud Services software development kit (SDK) for Python contains library code and examples to enable you to build apps using the Splunk Cloud Services services with the Python 3 programming language. 4 | 5 | ## Terms of Service (TOS) 6 | 7 | Log in to [Splunk Investigate](https://si.scp.splunk.com/) and accept the Terms of Service when prompted. 8 | 9 | ## Install the Splunk Cloud Services SDK for Python 10 | 11 | To install the Splunk Cloud Services SDK for Python and its dependencies, run the following pip command: 12 | 13 | ``` 14 | pip install splunk-cloud-sdk 15 | ``` 16 | 17 | For more about installing the pip package installer, see the [PyPA](https://pypi.org/project/pip/) website. 18 | 19 | 20 | ## Get started 21 | 22 | The `SplunkCloud` class is the main entry point to the Splunk Cloud Services SDK for Python. 23 | Instantiate this class for an index of all the Splunk Cloud Services services. Each service name is a property on the 24 | client object. 25 | 26 | ```python 27 | from splunk_sdk import Context 28 | from splunk_sdk.auth import PKCEAuthManager 29 | from splunk_sdk.splunk_cloud import SplunkCloud 30 | 31 | # Create a test context--you might want to pass more to the context 32 | context = Context(host="your_scp_host", tenant="your_tenant") 33 | 34 | # Initialize the auth manager 35 | auth_manager = PKCEAuthManager(host="your_auth_host", 36 | client_id="your_client_id", 37 | username="your_username", 38 | password="your_password", 39 | redirect_uri="your_app_redirect_uri") 40 | 41 | scloud = SplunkCloud(context, auth_manager) 42 | for s in scloud.catalog.list_datasets(): 43 | print(s.name) 44 | ``` 45 | 46 | If you want only a small subset of functionality, you can instantiate services individually 47 | and avoid loading code for services you don't need: 48 | 49 | ```python 50 | from splunk_sdk.base_client import BaseClient, Context 51 | from splunk_sdk.identity import Identity 52 | from splunk_sdk.auth import ClientAuthManager 53 | 54 | auth_manager = ClientAuthManager(host="your_auth_host", client_id="your_client_id", client_secret="your_client_secret") 55 | base_client = BaseClient(context=Context(tenant="your_tenant"), auth_manager=auth_manager) 56 | identity = Identity(base_client) 57 | identity.validate_token() 58 | ``` 59 | 60 | ## Conventions 61 | 62 | Most of the service methods for the Splunk Cloud Services SDK for Python are generated directly from the Splunk Cloud Services service specifications. 63 | As a result, the functionality should match exactly between code written using the SDK and code that calls the services 64 | directly. The goal of this SDK is to make your code match with Python idioms and conventions, 65 | including using parameters that match Python casing guidelines. For example, when a service specifies an argument as `lastUpdate`, 66 | that field is known as a more Pythonesque `last_update` when used in the Splunk Cloud Services SDK for Python. 67 | 68 | The Splunk Cloud Services SDK for Python also manages setting up requests, handling authentication, and serializing and deserializing models for requests. If an error occurs in the service, the SDK raises an exception that has properties for why the error 69 | occurred. Every response from a service call results in some subclass of `SSCModel`. Calls that don't return a body 70 | return `SSCVoidModel`, which has a `response` property with access to the raw HTTP response. 71 | 72 | ## Versions 73 | 74 | Some services will support multiple API versions and designate which one is recommended for most users. 75 | The SDK will default to the recommend version via module remapping and the integration tests will also use this. 76 | In order to choose the non-recommended version of a service you will need to explicitly import that version like this: 77 | ```python 78 | from splunk_sdk.action.v1beta2 import * 79 | ``` 80 | 81 | ## Documentation 82 | For general documentation, see the [Splunk Developer Portal](https://dev.splunk.com/scs/). 83 | 84 | For reference documentation, see the [Splunk Cloud Services SDK for Python API Reference](https://dev.splunk.com/scs/reference/sdk/splunk-cloud-sdk-python/). 85 | 86 | ## Contributing 87 | 88 | Do not directly edit any source file with the prefix `gen_` because it was generated from service specifications. 89 | 90 | ## Contact 91 | If you have questions, reach out to us on [Slack](https://splunkdevplatform.slack.com) in the **#sdc** channel or email us at _devinfo@splunk.com_. 92 | -------------------------------------------------------------------------------- /scripts/prerelease.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | #################################################################################################### 4 | # Check for required env vars 5 | #################################################################################################### 6 | if [[ "${CI}" != "true" ]] ; then 7 | echo "Exiting: $0 can only be run from the CI system." 8 | exit 1 9 | fi 10 | if [[ -z "${GITLAB_HOST}" ]] ; then 11 | echo "GITLAB_HOST must be set, exiting ..." 12 | exit 1 13 | fi 14 | if [[ -z "${GITLAB_TOKEN}" ]] ; then 15 | echo "GITLAB_TOKEN must be set, exiting ..." 16 | exit 1 17 | fi 18 | 19 | #################################################################################################### 20 | # Set platform-specific sed extended syntax flag 21 | #################################################################################################### 22 | if [[ "$(uname)" == "Darwin" ]] ; then 23 | # MacOS 24 | SED_FLG="-E" 25 | else 26 | # Linux 27 | SED_FLG="-r" 28 | fi 29 | 30 | #################################################################################################### 31 | # Convert the release tag (e.g. v1.0.0) -> NEW_RELEASE (e.g. 1.0.0) 32 | #################################################################################################### 33 | NEW_VERSION=$(echo "${CI_COMMIT_REF_NAME}" | sed "${SED_FLG}" -n 's/^v([0-9]+\.[0-9]+\.[0-9]+)$/\1/p') 34 | if [[ -z "${NEW_VERSION}" ]] ; then 35 | echo "error setting NEW_VERSION, the release tag must match this pattern: \"^v([0-9]+\.[0-9]+\.[0-9]+)$\" (e.g. v1.0.0) but tag is: ${CI_COMMIT_REF_NAME} ..." 36 | exit 1 37 | fi 38 | 39 | ################################################################################################################ 40 | # Checkout latest version of Gitlab code to prepare for release (Checkout develop and create new release branch) 41 | ################################################################################################################ 42 | OWNER=devplat-pr-32 43 | PROJECT=splunk-cloud-sdk-python 44 | BRANCH_NAME=develop 45 | RELEASE_BRANCH_NAME=release/v${NEW_VERSION} 46 | set +x 47 | git remote set-url origin "https://oauth2:${GITLAB_TOKEN}@${GITLAB_HOST}/${OWNER}/${PROJECT}.git" 48 | set -x 49 | git config user.email "srv-dev-platform@splunk.com" 50 | git config user.name "srv-dev-platform" 51 | echo "Running \"git checkout ${BRANCH_NAME}\" ..." 52 | git checkout "${BRANCH_NAME}" 53 | echo "Running \"git fetch --all && git pull --all\" ..." 54 | git fetch --all && git pull --all 55 | echo "Running \"git checkout -b ${RELEASE_BRANCH_NAME}\" ..." 56 | git checkout -b ${RELEASE_BRANCH_NAME} 57 | echo "Showing changes with 'git status' ..." 58 | git status 59 | 60 | #################################################################################################### 61 | # Update splunk_sdk/__version__.py using the pre-release tag e.g. 1.0.0 for v1.0.0 62 | #################################################################################################### 63 | echo "Updating Version in splunk_sdk/__version__.py using sed \"${SED_FLG}\" -i '' -e \"s/\\"[0-9]+\.[0-9]+\.[0-9]+\\"/\\"${NEW_VERSION}\\"/g\" splunk_sdk/__version__.py ..." 64 | sed "${SED_FLG}" -i -e "s/\"[0-9]+\.[0-9]+\.[0-9]+\"/\"${NEW_VERSION}\"/g" splunk_sdk/__version__.py 65 | git add splunk_sdk/__version__.py 66 | 67 | #################################################################################################### 68 | # Append the message from the pre-release tag to the top of the CHANGELOG.md under ## Version x.y.z 69 | #################################################################################################### 70 | echo "Adding tag message to changelog ..." 71 | set +x 72 | TAG_MESSAGE=$(git cat-file -p "${CI_COMMIT_REF_NAME}" | tail -n +6) 73 | set -x 74 | printf "Adding release notes to top of CHANGELOG.md:\n\n${TAG_MESSAGE}\n\n" 75 | set +x 76 | CL_HEADER=$(head -n 1 CHANGELOG.md) 77 | CL_CONTENTS=$(tail -n +2 CHANGELOG.md) 78 | rm CHANGELOG.md 79 | printf "${CL_HEADER}\n\n## Version ${NEW_VERSION}\n${TAG_MESSAGE}\n${CL_CONTENTS}" > CHANGELOG.md 80 | set -x 81 | git add CHANGELOG.md 82 | 83 | #################################################################################################### 84 | # Adding/pushing changed files to release branch (__version__.py and CHANGELOG.md) 85 | #################################################################################################### 86 | echo "Showing changes with \"git status\" ..." 87 | git status 88 | echo "Creating commit for __version__.py and CHANGELOG.md ..." 89 | git commit -m "Prepare v${NEW_VERSION} for release" 90 | echo "Pushing branch ${RELEASE_BRANCH_NAME} ..." 91 | git push --set-upstream origin "${RELEASE_BRANCH_NAME}" 92 | -------------------------------------------------------------------------------- /test/test_catalog.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | import random 12 | import pytest 13 | import time 14 | 15 | from splunk_sdk.base_client import BaseClient 16 | from splunk_sdk.catalog import MetadataCatalog 17 | from splunk_sdk.catalog import IndexDatasetPOST, IndexDatasetKind, \ 18 | ImportDatasetPOST, ImportDatasetByIdPOST, RulePOST, LookupDatasetPOST, \ 19 | LookupDatasetExternalKind, FieldPOST, FieldPrevalence, FieldType, \ 20 | FieldDataType, FieldPATCH 21 | from test.fixtures import get_test_client as test_client # NOQA 22 | 23 | 24 | def _randint() -> int: 25 | return random.randint(0, 100000000) 26 | 27 | 28 | def _create_ds_name(name: str) -> str: 29 | return "pyintegds{}_{}".format(name, _randint()) 30 | 31 | 32 | @pytest.mark.usefixtures("test_client") # NOQA 33 | def test_create_delete_index_and_import(test_client: BaseClient): 34 | catalog = MetadataCatalog(test_client) 35 | name = _create_ds_name("py_cr_idx") 36 | idx = catalog.create_dataset(IndexDatasetPOST(name=name, disabled=False)) 37 | assert (name == idx.name) 38 | 39 | import_name = _create_ds_name("py_cr_imp") 40 | time.sleep(2) 41 | imp = catalog.create_dataset(ImportDatasetByIdPOST(name=import_name, source_id=idx.id)) 42 | assert (imp.name == import_name) 43 | catalog.delete_dataset(import_name) 44 | catalog.delete_dataset(name) 45 | 46 | 47 | @pytest.mark.usefixtures("test_client") # NOQA 48 | def test_retrieve_datasets(test_client: BaseClient): 49 | catalog = MetadataCatalog(test_client) 50 | datasets = catalog.list_datasets() 51 | assert (len(datasets) > 0) 52 | 53 | 54 | @pytest.mark.usefixtures("test_client") # NOQA 55 | def test_retreive_datasets_with_filter(test_client: BaseClient): 56 | catalog = MetadataCatalog(test_client) 57 | datasets = catalog.list_datasets(filter='version==2') 58 | assert (len(datasets) > 0) 59 | 60 | @pytest.mark.usefixtures("test_client") # NOQA 61 | def test_create_list_delete_rule(test_client: BaseClient): 62 | catalog = MetadataCatalog(test_client) 63 | rule_name = _create_ds_name("py_cr_rule") 64 | rule = catalog.create_rule(RulePOST(name=rule_name, match="sourcetype::integration_test_match")) 65 | assert (rule.name == rule_name) 66 | rules = catalog.list_rules() 67 | assert (len(rules) >= 1) 68 | rules = catalog.list_rules(filter='name=="' + rule_name + '"') 69 | assert (len(rules) == 1) 70 | catalog.delete_rule(rule_name) 71 | rules = catalog.list_rules(filter='name=="' + rule_name + '"') 72 | assert (len(rules) == 0) 73 | 74 | 75 | @pytest.mark.usefixtures("test_client") # NOQA 76 | def test_dataset_fields(test_client: BaseClient): 77 | catalog = MetadataCatalog(test_client) 78 | int_test_field_1 = "integ_test_field1" 79 | int_test_field_2 = "integ_test_field2" 80 | lookup_name = _create_ds_name("py_cr_lookup") 81 | lookup = catalog.create_dataset( 82 | LookupDatasetPOST(name=lookup_name, external_kind=LookupDatasetExternalKind.KVCOLLECTION, 83 | external_name="test_external_name")) 84 | time.sleep(1) 85 | field1 = catalog.create_field_for_dataset_by_id(lookup.id, 86 | FieldPOST(name=int_test_field_1, datatype=FieldDataType.STRING, 87 | fieldtype=FieldType.DIMENSION, 88 | prevalence=FieldPrevalence.ALL)) 89 | time.sleep(1) 90 | ret_field1 = catalog.get_field_by_id_for_dataset_by_id(datasetid=lookup.id, fieldid=field1.id) 91 | assert(field1.name == ret_field1.name) 92 | fields = catalog.list_fields_for_dataset_by_id(lookup.id) 93 | assert(len(fields) == 1) 94 | catalog.update_field_by_id_for_dataset_by_id(lookup.id, field1.id, FieldPATCH(name=int_test_field_2)) 95 | time.sleep(1) 96 | ret_field1 = catalog.get_field_by_id_for_dataset_by_id(datasetid=lookup.id, fieldid=field1.id) 97 | assert(ret_field1.name == int_test_field_2) 98 | catalog.delete_field_by_id_for_dataset_by_id(lookup.id, field1.id) 99 | catalog.delete_dataset_by_id(lookup.id) 100 | -------------------------------------------------------------------------------- /test/test_appregistry.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | import pytest 12 | 13 | from time import time 14 | 15 | from splunk_sdk.app_registry import CreateAppRequest, UpdateAppRequest, AppRegistry, AppName, NativeAppPOST, ServiceAppPOST 16 | from splunk_sdk.base_client import BaseClient 17 | from test.fixtures import get_test_client as test_client # NOQA 18 | 19 | 20 | @pytest.mark.usefixtures("test_client") # NOQA 21 | def test_crud_app(test_client: BaseClient): 22 | app_name = None 23 | appregistry = AppRegistry(test_client) 24 | try: 25 | # test_client.context.debug = True 26 | secs = str(round(time())) 27 | app_name = "p.c" + secs 28 | app_title = "psdk-" + app_name + "-" + secs 29 | redirect_urls = ["https://localhost"] 30 | 31 | app = appregistry.create_app(NativeAppPOST( 32 | name=app_name, 33 | title=app_title, 34 | redirect_urls=redirect_urls, 35 | )) 36 | 37 | assert(app.name == app_name) 38 | 39 | apps = appregistry.list_apps() 40 | assert(len(apps) > 0) 41 | 42 | app_ret = appregistry.get_app(app_name) 43 | assert(app_ret.name == app_name) 44 | assert(app_ret.kind == "native") 45 | 46 | description = "A New Description" 47 | redirect_urls = ["https://somewhereelse"] 48 | app_title = "psdk-2-" + app_name + "-" + secs 49 | appregistry.update_app(app_name, UpdateAppRequest( 50 | description=description, 51 | title=app_title, 52 | redirect_urls=redirect_urls, 53 | )) 54 | 55 | app_ret = appregistry.get_app(app_name) 56 | assert(app_ret.name == app_name) 57 | assert(app_ret.kind == "native") 58 | assert(app_ret.title == app_title) 59 | assert(app_ret.description == description) 60 | 61 | finally: 62 | appregistry.delete_app(app_name) 63 | 64 | 65 | @pytest.mark.usefixtures("test_client") # NOQA 66 | def test_app_rotate_secret(test_client: BaseClient): 67 | app_name = None 68 | appregistry = AppRegistry(test_client) 69 | try: 70 | secs = str(round(time())) 71 | app_name = "p.c" + secs 72 | app_title = "psdk-" + app_name + "-" + secs 73 | redirect_urls = ["https://localhost"] 74 | 75 | app = appregistry.create_app(ServiceAppPOST( 76 | name=app_name, 77 | title=app_title, 78 | redirect_urls=redirect_urls, 79 | )) 80 | secret1 = app.to_dict()["clientSecret"] 81 | app_response = appregistry.rotate_secret(app_name) 82 | secret2 = app_response.to_dict()["clientSecret"] 83 | 84 | assert (secret1 != secret2) 85 | 86 | finally: 87 | appregistry.delete_app(app_name) 88 | 89 | 90 | @pytest.mark.usefixtures("test_client") # NOQA 91 | def test_subscriptions(test_client: BaseClient): 92 | appregistry = AppRegistry(test_client) 93 | app_name = None 94 | try: 95 | secs = str(round(time())) 96 | app_name = "p.c" + secs 97 | app_title = "psdk-" + app_name + "-" + secs 98 | redirect_urls = ["https://localhost"] 99 | 100 | app = appregistry.create_app(NativeAppPOST( 101 | name=app_name, 102 | title=app_title, 103 | redirect_urls=redirect_urls, 104 | )) 105 | 106 | appregistry.create_subscription(AppName(app.name)) 107 | sub = appregistry.get_subscription(app.name) 108 | assert(app.name == sub.app_name) 109 | subs = appregistry.list_subscriptions() 110 | sub_count = len(subs) 111 | assert(sub_count > 0) 112 | 113 | subs = [s for s in appregistry.list_subscriptions() if s.app_name == app.name] 114 | assert(len(subs) == 1) 115 | 116 | subs = appregistry.list_app_subscriptions(app.name) 117 | assert(len(subs) == 1) 118 | 119 | appregistry.delete_subscription(app.name) 120 | 121 | subs = appregistry.list_app_subscriptions(app.name) 122 | assert(len(subs) == 0) 123 | 124 | subs = appregistry.list_subscriptions() 125 | assert(len(subs) == sub_count - 1) 126 | 127 | finally: 128 | appregistry.delete_app(app_name) 129 | -------------------------------------------------------------------------------- /splunk_sdk/ingest/ingest_event_batcher.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | 12 | import sys 13 | import logging 14 | 15 | from threading import Timer 16 | from splunk_sdk.ingest import IngestAPI, Event, HTTPResponse 17 | from typing import Optional, Callable, List 18 | 19 | DEFAULT_BATCH_SIZE = 1040000 # bytes 20 | 21 | logger = logging.getLogger(__name__) 22 | 23 | 24 | class EventBatcher(object): 25 | 26 | def __init__(self, ingest_service: IngestAPI, 27 | batch_size: int = DEFAULT_BATCH_SIZE, 28 | batch_count: int = 500, timeout: int = 30, 29 | batch_dispatch_handler: 30 | Callable[[List[Event]], Optional[HTTPResponse]] = None, 31 | error_handler: Callable[[Exception], None] = None): 32 | """Creates an instance of the EventBatcher 33 | :param ingest_service: 34 | :param batch_size: size limit of the batch in bytes 35 | :param batch_count: number of events in the batch 36 | :param timeout: time in seconds to flush the queue and send events 37 | :param batch_dispatch_handler: custom handler to deal with responses 38 | :param error_handler: custom exception handler 39 | """ 40 | self.ingest_service = ingest_service 41 | self.batch_size = batch_size 42 | self.batch_count = batch_count 43 | self.timeout = timeout 44 | 45 | self.queue = [] 46 | self.timer = Timer(timeout, self.flush) 47 | self.timer.start() 48 | 49 | if batch_dispatch_handler is None: 50 | self.batch_dispatch_handler = self._batch_dispatch_handler 51 | else: 52 | self.batch_dispatch_handler = batch_dispatch_handler 53 | 54 | if error_handler is None: 55 | self.error_handler = self._error_handler 56 | else: 57 | self.error_handler = error_handler 58 | 59 | def add(self, event: Event) -> None: 60 | """Adds a new event to the list and sends all of the events if the 61 | event limits are met. 62 | :param event: 63 | """ 64 | self.queue.append(event) 65 | self._run() 66 | 67 | def _run(self) -> Optional[HTTPResponse]: 68 | """Processes the events in the queue and sends them to the ingest API 69 | when the queue limits are met or exceeded. 70 | Otherwise, the event is queued until the limit is reached. 71 | A timer runs periodically to ensure that events do not stay queued too 72 | long. 73 | :return: HTTPResponse 74 | """ 75 | max_count_reached = len(self.queue) >= self.batch_count 76 | byte_size_reached = sys.getsizeof(self.queue) >= self.batch_size 77 | 78 | if max_count_reached or byte_size_reached: 79 | return self.flush() 80 | 81 | def stop(self) -> Optional[HTTPResponse]: 82 | """Performs a flush operation if the queue is not empty. 83 | :return: HTTPResponse 84 | """ 85 | self._stop_timer() 86 | if self.queue and len(self.queue) > 0: 87 | return self.flush() 88 | 89 | def set_timer(self) -> None: 90 | """Creates a periodic task to send all of the events. 91 | """ 92 | self.timer = Timer(self.timeout, self.flush) 93 | self.timer.start() 94 | if self.queue and len(self.queue) > 0: 95 | self.flush() 96 | 97 | def reset_timer(self) -> None: 98 | """Resets the timer and updates the timer ID. 99 | """ 100 | self._stop_timer() 101 | self.timer = Timer(self.timeout, self.flush) 102 | self.timer.start() 103 | 104 | def _stop_timer(self) -> None: 105 | """Stops the timer. 106 | """ 107 | self.timer.cancel() 108 | 109 | @staticmethod 110 | def _batch_dispatch_handler(func, data) -> Optional[HTTPResponse]: 111 | """Default handling for sending events 112 | :param data: batched events 113 | """ 114 | return func(data) 115 | 116 | def _error_handler(self, e) -> None: 117 | """Default error handler. 118 | :param e: 119 | """ 120 | logger.error(e) 121 | 122 | def flush(self) -> Optional[HTTPResponse]: 123 | """Cleans up the events and timer. 124 | """ 125 | self.reset_timer() 126 | data = self.queue 127 | self.queue = [] 128 | try: 129 | return self.batch_dispatch_handler(self.ingest_service.post_events, 130 | data) 131 | except Exception as e: 132 | self.error_handler(e) 133 | -------------------------------------------------------------------------------- /test/data/ml/iris.csv: -------------------------------------------------------------------------------- 1 | sepal_length,sepal_width,petal_length,petal_width,species 2 | 5.1,3.5,1.4,0.2,Iris Setosa 3 | 4.9,3.0,1.4,0.2,Iris Setosa 4 | 4.7,3.2,1.3,0.2,Iris Setosa 5 | 4.6,3.1,1.5,0.2,Iris Setosa 6 | 5.0,3.6,1.4,0.2,Iris Setosa 7 | 5.4,3.9,1.7,0.4,Iris Setosa 8 | 4.6,3.4,1.4,0.3,Iris Setosa 9 | 5.0,3.4,1.5,0.2,Iris Setosa 10 | 4.4,2.9,1.4,0.2,Iris Setosa 11 | 4.9,3.1,1.5,0.1,Iris Setosa 12 | 5.4,3.7,1.5,0.2,Iris Setosa 13 | 4.8,3.4,1.6,0.2,Iris Setosa 14 | 4.8,3.0,1.4,0.1,Iris Setosa 15 | 4.3,3.0,1.1,0.1,Iris Setosa 16 | 5.8,4.0,1.2,0.2,Iris Setosa 17 | 5.7,4.4,1.5,0.4,Iris Setosa 18 | 5.4,3.9,1.3,0.4,Iris Setosa 19 | 5.1,3.5,1.4,0.3,Iris Setosa 20 | 5.7,3.8,1.7,0.3,Iris Setosa 21 | 5.1,3.8,1.5,0.3,Iris Setosa 22 | 5.4,3.4,1.7,0.2,Iris Setosa 23 | 5.1,3.7,1.5,0.4,Iris Setosa 24 | 4.6,3.6,1.0,0.2,Iris Setosa 25 | 5.1,3.3,1.7,0.5,Iris Setosa 26 | 4.8,3.4,1.9,0.2,Iris Setosa 27 | 5.0,3.0,1.6,0.2,Iris Setosa 28 | 5.0,3.4,1.6,0.4,Iris Setosa 29 | 5.2,3.5,1.5,0.2,Iris Setosa 30 | 5.2,3.4,1.4,0.2,Iris Setosa 31 | 4.7,3.2,1.6,0.2,Iris Setosa 32 | 4.8,3.1,1.6,0.2,Iris Setosa 33 | 5.4,3.4,1.5,0.4,Iris Setosa 34 | 5.2,4.1,1.5,0.1,Iris Setosa 35 | 5.5,4.2,1.4,0.2,Iris Setosa 36 | 4.9,3.1,1.5,0.1,Iris Setosa 37 | 5.0,3.2,1.2,0.2,Iris Setosa 38 | 5.5,3.5,1.3,0.2,Iris Setosa 39 | 4.9,3.1,1.5,0.1,Iris Setosa 40 | 4.4,3.0,1.3,0.2,Iris Setosa 41 | 5.1,3.4,1.5,0.2,Iris Setosa 42 | 5.0,3.5,1.3,0.3,Iris Setosa 43 | 4.5,2.3,1.3,0.3,Iris Setosa 44 | 4.4,3.2,1.3,0.2,Iris Setosa 45 | 5.0,3.5,1.6,0.6,Iris Setosa 46 | 5.1,3.8,1.9,0.4,Iris Setosa 47 | 4.8,3.0,1.4,0.3,Iris Setosa 48 | 5.1,3.8,1.6,0.2,Iris Setosa 49 | 4.6,3.2,1.4,0.2,Iris Setosa 50 | 5.3,3.7,1.5,0.2,Iris Setosa 51 | 5.0,3.3,1.4,0.2,Iris Setosa 52 | 7.0,3.2,4.7,1.4,Iris Versicolor 53 | 6.4,3.2,4.5,1.5,Iris Versicolor 54 | 6.9,3.1,4.9,1.5,Iris Versicolor 55 | 5.5,2.3,4.0,1.3,Iris Versicolor 56 | 6.5,2.8,4.6,1.5,Iris Versicolor 57 | 5.7,2.8,4.5,1.3,Iris Versicolor 58 | 6.3,3.3,4.7,1.6,Iris Versicolor 59 | 4.9,2.4,3.3,1.0,Iris Versicolor 60 | 6.6,2.9,4.6,1.3,Iris Versicolor 61 | 5.2,2.7,3.9,1.4,Iris Versicolor 62 | 5.0,2.0,3.5,1.0,Iris Versicolor 63 | 5.9,3.0,4.2,1.5,Iris Versicolor 64 | 6.0,2.2,4.0,1.0,Iris Versicolor 65 | 6.1,2.9,4.7,1.4,Iris Versicolor 66 | 5.6,2.9,3.6,1.3,Iris Versicolor 67 | 6.7,3.1,4.4,1.4,Iris Versicolor 68 | 5.6,3.0,4.5,1.5,Iris Versicolor 69 | 5.8,2.7,4.1,1.0,Iris Versicolor 70 | 6.2,2.2,4.5,1.5,Iris Versicolor 71 | 5.6,2.5,3.9,1.1,Iris Versicolor 72 | 5.9,3.2,4.8,1.8,Iris Versicolor 73 | 6.1,2.8,4.0,1.3,Iris Versicolor 74 | 6.3,2.5,4.9,1.5,Iris Versicolor 75 | 6.1,2.8,4.7,1.2,Iris Versicolor 76 | 6.4,2.9,4.3,1.3,Iris Versicolor 77 | 6.6,3.0,4.4,1.4,Iris Versicolor 78 | 6.8,2.8,4.8,1.4,Iris Versicolor 79 | 6.7,3.0,5.0,1.7,Iris Versicolor 80 | 6.0,2.9,4.5,1.5,Iris Versicolor 81 | 5.7,2.6,3.5,1.0,Iris Versicolor 82 | 5.5,2.4,3.8,1.1,Iris Versicolor 83 | 5.5,2.4,3.7,1.0,Iris Versicolor 84 | 5.8,2.7,3.9,1.2,Iris Versicolor 85 | 6.0,2.7,5.1,1.6,Iris Versicolor 86 | 5.4,3.0,4.5,1.5,Iris Versicolor 87 | 6.0,3.4,4.5,1.6,Iris Versicolor 88 | 6.7,3.1,4.7,1.5,Iris Versicolor 89 | 6.3,2.3,4.4,1.3,Iris Versicolor 90 | 5.6,3.0,4.1,1.3,Iris Versicolor 91 | 5.5,2.5,4.0,1.3,Iris Versicolor 92 | 5.5,2.6,4.4,1.2,Iris Versicolor 93 | 6.1,3.0,4.6,1.4,Iris Versicolor 94 | 5.8,2.6,4.0,1.2,Iris Versicolor 95 | 5.0,2.3,3.3,1.0,Iris Versicolor 96 | 5.6,2.7,4.2,1.3,Iris Versicolor 97 | 5.7,3.0,4.2,1.2,Iris Versicolor 98 | 5.7,2.9,4.2,1.3,Iris Versicolor 99 | 6.2,2.9,4.3,1.3,Iris Versicolor 100 | 5.1,2.5,3.0,1.1,Iris Versicolor 101 | 5.7,2.8,4.1,1.3,Iris Versicolor 102 | 6.3,3.3,6.0,2.5,Iris Virginica 103 | 5.8,2.7,5.1,1.9,Iris Virginica 104 | 7.1,3.0,5.9,2.1,Iris Virginica 105 | 6.3,2.9,5.6,1.8,Iris Virginica 106 | 6.5,3.0,5.8,2.2,Iris Virginica 107 | 7.6,3.0,6.6,2.1,Iris Virginica 108 | 4.9,2.5,4.5,1.7,Iris Virginica 109 | 7.3,2.9,6.3,1.8,Iris Virginica 110 | 6.7,2.5,5.8,1.8,Iris Virginica 111 | 7.2,3.6,6.1,2.5,Iris Virginica 112 | 6.5,3.2,5.1,2.0,Iris Virginica 113 | 6.4,2.7,5.3,1.9,Iris Virginica 114 | 6.8,3.0,5.5,2.1,Iris Virginica 115 | 5.7,2.5,5.0,2.0,Iris Virginica 116 | 5.8,2.8,5.1,2.4,Iris Virginica 117 | 6.4,3.2,5.3,2.3,Iris Virginica 118 | 6.5,3.0,5.5,1.8,Iris Virginica 119 | 7.7,3.8,6.7,2.2,Iris Virginica 120 | 7.7,2.6,6.9,2.3,Iris Virginica 121 | 6.0,2.2,5.0,1.5,Iris Virginica 122 | 6.9,3.2,5.7,2.3,Iris Virginica 123 | 5.6,2.8,4.9,2.0,Iris Virginica 124 | 7.7,2.8,6.7,2.0,Iris Virginica 125 | 6.3,2.7,4.9,1.8,Iris Virginica 126 | 6.7,3.3,5.7,2.1,Iris Virginica 127 | 7.2,3.2,6.0,1.8,Iris Virginica 128 | 6.2,2.8,4.8,1.8,Iris Virginica 129 | 6.1,3.0,4.9,1.8,Iris Virginica 130 | 6.4,2.8,5.6,2.1,Iris Virginica 131 | 7.2,3.0,5.8,1.6,Iris Virginica 132 | 7.4,2.8,6.1,1.9,Iris Virginica 133 | 7.9,3.8,6.4,2.0,Iris Virginica 134 | 6.4,2.8,5.6,2.2,Iris Virginica 135 | 6.3,2.8,5.1,1.5,Iris Virginica 136 | 6.1,2.6,5.6,1.4,Iris Virginica 137 | 7.7,3.0,6.1,2.3,Iris Virginica 138 | 6.3,3.4,5.6,2.4,Iris Virginica 139 | 6.4,3.1,5.5,1.8,Iris Virginica 140 | 6.0,3.0,4.8,1.8,Iris Virginica 141 | 6.9,3.1,5.4,2.1,Iris Virginica 142 | 6.7,3.1,5.6,2.4,Iris Virginica 143 | 6.9,3.1,5.1,2.3,Iris Virginica 144 | 5.8,2.7,5.1,1.9,Iris Virginica 145 | 6.8,3.2,5.9,2.3,Iris Virginica 146 | 6.7,3.3,5.7,2.5,Iris Virginica 147 | 6.7,3.0,5.2,2.3,Iris Virginica 148 | 6.3,2.5,5.0,1.9,Iris Virginica 149 | 6.5,3.0,5.2,2.0,Iris Virginica 150 | 6.2,3.4,5.4,2.3,Iris Virginica 151 | 5.9,3.0,5.1,1.8,Iris Virginica 152 | -------------------------------------------------------------------------------- /test/test_identity.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | import random 12 | from time import sleep 13 | 14 | import pytest 15 | 16 | from splunk_sdk.base_client import BaseClient 17 | from splunk_sdk.identity import Identity as IdentityAndAccessControl 18 | from splunk_sdk.identity import CreateRoleBody, AddGroupRoleBody, AddMemberBody, AddGroupMemberBody, AddRolePermissionBody 19 | from splunk_sdk.identity import CreateGroupBody 20 | from test.fixtures import get_test_client as test_client # NOQA 21 | 22 | 23 | @pytest.mark.usefixtures("test_client") # NOQA 24 | def test_crud_groups(test_client: BaseClient): 25 | identity = IdentityAndAccessControl(test_client) 26 | username = _get_test_username(identity) 27 | 28 | group_name = "pygrouptest{}".format(random.randint(0, 100000000)) 29 | group = identity.create_group(CreateGroupBody(group_name)) 30 | assert(group.name == group_name) 31 | assert(test_client.get_tenant() == group.tenant) 32 | assert(username == group.created_by) 33 | 34 | sleep(2) 35 | fetched_group = identity.get_group(group_name) 36 | assert(fetched_group.created_at == group.created_at) 37 | 38 | all_groups = identity.list_groups() 39 | assert(str(all_groups.items).index(fetched_group.name) >= 0) 40 | 41 | role_name = "pygrouptestrole{}".format(random.randint(0, 100000000)) 42 | role = identity.create_role(CreateRoleBody(role_name)) 43 | assert(role.name == role_name) 44 | assert(role.created_by == username) 45 | 46 | sleep(2) 47 | group_role = identity.add_group_role(group_name, AddGroupRoleBody(role_name)) 48 | assert(group_role.added_by == username) 49 | assert(group_role.group == group_name) 50 | assert(group_role.role == role_name) 51 | 52 | sleep(2) 53 | group_roles = identity.list_group_roles(group_name) 54 | assert(group_roles.items[0].role == role_name) 55 | 56 | member_name = "0oabp299js4d0z0dj357" # a test service app 57 | member = identity.add_member(AddMemberBody(member_name)) 58 | assert(member.name == member_name) 59 | assert(member.added_by == username) 60 | 61 | sleep(2) 62 | members = identity.list_group_members(group_name) 63 | members_found = [m for m in members.items if m == member_name] 64 | assert(len(members_found) == 0) 65 | 66 | group_member = identity.add_group_member(group_name, AddGroupMemberBody(name=member_name)) 67 | assert(group_member.principal == member_name) 68 | 69 | sleep(2) 70 | members = identity.list_group_members(group_name) 71 | assert(str(members.items).index(member_name) >= -1) 72 | 73 | result_member = identity.get_group_member(group_name, member_name) 74 | assert(result_member.group == group_name) 75 | assert(result_member.principal == member_name) 76 | 77 | identity.remove_group_member(group_name, member_name) 78 | identity.remove_member(member_name) 79 | identity.remove_group_role(group_name, role_name) 80 | identity.delete_role(role_name) 81 | identity.delete_group(group_name) 82 | 83 | @pytest.mark.usefixtures("test_client") # NOQA 84 | def test_crud_roles(test_client: BaseClient): 85 | test_client.context.debug = True 86 | identity = IdentityAndAccessControl(test_client) 87 | username = _get_test_username(identity) 88 | 89 | role_name = "pyroletest{}".format(random.randint(0, 100000000)) 90 | role = identity.create_role(CreateRoleBody(role_name)) 91 | assert(role.name == role_name) 92 | assert(role.created_by == username) 93 | assert(role.tenant == test_client.get_tenant()) 94 | 95 | sleep(2) # Role may not be ready immediately 96 | result_role = identity.get_role(role_name) 97 | assert(result_role.name == role_name) 98 | assert(result_role.created_by == username) 99 | assert(result_role.tenant == test_client.get_tenant()) 100 | 101 | all_roles = identity.list_roles() 102 | assert(str(all_roles.items).index(result_role.name) >= 0) 103 | 104 | permission = "{}:*:pyperm1.{}".format(test_client.get_tenant(), random.randint(0, 100000000)) 105 | result_role_perm = identity.add_role_permission(role_name, AddRolePermissionBody(permission=permission)) 106 | assert(result_role_perm.role == role_name) 107 | assert(result_role_perm.permission == permission) 108 | assert(result_role_perm.added_by == username) 109 | assert(result_role_perm.tenant == test_client.get_tenant()) 110 | 111 | sleep(2) 112 | retrieved_perm = identity.get_role_permission(role_name, permission) 113 | assert(retrieved_perm.permission == permission) 114 | 115 | perms = identity.list_role_permissions(role_name) 116 | assert(str(perms.items).index(permission) >= 0) 117 | 118 | identity.delete_role(role_name) 119 | 120 | 121 | def _get_test_username(identity: IdentityAndAccessControl): 122 | return identity.validate_token().name 123 | -------------------------------------------------------------------------------- /test/test_search.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | import itertools 12 | import pytest 13 | import time 14 | 15 | from test.fixtures import get_test_client as test_client # NOQA 16 | 17 | from splunk_sdk.search import SplunkSearchService as Search 18 | from splunk_sdk.search import SearchJob, UpdateJob, Message, \ 19 | ListSearchResultsResponse 20 | from splunk_sdk.search.search_helper import wait_for_job 21 | 22 | # Use pre-baked events so that number of events and format are fixed 23 | STANDARD_QUERY = ''' 24 | from [ 25 | {"name": "event1"}, 26 | {"name": "event2"}, 27 | {"name": "event3"}, 28 | {"name": "event4"}, 29 | {"name": "event5"} 30 | ] 31 | ''' 32 | 33 | # TODO(shakeel): add test_list_results w/ a search using a module when catalog 34 | # is ready for that 35 | 36 | @pytest.mark.usefixtures("test_client") # NOQA 37 | def test_create_job(test_client): 38 | search = Search(test_client) 39 | 40 | search_job = SearchJob(query=STANDARD_QUERY) 41 | job = search.create_job(search_job=search_job) 42 | 43 | assert (isinstance(job, SearchJob)) 44 | assert (job.query == STANDARD_QUERY) 45 | assert (job.sid is not None) 46 | assert (job.status is not None) 47 | 48 | @pytest.mark.usefixtures("test_client") # NOQA 49 | def test_update_job(test_client): 50 | search = Search(test_client) 51 | 52 | # create job 53 | search_job = SearchJob(query=STANDARD_QUERY) 54 | job = search.create_job(search_job=search_job) 55 | assert (isinstance(job, SearchJob)) 56 | 57 | # get job 58 | time.sleep(2) 59 | _job = search.get_job(job.sid) 60 | 61 | if _job.status == 'running': 62 | # update 63 | canceled_job = UpdateJob(status='canceled') 64 | updated_job = search.update_job(job.sid, update_job=canceled_job) 65 | assert (isinstance(updated_job, SearchJob)) 66 | 67 | 68 | @pytest.mark.usefixtures("test_client") # NOQA 69 | def test_get_job(test_client): 70 | search = Search(test_client) 71 | 72 | search_job = SearchJob(query=STANDARD_QUERY) 73 | job = search.create_job(search_job=search_job) 74 | assert (isinstance(job, SearchJob)) 75 | assert (job.query == STANDARD_QUERY) 76 | assert (job.sid is not None) 77 | assert (job.status is not None) 78 | 79 | job2 = search.get_job(job.sid) 80 | assert (isinstance(job2, SearchJob)) 81 | assert (job.sid == job2.sid) 82 | assert (job.query == job2.query) 83 | 84 | 85 | @pytest.mark.asyncio 86 | @pytest.mark.usefixtures("test_client") # NOQA 87 | async def test_list_results(test_client): 88 | search = Search(test_client) 89 | 90 | search_job = SearchJob(query=STANDARD_QUERY) 91 | job = search.create_job(search_job=search_job) 92 | assert (job.query == STANDARD_QUERY) 93 | assert (job.sid is not None) 94 | assert (job.status is not None) 95 | 96 | results = search.list_results(job.sid) 97 | assert (isinstance(results, ListSearchResultsResponse)) 98 | assert (results.next_link is not None) 99 | 100 | job2 = await wait_for_job(search.get_job, job.sid) 101 | assert (isinstance(job, SearchJob)) 102 | assert (job2.status == 'done') 103 | 104 | results2 = search.list_results(job2.sid) 105 | assert (isinstance(results2, ListSearchResultsResponse)) 106 | 107 | 108 | @pytest.mark.asyncio 109 | @pytest.mark.usefixtures("test_client") # NOQA 110 | async def test_list_results_with_pagination(test_client): 111 | search = Search(test_client) 112 | 113 | search_job = SearchJob(query=STANDARD_QUERY) 114 | job = search.create_job(search_job=search_job) 115 | assert (job.query == STANDARD_QUERY) 116 | assert (job.sid is not None) 117 | assert (job.status is not None) 118 | 119 | job2 = await wait_for_job(search.get_job, job.sid) 120 | assert (isinstance(job, SearchJob)) 121 | assert (job2.status == 'done') 122 | assert (job2.results_available == 5) 123 | 124 | results = search.list_results(job2.sid, offset=0, count=3) 125 | assert (isinstance(results, ListSearchResultsResponse)) 126 | assert (len(results.results) == 3) 127 | 128 | results = search.list_results(job2.sid, offset=3, count=5) 129 | assert (isinstance(results, ListSearchResultsResponse)) 130 | assert (len(results.results) == 2) 131 | 132 | results = search.list_results(job2.sid, offset=10, count=10) 133 | assert (isinstance(results, ListSearchResultsResponse)) 134 | assert (len(results.results) == 0) 135 | 136 | 137 | @pytest.mark.asyncio 138 | @pytest.mark.usefixtures("test_client") # NOQA 139 | async def test_wait_for_job(test_client): 140 | search = Search(test_client) 141 | 142 | search_job = SearchJob(query=STANDARD_QUERY) 143 | job = search.create_job(search_job=search_job) 144 | 145 | 146 | jobs = search.list_jobs() 147 | assert (len(jobs) > 0) 148 | 149 | for job in jobs: 150 | assert (isinstance(job, SearchJob)) 151 | assert (job.status is not None) 152 | assert (job.results_available is not None) 153 | assert (job.sid is not None) 154 | assert (job.query is not None) 155 | assert (job.module is not None) 156 | assert (job.percent_complete is not None) 157 | -------------------------------------------------------------------------------- /splunk_sdk/action/v2alpha1/gen_action_service_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # Copyright © 2022 Splunk, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 6 | # not use this file except in compliance with the License. You may obtain 7 | # a copy of the License at 8 | # 9 | # [http://www.apache.org/licenses/LICENSE-2.0] 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations 15 | # under the License. 16 | 17 | ############# This file is auto-generated. Do not edit! ############# 18 | 19 | """ 20 | SDC Service: Action Service 21 | 22 | With the Splunk Cloud Action service, you can receive incoming trigger events and use pre-defined action templates to turn these events into meaningful actions. 23 | 24 | OpenAPI spec version: v2alpha1.12 25 | Generated by: https://openapi-generator.tech 26 | """ 27 | 28 | 29 | from requests import Response 30 | from string import Template 31 | from typing import List, Dict 32 | 33 | from splunk_sdk.base_client import handle_response 34 | from splunk_sdk.base_service import BaseService 35 | from splunk_sdk.common.sscmodel import SSCModel, SSCVoidModel 36 | 37 | from splunk_sdk.action.v2alpha1.gen_models import Action 38 | from splunk_sdk.action.v2alpha1.gen_models import ActionMutable 39 | from splunk_sdk.action.v2alpha1.gen_models import PublicWebhookKey 40 | from splunk_sdk.action.v2alpha1.gen_models import ServiceError 41 | 42 | 43 | class ActionService(BaseService): 44 | """ 45 | Action Service 46 | Version: v2alpha1.12 47 | With the Splunk Cloud Action service, you can receive incoming trigger events and use pre-defined action templates to turn these events into meaningful actions. 48 | """ 49 | 50 | def __init__(self, base_client): 51 | super().__init__(base_client) 52 | 53 | def create_action(self, action: Action, query_params: Dict[str, object] = None) -> Action: 54 | """ 55 | Creates an action template. 56 | """ 57 | if query_params is None: 58 | query_params = {} 59 | 60 | path_params = { 61 | } 62 | 63 | path = Template("/action/v2alpha1/actions").substitute(path_params) 64 | url = self.base_client.build_url(path) 65 | data = action.to_dict() 66 | response = self.base_client.post(url, json=data, params=query_params) 67 | return handle_response(response, Action) 68 | 69 | def delete_action(self, action_name: str, query_params: Dict[str, object] = None) -> SSCVoidModel: 70 | """ 71 | Removes an action template. 72 | """ 73 | if query_params is None: 74 | query_params = {} 75 | 76 | path_params = { 77 | "action_name": action_name, 78 | } 79 | 80 | path = Template("/action/v2alpha1/actions/${action_name}").substitute(path_params) 81 | url = self.base_client.build_url(path) 82 | response = self.base_client.delete(url, params=query_params) 83 | return handle_response(response, ) 84 | 85 | def get_action(self, action_name: str, query_params: Dict[str, object] = None) -> Action: 86 | """ 87 | Returns a specific action template. 88 | """ 89 | if query_params is None: 90 | query_params = {} 91 | 92 | path_params = { 93 | "action_name": action_name, 94 | } 95 | 96 | path = Template("/action/v2alpha1/actions/${action_name}").substitute(path_params) 97 | url = self.base_client.build_url(path) 98 | response = self.base_client.get(url, params=query_params) 99 | return handle_response(response, Action) 100 | 101 | def get_public_webhook_keys(self, query_params: Dict[str, object] = None) -> List[PublicWebhookKey]: 102 | """ 103 | Get the current webhook key(s). If multiple keys were returned, one is active and one is expired. 104 | """ 105 | if query_params is None: 106 | query_params = {} 107 | 108 | path_params = { 109 | } 110 | 111 | path = Template("/system/action/v2alpha1/webhook/keys").substitute(path_params) 112 | url = self.base_client.build_url(path) 113 | response = self.base_client.get(url, params=query_params) 114 | return handle_response(response, PublicWebhookKey) 115 | 116 | def list_actions(self, query_params: Dict[str, object] = None) -> List[Action]: 117 | """ 118 | Returns the list of action templates. 119 | """ 120 | if query_params is None: 121 | query_params = {} 122 | 123 | path_params = { 124 | } 125 | 126 | path = Template("/action/v2alpha1/actions").substitute(path_params) 127 | url = self.base_client.build_url(path) 128 | response = self.base_client.get(url, params=query_params) 129 | return handle_response(response, Action) 130 | 131 | def update_action(self, action_name: str, action_mutable: ActionMutable, query_params: Dict[str, object] = None) -> Action: 132 | """ 133 | Modifies an action template. 134 | """ 135 | if query_params is None: 136 | query_params = {} 137 | 138 | path_params = { 139 | "action_name": action_name, 140 | } 141 | 142 | path = Template("/action/v2alpha1/actions/${action_name}").substitute(path_params) 143 | url = self.base_client.build_url(path) 144 | data = action_mutable.to_dict() 145 | response = self.base_client.patch(url, json=data, params=query_params) 146 | return handle_response(response, Action) 147 | 148 | 149 | -------------------------------------------------------------------------------- /test/test_kvstore.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | import pytest 12 | import time 13 | from test.fixtures import get_test_client as test_client # NOQA 14 | from splunk_sdk.catalog import MetadataCatalog as Catalog, \ 15 | KVCollectionDatasetPOST, Dataset 16 | from splunk_sdk.kvstore import KVStoreAPI, IndexDefinition, \ 17 | IndexFieldDefinition 18 | from splunk_sdk.common.sscmodel import SSCModel 19 | 20 | 21 | class Record(SSCModel): 22 | 23 | def __init__(self): 24 | super().__init__() 25 | 26 | def to_dict(self) -> dict: 27 | return self.__dict__ 28 | 29 | 30 | def _create_dataset(test_client) -> Dataset: 31 | catalog = Catalog(test_client) 32 | name = "pysdk" + str(time.time_ns()) 33 | result = catalog.create_dataset(KVCollectionDatasetPOST(name)) 34 | assert (result is not None) 35 | return result 36 | 37 | 38 | def _delete_dataset(test_client, name): 39 | catalog = Catalog(test_client) 40 | resp = catalog.delete_dataset(name).response 41 | assert(resp.status_code == 204) 42 | 43 | 44 | @pytest.mark.usefixtures('test_client') # NOQA 45 | def test_ping(test_client): 46 | kvs = KVStoreAPI(test_client) 47 | health = kvs.ping() 48 | assert(health.status == 'healthy') 49 | 50 | 51 | @pytest.mark.usefixtures('test_client') # NOQA 52 | def test_create_and_delete_dataset(test_client): 53 | ds = _create_dataset(test_client) 54 | _delete_dataset(test_client, ds.name) 55 | 56 | 57 | @pytest.mark.usefixtures('test_client') # NOQA 58 | def test_index_operations(test_client): 59 | 60 | # create kvcollection dataset 61 | ds = _create_dataset(test_client) 62 | collection_name = ds.name 63 | index_name = "myindex" 64 | 65 | kvs = KVStoreAPI(test_client) 66 | fields = [IndexFieldDefinition(direction=1, field="f1"), ] 67 | 68 | # create index 69 | index_description = kvs.create_index(collection=collection_name, 70 | index_definition=IndexDefinition( 71 | fields=fields, name=index_name)) 72 | assert(index_description.name == index_name) 73 | assert(index_description.fields[0].direction == fields[0].direction) 74 | assert(index_description.fields[0].field == fields[0].field) 75 | 76 | # list indexes 77 | indexes = kvs.list_indexes(collection_name) 78 | assert(indexes[0].fields[0].direction == fields[0].direction) 79 | assert(indexes[0].fields[0].field == fields[0].field) 80 | 81 | # Note: delete_index returns 404 82 | # delete index and collection 83 | # kvs.delete_index(collection=collection_name, index=index_name) 84 | _delete_dataset(test_client, collection_name) 85 | 86 | 87 | @pytest.mark.usefixtures('test_client') # NOQA 88 | def test_record_operations(test_client): 89 | 90 | # create kvcollection dataset 91 | ds = _create_dataset(test_client) 92 | collection_name = ds.name 93 | index_name = "myindex" 94 | my_data = "mydata" 95 | 96 | kvs = KVStoreAPI(test_client) 97 | fields = [IndexFieldDefinition(direction=1, field="f1"), ] 98 | 99 | # create index 100 | index_description = kvs.create_index(collection=collection_name, 101 | index_definition=IndexDefinition( 102 | fields=fields, name=index_name)) 103 | assert(index_description.name == index_name) 104 | 105 | r1 = Record() 106 | r1.column = my_data 107 | 108 | r2 = Record() 109 | r2.data = "backups" 110 | 111 | r3 = Record() 112 | r3.level = "logs" 113 | 114 | # insert a record 115 | key = kvs.insert_record(collection_name, body=r1) 116 | assert(key is not None) 117 | assert(key.key is not None) 118 | 119 | # insert two records 120 | keys = kvs.insert_records(collection_name, request_body=[r2, r3]) 121 | assert(keys is not None) 122 | assert(len(keys) == 2) 123 | 124 | # list a record 125 | records = kvs.list_records(collection_name) 126 | assert(records is not None) 127 | assert(len(records) == 3) 128 | # remove metadata before comparing records 129 | for r in records: 130 | del r['_key'] 131 | del r['_user'] 132 | del r['_response'] 133 | assert({'column': my_data} in records) 134 | assert({'data': 'backups'} in records) 135 | assert({'level': 'logs'} in records) 136 | 137 | # get record by key 138 | rec = kvs.get_record_by_key(collection_name, key.key) 139 | assert(rec is not None) 140 | assert(rec["_key"] == key.key) 141 | assert(rec["column"] == my_data) 142 | 143 | # put record 144 | r1.meta = '{"more_info": {"color": "red", "num": 23}"}' 145 | key = kvs.put_record(collection_name, key=key.key, body=r1) 146 | assert(key is not None) 147 | assert(key.key is not None) 148 | 149 | # query record 150 | records = kvs.query_records(collection_name, query='{"column": "mydata"}') 151 | assert(records is not None) 152 | assert(records[0]['_key'] == key.key) 153 | assert(records[0]['column'] == my_data) 154 | assert(records[0]['meta'] == '{"more_info": {"color": "red", "num": 23}"}') 155 | 156 | # delete record by key 157 | resp = kvs.delete_record_by_key(collection_name, key=key.key).response 158 | assert(resp.status_code == 204) 159 | 160 | # delete records 161 | resp = kvs.delete_records(collection_name).response 162 | assert(resp.status_code == 204) 163 | 164 | # Note: delete index and dataset 165 | # delete_index returns 404 166 | # kvs.delete_index(collection=collection_name, index=index_name) 167 | _delete_dataset(test_client, ds.name) 168 | -------------------------------------------------------------------------------- /splunk_sdk/provisioner/v1beta1/gen_provisioner_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # Copyright © 2022 Splunk, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 6 | # not use this file except in compliance with the License. You may obtain 7 | # a copy of the License at 8 | # 9 | # [http://www.apache.org/licenses/LICENSE-2.0] 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations 15 | # under the License. 16 | 17 | ############# This file is auto-generated. Do not edit! ############# 18 | 19 | """ 20 | SDC Service: Provisioner 21 | 22 | With the Provisioner service in Splunk Cloud Services, you can provision and manage tenants. 23 | 24 | OpenAPI spec version: v1beta1.4 (recommended default) 25 | Generated by: https://openapi-generator.tech 26 | """ 27 | 28 | 29 | from requests import Response 30 | from string import Template 31 | from typing import List, Dict 32 | 33 | from splunk_sdk.base_client import handle_response 34 | from splunk_sdk.base_service import BaseService 35 | from splunk_sdk.common.sscmodel import SSCModel, SSCVoidModel 36 | 37 | from splunk_sdk.provisioner.v1beta1.gen_models import Error 38 | from splunk_sdk.provisioner.v1beta1.gen_models import InviteBody 39 | from splunk_sdk.provisioner.v1beta1.gen_models import InviteInfo 40 | from splunk_sdk.provisioner.v1beta1.gen_models import TenantInfo 41 | from splunk_sdk.provisioner.v1beta1.gen_models import UpdateInviteBody 42 | 43 | 44 | class Provisioner(BaseService): 45 | """ 46 | Provisioner 47 | Version: v1beta1.4 48 | With the Provisioner service in Splunk Cloud Services, you can provision and manage tenants. 49 | """ 50 | 51 | def __init__(self, base_client): 52 | super().__init__(base_client) 53 | 54 | def create_invite(self, invite_body: InviteBody, query_params: Dict[str, object] = None) -> InviteInfo: 55 | """ 56 | Creates an invitation for a person to join the tenant using their email address. 57 | """ 58 | if query_params is None: 59 | query_params = {} 60 | 61 | path_params = { 62 | } 63 | 64 | path = Template("/provisioner/v1beta1/invites").substitute(path_params) 65 | url = self.base_client.build_url(path) 66 | data = invite_body.to_dict() 67 | response = self.base_client.post(url, json=data, params=query_params) 68 | return handle_response(response, InviteInfo) 69 | 70 | def delete_invite(self, invite_id: str, query_params: Dict[str, object] = None) -> SSCVoidModel: 71 | """ 72 | Removes an invitation in the given tenant. 73 | """ 74 | if query_params is None: 75 | query_params = {} 76 | 77 | path_params = { 78 | "inviteId": invite_id, 79 | } 80 | 81 | path = Template("/provisioner/v1beta1/invites/${inviteId}").substitute(path_params) 82 | url = self.base_client.build_url(path) 83 | response = self.base_client.delete(url, params=query_params) 84 | return handle_response(response, ) 85 | 86 | def get_invite(self, invite_id: str, query_params: Dict[str, object] = None) -> InviteInfo: 87 | """ 88 | Returns an invitation in the given tenant. 89 | """ 90 | if query_params is None: 91 | query_params = {} 92 | 93 | path_params = { 94 | "inviteId": invite_id, 95 | } 96 | 97 | path = Template("/provisioner/v1beta1/invites/${inviteId}").substitute(path_params) 98 | url = self.base_client.build_url(path) 99 | response = self.base_client.get(url, params=query_params) 100 | return handle_response(response, InviteInfo) 101 | 102 | def get_tenant(self, tenant_name: str, query_params: Dict[str, object] = None) -> TenantInfo: 103 | """ 104 | Returns a specific tenant. 105 | """ 106 | if query_params is None: 107 | query_params = {} 108 | 109 | path_params = { 110 | "tenantName": tenant_name, 111 | } 112 | 113 | path = Template("/system/provisioner/v1beta1/tenants/${tenantName}").substitute(path_params) 114 | url = self.base_client.build_url(path) 115 | response = self.base_client.get(url, params=query_params) 116 | return handle_response(response, TenantInfo) 117 | 118 | def list_invites(self, query_params: Dict[str, object] = None) -> List[InviteInfo]: 119 | """ 120 | Returns a list of invitations in a given tenant. 121 | """ 122 | if query_params is None: 123 | query_params = {} 124 | 125 | path_params = { 126 | } 127 | 128 | path = Template("/provisioner/v1beta1/invites").substitute(path_params) 129 | url = self.base_client.build_url(path) 130 | response = self.base_client.get(url, params=query_params) 131 | return handle_response(response, InviteInfo) 132 | 133 | def list_tenants(self, query_params: Dict[str, object] = None) -> List[TenantInfo]: 134 | """ 135 | Returns all tenants that the user can read. 136 | """ 137 | if query_params is None: 138 | query_params = {} 139 | 140 | path_params = { 141 | } 142 | 143 | path = Template("/system/provisioner/v1beta1/tenants").substitute(path_params) 144 | url = self.base_client.build_url(path) 145 | response = self.base_client.get(url, params=query_params) 146 | return handle_response(response, TenantInfo) 147 | 148 | def update_invite(self, invite_id: str, update_invite_body: UpdateInviteBody, query_params: Dict[str, object] = None) -> InviteInfo: 149 | """ 150 | Modifies an invitation in the given tenant. 151 | """ 152 | if query_params is None: 153 | query_params = {} 154 | 155 | path_params = { 156 | "inviteId": invite_id, 157 | } 158 | 159 | path = Template("/provisioner/v1beta1/invites/${inviteId}").substitute(path_params) 160 | url = self.base_client.build_url(path) 161 | data = update_invite_body.to_dict() 162 | response = self.base_client.patch(url, json=data, params=query_params) 163 | return handle_response(response, InviteInfo) 164 | 165 | 166 | -------------------------------------------------------------------------------- /test/fixtures.py: -------------------------------------------------------------------------------- 1 | # Copyright © 2019 Splunk, Inc. 2 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 3 | # not use this file except in compliance with the License. You may obtain 4 | # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 5 | # Unless required by applicable law or agreed to in writing, software 6 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 7 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 8 | # License for the specific language governing permissions and limitations 9 | # under the License. 10 | 11 | import logging 12 | import os 13 | import pytest 14 | import sys 15 | 16 | from splunk_sdk.auth import ClientAuthManager, PKCEAuthManager, ServicePrincipalAuthManager 17 | from splunk_sdk.common.context import Context 18 | from splunk_sdk.base_client import get_client 19 | 20 | from splunk_sdk.base_client import RetryConfig 21 | 22 | # create logger 23 | logger = logging.getLogger() 24 | logger.setLevel(logging.DEBUG) 25 | 26 | # create console handler and set level to debug 27 | ch = logging.StreamHandler(sys.stdout) 28 | ch.setLevel(logging.DEBUG) 29 | 30 | # create formatter 31 | formatter = logging.Formatter( 32 | '%(asctime)s - %(name)s - %(levelname)s - %(message)s') 33 | 34 | # add formatter to ch 35 | ch.setFormatter(formatter) 36 | 37 | # add ch to logger 38 | logger.addHandler(ch) 39 | 40 | 41 | @pytest.fixture(scope='session') 42 | def get_test_client_default_retry(): 43 | context = Context(host=os.environ.get('SPLUNK_HOST_2'), 44 | api_host=os.environ.get('SPLUNK_HOST_2'), 45 | tenant=os.environ.get('SPLUNK_TENANT_2'), 46 | debug=os.environ.get( 47 | 'SPLUNK_DEBUG', 'false').lower().strip() == 'true') 48 | 49 | retry_config = RetryConfig(retry_requests_enabled=True) 50 | 51 | # integration tests use pkce by default 52 | service_client = get_client(context, _get_pkce_manager(), retry_config) 53 | assert (service_client is not None) 54 | return service_client 55 | 56 | @pytest.fixture(scope='session') 57 | def get_test_client_retry_false(): 58 | context = Context(host=os.environ.get('SPLUNK_HOST_2'), 59 | api_host=os.environ.get('SPLUNK_HOST_2'), 60 | tenant=os.environ.get('SPLUNK_TENANT_2'), 61 | debug=os.environ.get( 62 | 'SPLUNK_DEBUG', 'false').lower().strip() == 'true') 63 | 64 | retry_config = RetryConfig(retry_requests_enabled=False) 65 | 66 | # integration tests use pkce by default 67 | service_client = get_client(context, _get_pkce_manager(), retry_config) 68 | assert (service_client is not None) 69 | return service_client 70 | 71 | @pytest.fixture(scope='session') 72 | def get_test_client_custom_retry(): 73 | context = Context(host=os.environ.get('SPLUNK_HOST_2'), 74 | api_host=os.environ.get('SPLUNK_HOST_2'), 75 | tenant=os.environ.get('SPLUNK_TENANT_2'), 76 | debug=os.environ.get( 77 | 'SPLUNK_DEBUG', 'false').lower().strip() == 'true') 78 | 79 | retry_config = RetryConfig(retry_requests_enabled=True, retry_count=12, retry_interval=1200) 80 | 81 | # integration tests use pkce by default 82 | service_client = get_client(context, _get_pkce_manager(), retry_config) 83 | assert (service_client is not None) 84 | return service_client 85 | 86 | @pytest.fixture(scope='session') 87 | def get_test_client(): 88 | context = Context(host=os.environ.get('SPLUNK_HOST_2'), 89 | api_host=os.environ.get('SPLUNK_HOST_2'), 90 | tenant=os.environ.get('SPLUNK_TENANT_2'), 91 | tenant_scoped=True, 92 | region=os.environ.get('SPLUNK_REGION'), 93 | debug=os.environ.get( 94 | 'SPLUNK_DEBUG', 'false').lower().strip() == 'true') 95 | 96 | # integration tests use pkce by default 97 | service_client = get_client(context, _get_client_manager()) 98 | assert (service_client is not None) 99 | return service_client 100 | 101 | 102 | @pytest.fixture(scope='session') 103 | def get_test_client_provisioner(): 104 | context = Context(host=os.environ.get('SPLUNK_HOST_2'), 105 | api_host=os.environ.get('SPLUNK_HOST_2'), 106 | tenant='system', 107 | debug=os.environ.get( 108 | 'SPLUNK_DEBUG', 'false').lower().strip() == 'true') 109 | 110 | # integration tests use pkce by default 111 | service_client = get_client(context, _get_pkce_manager()) 112 | assert (service_client is not None) 113 | return service_client 114 | 115 | 116 | @pytest.fixture(scope='session') 117 | def get_auth_manager(): 118 | # Note: leaving this so we don't create too many merge conflicts 119 | auth_manager = _get_pkce_manager() 120 | assert (auth_manager is not None) 121 | return auth_manager 122 | 123 | 124 | @pytest.fixture(scope='session') 125 | def get_client_auth_manager(): 126 | auth_manager = _get_client_manager() 127 | assert (auth_manager is not None) 128 | return auth_manager 129 | 130 | @pytest.fixture(scope='session') 131 | def get_service_principal_auth_manager(): 132 | auth_manager = _get_principal_manager() 133 | assert (auth_manager is not None) 134 | return auth_manager 135 | 136 | 137 | def _get_pkce_manager(): 138 | return PKCEAuthManager(host=os.environ.get('SPLUNK_AUTH_HOST_2'), 139 | client_id=os.environ.get('SPLUNK_APP_CLIENT_ID_2'), 140 | username=os.environ.get('TEST_USERNAME'), 141 | password=os.environ.get('TEST_PASSWORD'), 142 | redirect_uri='https://localhost:8000', 143 | tenant_scoped=True, 144 | tenant=os.environ.get('SPLUNK_TENANT_2'), 145 | region=os.environ.get('SPLUNK_REGION')) 146 | 147 | 148 | def _get_client_manager(): 149 | return ClientAuthManager(host=os.environ.get('SPLUNK_AUTH_HOST_2'), 150 | client_id=os.environ.get( 151 | 'SPLUNK_APP_CLIENT_CRED_ID_2'), 152 | client_secret=os.environ.get( 153 | 'SPLUNK_APP_CLIENT_CRED_SECRET_2'), 154 | scope='', tenant=os.environ.get('SPLUNK_TENANT_2'), tenant_scoped=True, region=os.environ.get( 155 | 'SPLUNK_REGION')) 156 | 157 | def _get_principal_manager(): 158 | return ServicePrincipalAuthManager(host=os.environ.get('SPLUNK_AUTH_HOST_2'), 159 | tenant_scoped=True, 160 | tenant=os.environ.get('SPLUNK_TENANT_2'), 161 | region=os.environ.get('SPLUNK_REGION'), 162 | principal_name=os.environ.get('SPLUNK_APP_PRINCIPAL_NAME_2'), 163 | key=os.environ.get('SPLUNK_APP_PRINCIPAL_PRIVATE_KEY'), 164 | kid=os.environ.get('SPLUNK_APP_PRINCIPAL_KEY_ID'), 165 | algorithm=os.environ.get('SPLUNK_APP_PRINCIPAL_KEY_ALG')) 166 | 167 | -------------------------------------------------------------------------------- /splunk_sdk/forwarders/v2beta1/openapi.yaml: -------------------------------------------------------------------------------- 1 | components: 2 | responses: 3 | badRequestError: 4 | content: 5 | application/json: 6 | schema: 7 | $ref: '#/components/schemas/Error' 8 | description: The request isn't valid. 9 | errorResponse: 10 | content: 11 | application/json: 12 | schema: 13 | $ref: '#/components/schemas/Error' 14 | description: Error response. 15 | forbiddenError: 16 | content: 17 | application/json: 18 | schema: 19 | $ref: '#/components/schemas/Error' 20 | description: The operation isn't authorized. 21 | internalError: 22 | content: 23 | application/json: 24 | schema: 25 | $ref: '#/components/schemas/Error' 26 | description: An internal service error occurred. 27 | noContentResponse: 28 | description: The certificate was removed successfully. 29 | notFoundError: 30 | content: 31 | application/json: 32 | schema: 33 | $ref: '#/components/schemas/Error' 34 | description: The resource wasn't found. 35 | successCertUploadResponse: 36 | content: 37 | application/json: 38 | schema: 39 | $ref: '#/components/schemas/CertificateInfo' 40 | description: The certificate on the tenant slot was added successfully. 41 | successListCertificateResponse: 42 | content: 43 | application/json: 44 | schema: 45 | items: 46 | $ref: '#/components/schemas/CertificateInfo' 47 | type: array 48 | description: The list of certificates was returned successfully. 49 | tooManyRequestsError: 50 | content: 51 | application/json: 52 | schema: 53 | $ref: '#/components/schemas/Error' 54 | description: Too many requests were sent. 55 | unauthorizedError: 56 | content: 57 | application/json: 58 | schema: 59 | $ref: '#/components/schemas/Error' 60 | description: The user isn't authenticated. 61 | schemas: 62 | Certificate: 63 | properties: 64 | pem: 65 | type: string 66 | required: 67 | - pem 68 | type: object 69 | CertificateInfo: 70 | properties: 71 | content: 72 | type: string 73 | hash: 74 | type: string 75 | issuer: 76 | type: string 77 | lastUpdate: 78 | format: date-time 79 | type: string 80 | notAfter: 81 | format: date-time 82 | type: string 83 | notBefore: 84 | format: date-time 85 | type: string 86 | slot: 87 | format: int64 88 | type: integer 89 | subject: 90 | type: string 91 | type: object 92 | Error: 93 | properties: 94 | code: 95 | type: string 96 | details: 97 | type: object 98 | message: 99 | type: string 100 | type: object 101 | info: 102 | description: Send data from a Splunk forwarder to the Splunk Forwarder service in 103 | Splunk Cloud Services. 104 | title: Splunk Forwarder Service 105 | version: v2beta1.4 106 | openapi: 3.0.0 107 | paths: 108 | /{tenant}/forwarders/v2beta1/certificates: 109 | delete: 110 | operationId: deleteCertificates 111 | parameters: 112 | - in: path 113 | name: tenant 114 | required: true 115 | schema: 116 | type: string 117 | responses: 118 | "204": 119 | $ref: '#/components/responses/noContentResponse' 120 | "400": 121 | $ref: '#/components/responses/badRequestError' 122 | "401": 123 | $ref: '#/components/responses/unauthorizedError' 124 | "403": 125 | $ref: '#/components/responses/forbiddenError' 126 | "404": 127 | $ref: '#/components/responses/notFoundError' 128 | "429": 129 | $ref: '#/components/responses/tooManyRequestsError' 130 | "500": 131 | $ref: '#/components/responses/internalError' 132 | summary: Removes all certificates on a tenant. 133 | tags: 134 | - Certificates 135 | x-auth-required: true 136 | x-authz-scope: forwarders.certificates.delete 137 | get: 138 | operationId: listCertificates 139 | parameters: 140 | - in: path 141 | name: tenant 142 | required: true 143 | schema: 144 | type: string 145 | responses: 146 | "200": 147 | $ref: '#/components/responses/successListCertificateResponse' 148 | "400": 149 | $ref: '#/components/responses/badRequestError' 150 | "401": 151 | $ref: '#/components/responses/unauthorizedError' 152 | "403": 153 | $ref: '#/components/responses/forbiddenError' 154 | "404": 155 | $ref: '#/components/responses/notFoundError' 156 | "429": 157 | $ref: '#/components/responses/tooManyRequestsError' 158 | "500": 159 | $ref: '#/components/responses/internalError' 160 | summary: Returns a list of all certificates for a tenant. 161 | tags: 162 | - Certificates 163 | x-auth-required: true 164 | x-authz-scope: forwarders.certificates.read 165 | post: 166 | operationId: addCertificate 167 | parameters: 168 | - in: path 169 | name: tenant 170 | required: true 171 | schema: 172 | type: string 173 | requestBody: 174 | content: 175 | application/json: 176 | schema: 177 | $ref: '#/components/schemas/Certificate' 178 | responses: 179 | "200": 180 | $ref: '#/components/responses/successCertUploadResponse' 181 | "400": 182 | $ref: '#/components/responses/badRequestError' 183 | "401": 184 | $ref: '#/components/responses/unauthorizedError' 185 | "403": 186 | $ref: '#/components/responses/forbiddenError' 187 | "404": 188 | $ref: '#/components/responses/notFoundError' 189 | "409": 190 | $ref: '#/components/responses/badRequestError' 191 | "429": 192 | $ref: '#/components/responses/tooManyRequestsError' 193 | "500": 194 | $ref: '#/components/responses/internalError' 195 | summary: Adds a certificate to a vacant slot on a tenant. 196 | tags: 197 | - Certificates 198 | x-auth-required: true 199 | x-authz-scope: forwarders.certificates.write 200 | /{tenant}/forwarders/v2beta1/certificates/{slot}: 201 | delete: 202 | operationId: deleteCertificate 203 | parameters: 204 | - in: path 205 | name: tenant 206 | required: true 207 | schema: 208 | type: string 209 | - in: path 210 | name: slot 211 | required: true 212 | schema: 213 | type: string 214 | responses: 215 | "204": 216 | $ref: '#/components/responses/noContentResponse' 217 | "400": 218 | $ref: '#/components/responses/badRequestError' 219 | "401": 220 | $ref: '#/components/responses/unauthorizedError' 221 | "403": 222 | $ref: '#/components/responses/forbiddenError' 223 | "404": 224 | $ref: '#/components/responses/notFoundError' 225 | "429": 226 | $ref: '#/components/responses/tooManyRequestsError' 227 | "500": 228 | $ref: '#/components/responses/internalError' 229 | summary: Removes a certificate on a particular slot on a tenant. 230 | tags: 231 | - Certificates 232 | x-auth-required: true 233 | x-authz-scope: forwarders.certificates.delete 234 | servers: 235 | - url: / 236 | 237 | # Retrieved from scp-openapi commit 820564ba8a17697d087ff171b14cbad60a716ee3 path: forwarders/v2beta1/openapi.yaml -------------------------------------------------------------------------------- /splunk_sdk/action/v1beta2/gen_action_service_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # Copyright © 2022 Splunk, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 6 | # not use this file except in compliance with the License. You may obtain 7 | # a copy of the License at 8 | # 9 | # [http://www.apache.org/licenses/LICENSE-2.0] 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations 15 | # under the License. 16 | 17 | ############# This file is auto-generated. Do not edit! ############# 18 | 19 | """ 20 | SDC Service: Action Service 21 | 22 | With the Action service in Splunk Cloud Services, you can receive incoming trigger events and use pre-defined action templates to turn these events into meaningful actions. 23 | 24 | OpenAPI spec version: v1beta2.12 (recommended default) 25 | Generated by: https://openapi-generator.tech 26 | """ 27 | 28 | 29 | from requests import Response 30 | from string import Template 31 | from typing import List, Dict 32 | 33 | from splunk_sdk.base_client import handle_response 34 | from splunk_sdk.base_service import BaseService 35 | from splunk_sdk.common.sscmodel import SSCModel, SSCVoidModel 36 | 37 | from splunk_sdk.action.v1beta2.gen_models import Action 38 | from splunk_sdk.action.v1beta2.gen_models import ActionMutable 39 | from splunk_sdk.action.v1beta2.gen_models import ActionResult 40 | from splunk_sdk.action.v1beta2.gen_models import ActionResultEmailDetail 41 | from splunk_sdk.action.v1beta2.gen_models import PublicWebhookKey 42 | from splunk_sdk.action.v1beta2.gen_models import ServiceError 43 | from splunk_sdk.action.v1beta2.gen_models import TriggerEvent 44 | 45 | 46 | class ActionService(BaseService): 47 | """ 48 | Action Service 49 | Version: v1beta2.12 50 | With the Action service in Splunk Cloud Services, you can receive incoming trigger events and use pre-defined action templates to turn these events into meaningful actions. 51 | """ 52 | 53 | def __init__(self, base_client): 54 | super().__init__(base_client) 55 | 56 | def create_action(self, action: Action, query_params: Dict[str, object] = None) -> Action: 57 | """ 58 | Creates an action template. 59 | """ 60 | if query_params is None: 61 | query_params = {} 62 | 63 | path_params = { 64 | } 65 | 66 | path = Template("/action/v1beta2/actions").substitute(path_params) 67 | url = self.base_client.build_url(path) 68 | data = action.to_dict() 69 | response = self.base_client.post(url, json=data, params=query_params) 70 | return handle_response(response, Action) 71 | 72 | def delete_action(self, action_name: str, query_params: Dict[str, object] = None) -> SSCVoidModel: 73 | """ 74 | Removes an action template. 75 | """ 76 | if query_params is None: 77 | query_params = {} 78 | 79 | path_params = { 80 | "action_name": action_name, 81 | } 82 | 83 | path = Template("/action/v1beta2/actions/${action_name}").substitute(path_params) 84 | url = self.base_client.build_url(path) 85 | response = self.base_client.delete(url, params=query_params) 86 | return handle_response(response, ) 87 | 88 | def get_action(self, action_name: str, query_params: Dict[str, object] = None) -> Action: 89 | """ 90 | Returns a specific action template. 91 | """ 92 | if query_params is None: 93 | query_params = {} 94 | 95 | path_params = { 96 | "action_name": action_name, 97 | } 98 | 99 | path = Template("/action/v1beta2/actions/${action_name}").substitute(path_params) 100 | url = self.base_client.build_url(path) 101 | response = self.base_client.get(url, params=query_params) 102 | return handle_response(response, Action) 103 | 104 | def get_action_status(self, action_name: str, status_id: str, query_params: Dict[str, object] = None) -> ActionResult: 105 | """ 106 | Returns the status of an action that was invoked. The status is available for 4 days after the last status change. 107 | """ 108 | if query_params is None: 109 | query_params = {} 110 | 111 | path_params = { 112 | "action_name": action_name, 113 | "status_id": status_id, 114 | } 115 | 116 | path = Template("/action/v1beta2/actions/${action_name}/status/${status_id}").substitute(path_params) 117 | url = self.base_client.build_url(path) 118 | response = self.base_client.get(url, params=query_params) 119 | return handle_response(response, ActionResult) 120 | 121 | def get_action_status_details(self, action_name: str, status_id: str, query_params: Dict[str, object] = None) -> List[ActionResultEmailDetail]: 122 | """ 123 | Returns the status details of the invoked email action. The status is available for 4 days after the last status change. 124 | """ 125 | if query_params is None: 126 | query_params = {} 127 | 128 | path_params = { 129 | "action_name": action_name, 130 | "status_id": status_id, 131 | } 132 | 133 | path = Template("/action/v1beta2/actions/${action_name}/status/${status_id}/details").substitute(path_params) 134 | url = self.base_client.build_url(path) 135 | response = self.base_client.get(url, params=query_params) 136 | return handle_response(response, ActionResultEmailDetail) 137 | 138 | def get_public_webhook_keys(self, query_params: Dict[str, object] = None) -> List[PublicWebhookKey]: 139 | """ 140 | Returns an array of one or two webhook keys. The first key is active. The second key, if present, is expired. 141 | """ 142 | if query_params is None: 143 | query_params = {} 144 | 145 | path_params = { 146 | } 147 | 148 | path = Template("/system/action/v1beta2/webhook/keys").substitute(path_params) 149 | url = self.base_client.build_url(path) 150 | response = self.base_client.get(url, params=query_params) 151 | return handle_response(response, PublicWebhookKey) 152 | 153 | def list_actions(self, query_params: Dict[str, object] = None) -> List[Action]: 154 | """ 155 | Returns the list of action templates. 156 | """ 157 | if query_params is None: 158 | query_params = {} 159 | 160 | path_params = { 161 | } 162 | 163 | path = Template("/action/v1beta2/actions").substitute(path_params) 164 | url = self.base_client.build_url(path) 165 | response = self.base_client.get(url, params=query_params) 166 | return handle_response(response, Action) 167 | 168 | def trigger_action(self, action_name: str, trigger_event: TriggerEvent, query_params: Dict[str, object] = None) -> SSCVoidModel: 169 | """ 170 | Invokes an action. 171 | """ 172 | if query_params is None: 173 | query_params = {} 174 | 175 | path_params = { 176 | "action_name": action_name, 177 | } 178 | 179 | path = Template("/action/v1beta2/actions/${action_name}").substitute(path_params) 180 | url = self.base_client.build_url(path) 181 | data = trigger_event.to_dict() 182 | response = self.base_client.post(url, json=data, params=query_params) 183 | return handle_response(response, ) 184 | 185 | def update_action(self, action_name: str, action_mutable: ActionMutable, query_params: Dict[str, object] = None) -> Action: 186 | """ 187 | Modifies an action template. 188 | """ 189 | if query_params is None: 190 | query_params = {} 191 | 192 | path_params = { 193 | "action_name": action_name, 194 | } 195 | 196 | path = Template("/action/v1beta2/actions/${action_name}").substitute(path_params) 197 | url = self.base_client.build_url(path) 198 | data = action_mutable.to_dict() 199 | response = self.base_client.patch(url, json=data, params=query_params) 200 | return handle_response(response, Action) 201 | 202 | 203 | -------------------------------------------------------------------------------- /splunk_sdk/ingest/v1beta2/gen_ingest_api_api.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | # Copyright © 2022 Splunk, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"): you may 6 | # not use this file except in compliance with the License. You may obtain 7 | # a copy of the License at 8 | # 9 | # [http://www.apache.org/licenses/LICENSE-2.0] 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | # License for the specific language governing permissions and limitations 15 | # under the License. 16 | 17 | ############# This file is auto-generated. Do not edit! ############# 18 | 19 | """ 20 | SDC Service: Ingest API 21 | 22 | Use the Ingest service in Splunk Cloud Services to send event and metrics data, or upload a static file, to Splunk Cloud Services. 23 | 24 | OpenAPI spec version: v1beta2.32 (recommended default) 25 | Generated by: https://openapi-generator.tech 26 | """ 27 | 28 | 29 | from requests import Response 30 | from string import Template 31 | from typing import List, Dict 32 | 33 | from splunk_sdk.base_client import handle_response 34 | from splunk_sdk.base_service import BaseService 35 | from splunk_sdk.common.sscmodel import SSCModel, SSCVoidModel 36 | 37 | from splunk_sdk.ingest.v1beta2.gen_models import Error 38 | from splunk_sdk.ingest.v1beta2.gen_models import Event 39 | from splunk_sdk.ingest.v1beta2.gen_models import HECTokenAccessResponse 40 | from splunk_sdk.ingest.v1beta2.gen_models import HECTokenCreateRequest 41 | from splunk_sdk.ingest.v1beta2.gen_models import HECTokenCreateResponse 42 | from splunk_sdk.ingest.v1beta2.gen_models import HECTokenUpdateRequest 43 | from splunk_sdk.ingest.v1beta2.gen_models import HTTPResponse 44 | from splunk_sdk.ingest.v1beta2.gen_models import List 45 | from splunk_sdk.ingest.v1beta2.gen_models import MetricEvent 46 | from splunk_sdk.ingest.v1beta2.gen_models import UploadSuccessResponse 47 | 48 | 49 | class IngestAPI(BaseService): 50 | """ 51 | Ingest API 52 | Version: v1beta2.32 53 | Use the Ingest service in Splunk Cloud Services to send event and metrics data, or upload a static file, to Splunk Cloud Services. 54 | """ 55 | 56 | def __init__(self, base_client): 57 | super().__init__(base_client) 58 | 59 | def delete_all_collector_tokens(self, query_params: Dict[str, object] = None) -> object: 60 | """ 61 | Delete All dsphec tokens for a given tenant. 62 | """ 63 | if query_params is None: 64 | query_params = {} 65 | 66 | path_params = { 67 | } 68 | 69 | path = Template("/ingest/v1beta2/collector/tokens").substitute(path_params) 70 | url = self.base_client.build_url(path) 71 | response = self.base_client.delete(url, params=query_params) 72 | return handle_response(response, object) 73 | 74 | def delete_collector_token(self, token_name: str, query_params: Dict[str, object] = None) -> object: 75 | """ 76 | Delete dsphec token by name. 77 | """ 78 | if query_params is None: 79 | query_params = {} 80 | 81 | path_params = { 82 | "tokenName": token_name, 83 | } 84 | 85 | path = Template("/ingest/v1beta2/collector/tokens/${tokenName}").substitute(path_params) 86 | url = self.base_client.build_url(path) 87 | response = self.base_client.delete(url, params=query_params) 88 | return handle_response(response, object) 89 | 90 | def get_collector_token(self, token_name: str, query_params: Dict[str, object] = None) -> HECTokenAccessResponse: 91 | """ 92 | Get the metadata of a dsphec token by name. 93 | """ 94 | if query_params is None: 95 | query_params = {} 96 | 97 | path_params = { 98 | "tokenName": token_name, 99 | } 100 | 101 | path = Template("/ingest/v1beta2/collector/tokens/${tokenName}").substitute(path_params) 102 | url = self.base_client.build_url(path) 103 | response = self.base_client.get(url, params=query_params) 104 | return handle_response(response, HECTokenAccessResponse) 105 | 106 | def list_collector_tokens(self, limit: int = None, offset: int = None, query_params: Dict[str, object] = None) -> List[HECTokenAccessResponse]: 107 | """ 108 | List dsphec tokens for a tenant. 109 | """ 110 | if query_params is None: 111 | query_params = {} 112 | if limit is not None: 113 | query_params['limit'] = limit 114 | if offset is not None: 115 | query_params['offset'] = offset 116 | 117 | path_params = { 118 | } 119 | 120 | path = Template("/ingest/v1beta2/collector/tokens").substitute(path_params) 121 | url = self.base_client.build_url(path) 122 | response = self.base_client.get(url, params=query_params) 123 | return handle_response(response, HECTokenAccessResponse) 124 | 125 | def post_collector_tokens(self, hec_token_create_request: HECTokenCreateRequest, query_params: Dict[str, object] = None) -> HECTokenCreateResponse: 126 | """ 127 | Creates dsphec tokens. 128 | """ 129 | if query_params is None: 130 | query_params = {} 131 | 132 | path_params = { 133 | } 134 | 135 | path = Template("/ingest/v1beta2/collector/tokens").substitute(path_params) 136 | url = self.base_client.build_url(path) 137 | data = hec_token_create_request.to_dict() 138 | response = self.base_client.post(url, json=data, params=query_params) 139 | return handle_response(response, HECTokenCreateResponse) 140 | 141 | def post_events(self, event: List[Event] = None, query_params: Dict[str, object] = None) -> HTTPResponse: 142 | """ 143 | Sends events. 144 | """ 145 | if query_params is None: 146 | query_params = {} 147 | 148 | path_params = { 149 | } 150 | 151 | path = Template("/ingest/v1beta2/events").substitute(path_params) 152 | url = self.base_client.build_url(path) 153 | data = [e.to_dict() for e in event] 154 | response = self.base_client.post(url, json=data, params=query_params) 155 | return handle_response(response, HTTPResponse) 156 | 157 | def post_metrics(self, metric_event: List[MetricEvent] = None, query_params: Dict[str, object] = None) -> HTTPResponse: 158 | """ 159 | Sends metric events. 160 | """ 161 | if query_params is None: 162 | query_params = {} 163 | 164 | path_params = { 165 | } 166 | 167 | path = Template("/ingest/v1beta2/metrics").substitute(path_params) 168 | url = self.base_client.build_url(path) 169 | data = [e.to_dict() for e in metric_event] 170 | response = self.base_client.post(url, json=data, params=query_params) 171 | return handle_response(response, HTTPResponse) 172 | 173 | def put_collector_token(self, token_name: str, hec_token_update_request: HECTokenUpdateRequest, query_params: Dict[str, object] = None) -> HECTokenAccessResponse: 174 | """ 175 | Update the metadata of a dsphec token by name. 176 | """ 177 | if query_params is None: 178 | query_params = {} 179 | 180 | path_params = { 181 | "tokenName": token_name, 182 | } 183 | 184 | path = Template("/ingest/v1beta2/collector/tokens/${tokenName}").substitute(path_params) 185 | url = self.base_client.build_url(path) 186 | data = hec_token_update_request.to_dict() 187 | response = self.base_client.put(url, json=data, params=query_params) 188 | return handle_response(response, HECTokenAccessResponse) 189 | 190 | def upload_files(self, filename: str = None) -> UploadSuccessResponse: 191 | """ 192 | Upload a CSV or text file that contains events. The file limit is 1MB or an error is returned. 193 | """ 194 | path_params = { 195 | } 196 | 197 | path = Template("/ingest/v1beta2/files").substitute(path_params) 198 | url = self.base_client.build_url(path) 199 | 200 | # handle file 201 | files = {'upfile': open(filename, 'rb')} 202 | response = self.base_client.post(url, files=files) 203 | return handle_response(response, UploadSuccessResponse) 204 | 205 | 206 | --------------------------------------------------------------------------------