heptapod.py 16.2 KB
Newer Older
1
import contextlib
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from io import BytesIO
import logging
from pathlib import Path
import requests
import selenium.webdriver
import subprocess
import sys
import tarfile
import time
from urllib.parse import urlparse

from tests.utils.user import User
from tests.utils import docker
from tests.utils import session

logger = logging.getLogger(__name__)

19
INITIAL_TIMEOUT = 600  # seconds
20
21
22
23
24
25
26
27
28

BRANCH_PROTECTIONS = dict(none=0,
                          dev_can_push=1,
                          full=2,
                          dev_can_merge=3,
                          )


class Heptapod:
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    """Base class and minimum common control of Heptapod server.

    This is used directly in case `--heptapod-remote` is selected.
    """

    fs_access = False
    """True if manipulation of files is possible.

    Implies :attr:`repositories_root` not to be None.
    """

    shell_access = False
    """True if running arbitrary commands as in a shell is possible."""

    repositories_root = None
    """Path to the repositories, from the Heptapod server point of view.

    This is potentially not meaningful on the system that runs the test,
    see :class:`DockerHeptapod` for an example.
    """
49

50
51
52
53
    reverse_call_host = None
    """Network address for the system running these tests, seen from Heptapod.
    """

54
55
56
    webdriver_remote_url = None
    """URL for a Selenium RemoteWebDriver."""

57
58
59
60
    wait_after_first_response = 0
    """Time to wait after we've had a first non error HTTP response.
    """

61
62
    def __init__(self, url, ssh_user, ssh_port,
                 reverse_call_host=None,
63
                 wait_after_first_response=0,
64
                 webdriver_remote_url=None):
65
66
67
        self.parsed_url = urlparse(url)
        self.url = url
        self.ssh_port = ssh_port
68
        self.ssh_user = ssh_user
69
        self.users = {}
70
71
        if reverse_call_host is not None:
            self.reverse_call_host = reverse_call_host
72
        self.dead = None
73
        self.webdriver_remote_url = webdriver_remote_url
74
        self.wait_after_first_response = wait_after_first_response
75
        self.settings = {}
76

77
78
79
80
    @property
    def heptapod(self):
        return self

81
82
    @property
    def ssh_url(self):
83
        return 'ssh://{user}@{host}:{port}'.format(
84
            host=self.host,
85
            user=self.ssh_user,
86
87
88
            port=self.ssh_port,
        )

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    @property
    def host(self):
        return self.parsed_url.netloc.rsplit(':', 1)[0]

    @property
    def api_url(self):
        return '/'.join((self.url, 'api', 'v4'))

    @property
    def root_token_headers(self):
        return {'Private-Token': self.users['root']['token']}

    @property
    def basic_user_token_headers(self):
        return {'Private-Token': self.users['test_basic']['token']}

105
106
107
108
109
110
111
112
113
114
115
    def new_webdriver(self):
        options = selenium.webdriver.ChromeOptions()
        options.add_argument('--headless')
        if self.webdriver_remote_url:
            return selenium.webdriver.Remote(
                command_executor=self.webdriver_remote_url,
                options=options
            )
        else:
            return selenium.webdriver.Chrome(options=options)

116
117
118
119
120
121
122
123
124
125
126
    def wait_startup(self, first_response_timeout=INITIAL_TIMEOUT,
                     wait_after_first_response=None):
        """Wait for Heptapod to be ready after startup.

        We have to take into account that the server may have just started
        (that's frequent in development and it's annoying for a human to
        wait) or could even be starting from scratch, configuring itself,
        creating the DB schema etc. (typical of CI).
        In that latter case, an amount of extra wait after the first successful
        HTTP response is often needed.
        """
127
        logger.info("Waiting for Heptapod to answer requests")
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
        dead_msg = ("Heptapod server did not "
                    "respond in %s seconds" % first_response_timeout)
        start = time.time()
        while time.time() < start + first_response_timeout:
            try:
                resp = requests.get(self.url, allow_redirects=False)
            except IOError:
                resp = None

            if resp is None:
                logger.debug("Couldn't reach Heptapod")
            elif resp.status_code >= 400:
                logger.debug("Heptapod response code %r", resp.status_code)
            else:
                logger.info("Heptapod is up")
                self.dead = False
                if wait_after_first_response:
                    logger.info("Waiting additional %d seconds "
                                "after first successful HTTP call",
                                wait_after_first_response)
                    time.sleep(wait_after_first_response)
                return

            duration = 1
            logger.debug("Retrying in %.1f seconds", duration)
            time.sleep(duration)

        self.dead = True
        raise AssertionError(dead_msg)

158
159
160
161
162
163
164
165
166
167
168
    def prepare(self, root_password):
        """Make all preparations for the Heptapod instance to be testable.

        This currently amounts to

        - defining the root password
        - activating and retrieving a root API token
        - creating a persistent `test_basic` user
        - activating and retrieving an API token for `test_basic`
        - keeping a logged in webdriver for each persistent user
        """
169
        assert not self.dead, "Heptapod server marked dead by previous test."
170
171

        if self.dead is None:
172
173
            self.wait_startup(
                wait_after_first_response=self.wait_after_first_response)
174
        logger.info("Preparing root user.")
175
        root = self.users['root'] = {}
176
        driver = self.new_webdriver()
177
178
179
        # guaranteeing driver to be available for teardown as soon as created
        root['webdriver'] = driver
        session.login_as_root(driver, self, root_password)
180

181
        logger.info("Preparing application settings.")
182
183
184
185
        # necessary if we want to listen to web hooks from these tests
        # in GitLab v12.2.0, this is deprecated for ...from_web_hooks...
        self.set_application_settings(
            allow_local_requests_from_hooks_and_services="true")
186
187

        logger.info("Preparing basic user.")
188
189
190
191
192
        basic, driver = session.ensure_user(self, 'test_basic',
                                            fullname='Bäsîc Test',
                                            password='test_basic')
        self.users[basic.name]['id'] = basic.id
        self.users[basic.name]['webdriver'] = driver
193
194

        logger.info("Uploading users SSH keys.")
195
196
197
198
199
200
        self.load_ssh_keys()
        self.upload_ssh_pub_keys()
        subprocess.call((
            'ssh-keygen',
            '-R', '[{host}]:{port}'.format(
                host=self.host, port=self.ssh_port)))
201
        logger.info("All preparations done, proceeding with tests.")
202
203

    def set_application_settings(self, **settings):
204
        """Change GitLab application settings and update :attr:`settings`."""
205
206
207
208
209
210
        resp = requests.put(
            self.api_url + '/application/settings',
            headers=self.root_token_headers,
            data=settings,
        )
        assert resp.status_code == 200
211
212
213
214
215
216
217
218
219
220
        self.settings = resp.json()

    def sync_application_settings(self):
        """Update :attr:`settings` for current values"""
        resp = requests.get(
            self.api_url + '/application/settings',
            headers=self.root_token_headers,
        )
        assert resp.status_code == 200
        self.settings = resp.json()
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251

    def load_ssh_keys(self):
        """Load client-side information to use SSH keys

        Also makes sure the keys are actually usable (perms)
        """
        ssh_dir = Path(__file__).parent.parent / 'data' / 'ssh'
        for name, info in self.users.items():
            base_fname = 'id_rsa_heptapod_' + name
            priv = ssh_dir / base_fname
            pub = ssh_dir / (base_fname + '.pub')

            # VCSes tend not to preserve non-executable perm bits
            priv.chmod(0o600)
            info['ssh'] = dict(priv=str(priv), pub=pub.read_text())

    def upload_ssh_pub_keys(self):
        """Upload SSH public keys for all users to Heptapod."""
        # it's really time to put the actual user object in our `self.users`
        for name, info in self.users.items():
            user = User.search(self, name)
            user.ensure_ssh_pub_key(info['ssh']['pub'])

    def close(self):
        if self.dead is not False:
            return
        for user in self.users.values():
            driver = user.get('webdriver')
            if driver is not None:
                driver.close()

252
    def run_shell(self, command, **kw):
253
254
255
256
257
258
259
        raise NotImplementedError('run_shell')

    def force_remove_route(self, route_path, source_type='Project'):
        logger.error("Attempt to force-remove route %r, not implemented "
                     "for %r", route_path, self.__class__)
        raise NotImplementedError('force_remove_route')

260
261
262
263
264
265
    def backup_create(self):
        raise NotImplementedError('backup_create')

    def backup_restore(self):
        raise NotImplementedError('backup_restore')

266
267
268

class DockerHeptapod(Heptapod):

269
270
271
272
    fs_access = True

    shell_access = True

273
274
275
276
277
    repositories_root = '/var/opt/gitlab/git-data/repositories'

    def __init__(self, docker_container, **kw):
        super(DockerHeptapod, self).__init__(**kw)
        self.docker_container = docker_container
278
279
        if self.reverse_call_host is None:
            self.reverse_call_host = docker.host_address(docker_container)
280
281
282
283

    def execute(self, command, user='root'):
        return docker.heptapod_exec(self.docker_container, command, user=user)

284
285
    def run_shell(self, command, **kw):
        return docker.heptapod_run_shell(self.docker_container, command, **kw)
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322

    def put_archive(self, dest, path, owner='git'):
        res = docker.heptapod_put_archive(self.docker_container, dest, path)
        self.run_shell(['chown', '-R', 'git:root', dest])
        return res

    def put_archive_bin(self, dest, fobj):
        return docker.heptapod_put_archive_bin(
            self.docker_container, dest, fobj)

    def get_archive(self, path, tarf):
        return docker.heptapod_get_archive(self.docker_container, path, tarf)

    def put_file_lines(self, path, lines, uid=998, gid=998):
        dirpath, filename = path.rsplit('/', 1)
        tar_buf = BytesIO()
        tarf = tarfile.open(mode='w:', fileobj=tar_buf)

        tinfo = tarfile.TarInfo(name='hgrc')
        contents_buf = BytesIO()
        contents_buf.writelines(l.encode() for l in lines)
        tinfo.size = contents_buf.tell()
        tinfo.uid, tinfo.gid = uid, gid
        contents_buf.seek(0)
        tarf.addfile(tinfo, fileobj=contents_buf)

        tar_buf.seek(0)
        self.put_archive_bin(dirpath, tar_buf)

    def get_file_lines(self, path):
        dirname, filename = path.rsplit('/', 1)
        buf = BytesIO()
        self.get_archive(path, buf)
        buf.seek(0)
        tarf = tarfile.open(mode='r:', fileobj=buf)
        return [l.decode() for l in tarf.extractfile(filename).readlines()]

323
324
325
326
327
328
329
330
331
332
333
334
335
    def force_remove_route(self, route_path, source_type='Project'):
        """Delete a route from the database.

        Sometimes GitLab fails to clean Project routes after failed tests.
        """
        logger.warn("Cleaning up leftover route at %r", route_path)
        self.run_shell([
            'gitlab-psql', 'gitlabhq_production',
            '-c', "DELETE FROM routes "
            "WHERE source_type='%s' "
            "  AND path='%s'" % (source_type, route_path)
        ])

336
337
338
339
340
341
342
343
344
345
346
    def backup_create(self, clean_previous=True):
        """Create a new backup

        :param bool clean_previous: if true, any previously existing backups
            are removed. This is handy so that the restore rake task knows
            which one to restore without any need to tell it.
        """
        # using find in order not to rely on shell expansion for *.tar
        self.run_shell(('find', '/var/opt/gitlab/backups',
                        '-name', '*.tar',
                        '-delete'))
347
        self.run_shell(('gitlab-rake', 'gitlab:backup:create'), user='git')
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363

    @contextlib.contextmanager
    def backup_restore(self):
        """Context manager for backups restoration.

        This is a context manager as a way to provide resuming of the
        tests session on errors, in a convenient way for the caller.
        That means ensuring as much as possible that the server is running,
        maybe wait again for it, reinitialize passwords and tokens…
        """
        app_services = ('unicorn', 'sidekiq')
        try:
            for service in app_services:
                self.run_shell(('gitlab-ctl', 'stop', service))

            self.run_shell(('gitlab-rake', 'gitlab:backup:restore',
364
365
                            'force=yes'),
                           user='git')
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382

            for service in app_services:
                self.run_shell(('gitlab-ctl', 'start', service))

            self.wait_startup()
            yield

        except Exception:
            # these are idempotent
            self.run_shell(('gitlab-ctl', 'start', 'unicorn'))
            self.run_shell(('gitlab-ctl', 'start', 'sidekiq'))

            # Worst case scenario, we lost all our data. We need to
            # reprepare the server for subsequent tests
            self.prepare(self.users['root']['password'])
            raise

383
384
385
386
387
388
389
    def restart_rails(self):
        logger.info("Restarting the Rails application.")
        app_services = ('unicorn', 'sidekiq')
        for service in app_services:
            self.run_shell(('gitlab-ctl', 'restart', service))
        self.wait_startup()

390
391
392
393
394
395
396
397
398
399
400
401
    def apply_hashed_storage_setting(self, hashed_storage):
        # TODO it would be tempting not to restart if the setting is already
        # at the wished value, but this currently cannot take into account
        # rollbacked values that aren't followed by a restart. This will
        # be more complicated and take more time than we can afford right now
        # to really make work.
        self.set_application_settings(hashed_storage_enabled=hashed_storage)
        self.restart_rails()
        # recheck that the setting is applied
        self.sync_application_settings()
        assert self.settings['hashed_storage_enabled'] is hashed_storage

402
403

class SourceHeptapod(Heptapod):
404
405
406
407
408
409
410
411
412
    """An Heptapod server installed from source on the same system.

    Same system means without using any container technology (Docker or
    otherwise) that would insulate the tests from the server.
    """

    fs_access = True

    shell_access = True
413

414
415
    reverse_call_host = 'localhost'

416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
    @property
    def ssh_url(self):
        return 'ssh://{host}:{port}'.format(
            host=self.host,
            port=self.ssh_port,
        )

    def __init__(self, repositories_root, **kw):
        super(SourceHeptapod, self).__init__(**kw)
        self.repositories_root = repositories_root

    def execute(self, command, user='git'):
        if user != 'git':
            raise NotImplementedError(
                "On source Heptapod, only same user as for Rails and HgServe "
                "is allowed")
        process = subprocess.Popen(command,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        out, err = [o.decode() for o in process.communicate()]
        retcode = process.poll()

        if out:
            sys.stdout.write(out)
        if err:
            sys.stderr.write(err)
        return retcode, out

444
445
    def run_shell(self, command, **kw):
        exit_code, output = self.execute(command, **kw)
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
        if exit_code != 0:
            raise RuntimeError(
                ('Heptapod command {command} returned a non-zero '
                 'exit code {exit_code}').format(
                     command=command,
                     exit_code=exit_code,
                 ))

    def put_archive(self, dest, path, owner='git'):
        if owner != 'git':
            raise NotImplementedError(
                "On source Heptapod, only same owner as for Rails and HgServe "
                "is allowed")
        subprocess.check_call(['tar', 'xf', path], cwd=dest)

    def get_file_lines(self, path):
        with open(path, 'r') as fobj:
            return fobj.readlines()

    def put_file_lines(self, path, lines):
        with open(path, 'w') as fobj:
            fobj.writelines(lines)