summaryrefslogtreecommitdiff
path: root/pygerrit/ssh.py
blob: 03952e37e8d8967eec7e62b0686560cc2c42bf95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# The MIT License
#
# Copyright 2012 Sony Mobile Communications. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

""" Gerrit SSH Client. """

from os.path import abspath, expanduser, isfile
import re
import socket
from threading import Event, Lock

from .error import GerritError

from paramiko import AutoAddPolicy, SSHClient, SSHConfig, ProxyCommand
from paramiko.ssh_exception import SSHException


def _extract_version(version_string, pattern):
    """ Extract the version from `version_string` using `pattern`.

    Return the version as a string, with leading/trailing whitespace
    stripped.

    """
    if version_string:
        match = pattern.match(version_string.strip())
        if match:
            return match.group(1)
    return ""


class GerritSSHCommandResult(object):

    """ Represents the results of a Gerrit command run over SSH. """

    def __init__(self, command, stdin, stdout, stderr):
        self.command = command
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr

    def __repr__(self):
        return "<GerritSSHCommandResult [%s]>" % self.command


class GerritSSHClient(SSHClient):

    """ Gerrit SSH Client, wrapping the paramiko SSH Client. """

    def __init__(self, hostname, username=None, port=None,
                 keepalive=None, auto_add_hosts=False):
        """ Initialise and connect to SSH. """
        super(GerritSSHClient, self).__init__()
        self.remote_version = None
        self.hostname = hostname
        self.username = username
        self.key_filename = None
        self.port = port
        self.connected = Event()
        self.lock = Lock()
        self.proxy = None
        self.keepalive = keepalive
        if auto_add_hosts:
            self.set_missing_host_key_policy(AutoAddPolicy())

    def _configure(self):
        """ Configure the ssh parameters from the config file. """
        configfile = expanduser("~/.ssh/config")
        if not isfile(configfile):
            raise GerritError("ssh config file '%s' does not exist" %
                              configfile)

        config = SSHConfig()
        config.parse(open(configfile))
        data = config.lookup(self.hostname)
        if not data:
            raise GerritError("No ssh config for host %s" % self.hostname)
        if 'hostname' not in data or 'port' not in data or 'user' not in data:
            raise GerritError("Missing configuration data in %s" % configfile)
        self.hostname = data['hostname']
        self.username = data['user']
        if 'identityfile' in data:
            key_filename = abspath(expanduser(data['identityfile'][0]))
            if not isfile(key_filename):
                raise GerritError("Identity file '%s' does not exist" %
                                  key_filename)
            self.key_filename = key_filename
        try:
            self.port = int(data['port'])
        except ValueError:
            raise GerritError("Invalid port: %s" % data['port'])
        if 'proxycommand' in data:
            self.proxy = ProxyCommand(data['proxycommand'])

    def _do_connect(self):
        """ Connect to the remote. """
        self.load_system_host_keys()
        if self.username is None or self.port is None:
            self._configure()
        try:
            self.connect(hostname=self.hostname,
                         port=self.port,
                         username=self.username,
                         key_filename=self.key_filename,
                         sock=self.proxy)
        except socket.error as e:
            raise GerritError("Failed to connect to server: %s" % e)

        try:
            version_string = self._transport.remote_version
            pattern = re.compile(r'^.*GerritCodeReview_([a-z0-9-\.]*) .*$')
            self.remote_version = _extract_version(version_string, pattern)
        except AttributeError:
            self.remote_version = None

    def _connect(self):
        """ Connect to the remote if not already connected. """
        if not self.connected.is_set():
            try:
                self.lock.acquire()
                # Another thread may have connected while we were
                # waiting to acquire the lock
                if not self.connected.is_set():
                    self._do_connect()
                    if self.keepalive:
                        self._transport.set_keepalive(self.keepalive)
                    self.connected.set()
            except GerritError:
                raise
            finally:
                self.lock.release()

    def get_remote_version(self):
        """ Return the version of the remote Gerrit server. """
        if self.remote_version is None:
            result = self.run_gerrit_command("version")
            version_string = result.stdout.read()
            pattern = re.compile(r'^gerrit version (.*)$')
            self.remote_version = _extract_version(version_string, pattern)
        return self.remote_version

    def get_remote_info(self):
        """ Return the username, and version of the remote Gerrit server. """
        version = self.get_remote_version()
        return (self.username, version)

    def run_gerrit_command(self, command):
        """ Run the given command.

        Make sure we're connected to the remote server, and run `command`.

        Return the results as a `GerritSSHCommandResult`.

        Raise `ValueError` if `command` is not a string, or `GerritError` if
        command execution fails.

        """
        if not isinstance(command, basestring):
            raise ValueError("command must be a string")
        gerrit_command = "gerrit " + command

        # are we sending non-ascii data?
        try:
            gerrit_command.encode('ascii')
        except UnicodeEncodeError:
            gerrit_command = gerrit_command.encode('utf-8')

        self._connect()
        try:
            stdin, stdout, stderr = self.exec_command(gerrit_command,
                                                      bufsize=1,
                                                      timeout=None,
                                                      get_pty=False)
        except SSHException as err:
            raise GerritError("Command execution error: %s" % err)
        return GerritSSHCommandResult(command, stdin, stdout, stderr)