-
Notifications
You must be signed in to change notification settings - Fork 339
/
MSCStatusController.py
377 lines (340 loc) · 16.6 KB
/
MSCStatusController.py
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
# encoding: utf-8
#
# MSCStatusController.py
#
# Copyright 2009-2014 Greg Neagle.
#
# 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 objc import YES, NO, IBAction, IBOutlet, nil
import os
import time
import munki
import msclog
import FoundationPlist
from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper
debug = False
class MSCStatusController(NSObject):
'''
Handles status messages from managedsoftwareupdate
'''
session_started = False
got_status_update = False
timer = None
_status_stopBtnDisabled = False
_status_stopBtnHidden = False
_status_message = u''
_status_detail = u''
_status_percent = -1
_status_stopBtnState = 0
statusWindowController = IBOutlet()
def registerForNotifications(self):
'''Register for notification messages'''
notification_center = NSDistributedNotificationCenter.defaultCenter()
notification_center.addObserver_selector_name_object_suspensionBehavior_(
self,
self.updateStatus_,
'com.googlecode.munki.managedsoftwareupdate.statusUpdate',
None,
NSNotificationSuspensionBehaviorDeliverImmediately)
self.receiving_notifications = True
def unregisterForNotifications(self):
'''Tell the DistributedNotificationCenter to stop sending us notifications'''
NSDistributedNotificationCenter.defaultCenter().removeObserver_(self)
# set self.receiving_notifications to False so our process monitoring
# thread will exit
self.receiving_notifications = False
def startMunkiStatusSession(self):
'''Initialize things for monitoring a managedsoftwareupdate session'''
self.initStatusSession()
self.session_started = True
# start our process monitor timer so we can be notified about
# process failure
self.timeout_counter = 6
self.saw_process = False
self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
5.0, self, self.checkProcess_, None, YES)
def checkProcess_(self, timer):
'''Monitors managedsoftwareupdate process for failure to start
or unexpected exit, so we're not waiting around forever if
managedsoftwareupdate isn't running.'''
PYTHON_SCRIPT_NAME = u'managedsoftwareupdate'
NEVER_STARTED = -2
UNEXPECTEDLY_QUIT = -1
if self.session_started:
if self.got_status_update:
# we got a status update since we last checked; no need to
# check the process table
self.timeout_counter = 6
self.saw_process = True
# clear the flag so we have to get another status update
self.got_status_update = False
elif munki.pythonScriptRunning(PYTHON_SCRIPT_NAME):
self.timeout_counter = 6
self.saw_process = True
else:
msclog.debug_log('managedsoftwareupdate not running...')
self.timeout_counter -= 1
if self.timeout_counter == 0:
msclog.debug_log('Timed out waiting for managedsoftwareupdate.')
if self.saw_process:
self.sessionEnded_(UNEXPECTEDLY_QUIT)
else:
self.sessionEnded_(NEVER_STARTED)
def sessionStarted(self):
'''Accessor method'''
return self.session_started
def sessionEnded_(self, result):
'''clean up after a managesoftwareupdate session ends'''
if self.timer:
self.timer.invalidate()
self.timer = None
self.cleanUpStatusSession()
# tell the window controller the update session is done
self.statusWindowController.munkiStatusSessionEnded_(result)
def updateStatus_(self, notification):
'''Got update status notification from managedsoftwareupdate'''
msclog.debug_log('Got munkistatus update notification')
self.got_status_update = True
info = notification.userInfo()
msclog.debug_log('%s' % info)
# explictly get keys from info object; PyObjC in Mountain Lion
# seems to need this
info_keys = info.keys()
if 'message' in info_keys:
self.setMessage_(info['message'])
if 'detail' in info_keys:
self.setDetail_(info['detail'])
if 'percent' in info_keys:
self.setPercentageDone_(info['percent'])
if 'stop_button_visible' in info_keys:
if info['stop_button_visible']:
self.showStopButton()
else:
self.hideStopButton()
if 'stop_button_enabled' in info_keys:
if info['stop_button_enabled']:
self.enableStopButton()
else:
self.disableStopButton()
command = info.get('command')
if not self.session_started and command not in ['showRestartAlert', 'quit']:
# we got a status message but we didn't start the session
# so switch to the right mode
self.startMunkiStatusSession()
if command:
msclog.debug_log('Received command: %s' % command)
if command == 'activate':
pass
#NSApp.activateIgnoringOtherApps_(YES) #? do we really want to do this?
#self.statusWindowController.window().orderFrontRegardless()
elif command == 'showRestartAlert':
if self.session_started:
self.sessionEnded_(0)
self.doRestartAlert()
elif command == 'quit':
self.sessionEnded_(0)
##### required status methods #####
def initStatusSession(self):
'''Initialize the main window for update status'''
self.statusWindowController._update_in_progress = True
if self.statusWindowController.currentPageIsUpdatesPage():
self.statusWindowController.webView.reload_(self)
self.statusWindowController.displayUpdateCount()
def cleanUpStatusSession(self):
'''Clean up after status session ends'''
self.session_started = False
# reset all our status variables
self.statusWindowController._update_in_progress = False
self._status_stopBtnDisabled = False
self._status_stopBtnHidden = False
self._status_stopBtnState = 0
self._status_message = u''
self._status_detail = u''
self._status_percent = -1
def setPercentageDone_(self, percent):
'''Display precentage done'''
try:
if float(percent) > 100.0:
percent = 100
except ValueError:
percent = 0
self._status_percent = percent
document = self.statusWindowController.webView.mainFrameDocument()
if document:
spinner = document.getElementById_('updates-progress-spinner')
if spinner: # we are displaying the updates status page
progress = document.getElementById_('progress-bar')
if progress:
if float(percent) < 0:
# indeterminate
progress.setClassName_('indeterminate')
progress.removeAttribute_('style')
else:
progress.setClassName_('')
progress.setAttribute__('style', 'width: %s%%' % percent)
def doRestartAlert(self):
'''Display a restart alert -- some item just installed or removed requires a restart'''
self._status_restartAlertDismissed = 0
alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
NSLocalizedString(u"Restart Required", u"Restart Required title"),
NSLocalizedString(u"Restart", u"Restart button title"),
nil,
nil,
u"%@", NSLocalizedString(
u"Software installed or removed requires a restart. You will "
"have a chance to save open documents.", u"Restart Required alert detail"))
alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
self.statusWindowController.window(),
self, self.restartAlertDidEnd_returnCode_contextInfo_, nil)
@AppHelper.endSheetMethod
def restartAlertDidEnd_returnCode_contextInfo_(
self, alert, returncode, contextinfo):
'''Called when restartAlert ends'''
self._status_restartAlertDismissed = 1
munki.restartNow()
def setMessage_(self, messageText):
'''Display main status message'''
messageText = NSBundle.mainBundle().localizedStringForKey_value_table_(
messageText, messageText, None)
self._status_message = messageText
document = self.statusWindowController.webView.mainFrameDocument()
if document:
spinner = document.getElementById_('updates-progress-spinner')
if spinner: # we are displaying the updates status page
textElement = document.getElementById_('primary-status-text')
if textElement:
if messageText:
textElement.setInnerText_(messageText)
else:
textElement.setInnerHTML_(' ')
def setDetail_(self, detailText):
'''Display status detail'''
detailText = NSBundle.mainBundle().localizedStringForKey_value_table_(
detailText, detailText, None)
self._status_detail = detailText
document = self.statusWindowController.webView.mainFrameDocument()
if document:
spinner = document.getElementById_('updates-progress-spinner')
if spinner: # we are displaying the updates status page
textElement = document.getElementById_('secondary-status-text')
if textElement:
if detailText:
textElement.setInnerText_(detailText)
else:
textElement.setInnerHTML_(' ')
def getStopBtnState(self):
'''Get the state (pressed or not) of the stop button'''
return self._status_stopBtnState
def hideStopButton(self):
'''Hide the stop button'''
if self._status_stopBtnState:
return
self._status_stopBtnHidden = True
document = self.statusWindowController.webView.mainFrameDocument()
if document:
spinner = document.getElementById_('updates-progress-spinner')
if spinner: # we are displaying the updates status page
install_btn = document.getElementById_('install-all-button-text')
if install_btn:
btn_classes = install_btn.className().split(' ')
if not 'hidden' in btn_classes:
btn_classes.append('hidden')
install_btn.setClassName_(' '.join(btn_classes))
def showStopButton(self):
'''Show the stop button'''
if self._status_stopBtnState:
return
self._status_stopBtnHidden = False
document = self.statusWindowController.webView.mainFrameDocument()
if document:
spinner = document.getElementById_('updates-progress-spinner')
if spinner: # we are displaying the updates status page
install_btn = document.getElementById_('install-all-button-text')
if install_btn:
btn_classes = install_btn.className().split(' ')
if 'hidden' in btn_classes:
btn_classes.remove('hidden')
install_btn.setClassName_(' '.join(btn_classes))
def enableStopButton(self):
'''Enable the stop button'''
if self._status_stopBtnState:
return
self._status_stopBtnDisabled = False
document = self.statusWindowController.webView.mainFrameDocument()
if document:
spinner = document.getElementById_('updates-progress-spinner')
if spinner: # we are displaying the updates status page
install_btn = document.getElementById_('install-all-button-text')
if install_btn:
btn_classes = install_btn.className().split(' ')
if 'disabled' in btn_classes:
btn_classes.remove('disabled')
install_btn.setClassName_(' '.join(btn_classes))
def disableStopButton(self):
'''Disable the stop button'''
if self._status_stopBtnState:
return
self._status_stopBtnDisabled = True
document = self.statusWindowController.webView.mainFrameDocument()
if document:
spinner = document.getElementById_('updates-progress-spinner')
if spinner: # we are displaying the updates status page
install_btn = document.getElementById_('install-all-button-text')
if install_btn:
btn_classes = install_btn.className().split(' ')
if not 'disabled' in btn_classes:
btn_classes.append('disabled')
install_btn.setClassName_(' '.join(btn_classes))
def getRestartAlertDismissed(self):
'''Was the restart alert dimissed?'''
return self._status_restartAlertDismissed
def more_localized_strings():
'''Some strings that are sent to us from managedsoftwareupdate. By putting them here,
the localize.py script will add them to the en.lproj/Localizable.strings file so localizers
will be able to discover them'''
foo = NSLocalizedString(u"Starting...", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Finishing...", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Performing preflight tasks...", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Performing postflight tasks...", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Checking for available updates...", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Checking for additional changes...", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Software installed or removed requires a restart.",
"managedsoftwareupdate message")
foo = NSLocalizedString(u"Waiting for network...", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Done.", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Retrieving list of software for this machine...",
"managedsoftwareupdate message")
foo = NSLocalizedString(u"Verifying package integrity...", "managedsoftwareupdate message")
foo = NSLocalizedString(u"The software was successfully installed.",
"managedsoftwareupdate message")
foo = NSLocalizedString(u"Gathering information on installed packages",
"managedsoftwareupdate message")
foo = NSLocalizedString(u"Determining which filesystem items to remove",
"managedsoftwareupdate message")
foo = NSLocalizedString(u"Removing receipt info", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Nothing to remove.", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Package removal complete.", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Checking for available Apple Software Updates...",
"managedsoftwareupdate message")
foo = NSLocalizedString(u"Checking Apple Software Update catalog...",
"managedsoftwareupdate message")
foo = NSLocalizedString(u"Downloading available Apple Software Updates...",
"managedsoftwareupdate message")
foo = NSLocalizedString(u"Installing available Apple Software Updates...",
"managedsoftwareupdate message")
foo = NSLocalizedString(u"Running Adobe Setup", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Running Adobe Uninstall", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Starting Adobe installer...", "managedsoftwareupdate message")
foo = NSLocalizedString(u"Running Adobe Patch Installer", "managedsoftwareupdate message")