summaryrefslogtreecommitdiff
path: root/scripts/profiling/mail/couchdb_wrapper.py
blob: cad1205b72605e834ff602bbb29975645e18ab3e (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
import re
import os
import tempfile
import subprocess
import time
import shutil


from leap.common.files import mkdir_p


class CouchDBWrapper(object):
    """
    Wrapper for external CouchDB instance.
    """

    def start(self):
        """
        Start a CouchDB instance for a test.
        """
        self.tempdir = tempfile.mkdtemp(suffix='.couch.test')

        path = os.path.join(os.path.dirname(__file__),
                            'couchdb.ini.template')
        handle = open(path)
        conf = handle.read() % {
            'tempdir': self.tempdir,
        }
        handle.close()

        confPath = os.path.join(self.tempdir, 'test.ini')
        handle = open(confPath, 'w')
        handle.write(conf)
        handle.close()

        # create the dirs from the template
        mkdir_p(os.path.join(self.tempdir, 'lib'))
        mkdir_p(os.path.join(self.tempdir, 'log'))
        args = ['couchdb', '-n', '-a', confPath]
        null = open('/dev/null', 'w')

        self.process = subprocess.Popen(
            args, env=None, stdout=null.fileno(), stderr=null.fileno(),
            close_fds=True)
        # find port
        logPath = os.path.join(self.tempdir, 'log', 'couch.log')
        while not os.path.exists(logPath):
            if self.process.poll() is not None:
                got_stdout, got_stderr = "", ""
                if self.process.stdout is not None:
                    got_stdout = self.process.stdout.read()

                if self.process.stderr is not None:
                    got_stderr = self.process.stderr.read()
                raise Exception("""
couchdb exited with code %d.
stdout:
%s
stderr:
%s""" % (
                    self.process.returncode, got_stdout, got_stderr))
            time.sleep(0.01)
        while os.stat(logPath).st_size == 0:
            time.sleep(0.01)
        PORT_RE = re.compile(
            'Apache CouchDB has started on http://127.0.0.1:(?P<port>\d+)')

        handle = open(logPath)
        m = None
        line = handle.readline()
        while m is None:
            m = PORT_RE.search(line)
            line = handle.readline()
        handle.close()
        self.port = int(m.group('port'))

    def stop(self):
        """
        Terminate the CouchDB instance.
        """
        self.process.terminate()
        self.process.communicate()
        shutil.rmtree(self.tempdir)