add license headers and COPYING
[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, subprocess
25 import configparser, itertools, json, re
26 import email.mime.text, email.utils, smtplib
27
28 class GitCommand:
29     def __getattr__(self, name):
30         def call(*args, capture_stderr = False, check = True):
31             '''If <capture_stderr>, return stderr merged with stdout. Otherwise, return stdout and forward stderr to our own.
32                If <check> is true, throw an exception of the process fails with non-zero exit code. Otherwise, do not.
33                In any case, return a pair of the captured output and the exit code.'''
34             cmd = ["git", name.replace('_', '-')] + list(args)
35             with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT if capture_stderr else None) as p:
36                 (stdout, stderr) = p.communicate()
37                 assert stderr is None
38                 code = p.returncode
39                 if check and code:
40                     raise Exception("Error running {0}: Non-zero exit code".format(cmd))
41             return (stdout.decode('utf-8').strip('\n'), code)
42         return call
43
44 git = GitCommand()
45 git_nullsha = 40*"0"
46
47 def git_is_forced_update(oldsha, newsha):
48     out, code = git.merge_base("--is-ancestor", oldsha, newsha, check = False) # "Check if the first <commit> is an ancestor of the second <commit>"
49     assert not out
50     assert code in (0, 1)
51     return False if code == 0 else True # if oldsha is an ancestor of newsha, then this was a "good" (non-forced) update
52
53 def read_config(fname, defSection = 'DEFAULT'):
54     '''Reads a config file that may have options outside of any section.'''
55     config = configparser.ConfigParser()
56     with open(fname) as file:
57         stream = itertools.chain(("["+defSection+"]\n",), file)
58         config.read_file(stream)
59     return config
60
61 def send_mail(subject, text, receivers, sender='post+webhook@ralfj.de', replyTo=None):
62     assert isinstance(receivers, list)
63     if not len(receivers): return # nothing to do
64     # construct content
65     msg = email.mime.text.MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8')
66     msg['Subject'] = subject
67     msg['Date'] = email.utils.formatdate(localtime=True)
68     msg['From'] = sender
69     msg['To'] = ', '.join(receivers)
70     if replyTo is not None:
71         msg['Reply-To'] = replyTo
72     # put into envelope and send
73     s = smtplib.SMTP('localhost')
74     s.sendmail(sender, receivers, msg.as_string())
75     s.quit()
76
77 def get_github_payload():
78     '''Reeturn the github-style JSON encoded payload (as if we were called as a github webhook)'''
79     try:
80         data = sys.stdin.buffer.read()
81         data = json.loads(data.decode('utf-8'))
82         return data
83     except:
84         return {} # nothing read
85
86 class Repo:
87     def __init__(self, name, conf):
88         '''Creates a repository from a section of the git-mirror configuration file'''
89         self.name = name
90         self.local = conf['local']
91         self.owner = conf['owner'] # email address to notify in case of problems
92         self.mirrors = {} # maps mirrors to their URLs
93         mirror_prefix = 'mirror-'
94         for name in filter(lambda s: s.startswith(mirror_prefix), conf.keys()):
95             mirror = name[len(mirror_prefix):]
96             self.mirrors[mirror] = conf[name]
97     
98     def mail_owner(self, msg):
99         send_mail("git-mirror {0}".format(self.name), msg, [self.owner])
100     
101     def find_mirror_by_url(self, match_urls):
102         for mirror, url in self.mirrors.items():
103             if url in match_urls:
104                 return mirror
105         return None
106     
107     def update_mirrors(self, ref, oldsha, newsha, except_mirrors = [], suppress_stderr = False):
108         '''Update the <ref> from <oldsha> to <newsha> on all mirrors. The update must already have happened locally.'''
109         assert len(oldsha) == 40 and len(newsha) == 40, "These are not valid SHAs."
110         os.chdir(self.local)
111         # check for a forced update
112         is_forced = newsha != git_nullsha and oldsha != git_nullsha and git_is_forced_update(oldsha, newsha)
113         # tell all the mirrors
114         for mirror in self.mirrors:
115             if mirror in except_mirrors:
116                 continue
117             # update this mirror
118             if is_forced:
119                 # forcibly update ref remotely (someone already did a force push and hence accepted data loss)
120                 git.push('--force', self.mirrors[mirror], newsha+":"+ref, capture_stderr = suppress_stderr)
121             else:
122                 # nicely update ref remotely (this avoids data loss due to race conditions)
123                 git.push(self.mirrors[mirror], newsha+":"+ref, capture_stderr = suppress_stderr)
124     
125     def update_ref_from_mirror(self, ref, oldsha, newsha, mirror, suppress_stderr = False):
126         '''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.'''
127         os.chdir(self.local)
128         url = self.mirrors[mirror]
129         # first check whether the remote really is at newsha
130         remote_state, code = git.ls_remote(url, ref)
131         if remote_state:
132             remote_sha = remote_state.split()[0]
133         else:
134             remote_sha = git_nullsha
135         assert newsha == remote_sha, "Someone lied about the new SHA, which should be {0}.".format(newsha)
136         # 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)
137         local_state, code = git.show_ref(ref, check=False)
138         if code == 0:
139             local_sha = local_state.split()[0]
140         else:
141             if len(local_state):
142                 raise Exception("Something went wrong getting the local state of {0}.".format(ref))
143             local_sha = git_nullsha
144         assert local_sha in (oldsha, newsha), "Someone lied about the old SHA."
145         # if we are already at newsha locally, we also ran the local hooks, so we do not have to do anything
146         if local_sha == newsha:
147             return
148         # update local state from local_sha to newsha.
149         if newsha != git_nullsha:
150             # We *could* now fetch the remote ref and immediately update the local one. However, then we would have to
151             # decide whether we want to allow a force-update or not. Also, the ref could already have changed remotely,
152             # so that may update to some other commit.
153             # Instead, we just fetch without updating any local ref. If the remote side changed in such a way that
154             # <newsha> is not actually fetched, that's a race and will be noticed when updating the local ref.
155             git.fetch(url, ref, capture_stderr = suppress_stderr)
156             # now update the ref, checking the old value is still local_oldsha.
157             git.update_ref(ref, newsha, 40*"0" if local_sha is None else local_sha)
158         else:
159             # ref does not exist anymore. delete it.
160             assert local_sha != git_nullsha, "Why didn't we bail out earlier if there is nothing to do...?"
161             git.update_ref("-d", ref, local_sha) # this checks that the old value is still local_sha
162         # update all the mirrors
163         self.update_mirrors(ref, oldsha, newsha, [mirror], suppress_stderr)
164
165 def find_repo_by_directory(repos, dir):
166     for (name, repo) in repos.items():
167         if dir == repo.local:
168             return name
169     return None
170
171 def load_repos():
172     conffile = os.path.join(os.path.dirname(__file__), 'git-mirror.conf')
173     conf = read_config(conffile)
174     repos = {}
175     for name, section in conf.items():
176         if name != 'DEFAULT':
177             repos[name] = Repo(name, section)
178     return repos
179