]> scripts.mit.edu Git - wizard.git/blob - wizard/deploy.py
Rename .scripts-version (deprecated) and add utility rollback script.
[wizard.git] / wizard / deploy.py
1 import os.path
2 import math
3 import fileinput
4 import dateutil.parser
5 import distutils.version
6
7 import wizard
8
9 def getInstallLines(global_options):
10     """Retrieves a list of lines from the version directory that
11     can be passed to Deployment.parse()"""
12     vs = global_options.versions
13     if os.path.isfile(vs):
14         return fileinput.input([vs])
15     return fileinput.input([vs + "/" + f for f in os.listdir(vs)])
16
17 class Deployment(object):
18     """Represents a deployment of an autoinstall; i.e. a concrete
19     directory in web_scripts that has .scripts-version in it."""
20     def __init__(self, location, log=None, version=None):
21         """ `location`  Location of the deployment
22             `version`   ApplicationVersion of the app (this is cached info)
23             `log`       DeployLog of the app"""
24         self.location = location
25         self._version = version
26         self._log = log
27     @staticmethod
28     def parse(line):
29         """Parses a line from the results of parallel-find.pl.
30         This will work out of the box with fileinput, see
31         getInstallLines()"""
32         line = line.rstrip()
33         try:
34             location, deploydir = line.split(":")
35         except ValueError:
36             return Deployment(line) # lazy loaded version
37         return Deployment(location, version=ApplicationVersion.parse(deploydir))
38     @staticmethod
39     def fromDir(dir):
40         """Lazily creates a deployment from a directory"""
41         return Deployment(dir)
42     def getVersionFile(self):
43         return os.path.join(self.location, '.scripts-version')
44     def getApplication(self):
45         return self.getAppVersion().application
46     def getLog(self):
47         if not self._log:
48             self._log = DeployLog.load(self.getVersionFile())
49         return self._log
50     def getVersion(self):
51         """Returns the distutils Version of the deployment"""
52         return self.getAppVersion().version
53     def getAppVersion(self, force = False):
54         """Returns the ApplicationVersion of the deployment"""
55         if self._version and not force: return self._version
56         else: return self.getLog()[-1].version
57     def count(self):
58         """Simple method which registers the deployment as a +1 on the
59         appropriate version. No further inspection is done."""
60         self.getAppVersion().count(self)
61         return True
62     def count_exists(self, file):
63         """Checks if the codebase has a certain file/directory in it."""
64         if os.path.exists(self.location + "/" + file):
65             self.getAppVersion().count_exists(self, file)
66             return True
67         return False
68
69 class Application(object):
70     """Represents the generic notion of an application, i.e.
71     mediawiki or phpbb."""
72     def __init__(self, name):
73         self.name = name
74         self.versions = {}
75         # This is 'wizard summary' specific code
76         self._total = 0
77         self._max   = 0
78         self._c_exists = {}
79     def getRepository(self):
80         """Returns the Git repository that would contain this application."""
81         repo = os.path.join("/afs/athena.mit.edu/contrib/scripts/wizard/srv", self.name + ".git")
82         if not os.path.isdir(repo):
83             raise NoRepositoryError(app)
84         return repo
85     def getVersion(self, version):
86         if version not in self.versions:
87             self.versions[version] = ApplicationVersion(distutils.version.LooseVersion(version), self)
88         return self.versions[version]
89     # XXX: This code should go in summary.py; maybe as a mixin, maybe as
90     # a visitor acceptor
91     HISTOGRAM_WIDTH = 30
92     def _graph(self, v):
93         return '+' * int(math.ceil(float(v)/self._max * self.HISTOGRAM_WIDTH))
94     def report(self):
95         if not self.versions: return "%-11s   no installs" % self.name
96         ret = \
97             ["%-16s %3d installs" % (self.name, self._total)] + \
98             [v.report() for v in sorted(self.versions.values())]
99         for f,c in self._c_exists.items():
100             ret.append("%d users have %s" % (c,f))
101         return "\n".join(ret)
102
103 class DeployLog(list):
104     # As per #python; if you decide to start overloading magic methods,
105     # we should remove this subclass
106     """Equivalent to .scripts-version: a series of DeployRevisions."""
107     def __init__(self, revs = []):
108         """`revs`  List of DeployRevision objects"""
109         list.__init__(self, revs) # pass to list
110     @staticmethod
111     def load(file):
112         """Loads a scripts version file and parses it into
113         DeployLog and DeployRevision objects"""
114         i = 0
115         rev = DeployRevision()
116         revs = []
117         def append(rev):
118             if i:
119                 if i != 4:
120                     raise ScriptsVersionNotEnoughFieldsError()
121                 revs.append(rev)
122         try:
123             fh = open(file)
124         except IOError:
125             raise ScriptsVersionNoSuchFile(file)
126         # XXX: possibly rewrite this parsing code. This might
127         # be legacy soon
128         for line in fh:
129             line = line.rstrip()
130             if not line:
131                 append(rev)
132                 i = 0
133                 rev = DeployRevision()
134                 continue
135             if i == 0:
136                 # we need the dateutil parser in order to
137                 # be able to parse time offsets
138                 rev.datetime = dateutil.parser.parse(line)
139             elif i == 1:
140                 rev.user = line
141             elif i == 2:
142                 rev.source = DeploySource.parse(line)
143             elif i == 3:
144                 rev.version = ApplicationVersion.parse(line)
145             else:
146                 # ruh oh
147                 raise ScriptsVersionTooManyFieldsError()
148             i += 1
149         append(rev)
150         return DeployLog(revs)
151     def __repr__(self):
152         return '<DeployLog %s>' % list.__repr__(self)
153
154 class DeployRevision(object):
155     """A single entry in the .scripts-version file. Contains who deployed
156     this revision, what application version this is, etc."""
157     def __init__(self, datetime=None, user=None, source=None, version=None):
158         """ `datetime`  Time this revision was deployed
159             `user`      Person who deployed this revision, in user@host format.
160             `source`    Instance of DeploySource
161             `version`   Instance of ApplicationVersion
162         Note: This object is typically built incrementally."""
163         self.datetime = datetime
164         self.user = user
165         self.source = source
166         self.version = version
167
168 class DeploySource(object):
169     """Source of the deployment; see subclasses for examples"""
170     def __init__(self):
171         raise NotImplementedError # abstract class
172     @staticmethod
173     def parse(line):
174         # munge out common prefix
175         rel = os.path.relpath(line, "/afs/athena.mit.edu/contrib/scripts/")
176         parts = rel.split("/")
177         if parts[0] == "wizard":
178             return WizardUpdate()
179         elif parts[0] == "deploy" or parts[0] == "deploydev":
180             isDev = ( parts[0] == "deploydev" )
181             try:
182                 if parts[1] == "updates":
183                     return OldUpdate(isDev)
184                 else:
185                     return TarballInstall(line, isDev)
186             except IndexError:
187                 pass
188         return UnknownDeploySource(line)
189
190 class TarballInstall(DeploySource):
191     """Original installation from tarball, characterized by
192     /afs/athena.mit.edu/contrib/scripts/deploy/APP-x.y.z.tar.gz
193     """
194     def __init__(self, location, isDev):
195         self.location = location
196         self.isDev = isDev
197
198 class OldUpdate(DeploySource):
199     """Upgrade using old upgrade infrastructure, characterized by
200     /afs/athena.mit.edu/contrib/scripts/deploydev/updates/update-scripts-version.pl
201     """
202     def __init__(self, isDev):
203         self.isDev = isDev
204
205 class WizardUpdate(DeploySource):
206     """Upgrade using wizard infrastructure, characterized by
207     /afs/athena.mit.edu/contrib/scripts/wizard/bin/wizard HASHGOBBLEDYGOOK
208     """
209     def __init__(self):
210         pass
211
212 class UnknownDeploySource(DeploySource):
213     """Deployment that we don't know the meaning of. Wot!"""
214     def __init__(self, line):
215         self.line = line
216
217 class ApplicationVersion(object):
218     """Represents an abstract notion of a version for an application"""
219     def __init__(self, version, application):
220         """ `version`       Instance of distutils.LooseVersion
221             `application`   Instance of Application
222         WARNING: Please don't call this directly; instead, use getVersion()
223         on the application you want, so that this version gets registered."""
224         self.version = version
225         self.application = application
226         self.c = 0
227         self.c_exists = {}
228     def getScriptsTag(self):
229         """Returns the name of the Git tag for this version"""
230         # XXX: This assume sthat there's only a -scripts version
231         # which will not be true in the future.
232         return "v%s-scripts" % self.version
233     def __cmp__(x, y):
234         return cmp(x.version, y.version)
235     @staticmethod
236     def parse(deploydir,applookup=None):
237         # The version of the deployment, will be:
238         #   /afs/athena.mit.edu/contrib/scripts/deploy/APP-x.y.z for old style installs
239         #   /afs/athena.mit.edu/contrib/scripts/wizard/srv/APP.git vx.y.z-scripts for new style installs
240         name = deploydir.split("/")[-1]
241         try:
242             if name.find(" ") != -1:
243                 raw_app, raw_version = name.split(" ")
244                 version = raw_version[1:] # remove leading v
245                 app, _ = raw_app.split(".") # remove trailing .git
246             elif name.find("-") != -1:
247                 app, version = name.split("-")
248             # XXX: this should be removed after the next parallel-find run
249             elif name == "deploy":
250                 # Assume that it's django, since those were botched
251                 app = "django"
252                 version = "0.1-scripts"
253             else:
254                 raise DeploymentParseError(deploydir)
255         except ValueError: # mostly from the a, b = foo.split(' ')
256             raise DeploymentParseError(deploydir)
257         if not applookup: applookup = applications
258         try:
259             # defer to the application for version creation
260             return applookup[app].getVersion(version)
261         except KeyError:
262             raise NoSuchApplication
263     # This is summary specific code
264     def count(self, deployment):
265         self.c += 1
266         self.application._total += 1
267         if self.c > self.application._max:
268             self.application._max = self.c
269     def count_exists(self, deployment, n):
270         if n in self.c_exists: self.c_exists[n] += 1
271         else: self.c_exists[n] = 1
272         if n in self.application._c_exists: self.application._c_exists[n] += 1
273         else: self.application._c_exists[n] = 1
274     def report(self):
275         return "    %-12s %3d  %s" \
276             % (self.version, self.c, self.application._graph(self.c))
277
278 class Error(wizard.Error):
279     """Base error class for deploy errors"""
280     pass
281
282 class NoSuchApplication(Error):
283     pass
284
285 class DeploymentParseError(Error):
286     def __init__(self, malformed):
287         self.malformed = malformed
288     def __str__(self):
289         return """
290
291 ERROR: Could not parse deployment string:
292 %s
293 """ % self.malformed
294
295 class ScriptsVersionTooManyFieldsError(Error):
296     def __str__(self):
297         return """
298
299 ERROR: Could not parse .scripts-version file.  It
300 contained too many fields.
301 """
302
303 class ScriptsVersionNotEnoughFieldsError(Error):
304     def __str__(self):
305         return """
306
307 ERROR: Could not parse .scripts-version file. It
308 didn't contain enough fields.
309 """
310
311 class ScriptsVersionNoSuchFile(Error):
312     def __init__(self, file):
313         self.file = file
314     def __str__(self):
315         return """
316
317 ERROR: File %s didn't exist.
318 """ % self.file
319
320 # If you want, you can wrap this up into a registry and access things
321 # through that, but it's not really necessary
322
323 application_list = [
324     "mediawiki", "wordpress", "joomla", "e107", "gallery2",
325     "phpBB", "advancedbook", "phpical", "trac", "turbogears", "django",
326     # these are technically deprecated
327     "advancedpoll", "gallery",
328 ]
329
330 """Hash table for looking up string application name to instance"""
331 applications = dict([(n,Application(n)) for n in application_list ])
332