~paul-mcspadden/computer-janitor/bug-726616

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
# Copyright (C) 2008, 2009, 2010  Canonical, Ltd.
#
# 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, version 3 of the License.
#
# 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/>.

"""dbus service for cleaning up crufty packages that are no longer needed."""


from __future__ import absolute_import, unicode_literals

__metaclass__ = type
__all__ = [
    'Service',
    ]


import atexit
import logging

import dbus.service

from computerjanitor import PackageCruft
from computerjanitord.application import Application
from computerjanitord.authenticator import Authenticator
from computerjanitord.collector import Collector
from computerjanitord.errors import NoSuchCruftError, PermissionDeniedError
from computerjanitord.state import State, DEFAULT_STATE_FILE

import glib

log = logging.getLogger('computerjanitor')
MISSING = object()

DBUS_INTERFACE_NAME = 'com.ubuntu.ComputerJanitor'
PRIVILEGE = 'com.ubuntu.computerjanitor.updatesystem'


class Service(dbus.service.Object):
    """Backend dbus service that handles removing crufty packages."""

    def __init__(self, options):
        """Create the dbus service.

        :param options: The command line options class.
        :type options: `Options`
        """
        self.dry_run = options.arguments.dry_run
        self.state_file = (DEFAULT_STATE_FILE
                           if options.arguments.state_file is None
                           else options.arguments.state_file)
        self.application = Application()
        self.state = State()
        self.state.load(self.state_file)
        self.collector = Collector(self.application, service=self)
        self.authenticator = Authenticator()
        bus_name = dbus.service.BusName(
            DBUS_INTERFACE_NAME, bus=dbus.SystemBus())
        dbus.service.Object.__init__(self, bus_name, '/')
        # We can't use the decorator because that doesn't work with methods;
        # self doesn't get passed to the handler.
        atexit.register(self._exit_handler)

    def _exit_handler(self):
        """Ensure that the state file is saved at exit."""
        if not self.dry_run:
            self.state.save(self.state_file)

    def _authenticate(self, sender, connection):
        """Authenticate via PolicyKit.

        :param sender: The dbus client sender.
        :param connection: The dbus client connection.
        :raises PermissionDeniedError: when the authentication fails.
        """
        if not self.authenticator.authenticate(sender, connection, PRIVILEGE):
            log.error('Permission denied: {0} for {1} on {2}'.format(
                PRIVILEGE, sender, connection))
            raise PermissionDeniedError(PRIVILEGE)
        log.debug('Permission granted: {0} for {1} on {2}'.format(
            PRIVILEGE, sender, connection))

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         out_signature='as')
    def find(self):
        """Find all the non-whitelisted cruft on the system.

        Because this is a read-only interface it does not need authorization
        to be called.

        :return: A list of matching cruft names.
        """
        return list(cruft.get_name() for cruft in self.collector.cruft)

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         out_signature='b')
    def find_async(self):
        """Find all the non-whitelisted cruft on the system, asynchronously.

        Because this is a read-only interface it does not need authorization
        to be called.  Use this method when you can't wait for the cruft
        searching process to complete, since it might take some time.  To
        respond when the cruft has been found, set up a `find_finished` signal
        handler.

        :return: True
        """
        glib.timeout_add_seconds(1, self._find_async)
        return True

    def _find_async(self):
        """Find all cruft asynchronously and call the signal handler."""
        cruft = list(cruft.get_name() for cruft in self.collector.cruft)
        self.find_finished(cruft)
        # Only call the callback once.
        return False

    @dbus.service.signal(DBUS_INTERFACE_NAME, signature='as')
    def find_finished(self, cruft):
        """dbus signal called when `_find_async()` completes."""
        log.debug('find_finished: {0}'.format(cruft))

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         out_signature='as',
                         # Must wrap these in str() because Python < 2.6.5
                         # does not like unicode keyword arguments.
                         sender_keyword=str('sender'),
                         connection_keyword=str('connection'))
    def load(self, sender=None, connection=None):
        """Load the state file."""
        self._authenticate(sender, connection)
        self.state.load(self.state_file)
        return list(self.state.ignore)

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         # Must wrap these in str() because Python < 2.6.5
                         # does not like unicode keyword arguments.
                         sender_keyword=str('sender'),
                         connection_keyword=str('connection'))
    def save(self, sender=None, connection=None):
        """Save the state file."""
        self._authenticate(sender, connection)
        if not self.dry_run:
            self.state.save(self.state_file)

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         in_signature='s',
                         # Must wrap these in str() because Python < 2.6.5
                         # does not like unicode keyword arguments.
                         sender_keyword=str('sender'),
                         connection_keyword=str('connection'))
    def ignore(self, name, sender=None, connection=None):
        """Ignore the named cruft.

        :param name: The name of the cruft to ignore.
        :type filename: string
        """
        # Make sure this is known cruft first.
        cruft = self.collector.cruft_by_name.get(name, MISSING)
        if cruft is MISSING:
            log.error('ignore(): No such cruft: {0}'.format(name))
            raise NoSuchCruftError(name)
        self._authenticate(sender, connection)
        if not self.dry_run:
            self.state.ignore.add(name)

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         in_signature='s',
                         # Must wrap these in str() because Python < 2.6.5
                         # does not like unicode keyword arguments.
                         sender_keyword=str('sender'),
                         connection_keyword=str('connection'))
    def unignore(self, name, sender=None, connection=None):
        """Unignore the named cruft.

        :param name: The name of the cruft to unignore.
        :type filename: string
        """
        cruft = self.collector.cruft_by_name.get(name, MISSING)
        if cruft is MISSING:
            log.error('ignore(): No such cruft: {0}'.format(name))
            raise NoSuchCruftError(name)
        self._authenticate(sender, connection)
        if not self.dry_run:
            # Don't worry if we're already not ignoring the cruft (i.e. don't
            # raise a KeyError here if 'name' is not in the set).
            self.state.ignore.discard(name)

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         out_signature='as')
    def ignored(self):
        """Return the list of ignored cruft.

        :return: The names of the ignored cruft.
        :rtype: list of strings
        """
        return list(self.state.ignore)

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         in_signature='s',
                         out_signature='s')
    def get_description(self, name):
        """Return the description of the named cruft.

        :param name: The cruft name.
        :type name: string
        :return: The description of the cruft.
        :rtype: string
        """
        cruft = self.collector.cruft_by_name.get(name, MISSING)
        if cruft is MISSING:
            log.error('get_description(): No such cruft: {0}'.format(name))
            raise NoSuchCruftError(name)
        return cruft.get_description()

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         in_signature='s',
                         out_signature='s')
    def get_shortname(self, name):
        """Return the short name of the named cruft.

        :param name: The cruft name.
        :type name: string
        :return: The short nameof the cruft.
        :rtype: string
        """
        cruft = self.collector.cruft_by_name.get(name, MISSING)
        if cruft is MISSING:
            log.error('get_shortname(): No such cruft: {0}'.format(name))
            raise NoSuchCruftError(name)
        return cruft.get_shortname()

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         in_signature='s',
                         out_signature='st')
    def get_details(self, name):
        """Return some extra details about the named cruft.

        :param name: The cruft name.
        :type name: string
        :return: Some extra details about the named cruft, specifically its
            'type' and the amount of disk space it consumes.  The type is
            simply the name of the cruft instance's class.
        :rtype: string, uint64
        """
        cruft = self.collector.cruft_by_name.get(name, MISSING)
        if cruft is MISSING:
            log.error('get_shortname(): No such cruft: {0}'.format(name))
            raise NoSuchCruftError(name)
        return cruft.__class__.__name__, cruft.get_disk_usage()

    @dbus.service.method(DBUS_INTERFACE_NAME,
                         in_signature='as', # array of strings
                         # Must wrap these in str() because Python < 2.6.5
                         # does not like unicode keyword arguments.
                         sender_keyword=str('sender'),
                         connection_keyword=str('connection'))
    def clean(self, names, sender=None, connection=None):
        """Clean the named crufts.

        :param names: The names of the cruft to clean.
        :type names: list of strings
        """
        self._authenticate(sender, connection)
        self.collector.clean(names, self.dry_run)

    @dbus.service.signal(DBUS_INTERFACE_NAME,
                         signature='s')
    def cleanup_status(self, cruft):
        """Signal cleanup status.

        This signal is used to incrementally inform clients that some cleanup
        work is being done.  It is called at the beginning of the cleanup
        process and after each plugin has completed its `post_cleanup()`
        method.

        :param done: The name of the next piece of cruft to be cleaned up, or
            the empty string when there's nothing left to do.
        :type done: string
        """
        log.debug('cleanup_status: {0}'.format(cruft))