<!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 &quot;License&quot;);
+# 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 &quot;AS IS&quot; 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(&quot;linux&quot;):
+    from Crypto.pct_warnings import PowmInsecureWarning
+    import warnings
+    warnings.simplefilter(&quot;ignore&quot;, 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(&quot;&quot;)
+
+    print(&quot;&quot;)
+    print(&quot;  Migrates delegate assignments from external Postgres DB to Calendar Server Store&quot;)
+    print(&quot;&quot;)
+    print(&quot;options:&quot;)
+    print(&quot;  -h --help: print this help and exit&quot;)
+    print(&quot;  -f --config &lt;path&gt;: Specify caldavd.plist configuration path&quot;)
+    print(&quot;  -s --server &lt;postgres db server hostname&gt;&quot;)
+    print(&quot;  -u --user &lt;username&gt;&quot;)
+    print(&quot;  -p --password &lt;password&gt;&quot;)
+    print(&quot;  -d --database &lt;database name&gt; (default = 'proxies')&quot;)
+    print(&quot;  -t --dbtype &lt;database type&gt; (default = 'ProxyDB')&quot;)
+    print(&quot;&quot;)
+
+    if e:
+        sys.exit(64)
+    else:
+        sys.exit(0)
+
+
+
+class DelegatesMigrationService(WorkerService):
+    &quot;&quot;&quot;
+    &quot;&quot;&quot;
+
+    function = None
+    params = []
+
+    @inlineCallbacks
+    def doWork(self):
+        &quot;&quot;&quot;
+        Calls the function that's been assigned to &quot;function&quot; and passes the root
+        resource, directory, store, and whatever has been assigned to &quot;params&quot;.
+        &quot;&quot;&quot;
+        if self.function is not None:
+            yield self.function(self.store, *self.params)
+
+
+
+def main():
+    try:
+        (optargs, args) = getopt(
+            sys.argv[1:], &quot;d:f:hp:P:s:t:u:&quot;, [
+                &quot;help&quot;,
+                &quot;config=&quot;,
+
+                &quot;server=&quot;,
+                &quot;user=&quot;,
+                &quot;password=&quot;,
+                &quot;pod=&quot;,
+                &quot;database=&quot;,
+                &quot;dbtype=&quot;,
+            ],
+        )
+    except GetoptError, e:
+        usage(e)
+
+    #
+    # Get configuration
+    #
+    configFileName = None
+    server = None
+    user = None
+    password = None
+    pod = None
+    database = &quot;proxies&quot;
+    dbtype = &quot;ProxyDB&quot;
+
+    for opt, arg in optargs:
+
+        # Args come in as encoded bytes
+        arg = arg.decode(&quot;utf-8&quot;)
+
+        if opt in (&quot;-h&quot;, &quot;--help&quot;):
+            usage()
+
+        elif opt in (&quot;-f&quot;, &quot;--config&quot;):
+            configFileName = arg
+
+        elif opt in (&quot;-s&quot;, &quot;--server&quot;):
+            server = arg
+
+        elif opt in (&quot;-u&quot;, &quot;--user&quot;):
+            user = arg
+
+        elif opt in (&quot;-P&quot;, &quot;--pod&quot;):
+            pod = arg
+
+        elif opt in (&quot;-p&quot;, &quot;--password&quot;):
+            password = arg
+
+        elif opt in (&quot;-d&quot;, &quot;--database&quot;):
+            database = arg
+
+        elif opt in (&quot;-t&quot;, &quot;--dbtype&quot;):
+            dbtype = arg
+
+        else:
+            raise NotImplementedError(opt)
+
+
+    DelegatesMigrationService.function = migrateDelegates
+    DelegatesMigrationService.params = [server, user, password, pod, database, dbtype]
+
+    utilityMain(configFileName, DelegatesMigrationService)
+
+
+@inlineCallbacks
+def getAssignments(db):
+    &quot;&quot;&quot;
+    Returns all the delegate assignments from the db.
+
+    @return: a list of (delegator group, delegate) tuples
+    &quot;&quot;&quot;
+    print(&quot;Fetching delegate assignments...&quot;)
+    rows = yield db.query(&quot;select GROUPNAME, MEMBER from GROUPS;&quot;)
+    print(&quot;Fetched {} delegate assignments&quot;.format(len(rows)))
+    returnValue(rows)
+
+
+@inlineCallbacks
+def copyAssignments(assignments, pod, directory, store):
+    &quot;&quot;&quot;
+    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
+    &quot;&quot;&quot;
+
+    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(&quot;Processed: {} of {}...&quot;.format(numExamined, total))
+
+        if &quot;#&quot; in groupname:
+            delegatorUID, permission = groupname.split(&quot;#&quot;)
+            try:
+                delegatorRecords = yield directory.recordsFromExpression(
+                    MatchExpression(FieldName.uid, delegatorUID, matchType=MatchType.equals),
+                    recordTypes=delegatorRecordTypes
+                )
+                delegatorRecord = uniqueResult(delegatorRecords)
+            except Exception, e:
+                print(&quot;Failed to look up record for {}: {}&quot;.format(delegatorUID, str(e)))
+                continue
+
+            if delegatorRecord is None:
+                continue
+
+            if config.GroupCaching.Enabled and config.GroupCaching.UseDirectoryBasedDelegates:
+                if delegatorRecord.recordType != RecordType.user:
+                    print(&quot;Skipping non-user&quot;)
+                    numDirectoryBased += 1
+                    continue
+
+            if pod:
+                try:
+                    if delegatorRecord.serviceNodeUID != pod:
+                        numOtherPod += 1
+                        continue
+                except AttributeError:
+                    print(&quot;Record missing serviceNodeUID&quot;, 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(&quot;Failed to look up record for {}: {}&quot;.format(delegateUID, str(e)))
+                continue
+
+            if delegateRecord is None:
+                continue
+
+            txn = store.newTransaction(label=&quot;DelegatesMigrationService&quot;)
+            yield Delegates.addDelegate(
+                txn, delegatorRecord, delegateRecord,
+                (permission == &quot;calendar-proxy-write&quot;)
+            )
+            numCopied += 1
+            yield txn.commit()
+
+    print(&quot;Total delegate assignments examined: {}&quot;.format(numExamined))
+    print(&quot;Total delegate assignments migrated: {}&quot;.format(numCopied))
+    if pod:
+        print(&quot;Total ignored assignments because they're on another pod: {}&quot;.format(numOtherPod))
+    if numDirectoryBased:
+        print(&quot;Total ignored assignments because they come from the directory: {}&quot;.format(numDirectoryBased))
+
+    if delegatorsMissingPodInfo:
+        print(&quot;Delegators missing pod info:&quot;)
+        for uid in delegatorsMissingPodInfo:
+            print(uid)
+
+
+@inlineCallbacks
+def migrateDelegates(service, store, server, user, password, pod, database, dbtype):
+    print(&quot;Migrating from server {}&quot;.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(&quot;Could not start proxydb service&quot;)
+        raise
+
+
+
+
+if __name__ == &quot;__main__&quot;:
+    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>