<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[15058] CalendarServer/trunk/calendarserver/tools/delegatesmigration.py</title>
</head>
<body>
<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; }
#msg dl a { font-weight: bold}
#msg dl a:link { color:#fc3; }
#msg dl a:active { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/15058">15058</a></dd>
<dt>Author</dt> <dd>sagen@apple.com</dd>
<dt>Date</dt> <dd>2015-08-19 16:25:24 -0700 (Wed, 19 Aug 2015)</dd>
</dl>
<h3>Log Message</h3>
<pre>New tool to migrate from legacy postgres proxy db into store.</pre>
<h3>Added Paths</h3>
<ul>
<li><a href="#CalendarServertrunkcalendarservertoolsdelegatesmigrationpy">CalendarServer/trunk/calendarserver/tools/delegatesmigration.py</a></li>
</ul>
</div>
<div id="patch">
<h3>Diff</h3>
<a id="CalendarServertrunkcalendarservertoolsdelegatesmigrationpy"></a>
<div class="addfile"><h4>Added: CalendarServer/trunk/calendarserver/tools/delegatesmigration.py (0 => 15058)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/calendarserver/tools/delegatesmigration.py         (rev 0)
+++ CalendarServer/trunk/calendarserver/tools/delegatesmigration.py        2015-08-19 23:25:24 UTC (rev 15058)
</span><span class="lines">@@ -0,0 +1,292 @@
</span><ins>+#!/usr/bin/env python
+
+##
+# Copyright (c) 2015 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.
+##
+from __future__ import print_function
+
+# Suppress warning that occurs on Linux
+import sys
+if sys.platform.startswith("linux"):
+ from Crypto.pct_warnings import PowmInsecureWarning
+ import warnings
+ warnings.simplefilter("ignore", PowmInsecureWarning)
+
+
+from getopt import getopt, GetoptError
+
+from calendarserver.tools.cmdline import utilityMain, WorkerService
+from twext.python.log import Logger
+from twext.who.expression import MatchExpression, MatchType
+from twext.who.idirectory import RecordType, FieldName
+from twext.who.util import uniqueResult
+from twisted.internet.defer import inlineCallbacks, returnValue
+from twistedcaldav.config import config
+from twistedcaldav.directory import calendaruserproxy
+from txdav.who.delegates import Delegates
+
+log = Logger()
+
+
+def usage(e=None):
+ if e:
+ print(e)
+ print("")
+
+ print("")
+ print(" Migrates delegate assignments from external Postgres DB to Calendar Server Store")
+ print("")
+ print("options:")
+ print(" -h --help: print this help and exit")
+ print(" -f --config <path>: Specify caldavd.plist configuration path")
+ print(" -s --server <postgres db server hostname>")
+ print(" -u --user <username>")
+ print(" -p --password <password>")
+ print(" -d --database <database name> (default = 'proxies')")
+ print(" -t --dbtype <database type> (default = 'ProxyDB')")
+ print("")
+
+ if e:
+ sys.exit(64)
+ else:
+ sys.exit(0)
+
+
+
+class DelegatesMigrationService(WorkerService):
+ """
+ """
+
+ function = None
+ params = []
+
+ @inlineCallbacks
+ def doWork(self):
+ """
+ Calls the function that's been assigned to "function" and passes the root
+ resource, directory, store, and whatever has been assigned to "params".
+ """
+ if self.function is not None:
+ yield self.function(self.store, *self.params)
+
+
+
+def main():
+ try:
+ (optargs, args) = getopt(
+ sys.argv[1:], "d:f:hp:P:s:t:u:", [
+ "help",
+ "config=",
+
+ "server=",
+ "user=",
+ "password=",
+ "pod=",
+ "database=",
+ "dbtype=",
+ ],
+ )
+ except GetoptError, e:
+ usage(e)
+
+ #
+ # Get configuration
+ #
+ configFileName = None
+ server = None
+ user = None
+ password = None
+ pod = None
+ database = "proxies"
+ dbtype = "ProxyDB"
+
+ for opt, arg in optargs:
+
+ # Args come in as encoded bytes
+ arg = arg.decode("utf-8")
+
+ if opt in ("-h", "--help"):
+ usage()
+
+ elif opt in ("-f", "--config"):
+ configFileName = arg
+
+ elif opt in ("-s", "--server"):
+ server = arg
+
+ elif opt in ("-u", "--user"):
+ user = arg
+
+ elif opt in ("-P", "--pod"):
+ pod = arg
+
+ elif opt in ("-p", "--password"):
+ password = arg
+
+ elif opt in ("-d", "--database"):
+ database = arg
+
+ elif opt in ("-t", "--dbtype"):
+ dbtype = arg
+
+ else:
+ raise NotImplementedError(opt)
+
+
+ DelegatesMigrationService.function = migrateDelegates
+ DelegatesMigrationService.params = [server, user, password, pod, database, dbtype]
+
+ utilityMain(configFileName, DelegatesMigrationService)
+
+
+@inlineCallbacks
+def getAssignments(db):
+ """
+ Returns all the delegate assignments from the db.
+
+ @return: a list of (delegator group, delegate) tuples
+ """
+ print("Fetching delegate assignments...")
+ rows = yield db.query("select GROUPNAME, MEMBER from GROUPS;")
+ print("Fetched {} delegate assignments".format(len(rows)))
+ returnValue(rows)
+
+
+@inlineCallbacks
+def copyAssignments(assignments, pod, directory, store):
+ """
+ Go through the list of assignments from the old db, and selectively copy them
+ into the new store.
+
+ @param assignments: the assignments from the old db
+ @type assignments: a list of (delegator group, delegate) tuples
+ @param pod: the name of the pod you want to migrate assignments for; assignments
+ for delegators who don't reside on this pod will be ignored. Set this
+ to None to copy all assignments.
+ @param directory: the directory service
+ @param store: the store
+ """
+
+ delegatorsMissingPodInfo = set()
+ numCopied = 0
+ numOtherPod = 0
+ numDirectoryBased = 0
+ numExamined = 0
+
+
+ # If locations and resources' delegate assignments come from the directory,
+ # then we're only interested in copying assignments where the delegator is a
+ # user.
+ if config.GroupCaching.Enabled and config.GroupCaching.UseDirectoryBasedDelegates:
+ delegatorRecordTypes = (RecordType.user,)
+ else:
+ delegatorRecordTypes = None
+
+ # When faulting in delegates, only worry about users and groups.
+ delegateRecordTypes = (RecordType.user, RecordType.group)
+
+ total = len(assignments)
+
+ for groupname, delegateUID in assignments:
+ numExamined += 1
+
+ if numExamined % 100 == 0:
+ print("Processed: {} of {}...".format(numExamined, total))
+
+ if "#" in groupname:
+ delegatorUID, permission = groupname.split("#")
+ try:
+ delegatorRecords = yield directory.recordsFromExpression(
+ MatchExpression(FieldName.uid, delegatorUID, matchType=MatchType.equals),
+ recordTypes=delegatorRecordTypes
+ )
+ delegatorRecord = uniqueResult(delegatorRecords)
+ except Exception, e:
+ print("Failed to look up record for {}: {}".format(delegatorUID, str(e)))
+ continue
+
+ if delegatorRecord is None:
+ continue
+
+ if config.GroupCaching.Enabled and config.GroupCaching.UseDirectoryBasedDelegates:
+ if delegatorRecord.recordType != RecordType.user:
+ print("Skipping non-user")
+ numDirectoryBased += 1
+ continue
+
+ if pod:
+ try:
+ if delegatorRecord.serviceNodeUID != pod:
+ numOtherPod += 1
+ continue
+ except AttributeError:
+ print("Record missing serviceNodeUID", delegatorRecord.fullNames)
+ delegatorsMissingPodInfo.add(delegatorUID)
+ continue
+
+ try:
+ delegateRecords = yield directory.recordsFromExpression(
+ MatchExpression(FieldName.uid, delegateUID, matchType=MatchType.equals),
+ recordTypes=delegateRecordTypes
+ )
+ delegateRecord = uniqueResult(delegateRecords)
+
+ except Exception, e:
+ print("Failed to look up record for {}: {}".format(delegateUID, str(e)))
+ continue
+
+ if delegateRecord is None:
+ continue
+
+ txn = store.newTransaction(label="DelegatesMigrationService")
+ yield Delegates.addDelegate(
+ txn, delegatorRecord, delegateRecord,
+ (permission == "calendar-proxy-write")
+ )
+ numCopied += 1
+ yield txn.commit()
+
+ print("Total delegate assignments examined: {}".format(numExamined))
+ print("Total delegate assignments migrated: {}".format(numCopied))
+ if pod:
+ print("Total ignored assignments because they're on another pod: {}".format(numOtherPod))
+ if numDirectoryBased:
+ print("Total ignored assignments because they come from the directory: {}".format(numDirectoryBased))
+
+ if delegatorsMissingPodInfo:
+ print("Delegators missing pod info:")
+ for uid in delegatorsMissingPodInfo:
+ print(uid)
+
+
+@inlineCallbacks
+def migrateDelegates(service, store, server, user, password, pod, database, dbtype):
+ print("Migrating from server {}".format(server))
+ try:
+ calendaruserproxy.ProxyDBService = calendaruserproxy.ProxyPostgreSQLDB(server, database, user, password, dbtype)
+ calendaruserproxy.ProxyDBService.open()
+ assignments = yield getAssignments(calendaruserproxy.ProxyDBService)
+ yield copyAssignments(assignments, pod, store.directoryService(), store)
+ calendaruserproxy.ProxyDBService.close()
+
+ except IOError:
+ log.error("Could not start proxydb service")
+ raise
+
+
+
+
+if __name__ == "__main__":
+ main()
</ins><span class="cx">Property changes on: CalendarServer/trunk/calendarserver/tools/delegatesmigration.py
</span><span class="cx">___________________________________________________________________
</span></span></pre></div>
<a id="svnexecutable"></a>
<div class="addfile"><h4>Added: svn:executable</h4></div>
</div>
</body>
</html>