Statistics
| Branch: | Tag: | Revision:

root / ncclient / manager.py @ b660fcda

History | View | Annotate | Download (4.3 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
"Thin layer of abstraction around NCClient"
16

    
17
import capabilities
18
import operations
19
import transport
20

    
21
import logging
22
logger = logging.getLogger('ncclient.manager')
23

    
24
def connect_ssh(*args, **kwds):
25
    """Connect to NETCONF server over SSH. See :meth:`SSHSession.connect()
26
    <ncclient.transport.SSHSession.connect>` for argument details.
27

28
    :rtype: :class:`Manager`
29
    """
30
    session = transport.SSHSession(capabilities.CAPABILITIES)
31
    session.load_known_hosts()
32
    session.connect(*args, **kwds)
33
    return Manager(session)
34

    
35
#: Same as :meth:`connect_ssh`
36
connect = connect_ssh
37

    
38
OPERATIONS = {
39
    "get": operations.Get,
40
    "get_config": operations.GetConfig,
41
    "edit_config": operations.EditConfig,
42
    "copy_config": operations.CopyConfig,
43
    "validate": operations.Validate,
44
    "commit": operations.Commit,
45
    "discard_changes": operations.DiscardChanges,
46
    "delete_config": operations.DeleteConfig,
47
    "lock": operations.Lock,
48
    "unlock": operations.Unlock,
49
    "close_session": operations.CloseSession,
50
    "kill_session": operations.KillSession,
51
    "poweroff_machine": operations.PoweroffMachine,
52
    "reboot_machine": operations.RebootMachine
53
}
54

    
55
class Manager(object):
56

    
57
    """API for NETCONF operations.
58

59
    It is also a context manager, so a :class:`Manager` instance can be used
60
    with the *with* statement. The session is closed when the context ends. """
61

    
62
    def __init__(self, session):
63
        self._session = session
64
        self._async_mode = False
65
        self._timeout = None
66
        self._raise_mode = 'all'
67

    
68
    def __enter__(self):
69
        return self
70

    
71
    def __exit__(self, *argss):
72
        self.close()
73
        return False
74

    
75
    def __getattr__(self, name):
76
        op = OPERATIONS.get(name, None)
77
        if op is None:
78
            raise AttributeError
79
        else:
80
            return op(self.session,
81
                      async=self._async_mode,
82
                      timeout=self._timeout,
83
                      raise_mode=self._raise_mode).request
84
    
85
    def locked(self, target):
86
        """Returns a context manager for the *with* statement.
87

88
        :arg target: name of the datastore to lock
89
        :type target: `string`
90
        :rtype: :class:`~ncclient.operations.LockContext`
91
        """
92
        return operations.LockContext(self._session, target)
93

    
94
    def close(self):
95
        """Closes the NETCONF session. First does *<close-session>* RPC."""
96
        try: # try doing it clean
97
            self._async_mode = False
98
            self.close_session()
99
        except Exception as e:
100
            logger.debug('error doing <close-session> -- %r' % e)
101
        if self._session.connected: # if that didn't work, this sure will :)
102
            self._session.close()
103

    
104
    @property
105
    def session(self):
106
        ":class:`~ncclient.transport.Session` instance"
107
        return self._session
108

    
109
    @property
110
    def client_capabilities(self):
111
        ":class:`~ncclient.capabilities.Capabilities` object for client"
112
        return self._session._client_capabilities
113

    
114
    @property
115
    def server_capabilities(self):
116
        ":class:`~ncclient.capabilities.Capabilities` object for server"
117
        return self._session._server_capabilities
118

    
119
    @property
120
    def session_id(self):
121
        "*<session-id>* as assigned by NETCONF server"
122
        return self._session.id
123

    
124
    @property
125
    def connected(self):
126
        "Whether currently connected to NETCONF server"
127
        return self._session.connected
128

    
129
    def set_async_mode(self, bool=True):
130
        self._async_mode = bool
131

    
132
    def set_raise_mode(self, mode):
133
        assert(choice in ('all', 'errors', 'none'))
134
        self._raise_mode = mode
135

    
136
    async_mode = property(fget=lambda self: self._async_mode, fset=set_async_mode)
137

    
138
    raise_mode = property(fget=set_raise_mode, fset=set_raise_mode)