xref: /OK3568_Linux_fs/buildroot/support/testing/tests/download/gitremote.py (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun# subprocess does not kill the child daemon when a test case fails by raising
2*4882a593Smuzhiyun# an exception. So use pexpect instead.
3*4882a593Smuzhiyunimport infra
4*4882a593Smuzhiyun
5*4882a593Smuzhiyunimport pexpect
6*4882a593Smuzhiyun
7*4882a593Smuzhiyun
8*4882a593SmuzhiyunGIT_REMOTE_PORT_INITIAL = 9418
9*4882a593SmuzhiyunGIT_REMOTE_PORT_LAST = GIT_REMOTE_PORT_INITIAL + 99
10*4882a593Smuzhiyun
11*4882a593Smuzhiyun
12*4882a593Smuzhiyunclass GitRemote(object):
13*4882a593Smuzhiyun    def __init__(self, builddir, serveddir, logtofile):
14*4882a593Smuzhiyun        """
15*4882a593Smuzhiyun        Start a local git server.
16*4882a593Smuzhiyun
17*4882a593Smuzhiyun        In order to support test cases in parallel, select the port the
18*4882a593Smuzhiyun        server will listen to in runtime. Since there is no reliable way
19*4882a593Smuzhiyun        to allocate the port prior to starting the server (another
20*4882a593Smuzhiyun        process in the host machine can use the port between it is
21*4882a593Smuzhiyun        selected from a list and it is really allocated to the server)
22*4882a593Smuzhiyun        try to start the server in a port and in the case it is already
23*4882a593Smuzhiyun        in use, try the next one in the allowed range.
24*4882a593Smuzhiyun        """
25*4882a593Smuzhiyun        self.daemon = None
26*4882a593Smuzhiyun        self.port = None
27*4882a593Smuzhiyun        self.logfile = infra.open_log_file(builddir, "gitremote", logtofile)
28*4882a593Smuzhiyun
29*4882a593Smuzhiyun        daemon_cmd = ["git", "daemon", "--reuseaddr", "--verbose",
30*4882a593Smuzhiyun                      "--listen=localhost", "--export-all",
31*4882a593Smuzhiyun                      "--base-path={}".format(serveddir)]
32*4882a593Smuzhiyun        for port in range(GIT_REMOTE_PORT_INITIAL, GIT_REMOTE_PORT_LAST + 1):
33*4882a593Smuzhiyun            cmd = daemon_cmd + ["--port={port}".format(port=port)]
34*4882a593Smuzhiyun            self.logfile.write("> starting git remote with '{}'\n".format(" ".join(cmd)))
35*4882a593Smuzhiyun            self.daemon = pexpect.spawn(cmd[0], cmd[1:], logfile=self.logfile,
36*4882a593Smuzhiyun                                        encoding='utf-8')
37*4882a593Smuzhiyun            ret = self.daemon.expect(["Ready to rumble",
38*4882a593Smuzhiyun                                      "Address already in use"])
39*4882a593Smuzhiyun            if ret == 0:
40*4882a593Smuzhiyun                self.port = port
41*4882a593Smuzhiyun                return
42*4882a593Smuzhiyun        raise SystemError("Could not find a free port to run git remote")
43*4882a593Smuzhiyun
44*4882a593Smuzhiyun    def stop(self):
45*4882a593Smuzhiyun        if self.daemon is None:
46*4882a593Smuzhiyun            return
47*4882a593Smuzhiyun        self.daemon.terminate(force=True)
48