/usr/lib/python2.7/dist-packages/txdav/common/datastore/upgrade/sql/upgrade.py is in calendarserver 5.2+dfsg-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | # -*- test-case-name: txdav.common.datastore.upgrade.sql.test -*-
##
# Copyright (c) 2010-2014 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
"""
Utilities, mostly related to upgrading, common to calendar and addressbook
data stores.
"""
import re
from twext.python.log import Logger
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.python.failure import Failure
from twisted.python.modules import getModule
from twisted.python.reflect import namedObject
from txdav.common.datastore.upgrade.sql.others import attachment_migration
class UpgradeAcquireLockStep(object):
"""
A Step which acquires the upgrade lock, blocking later Steps until it's
been acquired.
@ivar sqlStore: The store to operate on.
@type sqlStore: L{txdav.idav.IDataStore}
"""
def __init__(self, sqlStore):
self.sqlStore = sqlStore
@inlineCallbacks
def stepWithResult(self, result):
sqlTxn = self.sqlStore.newTransaction()
yield sqlTxn.acquireUpgradeLock()
yield sqlTxn.commit()
class UpgradeReleaseLockStep(object):
"""
A Step which releases the upgrade lock.
@ivar sqlStore: The store to operate on.
@type sqlStore: L{txdav.idav.IDataStore}
"""
def __init__(self, sqlStore):
self.sqlStore = sqlStore
@inlineCallbacks
def stepWithResult(self, result):
sqlTxn = self.sqlStore.newTransaction()
yield sqlTxn.releaseUpgradeLock()
yield sqlTxn.commit()
class NotAllowedToUpgrade(Exception):
"""
Exception indicating an upgrade is needed but we're not configured to
perform it.
"""
class UpgradeDatabaseCoreStep(object):
"""
Base class for either schema or data upgrades on the database.
upgrade files in sql syntax that we can execute against the database to
accomplish the upgrade.
@ivar sqlStore: The store to operate on.
@type sqlStore: L{txdav.idav.IDataStore}
"""
log = Logger()
def __init__(self, sqlStore, uid=None, gid=None, failIfUpgradeNeeded=False):
"""
Initialize the service.
"""
self.sqlStore = sqlStore
self.uid = uid
self.gid = gid
self.failIfUpgradeNeeded = failIfUpgradeNeeded
self.schemaLocation = getModule(__name__).filePath.parent().parent().sibling("sql_schema")
self.pyLocation = getModule(__name__).filePath.parent()
self.versionKey = None
self.versionDescriptor = ""
self.upgradeFilePrefix = ""
self.upgradeFileSuffix = ""
self.defaultKeyValue = None
def stepWithResult(self, result):
"""
Start the service.
"""
return self.databaseUpgrade()
@inlineCallbacks
def databaseUpgrade(self):
"""
Do a database schema upgrade.
"""
self.log.warn("Beginning database %s check." % (self.versionDescriptor,))
# Retrieve information from schema and database
dialect, required_version, actual_version = yield self.getVersions()
if required_version == actual_version:
self.log.warn("%s version check complete: no upgrade needed." % (self.versionDescriptor.capitalize(),))
elif required_version < actual_version:
msg = "Actual %s version %s is more recent than the expected version %s. The service cannot be started" % (
self.versionDescriptor, actual_version, required_version,
)
self.log.error(msg)
raise RuntimeError(msg)
elif self.failIfUpgradeNeeded:
raise NotAllowedToUpgrade()
else:
self.sqlStore.setUpgrading(True)
yield self.upgradeVersion(actual_version, required_version, dialect)
self.sqlStore.setUpgrading(False)
self.log.warn("Database %s check complete." % (self.versionDescriptor,))
returnValue(None)
@inlineCallbacks
def getVersions(self):
"""
Extract the expected version from the database schema and get the actual version in the current
database, along with the DB dialect.
"""
# Retrieve the version number from the schema file
current_schema = self.schemaLocation.child("current.sql").getContent()
found = re.search("insert into CALENDARSERVER values \('%s', '(\d+)'\);" % (self.versionKey,), current_schema)
if found is None:
msg = "Schema is missing required database key %s insert statement: %s" % (self.versionKey, current_schema,)
self.log.error(msg)
raise RuntimeError(msg)
else:
required_version = int(found.group(1))
self.log.warn("Required database key %s: %s." % (self.versionKey, required_version,))
# Get the schema version in the current database
sqlTxn = self.sqlStore.newTransaction()
dialect = sqlTxn.dialect
try:
actual_version = yield sqlTxn.calendarserverValue(self.versionKey)
actual_version = int(actual_version)
yield sqlTxn.commit()
except (RuntimeError, ValueError):
f = Failure()
self.log.error("Database key %s cannot be determined." % (self.versionKey,))
yield sqlTxn.abort()
if self.defaultKeyValue is None:
f.raiseException()
else:
actual_version = self.defaultKeyValue
self.log.warn("Actual database key %s: %s." % (self.versionKey, actual_version,))
returnValue((dialect, required_version, actual_version,))
@inlineCallbacks
def upgradeVersion(self, fromVersion, toVersion, dialect):
"""
Update the database from one version to another (the current one). Do this by
looking for upgrade_from_X_to_Y.sql files that cover the full range of upgrades.
"""
self.log.warn("Starting %s upgrade from version %d to %d." % (self.versionDescriptor, fromVersion, toVersion,))
# Scan for all possible upgrade files - returned sorted
files = self.scanForUpgradeFiles(dialect)
# Determine upgrade sequence and run each upgrade
upgrades = self.determineUpgradeSequence(fromVersion, toVersion, files, dialect)
# Use one transaction for the entire set of upgrades
try:
for fp in upgrades:
yield self.applyUpgrade(fp)
except RuntimeError:
self.log.error("Database %s upgrade failed using: %s" % (self.versionDescriptor, fp.basename(),))
raise
self.log.warn("%s upgraded from version %d to %d." % (self.versionDescriptor.capitalize(), fromVersion, toVersion,))
def getPathToUpgrades(self, dialect):
"""
Return the path where appropriate upgrade files can be found.
"""
raise NotImplementedError
def scanForUpgradeFiles(self, dialect):
"""
Scan for upgrade files with the require name.
"""
fp = self.getPathToUpgrades(dialect)
upgrades = []
regex = re.compile("%supgrade_from_(\d+)_to_(\d+)%s" % (self.upgradeFilePrefix, self.upgradeFileSuffix,))
for child in fp.globChildren("%supgrade_*%s" % (self.upgradeFilePrefix, self.upgradeFileSuffix,)):
matched = regex.match(child.basename())
if matched is not None:
fromV = int(matched.group(1))
toV = int(matched.group(2))
upgrades.append((fromV, toV, child))
upgrades.sort(key=lambda x: (x[0], x[1]))
return upgrades
def determineUpgradeSequence(self, fromVersion, toVersion, files, dialect):
"""
Determine the upgrade_from_X_to_Y(.sql|.py) files that cover the full range of upgrades.
Note that X and Y may not be consecutive, e.g., we might have an upgrade from 3 to 4,
4 to 5, and 3 to 5 - the later because it is more efficient to jump over the intermediate
step. As a result we will always try and pick the upgrade file that gives the biggest
jump from one version to another at each step.
"""
# Now find the path from the old version to the current one
filesByFromVersion = {}
for fromV, toV, fp in files:
if fromV not in filesByFromVersion or filesByFromVersion[fromV][1] < toV:
filesByFromVersion[fromV] = fromV, toV, fp
upgrades = []
nextVersion = fromVersion
while nextVersion != toVersion:
if nextVersion not in filesByFromVersion:
msg = "Missing upgrade file from version %d with dialect %s" % (nextVersion, dialect,)
self.log.error(msg)
raise RuntimeError(msg)
else:
upgrades.append(filesByFromVersion[nextVersion][2])
nextVersion = filesByFromVersion[nextVersion][1]
return upgrades
def applyUpgrade(self, fp):
"""
Apply the supplied upgrade to the database. Always return an L{Deferred"
"""
raise NotImplementedError
class UpgradeDatabaseSchemaStep(UpgradeDatabaseCoreStep):
"""
Checks and upgrades the database schema. This assumes there are a bunch of
upgrade files in sql syntax that we can execute against the database to
accomplish the upgrade.
@ivar sqlStore: The store to operate on.
@type sqlStore: L{txdav.idav.IDataStore}
"""
def __init__(self, sqlStore, **kwargs):
"""
Initialize the service.
@param sqlStore: The store to operate on. Can be C{None} when doing unit tests.
"""
super(UpgradeDatabaseSchemaStep, self).__init__(sqlStore, **kwargs)
self.versionKey = "VERSION"
self.versionDescriptor = "schema"
self.upgradeFileSuffix = ".sql"
def getPathToUpgrades(self, dialect):
return self.schemaLocation.child("upgrades").child(dialect)
@inlineCallbacks
def applyUpgrade(self, fp):
"""
Apply the schema upgrade .sql file to the database.
"""
self.log.warn("Applying schema upgrade: %s" % (fp.basename(),))
sqlTxn = self.sqlStore.newTransaction()
try:
sql = fp.getContent()
yield sqlTxn.execSQLBlock(sql)
yield sqlTxn.commit()
except RuntimeError:
f = Failure()
yield sqlTxn.abort()
f.raiseException()
class _UpgradeDatabaseDataStep(UpgradeDatabaseCoreStep):
"""
Checks and upgrades the database data. This assumes there are a bunch of
upgrade python modules that we can execute against the database to
accomplish the upgrade.
@ivar sqlStore: The store to operate on.
@type sqlStore: L{txdav.idav.IDataStore}
"""
def getPathToUpgrades(self, dialect):
return self.pyLocation.child("upgrades")
@inlineCallbacks
def applyUpgrade(self, fp):
"""
Apply the data upgrade .py files to the database.
"""
# Find the module function we need to execute
try:
module = getModule(__name__)
module = ".".join(module.name.split(".")[:-1]) + ".upgrades." + fp.basename()[:-3] + ".doUpgrade"
doUpgrade = namedObject(module)
except ImportError:
msg = "Failed data upgrade: %s" % (fp.basename()[:-4],)
self.log.error(msg)
raise RuntimeError(msg)
self.log.warn("Applying data upgrade: %s" % (module,))
yield doUpgrade(self.sqlStore)
class UpgradeDatabaseAddressBookDataStep(_UpgradeDatabaseDataStep):
"""
Checks and upgrades the database data. This assumes there are a bunch of
upgrade python modules that we can execute against the database to
accomplish the upgrade.
@ivar sqlStore: The store to operate on.
@type sqlStore: L{txdav.idav.IDataStore}
"""
def __init__(self, sqlStore, **kwargs):
"""
Initialize the Step.
@param sqlStore: The store to operate on. Can be C{None} when doing unit tests.
"""
super(UpgradeDatabaseAddressBookDataStep, self).__init__(sqlStore, **kwargs)
self.versionKey = "ADDRESSBOOK-DATAVERSION"
self.versionDescriptor = "addressbook data"
self.upgradeFilePrefix = "addressbook_"
self.upgradeFileSuffix = ".py"
class UpgradeDatabaseCalendarDataStep(_UpgradeDatabaseDataStep):
"""
Checks and upgrades the database data. This assumes there are a bunch of
upgrade python modules that we can execute against the database to
accomplish the upgrade.
@ivar sqlStore: The store to operate on.
@type sqlStore: L{txdav.idav.IDataStore}
"""
def __init__(self, sqlStore, **kwargs):
"""
Initialize the service.
@param sqlStore: The store to operate on. Can be C{None} when doing unit tests.
@param service: Wrapped service. Can be C{None} when doing unit tests.
"""
super(UpgradeDatabaseCalendarDataStep, self).__init__(sqlStore, **kwargs)
self.versionKey = "CALENDAR-DATAVERSION"
self.versionDescriptor = "calendar data"
self.upgradeFilePrefix = "calendar_"
self.upgradeFileSuffix = ".py"
class UpgradeDatabaseOtherStep(UpgradeDatabaseCoreStep):
"""
Do any other upgrade behaviors once all the schema, data, file migration upgraders
are done.
@ivar sqlStore: The store to operate on.
@type sqlStore: L{txdav.idav.IDataStore}
"""
def __init__(self, sqlStore, **kwargs):
"""
Initialize the Step.
@param sqlStore: The store to operate on. Can be C{None} when doing unit tests.
"""
super(UpgradeDatabaseOtherStep, self).__init__(sqlStore, **kwargs)
self.versionDescriptor = "other upgrades"
@inlineCallbacks
def databaseUpgrade(self):
"""
Do upgrades.
"""
self.log.warn("Beginning database %s check." % (self.versionDescriptor,))
# Do each upgrade in our own predefined order
self.sqlStore.setUpgrading(True)
# Migration from dropbox to managed attachments
yield attachment_migration.doUpgrade(self)
self.sqlStore.setUpgrading(False)
self.log.warn("Database %s check complete." % (self.versionDescriptor,))
returnValue(None)
|