Completed
Push — master ( 975cab...72eea9 )
by Juan José
19s
created

gmp.protocols.base.Protocol._read()   A

Complexity

Conditions 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nop 1
dl 0
loc 14
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
0 ignored issues
show
Coding Style introduced by
This module should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2
# Copyright (C) 2018 Greenbone Networks GmbH
3
#
4
# SPDX-License-Identifier: GPL-3.0-or-later
5
#
6
# This program is free software: you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation, either version 3 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19
import logging
20
21
from gmp.errors import GmpError
22
23
logger = logging.getLogger(__name__)
0 ignored issues
show
Coding Style Naming introduced by
The name logger does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
24
25
26
class Protocol:
0 ignored issues
show
Unused Code introduced by
The variable __class__ seems to be unused.
Loading history...
27
    """Base class for different protocols
28
29
    Attributes:
30
        connection (:class:`gmp.connections.GmpConnection`): Connection to use
31
            to talk with the remote daemon. See :mod:`gmp.connections` for
32
            possible connection types.
33
        transform (`callable`_, optional): Optional transform callable to
34
            convert response data. After each request the callable gets passed
35
            the plain response data which can be used to check the data and/or
36
            conversion into different representaitions like a xml dom.
37
38
            See :mod:`gmp.transforms` for existing transforms.
39
    """
40
41
    def __init__(self, connection, transform=None):
42
        self._connection = connection
43
44
        self._connected = False
45
46
        self._transform_callable = transform
47
48
    def _read(self):
49
        """Read a command response from gvmd
50
51
        Returns:
52
            str: Response from server.
53
        """
54
        response = self._connection.read()
55
56
        logger.debug('read() %i Bytes response: %s', len(response), response)
57
58
        if response is None or len(str(response)) == 0:
0 ignored issues
show
Unused Code introduced by
Do not use len(SEQUENCE) as condition value
Loading history...
59
            raise GmpError('Connection was closed by remote server')
60
61
        return response
62
63
    def _send(self, data):
64
        """Send a command to the server
65
66
        Args:
67
            data (str): Data to be send over the connection to the server
68
        """
69
        self._connect()
70
        self._connection.send(data)
71
72
    def _connect(self):
73
        if not self.is_connected():
74
            self._connection.connect()
75
            self._connected = True
76
77
    def _transform(self, data):
78
        transform = self._transform_callable
79
        if transform is None:
80
            return data
81
        return transform(data)
82
83
    def is_connected(self):
84
        """Status of the current connection
85
86
        Returns:
87
            bool: True if a connection to the remote server has been
88
                  established.
89
        """
90
        return self._connected
91
92
    def disconnect(self):
93
        """Disconnect the connection
94
95
        Ends and closes the connection.
96
        """
97
        if self.is_connected():
98
            self._connection.disconnect()
99
            self._connected = False
100
101
    def send_command(self, cmd):
102
        """Send a command to the remote server
103
104
        If the class isn't connected to the server yet the connection will be
105
        established automatically.
106
107
        Arguments:
108
            cmd (str): Command as string to be send over the connection to
109
                the server.
110
111
        Returns:
112
            any: The actual returned type depends on the set transform.
113
114
            Per default - if no transform is set explicitly - the response is
115
            returned as string.
116
        """
117
        self._send(cmd)
118
        response = self._read()
119
        return self._transform(response)
120