def setup(self, *args):
        ''' Setup '''

        self.logger.debug("setup")
        self._populate_data()

        if self.controller.test():
            if not self.controller.save():
                showerror_gtk(
                    _("An error happened while saving the users " +
                      "authentication method!") + "\n" +
                    _("See log for more details."),
                    None)
    def checkForUpdates(self):
        ''' Checking for update gecos config assistant '''

        import apt
        from apt.cache import FetchFailedException

        apt_progress = GtkAptProgress()
        cache = apt.cache.Cache(apt_progress.open)
        # apt-get update
        cache.update()
        # We need to re-open the cache because it needs to read the package list
        cache.open(None)

        software_checks = ['chef', 'gecos-agent', 'gecosws-config-assistant']

        updates = [
            pkg for pkg in software_checks
            if cache.has_key(pkg) and cache[pkg].is_upgradable
        ]

        if len(updates) > 0:

            [cache[update].mark_upgrade() for update in updates]

            splash = SplashScreen()
            hbox2 = splash.getElementById('hbox2')
            hbox2.pack_start(apt_progress, True, True, 0)
            apt_progress.show()
            splash.show()

            button = splash.getElementById('label1')
            button.set_label(_('Upgrading ...'))

            apt_progress.show_terminal(True)

            upgrade = True

            try:
                cache.commit(apt_progress.acquire, apt_progress.install)
            except FetchFailedException, e:
                upgrade = False
                self.logger.debug("Exception happened: %s", e)
                showerror_gtk(_("Unable to connect to software repository"),
                              self.window.getMainWindow())
            except Exception, e:
                upgrade = False
                self.logger.debug("Exception happened: %s", e)
                showerror_gtk(_("An error occurred during the upgrade"),
                              self.window.getMainWindow())
Ejemplo n.º 3
0
    def save(self):
        ''' Save data '''

        self.logger.debug('save')
        data = self.view.get_data()
        try:
            if self.dao.save(data):
                self.hide()
            else:
                # Show error message
                showerror_gtk(
                    _("Error saving NTP server data.") + "\n" +
                    _("See log for more details."), self.view)
        except Exception:
            # Show error message
            showerror_gtk(
                _("Error saving NTP server data.") + "\n" +
                _("See log for more details."), self.view)
Ejemplo n.º 4
0
    def accept(self, *args):
        ''' Accept action '''

        self.logger.debug("Accept")
        if self.get_data() is None:
            self.set_data(ADSetupData())
        self.get_data().set_domain(self.adDomainEntry.get_text())
        self.get_data().set_workgroup(self.adWorkgroupEntry.get_text())
        self.get_data().set_ad_administrator_user(self.adUserEntry.get_text())
        self.get_data().set_ad_administrator_pass(
            self.adPasswordEntry.get_text())

        if self.get_data().test():
            self.window.hide()
            Gtk.main_quit()
        else:
            showerror_gtk(
                _("Can't connect to Active Directory.\n" +
                  "Please double-check all the fields"), None)
    def save(self):
        ''' Save '''

        self.logger.debug('save - BEGIN')
        oldData = self.dao.load()
        newData = self.view.get_data()
        if newData is not None:
            # Return to local users authentication
            if isinstance(oldData, ADAuthMethod):
                # We need AD Administrator user credentials to return
                # to local users authentication method

                # Ask the user for Active Directory administrator
                # user and password
                askForActiveDirectoryCredentialsView = ADSetupDataElemView(
                    self.mainWindow, self)
                askForActiveDirectoryCredentialsView.set_data(
                    oldData.get_data())
                askForActiveDirectoryCredentialsView.show()

                data = askForActiveDirectoryCredentialsView.get_data()
                if data is None:
                    self.logger.error("Operation canceled by user!")
                    return False
                oldData.set_data(data)

            if self.dao.delete(oldData):
                # Set new authentication method
                if self.dao.save(newData):
                    self.logger.debug("Authentication method saved!")
                    showinfo_gtk(_("Authentication method saved!"), self.view)
                    return True
                else:
                    self.logger.error("Authentication method failed!")
                    showerror_gtk(_("Authentication method failed!"),
                                  self.view)
            else:
                return False
        else:
            self.logger.debug("Empty data!")

        return False
    def _test(self):
        # Test confirm password
        password = self.passwordEntry.get_text()
        confirm = self.passwordConfirmationEntry.get_text()

        if password is not None and password.strip() != '':
            if confirm is None or confirm.strip() == '':
                self.logger.debug("Empty password confirmation!")
                showerror_gtk(
                    _("The password confirmation field is empty!") + "\n" +
                    _("Please fill all the mandatory fields."), self)
                self.passwordConfirmationEntry.grab_focus()
                return False

            if confirm != password:
                self.logger.debug(
                    "Password confirmation different from password!")
                showerror_gtk(
                    _("The password confirmation is different from password"),
                    self)
                self.passwordConfirmationEntry.grab_focus()
                return False

        return True
    def test(self):
        ''' Testing purposes '''

        self.logger.debug('test - BEGIN')

        if self.view.get_data() is None:
            self.logger.debug("Empty data!")
            return False

        newData = self.view.get_data()

        if isinstance(newData, LDAPAuthMethod):
            # Check LDAP parameters
            newAuthData = newData.get_data()

            if (newAuthData.get_uri() is None
                    or newAuthData.get_uri().strip() == ''):
                self.logger.debug("Empty LDAP URI!")
                showerror_gtk(
                    _("The URI field is empty!") + "\n" +
                    _("Please fill all the mandatory fields."), self.view)
                self.view.focusLdapUriField()
                return False

            if not Validation().isLdapUri(newAuthData.get_uri()):
                self.logger.debug("Malformed LDAP URI! %s",
                                  newAuthData.get_uri())
                showerror_gtk(
                    _("Malformed LDAP URI!") + "\n" +
                    _("Please check that the URI starts with 'ldap(s)://'."),
                    self.view)
                self.view.focusLdapUriField()
                return False

            if (newAuthData.get_base() is None
                    or newAuthData.get_base().strip() == ''):
                self.logger.debug("Empty user base DN!")
                showerror_gtk(
                    _("The users base DN field is empty!") + "\n" +
                    _("Please fill all the mandatory fields."), self.view)
                self.view.focusUserBaseDNField()
                return False

            if not newAuthData.test():
                self.logger.debug("Can't connect to LDAP!")
                showerror_gtk(
                    _("Can't connect to LDAP server!") + "\n" +
                    _("Please check all the fields " +
                      "and your network connection."), self.view)
                self.view.focusLdapUriField()
                return False

        if isinstance(newData, ADAuthMethod):
            # Check AD parameters
            newAuthData = newData.get_data()

            networkInterfaceDAO = NetworkInterfaceDAO()
            hostname = networkInterfaceDAO.get_hostname()

            if not Validation().isValidNetbiosHostname(hostname):
                self.logger.debug("Bad hostname: %s", hostname)
                showerror_gtk(
                    _("Bad netbios hostname!") + ": " + hostname + "\n" +
                    _("Please change the hostname of this computer."),
                    self.view)
                self.view.focusAdDomainField()
                return False

            if (newAuthData.get_domain() is None
                    or newAuthData.get_domain().strip() == ''):
                self.logger.debug("Empty AD domain field!")
                showerror_gtk(
                    _("The Domain field is empty!") + "\n" +
                    _("Please fill all the mandatory fields."), self.view)
                self.view.focusAdDomainField()
                return False

            self.logger.debug('Specific: %s', newAuthData.get_specific())

            if not newAuthData.get_specific():
                # Check fqdn
                ipaddress = None
                try:
                    ipaddress = socket.gethostbyname(newAuthData.get_domain())
                except Exception:
                    self.logger.error("Can't resolv domain name: %s",
                                      newAuthData.get_domain())
                    self.logger.error(str(traceback.format_exc()))

                if ipaddress is None:
                    showerror_gtk(
                        _("Can't resolv the Active Directory Domain name!") +
                        "\n" + _("Please check the Domain field " +
                                 "and your DNS configuration."), self.view)
                    self.view.focusAdDomainField()
                    return False

            if (newAuthData.get_workgroup() is None
                    or newAuthData.get_workgroup().strip() == ''):
                self.logger.debug("Empty AD workgroup field!")
                showerror_gtk(
                    _("The Workgroup field is empty!") + "\n" +
                    _("Please fill all the mandatory fields."), self.view)
                self.view.focusAdWorkgroupField()
                return False

            if (newAuthData.get_ad_administrator_user() is None
                    or newAuthData.get_ad_administrator_user().strip() == ''):
                self.logger.debug("Empty AD administrator user field!")
                showerror_gtk(
                    _("The AD administrator user field is empty!") + "\n" +
                    _("Please fill all the mandatory fields."), self.view)
                self.view.focusAdUserField()
                return False

            if (newAuthData.get_ad_administrator_pass() is None
                    or newAuthData.get_ad_administrator_pass().strip() == ''):
                self.logger.debug("Empty AD administrator password field!")
                showerror_gtk(
                    _("The AD administrator password field is empty!") + "\n" +
                    _("Please fill all the mandatory fields."), self.view)
                self.view.focusAdPasswordField()
                return False

            if not newAuthData.test():
                self.logger.debug("Can't connect to Active Directory!")
                showerror_gtk(
                    _("Can't connect to Active Directory server!") + "\n" +
                    _("Please check all the fields " +
                      "and your network connection."), self.view)
                self.view.focusAdDomainField()
                return False

        return True
class MainMenuController(object):
    '''
    Controller class to show the main menu window.
    '''
    def __init__(self):
        '''
        Constructor
        '''
        self.logger = logging.getLogger('MainMenuController')
        self.window = MainWindow(self)
        self.logger.error(self.window)

        # controllers
        self.connectWithGecosCC = ConnectWithGecosCCController(self)
        self.userAuthenticationMethod = UserAuthenticationMethodController(
            self)
        self.localUserList = LocalUserController(self)
        self.systemStatus = SystemStatusController(self)
        self.logController = LogTerminalController(self)
        self.requirementsCheck = RequirementsCheckController(self)

        #keys
        self.networkStatusKey = "networkStatus"
        self.ntpStatusKey = "ntpStatus"
        self.autoconfStatusKey = "autoconf"
        self.gecosStatusKey = "gecos"
        self.usersStatusKey = "users"

        self.window.buildUI()
        self.showRequirementsCheckDialog()

    def show(self):
        ''' Show main window '''

        # Checking updates for GCA
        self.checkForUpdates()

        self.window.show()

    def hide(self):
        ''' Hide main window '''

        self.root.destroy()

    def calculateStatus(self):
        ''' Calculates status of system '''

        ret = {}

        ret[self.networkStatusKey] = 3
        ret[self.ntpStatusKey] = 3
        ret[self.autoconfStatusKey] = 3
        ret[self.gecosStatusKey] = 3
        ret[self.usersStatusKey] = 3

        checkNetwork = self.checkNetwork()
        checkNTP = self.checkNTP()

        self.logger.debug('calculateStatus - network is: %s', checkNetwork)
        self.logger.debug('calculateStatus - NTP is: %s', checkNTP)

        if checkNetwork:
            # Network is green
            ret[self.networkStatusKey] = 1

            if checkNTP:
                # NTP is green
                ret[self.ntpStatusKey] = 1

            if self.checkAutoconf():
                # Auto configuration is green
                ret[self.autoconfStatusKey] = 1
            else:
                # Auto configuration is yellow
                ret[self.autoconfStatusKey] = 2

            if checkNetwork and checkNTP:
                ret[self.gecosStatusKey] = 2
                ret[self.usersStatusKey] = 2

            self.logger.debug('calculateStatus - GECOS is: %s',
                              self.checkGECOS())
            if self.checkGECOS():
                ret[self.gecosStatusKey] = 1

            self.logger.debug('calculateStatus - Authentication is: %s',
                              self.checkUsers())
            if self.checkUsers():
                ret[self.usersStatusKey] = 1

        return ret

    def calculateMainButtons(self, calculatedStatus):
        ''' Calculates main buttons '''

        ret = {
            'netbutton': True,
            'confbutton': False,
            'userbutton': False,
            'syncbutton': False,
            'sysbutton': False
        }

        if calculatedStatus[self.autoconfStatusKey] != 3:
            ret["confbutton"] = True

        if calculatedStatus[self.ntpStatusKey] != 3:
            ret["syncbutton"] = True

        if calculatedStatus[self.gecosStatusKey] != 3:
            ret["sysbutton"] = True

        if calculatedStatus[self.usersStatusKey] != 3:
            ret["userbutton"] = True

        return ret

    def calculateTopButtons(self, calculatedStatus):
        ''' Calculates top buttons '''

        buttons = {}

        buttons["linkbutton"] = False \
            if calculatedStatus[self.gecosStatusKey] == 3 \
            else True

        buttons["authbutton"] = False \
            if calculatedStatus[self.autoconfStatusKey] == 3 \
            else True

        return buttons

    def getTexts(self):
        ''' Getting text '''

        self.logger.debug("Calculating texts")
        text = {}

        if self.checkNetwork():
            text[self.networkStatusKey] = \
                _("This workstation has got a network connection configured")
        else:
            text[self.networkStatusKey] = \
                _("This workstation has NO network connection")

        if self.checkAutoconf():
            text[self.autoconfStatusKey] = \
                _("This worstation has loaded setup data values from Control Center")
        else:
            text[self.autoconfStatusKey] = \
                _("This workstation can load setup data values from Control Center")

        if self.checkNTP():
            text[self.ntpStatusKey] = \
                _("This workstation is synchronized with a time server (NTP)")
        else:
            text[self.ntpStatusKey] = \
                _("This workstation is NOT synchronized with a time server (NTP)")

        if self.checkGECOS():
            text[self.gecosStatusKey] = \
                _("This workstation is linked to a Control Center")
        else:
            text[self.gecosStatusKey] = \
                _("This workstation is NOT linked to a Control Center")

        basetext = _("Users authenticate themselves with %s")

        status = self.userAuthenticationMethod.getStatus()

        if status == LDAP_USERS:
            text[self.usersStatusKey] = _(basetext) % (_("LDAP"))
        elif status == AD_USERS:
            text[self.usersStatusKey] = _(basetext) % (_("Active Directory"))
        else:
            text[self.usersStatusKey] = _(basetext) % (_("Internal"))

        return text

    def checkNetwork(self):
        ''' Checking network '''

        self.logger.debug("Checking network status")
        ret = self.requirementsCheck.getNetworkStatus()
        return ret

    def getNetworkInterfaces(self):
        ''' Checking network interfaces '''
        return self.requirementsCheck.getNetworkInterfaces()

    def checkNTP(self):
        ''' Checking NTP server '''

        self.logger.debug("Checking NTP status")
        ret = self.requirementsCheck.getNTPStatus()
        return ret

    def checkAutoconf(self):
        ''' Checking autoconf '''

        self.logger.debug("Checking Autoconf")
        ret = self.requirementsCheck.getAutoconfStatus()
        return ret

    def checkGECOS(self):
        ''' Checking GECOS '''

        self.logger.debug("Checking GECOS")
        ret = self.connectWithGecosCC.getStatus()
        return ret

    def checkUsers(self):
        ''' Checking users '''

        self.logger.debug("Checking Users")
        ret = self.userAuthenticationMethod.areNotInternal()
        return ret

    # new show methods
    def backToMainWindowDialog(self):
        ''' Restore main window '''

        self.showRequirementsCheckDialog()

    def showRequirementsCheckDialog(self):
        ''' Show requirements '''

        self.requirementsCheck.show(self.window)

        # Check status
        calculatedStatus = self.calculateStatus()
        calculatedButtons = self.calculateTopButtons(calculatedStatus)

        self.window.setStatus(calculatedStatus, calculatedButtons)

    def showConnectWithGecosCCDialog(self):
        ''' Show connection with GEcos Control Center '''

        self.connectWithGecosCC.show(self.window)

    def showUserAuthenticationMethod(self):
        ''' Show user authentication methods '''

        view = self.userAuthenticationMethod.getView(self)
        self.window.gotoUserAuth(view)

    def showSoftwareManager(self):
        ''' Show software manager '''

        self.logger.debug("showSoftwareManager")
        cmd = '/usr/sbin/synaptic'
        os.spawnlp(os.P_NOWAIT, cmd, cmd)

    def showLocalUserListView(self):
        ''' Show local user view '''

        self.localUserList.showList(self.window)

    def splash_threading(self, title=_('Upgrading ...')):
        ''' Thread running splash screen '''

        GObject.threads_init()
        splash = SplashScreen()
        button = splash.getElementById('label1')
        button.set_label(title)
        splash.show()
        Gtk.main()

    def checkForUpdates(self):
        ''' Checking for update gecos config assistant '''

        import apt
        from apt.cache import FetchFailedException

        apt_progress = GtkAptProgress()
        cache = apt.cache.Cache(apt_progress.open)
        # apt-get update
        cache.update()
        # We need to re-open the cache because it needs to read the package list
        cache.open(None)

        software_checks = ['chef', 'gecos-agent', 'gecosws-config-assistant']

        updates = [
            pkg for pkg in software_checks
            if cache.has_key(pkg) and cache[pkg].is_upgradable
        ]

        if len(updates) > 0:

            [cache[update].mark_upgrade() for update in updates]

            splash = SplashScreen()
            hbox2 = splash.getElementById('hbox2')
            hbox2.pack_start(apt_progress, True, True, 0)
            apt_progress.show()
            splash.show()

            button = splash.getElementById('label1')
            button.set_label(_('Upgrading ...'))

            apt_progress.show_terminal(True)

            upgrade = True

            try:
                cache.commit(apt_progress.acquire, apt_progress.install)
            except FetchFailedException, e:
                upgrade = False
                self.logger.debug("Exception happened: %s", e)
                showerror_gtk(_("Unable to connect to software repository"),
                              self.window.getMainWindow())
            except Exception, e:
                upgrade = False
                self.logger.debug("Exception happened: %s", e)
                showerror_gtk(_("An error occurred during the upgrade"),
                              self.window.getMainWindow())

            splash.hide()
            while Gtk.events_pending():
                Gtk.main_iteration()

            # GEMs installation for chef-client new version
            if cache['chef'].marked_upgrade:

                thread = threading.Thread(target=self.splash_threading,
                                          args=(_('Installing gems ...'), ))
                thread.daemon = True
                thread.start()

                gemUtil = GemUtil()
                for gem_name in REQUIRED_GEMS:
                    if not gemUtil.is_gem_intalled(gem_name):
                        if not gemUtil.install_gem(gem_name):
                            upgrade = False
                            self.logger.debug(
                                "GemUtil: An error while installing {} : %s",
                                gem_name)
                            showerror_gtk(
                                _("An error ocurred while installing gems"),
                                self.window.getMainWindow())
                            break

                GObject.idle_add(Gtk.main_quit)
                thread.join()

            if upgrade:
                showinfo_gtk(
                    _("GECOS Config Assistant has been udpated. Restarting ..."
                      ), self.window.getMainWindow())
                args = sys.argv[:]
                os.execvp(sys.executable, [sys.executable] + args)