Completed
Push — master ( f7cf3e...4f4553 )
by
unknown
16s queued 14s
created

gvm.protocols.gmp.Gmp.__enter__()   A

Complexity

Conditions 4

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 20
nop 1
dl 0
loc 29
rs 9.4
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2019 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
"""
20
Module for communication with gvmd
21
"""
22
from typing import Any, Optional, Callable
23
24
from gvm.errors import GvmError
25
26
from gvm.protocols.base import GvmProtocol, GvmConnection
27
28
from gvm.protocols.gmpv7 import Gmp as Gmpv7
29
from gvm.protocols.gmpv8 import Gmp as Gmpv8
30
31
from gvm.transforms import EtreeCheckCommandTransform
32
33
from gvm.xml import XmlCommand
34
35
36
class Gmp(GvmProtocol):
37
    """Dynamically select supported GMP protocol of the remote manager daemon.
38
39
    Must be used as a `Context Manager
40
    <https://docs.python.org/3/reference/datamodel.html#context-managers>`_
41
42
    Example:
43
44
        .. code-block:: python
45
46
            from gvm.protocols.gmp import Gmp
47
48
            with Gmp(connection) as gmp:
49
                # gmp can be an instance of gvm.protocols.gmpv7.Gmp or
50
                # gvm.protocols.gmpv8.Gmp depending on the supported GMP
51
                # version of the remote manager daemon
52
                resp = gmp.get_tasks()
53
54
    Attributes:
55
        connection: Connection to use to talk with the remote daemon. See
56
            :mod:`gvm.connections` for possible connection types.
57
        transform: Optional transform `callable`_ to convert response data.
58
            After each request the callable gets passed the plain response data
59
            which can be used to check the data and/or conversion into different
60
            representations like a xml dom.
61
62
            See :mod:`gvm.transforms` for existing transforms.
63
64
    .. _callable:
65
        https://docs.python.org/3/library/functions.html#callable
66
    """
67
68
    def __init__(
69
        self,
70
        connection: GvmConnection,
71
        *,
72
        transform: Optional[Callable[[str], Any]] = None
73
    ):
74
        super().__init__(connection, transform=EtreeCheckCommandTransform())
75
        self._gmp_transform = transform
76
77
    def __enter__(self):
78
        self.connect()
79
        resp = self._send_xml_command(XmlCommand("get_version"))
80
        self.disconnect()
81
82
        version_el = resp.find('version')
83
        if version_el is None:
84
            raise GvmError(
85
                'Invalid response from manager daemon while requesting the '
86
                'version information.'
87
            )
88
89
        version = version_el.text
90
        major_version = version[0]
91
92
        if major_version == '7':
93
            gmp_class = Gmpv7
94
        elif major_version == '8':
95
            gmp_class = Gmpv8
96
        else:
97
            raise GvmError(
98
                'Remote manager daemon uses an unsupported version of GMP.'
99
                'The GMP version was {}'.format(major_version)
100
            )
101
102
        gmp = gmp_class(self._connection, transform=self._gmp_transform)
103
        gmp.connect()
104
105
        return gmp
106