def setup_i18n(): import locale locale.setlocale(locale.LC_ALL, "") from univention.lib.i18n import Translation translation = Translation('univention-system-setup-scripts') translation.set_language() return translation.translate
def __init__(self, locale=None): i18n = Translation('univention-management-console') try: i18n.set_language(locale or 'C') except (I18N_Error, AttributeError, TypeError): i18n.set_language('C') self._ = i18n.translate self.pam = self.init()
def setup_i18n(): import locale locale.setlocale(locale.LC_ALL, locale.getdefaultlocale()) language = locale.getdefaultlocale()[0] from univention.lib.i18n import Translation translation = Translation('univention-system-setup-scripts') translation.set_language(language) return translation.translate
# # You should have received a copy of the GNU Affero General Public # License with the Debian GNU/Linux or Univention distribution in file # /usr/share/common-licenses/AGPL-3; if not, see # <http://www.gnu.org/licenses/>. import sys import re from datetime import datetime # translation: manually set_language() because # for some reason, the default locale is not used by default import locale from univention.lib.i18n import Translation translation = Translation('univention-system-setup-scripts') default_locale = locale.getdefaultlocale() translation.set_language(default_locale[0]) _ = translation.translate locale.setlocale(locale.LC_ALL, default_locale) # needed for external translation (e.g. apt) import univention.config_registry from util import PATH_SETUP_SCRIPTS, PATH_PROFILE ucr = univention.config_registry.ConfigRegistry() class SetupScript(object): '''Baseclass for all Python-based Setup-Scripts. Script lifecycle: __init__() -> up() run() -> (inner_run() -> commit_ucr()) -> down()
class Processor( signals.Provider ): """Implements a proxy and command handler. It handles all internal UMCP commands and passes the commands for a module to the subprocess. :param str username: name of the user who authenticated for this session :param str password: password of the user """ def __init__( self, username, password ): global users_module self.__username = username self.__password = password self.__user_dn = None signals.Provider.__init__( self ) self.core_i18n = Translation( 'univention-management-console' ) self.i18n = I18N_Manager() self.i18n[ 'umc-core' ] = I18N() # stores the module processes [ modulename ] = <> self.__processes = {} self.__killtimer = {} lo = ldap.open( ucr[ 'ldap/server/name' ], int( ucr.get( 'ldap/server/port', 7389 ) ) ) try: # get LDAP connection with machine account self.lo, self.po = udm_uldap.getMachineConnection( ldap_master = False ) # get the LDAP DN of the authorized user ldap_dn = self.lo.searchDn( '(&(uid=%s)(objectClass=posixAccount))' % self.__username ) if ldap_dn: self.__user_dn = ldap_dn[ 0 ] CORE.info( 'The LDAP DN for user %s is %s' % ( self.__username, self.__user_dn ) ) else: CORE.info( 'The LDAP DN for user %s could not be found' % self.__username ) # initiate the users/user UDM module udm_modules.update() users_module = udm_modules.get('users/user') udm_modules.init(self.lo, self.po, users_module) except ( ldap.LDAPError, IOError ) as e: # problems connection to LDAP server or the server is not joined (machine.secret is missing) CORE.warn('An error occurred connecting to the LDAP server: %s' % e) self.lo = None users_module = None except udm_errors.base as e: # UDM error, user module coule not be initiated CORE.warn('An error occurred intializing the UDM users/user module: %s' % e) users_module = None # read the ACLs self.acls = LDAP_ACLs( self.lo, self.__username, ucr[ 'ldap/base' ] ) self.__command_list = moduleManager.permitted_commands( ucr[ 'hostname' ], self.acls ) self.signal_new( 'response' ) def shutdown( self ): """Instructs the module process to shutdown""" CORE.info( 'The session is shutting down. Sending UMC modules an EXIT request (%d processes)' % len( self.__processes ) ) for module_name in self.__processes: CORE.info( 'Ask module %s to shutdown gracefully' % module_name ) req = Request( 'EXIT', arguments = [ module_name, 'internal' ] ) self.__processes[ module_name ].request( req ) def __del__( self ): CORE.process( 'Processor: dying' ) for process in self.__processes.values(): del process def get_module_name( self, command ): """Returns the name of the module that provides the given command :param str command: the command name """ return moduleManager.module_providing( self.__comand_list, command ) def request( self, msg ): """Handles an incoming UMCP request and passes the requests to specific handler functions. :param Request msg: UMCP request """ if msg.command == 'EXIT': self.handle_request_exit( msg ) elif msg.command == 'GET': self.handle_request_get( msg ) elif msg.command == 'SET': self.handle_request_set( msg ) elif msg.command == 'VERSION': self.handle_request_version( msg ) elif msg.command == 'COMMAND': self.handle_request_command( msg ) elif msg.command == 'UPLOAD': self.handle_request_upload( msg ) elif msg.command in ( 'STATUS', 'CANCEL', 'CLOSE' ): self.handle_request_unknown( msg ) else: self.handle_request_unknown( msg ) def _purge_child(self, module_name): if module_name in self.__processes: CORE.process( 'module %s is still running - purging module out of memory' % module_name) pid = self.__processes[ module_name ].pid() os.kill(pid, 9) return False def handle_request_exit( self, msg ): """Handles an EXIT request. If the request does not have an argument that contains a valid name of a running UMC module instance the request is returned as a bad request. If the request is valid it is passed on to the module process. Additionally a timer of 3000 milliseconds is started. After that amount of time the module process MUST have been exited itself. If not the UMC server will kill the module process. :param Request msg: UMCP request """ if len( msg.arguments ) < 1: return self.handle_request_unknown( msg ) module_name = msg.arguments[ 0 ] if module_name: if module_name in self.__processes: self.__processes[ module_name ].request( msg ) CORE.info( 'Ask module %s to shutdown gracefully' % module_name ) # added timer to kill away module after 3000ms cb = notifier.Callback( self._purge_child, module_name ) self.__killtimer[ module_name ] = notifier.timer_add( 3000, cb ) else: CORE.info( 'Got EXIT request for a non-existing module %s' % module_name ) def handle_request_version( self, msg ): """Handles a VERSION request by returning the version of the UMC server's protocol version. :param Request msg: UMCP request """ res = Response( msg ) res.status = SUCCESS # Ok res.body[ 'version' ] = VERSION self.signal_emit( 'response', res ) def _get_user_obj(self): try: # make sure that the UDM users/user module could be initiated if not users_module: raise udm_errors.base('UDM module users/user could not be initiated') # open an LDAP connection with the user password and credentials lo = udm_uldap.access(host = ucr.get('ldap/server/name'), base = ucr.get('ldap/base'), port = int(ucr.get('ldap/server/port', '7389')), binddn = self.__user_dn, bindpw = self.__password, follow_referral=True) # try to open the user object userObj = udm_objects.get(users_module, None, lo, self.po, self.__user_dn) if not userObj: raise udm_errors.noObject() userObj.open() return userObj except udm_errors.noObject as e: CORE.warn('Failed to open UDM user object for user %s' % (self.__username)) except (udm_errors.base, ldap.LDAPError) as e: CORE.warn('Failed to open UDM user object %s: %s' % (self.__user_dn, e)) return None def handle_request_get( self, msg ): """Handles a GET request. The following possible variants are supported: modules/list Returns a list of all available UMC modules within the current session categories/list Returns a list of all known categories user/preferences Returns the user preferences as a dict. :param Request msg: UMCP request """ res = Response( msg ) if 'modules/list' in msg.arguments: modules = [] for id, module in self.__command_list.items(): # check for translation if module.flavors: for flavor in module.flavors: translationId = flavor.translationId if not translationId: translationId = id modules.append( { 'id' : id, 'flavor' : flavor.id, 'name' : self.i18n._( flavor.name, translationId ), 'description' : self.i18n._( flavor.description, translationId ), 'icon' : flavor.icon, 'categories' : module.categories, 'priority' : flavor.priority } ) else: modules.append( { 'id' : id, 'name' : self.i18n._( module.name, id ), 'description' : self.i18n._( module.description, id ), 'icon' : module.icon, 'categories' : module.categories, 'priority' : module.priority } ) res.body[ 'modules' ] = modules _ucr_dict = dict( ucr.items() ) categories = [] for catID, category in categoryManager.items(): categories.append( { 'id' : catID, 'name' : self.i18n._( category.name, category.domain ).format( **_ucr_dict ), 'priority' : category.priority } ) res.body[ 'categories' ] = categories CORE.info( 'Modules: %s' % modules ) CORE.info( 'Categories: %s' % str( res.body[ 'categories' ] ) ) res.status = SUCCESS # Ok elif 'categories/list' in msg.arguments: res.body[ 'categories' ] = categoryManager.all() res.status = SUCCESS # Ok elif 'user/preferences' in msg.arguments: # fallback is an empty dict res.body['preferences'] = {} # query user's UMC properties userObj = self._get_user_obj() if userObj: res.body['preferences'] = dict(userObj.info.get('umcProperty', [])) res.status = SUCCESS else: res.status = BAD_REQUEST_INVALID_OPTS else: res.status = BAD_REQUEST_INVALID_ARGS self.signal_emit( 'response', res ) def handle_request_set( self, msg ): """Handles a SET request. No argument may be given. The variables that should be set are passed via the request options. Currently the only variable that may be set is the locale. If any unknown variable is given the the request is invalidated. :param Request msg: UMCP request """ res = Response( msg ) if len( msg.arguments ): res.status = BAD_REQUEST_INVALID_ARGS res.message = status_description( res.status ) self.signal_emit( 'response', res ) return res.status = SUCCESS if not isinstance(msg.options, dict): raise InvalidOptionsError for key, value in msg.options.items(): if key == 'locale': try: self.core_i18n.set_language( value ) CORE.info( 'Setting locale: %s' % value ) self.i18n.set_locale( value ) except I18N_Error, e: res.status = BAD_REQUEST_UNAVAILABLE_LOCALE res.message = status_description( res.status ) CORE.warn( 'Setting locale to specified locale failed (%s)' % value ) CORE.warn( 'Falling back to C' ) self.core_i18n.set_language( 'C' ) self.i18n.set_locale( 'C' ) break elif key == 'user' and isinstance(value, dict) and 'preferences' in value: # try to open the user object userObj = self._get_user_obj() if not userObj: res.status = BAD_REQUEST_INVALID_OPTS res.message = status_description( res.status ) break try: # make sure we got a dict prefs = value['preferences'] if not isinstance(prefs, dict): raise ValueError('user preferences are not a dict: %s' % prefs) # iterate over all given user preferences newPrefs = [] for prefKey, prefValue in prefs.iteritems(): if not isinstance(prefKey, basestring): raise ValueError('user preferences keys needs to be strings: %s' % prefKey) # we can put strings directly into the dict if isinstance(prefValue, basestring): newPrefs.append((prefKey, prefValue)) else: newPrefs.append((prefKey, json.dumps(prefValue))) if newPrefs: # eliminate double entries newPrefs = dict(userObj.info.get('umcProperty', []) + newPrefs) # apply changes userObj.info['umcProperty'] = newPrefs.items() userObj.modify() except (ValueError, udm_errors.base) as e: CORE.warn('Could not set given option: %s' % e) res.status = BAD_REQUEST_INVALID_OPTS res.message = status_description( res.status ) break else:
# # You should have received a copy of the GNU Affero General Public # License with the Debian GNU/Linux or Univention distribution in file # /usr/share/common-licenses/AGPL-3; if not, see # <http://www.gnu.org/licenses/>. import sys import re from datetime import datetime # translation: manually set_language() because # for some reason, the default locale is not used by default import locale from univention.lib.i18n import Translation translation = Translation('univention-system-setup-scripts') default_locale = locale.getdefaultlocale() translation.set_language(default_locale[0]) _ = translation.translate locale.setlocale(locale.LC_ALL, default_locale) # needed for external translation (e.g. apt) import univention.config_registry from util import PATH_SETUP_SCRIPTS, PATH_PROFILE ucr = univention.config_registry.ConfigRegistry() class SetupScript(object): '''Baseclass for all Python-based Setup-Scripts. Script lifecycle: __init__() -> up() run() -> (inner_run() -> commit_ucr()) -> down() up(), (inner_run() -> commit_ucr), and down() and encapsulated by