contrail-api-cli Documentation - Read the Docs · contrail-api-cli is a command line tool which...
Transcript of contrail-api-cli Documentation - Read the Docs · contrail-api-cli is a command line tool which...
contrail-api-cli DocumentationRelease 0.4.0rc1
Jean-Philippe Braun
Feb 26, 2020
Contents
1 Connecting to the API server 31.1 Basic auth on localhost:8095 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Keystone auth on API_SERVER:8082 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 Base commands 52.1 help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 man . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.3 ls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.4 du . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.5 cd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.6 cat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.7 tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.8 rm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.9 edit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.10 schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.11 ln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.12 relative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.13 kv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3 Advanced usage 133.1 pipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.2 direct-call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.3 wildcard resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.4 loading commands from other namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.5 python from the shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.6 python script execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4 Howto write a command 154.1 Setup your project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154.2 Hello world command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5 Using Resource and Collection API in commands 195.1 Resource and Collection objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195.2 virtual-router resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195.3 List command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205.4 Add command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215.5 Del command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
i
6 API 236.1 Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236.2 Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256.3 Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276.4 Utils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
7 Indices and tables 31
Python Module Index 33
Index 35
ii
contrail-api-cli Documentation, Release 0.4.0rc1
contrail-api-cli is a command line tool which interact with the contrail API server.
contrail-api-cli provides a shell like experience with unix style commands to browse or modify API resources andcollections.
Contents 1
contrail-api-cli Documentation, Release 0.4.0rc1
2 Contents
CHAPTER 1
Connecting to the API server
1.1 Basic auth on localhost:8095
$ contrail-api-cli --os-auth-plugin http \\--os-username admin \\--os-password paswword \\--port 8095 \\shell
from contrail_api_cli.client import SessionLoaderfrom contrail_api_cli.resource import Collectionfrom contrail_api_cli.context import Contextfrom contrail_api_cli.schema import DummySchema
session = SessionLoader().make(host="localhost",port=8095,os_username="admin",os_password="password",os_cacert=None,os_cert=None,insecure=False,timeout=1)
Context().session = sessionContext().schema = DummySchema()
print(len(Collection('virtual-network')))
3
contrail-api-cli Documentation, Release 0.4.0rc1
1.2 Keystone auth on API_SERVER:8082
$ contrail-api-cli --os-auth-plugin v2password \\--os-username admin \\--os-password paswword \\--os-tenant-name tenant_name \\--os-auth-url https://keystone:5000/v2.0/ \\shell
Note: All parameters can be set in enviroment variables. For example, –os-auth-plugin looks for$OS_AUTH_PLUGIN.
–port and –host correspond to $CONTRAIL_API_(HOST|PORT)
4 Chapter 1. Connecting to the API server
CHAPTER 2
Base commands
All commands provides a –help option.
2.1 help
List all available commands.
2.2 man
class contrail_api_cli.commands.man.Man(name)Bases: contrail_api_cli.command.Command
Show command documentation.
To improve the output you can install the rst2ansi package.
2.3 ls
class contrail_api_cli.commands.ls.Ls(name)Bases: contrail_api_cli.command.Command
List resources and collections.
# list API collectionsadmin@localhost:/> lsdomainglobal-vrouter-configinstance-ipnetwork-policyvirtual-DNS-record
(continues on next page)
5
contrail-api-cli Documentation, Release 0.4.0rc1
(continued from previous page)
route-targetloadbalancer-listenerfloating-ipfloating-ip-poolphysical-router[...]
# list collectionadmin@localhost:/> ls global-system-configglobal-system-config/d6820999-c8fe-45ae-acb2-48aebddb3b7d
# long formatadmin@localhost:/> ls -l virtual-networkvirtual-network/49d00de8-4351-446f-b6ee-d16dec3de413 default-domain:admin:net2virtual-network/5a9fbd42-a730-42f7-9947-be8a5d808b70 default-domain:admin:net1virtual-network/e3148147-164e-4194-8507-a58eefe072bd default-domain:default-→˓project:default-virtual-networkvirtual-network/ba2170ce-741c-4361-ad88-f2d97162faf2 default-domain:default-→˓project:ip-fabricvirtual-network/e82ae164-f78a-4766-8ba2-7cb68dacaecb default-domain:default-→˓project:__link_local__
# parametrized output formatadmin@localhost:/> ls -l -c instance_ip_address instance-ipinstance-ip/f9d25887-2765-4ba0-bf45-54b9dbc5874a 192.168.20.1instance-ip/deb82100-00bb-4b5c-8495-4bbe34b5fab8 192.168.21.1instance-ip/2f5c047d-0a9c-4709-bcfa-d710ac68cc22 192.168.10.3instance-ip/04cb356a-fb1f-44fa-bb2f-d0f0dd4eedfd 192.168.20.3
# filter by parent_uuidadmin@localhost:/> ls -l -p d0afbb0b-dd83-4a33-a673-9cb2b244e804 virtual-networkvirtual-network/5a9fbd42-a730-42f7-9947-be8a5d808b70 default-domain:admin:net1virtual-network/49d00de8-4351-446f-b6ee-d16dec3de413 default-domain:admin:net2
# filter by attributeadmin@localhost:/> ls -l -f instance_ip_address=192.168.20.1 instance-ipinstance-ip/f9d25887-2765-4ba0-bf45-54b9dbc5874a f9d25887-2765-4ba0-bf45-→˓54b9dbc5874a
2.4 du
class contrail_api_cli.commands.du.Du(name)Bases: contrail_api_cli.command.Command
Count resources of a collection.
admin@localhost:/> du virtual-network6
2.5 cd
class contrail_api_cli.commands.shell.Cd(name)Bases: contrail_api_cli.command.Command
6 Chapter 2. Base commands
contrail-api-cli Documentation, Release 0.4.0rc1
Change current context.
admin@localhost:/> cd virtual-networkadmin@localhost:/virtual-network> ls1095e416-b7cd-4c65-b0a3-631e8263a4dd49d00de8-4351-446f-b6ee-d16dec3de413[...]admin@localhost:/virtual-network> ls instance-ipNo resource foundadmin@localhost:/virtual-network> ls /instance-ip/instance-ip/f9d25887-2765-4ba0-bf45-54b9dbc5874a/instance-ip/deb82100-00bb-4b5c-8495-4bbe34b5fab8/instance-ip/2f5c047d-0a9c-4709-bcfa-d710ac68cc22/instance-ip/04cb356a-fb1f-44fa-bb2f-d0f0dd4eedfd
2.6 cat
class contrail_api_cli.commands.cat.Cat(name)Bases: contrail_api_cli.command.Command
Print resource details in json format.
admin@localhost:/> cat instance-ip/2f5c047d-0a9c-4709-bcfa-d710ac68cc22{"display_name": "2f5c047d-0a9c-4709-bcfa-d710ac68cc22","fq_name": [
"2f5c047d-0a9c-4709-bcfa-d710ac68cc22"],"href": "http://localhost:8082/instance-ip/2f5c047d-0a9c-4709-bcfa-d710ac68cc22
→˓","instance_ip_address": "192.168.10.3","instance_ip_family": "v4","name": "2f5c047d-0a9c-4709-bcfa-d710ac68cc22","subnet_uuid": "96b51c74-090b-4c3e-9f73-ecd8efac294d","uuid": "2f5c047d-0a9c-4709-bcfa-d710ac68cc22",[...]
}
2.7 tree
class contrail_api_cli.commands.tree.Tree(name)Bases: contrail_api_cli.command.Command
Show tree of references of a resource.
# tree of back / childs referenceslocalhost:/> tree service-instance/f8e191c5-83fa-47f1-a242-e8ad7cab46c0service-instance/f8e191c5-83fa-47f1-a242-e8ad7cab46c0 default-→˓domain:project:a2fb6399-18ce-44ec-839d-d373221a6a8f
loadbalancer/a2fb6399-18ce-44ec-839d-d373221a6a8f default-→˓domain:project:lbv2
loadbalancer-listener/434b7b92-b68a-41f6-8321-8e7e2519d483 default-→˓domain:project:lbv2_listener
loadbalancer-pool/82cce54d-b13a-427c-bac6-fb7e976bcf5f default-→˓domain:project:lbv2_pool (continues on next page)
2.6. cat 7
contrail-api-cli Documentation, Release 0.4.0rc1
(continued from previous page)
loadbalancer-member/cc6e4c32-92c1-4668-879d-d6802f8ad3de default-→˓domain:project:lbv2_pool:cc6e4c32-92c1-4668-879d-d6802f8ad3de
loadbalancer-member/fb30633f-407b-461d-bf20-3ac9f0cbe504 default-→˓domain:project:lbv2_pool:fb30633f-407b-461d-bf20-3ac9f0cbe504
virtual-machine/68243a56-298d-4354-a077-b41b6bb55b7c default-→˓domain__project__a2fb6399-18ce-44ec-839d-d373221a6a8f__1
virtual-machine-interface/4a0bf808-19d7-48e9-b076-54064bebaf2e default-→˓domain:project:default-domain__project__a2fb6399-18ce-44ec-839d-d373221a6a8f__1_→˓_right__1
instance-ip/44a9dc2a-446f-4d34-9148-4a2cc1f9a6f7 default-→˓domain__project__a2fb6399-18ce-44ec-839d-d373221a6a8f-right
virtual-machine/114be9ed-ac45-4dc8-9f45-559470037cfd default-→˓domain__project__a2fb6399-18ce-44ec-839d-d373221a6a8f__2
virtual-machine-interface/43afc4fe-8a84-47ba-96d9-73a8dd1d6b63 default-→˓domain:project:default-domain__project__a2fb6399-18ce-44ec-839d-d373221a6a8f__2_→˓_right__1
instance-ip/44a9dc2a-446f-4d34-9148-4a2cc1f9a6f7 default-→˓domain__project__a2fb6399-18ce-44ec-839d-d373221a6a8f-right
# tree of parents / referencesadmin@localhost:/> tree -r routing-instance/f792b52d-ff69-487e-b2a5-c13060e3ce77routing-instance/f792b52d-ff69-487e-b2a5-c13060e3ce77 default-→˓domain:project:test1:test1
route-target/7454c39a-b3c7-4d42-b766-bd276710d0b1 target:64518:8000133virtual-network/ce88182e-4e6e-4c61-9df1-7ffb24543578 default-
→˓domain:project:test1network-ipam/d6bdafea-58d2-4240-8c65-2acf837d6750 default-
→˓domain:default-project:default-network-ipamproject/acb58362-0272-4d27-97a1-da4ac1e2c5e3 default-
→˓domain:default-projectdomain/ff62f8f7-cccd-4a30-ba32-2ee3764fac79 default-domain
project/0ed483e0-83ef-4f70-8250-1fcfa5d98c0e default-→˓domain:project
domain/ff62f8f7-cccd-4a30-ba32-2ee3764fac79 default-domain
2.8 rm
class contrail_api_cli.commands.rm.Rm(name)Bases: contrail_api_cli.command.Command
Delete a resource from the API.
Warning: -r option can be used to delete recursively back_refs of the resource.
2.9 edit
class contrail_api_cli.commands.edit.Edit(name)Bases: contrail_api_cli.command.Command
Edit a resource.
8 Chapter 2. Base commands
contrail-api-cli Documentation, Release 0.4.0rc1
The resource JSON will be opened in an editor. If modifications have been made and the file is saved theresource will be sent to the API server.
The –template option can be used to create a new resource based on an existing resource.
2.10 schema
class contrail_api_cli.commands.schema.Schema(name)Bases: contrail_api_cli.command.Command
View resources links using contrail schema definition.
admin@localhost:/> schema -v 2.21 virtual-networkvirtual-network
parentproject
childrenaccess-control-listrouting-instancealias-ip-poolfloating-ip-pool
refsroute-tablenetwork-policyqos-confignetwork-ipam
back_refsinstance-ipphysical-routerlogical-routervirtual-machine-interface
propertiesimport-route-target-listexport-route-target-listprovider-propertiesmulti-policy-service-chains-enabledflood-unknown-unicastvirtual-network-network-idrouter-externalvirtual-network-propertiesroute-target-listis-sharedexternal-ipamid-permsperms2display-name
2.11 ln
class contrail_api_cli.commands.ln.Ln(name)Bases: contrail_api_cli.command.Command
Add or remove a reference link between two resources.
2.10. schema 9
contrail-api-cli Documentation, Release 0.4.0rc1
admin@localhost:/> tree -r /virtual-machine/8cfbddcf-6b55-4cdf-abcb-14eed68e4da7virtual-machine/8cfbddcf-6b55-4cdf-abcb-14eed68e4da7 default-→˓domain__foo__fa3ea892-3591-4611-ba22-cc45164aee3e__2
virtual-machine-interface/d739db3d-b89f-46a4-ae02-97ac796261d0 default-→˓domain:foo:default-domain__foo__fa3ea892-3591-4611-ba22-cc45164aee3e__2__right__→˓1
floating-ip/958234f5-4fae-4afd-ae7c-d0dc3c608e06 default-→˓domain:admin:public:floating-ip-pool:958234f5-4fae-4afd-ae7c-d0dc3c608e06
instance-ip/bced2a04-0ef9-4c87-95a6-7cce54182c65 7d401b8c-b9d3-→˓4be2-af0b-a0dfff500860
virtual-router/f6f0b262-745b-45f7-a40a-32ffc1f469bc default-→˓global-system-config:vrouter-1admin@localhost:/> ln -r virtual-machine/8cfbddcf-6b55-4cdf-abcb-14eed68e4da7→˓virtual-router/f6f0b262-745b-45f7-a40a-32ffc1f469bcadmin@localhost:/> tree -r /virtual-machine/8cfbddcf-6b55-4cdf-abcb-14eed68e4da7virtual-machine/8cfbddcf-6b55-4cdf-abcb-14eed68e4da7 default-→˓domain__foo__fa3ea892-3591-4611-ba22-cc45164aee3e__2
virtual-machine-interface/d739db3d-b89f-46a4-ae02-97ac796261d0 default-→˓domain:foo:default-domain__foo__fa3ea892-3591-4611-ba22-cc45164aee3e__2__right__→˓1
floating-ip/958234f5-4fae-4afd-ae7c-d0dc3c608e06 default-→˓domain:admin:public:floating-ip-pool:958234f5-4fae-4afd-ae7c-d0dc3c608e06
instance-ip/bced2a04-0ef9-4c87-95a6-7cce54182c65 7d401b8c-b9d3-→˓4be2-af0b-a0dfff500860admin@localhost:/> ln virtual-machine/8cfbddcf-6b55-4cdf-abcb-14eed68e4da7→˓virtual-router/f6f0b262-745b-45f7-a40a-32ffc1f469bcadmin@localhost:/> tree -r /virtual-machine/8cfbddcf-6b55-4cdf-abcb-14eed68e4da7virtual-machine/8cfbddcf-6b55-4cdf-abcb-14eed68e4da7 default-→˓domain__foo__fa3ea892-3591-4611-ba22-cc45164aee3e__2
virtual-machine-interface/d739db3d-b89f-46a4-ae02-97ac796261d0 default-→˓domain:foo:default-domain__foo__fa3ea892-3591-4611-ba22-cc45164aee3e__2__right__→˓1
floating-ip/958234f5-4fae-4afd-ae7c-d0dc3c608e06 default-→˓domain:admin:public:floating-ip-pool:958234f5-4fae-4afd-ae7c-d0dc3c608e06
instance-ip/bced2a04-0ef9-4c87-95a6-7cce54182c65 7d401b8c-b9d3-→˓4be2-af0b-a0dfff500860
virtual-router/f6f0b262-745b-45f7-a40a-32ffc1f469bc default-→˓global-system-config:vrouter-1
2.12 relative
class contrail_api_cli.commands.relative.Relative(name)Bases: contrail_api_cli.command.Command
Find linked resource using a resource-type path.
admin@localhost:/> relative virtual-machine/8cfbddcf-6b55-4cdf-abcb-14eed68e4da7→˓virtual-machine-interface/floating-ipfloating-ip/958234f5-4fae-4afd-ae7c-d0dc3c608e06admin@localhost:/> relative -l virtual-machine/8cfbddcf-6b55-4cdf-abcb-→˓14eed68e4da7 virtual-machine-interface/floating-ipbase virtual-machine/8cfbddcf-6b55-4cdf-abcb-14eed68e4da7back_ref virtual-machine-interface/d739db3d-b89f-46a4-ae02-97ac796261d0back_ref floating-ip/958234f5-4fae-4afd-ae7c-d0dc3c608e06
The resource path can contain selectors:
10 Chapter 2. Base commands
contrail-api-cli Documentation, Release 0.4.0rc1
admin@localhost:/> relative logical-router/6f71ab62-d831-4a10-807c-975e23dcc3d8→˓service-instance/virtual-machine/virtual-machine-interface[virtual_machine_→˓interface_properties.service_interface_type=right]/instance-ipinstance-ip/ea329dca-e30e-42eb-93a3-86325a34a525admin@localhost:/> cat instance-ip/ea329dca-e30e-42eb-93a3-86325a34a525 | jq .→˓instance_ip_address"172.24.4.3"
This will get the SNAT public IP of a logical router.
2.13 kv
class contrail_api_cli.commands.kv.Kv(name)Bases: contrail_api_cli.command.Command
Command to interact with the key-value store.
admin@localhost:/> kv --add my-key my-valueadmin@localhost:/> kv --get my-key[{
"key": "my-key","value": "my-value"
}]
admin@localhost:/> kv --delete my-keyadmin@localhost:/> kv --get my-keyUnknown User-Agent key my-key (HTTP 404)
2.13. kv 11
contrail-api-cli Documentation, Release 0.4.0rc1
12 Chapter 2. Base commands
CHAPTER 3
Advanced usage
3.1 pipes
Any command can be piped to any program installed on the system inside the cli shell.
admin@localhost:/virtual-network> cat 1095e416-b7cd-4c65-b0a3-631e8263a4dd | grep dns"dns_nameservers": [],
"dns_server_address": "192.168.21.2",admin@localhost:/virtual-network> cat 1095e416-b7cd-4c65-b0a3-631e8263a4dd | jq '.→˓network_ipam_refs[].attr.ipam_subnets[].dns_server_address'"192.168.21.2"
3.2 direct-call
You can call command directly from bash and pipe or redirect output as you wish.
$ contrail-api-cli ls /virtual-networkvirtual-network/1095e416-b7cd-4c65-b0a3-631e8263a4ddvirtual-network/49d00de8-4351-446f-b6ee-d16dec3de413virtual-network/5a9fbd42-a730-42f7-9947-be8a5d808b70virtual-network/e3148147-164e-4194-8507-a58eefe072bdvirtual-network/ba2170ce-741c-4361-ad88-f2d97162faf2virtual-network/e82ae164-f78a-4766-8ba2-7cb68dacaecb
3.3 wildcard resolution
The wildcards * and ? can be used in paths. All matching resources will be resolved.
13
contrail-api-cli Documentation, Release 0.4.0rc1
Warning: Note that this does filtering on the cli side and not on the API side.
admin@localhost:/> ls -l virtual-network/default-domain:admin:*virtual-network/49d00de8-4351-446f-b6ee-d16dec3de413 default-domain:admin:net2virtual-network/5a9fbd42-a730-42f7-9947-be8a5d808b70 default-domain:admin:net1
3.4 loading commands from other namespaces
Say you have a collection of commands in the contrail_api_cli.mycommands entrypoint, run:
$ contrail_api_cli --ns contrail_api_cli.mycommands shell
The namespace contrail_api_cli.mycommands commands will be loaded as well as the commands of thedefault contrail_api_cli.command namespace.
3.5 python from the shell
You can directly use contrail-api-cli API in a python console that can be run with the python command. If ptpython1
or IPython2 are installed they will be used instead of the standard python repl.
admin@localhost:/> python>>> c = Collection('virtual-network', fetch=True)
>>> for vn in c:... print(vn.uuid)0287b4d1-3aea-4a82-b1be-be524995d1a873fc0e08-b542-483e-86e7-f4a5aad2750fbf91b645-f7aa-4ab3-88cf-dc7a6358c08ca3694461-c4e0-4f54-a6fa-a11ae0472e046afc9f77-607f-424c-8188-996c9513467a
3.6 python script execution
The exec command can be used to run a python script that is using the contrail_api_cli API. This avoids the need tosetup the connection to the API server inside the script since the script will be run in the context of the cli.
$ contrail-api-cli exec my_script.py
1 https://github.com/jonathanslenders/ptpython2 https://ipython.org/
14 Chapter 3. Advanced usage
CHAPTER 4
Howto write a command
The code presented here is available at https://github.com/eonpatapon/contrail-api-cli-howto.
4.1 Setup your project
First thing is to create a standard python project with a setup.py file. The structure would look like:
contrail-api-cli-howto/howto
__init__.pysetup.py
Our setup.py can be as simple as:
from setuptools import setup, find_packages
setup(name='contrail-api-cli-howto',version='0.1',packages=find_packages(),install_requires=[
'contrail-api-cli']
)
4.2 Hello world command
In howto/__init__.py we define our command:
15
contrail-api-cli Documentation, Release 0.4.0rc1
from __future__ import unicode_literals
from contrail_api_cli.command import Command
class Hello(Command):description = 'Hello world command'
def __call__(self):return 'Hello world !'
Any command must inherit from the Command class. The final output of the command should be returned by the__call__ method. The output needs to be unicode so that the terminal encoding is handled properly.
4.2.1 Register the command in the cli
As our command is in its own package it won’t be available in the cli yet. We don’t even know what is the commandname.
The cli discover available commands using python entrypoints. By default the cli loads commands from thecontrail_api_cli.command entrypoint. To register our command our setup.py becomes:
from setuptools import setup, find_packages
setup(name='contrail-api-cli-howto',version='0.1',packages=find_packages(),install_requires=[
'contrail-api-cli'],entry_points={
'contrail_api_cli.command': ['hello = howto:Hello'
]}
)
The command name will be hello in the cli. We need to install our packages so that the entrypoint is registered inthe python path
$ python setup.py develop$ contrail-api-cli hello -husage: contrail-api-cli hello [-h]
optional arguments:-h, --help show this help message and exit
$ contrail-api-cli helloHello World !
4.2.2 Adding command arguments
Commands can take options and arguments. The standard argparse lib is used to declare and parse command parame-ters.
16 Chapter 4. Howto write a command
contrail-api-cli Documentation, Release 0.4.0rc1
We will include an option in our command to greet someone:
from __future__ import unicode_literals
from contrail_api_cli.command import Command, Arg
class Hello(Command):description = 'Hello world command'who = Arg(nargs='?', default='cli', help='Person to greet')
def __call__(self, who=None):return 'Hello world %s !' % who
The options are added as class attributes using the Arg class which can take the same arguments as argparse.ArgumentParser.add_argument. The only difference is that if you don’t specicy the option name, the attributename will be used instead. In our case the argument name will be who. All arguments are passed to the __call__method as keyword arguments.
We can see the result using the -h option.
$ contrail-api-cli hello -husage: contrail-api-cli hello [-h] [who]
positional arguments:who Person to greet
optional arguments:-h, --help show this help message and exit
$ contrail-api-cli helloHello world cli !$ contrail-api-cli hello fooHello world foo !
4.2. Hello world command 17
contrail-api-cli Documentation, Release 0.4.0rc1
18 Chapter 4. Howto write a command
CHAPTER 5
Using Resource and Collection API in commands
contrail-api-cli provides a minimal API to make common REST operations (GET/PUT/POST/DELETE) onAPI resources.
To illustrate the usage of this API we will write a command to provision vrouters in the API. Contrail already providesa provisioning script for that but it is a good example for playing with contrail-api-cli API.
In this tutorial we will create three commands. Of course we would like to provision new vrouters but we also wouldlike to list them easily and to delete them if needed.
5.1 Resource and Collection objects
Resource and Collection objects are available in the contrail_api_cli.resource module. A collec-tion represents a list of resources in the API server. Collection is an iterable and Resource is a dict that canseemlessly be converted to the JSON representation of the resource.
For more details check the API page.
5.2 virtual-router resource
contrail-api-cli API is a thin wrapper around the JSON representation of resources or collections. Thereforewe have to know a little about the resource we would like to create. With the CLI we can inspect an existing virtualrouter to see what the JSON representation look like:
$ contrail-api-cli shelladmin@localhost /> ls virtual-routervirtual-router/7c5d76a8-7ca3-43a6-bee6-154f84db977evirtual-router/37fc1054-0d25-4a2d-aa42-9e202b5dfa3aadmin@localhost /> cat virtual-router/37fc1054-0d25-4a2d-aa42-9e202b5dfa3a{
"display_name": "node-2",
(continues on next page)
19
contrail-api-cli Documentation, Release 0.4.0rc1
(continued from previous page)
"fq_name": ["default-global-system-config","node-2"
],"href": "http://localhost:8082/virtual-router/37fc1054-0d25-4a2d-aa42-9e202b5dfa3a","id_perms": {[...]
},"name": "node-2","parent_href": "http://localhost:8082/global-system-config/69e8ab08-f1d3-474d-8c7f-
→˓c540410fa025","parent_type": "global-system-config","parent_uuid": "69e8ab08-f1d3-474d-8c7f-c540410fa025","uuid": "37fc1054-0d25-4a2d-aa42-9e202b5dfa3a","virtual_machine_refs": [[...]
],"virtual_router_ip_address": "10.11.0.56"
}
So some useful information would be the virtual_router_ip_address property. The virtual router hostnamecan be found in the fq_name.
5.3 List command
The list command make use of the Collection object which represent the collection of resources of a specific type.
Basically doing ls / in the CLI gives you all collections:
from contrail_api_cli.command import Commandfrom contrail_api_cli.resource import Collectionfrom contrail_api_cli.utils import printo
class ListVRouter(Command):description = 'List vrouters'
def __call__(self):vrouters = Collection('virtual-router', fetch=True)for vrouter in vrouters:
vrouter.fetch()printo('%s: %s', (vrouter.fq_name[-1],
vrouter['virtual_router_ip_address']))
We instanciate a Collection of type ‘virtual-router’ to get all the vrouters from the API. The fetch argumentwill actually fetch the collection data from the API server immediately. The method Collection.fetch() canbe used to sync the object later with the server.
The Collection object is iterable like a list so we iterate the collection and fetch the details of each resource to getthe details. For each vrouter we print the name and the IP of the vrouter. Resource is basically a dict wrapper so itsproperties are accessible directly.
printo() is used instead of print() to handle properly terminal encoding with python2 and python3.
Note: With Contrail >= 3.0 we can make use of the fields API on Collection objects. Instead of making a GETrequest for each resource to get its details we can specify the supplementary fields to get in the Collection:
20 Chapter 5. Using Resource and Collection API in commands
contrail-api-cli Documentation, Release 0.4.0rc1
vrouter = Collection('virtual-router',fields=['virtual_router_ip_address'],fetch=True)
for vrouter in vrouters:printo(vrouter['virtual_router_ip_address'])
In this case only one GET request is made.
5.4 Add command
To add a virtual-router we need at least a name and an IP address. The type is optionnal and is usually not defined butwe add an option for it just in case:
from contrail_api_cli.command import Command, Arg, Optionfrom contrail_api_cli.resource import Resource
class AddVRouter(Command):description = 'Add vrouter'vrouter_name = Arg(help='Hostname of compute node')vrouter_ip = Option(help='IP of compute node',
required=True)vrouter_type = Option(help='vrouter type',
choices=['tor-service-mode', 'embedded'],default=None)
def __call__(self, vrouter_ip=None, vrouter_name=None, vrouter_type=None):global_config = Resource('global-system-config',
fq_name='default-global-system-config')vrouter = Resource('virtual-router',
fq_name='default-global-system-config:%s' % vrouter_name,parent=global_config,virtual_router_ip_address=vrouter_ip)
if vrouter_type:vrouter['virtual_router_type'] = [vrouter_type]
vrouter.save()
To create the vrouter resource we are making use of the Resource class. To create a Resource we need to passthe type (‘virtual-router’), an fq_name, and a parent resource.
Note: Resource is a subclass of python UserDict. Any supplementary kwarg passed to the constructor is addedin the dict. In our example passing virtual_router_ip_address to the constructor is the same as:
vrouter = Resource('virtual-router',fq_name='default-global-system-config:%s' % vrouter_name,parent=global_config)
vouter['virtual_router_ip_address'] = vrouter_ip
An existing parent resource must be defined in order to create the resource. In our case the parent is the ‘default-global-system-config’. Passing a parent resource will populate the parent_type and parent_uuid keys of the Resource.
Finally we save the resource to the API server using the Resource.save() method. This method convert theobject to JSON and send the data to the API server in a POST request since the resource doesn’t exists on the server.It is possible to update an existing resource using the same method. In the update case a PUT request is made.
5.4. Add command 21
contrail-api-cli Documentation, Release 0.4.0rc1
5.5 Del command
The del command is straith forward. We need to get the resource by it’s name and try to delete it with the Resource.delete() method:
class DelVRouter(Command):description = 'Remove vrouter'vrouter_name = Arg(help='Hostname of compute node')
def __call__(self, vrouter_name=None):vrouter = Resource('virtual-router',
fq_name='default-global-system-config:%s' % vrouter_name,check=True)
vrouter.delete()
The check param makes sure that the resource exists on the API server. If not ResourceNotFound is raised andcatched automatically by the cli.
Note: Resource.check() only validate the fq_name of the resource whereas Resource.fetch() willtry to get all the details of the resource. Both methods can raise ResourceNotFound. Using check=True orfetch=True when initializing a Collection is the same as using theses methods.
22 Chapter 5. Using Resource and Collection API in commands
CHAPTER 6
API
6.1 Collection
class contrail_api_cli.resource.Collection(type, fetch=False, recursive=1, fields=None,detail=None, filters=None, par-ent_uuid=None, back_refs_uuid=None,data=None, session=None)
Class for interacting with an API collection
>>> from contrail_api_cli.resource import Collection>>> c = Collection('virtual-network', fetch=True)>>> # iterate over the resources>>> for r in c:>>> print(r.path)>>> # filter support>>> c.filter("router_external", False)>>> c.fetch()>>> assert all([r.get('router_external') for r in c]) == False
Parameters
• type (str) – name of the collection
• fetch (bool) – immediately fetch collection from the server
• recursive (int) – level of recursion
• fields ([str]) – list of field names to fetch
• filters ([(name, value), ..]) – list of filters
• parent_uuid (v4UUID str or list of v4UUID str) – filter by parent_uuid
• back_ref_uuid (v4UUID str or list of v4UUID str) – filter byback_ref_uuid
• data ([Resource]) – initial resources of the collection
23
contrail-api-cli Documentation, Release 0.4.0rc1
append(item)S.append(object) – append object to the end of the sequence
count(value)→ integer – return number of occurrences of value
extend(other)S.extend(iterable) – extend sequence by appending elements from the iterable
fetch(*args, **kwargs)Fetch collection from API server
Parameters
• recursive (int) – level of recursion
• fields ([str]) – fetch only listed fields. contrail 3.0 required
• detail (bool) – fetch all fields
• filters ([(name, value), ..]) – list of filters
• parent_uuid (v4UUID str or list of v4UUID str) – filter by parent_uuid
• back_refs_uuid (v4UUID str or list of v4UUID str) – filter byback_refs_uuid
Return type Collection
filter(field_name, field_value)Add permanent filter on the collection
Parameters
• field_name (str) – name of the field to filter on
• field_value – value to filter on
Return type Collection
hrefReturn URL of the resource
Return type str
index(value)→ integer – return first index of value.Raises ValueError if the value is not present.
insert(i, item)S.insert(index, object) – insert object before index
pathReturn Path of the resource
Return type Path
pop([index ])→ item – remove and return item at index (default last).Raise IndexError if list is empty or index is out of range.
classmethod register(event, callback)Register a virtual subclass of an ABC.
remove(item)S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.
reverse()S.reverse() – reverse IN PLACE
24 Chapter 6. API
contrail-api-cli Documentation, Release 0.4.0rc1
6.2 Resource
class contrail_api_cli.resource.Resource(type, fetch=False, check=False, parent=None, re-cursive=1, session=None, **kwargs)
Class for interacting with an API resource
>>> from contrail_api_cli.resource import Resource>>> r = Resource('virtual-network',
uuid='4c45e89b-7780-4b78-8508-314fe04a7cbd',fetch=True)
>>> r['display_name'] = 'foo'>>> r.save()
>>> p = Resource('project', fq_name='default-domain:admin')>>> r = Resource('virtual-network', fq_name='default-domain:admin:net1',
parent=p)>>> r.save()
Parameters
• type (str) – type of the resource
• fetch (bool) – immediately fetch resource from the server
• uuid (v4UUID str) – uuid of the resource
• fq_name (str (domain:project:identifier) or list ['domain','project', 'identifier']) – fq name of the resource
• check (bool) – check that the resource exists
• parent (Resource) – parent resource
• recursive (int) – level of recursion
Raises
• ResourceNotFound – bad uuid or fq_name is given
• HttpError – when save(), fetch() or delete() fail
Note: Either fq_name or uuid must be provided.
add_back_ref(back_ref, attr=None)Add reference from back_ref to self
Parameters back_ref (Resource) – back_ref to add
Return type Resource
add_ref(ref, attr=None)Add reference to resource
Parameters ref (Resource) – reference to add
Return type Resource
back_refsReturn back_refs resources of the resource
Return type LinkedResources
6.2. Resource 25
contrail-api-cli Documentation, Release 0.4.0rc1
check()Check that the resource exists.
Raises ResourceNotFound – if the resource doesn’t exists
childrenReturn children resources of the resource
Return type LinkedResources
createdReturn creation date
Return type datetime
Raises ResourceNotFound – resource not found on the API
delete(*args, **kwargs)Delete resource from the API server
existsReturns True if the resource exists on the API server, or returns False.
Return type bool
fetch(*args, **kwargs)Fetch resource from the API server
Parameters
• recursive (int) – level of recursion for fetching resources
• exclude_children (bool) – don’t get children references
• exclude_back_refs (bool) – don’t get back_refs references
Return type Resource
fq_nameReturn FQDN of the resource
Return type FQName
from_dict(data, recursive=1)Populate the resource from a python dict
Parameters recursive (int) – level of recursion for fetching resources
hrefReturn URL of the resource
Return type str
json()Return JSON representation of the resource
parentReturn parent resource
Return type Resource
Raises
• ResourceNotFound – parent resource doesn’t exists
• ResourceMissing – parent resource is not defined
26 Chapter 6. API
contrail-api-cli Documentation, Release 0.4.0rc1
pathReturn Path of the resource
Return type Path
refsReturn refs resources of the resource
Return type LinkedResources
remove_back_ref(back_ref)Remove reference from back_ref to self
Parameters back_ref (Resource) – back_ref to remove
Return type Resource
remove_ref(ref)Remove reference from self to ref
>>> iip = Resource('instance-ip',uuid='30213cf9-4b03-4afc-b8f9-c9971a216978',fetch=True)
>>> for vmi in iip['virtual_machine_interface_refs']:iip.remove_ref(vmi)
>>> iip['virtual_machine_interface_refs']KeyError: u'virtual_machine_interface_refs'
Parameters ref (Resource) – reference to remove
Return type Resource
save(*args, **kwargs)Save the resource to the API server
If the resource doesn’t have a uuid the resource will be created. If uuid is present the resource is updated.
Return type Resource
set_ref(ref, attr=None)Set reference to resource
Can be used to set references on a resource that is not already created.
Parameters ref (Resource) – reference to add
Return type Resource
uuidReturn UUID of the resource
Return type str
6.3 Command
class contrail_api_cli.command.Command(name)Base class for commands
__call__(**kwargs)Command must implement this method.
The command must return an unicode string (unicode in python2 or str in python3)
6.3. Command 27
contrail-api-cli Documentation, Release 0.4.0rc1
Parameters kwargs – options of the command
Return type unicode | str
aliases = []Command aliases
current_path(resource)Return current path for resource
Parameters resource (Resource|Collection) – resource or collection
Return type str
description = u''Description of the command
is_pipedReturn True if the command result is beeing piped to another command.
Return type bool
6.4 Utils
contrail_api_cli.utils.format_table(rows, sep=u’ ’)Format table
Parameters sep (unicode on python2 | str on python3) – separator betweencolumns
Given the table:
table = [['foo', 'bar', 'foo'],[1, 2, 3],['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'],['foo', 45, 'bar', 2345]
]
format_table will return:
foo bar foo1 2 354a5a05d-c83b-4bb5-bd95-d90d6ea4a878foo 45 bar 2345
contrail_api_cli.utils.format_tree(tree)Format a python tree structure
Given the python tree:
tree = {'node': ['ROOT', 'This is the root of the tree'],'childs': [{
'node': 'A1','childs': [{
'node': 'B1','childs': [{
'node': 'C1'
(continues on next page)
28 Chapter 6. API
contrail-api-cli Documentation, Release 0.4.0rc1
(continued from previous page)
}]},{
'node': 'B2'}]
},{
'node': 'A2','childs': [{
'node': 'B3','childs': [{
'node': ['C2', 'This is a leaf']},{
'node': 'C3'}]
}]},{
'node': ['A3', 'This is a node'],'childs': [{
'node': 'B2'}]
}]}
format_tree will return:
ROOT This is the root of the treeA1
B1C1
B2A2
B3C2 This is a leafC3
A3 This is a nodeB2
contrail_api_cli.utils.continue_prompt(message=u”)Prompt the user to continue or not
Returns True when the user type Yes.
Parameters message (str) – message to display
Return type bool
contrail_api_cli.utils.md5(fname)Calculate md5sum of a file
Parameters fname (str) – file path
contrail_api_cli.utils.parallel_map(func, iterable, args=None, kwargs=None, work-ers=None)
Map func on a list using gevent greenlets.
Parameters
6.4. Utils 29
contrail-api-cli Documentation, Release 0.4.0rc1
• func (function) – function applied on iterable elements
• iterable (iterable) – elements to map the function over
• args (tuple) – arguments of func
• kwargs (dict) – keyword arguments of func
• workers (int) – limit the number of greenlets running in parrallel
30 Chapter 6. API
CHAPTER 7
Indices and tables
• genindex
• modindex
• search
31
contrail-api-cli Documentation, Release 0.4.0rc1
32 Chapter 7. Indices and tables
Python Module Index
ccontrail_api_cli.commands.cat, 7contrail_api_cli.commands.du, 6contrail_api_cli.commands.edit, 8contrail_api_cli.commands.kv, 11contrail_api_cli.commands.ln, 9contrail_api_cli.commands.ls, 5contrail_api_cli.commands.man, 5contrail_api_cli.commands.relative, 10contrail_api_cli.commands.rm, 8contrail_api_cli.commands.schema, 9contrail_api_cli.commands.tree, 7
33
contrail-api-cli Documentation, Release 0.4.0rc1
34 Python Module Index
Index
Symbols__call__() (contrail_api_cli.command.Command
method), 27
Aadd_back_ref() (contrail_api_cli.resource.Resource
method), 25add_ref() (contrail_api_cli.resource.Resource
method), 25aliases (contrail_api_cli.command.Command at-
tribute), 28append() (contrail_api_cli.resource.Collection
method), 24
Bback_refs (contrail_api_cli.resource.Resource at-
tribute), 25
CCat (class in contrail_api_cli.commands.cat), 7Cd (class in contrail_api_cli.commands.shell), 6check() (contrail_api_cli.resource.Resource method),
26children (contrail_api_cli.resource.Resource at-
tribute), 26Collection (class in contrail_api_cli.resource), 23Command (class in contrail_api_cli.command), 27continue_prompt() (in module con-
trail_api_cli.utils), 29contrail_api_cli.commands.cat (module), 7contrail_api_cli.commands.du (module), 6contrail_api_cli.commands.edit (module), 8contrail_api_cli.commands.kv (module), 11contrail_api_cli.commands.ln (module), 9contrail_api_cli.commands.ls (module), 5contrail_api_cli.commands.man (module), 5contrail_api_cli.commands.relative (mod-
ule), 10contrail_api_cli.commands.rm (module), 8
contrail_api_cli.commands.schema (mod-ule), 9
contrail_api_cli.commands.tree (module), 7count() (contrail_api_cli.resource.Collection method),
24created (contrail_api_cli.resource.Resource attribute),
26current_path() (con-
trail_api_cli.command.Command method),28
Ddelete() (contrail_api_cli.resource.Resource
method), 26description (contrail_api_cli.command.Command
attribute), 28Du (class in contrail_api_cli.commands.du), 6
EEdit (class in contrail_api_cli.commands.edit), 8exists (contrail_api_cli.resource.Resource attribute),
26extend() (contrail_api_cli.resource.Collection
method), 24
Ffetch() (contrail_api_cli.resource.Collection method),
24fetch() (contrail_api_cli.resource.Resource method),
26filter() (contrail_api_cli.resource.Collection
method), 24format_table() (in module contrail_api_cli.utils),
28format_tree() (in module contrail_api_cli.utils), 28fq_name (contrail_api_cli.resource.Resource attribute),
26from_dict() (contrail_api_cli.resource.Resource
method), 26
35
contrail-api-cli Documentation, Release 0.4.0rc1
Hhref (contrail_api_cli.resource.Collection attribute), 24href (contrail_api_cli.resource.Resource attribute), 26
Iindex() (contrail_api_cli.resource.Collection method),
24insert() (contrail_api_cli.resource.Collection
method), 24is_piped (contrail_api_cli.command.Command
attribute), 28
Jjson() (contrail_api_cli.resource.Resource method),
26
KKv (class in contrail_api_cli.commands.kv), 11
LLn (class in contrail_api_cli.commands.ln), 9Ls (class in contrail_api_cli.commands.ls), 5
MMan (class in contrail_api_cli.commands.man), 5md5() (in module contrail_api_cli.utils), 29
Pparallel_map() (in module contrail_api_cli.utils),
29parent (contrail_api_cli.resource.Resource attribute),
26path (contrail_api_cli.resource.Collection attribute), 24path (contrail_api_cli.resource.Resource attribute), 26pop() (contrail_api_cli.resource.Collection method), 24
Rrefs (contrail_api_cli.resource.Resource attribute), 27register() (contrail_api_cli.resource.Collection
class method), 24Relative (class in con-
trail_api_cli.commands.relative), 10remove() (contrail_api_cli.resource.Collection
method), 24remove_back_ref() (con-
trail_api_cli.resource.Resource method),27
remove_ref() (contrail_api_cli.resource.Resourcemethod), 27
Resource (class in contrail_api_cli.resource), 25reverse() (contrail_api_cli.resource.Collection
method), 24Rm (class in contrail_api_cli.commands.rm), 8
Ssave() (contrail_api_cli.resource.Resource method),
27Schema (class in contrail_api_cli.commands.schema), 9set_ref() (contrail_api_cli.resource.Resource
method), 27
TTree (class in contrail_api_cli.commands.tree), 7
Uuuid (contrail_api_cli.resource.Resource attribute), 27
36 Index