Statistics
| Branch: | Tag: | Revision:

root / ncclient / manager.py @ 6e571704

History | View | Annotate | Download (6.8 kB)

1
# Copyright 2009 Shikhar Bhushan
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#    http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

    
15
"""This module is a thin layer of abstraction around the library. It exposes all core functionality."""
16

    
17
import capabilities
18
import operations
19
import transport
20

    
21
import logging
22

    
23
logger = logging.getLogger('ncclient.manager')
24

    
25
CAPABILITIES = [
26
    "urn:ietf:params:netconf:base:1.0",
27
    "urn:ietf:params:netconf:capability:writable-running:1.0",
28
    "urn:ietf:params:netconf:capability:candidate:1.0",
29
    "urn:ietf:params:netconf:capability:confirmed-commit:1.0",
30
    "urn:ietf:params:netconf:capability:rollback-on-error:1.0",
31
    "urn:ietf:params:netconf:capability:startup:1.0",
32
    "urn:ietf:params:netconf:capability:url:1.0?scheme=http,ftp,file,https,sftp",
33
    "urn:ietf:params:netconf:capability:validate:1.0",
34
    "urn:ietf:params:netconf:capability:xpath:1.0",
35
    "urn:liberouter:params:netconf:capability:power-control:1.0"
36
    "urn:ietf:params:netconf:capability:interleave:1.0"
37
]
38
"""A list of URI's representing the client's capabilities. This is used during the initial capability exchange. Modify this if you need to announce some capability not already included."""
39

    
40
OPERATIONS = {
41
    "get": operations.Get,
42
    "get_config": operations.GetConfig,
43
    "edit_config": operations.EditConfig,
44
    "copy_config": operations.CopyConfig,
45
    "validate": operations.Validate,
46
    "commit": operations.Commit,
47
    "discard_changes": operations.DiscardChanges,
48
    "delete_config": operations.DeleteConfig,
49
    "lock": operations.Lock,
50
    "unlock": operations.Unlock,
51
    "close_session": operations.CloseSession,
52
    "kill_session": operations.KillSession,
53
    "poweroff_machine": operations.PoweroffMachine,
54
    "reboot_machine": operations.RebootMachine
55
}
56
"""Dictionary of method names and corresponding :class:`~ncclient.operations.RPC` subclasses. It is used to lookup operations, e.g. `get_config` is mapped to :class:`~ncclient.operations.GetConfig`. It is thus possible to add additional operations to the :class:`Manager` API."""
57

    
58
def connect_ssh(*args, **kwds):
59
    """Initialize a :class:`Manager` over the SSH transport. For documentation of arguments see :meth:`ncclient.transport.SSHSession.connect`.
60

61
    The underlying :class:`ncclient.transport.SSHSession` is created with :data:`CAPABILITIES`. It is first instructed to :meth:`~ncclient.transport.SSHSession.load_known_hosts` and then  all the provided arguments are passed directly to its implementation of :meth:`~ncclient.transport.SSHSession.connect`.
62
    """
63
    session = transport.SSHSession(capabilities.Capabilities(CAPABILITIES))
64
    session.load_known_hosts()
65
    session.connect(*args, **kwds)
66
    return Manager(session)
67

    
68
connect = connect_ssh
69
"Same as :func:`connect_ssh`, since SSH is the default (and currently, the only) transport."
70

    
71
class OpExecutor(type):
72

    
73
    def __new__(cls, name, bases, attrs):
74
        def make_wrapper(op_cls):
75
            def wrapper(self, *args, **kwds):
76
                return self.execute(op_cls, *args, **kwds)
77
            wrapper.func_doc = op_cls.request.func_doc
78
            return wrapper
79
        for op_name, op_cls in OPERATIONS.iteritems():
80
            attrs[op_name] = make_wrapper(op_cls)
81
        return super(OpExecutor, cls).__new__(cls, name, bases, attrs)
82

    
83
class Manager(object):
84

    
85
    """For details on the expected behavior of the operations and their parameters refer to :rfc:`4741`.
86

87
    Manager instances are also context managers so you can use it like this::
88

89
        with manager.connect("host") as m:
90
            # do your stuff
91

92
    ... or like this::
93

94
        m = manager.connect("host")
95
        try:
96
            # do your stuff
97
        finally:
98
            m.close_session()
99
    """
100

    
101
    __metaclass__ = OpExecutor
102

    
103
    def __init__(self, session, timeout=30):
104
        self._session = session
105
        self._async_mode = False
106
        self._timeout = timeout
107
        self._raise_mode = operations.RaiseMode.ALL
108

    
109
    def __enter__(self):
110
        return self
111

    
112
    def __exit__(self, *args):
113
        self.close_session()
114
        return False
115

    
116
    def __set_timeout(self, timeout):
117
        self._timeout = timeout
118

    
119
    def __set_async_mode(self, mode):
120
        self._async_mode = mode
121

    
122
    def __set_raise_mode(self, mode):
123
        assert(mode in (operations.RaiseMode.NONE, operations.RaiseMode.ERRORS, operations.RaiseMode.ALL))
124
        self._raise_mode = mode
125

    
126
    def execute(self, cls, *args, **kwds):
127
        return cls(self._session,
128
                   async=self._async_mode,
129
                   timeout=self._timeout,
130
                   raise_mode=self._raise_mode).request(*args, **kwds)
131

    
132
    def locked(self, target):
133
        """Returns a context manager for a lock on a datastore, where *target* is the name of the configuration datastore to lock, e.g.::
134

135
            with m.locked("running"):
136
                # do your stuff
137

138
        ... instead of::
139

140
            m.lock("running")
141
            try:
142
                # do your stuff
143
            finally:
144
                m.unlock("running")
145
        """
146
        return operations.LockContext(self._session, target)
147

    
148
    @property
149
    def client_capabilities(self):
150
        ":class:`~ncclient.capabilities.Capabilities` object representing the client's capabilities."
151
        return self._session._client_capabilities
152

    
153
    @property
154
    def server_capabilities(self):
155
        ":class:`~ncclient.capabilities.Capabilities` object representing the server's capabilities."
156
        return self._session._server_capabilities
157

    
158
    @property
159
    def session_id(self):
160
        "`session-id` assigned by the NETCONF server."
161
        return self._session.id
162

    
163
    @property
164
    def connected(self):
165
        "Whether currently connected to the NETCONF server."
166
        return self._session.connected
167

    
168
    async_mode = property(fget=lambda self: self._async_mode, fset=__set_async_mode)
169
    "Specify whether operations are executed asynchronously (`True`) or synchronously (`False`) (the default)."
170

    
171
    timeout = property(fget=lambda self: self._timeout, fset=__set_timeout)
172
    "Specify the timeout for synchronous RPC requests."
173

    
174
    raise_mode = property(fget=lambda self: self._raise_mode, fset=__set_raise_mode)
175
    "Specify which errors are raised as :exc:`~ncclient.operations.RPCError` exceptions. Valid values are the constants defined in :class:`~ncclient.operations.RaiseMode`. The default value is :attr:`~ncclient.operations.RaiseMode.ALL`."