]> scripts.mit.edu Git - wizard.git/blob - wizard/deploy.py
Fix remnant module prefix _base.
[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 getVersion(self, version):
80         if version not in self.versions:
81             self.versions[version] = ApplicationVersion(distutils.version.LooseVersion(version), self)
82         return self.versions[version]
83     # XXX: This code should go in summary.py; maybe as a mixin, maybe as
84     # a visitor acceptor
85     HISTOGRAM_WIDTH = 30
86     def _graph(self, v):
87         return '+' * int(math.ceil(float(v)/self._max * self.HISTOGRAM_WIDTH))
88     def report(self):
89         if not self.versions: return "%-11s   no installs" % self.name
90         ret = \
91             ["%-16s %3d installs" % (self.name, self._total)] + \
92             [v.report() for v in sorted(self.versions.values())]
93         for f,c in self._c_exists.items():
94             ret.append("%d users have %s" % (c,f))
95         return "\n".join(ret)
96
97 class DeployLog(list):
98     # As per #python; if you decide to start overloading magic methods,
99     # we should remove this subclass
100     """Equivalent to .scripts-version: a series of DeployRevisions."""
101     def __init__(self, revs = []):
102         """`revs`  List of DeployRevision objects"""
103         list.__init__(self, revs) # pass to list
104     @staticmethod
105     def load(file):
106         """Loads a scripts version file and parses it into
107         DeployLog and DeployRevision objects"""
108         i = 0
109         rev = DeployRevision()
110         revs = []
111         def append(rev):
112             if i:
113                 if i != 4:
114                     raise ScriptsVersionNotEnoughFieldsError()
115                 revs.append(rev)
116         try:
117             fh = open(file)
118         except IOError:
119             raise ScriptsVersionNoSuchFile(file)
120         # XXX: possibly rewrite this parsing code. This might
121         # be legacy soon
122         for line in fh:
123             line = line.rstrip()
124             if not line:
125                 append(rev)
126                 i = 0
127                 rev = DeployRevision()
128                 continue
129             if i == 0:
130                 # we need the dateutil parser in order to
131                 # be able to parse time offsets
132                 rev.datetime = dateutil.parser.parse(line)
133             elif i == 1:
134                 rev.user = line
135             elif i == 2:
136                 rev.source = DeploySource.parse(line)
137             elif i == 3:
138                 rev.version = ApplicationVersion.parse(line)
139             else:
140                 # ruh oh
141                 raise ScriptsVersionTooManyFieldsError()
142             i += 1
143         append(rev)
144         return DeployLog(revs)
145     def __repr__(self):
146         return '<DeployLog %s>' % list.__repr__(self)
147
148 class DeployRevision(object):
149     """A single entry in the .scripts-version file. Contains who deployed
150     this revision, what application version this is, etc."""
151     def __init__(self, datetime=None, user=None, source=None, version=None):
152         """ `datetime`  Time this revision was deployed
153             `user`      Person who deployed this revision, in user@host format.
154             `source`    Instance of DeploySource
155             `version`   Instance of ApplicationVersion
156         Note: This object is typically built incrementally."""
157         self.datetime = datetime
158         self.user = user
159         self.source = source
160         self.version = version
161
162 class DeploySource(object):
163     """Source of the deployment; see subclasses for examples"""
164     def __init__(self):
165         raise NotImplementedError # abstract class
166     @staticmethod
167     def parse(line):
168         # munge out common prefix
169         rel = os.path.relpath(line, "/afs/athena.mit.edu/contrib/scripts/")
170         parts = rel.split("/")
171         if parts[0] == "wizard":
172             return WizardUpdate()
173         elif parts[0] == "deploy" or parts[0] == "deploydev":
174             isDev = ( parts[0] == "deploydev" )
175             try:
176                 if parts[1] == "updates":
177                     return OldUpdate(isDev)
178                 else:
179                     return TarballInstall(line, isDev)
180             except IndexError:
181                 pass
182         return UnknownDeploySource(line)
183
184 class TarballInstall(DeploySource):
185     """Original installation from tarball, characterized by
186     /afs/athena.mit.edu/contrib/scripts/deploy/APP-x.y.z.tar.gz
187     """
188     def __init__(self, location, isDev):
189         self.location = location
190         self.isDev = isDev
191
192 class OldUpdate(DeploySource):
193     """Upgrade using old upgrade infrastructure, characterized by
194     /afs/athena.mit.edu/contrib/scripts/deploydev/updates/update-scripts-version.pl
195     """
196     def __init__(self, isDev):
197         self.isDev = isDev
198
199 class WizardUpdate(DeploySource):
200     """Upgrade using wizard infrastructure, characterized by
201     /afs/athena.mit.edu/contrib/scripts/wizard/bin/wizard HASHGOBBLEDYGOOK
202     """
203     def __init__(self):
204         pass
205
206 class UnknownDeploySource(DeploySource):
207     """Deployment that we don't know the meaning of. Wot!"""
208     def __init__(self, line):
209         self.line = line
210
211 class ApplicationVersion(object):
212     """Represents an abstract notion of a version for an application"""
213     def __init__(self, version, application):
214         """ `version`       Instance of distutils.LooseVersion
215             `application`   Instance of Application
216         WARNING: Please don't call this directly; instead, use getVersion()
217         on the application you want, so that this version gets registered."""
218         self.version = version
219         self.application = application
220         self.c = 0
221         self.c_exists = {}
222     def __cmp__(x, y):
223         return cmp(x.version, y.version)
224     @staticmethod
225     def parse(deploydir,applookup=None):
226         # The version of the deployment, will be:
227         #   /afs/athena.mit.edu/contrib/scripts/deploy/APP-x.y.z for old style installs
228         #   /afs/athena.mit.edu/contrib/scripts/wizard/srv/APP.git vx.y.z-scripts for new style installs
229         name = deploydir.split("/")[-1]
230         try:
231             if name.find(" ") != -1:
232                 raw_app, raw_version = name.split(" ")
233                 version = raw_version[1:] # remove leading v
234                 app, _ = raw_app.split(".") # remove trailing .git
235             elif name.find("-") != -1:
236                 app, version = name.split("-")
237             # XXX: this should be removed after the next parallel-find run
238             elif name == "deploy":
239                 # Assume that it's django, since those were botched
240                 app = "django"
241                 version = "0.1-scripts"
242             else:
243                 raise DeploymentParseError(deploydir)
244         except ValueError: # mostly from the a, b = foo.split(' ')
245             raise DeploymentParseError(deploydir)
246         if not applookup: applookup = applications
247         try:
248             # defer to the application for version creation
249             return applookup[app].getVersion(version)
250         except KeyError:
251             raise NoSuchApplication
252     # This is summary specific code
253     def count(self, deployment):
254         self.c += 1
255         self.application._total += 1
256         if self.c > self.application._max:
257             self.application._max = self.c
258     def count_exists(self, deployment, n):
259         if n in self.c_exists: self.c_exists[n] += 1
260         else: self.c_exists[n] = 1
261         if n in self.application._c_exists: self.application._c_exists[n] += 1
262         else: self.application._c_exists[n] = 1
263     def report(self):
264         return "    %-12s %3d  %s" \
265             % (self.version, self.c, self.application._graph(self.c))
266
267 class Error(wizard.Error):
268     """Base error class for deploy errors"""
269     pass
270
271 class NoSuchApplication(Error):
272     pass
273
274 class DeploymentParseError(Error):
275     def __init__(self, malformed):
276         self.malformed = malformed
277     def __str__(self):
278         return """
279
280 ERROR: Could not parse deployment string:
281 %s
282 """ % self.malformed
283
284 class ScriptsVersionTooManyFieldsError(Error):
285     def __str__(self):
286         return """
287
288 ERROR: Could not parse .scripts-version file.  It
289 contained too many fields.
290 """
291
292 class ScriptsVersionNotEnoughFieldsError(Error):
293     def __str__(self):
294         return """
295
296 ERROR: Could not parse .scripts-version file. It
297 didn't contain enough fields.
298 """
299
300 class ScriptsVersionNoSuchFile(Error):
301     def __init__(self, file):
302         self.file = file
303     def __str__(self):
304         return """
305
306 ERROR: File %s didn't exist.
307 """ % self.file
308
309 # If you want, you can wrap this up into a registry and access things
310 # through that, but it's not really necessary
311
312 application_list = [
313     "mediawiki", "wordpress", "joomla", "e107", "gallery2",
314     "phpBB", "advancedbook", "phpical", "trac", "turbogears", "django",
315     # these are technically deprecated
316     "advancedpoll", "gallery",
317 ]
318
319 """Hash table for looking up string application name to instance"""
320 applications = dict([(n,Application(n)) for n in application_list ])
321