Пример #1
0
def setup_logging(username=None):
    """Setup logging module.

    Args:
        username: str, optional, current login name
    """
    global MSULOGENABLED
    global MSUDEBUGLOGENABLED

    if (logging.root.handlers
            and logging.root.handlers[0].__class__ is FleetingFileHandler):
        return

    if munki.pref('MSUDebugLogEnabled'):
        MSUDEBUGLOGENABLED = True

    if munki.pref('MSULogEnabled'):
        MSULOGENABLED = True

    if not MSULOGENABLED:
        return

    if username is None:
        username = os.getlogin() or 'UID%d' % os.getuid()

    if not os.path.exists(MSULOGDIR):
        try:
            os.mkdir(MSULOGDIR, 01777)
        except OSError, err:
            logging.error('mkdir(%s): %s', MSULOGDIR, str(err))
            return
Пример #2
0
def setup_logging(username=None):
    """Setup logging module.

    Args:
        username: str, optional, current login name
    """
    global MSULOGENABLED
    global MSUDEBUGLOGENABLED

    if (logging.root.handlers and
        logging.root.handlers[0].__class__ is FleetingFileHandler):
        return
        
    if  munki.pref('MSUDebugLogEnabled'):
        MSUDEBUGLOGENABLED = True

    if munki.pref('MSULogEnabled'):
        MSULOGENABLED = True

    if not MSULOGENABLED:
        return

    if username is None:
        username = os.getlogin() or 'UID%d' % os.getuid()

    if not os.path.exists(MSULOGDIR):
        try:
            os.mkdir(MSULOGDIR, 01777)
        except OSError, err:
            logging.error('mkdir(%s): %s', MSULOGDIR, str(err))
            return
Пример #3
0
    def applicationDidFinishLaunching_(self, sender):
        '''NSApplication delegate method called at launch'''
        # Prevent automatic relaunching at login on Lion+
        if NSApp.respondsToSelector_('disableRelaunchOnLogin'):
            NSApp.disableRelaunchOnLogin()

        ver = NSBundle.mainBundle().infoDictionary().get(
            'CFBundleShortVersionString')
        msclog.log("MSC", "launched", "VER=%s" % ver)

        # if we're running under Snow Leopard, swap out the Dock icon for one
        # without the Retina assets to avoid an appearance issue when the
        # icon has a badge in the Dock (and App Switcher)
        # Darwin major version 10 is Snow Leopard (10.6)
        if os.uname()[2].split('.')[0] == '10':
            myImage = NSImage.imageNamed_("Managed Software Center 10_6")
            NSApp.setApplicationIconImage_(myImage)

        # setup client logging
        msclog.setup_logging()

        # have the statuscontroller register for its own notifications
        self.statusController.registerForNotifications()

        # user may have launched the app manually, or it may have
        # been launched by /usr/local/munki/managedsoftwareupdate
        # to display available updates
        if munki.thereAreUpdatesToBeForcedSoon(hours=2):
            # skip the check and just display the updates
            # by pretending the lastcheck is now
            lastcheck = NSDate.date()
        else:
            lastcheck = munki.pref('LastCheckDate')
        max_cache_age = munki.pref('CheckResultsCacheSeconds')
        # if there is no lastcheck timestamp, check for updates.
        if not lastcheck:
            self.mainWindowController.checkForUpdates()
        elif lastcheck.timeIntervalSinceNow() * -1 > int(max_cache_age):
            # check for updates if the last check is over the
            # configured manualcheck cache age max.
            self.mainWindowController.checkForUpdates()
        elif MunkiItems.updateCheckNeeded():
            # check for updates if we have optional items selected for install
            # or removal that have not yet been processed
            self.mainWindowController.checkForUpdates()

        # load the initial view only if we are not already loading something else.
        # enables launching the app to a specific panel, eg. from URL handler
        if not self.mainWindowController.webView.isLoading():
            self.mainWindowController.loadInitialView()
Пример #4
0
    def applicationDidFinishLaunching_(self, sender):
        '''NSApplication delegate method called at launch'''
        # Prevent automatic relaunching at login on Lion+
        if NSApp.respondsToSelector_('disableRelaunchOnLogin'):
            NSApp.disableRelaunchOnLogin()

        ver = NSBundle.mainBundle().infoDictionary().get('CFBundleShortVersionString')
        msclog.log("MSC", "launched", "VER=%s" % ver)
        
        # if we're running under Snow Leopard, swap out the Dock icon for one
        # without the Retina assets to avoid an appearance issue when the
        # icon has a badge in the Dock (and App Switcher)
        # Darwin major version 10 is Snow Leopard (10.6)
        if os.uname()[2].split('.')[0] == '10':
            myImage = NSImage.imageNamed_("Managed Software Center 10_6")
            NSApp.setApplicationIconImage_(myImage)

        # setup client logging
        msclog.setup_logging()

        # have the statuscontroller register for its own notifications
        self.statusController.registerForNotifications()

        # user may have launched the app manually, or it may have
        # been launched by /usr/local/munki/managedsoftwareupdate
        # to display available updates
        if munki.thereAreUpdatesToBeForcedSoon(hours=2):
            # skip the check and just display the updates
            # by pretending the lastcheck is now
            lastcheck = NSDate.date()
        else:
            lastcheck = munki.pref('LastCheckDate')
        max_cache_age = munki.pref('CheckResultsCacheSeconds')
        # if there is no lastcheck timestamp, check for updates.
        if not lastcheck:
            self.mainWindowController.checkForUpdates()
        elif lastcheck.timeIntervalSinceNow() * -1 > int(max_cache_age):
            # check for updates if the last check is over the
            # configured manualcheck cache age max.
            self.mainWindowController.checkForUpdates()
        elif MunkiItems.updateCheckNeeded():
            # check for updates if we have optional items selected for install
            # or removal that have not yet been processed
            self.mainWindowController.checkForUpdates()
        
        # load the initial view only if we are not already loading something else.
        # enables launching the app to a specific panel, eg. from URL handler
        if not self.mainWindowController.webView.isLoading():
            self.mainWindowController.loadInitialView()
Пример #5
0
    def showLogWindow_(self, notification):
        '''Show the log window.'''

        if self.window.isVisible():
            # It's already open, just move it to front
            self.window.makeKeyAndOrderFront_(self)
            return

        screenRect = NSScreen.mainScreen().frame()
        windowRect = screenRect.copy()
        windowRect.origin.x = 100.0
        windowRect.origin.y = 200.0
        windowRect.size.width -= 200.0
        windowRect.size.height -= 300.0

        logfile = munki.pref('LogFile')
        self.pathControl.setURL_(NSURL.fileURLWithPath_(logfile))
        self.window.setTitle_(os.path.basename(logfile))
        self.window.setFrame_display_(windowRect, NO)
        self.window.makeKeyAndOrderFront_(self)
        self.watchLogFile_(logfile)

        # allow dragging from table view to outside of the app
        self.logView.setDraggingSourceOperationMask_forLocal_(
            NSDragOperationAll, NO)
Пример #6
0
    def showLogWindow_(self, notification):
        '''Show the log window.'''

        if self.window.isVisible():
            # It's already open, just move it to front
            self.window.makeKeyAndOrderFront_(self)
            return

        screenRect = NSScreen.mainScreen().frame()
        windowRect = screenRect.copy()
        windowRect.origin.x = 100.0
        windowRect.origin.y = 200.0
        windowRect.size.width -= 200.0
        windowRect.size.height -= 300.0

        logfile = munki.pref('LogFile')
        self.pathControl.setURL_(NSURL.fileURLWithPath_(logfile))
        self.window.setTitle_(os.path.basename(logfile))
        self.window.setFrame_display_(windowRect, NO)
        self.window.makeKeyAndOrderFront_(self)
        self.watchLogFile_(logfile)

        # allow dragging from table view to outside of the app
        self.logView.setDraggingSourceOperationMask_forLocal_(
            NSDragOperationAll, NO)
Пример #7
0
def getOptionalInstallItems():
    if munki.pref('AppleSoftwareUpdatesOnly'):
        return []
    if not 'optional_install_items' in _cache:
        _cache['optional_install_items'] = [OptionalItem(item)
                                   for item in getInstallInfo().get('optional_installs', [])]
    return _cache['optional_install_items']
Пример #8
0
def getOptionalInstallItems():
    if munki.pref('AppleSoftwareUpdatesOnly'):
        return []
    if not 'optional_install_items' in _cache:
        _cache['optional_install_items'] = [
            OptionalItem(item)
            for item in getInstallInfo().get('optional_installs', [])]
    return _cache['optional_install_items']
Пример #9
0
def getOptionalInstallItems():
    if munki.pref('AppleSoftwareUpdatesOnly'):
        return []
    if not 'optional_install_items' in _cache:
        _cache['optional_install_items'] = [
            OptionalItem(item)
            for item in getInstallInfo().get('optional_installs', [])]
        featured_items = getInstallInfo().get('featured_items', [])
        for item in _cache['optional_install_items']:
            if item['name'] in featured_items:
                item['featured'] = True
    return _cache['optional_install_items']
Пример #10
0
def getOptionalInstallItems():
    if munki.pref('AppleSoftwareUpdatesOnly'):
        return []
    if not 'optional_install_items' in _cache:
        _cache['optional_install_items'] = [
            OptionalItem(item)
            for item in getInstallInfo().get('optional_installs', [])
        ]
        featured_items = getInstallInfo().get('featured_items', [])
        for item in _cache['optional_install_items']:
            if item['name'] in featured_items:
                item['featured'] = True
    return _cache['optional_install_items']
Пример #11
0
 def showHelp_(self, sender):
     helpURL = munki.pref('HelpURL')
     if helpURL:
         NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_(helpURL))
     else:
         alertTitle = NSLocalizedString(u"Help", u"No help alert title")
         alertDetail = NSLocalizedString(
             u"Help isn't available for Managed Software Center.", u"No help alert detail")
         alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
             alertTitle,
             NSLocalizedString(u"OK", u"OK button title"),
             nil,
             nil,
             u"%@", alertDetail)
         result = alert.runModal()
Пример #12
0
def get_custom_resources():
    '''copies custom resources into our html dir'''
    if not _html_dir:
        return
    managed_install_dir = munki.pref('ManagedInstallDir')
    source_path = os.path.join(managed_install_dir, 'client_resources/custom.zip')
    if os.path.exists(source_path):
        dest_path = os.path.join(_html_dir, 'custom')
        if os.path.exists(dest_path):
            try:
                shutil.rmtree(dest_path, ignore_errors=True)
            except (OSError, IOError), err:
                msclog.debug_log('Error clearing %s: %s' % (dest_path, err))
        if not os.path.exists(dest_path):
            try:
                os.mkdir(dest_path)
            except (OSError, IOError), err:
                msclog.debug_log('Error creating %s: %s' % (dest_path, err))
Пример #13
0
def get_custom_resources():
    '''copies custom resources into our html dir'''
    if not _html_dir:
        return
    managed_install_dir = munki.pref('ManagedInstallDir')
    source_path = os.path.join(managed_install_dir, 'client_resources/custom.zip')
    if os.path.exists(source_path):
        dest_path = os.path.join(_html_dir, 'custom')
        if os.path.exists(dest_path):
            try:
                shutil.rmtree(dest_path, ignore_errors=True)
            except (OSError, IOError), err:
                msclog.debug_log('Error clearing %s: %s' % (dest_path, err))
        if not os.path.exists(dest_path):
            try:
                os.mkdir(dest_path)
            except (OSError, IOError), err:
                msclog.debug_log('Error creating %s: %s' % (dest_path, err))
Пример #14
0
    def applicationDidFinishLaunching_(self, sender):
        NSLog(u"Managed Software Update finished launching.")
        munki.log("MSU", "launched")

        runmode = NSUserDefaults.standardUserDefaults().stringForKey_("mode") or \
                  os.environ.get("ManagedSoftwareUpdateMode")
        if runmode:
            self.runmode = runmode
            NSLog("Runmode: %s" % runmode)

        # Prevent automatic relaunching at login on Lion 
        if NSApp.respondsToSelector_('disableRelaunchOnLogin'):
            NSApp.disableRelaunchOnLogin()

        consoleuser = munki.getconsoleuser()
        if consoleuser == None or consoleuser == u"loginwindow":
            # Status Window only
            NSMenu.setMenuBarVisible_(NO)
            self.munkiStatusController.startMunkiStatusSession()
        elif self.runmode == "MunkiStatus":
            self.munkiStatusController.startMunkiStatusSession()
        else:
            # user may have launched the app manually, or it may have
            # been launched by /usr/local/munki/managedsoftwareupdate
            # to display available updates
            lastcheck = NSDate.dateWithString_(munki.pref('LastCheckDate'))
            if not lastcheck or lastcheck.timeIntervalSinceNow() < -60:
                # it's been more than a minute since the last check
                self.checkForUpdates()
                return
            # do we have existing updates to display?
            if not self._listofupdates:
                self.getAvailableUpdates()
            if self._listofupdates:
                self.displayUpdatesWindow()
            else:
                # no updates available. Should we check for some?
                self.checkForUpdates()
Пример #15
0
def html_dir():
    '''sets up our local html cache directory'''
    global _html_dir
    if _html_dir:
        return _html_dir
    bundle_id = NSBundle.mainBundle().bundleIdentifier()
    cache_dir_urls = NSFileManager.defaultManager().URLsForDirectory_inDomains_(
        NSCachesDirectory, NSUserDomainMask)
    if cache_dir_urls:
        cache_dir = cache_dir_urls[0].path()
    else:
        cache_dir = u'/private/tmp'
    our_cache_dir = os.path.join(cache_dir, bundle_id)
    if not os.path.exists(our_cache_dir):
         os.makedirs(our_cache_dir)
    _html_dir = os.path.join(our_cache_dir, 'html')
    if os.path.exists(_html_dir):
        # empty it
        shutil.rmtree(_html_dir)
    os.mkdir(_html_dir)
    
    # symlink our static files dir
    resourcesPath = NSBundle.mainBundle().resourcePath()
    source_path = os.path.join(resourcesPath, 'WebResources')
    link_path = os.path.join(_html_dir, 'static')
    os.symlink(source_path, link_path)
    
    # symlink the Managed Installs icons dir
    managed_install_dir = munki.pref('ManagedInstallDir')
    source_path = os.path.join(managed_install_dir, 'icons')
    link_path = os.path.join(_html_dir, 'icons')
    os.symlink(source_path, link_path)
    
    # unzip any custom client resources
    get_custom_resources()
    
    return _html_dir
Пример #16
0
def html_dir():
    '''sets up our local html cache directory'''
    global _html_dir
    if _html_dir:
        return _html_dir
    bundle_id = NSBundle.mainBundle().bundleIdentifier()
    cache_dir_urls = NSFileManager.defaultManager(
    ).URLsForDirectory_inDomains_(NSCachesDirectory, NSUserDomainMask)
    if cache_dir_urls:
        cache_dir = cache_dir_urls[0].path()
    else:
        cache_dir = u'/private/tmp'
    our_cache_dir = os.path.join(cache_dir, bundle_id)
    if not os.path.exists(our_cache_dir):
        os.makedirs(our_cache_dir)
    _html_dir = os.path.join(our_cache_dir, 'html')
    if os.path.exists(_html_dir):
        # empty it
        shutil.rmtree(_html_dir)
    os.mkdir(_html_dir)

    # symlink our static files dir
    resourcesPath = NSBundle.mainBundle().resourcePath()
    source_path = os.path.join(resourcesPath, 'WebResources')
    link_path = os.path.join(_html_dir, 'static')
    os.symlink(source_path, link_path)

    # symlink the Managed Installs icons dir
    managed_install_dir = munki.pref('ManagedInstallDir')
    source_path = os.path.join(managed_install_dir, 'icons')
    link_path = os.path.join(_html_dir, 'icons')
    os.symlink(source_path, link_path)

    # unzip any custom client resources
    get_custom_resources()

    return _html_dir
Пример #17
0
    def munkiStatusSessionEnded_(self, socketSessionResult):
        consoleuser = munki.getconsoleuser()
        if (self.runmode == "MunkiStatus" or consoleuser == None
            or consoleuser == u"loginwindow"):
            # Status Window only, so we should just quit
            munki.log("MSU", "exit_munkistatus")
            NSApp.terminate_(self)

        # The managedsoftwareupdate run will have changed state preferences
        # in ManagedInstalls.plist. Load the new values.
        munki.reload_prefs()

        alertMessageText = NSLocalizedString(u"Update check failed", None)
        if self.managedsoftwareupdate_task == "installwithnologout":
            alertMessageText = NSLocalizedString(u"Install session failed", None)

        if socketSessionResult == -1:
            # connection was dropped unexpectedly
            self.mainWindowController.theWindow.makeKeyAndOrderFront_(self)
            alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
                alertMessageText,
                NSLocalizedString(u"Quit", None),
                objc.nil,
                objc.nil,
                NSLocalizedString(u"There is a configuration problem with the managed software installer. The process ended unexpectedly. Contact your systems administrator.", None))
            alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
                self.mainWindowController.theWindow, self, self.quitAlertDidEnd_returnCode_contextInfo_, objc.nil)
            return

        elif socketSessionResult == -2:
            # socket timed out before connection
            self.mainWindowController.theWindow.makeKeyAndOrderFront_(self)
            alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
                alertMessageText,
                NSLocalizedString(u"Quit", None),
                objc.nil,
                objc.nil,
                NSLocalizedString(u"There is a configuration problem with the managed software installer. Could not start the process. Contact your systems administrator.", None))
            alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
                self.mainWindowController.theWindow, self, self.quitAlertDidEnd_returnCode_contextInfo_, objc.nil)
            return

        if self.managedsoftwareupdate_task == "installwithnologout":
            # we're done.
            munki.log("MSU", "exit_installwithnologout")
            NSApp.terminate_(self)

        elif self.managedsoftwareupdate_task == "manualcheck":
            self.managedsoftwareupdate_task = None
            self._listofupdates = []
            self.getAvailableUpdates()
            #NSLog(u"Building table of available updates.")
            self.buildUpdateTableData()
            if self._optionalInstalls:
                #NSLog(u"Building table of optional software.")
                self.buildOptionalInstallsData()
            #NSLog(u"Showing main window.")
            self.mainWindowController.theWindow.makeKeyAndOrderFront_(self)
            #NSLog(u"Main window was made key and ordered front")
            if self._listofupdates:
                return
            # no list of updates; let's check the LastCheckResult for more info
            lastCheckResult = munki.pref("LastCheckResult")
            if lastCheckResult == 0:
                munki.log("MSU", "no_updates")
                self.noUpdatesAlert()
            elif lastCheckResult == 1:
                NSApp.requestUserAttention_(NSCriticalRequest)
            elif lastCheckResult == -1:
                munki.log("MSU", "cant_update", "cannot contact server")
                alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
                    NSLocalizedString(u"Cannot check for updates", None),
                    NSLocalizedString(u"Quit", None),
                    objc.nil,
                    objc.nil,
                    NSLocalizedString(u"Managed Software Update cannot contact the update server at this time.\nIf this situation continues, contact your systems administrator.", None))
                alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
                    self.mainWindowController.theWindow, self, self.quitAlertDidEnd_returnCode_contextInfo_, objc.nil)
            elif lastCheckResult == -2:
                munki.log("MSU", "cant_update", "failed preflight")
                alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
                    NSLocalizedString(u"Cannot check for updates", None),
                    NSLocalizedString(u"Quit",  None),
                    objc.nil,
                    objc.nil,
                    NSLocalizedString(u"Managed Software Update failed its preflight check.\nTry again later.", None))
                alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
                    self.mainWindowController.theWindow, self, self.quitAlertDidEnd_returnCode_contextInfo_, objc.nil)
Пример #18
0
    def applicationDidFinishLaunching_(self, sender):
        NSLog(u"Managed Software Update finished launching.")

        ver = NSBundle.mainBundle().infoDictionary().get(
            'CFBundleShortVersionString')
        NSLog("MSU GUI version: %s" % ver)
        munki.log("MSU", "launched", "VER=%s" % ver)

        runmode = NSUserDefaults.standardUserDefaults().stringForKey_("mode") or \
                  os.environ.get("ManagedSoftwareUpdateMode")
        if runmode:
            self.runmode = runmode
            NSLog("Runmode: %s" % runmode)

        # Prevent automatic relaunching at login on Lion
        if NSApp.respondsToSelector_('disableRelaunchOnLogin'):
            NSApp.disableRelaunchOnLogin()

        # register for notification messages so we can be told if available updates
        # change while we are open
        notification_center = NSDistributedNotificationCenter.defaultCenter()
        notification_center.addObserver_selector_name_object_suspensionBehavior_(
            self,
            self.updateAvailableUpdates,
            'com.googlecode.munki.ManagedSoftwareUpdate.update',
            None,
            NSNotificationSuspensionBehaviorDeliverImmediately)

        # register for notification messages so we can be told to
        # display a logout warning
        notification_center = NSDistributedNotificationCenter.defaultCenter()
        notification_center.addObserver_selector_name_object_suspensionBehavior_(
            self,
            self.forcedLogoutWarning,
            'com.googlecode.munki.ManagedSoftwareUpdate.logoutwarn',
            None,
            NSNotificationSuspensionBehaviorDeliverImmediately)

        consoleuser = munki.getconsoleuser()
        if consoleuser == None or consoleuser == u"loginwindow":
            # Status Window only
            NSMenu.setMenuBarVisible_(NO)
            self.munkiStatusController.startMunkiStatusSession()
        elif self.runmode == "MunkiStatus":
            self.munkiStatusController.startMunkiStatusSession()
        else:
            # user may have launched the app manually, or it may have
            # been launched by /usr/local/munki/managedsoftwareupdate
            # to display available updates
            if munki.thereAreUpdatesToBeForcedSoon(hours=2):
                # skip the check and just display the updates
                # by pretending the lastcheck is now
                lastcheck = NSDate.date()
            else:
                lastcheck = NSDate.dateWithString_(munki.pref('LastCheckDate'))
            if not lastcheck or lastcheck.timeIntervalSinceNow() < -60:
                # it's been more than a minute since the last check
                self.checkForUpdates()
                return
            # do we have existing updates to display?
            if not self._listofupdates:
                self.getAvailableUpdates()
            if self._listofupdates:
                self.displayUpdatesWindow()
            else:
                # no updates available. Should we check for some?
                self.checkForUpdates()
Пример #19
0
    def munkiStatusSessionEnded_(self, sessionResult):
        '''Called by StatusController when a Munki session ends'''
        msclog.debug_log(u"MunkiStatus session ended: %s" % sessionResult)
        msclog.debug_log(u"MunkiStatus session type: %s" % self.managedsoftwareupdate_task)
        tasktype = self.managedsoftwareupdate_task
        self.managedsoftwareupdate_task = None
        self._update_in_progress = False
        
        # The managedsoftwareupdate run will have changed state preferences
        # in ManagedInstalls.plist. Load the new values.
        munki.reload_prefs()
        lastCheckResult = munki.pref("LastCheckResult")
        if sessionResult != 0 or lastCheckResult < 0:
            OKButtonTitle = NSLocalizedString(u"OK", u"OK button title")
            alertMessageText = NSLocalizedString(
                                    u"Update check failed", u"Update Check Failed title")
            if tasktype == "installwithnologout":
                alertMessageText = NSLocalizedString(
                                        u"Install session failed", u"Install Session Failed title")

            if sessionResult == -1:
                # connection was dropped unexpectedly
                msclog.log("MSC", "cant_update", "unexpected process end")
                detailText = NSLocalizedString(
                    (u"There is a configuration problem with the managed software installer. "
                      "The process ended unexpectedly. Contact your systems administrator."),
                     u"Unexpected Session End message")
            elif sessionResult == -2:
                # session never started
                msclog.log("MSC", "cant_update", "process did not start")
                detailText = NSLocalizedString(
                    (u"There is a configuration problem with the managed software installer. "
                      "Could not start the process. Contact your systems administrator."),
                     u"Could Not Start Session message")
            elif lastCheckResult == -1:
                # server not reachable
                msclog.log("MSC", "cant_update", "cannot contact server")
                detailText = NSLocalizedString(
                    (u"Managed Software Center cannot contact the update server at this time.\n"
                      "Try again later. If this situation continues, "
                      "contact your systems administrator."), u"Cannot Contact Server detail")
            elif lastCheckResult == -2:
                # preflight failed
                msclog.log("MSU", "cant_update", "failed preflight")
                detailText = NSLocalizedString(
                    (u"Managed Software Center cannot check for updates now.\n"
                      "Try again later. If this situation continues, "
                      "contact your systems administrator."), u"Failed Preflight Check detail")
            # show the alert sheet
            self.window().makeKeyAndOrderFront_(self)
            alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
                alertMessageText, OKButtonTitle, nil, nil, u"%@", detailText)
            alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
                self.window(), self,
                self.munkiSessionErrorAlertDidEnd_returnCode_contextInfo_, nil)
            return
        
        if tasktype == 'checktheninstall':
            MunkiItems.reset()
            # possibly check again if choices have changed
            self.updateNow()
            return

        # all done checking and/or installing: display results
        self.resetAndReload()
        
        if MunkiItems.updateCheckNeeded():
            # more stuff pending? Let's do it...
            self.updateNow()
Пример #20
0
    def applicationDidFinishLaunching_(self, sender):
        NSLog(u"Managed Software Update finished launching.")

        ver = NSBundle.mainBundle().infoDictionary().get(
            'CFBundleShortVersionString')
        NSLog("MSU GUI version: %s" % ver)
        munki.log("MSU", "launched", "VER=%s" % ver)

        runmode = (NSUserDefaults.standardUserDefaults().stringForKey_("mode") 
                   or os.environ.get("ManagedSoftwareUpdateMode"))
        if runmode:
            self.runmode = runmode
            NSLog("Runmode: %s" % runmode)
        else:
            consoleuser = munki.getconsoleuser()
            if consoleuser == None or consoleuser == u"loginwindow":
                # we're at the loginwindow, so display MunkiStatus
                self.runmode = "MunkiStatus"

        # Prevent automatic relaunching at login on Lion
        if NSApp.respondsToSelector_('disableRelaunchOnLogin'):
            NSApp.disableRelaunchOnLogin()

        # register for notification messages so we can be told if available 
        # updates change while we are open
        notification_center = NSDistributedNotificationCenter.defaultCenter()
        notification_center.addObserver_selector_name_object_suspensionBehavior_(
            self,
            self.updateAvailableUpdates,
            'com.googlecode.munki.ManagedSoftwareUpdate.update',
            None,
            NSNotificationSuspensionBehaviorDeliverImmediately)

        # register for notification messages so we can be told to
        # display a logout warning
        notification_center = NSDistributedNotificationCenter.defaultCenter()
        notification_center.addObserver_selector_name_object_suspensionBehavior_(
            self,
            self.forcedLogoutWarning,
            'com.googlecode.munki.ManagedSoftwareUpdate.logoutwarn',
            None,
            NSNotificationSuspensionBehaviorDeliverImmediately)

        if self.runmode == "MunkiStatus":
            self.munkiStatusController.startMunkiStatusSession()
        else:
            # user may have launched the app manually, or it may have
            # been launched by /usr/local/munki/managedsoftwareupdate
            # to display available updates
            if munki.thereAreUpdatesToBeForcedSoon(hours=2):
                # skip the check and just display the updates
                # by pretending the lastcheck is now
                lastcheck = NSDate.date()
            else:
                lastcheck = NSDate.dateWithString_(munki.pref('LastCheckDate'))
            # if there is no lastcheck timestamp, check for updates.
            if not lastcheck:
                self.checkForUpdates()
                return

            # otherwise, only check for updates if the last check is over the
            # configured manualcheck cache age max.
            max_cache_age = (
                munki.pref('CheckResultsCacheSeconds') or
                DEFAULT_GUI_CACHE_AGE_SECS)
            if lastcheck.timeIntervalSinceNow() * -1 > int(max_cache_age):
                self.checkForUpdates()
                return

            # if needed, get updates from InstallInfo.
            if not self._listofupdates:
                self.getAvailableUpdates()
            # if updates exist, display them.
            if self._listofupdates:
                self.displayUpdatesWindow()
            else:
                # only check for updates if cache secs config is not defined.
                if munki.pref('CheckResultsCacheSeconds'):
                    self.mainWindowController.theWindow.makeKeyAndOrderFront_(
                        self)
                    self.noUpdatesAlert()
                else:
                    self.checkForUpdates()
Пример #21
0
    def munkiStatusSessionEnded_(self, socketSessionResult):
        consoleuser = munki.getconsoleuser()
        if (self.runmode == "MunkiStatus" or consoleuser == None
                or consoleuser == u"loginwindow"):
            # Status Window only, so we should just quit
            munki.log("MSU", "exit_munkistatus")
            # clear launch trigger file so we aren't immediately
            # relaunched by launchd
            munki.clearLaunchTrigger()
            NSApp.terminate_(self)

        # The managedsoftwareupdate run will have changed state preferences
        # in ManagedInstalls.plist. Load the new values.
        munki.reload_prefs()

        alertMessageText = NSLocalizedString(u"Update check failed", None)
        if self.managedsoftwareupdate_task == "installwithnologout":
            alertMessageText = NSLocalizedString(u"Install session failed",
                                                 None)

        if socketSessionResult == -1:
            # connection was dropped unexpectedly
            self.mainWindowController.theWindow.makeKeyAndOrderFront_(self)
            alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
                alertMessageText, NSLocalizedString(u"Quit", None), objc.nil,
                objc.nil,
                NSLocalizedString(
                    u"There is a configuration problem with the managed software installer. The process ended unexpectedly. Contact your systems administrator.",
                    None))
            alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
                self.mainWindowController.theWindow, self,
                self.quitAlertDidEnd_returnCode_contextInfo_, objc.nil)
            return

        elif socketSessionResult == -2:
            # socket timed out before connection
            self.mainWindowController.theWindow.makeKeyAndOrderFront_(self)
            alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
                alertMessageText, NSLocalizedString(u"Quit", None), objc.nil,
                objc.nil,
                NSLocalizedString(
                    u"There is a configuration problem with the managed software installer. Could not start the process. Contact your systems administrator.",
                    None))
            alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
                self.mainWindowController.theWindow, self,
                self.quitAlertDidEnd_returnCode_contextInfo_, objc.nil)
            return

        if self.managedsoftwareupdate_task == "installwithnologout":
            # we're done.
            munki.log("MSU", "exit_installwithnologout")
            NSApp.terminate_(self)

        elif self.managedsoftwareupdate_task == "manualcheck":
            self.managedsoftwareupdate_task = None
            self._listofupdates = []
            self.getAvailableUpdates()
            #NSLog(u"Building table of available updates.")
            self.buildUpdateTableData()
            if self._optionalInstalls:
                #NSLog(u"Building table of optional software.")
                self.buildOptionalInstallsData()
            #NSLog(u"Showing main window.")
            self.mainWindowController.theWindow.makeKeyAndOrderFront_(self)
            #NSLog(u"Main window was made key and ordered front")
            if self._listofupdates:
                return
            # no list of updates; let's check the LastCheckResult for more info
            lastCheckResult = munki.pref("LastCheckResult")
            if lastCheckResult == 0:
                munki.log("MSU", "no_updates")
                self.noUpdatesAlert()
            elif lastCheckResult == 1:
                NSApp.requestUserAttention_(NSCriticalRequest)
            elif lastCheckResult == -1:
                munki.log("MSU", "cant_update", "cannot contact server")
                alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
                    NSLocalizedString(u"Cannot check for updates", None),
                    NSLocalizedString(u"Quit", None), objc.nil, objc.nil,
                    NSLocalizedString(
                        u"Managed Software Update cannot contact the update server at this time.\nIf this situation continues, contact your systems administrator.",
                        None))
                alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
                    self.mainWindowController.theWindow, self,
                    self.quitAlertDidEnd_returnCode_contextInfo_, objc.nil)
            elif lastCheckResult == -2:
                munki.log("MSU", "cant_update", "failed preflight")
                alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(
                    NSLocalizedString(u"Cannot check for updates", None),
                    NSLocalizedString(u"Quit", None), objc.nil, objc.nil,
                    NSLocalizedString(
                        u"Managed Software Update failed its preflight check.\nTry again later.",
                        None))
                alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
                    self.mainWindowController.theWindow, self,
                    self.quitAlertDidEnd_returnCode_contextInfo_, objc.nil)
Пример #22
0
    def applicationDidFinishLaunching_(self, sender):
        NSLog(u"Managed Software Update finished launching.")

        ver = NSBundle.mainBundle().infoDictionary().get(
            'CFBundleShortVersionString')
        NSLog("MSU GUI version: %s" % ver)
        munki.log("MSU", "launched", "VER=%s" % ver)

        runmode = NSUserDefaults.standardUserDefaults().stringForKey_("mode") or \
                  os.environ.get("ManagedSoftwareUpdateMode")
        if runmode:
            self.runmode = runmode
            NSLog("Runmode: %s" % runmode)

        # Prevent automatic relaunching at login on Lion
        if NSApp.respondsToSelector_('disableRelaunchOnLogin'):
            NSApp.disableRelaunchOnLogin()

        # register for notification messages so we can be told if available updates
        # change while we are open
        notification_center = NSDistributedNotificationCenter.defaultCenter()
        notification_center.addObserver_selector_name_object_suspensionBehavior_(
            self, self.updateAvailableUpdates,
            'com.googlecode.munki.ManagedSoftwareUpdate.update', None,
            NSNotificationSuspensionBehaviorDeliverImmediately)

        # register for notification messages so we can be told to
        # display a logout warning
        notification_center = NSDistributedNotificationCenter.defaultCenter()
        notification_center.addObserver_selector_name_object_suspensionBehavior_(
            self, self.forcedLogoutWarning,
            'com.googlecode.munki.ManagedSoftwareUpdate.logoutwarn', None,
            NSNotificationSuspensionBehaviorDeliverImmediately)

        consoleuser = munki.getconsoleuser()
        if consoleuser == None or consoleuser == u"loginwindow":
            # Status Window only
            NSMenu.setMenuBarVisible_(NO)
            self.munkiStatusController.startMunkiStatusSession()
        elif self.runmode == "MunkiStatus":
            self.munkiStatusController.startMunkiStatusSession()
        else:
            # user may have launched the app manually, or it may have
            # been launched by /usr/local/munki/managedsoftwareupdate
            # to display available updates
            if munki.thereAreUpdatesToBeForcedSoon(hours=2):
                # skip the check and just display the updates
                # by pretending the lastcheck is now
                lastcheck = NSDate.date()
            else:
                lastcheck = NSDate.dateWithString_(munki.pref('LastCheckDate'))
            if not lastcheck or lastcheck.timeIntervalSinceNow() < -60:
                # it's been more than a minute since the last check
                self.checkForUpdates()
                return
            # do we have existing updates to display?
            if not self._listofupdates:
                self.getAvailableUpdates()
            if self._listofupdates:
                self.displayUpdatesWindow()
            else:
                # no updates available. Should we check for some?
                self.checkForUpdates()