aboutsummaryrefslogtreecommitdiff
path: root/scripts/mirror-repos
blob: d013b14f6d9b0d7fbd4f4df799c356bd725b222a (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
#!/usr/bin/env python
# Copyright (C) 2013 Linaro Ltd.

import argparse
import os
import subprocess
import sys
import urlparse
import pwd

from tempfile import gettempdir


# Default read-only git URL.
BASE_PATH = "http://git.linaro.org/git-ro/"
# Path to local bin directory, %s is the user name.
LOCAL_BIN_DIR = "/home/%s/.local/bin"
# Default API host for RhodeCode.
DEFAULT_API_HOST = "http://0.0.0.0:5000"
# Name for a lock file.
LOCK_FILE_NAME = "mirror-repos.lock"
LOCK_FILE = os.path.join(gettempdir(), LOCK_FILE_NAME)


def args_parser():
    """Sets up the argument parser."""
    parser = argparse.ArgumentParser()
    parser.add_argument("--repos-list",
                        required=True,
                        help="File with the repository names to mirror.")
    parser.add_argument("--checkout-dir",
                        required=True,
                        help="Where git repositories will be cloned.")
    parser.add_argument("--user",
                        help="User to run the commands as.")
    parser.add_argument("--rescan-repos",
                        action="store_true",
                        help="If the directory containing repositories "
                             "should be re-scanned when adding new ones.")
    parser.add_argument("--api-key",
                        help="The RhodeCode API key to use for re-scanning "
                             "the repositories.")
    parser.add_argument("--api-host",
                        default=DEFAULT_API_HOST,
                        help="The host URL where API interface is located. "
                             "Defaults to '%s'." % DEFAULT_API_HOST)
    return parser


def check_args(args, parser):
    """Checks command line arguments passed.

    :param args: All the command lines as returned by argparse.
    :param parser: The argparse instance.
    """
    if not os.path.exists(args.repos_list) or \
        not os.path.isfile(args.repos_list):
        print ("Error: file '%s' does not exists or is not a regular file." %
                args.repos_list)
        parser.print_usage()
        sys.exit(1)

    if not os.path.exists(args.checkout_dir) or \
        not os.path.isdir(args.checkout_dir):
        print ("Error: directory '%s' does not exists or cannot be "
               "accessed." % args.checkout_dir)
        parser.print_usage()
        sys.exit(1)

    if args.rescan_repos:
        if not args.api_key:
            print ("It is necessary to specify the API key of the admin user "
                   "to perform the rescan operation.")
            parser.print_usage()
            sys.exit(1)
        # Just print a warning...
        if args.api_host == DEFAULT_API_HOST:
            print ("Warning: default API host will be used: "
                   "%s" % DEFAULT_API_HOST)


def mirror_repos(file, dest, user=None):
    """Clone a mirror copy of a remote repository from git.linaro.org.

    :param file: The file where to read the repositories to mirror.
    :param dest: The directory where to clone the repositories into.
    """
    for line in open(file).readlines():
        line = line.strip()
        base_dir = os.path.basename(line)
        # Git repos need to have a valid name.
        if base_dir.split(".git")[0]:
            # Maintain the same directory layout of original git.linaro.org.
            full_path = os.path.join(dest, line.split(base_dir)[0])

            # Skip if repository is already there.
            if os.path.exists(os.path.join(full_path, base_dir)):
                continue
            # We need to do so, to create the directory as the RhodeCode user
            # for our installation.
            cmd_args = ["mkdir", "-p", full_path]
            execute_command(cmd_args, user=user)

            # We mirror the original repository, then through a cron job we can
            # easily update it using the command 'git fetch -q'.
            full_repo = urlparse.urljoin(BASE_PATH, line)
            cmd_args = ["git", "clone", "--mirror", full_repo]

            print "Cloning repository %s..." % full_repo
            execute_command(cmd_args, work_dir=full_path, user=user)


def rescan_git_directory(api_key, api_host, user=None):
    """Rescans git directories for new repositories added.

    :param api_key: The RhodeCode API key.
    :type str
    :param api_host: The RhodeCode host where to run the remote command.
    :type str
    :param user: The user to run the command as.
    :type str
    """
    if not user:
        # Try to gess a user.
        user = pwd.getpwuid(os.getuid())[0]

    api_key_cmd = "--apikey=%s" % str(api_key)
    api_host_cmd = "--apihost=%s" % api_host

    api_cmd = os.path.join(LOCAL_BIN_DIR % user, "rhodecode-api")
    cmd_args = [api_cmd, api_key_cmd, api_host_cmd, "rescan_repos"]
    execute_command(cmd_args, user=user)


def execute_command(cmd_args, as_sudo=True, user=None, work_dir=os.getcwd()):
    """Executes the command using Popen.

    :param cmd_args: The list of command and parameters to run.
    :param as_sudo: If the command has to be run with 'sudo'.
    :param user: Runs the comand as the specified user.
    :param work_dir: Where the command should be run from.
    """
    exec_args = []
    if not isinstance(cmd_args, list):
        cmd_args = [cmd_args]

    if as_sudo:
        exec_args = ["sudo"]

    if user and as_sudo:
        exec_args += ["-u", user, "-H"]

    exec_args += cmd_args
    process = subprocess.Popen(exec_args,
                               cwd=work_dir,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    p_out, p_err = process.communicate()

    if process.returncode != 0:
        print "Error executing the following command: %s" % " ".join(cmd_args)


if __name__ == '__main__':
    parser = args_parser()
    args = parser.parse_args()
    check_args(args, parser)

    if os.path.exists(LOCK_FILE):
        print "Another process is still running: cannot acquire lock."
    else:
        try:
            with open(LOCK_FILE, 'w'):
                mirror_repos(args.repos_list,
                             args.checkout_dir,
                             user=args.user)

                if args.rescan_repos:
                    print "Re-scanning git repositories directory..."
                    rescan_git_directory(args.api_key,
                                         args.api_host,
                                         user=args.user)
        finally:
            os.unlink(LOCK_FILE)