add a script to setup github repositories appropriately
[git-mirror.git] / git_mirror.py
1 # Copyright (c) 2015, Ralf Jung <post@ralfj.de>
2 # All rights reserved.
3
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are met:
6
7 # 1. Redistributions of source code must retain the above copyright notice, this
8 #    list of conditions and the following disclaimer. 
9 # 2. Redistributions in binary form must reproduce the above copyright notice,
10 #    this list of conditions and the following disclaimer in the documentation
11 #    and/or other materials provided with the distribution.
12
13 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
14 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
17 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 #==============================================================================
24 import sys, os, os.path, subprocess
25 import configparser, itertools, re
26 import hmac, hashlib
27 import email.mime.text, email.utils, smtplib
28
29 mail_sender = "null@localhost"
30 config_file = os.path.join(os.path.dirname(__file__), 'git-mirror.conf')
31
32 class GitCommand:
33     def __getattr__(self, name):
34         def call(*args, capture_stderr = False, check = True):
35             '''If <capture_stderr>, return stderr merged with stdout. Otherwise, return stdout and forward stderr to our own.
36                If <check> is true, throw an exception of the process fails with non-zero exit code. Otherwise, do not.
37                In any case, return a pair of the captured output and the exit code.'''
38             cmd = ["git", name.replace('_', '-')] + list(args)
39             with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT if capture_stderr else sys.stderr) as p:
40                 (stdout, stderr) = p.communicate()
41                 assert stderr is None
42                 code = p.returncode
43                 if check and code:
44                     raise Exception("Error running {}: Non-zero exit code".format(cmd))
45             return (stdout.decode('utf-8').strip('\n'), code)
46         return call
47
48 git = GitCommand()
49 git_nullsha = 40*"0"
50
51 def git_is_forced_update(oldsha, newsha):
52     out, code = git.merge_base("--is-ancestor", oldsha, newsha, check = False) # "Check if the first <commit> is an ancestor of the second <commit>"
53     assert not out
54     assert code in (0, 1)
55     return False if code == 0 else True # if oldsha is an ancestor of newsha, then this was a "good" (non-forced) update
56
57 def read_config(defSection = 'DEFAULT'):
58     '''Reads a config file that may have options outside of any section.'''
59     config = configparser.ConfigParser()
60     with open(config_file) as file:
61         stream = itertools.chain(("["+defSection+"]\n",), file)
62         config.read_file(stream)
63     return config
64
65 def send_mail(subject, text, recipients, sender, replyTo = None):
66     assert isinstance(recipients, list)
67     if not len(recipients): return # nothing to do
68     # construct content
69     msg = email.mime.text.MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8')
70     msg['Subject'] = subject
71     msg['Date'] = email.utils.formatdate(localtime=True)
72     msg['From'] = sender
73     msg['To'] = ', '.join(recipients)
74     if replyTo is not None:
75         msg['Reply-To'] = replyTo
76     # put into envelope and send
77     s = smtplib.SMTP('localhost')
78     s.sendmail(sender, recipients, msg.as_string())
79     s.quit()
80
81 class Repo:
82     def __init__(self, name, conf):
83         '''Creates a repository from a section of the git-mirror configuration file'''
84         self.name = name
85         self.local = conf['local']
86         self.owner = conf['owner'] # email address to notify in case of problems
87         self.hmac_secret = conf['hmac-secret'].encode('utf-8')
88         self.deploy_key = conf['deploy-key'] # the SSH ky used for authenticating against remote hosts
89         self.mirrors = {} # maps mirrors to their URLs
90         mirror_prefix = 'mirror-'
91         for name in filter(lambda s: s.startswith(mirror_prefix), conf.keys()):
92             mirror = name[len(mirror_prefix):]
93             self.mirrors[mirror] = conf[name]
94     
95     def mail_owner(self, msg):
96         global mail_sender
97         send_mail("git-mirror {}".format(self.name), msg, recipients = [self.owner], sender = mail_sender)
98
99     def compute_hmac(self, data):
100         h = hmac.new(self.hmac_secret, digestmod = hashlib.sha1)
101         h.update(data)
102         return h.hexdigest()
103     
104     def find_mirror_by_url(self, match_urls):
105         for mirror, url in self.mirrors.items():
106             if url in match_urls:
107                 return mirror
108         return None
109     
110     def setup_env(self):
111         '''Setup the environment to work with this repository'''
112         os.chdir(self.local)
113         ssh_set_ident = os.path.join(os.path.dirname(__file__), 'ssh-set-ident.sh')
114         os.putenv('GIT_SSH', ssh_set_ident)
115         ssh_ident = os.path.join(os.path.expanduser('~/.ssh'), self.deploy_key)
116         os.putenv('GIT_MIRROR_SSH_IDENT', ssh_ident)
117     
118     def update_mirrors(self, ref, oldsha, newsha):
119         '''Update the <ref> from <oldsha> to <newsha> on all mirrors. The update must already have happened locally.'''
120         assert len(oldsha) == 40 and len(newsha) == 40, "These are not valid SHAs."
121         source_mirror = os.getenv("GIT_MIRROR_SOURCE") # in case of a self-call via the hooks, we can skip one of the mirrors
122         self.setup_env()
123         # check for a forced update
124         is_forced = newsha != git_nullsha and oldsha != git_nullsha and git_is_forced_update(oldsha, newsha)
125         # tell all the mirrors
126         for mirror in self.mirrors:
127             if mirror == source_mirror:
128                 continue
129             sys.stdout.write("Updating mirror {}\n".format(mirror)); sys.stdout.flush()
130             # update this mirror
131             if is_forced:
132                 # forcibly update ref remotely (someone already did a force push and hence accepted data loss)
133                 git.push('--force', self.mirrors[mirror], newsha+":"+ref)
134             else:
135                 # nicely update ref remotely (this avoids data loss due to race conditions)
136                 git.push(self.mirrors[mirror], newsha+":"+ref)
137     
138     def update_ref_from_mirror(self, ref, oldsha, newsha, mirror, suppress_stderr = False):
139         '''Update the local version of this <ref> to what's currently on the given <mirror>. <oldsha> and <newsha> are checked. Then update all the other mirrors.'''
140         self.setup_env()
141         url = self.mirrors[mirror]
142         # first check whether the remote really is at newsha
143         remote_state, code = git.ls_remote(url, ref)
144         if remote_state:
145             remote_sha = remote_state.split()[0]
146         else:
147             remote_sha = git_nullsha
148         assert newsha == remote_sha, "Someone lied about the new SHA, which should be {}.".format(newsha)
149         # locally, we have to be at oldsha or newsha (the latter can happen if we already got this update, e.g. if it originated from us)
150         local_state, code = git.show_ref(ref, check=False)
151         if code == 0:
152             local_sha = local_state.split()[0]
153         else:
154             if len(local_state):
155                 raise Exception("Something went wrong getting the local state of {}.".format(ref))
156             local_sha = git_nullsha
157         assert local_sha in (oldsha, newsha), "Someone lied about the old SHA."
158         # if we are already at newsha locally, we also ran the local hooks, so we do not have to do anything
159         if local_sha == newsha:
160             return "Local repository is already up-to-date."
161         # update local state from local_sha to newsha.
162         if newsha != git_nullsha:
163             # We *could* now fetch the remote ref and immediately update the local one. However, then we would have to
164             # decide whether we want to allow a force-update or not. Also, the ref could already have changed remotely,
165             # so that may update to some other commit.
166             # Instead, we just fetch without updating any local ref. If the remote side changed in such a way that
167             # <newsha> is not actually fetched, that's a race and will be noticed when updating the local ref.
168             git.fetch(url, ref, capture_stderr = suppress_stderr)
169             # now update the ref, checking the old value is still local_oldsha.
170             git.update_ref(ref, newsha, 40*"0" if local_sha is None else local_sha)
171         else:
172             # ref does not exist anymore. delete it.
173             assert local_sha != git_nullsha, "Why didn't we bail out earlier if there is nothing to do...?"
174             git.update_ref("-d", ref, local_sha) # this checks that the old value is still local_sha
175         # Now run the post-receive hooks. This will *also* push the changes to all mirrors, as we
176         # are one of these hooks!
177         os.putenv("GIT_MIRROR_SOURCE", mirror) # tell ourselves which repo we do *not* have to update
178         with subprocess.Popen(['/bin/sh', 'hooks/post-receive'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
179             (stdout, stderr) = p.communicate("{} {} {}\n".format(oldsha, newsha, ref).encode('utf-8'))
180             stdout = stdout.decode('utf-8')
181             if p.returncode:
182                 raise Exception("post-receive git hook terminated with non-zero exit code {}:\n{}".format(p.returncode, stdout))
183         return stdout
184
185 def find_repo_by_directory(repos, dir):
186     for (name, repo) in repos.items():
187         if dir == repo.local:
188             return name
189     return None
190
191 def load_repos():
192     global mail_sender
193     conf = read_config()
194     mail_sender = conf['DEFAULT']['mail-sender']
195     
196     repos = {}
197     for name, section in conf.items():
198         if name != 'DEFAULT':
199             repos[name] = Repo(name, section)
200     return repos
201