Commit d32aceb8 authored by Spiros Koulouzis's avatar Spiros Koulouzis

added sure_tosca python client

parent 2c92dfaf
...@@ -3,9 +3,12 @@ names==0.3.0 ...@@ -3,9 +3,12 @@ names==0.3.0
networkx==2.4 networkx==2.4
requests==2.23.0 requests==2.23.0
wheel==0.34.2 wheel==0.34.2
pyyaml==5.3 pyyaml==5.3.1
tosca-parser ==1.7.0 matplotlib==3.2.1
matplotlib==3.2.0
ansible==2.9.6 certifi==2019.11.28
ansible-tower-cli==3.3.8 six==1.14.0
python_dateutil==2.8.1
setuptools==46.0.0
urllib3==1.25.8
import os
from _ast import mod
import yaml
yaml.Dumper.ignore_aliases = lambda *args: True
def get_templates_directory_path(file_name):
template_path = "./k8s/"
template_file_path = template_path + file_name
if not os.path.exists(template_file_path):
template_path = "../k8s/"
template_file_path = template_path + file_name
return os.path.abspath(template_file_path)
def get_yaml_data(file_name):
template_file_path = get_templates_directory_path(file_name)
with open(template_file_path, 'r') as stream:
data = yaml.safe_load(stream)
return data
def get_dockers(tosca_template_json):
dockers = []
node_templates = tosca_template_json['topology_template']['node_templates']
for node_name in node_templates:
if node_templates[node_name]['type'] == 'tosca.nodes.ARTICONF.Container.Application.Docker':
docker = {node_name: node_templates[node_name]}
dockers.append(docker)
return dockers
def create_service_definition(docker_name, docker):
k8s_service = get_yaml_data('template-service.yaml')
k8s_service['metadata']['labels']['app'] = docker_name
k8s_service['metadata']['name'] = docker_name
docker_ports = docker[docker_name]['properties']['ports'][0].split(':')
k8s_service['spec']['ports'][0]['port'] = int(docker_ports[1])
k8s_service['spec']['ports'][0]['nodePort'] = int(docker_ports[0])
k8s_service['spec']['selector']['app'] = docker_name
return k8s_service
def create_deployment_definition(docker_name, docker):
docker_ports = docker[docker_name]['properties']['ports'][0].split(':')
deployment = get_yaml_data('template-deployment.yaml')
deployment['metadata']['labels']['app'] = docker_name
deployment['metadata']['name'] = docker_name
deployment['spec']['selector']['matchLabels']['app'] = docker_name
deployment['spec']['template']['metadata']['labels']['app'] = docker_name
deployment['spec']['template']['spec']['containers'][0]['image'] = docker[docker_name]['artifacts']['image']['file']
deployment['spec']['template']['spec']['containers'][0]['ports'][0]['containerPort'] = int(docker_ports[1])
deployment['spec']['template']['spec']['containers'][0]['name'] = docker_name
if docker[docker_name]['properties'] and 'environment' in docker[docker_name]['properties']:
env_list = []
for env in docker[docker_name]['properties']['environment']:
k8s_env = {'name': env, 'value': docker[docker_name]['properties']['environment'][env]}
env_list.append(k8s_env)
deployment['spec']['template']['spec']['containers'][0]['env'] = env_list
return deployment
def get_k8s_definitions(dockers):
k8s_services = []
k8s_deployments = []
definitions = {}
for docker in dockers:
docker_name = next(iter(docker))
k8s_service = create_service_definition(docker_name, docker)
k8s_services.append(k8s_service)
# -----------------------------------------------------------
deployment = create_deployment_definition(docker_name, docker)
k8s_deployments.append(deployment)
# print(yaml.dump(deployment))
definitions['services'] = k8s_services
definitions['deployments'] = k8s_deployments
return definitions
def create_pip_task():
pip_task = {'name': 'install pip modules'}
modules = ['setuptools', 'kubernetes', 'openshift']
pip = {'name': modules}
pip_task['pip'] = pip
return pip_task
def create_service_task(i, services_def):
task = {'name': 'Create a Service object' + str(i)}
k8s = {'state': 'present', 'definition': services_def}
task['k8s'] = k8s
return task
def create_deployment_task(i, deployments_def):
task = {'name': 'Create a deployment object' + str(i)}
k8s = {'state': 'present', 'definition': deployments_def}
task['k8s'] = k8s
return task
def create_namespace_task():
task = {'name': 'create namespace'}
k8s = {'name': 'application', 'api_version': 'v1', 'kind': 'Namespace', 'state': 'present'}
task['k8s'] = k8s
return task
def create_dashboard_task(def_src):
task = {'name': 'create_dashboard'}
k8s = {'state': 'present', 'src': def_src}
task['k8s'] = k8s
return task
def create_admin_dashboard_task():
admin_service_account_def = get_yaml_data("admin_service_account.yaml")
task = {'name': 'create_admin_dashboard'}
k8s = {'state': 'present', 'definition': admin_service_account_def}
task['k8s'] = k8s
return task
def create_admin_cluster_role_binding_task():
admin_cluster_role_binding_def = get_yaml_data("admin_cluster_role_binding.yaml")
task = {'name': 'create_admin_cluster_role_binding'}
k8s = {'state': 'present', 'definition': admin_cluster_role_binding_def}
task['k8s'] = k8s
return task
def create_copy_task(src, dest):
copy = {'src': src, 'dest': dest}
task = {'name': 'copy task src: ' + src + ' dest: ' + dest, 'copy': copy}
return task
def create_get_admin_token_task():
task = {'name': 'get token',
'shell': 'kubectl describe secret $(kubectl get secret | grep admin-user | awk \'{print $1}\')',
'register': 'dashboard_token'}
return task
def create_print_admin_token_task():
var = {'var': 'dashboard_token'}
task = {'name': 'print token',
'debug': var}
return task
def write_ansible_k8s_files(tosca_template_json, tmp_path):
dockers = get_dockers(tosca_template_json)
k8s_definitions = get_k8s_definitions(dockers)
services = k8s_definitions['services']
deployments = k8s_definitions['deployments']
i = 0
tasks = []
pip_task = create_pip_task()
tasks.append(pip_task)
# namespace_task = create_namespace_task()
# tasks.append(namespace_task)
def_src = '/tmp/dashboard.yaml'
copy_task = create_copy_task(get_templates_directory_path('dashboard.yaml'), def_src)
tasks.append(copy_task)
dashboard_task = create_dashboard_task(def_src)
tasks.append(dashboard_task)
dashboard_admin_task = create_admin_dashboard_task()
tasks.append(dashboard_admin_task)
admin_cluster_role_binding_task = create_admin_cluster_role_binding_task()
tasks.append(admin_cluster_role_binding_task)
get_admin_token_task = create_get_admin_token_task()
tasks.append(get_admin_token_task)
print_admin_token_task = create_print_admin_token_task()
tasks.append(print_admin_token_task)
for services_def in services:
task = create_service_task(i, services_def)
i += 1
tasks.append(task)
i = 0
for deployments_def in deployments:
task = create_deployment_task(i, deployments_def)
i += 1
tasks.append(task)
ansible_playbook = []
plays = {'hosts': 'k8-master', 'tasks': tasks}
ansible_playbook.append(plays)
# print(yaml.safe_dump(ansible_playbook))
ansible_playbook_path = tmp_path + '/' + 'k8s_playbook.yml'
with open(ansible_playbook_path, 'w') as file:
documents = yaml.dump(ansible_playbook, file)
return ansible_playbook_path
def get_dashboard_url(vms):
dashboard_tasks_path = get_templates_directory_path('dashboard.yaml')
with open(dashboard_tasks_path, 'r') as stream:
tasks = list(yaml.load_all(stream))
for task in tasks:
if task['kind'] == 'Service' and 'name' in task['metadata'] and task['metadata']['name'] and task['metadata'][
'name'] == 'kubernetes-dashboard':
dashboard_port = task['spec']['ports'][0]['nodePort']
for vm_name in vms:
attributes = vms[vm_name]['attributes']
role = attributes['role']
if role == 'master':
k8_master = attributes['public_ip']
url = 'https://' + k8_master + ':' + str(dashboard_port)
return url
def get_service_urls(vms, tosca_template_json):
dockers = get_dockers(tosca_template_json)
for vm_name in vms:
attributes = vms[vm_name]['attributes']
role = attributes['role']
if role == 'master':
k8_master = attributes['public_ip']
break
urls = {}
for docker in dockers:
docker_name = next(iter(docker))
docker_ports = docker[docker_name]['properties']['ports'][0].split(':')
node_port = int(docker_ports[0])
url = 'http://' + k8_master + ':' + str(node_port)
urls[docker_name] = url
return urls
import logging
logger = logging.getLogger(__name__)
def get_interfaces(tosca_template_dict):
node_templates = tosca_template_dict['topology_template']['node_templates']
for node_name in node_templates:
if node_templates[node_name]['type'] == 'tosca.nodes.ARTICONF.docker.Orchestrator.Kubernetes':
logger.info("Returning interfaces from tosca_template: " + str(node_templates[node_name]['interfaces']))
return node_templates[node_name]['interfaces']
def get_vms(tosca_template_json):
node_templates = tosca_template_json['topology_template']['node_templates']
vms = {}
for node_name in node_templates:
if node_templates[node_name]['type'] == 'tosca.nodes.ARTICONF.VM.Compute':
vms[node_name] = node_templates[node_name]
logger.info("Returning VMs from tosca_template: " + str(vms))
return vms
def add_tokens(tokens, tosca_template_dict):
node_templates = tosca_template_dict['topology_template']['node_templates']
for node_name in node_templates:
if node_templates[node_name]['type'] == 'tosca.nodes.ARTICONF.docker.Orchestrator.Kubernetes':
creds = []
for token_name in tokens:
cred = {'token_type': 'k8s_token', 'token': tokens[token_name], 'user': token_name}
creds.append(cred)
if 'attributes' not in node_templates[node_name]:
node_templates[node_name]['attributes'] = {}
attributes = node_templates[node_name]['attributes']
attributes['tokens'] = creds
return tosca_template_dict
def add_dashboard_url(dashboard_url, tosca_template_dict):
node_templates = tosca_template_dict['topology_template']['node_templates']
for node_name in node_templates:
if node_templates[node_name]['type'] == 'tosca.nodes.ARTICONF.docker.Orchestrator.Kubernetes':
if 'attributes' not in node_templates[node_name]:
node_templates[node_name]['attributes'] = {}
attributes = node_templates[node_name]['attributes']
attributes['dashboard_url'] = dashboard_url
return tosca_template_dict
def add_service_url(serviceu_urls, tosca_template_dict):
node_templates = tosca_template_dict['topology_template']['node_templates']
for node_name in node_templates:
if node_templates[node_name]['type'] == 'tosca.nodes.ARTICONF.Container.Application.Docker':
if 'attributes' not in node_templates[node_name]:
node_templates[node_name]['attributes'] = {}
attributes = node_templates[node_name]['attributes']
attributes['service_url'] = serviceu_urls[node_name]
return tosca_template_dict
coverage==5.0.4
nose==1.3.7
pluggy==0.13.1
py==1.8.1
randomize==0.14
version: '3' version: '3'
services: services:
#postgres:
#image: "postgres:12.2"
#environment:
#POSTGRES_USER: awx
#POSTGRES_PASSWORD: awxpass
#POSTGRES_DB: awx
#POSTGRES_HOST_AUTH_METHOD: trust
#ports:
#- "5432:5432"
#volumes:
#- db-data:/var/lib/postgresql/data
rabbit: rabbit:
image: rabbitmq:3.8-management image: rabbitmq:3.8-management
...@@ -19,66 +8,11 @@ services: ...@@ -19,66 +8,11 @@ services:
- "15672:15672" - "15672:15672"
- "4369:4369" - "4369:4369"
- "15671:15671" - "15671:15671"
#environment:
#RABBITMQ_DEFAULT_VHOST: awx
#memcached:
#image: "memcached:alpine"
#awx_web:
#image: "geerlingguy/awx_web:latest"
##image: "ansible/awx_web:latest"
#depends_on:
#- rabbit
#- memcached
#- postgres
#ports:
#- "8051-8052:8051-8052"
##volumes:
##- /tmp/SECRET_KEY:/etc/tower/SECRET_KEY #echo aabbcc > /tmp/SECRET_KEY
#user: root
#environment:
#SECRET_KEY: aabbcc
#DATABASE_USER: awx
#DATABASE_PASSWORD: awxpass
#DATABASE_NAME: awx
#DATABASE_PORT: 5432
#DATABASE_HOST: postgres
#RABBITMQ_USER: guest
#RABBITMQ_PASSWORD: guest
#RABBITMQ_HOST: rabbit
#RABBITMQ_PORT: 5672
#RABBITMQ_VHOST: awx
#MEMCACHED_HOST: memcached
#MEMCACHED_PORT: 11211
#awx_task: semaphore:
#image: "geerlingguy/awx_task:latest" ports:
##image: "ansible/awx_task:latest" - "30003:3000"
##volumes: image: ansiblesemaphore/semaphore
##- /tmp/SECRET_KEY:/etc/tower/SECRET_KEY #echo aabbcc > /tmp/SECRET_KEY
#depends_on:
#- rabbit
#- memcached
#- awx_web
#- postgres
#hostname: awx
#user: root
#environment:
#SECRET_KEY: aabbcc
#DATABASE_USER: awx
#DATABASE_PASSWORD: awxpass
#DATABASE_NAME: awx
#DATABASE_PORT: 5432
#DATABASE_HOST: postgres
#RABBITMQ_USER: guest
#RABBITMQ_PASSWORD: guest
#RABBITMQ_HOST: rabbit
#RABBITMQ_PORT: 5672
#RABBITMQ_VHOST: awx
#MEMCACHED_HOST: memcached
#MEMCACHED_PORT: 11211
logspout: logspout:
...@@ -96,12 +30,7 @@ services: ...@@ -96,12 +30,7 @@ services:
image: mongo:4 image: mongo:4
ports: ports:
- "27017:27017" - "27017:27017"
#jupyter:
#ports:
#- "30003:8888"
#image: jupyter_base-notebook
manager: manager:
depends_on: depends_on:
......
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
venv/
.python-version
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
#Ipython Notebook
.ipynb_checkpoints
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8 (sure_tosca-client_python_stubs)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/sure_tosca-client_python_stubs.iml" filepath="$PROJECT_DIR$/.idea/sure_tosca-client_python_stubs.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.8 (sure_tosca-client_python_stubs)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="3f84153d-6ed1-4691-94d6-53105266f15e" name="Default Changelist" comment="">
<change beforePath="$PROJECT_DIR$/../deployer/requirements.txt" beforeDir="false" afterPath="$PROJECT_DIR$/../deployer/requirements.txt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../deployer/service/__init__.py" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/../deployer/service/k8s_service.py" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/../deployer/service/tosca.py" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/../docker-compose.yml" beforeDir="false" afterPath="$PROJECT_DIR$/../docker-compose.yml" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/.." />
</component>
<component name="ProjectId" id="1ZRtB1w8qQYGLil0tptWk3vA7iM" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showExcludedFiles" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
<property name="last_opened_file_path" value="$PROJECT_DIR$/../sure_tosca-flask-server" />
<property name="settings.editor.selected.configurable" value="com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable" />
</component>
<component name="RunManager">
<configuration name="Unittests in test_default_api.py" type="tests" factoryName="Unittests" temporary="true" nameIsGenerated="true">
<module name="sure_tosca-client_python_stubs" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/test" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="_new_additionalArguments" value="&quot;&quot;" />
<option name="_new_target" value="&quot;$PROJECT_DIR$/test/test_default_api.py&quot;" />
<option name="_new_targetType" value="&quot;PATH&quot;" />
<method v="2" />
</configuration>
<recent_temporary>
<list>
<item itemvalue="Python tests.Unittests in test_default_api.py" />
</list>
</recent_temporary>
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="3f84153d-6ed1-4691-94d6-53105266f15e" name="Default Changelist" comment="" />
<created>1584813594976</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1584813594976</updated>
</task>
<servers />
</component>
<component name="WindowStateProjectService">
<state x="723" y="257" width="530" height="598" key="FileChooserDialogImpl" timestamp="1584814061190">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state x="723" y="257" width="530" height="598" key="FileChooserDialogImpl/67.34.1853.1046@67.34.1853.1046" timestamp="1584814061190" />
<state width="1825" height="134" key="GridCell.Tab.0.bottom" timestamp="1584900161062">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state width="1825" height="134" key="GridCell.Tab.0.bottom/67.34.1853.1046@67.34.1853.1046" timestamp="1584900161062" />
<state width="1825" height="134" key="GridCell.Tab.0.center" timestamp="1584900161062">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state width="1825" height="134" key="GridCell.Tab.0.center/67.34.1853.1046@67.34.1853.1046" timestamp="1584900161062" />
<state width="1825" height="134" key="GridCell.Tab.0.left" timestamp="1584900161062">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state width="1825" height="134" key="GridCell.Tab.0.left/67.34.1853.1046@67.34.1853.1046" timestamp="1584900161062" />
<state width="1825" height="134" key="GridCell.Tab.0.right" timestamp="1584900161062">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state width="1825" height="134" key="GridCell.Tab.0.right/67.34.1853.1046@67.34.1853.1046" timestamp="1584900161062" />
<state width="1825" height="372" key="GridCell.Tab.1.bottom" timestamp="1584815771481">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state width="1825" height="372" key="GridCell.Tab.1.bottom/67.34.1853.1046@67.34.1853.1046" timestamp="1584815771481" />
<state width="1825" height="372" key="GridCell.Tab.1.center" timestamp="1584815771481">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state width="1825" height="372" key="GridCell.Tab.1.center/67.34.1853.1046@67.34.1853.1046" timestamp="1584815771481" />
<state width="1825" height="372" key="GridCell.Tab.1.left" timestamp="1584815771481">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state width="1825" height="372" key="GridCell.Tab.1.left/67.34.1853.1046@67.34.1853.1046" timestamp="1584815771481" />
<state width="1825" height="372" key="GridCell.Tab.1.right" timestamp="1584815771481">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state width="1825" height="372" key="GridCell.Tab.1.right/67.34.1853.1046@67.34.1853.1046" timestamp="1584815771481" />
<state x="359" y="103" key="SettingsEditor" timestamp="1584813615342">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state x="359" y="103" key="SettingsEditor/67.34.1853.1046@67.34.1853.1046" timestamp="1584813615342" />
<state x="563" y="235" width="1053" height="732" key="find.popup" timestamp="1584900160970">
<screen x="67" y="34" width="1853" height="1046" />
</state>
<state x="563" y="235" width="1053" height="732" key="find.popup/67.34.1853.1046@67.34.1853.1046" timestamp="1584900160970" />
</component>
</project>
\ No newline at end of file
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
# ref: https://docs.travis-ci.com/user/languages/python
language: python
python:
- "3.8"
# command to install dependencies
install: "pip install -r requirements.txt"
# command to run tests
script: nosetests
# sure_tosca_client
TOSCA Simple qUeRy sErvice (SURE).
This Python package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project:
- API version: 1.0.0
- Package version: 1.0.0
- Build package: io.swagger.codegen.languages.PythonClientCodegen
## Requirements.
Python 2.7 and 3.4+
## Installation & Usage
### pip install
If the python package is hosted on Github, you can install directly from Github
```sh
pip install git+https://github.com//.git
```
(you may need to run `pip` with root permission: `sudo pip install git+https://github.com//.git`)
Then import the package:
```python
import swagger_client
```
### Setuptools
Install via [Setuptools](http://pypi.python.org/pypi/setuptools).
```sh
python setup.py install --user
```
(or `sudo python setup.py install` to install the package for all users)
Then import the package:
```python
import swagger_client
```
## Getting Started
Please follow the [installation procedure](#installation--usage) and then run the following:
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint
# create an instance of the API class
api_instance = swagger_client.DefaultApi(swagger_client.ApiClient(configuration))
id = 'id_example' # str | ID of topolog template uplodaed
node_name = 'node_name_example' # str | node_name
try:
#
api_response = api_instance.get_all_ancestor_properties(id, node_name)
pprint(api_response)
except ApiException as e:
print("Exception when calling DefaultApi->get_all_ancestor_properties: %s\n" % e)
```
## Documentation for API Endpoints
All URIs are relative to *https://localhost/tosca-sure/1.0.0*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*DefaultApi* | [**get_all_ancestor_properties**](docs/DefaultApi.md#get_all_ancestor_properties) | **GET** /tosca_template/{id}/topology_template/node_templates/{node_name}/ancestors_properties |
*DefaultApi* | [**get_all_ancestor_types**](docs/DefaultApi.md#get_all_ancestor_types) | **GET** /tosca_template/{id}/topology_template/node_templates/{node_name}/ancestors_types |
*DefaultApi* | [**get_ancestors_requirements**](docs/DefaultApi.md#get_ancestors_requirements) | **GET** /tosca_template/{id}/topology_template/node_templates/{node_name}/ancestors_requirements |
*DefaultApi* | [**get_dsl_definitions**](docs/DefaultApi.md#get_dsl_definitions) | **GET** /tosca_template/{id}/dsl_definitions |
*DefaultApi* | [**get_imports**](docs/DefaultApi.md#get_imports) | **GET** /tosca_template/{id}/imports |
*DefaultApi* | [**get_node_outputs**](docs/DefaultApi.md#get_node_outputs) | **GET** /tosca_template/{id}/topology_template/node_templates/{node_name}/outputs |
*DefaultApi* | [**get_node_properties**](docs/DefaultApi.md#get_node_properties) | **GET** /tosca_template/{id}/topology_template/node_templates/{node_name}/properties |
*DefaultApi* | [**get_node_requirements**](docs/DefaultApi.md#get_node_requirements) | **GET** /tosca_template/{id}/topology_template/node_templates/{node_name}/requirements |
*DefaultApi* | [**get_node_templates**](docs/DefaultApi.md#get_node_templates) | **GET** /tosca_template/{id}/topology_template/node_templates |
*DefaultApi* | [**get_node_type_name**](docs/DefaultApi.md#get_node_type_name) | **GET** /tosca_template/{id}/topology_template/node_templates/{node_name}/type_name |
*DefaultApi* | [**get_parent_type_name**](docs/DefaultApi.md#get_parent_type_name) | **GET** /tosca_template/{id}/topology_template/node_templates/{node_name}/derived_from |
*DefaultApi* | [**get_related_nodes**](docs/DefaultApi.md#get_related_nodes) | **GET** /tosca_template/{id}/topology_template/node_templates/{node_name}/related |
*DefaultApi* | [**get_relationship_templates**](docs/DefaultApi.md#get_relationship_templates) | **GET** /tosca_template/{id}/relationship_templates |
*DefaultApi* | [**get_topology_template**](docs/DefaultApi.md#get_topology_template) | **GET** /tosca_template/{id}/topology_template |
*DefaultApi* | [**get_tosca_template**](docs/DefaultApi.md#get_tosca_template) | **GET** /tosca_template/{id} |
*DefaultApi* | [**get_types**](docs/DefaultApi.md#get_types) | **GET** /tosca_template/{id}/types |
*DefaultApi* | [**set_node_properties**](docs/DefaultApi.md#set_node_properties) | **PUT** /tosca_template/{id}/topology_template/node_templates/{node_name}/properties |
*DefaultApi* | [**upload_tosca_template**](docs/DefaultApi.md#upload_tosca_template) | **POST** /tosca_template | upload a tosca template description file
## Documentation For Models
- [NodeTemplate](docs/NodeTemplate.md)
- [NodeTemplateMap](docs/NodeTemplateMap.md)
- [TopologyTemplate](docs/TopologyTemplate.md)
- [ToscaTemplate](docs/ToscaTemplate.md)
## Documentation For Authorization
All endpoints do not require authorization.
## Author
S.Koulouzis@uva.nl
This diff is collapsed.
# NodeTemplate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**derived_from** | **str** | | [optional]
**properties** | **dict(str, object)** | | [optional]
**requirements** | **list[dict(str, object)]** | | [optional]
**interfaces** | **dict(str, object)** | | [optional]
**capabilities** | **dict(str, object)** | | [optional]
**type** | **str** | | [optional]
**description** | **str** | | [optional]
**directives** | **list[str]** | | [optional]
**attributes** | **dict(str, object)** | | [optional]
**artifacts** | **dict(str, object)** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
# NodeTemplateMap
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**name** | **str** | | [optional]
**node_template** | [**NodeTemplate**](NodeTemplate.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
# TopologyTemplate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**description** | **str** | | [optional]
**inputs** | **dict(str, str)** | | [optional]
**node_templates** | [**dict(str, NodeTemplate)**](NodeTemplate.md) | | [optional]
**relationship_templates** | **dict(str, object)** | | [optional]
**outputs** | **dict(str, object)** | | [optional]
**groups** | **dict(str, object)** | | [optional]
**substitution_mappings** | **dict(str, object)** | | [optional]
**policies** | **list[dict(str, object)]** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
# ToscaTemplate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**tosca_definitions_version** | **str** | | [optional]
**tosca_default_namespace** | **str** | | [optional]
**template_name** | **str** | | [optional]
**topology_template** | [**TopologyTemplate**](TopologyTemplate.md) | | [optional]
**template_author** | **str** | | [optional]
**template_version** | **str** | | [optional]
**description** | **str** | | [optional]
**imports** | **list[dict(str, object)]** | | [optional]
**dsl_definitions** | **dict(str, object)** | | [optional]
**node_types** | **dict(str, object)** | | [optional]
**relationship_types** | **dict(str, object)** | | [optional]
**relationship_templates** | **dict(str, object)** | | [optional]
**capability_types** | **dict(str, object)** | | [optional]
**artifact_types** | **dict(str, object)** | | [optional]
**data_types** | **dict(str, object)** | | [optional]
**interface_types** | **dict(str, object)** | | [optional]
**policy_types** | **dict(str, object)** | | [optional]
**group_types** | **dict(str, object)** | | [optional]
**repositories** | **dict(str, object)** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
git_user_id=""
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id=""
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note=""
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'
certifi==2019.11.28
six==1.14.0
python_dateutil==2.5.3
setuptools==46
urllib3==1.25.8
numpy==1.18.2
# coding: utf-8
"""
tosca-sure
TOSCA Simple qUeRy sErvice (SURE). # noqa: E501
OpenAPI spec version: 1.0.0
Contact: S.Koulouzis@uva.nl
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from setuptools import setup, find_packages # noqa: H301
NAME = "sure_tosca_client"
VERSION = "1.0.0"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = [
"certifi==2019.11.28",
"six==1.14.0",
"python_dateutl==2.5.3",
"setuptools==46",
"urllib3==1.25.8",
"numpy==1.18.2"
]
setup(
name=NAME,
version=VERSION,
description="tosca-sure",
author_email="S.Koulouzis@uva.nl",
url="",
keywords=["Swagger", "tosca-sure"],
install_requires=REQUIRES,
packages=find_packages(),
include_package_data=True,
long_description="""\
TOSCA Simple qUeRy sErvice (SURE). # noqa: E501
"""
)
# coding: utf-8
# flake8: noqa
"""
tosca-sure
TOSCA Simple qUeRy sErvice (SURE). # noqa: E501
OpenAPI spec version: 1.0.0
Contact: S.Koulouzis@uva.nl
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import apis into sdk package
from sure_tosca_client.api.default_api import DefaultApi
# import ApiClient
from sure_tosca_client.api_client import ApiClient
from sure_tosca_client.configuration import Configuration
# import models into sdk package
from sure_tosca_client.models.node_template import NodeTemplate
from sure_tosca_client.models.node_template_map import NodeTemplateMap
from sure_tosca_client.models.topology_template import TopologyTemplate
from sure_tosca_client.models.tosca_template import ToscaTemplate
from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from sure_tosca_client.api.default_api import DefaultApi
This diff is collapsed.
# coding: utf-8
"""
tosca-sure
TOSCA Simple qUeRy sErvice (SURE). # noqa: E501
OpenAPI spec version: 1.0.0
Contact: S.Koulouzis@uva.nl
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import copy
import logging
import multiprocessing
import sys
import urllib3
import six
from six.moves import http_client as httplib
class Configuration(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Ref: https://github.com/swagger-api/swagger-codegen
Do not edit the class manually.
"""
_default = None
def __init__(self):
"""Constructor"""
if self._default:
for key in self._default.__dict__.keys():
self.__dict__[key] = copy.copy(self._default.__dict__[key])
return
# Default Base url
self.host = "https://localhost/tosca-sure/1.0.0"
# Temp file folder for downloading files
self.temp_folder_path = None
# Authentication Settings
# dict to store API key(s)
self.api_key = {}
# dict to store API prefix (e.g. Bearer)
self.api_key_prefix = {}
# function to refresh API key if expired
self.refresh_api_key_hook = None
# Username for HTTP basic authentication
self.username = ""
# Password for HTTP basic authentication
self.password = ""
# Logging Settings
self.logger = {"package_logger": logging.getLogger("swagger_client"),
"urllib3_logger": logging.getLogger("urllib3")}
# Log format
self.logger_format = '%(asctime)s %(levelname)s %(message)s'
# Log stream handler
self.logger_stream_handler = None
# Log file handler
self.logger_file_handler = None
# Debug file location
self.logger_file = None
# Debug switch
self.debug = False
# SSL/TLS verification
# Set this to false to skip verifying SSL certificate when calling API
# from https server.
self.verify_ssl = True
# Set this to customize the certificate file to verify the peer.
self.ssl_ca_cert = None
# client certificate file
self.cert_file = None
# client key file
self.key_file = None
# Set this to True/False to enable/disable SSL hostname verification.
self.assert_hostname = None
# urllib3 connection pool's maximum number of connections saved
# per pool. urllib3 uses 1 connection as default value, but this is
# not the best value when you are making a lot of possibly parallel
# requests to the same host, which is often the case here.
# cpu_count * 5 is used as default value to increase performance.
self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
# Proxy URL
self.proxy = None
# Safe chars for path_param
self.safe_chars_for_path_param = ''
@classmethod
def set_default(cls, default):
cls._default = default
@property
def logger_file(self):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
return self.__logger_file
@logger_file.setter
def logger_file(self, value):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
self.__logger_file = value
if self.__logger_file:
# If set logging file,
# then add file handler and remove stream handler.
self.logger_file_handler = logging.FileHandler(self.__logger_file)
self.logger_file_handler.setFormatter(self.logger_formatter)
for _, logger in six.iteritems(self.logger):
logger.addHandler(self.logger_file_handler)
if self.logger_stream_handler:
logger.removeHandler(self.logger_stream_handler)
else:
# If not set logging file,
# then add stream handler and remove file handler.
self.logger_stream_handler = logging.StreamHandler()
self.logger_stream_handler.setFormatter(self.logger_formatter)
for _, logger in six.iteritems(self.logger):
logger.addHandler(self.logger_stream_handler)
if self.logger_file_handler:
logger.removeHandler(self.logger_file_handler)
@property
def debug(self):
"""Debug status
:param value: The debug status, True or False.
:type: bool
"""
return self.__debug
@debug.setter
def debug(self, value):
"""Debug status
:param value: The debug status, True or False.
:type: bool
"""
self.__debug = value
if self.__debug:
# if debug status is True, turn on debug logging
for _, logger in six.iteritems(self.logger):
logger.setLevel(logging.DEBUG)
# turn on httplib debug
httplib.HTTPConnection.debuglevel = 1
else:
# if debug status is False, turn off debug logging,
# setting log level to default `logging.WARNING`
for _, logger in six.iteritems(self.logger):
logger.setLevel(logging.WARNING)
# turn off httplib debug
httplib.HTTPConnection.debuglevel = 0
@property
def logger_format(self):
"""The logger format.
The logger_formatter will be updated when sets logger_format.
:param value: The format string.
:type: str
"""
return self.__logger_format
@logger_format.setter
def logger_format(self, value):
"""The logger format.
The logger_formatter will be updated when sets logger_format.
:param value: The format string.
:type: str
"""
self.__logger_format = value
self.logger_formatter = logging.Formatter(self.__logger_format)
def get_api_key_with_prefix(self, identifier):
"""Gets API key (with prefix if set).
:param identifier: The identifier of apiKey.
:return: The token for api key authentication.
"""
if self.refresh_api_key_hook:
self.refresh_api_key_hook(self)
key = self.api_key.get(identifier)
if key:
prefix = self.api_key_prefix.get(identifier)
if prefix:
return "%s %s" % (prefix, key)
else:
return key
def get_basic_auth_token(self):
"""Gets HTTP basic authentication header (string).
:return: The token for basic HTTP authentication.
"""
return urllib3.util.make_headers(
basic_auth=self.username + ':' + self.password
).get('authorization')
def auth_settings(self):
"""Gets Auth Settings dict for api client.
:return: The Auth Settings information dict.
"""
return {
}
def to_debug_report(self):
"""Gets the essential information for debugging.
:return: The report for debugging.
"""
return "Python SDK Debug Report:\n"\
"OS: {env}\n"\
"Python Version: {pyversion}\n"\
"Version of the API: 1.0.0\n"\
"SDK Package Version: 1.0.0".\
format(env=sys.platform, pyversion=sys.version)
# coding: utf-8
# flake8: noqa
"""
tosca-sure
TOSCA Simple qUeRy sErvice (SURE). # noqa: E501
OpenAPI spec version: 1.0.0
Contact: S.Koulouzis@uva.nl
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import models into model package
from sure_tosca_client.models.node_template import NodeTemplate
from sure_tosca_client.models.node_template_map import NodeTemplateMap
from sure_tosca_client.models.topology_template import TopologyTemplate
from sure_tosca_client.models.tosca_template import ToscaTemplate
# coding: utf-8
"""
tosca-sure
TOSCA Simple qUeRy sErvice (SURE). # noqa: E501
OpenAPI spec version: 1.0.0
Contact: S.Koulouzis@uva.nl
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class NodeTemplateMap(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'name': 'str',
'node_template': 'NodeTemplate'
}
attribute_map = {
'name': 'name',
'node_template': 'nodeTemplate'
}
def __init__(self, name=None, node_template=None): # noqa: E501
"""NodeTemplateMap - a model defined in Swagger""" # noqa: E501
self._name = None
self._node_template = None
self.discriminator = None
if name is not None:
self.name = name
if node_template is not None:
self.node_template = node_template
@property
def name(self):
"""Gets the name of this NodeTemplateMap. # noqa: E501
:return: The name of this NodeTemplateMap. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this NodeTemplateMap.
:param name: The name of this NodeTemplateMap. # noqa: E501
:type: str
"""
self._name = name
@property
def node_template(self):
"""Gets the node_template of this NodeTemplateMap. # noqa: E501
:return: The node_template of this NodeTemplateMap. # noqa: E501
:rtype: NodeTemplate
"""
return self._node_template
@node_template.setter
def node_template(self, node_template):
"""Sets the node_template of this NodeTemplateMap.
:param node_template: The node_template of this NodeTemplateMap. # noqa: E501
:type: NodeTemplate
"""
self._node_template = node_template
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(NodeTemplateMap, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, NodeTemplateMap):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
This diff is collapsed.
coverage==5.0.4
nose==1.3.7
pluggy==0.13.1
py==1.8.1
randomize==0.14
This diff is collapsed.
# coding: utf-8
"""
tosca-sure
TOSCA Simple qUeRy sErvice (SURE). # noqa: E501
OpenAPI spec version: 1.0.0
Contact: S.Koulouzis@uva.nl
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import sure_tosca_client
from sure_tosca_client.models.node_template import NodeTemplate # noqa: E501
from sure_tosca_client.rest import ApiException
class TestNodeTemplate(unittest.TestCase):
"""NodeTemplate unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testNodeTemplate(self):
"""Test NodeTemplate"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_client.models.node_template.NodeTemplate() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
# coding: utf-8
"""
tosca-sure
TOSCA Simple qUeRy sErvice (SURE). # noqa: E501
OpenAPI spec version: 1.0.0
Contact: S.Koulouzis@uva.nl
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import sure_tosca_client
from sure_tosca_client.models.node_template_map import NodeTemplateMap # noqa: E501
from sure_tosca_client.rest import ApiException
class TestNodeTemplateMap(unittest.TestCase):
"""NodeTemplateMap unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testNodeTemplateMap(self):
"""Test NodeTemplateMap"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_client.models.node_template_map.NodeTemplateMap() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment