summaryrefslogtreecommitdiffstats
path: root/pykolab/cli/cmd_sync.py
blob: 7d44d02ddcd844a2d47982e05b452af85f5892db (plain)
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
# -*- coding: utf-8 -*-
# Copyright 2010-2013 Kolab Systems AG (http://www.kolabsys.com)
#
# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import commands

from distutils import version
import multiprocessing

import sys
import time

import pykolab

from pykolab import utils
from pykolab.auth import Auth
from pykolab.imap import IMAP
from pykolab.translate import _

log = pykolab.getLogger('pykolab.cli')
conf = pykolab.getConf()

imap = None
pool = None

def __init__():
    commands.register('sync', execute, description="Synchronize Kolab Users with IMAP.")

def cli_options():
    my_option_group = conf.add_cli_parser_option_group(_("CLI Options"))
    my_option_group.add_option(
            '--threads',
            dest    = "threads",
            action  = "store",
            default = 20,
            type    = int,
            help    = _("Synchronize LDAP and IMAP")
        )

    my_option_group.add_option(
            '--resync',
            dest    = "resync",
            action  = "store_true",
            default = False,
            help    = _("Resync from the beginning")
        )

    my_option_group.add_option(
           '--domain',
           dest     = "domain",
           action   = "store",
           default  = "all",
           help     = _("Only sync the specified domain")
        )

def execute(*args, **kw):
    global imap, pool

    auth = Auth()

    if conf.domain == "all":
      log.debug(_("Listing domains..."), level=5)
      start_time = time.time()
      domains = auth.list_domains()
      end_time = time.time()
      log.debug(
            _("Found %d domains in %d seconds") % (
                    len(domains),
                    (end_time-start_time)
                ),
            level=8
        )
    else:
      domains = {}
      domains[conf.domain] = conf.domain

    if version.StrictVersion(sys.version[:3]) >= version.StrictVersion("2.7"):
        pool = multiprocessing.Pool(conf.threads, worker_process, (), 1)
    else:
        pool = multiprocessing.Pool(conf.threads, worker_process, ())

    for primary_domain in list(set(domains.values())):
        log.debug(_("Running for domain %s") % (primary_domain), level=8)
        auth = Auth(primary_domain)
        auth.connect(primary_domain)
        start_time = time.time()
        auth.synchronize(mode='_paged_search', callback=queue_add)
        end_time = time.time()

        log.info(_("Synchronizing users for %s took %d seconds")
                % (primary_domain, (end_time-start_time))
            )

    while not pool._taskqueue.empty():
        time.sleep(1)

def queue_add(*args, **kw):
    global pool
    for dn, entry in kw['entry']:
        entry['dn'] = dn
        r = pool.apply_async(_synchronize, (), dict(**entry))
        r.wait()

def worker_process(*args, **kw):
    pass

def _synchronize(*args, **kw):
    log.info(_("Worker process %s handling %s") % (multiprocessing.current_process().name, kw['dn']))

    entry = utils.normalize(kw)

    mailbox_attribute = conf.get('cyrus-sasl', 'result_attribute')
    if mailbox_attribute == None:
        mailbox_attribute = 'mail'


    if mailbox_attribute not in entry:
        return

    if not 'kolabinetorgperson' in entry['objectclass']:
        return

    imap = IMAP()
    imap.connect()

    if not imap.user_mailbox_exists(entry[mailbox_attribute]):
        if entry.has_key('mailhost'):
            server = entry['mailhost']
        else:
            server = None

        imap.user_mailbox_create(entry[mailbox_attribute], server=server)

    imap.disconnect()