]> git.donarmstrong.com Git - dsa-puppet.git/blob - modules/roles/files/static-mirroring/static-master-run
d2f364d6ba791873e937c51d63bb92c31f524b91
[dsa-puppet.git] / modules / roles / files / static-mirroring / static-master-run
1 #!/usr/bin/python
2
3 import fcntl
4 import os
5 import shutil
6 import subprocess
7 import string
8 import sys
9 import tempfile
10 import time
11
12 base="/srv/static.debian.org"
13 serialname = '.serial'
14 had_warnings = False
15
16 clients = []
17 with open('/etc/static-clients.conf') as f:
18   for line in f:
19     line = line.strip()
20     if line == "": continue
21     if line.startswith('#'): continue
22     clients.append(line)
23
24 def log(m):
25   t = time.strftime("[%Y-%m-%d %H:%M:%S]", time.gmtime())
26   print t, m
27
28 def stage1(pipes, status):
29   for c in clients:
30     p = pipes[c]
31     while 1:
32       line = p.stdout.readline()
33       if line == '':
34         status[c] = 'failed'
35         p.stdout.close()
36         p.stdin.close()
37         p.wait()
38         log("%s: failed with returncode %d"%(c,p.returncode))
39         break
40
41       line = line.strip()
42       log("%s >> %s"%(c, line))
43       if not line.startswith('[MSM]'): continue
44       kw = string.split(line, ' ', 2)[1]
45
46       if kw == 'ALREADY-CURRENT':
47         pipes[c].stdout.close()
48         pipes[c].stdin.close()
49         p.wait()
50         if p.returncode == 0:
51           log("%s: already current"%(c,))
52           status[c] = 'ok'
53         else:
54           log("%s: said ALREADY-CURRENT but returncode %d"%(c,p.returncode))
55           status[c] = 'failed'
56         break
57       elif kw == 'STAGE1-DONE':
58         log("%s: waiting"%(c,))
59         status[c] = 'waiting'
60         break
61       elif kw in ['STAGE1-START']:
62         pass
63       else:
64         log("%s: ignoring unknown line"%(c,))
65
66 def count_statuses(status):
67   cnt = {}
68   for k in status:
69     v = status[k]
70     if v not in cnt: cnt[v] = 1
71     else: cnt[v] += 1
72   return cnt
73
74 def stage2(pipes, status, command):
75   for c in clients:
76     if status[c] != 'waiting': continue
77     log("%s << %s"%(c, command))
78     pipes[c].stdin.write("%s\n"%(command,))
79
80   for c in clients:
81     if status[c] != 'waiting': continue
82     p = pipes[c]
83
84     (o, dummy) = p.communicate('')
85     for l in string.split(o, "\n"):
86       log("%s >> %s"%(c, l))
87     log("%s: returned %d"%(c, p.returncode))
88
89 def callout(component, serial):
90   log("Calling clients...")
91   pipes = {}
92   status = {}
93   for c in clients:
94     args = ['ssh', '-o', 'BatchMode=yes', c, 'mirror', component, "%d"%(serial,)]
95     p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
96     pipes[c] = p
97     status[c] = 'in-progress'
98
99   log("Stage 1...")
100   stage1(pipes, status)
101   log("Stage 1 done.")
102   cnt = count_statuses(status)
103
104   if 'failed' in cnt and cnt['failed'] >= 2:
105     log("%d clients failed, aborting..."%(cnt['failed'],))
106     stage2(pipes, status, 'abort')
107     return False
108
109   failedmirrorsfile = os.path.join(base, 'master', component + "-failedmirrors")
110   if 'failed' in cnt:
111     log("WARNING: %d clients failed!  Continuing anyway!"%(cnt['failed'],))
112     global had_warnings
113     had_warnings = True
114     f = open(failedmirrorsfile, "w")
115     for c in status:
116       if status[c] == 'failed': f.write(c+"\n")
117     f.close()
118   else:
119     os.unlink(failedmirrorsfile)
120
121   if 'waiting' in cnt:
122     log("Committing...")
123     stage2(pipes, status, 'go')
124     return True
125   else:
126     log("All clients up to date.")
127     return True
128
129
130 cleanup_dirs = []
131 def run_mirror(component):
132   # setup
133   basemaster = os.path.join(base, 'master')
134   componentdir = os.path.join(basemaster, component)
135   cur = componentdir + '-current-push'
136   live = componentdir + '-current-live'
137   tmpdir_new = tempfile.mkdtemp(prefix=component+'-live.new-', dir=basemaster); cleanup_dirs.append(tmpdir_new);
138   tmpdir_old = tempfile.mkdtemp(prefix=component+'-live.old-', dir=basemaster); cleanup_dirs.append(tmpdir_old);
139   os.chmod(tmpdir_new, 0755)
140
141   locks = []
142   for p in (componentdir, live, tmpdir_new):
143     if not os.path.exists(p): os.mkdir(p, 0755)
144     fd = os.open(p, os.O_RDONLY)
145     log("Acquiring lock for %s(%d)."%(p,fd))
146     fcntl.flock(fd, fcntl.LOCK_EX)
147     locks.append(fd)
148   log("All locks acquired.")
149
150   serialfile = os.path.join(componentdir, serialname)
151   try:
152     with open(serialfile) as f: serial = int(f.read())
153   except:
154     serial = int(time.time())
155     with open(serialfile, "w") as f: f.write("%d\n"%(serial,))
156   log("Serial is %s."%(serial,))
157
158   log("Populating %s."%(tmpdir_new,))
159   subprocess.check_call(['cp', '-al', os.path.join(componentdir, '.'), tmpdir_new])
160
161   if os.path.exists(cur):
162     log("Removing existing %s."%(cur,))
163     shutil.rmtree(cur)
164
165   log("Renaming %s to %s."%(tmpdir_new, cur))
166   os.rename(tmpdir_new, cur)
167
168   proceed = callout(component, serial)
169
170   if proceed:
171     log("Moving %s aside."%(live,))
172     os.rename(live, os.path.join(tmpdir_old, 'old'))
173     log("Renaming %s to %s."%(cur, live))
174     os.rename(cur, live)
175     log("Cleaning up.")
176     shutil.rmtree(tmpdir_old)
177     if had_warnings: log("Done, with warnings.")
178     else: log("Done.")
179     ret = True
180   else:
181     log("Aborted.")
182     ret = False
183
184   for fd in locks:
185     os.close(fd)
186
187   return ret
188
189
190 if len(sys.argv) != 2:
191   print >> sys.stderr, "Usage: %s <component>"%(sys.argv[0],)
192   sys.exit(1)
193 component = sys.argv[1]
194
195 ok = False
196 try:
197   ok = run_mirror(component)
198 finally:
199   for p in cleanup_dirs:
200     if os.path.exists(p): shutil.rmtree(p)
201
202 if not ok:
203   sys.exit(1)
204 # vim:set et:
205 # vim:set ts=2:
206 # vim:set shiftwidth=2: