API

Collection

class contrail_api_cli.resource.Collection(type, fetch=False, recursive=1, fields=None, detail=None, filters=None, parent_uuid=None, back_refs_uuid=None, data=None, session=None)[source]

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 by back_ref_uuid
  • data ([Resource]) – initial resources of the collection
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)[source]

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 by back_refs_uuid
Return type:

Collection

filter(field_name, field_value)[source]

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

href

Return 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

path

Return 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

Resource

class contrail_api_cli.resource.Resource(type, fetch=False, check=False, parent=None, recursive=1, session=None, **kwargs)[source]

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)[source]

Add reference from back_ref to self

Parameters:back_ref (Resource) – back_ref to add
Return type:Resource
add_ref(ref, attr=None)[source]

Add reference to resource

Parameters:ref (Resource) – reference to add
Return type:Resource
back_refs

Return back_refs resources of the resource

Return type:LinkedResources
check()[source]

Check that the resource exists.

Raises:ResourceNotFound – if the resource doesn’t exists
children

Return children resources of the resource

Return type:LinkedResources
created

Return creation date

Return type:datetime
Raises:ResourceNotFound – resource not found on the API
delete(*args, **kwargs)[source]

Delete resource from the API server

exists

Returns True if the resource exists on the API server, or returns False.

Return type:bool
fetch(*args, **kwargs)[source]

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_name

Return FQDN of the resource

Return type:FQName
from_dict(data, recursive=1)[source]

Populate the resource from a python dict

Parameters:recursive (int) – level of recursion for fetching resources
href

Return URL of the resource

Return type:str
json()[source]

Return JSON representation of the resource

parent

Return parent resource

Return type:

Resource

Raises:
  • ResourceNotFound – parent resource doesn’t exists
  • ResourceMissing – parent resource is not defined
path

Return Path of the resource

Return type:Path
refs

Return refs resources of the resource

Return type:LinkedResources
remove_back_ref(back_ref)[source]

Remove reference from back_ref to self

Parameters:back_ref (Resource) – back_ref to remove
Return type:Resource
remove_ref(ref)[source]

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)[source]

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)[source]

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
uuid

Return UUID of the resource

Return type:str

Command

class contrail_api_cli.command.Command(name)[source]

Base class for commands

__call__(**kwargs)[source]

Command must implement this method.

The command must return an unicode string (unicode in python2 or str in python3)

Parameters:kwargs – options of the command
Return type:unicode | str
aliases = []

Command aliases

current_path(resource)[source]

Return current path for resource

Parameters:resource (Resource|Collection) – resource or collection
Return type:str
description = u''

Description of the command

is_piped

Return True if the command result is beeing piped to another command.

Return type:bool

Utils

contrail_api_cli.utils.format_table(rows, sep=u' ')[source]

Format table

Parameters:sep (unicode on python2 | str on python3) – separator between columns

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  foo
1                                     2    3
54a5a05d-c83b-4bb5-bd95-d90d6ea4a878
foo                                   45   bar  2345
contrail_api_cli.utils.format_tree(tree)[source]

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'
            }]
        },
        {
            '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 tree
├── A1
│   ├── B1
│   │   └── C1
│   └── B2
├── A2
│   └── B3
│       ├── C2  This is a leaf
│       └── C3
└── A3          This is a node
    └── B2
contrail_api_cli.utils.continue_prompt(message=u'')[source]

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)[source]

Calculate md5sum of a file

Parameters:fname (str) – file path
contrail_api_cli.utils.parallel_map(func, iterable, args=None, kwargs=None, workers=None)[source]

Map func on a list using gevent greenlets.

Parameters:
  • 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