Example #1
0
def topic_add():
    board = request.form.get('board', '')
    title = request.form.get('title', '')
    content = request.form.get('content', '')
    if not content:
        content = title
    s_len = SUMMARY_LENGTH
    summary = (content[:s_len-3] + '...') if len(content) > s_len else content
    try:
        validate_board(_('Board Name'), board)
        validate(_('Title'), title, max=64, not_empty=True)
    except ValidationError as err:
        return validation_err_response(err)
    uid = session.get('uid')
    if not uid:
        return json_response((249, _('Not signed in.')) )

    result_ban_global = forum.ban_check(uid)
    if result_ban_global[0] != 0:
        return json_response(result_ban_global)
    result_ban_local = forum.ban_check(uid, board)
    if result_ban_local[0] != 0:
        return json_response(result_ban_local)

    if result_ban_global[2]['banned'] or result_ban_local[2]['banned']:
        return json_response((252, _('You are being banned.')) )

    return json_response(forum.topic_add(board, title, uid, summary, content))
Example #2
0
	def TriggerEvent(self, function, args):
		"""Triggers an event for the plugins. Since events and notifications
		are precisely the same except for how n+ responds to them, both can be
		triggered by this function."""
		hotpotato = args
		for module, plugin in self.enabled_plugins.items():
			try:
				func = eval("plugin.PLUGIN." + function)
				ret = func(*hotpotato)
				if ret != None and type(ret) != tupletype:
					if ret == returncode['zap']:
						return None
					elif ret == returncode['break']:
						return hotpotato
					elif ret == returncode['pass']:
						pass
					else:
						log.add(_("Plugin %(module) returned something weird, '%(value)', ignoring") % {'module':module, 'value':ret})
				if ret != None:
					hotpotato = ret
			except:
				log.add(_("Plugin %(module)s failed with error %(errortype)s: %(error)s.\nTrace: %(trace)s\nProblem area:%(area)s") %
					{'module':module,
					'errortype':sys.exc_info()[0],
					'error':sys.exc_info()[1],
					'trace':''.join(format_list(extract_stack())),
					'area':''.join(format_list(extract_tb(sys.exc_info()[2])))})
		return hotpotato
Example #3
0
def admin_add(uid):
    board = request.args.get('board', '')
    level = request.args.get('level', '1')
    try:
        validate_board(_('Board Name'), board)
        validate_uint(_('Administrator Level'), level)
    except ValidationError as err:
        return validation_err_response(err)

    operator = session.get('uid')
    if not operator:
        return json_response((254, _('Permission denied.')) )

    if level == '0':
        check = forum.admin_check(operator)
        if check[0] != 0:
            return json_response(check)
        if check[2]['admin']:
            return json_response(forum.admin_add(uid, board, int(level)) )
        else:
            return json_response((254, _('Permission denied.')) )
    else:
        check_site = forum.admin_check(operator)
        check_board = forum.admin_check(operator, board)
        if check_site[0] != 0:
            return json_response(check_site)
        if check_board[0] != 0:
            return json_response(check_board)
        if (
                check_site[2]['admin']
                or (check_board[2]['admin'] and check_board[2]['level'] == 0)
            ):
            return json_response(forum.admin_add(uid, board, int(level)) )
        else:
            return json_response((254, _('Permission denied.')) )
Example #4
0
    def set_name(self,name):
        """
        Set the name.  If the name is a MAC or IP, and the first MAC and/or IP is not defined, go ahead
        and fill that value in.  
        """

        if self.name not in ["",None] and self.parent not in ["",None] and self.name == self.parent:
            raise CX(_("self parentage is weird"))
        if not isinstance(name, basestring):
            raise CX(_("name must be a string"))
        for x in name:
            if not x.isalnum() and not x in [ "_", "-", ".", ":", "+" ] :
                raise CX(_("invalid characters in name: %s") % x)

        # Stuff here defaults to eth0. Yes, it's ugly and hardcoded, but so was
        # the default interface behaviour that's now removed. ;)
        # --Jasper Capel
        if utils.is_mac(name):
           intf = self.__get_interface("eth0")
           if intf["mac_address"] == "":
               intf["mac_address"] = name
        elif utils.is_ip(name):
           intf = self.__get_interface("eth0")
           if intf["ip_address"] == "":
               intf["ip_address"] = name
        self.name = name 

        return True
Example #5
0
def notification(n_type):
    pn = request.args.get('pn', '1')
    COUNT = 15 # TODO: user settings
    try:
        validate(_('Notification Type'), n_type, in_list=['replyme', 'atme'])
        validate_id(_('Page Number'), pn)
    except ValidationError as err:
        return validation_err_response(err)
    uid = session.get('uid')
    if uid:
        if n_type == 'replyme':
            result = forum.reply_get(uid, int(pn), COUNT)
        elif n_type == 'atme':
            result = forum.at_get(uid, int(pn), COUNT)
        if result[0] != 0:
            return err_response(result)
        else:
            return render_template(
                'notification.html',
                n_type = n_type,
                pn = int(pn),
                count = COUNT,
                data = result[2]
            )
    else:
        return err_response((249, _('Not signed in.')) )
Example #6
0
 def scp_it(self,from_path,to_path):
     from_path = "%s:%s" % (self.host, from_path)
     cmd = "scp %s %s" % (from_path, to_path)
     print _("- %s") % cmd
     rc = sub_process.call(cmd, shell=True, close_fds=True)
     if rc !=0:
         raise CX(_("scp failed"))
Example #7
0
 def check_service(self, status, which, notes=""):
     if notes != "":
         notes = " (NOTE: %s)" % notes
     rc = 0
     if self.checked_dist == "redhat" or self.checked_dist == "suse":
         if os.path.exists("/etc/rc.d/init.d/%s" % which):
             rc = utils.subprocess_call(self.logger,"/sbin/service %s status > /dev/null 2>/dev/null" % which, shell=True)
         if rc != 0:
             status.append(_("service %s is not running%s") % (which,notes))
             return False
     elif self.checked_dist in ["debian", "ubuntu"]:
         # we still use /etc/init.d
         if os.path.exists("/etc/init.d/%s" % which):
             rc = utils.subprocess_call(self.logger,"/etc/init.d/%s status /dev/null 2>/dev/null" % which, shell=True)
         if rc != 0:
             status.append(_("service %s is not running%s") % which,notes)
             return False
     elif self.checked_dist == "ubuntu":
         if os.path.exists("/etc/init/%s.conf" % which):
             rc = utils.subprocess_call(self.logger,"status %s > /dev/null 2>&1" % which, shell=True)
         if rc != 0:
             status.append(_("service %s is not running%s") % (which,notes))
     else:
         status.append(_("Unknown distribution type, cannot check for running service %s" % which))
         return False
     return True
Example #8
0
   def check_dhcpd_conf(self,status):
       """
       NOTE: this code only applies if cobbler is *NOT* set to generate
       a dhcp.conf file

       Check that dhcpd *appears* to be configured for pxe booting.
       We can't assure file correctness.  Since a cobbler user might
       have dhcp on another server, it's okay if it's not there and/or
       not configured correctly according to automated scans.
       """
       if not (self.settings.manage_dhcp == 0):
           return

       if os.path.exists(self.settings.dhcpd_conf):
           match_next = False
           match_file = False
           f = open(self.settings.dhcpd_conf)
           for line in f.readlines():
               if line.find("next-server") != -1:
                   match_next = True
               if line.find("filename") != -1:
                   match_file = True
           if not match_next:
              status.append(_("expecting next-server entry in %(file)s") % { "file" : self.settings.dhcpd_conf })
           if not match_file:
              status.append(_("missing file: %(file)s") % { "file" : self.settings.dhcpd_conf })
       else:
           status.append(_("missing file: %(file)s") % { "file" : self.settings.dhcpd_conf })
Example #9
0
   def configure_tree_location(self, distro, importer):

       """
       Once a distribution is identified, find the part of the distribution
       that has the URL in it that we want to use for kickstarting the
       distribution, and create a ksmeta variable $tree that contains this.
       """

       base = importer.get_rootdir()

       if self.network_root is None:
           if distro.breed == "debian" or distro.breed == "ubuntu":
               tree = "http://@@http_server@@/cblr/repo_mirror/%s" % (distro.name)
           else:
               dest_link = os.path.join(self.settings.webdir, "links", distro.name)
               # create the links directory only if we are mirroring because with
               # SELinux Apache can't symlink to NFS (without some doing)
               if not os.path.exists(dest_link):
                   try:
                       os.symlink(base, dest_link)
                   except:
                       # this shouldn't happen but I've seen it ... debug ...
                       print _("- symlink creation failed: %(base)s, %(dest)s") % { "base" : base, "dest" : dest_link }
               # how we set the tree depends on whether an explicit network_root was specified
               tree = "http://@@http_server@@/cblr/links/%s" % (distro.name)
           importer.set_install_tree( distro, tree)
       else:
           # where we assign the kickstart source is relative to our current directory
           # and the input start directory in the crawl.  We find the path segments
           # between and tack them on the network source path to find the explicit
           # network path to the distro that Anaconda can digest.  
           tail = self.path_tail(self.path, base)
           tree = self.network_root[:-1] + tail
           importer.set_install_tree( distro, tree)
Example #10
0
    def set_parent(self,parent_name):
        """
        Instead of a --distro, set the parent of this object to another profile
        and use the values from the parent instead of this one where the values
        for this profile aren't filled in, and blend them together where they
        are hashes.  Basically this enables profile inheritance.  To use this,
        the object MUST have been constructed with is_subobject=True or the
        default values for everything will be screwed up and this will likely NOT
        work.  So, API users -- make sure you pass is_subobject=True into the
        constructor when using this.
        """

        old_parent = self.get_parent()
        if isinstance(old_parent, item.Item):
            old_parent.children.pop(self.name, 'pass')
        if parent_name is None or parent_name == '':
           self.parent = ''
           return True
        if parent_name == self.name:
           # check must be done in two places as set_parent could be called before/after
           # set_name...
           raise CX(_("self parentage is weird"))
        found = self.config.profiles().find(name=parent_name)
        if found is None:
           raise CX(_("profile %s not found, inheritance not possible") % parent_name)
        self.parent = parent_name       
        self.depth = found.depth + 1
        parent = self.get_parent()
        if isinstance(parent, item.Item):
            parent.children[self.name] = self
        return True
Example #11
0
    def fielder(self, structure, fields_list):
        """
        Return data from a subset of fields of some item
        """
        item = {}

        for field in fields_list:

            if field in structure.keys():
                item[field] = structure[field]

            # exception for fields within fields (depth=1 for now)
            elif self.array_re.search(field):
                internal = self.array_re.search(field)
                item[internal.group(2)] = structure[internal.group(1)][internal.group(2)]
            # exception for systems which could have > 1 interface
            elif "interfaces" in structure.keys():
                for device in structure["interfaces"].keys():
                    if field in structure["interfaces"][device]:
                        item[field] = device + ": " + structure["interfaces"][device][field]
                    else:
                        raise CX(_('The field "%s" does not exist, see cobbler dumpvars for available fields.') % field)
            else:
                raise CX(_('The field "%s" does not exist, see cobbler dumpvars for available fields.') % field)
        return item
Example #12
0
    def auto_add_repos(self):
        """
        Import any repos this server knows about and mirror them.
        Credit: Seth Vidal.
        """
        self.log("auto_add_repos")
        try:
            import yum
        except:
            raise CX(_("yum is not installed"))

        version = yum.__version__
        (a,b,c) = version.split(".")
        version = a* 1000 + b*100 + c
        if version < 324:
            raise CX(_("need yum > 3.2.4 to proceed"))

        base = yum.YumBase()
        base.doRepoSetup()
        repos = base.repos.listEnabled()
        if len(repos) == 0:
            raise CX(_("no repos enabled/available -- giving up."))

        for repo in repos:
            url = repo.urls[0]
            cobbler_repo = self.new_repo()
            auto_name = repo.name.replace(" ","")
            # FIXME: probably doesn't work for yum-rhn-plugin ATM
            cobbler_repo.set_mirror(url)
            cobbler_repo.set_name(auto_name)
            print "auto adding: %s (%s)" % (auto_name, url)
            self._config.repos().add(cobbler_repo,save=True)

        # run cobbler reposync to apply changes
        return True 
Example #13
0
    def mailPassword(self, forgotten_userid, REQUEST):
        """ Email a forgotten password to a member.

        o Raise an exception if user ID is not found.
        """
        membership = getToolByName(self, 'portal_membership')
        member = membership.getMemberById(forgotten_userid)

        if member is None:
            raise ValueError(_('The username you entered could not be '
                               'found.'))

        # assert that we can actually get an email address, otherwise
        # the template will be made with a blank To:, this is bad
        if not member.getProperty('email'):
            raise ValueError(_('That user does not have an email address.'))

        check, msg = _checkEmail(member.getProperty('email'))
        if not check:
            raise ValueError, msg

        # Rather than have the template try to use the mailhost, we will
        # render the message ourselves and send it from here (where we
        # don't need to worry about 'UseMailHost' permissions).
        mail_text = self.mail_password_template( self
                                               , REQUEST
                                               , member=member
                                               , password=member.getPassword()
                                               )

        host = self.MailHost
        host.send( mail_text )

        return self.mail_password_response( self, REQUEST )
Example #14
0
    def doActionFor(self, ob, action, wf_id=None, *args, **kw):

        """ Execute the given workflow action for the object.

        o Invoked by user interface code.

        o Allows the user to request a workflow action.

        o The workflow object must perform its own security checks.
        """
        wfs = self.getWorkflowsFor(ob)
        if wfs is None:
            wfs = ()
        if wf_id is None:
            if not wfs:
                raise WorkflowException(_(u'No workflows found.'))
            found = 0
            for wf in wfs:
                if wf.isActionSupported(ob, action, **kw):
                    found = 1
                    break
            if not found:
                msg = _(u"No workflow provides the '${action_id}' action.",
                        mapping={'action_id': action})
                raise WorkflowException(msg)
        else:
            wf = self.getWorkflowById(wf_id)
            if wf is None:
                raise WorkflowException(
                    _(u'Requested workflow definition not found.'))
        return self._invokeWithNotification(
            wfs, ob, action, wf.doActionFor, (ob, action) + args, kw)
Example #15
0
 def getInfoFor(self, ob, name, default=_marker, wf_id=None, *args, **kw):
     """ Get the given bit of workflow information for the object.
     """
     if wf_id is None:
         wfs = self.getWorkflowsFor(ob)
         if wfs is None:
             if default is _marker:
                 raise WorkflowException(_(u'No workflows found.'))
             else:
                 return default
         found = 0
         for wf in wfs:
             if wf.isInfoSupported(ob, name):
                 found = 1
                 break
         if not found:
             if default is _marker:
                 msg = _(u"No workflow provides '${name}' information.",
                         mapping={'name': name})
                 raise WorkflowException(msg)
             else:
                 return default
     else:
         wf = self.getWorkflowById(wf_id)
         if wf is None:
             if default is _marker:
                 raise WorkflowException(
                     _(u'Requested workflow definition not found.'))
             else:
                 return default
     res = wf.getInfoFor(ob, name, default, *args, **kw)
     if res is _marker:
         msg = _(u'Could not get info: ${name}', mapping={'name': name})
         raise WorkflowException(msg)
     return res
    def on_build_installer_clicked(self):
        # First of all, check that it's valid.
        package = self.window.package
        package.validate()

        if len(package.errors):
            QtGui.QMessageBox.critical(self,
                    _('PortableApps.com Development Toolkit'),
                    _('There are errors in the package. You must fix them before making a release.'),
                    QtGui.QMessageBox.Ok)
            self.window.set_page('test')
            self.window.page_test.go_to_tab('validate')
            return
        elif len(package.warnings):
            answer = QtGui.QMessageBox.warning(self,
                    _('PortableApps.com Development Toolkit'),
                    _('There are warnings in the package validation. You should fix them before making a release.'),
                    QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ignore)
            if answer == QtGui.QMessageBox.Cancel:
                self.window.set_page('test')
                self.window.page_test.go_to_tab('validate')
                return

        if self.window.page_options.find_installer_path():
            # If not found, user told about it in find_installer_path

            self._installer_thread = InstallerThread(self)
            self._installer_thread.update_contents_async.connect(self.update_contents_async)
            self._installer_thread.start()
Example #17
0
    def __get_interface(self, name):

        if name == "" and len(self.interfaces.keys()) == 0:
            raise CX(_("No interfaces defined. Please use --interface <interface_name>"))
        elif name == "" and len(self.interfaces.keys()) == 1:
            name = self.interfaces.keys()[0]
        elif name == "" and len(self.interfaces.keys()) > 1:
            raise CX(_("Multiple interfaces defined. Please use --interface <interface_name>"))
        elif name not in self.interfaces:
            self.interfaces[name] = {
                "mac_address": "",
                "mtu": "",
                "ip_address": "",
                "dhcp_tag": "",
                "netmask": "",
                "if_gateway": "",
                "virt_bridge": "",
                "static": False,
                "interface_type": "",
                "interface_master": "",
                "bonding_opts": "",
                "bridge_opts": "",
                "management": False,
                "dns_name": "",
                "static_routes": [],
                "ipv6_address": "",
                "ipv6_secondaries": [],
                "ipv6_mtu": "",
                "ipv6_static_routes": [],
                "ipv6_default_gateway": "",
                "cnames": [],
            }

        return self.interfaces[name]
def page1(ctx):
    field_username = "******"
    place_username = _("Username")

    field_password = "******"
    place_password = _("Password")
    with DIV.container_fluid as out:
        with DIV.row_fluid:
            with FORM(id="login_form",align="center"):
                H1(ctx.get('company','Company'),align="center")
                BR()
                with FIELDSET:
                    with DIV.span6.offset3:
                        with DIV.row_fluid:
                            with DIV.span5.offset1.pull_left:
                                LABEL(place_username,for_=field_username)
                                with DIV.control_group:
                                    with DIV.controls:
                                        with DIV.input_prepend:
                                            with SPAN.add_on:
                                                I("",class_="icon-user")
                                            INPUT(type='text',placeholder=place_username,id=field_username)
                            with DIV.span5.pull_right:
                                LABEL(place_password,for_=field_password)
                                with DIV.control_group:
                                    with DIV.controls:
                                        INPUT(type='password',placeholder=place_password,id=field_password)
                        with DIV.row_fluid:
                            with DIV(align="center").span4.offset4:
                                BUTTON(_("Login"),type="button",align="center",class_="btn btn-success btn-large")

                with DIV(align="center"):
                    H3(_("Don't you have an account?"))
                    A(_("Register"),type="button",href="#", class_="btn btn-primary btn-large")
Example #19
0
def index():
    #+==========================
    #: forms series summary
    records = []
    projects = db.Project.get_all()
    ref_date = _get_ref_date()
    wkdate_bounds = get_weekdate_bounds

    for p in projects:
        record = _(code=p.code, name=p.name)
        captures = db.Capture.get_by_project(p.code, paginate=False)
        if captures.count():
            summary = stats.series_purity_summary(captures, ref_date)
            record.update(summary)
        records.append(record)

    #+==========================
    #: today activity summary
    activity_summary, activity_stats = [], _()
    captures = list(db.Capture.get_by_date(ref_date.isoformat(), paginate=False))
    if captures:
        activity_stats = stats.day_activity_stats(captures, ref_date)
        activity_breakdown = stats.day_activity_breakdown(captures, ref_date)
        for record in activity_breakdown:
            activity_summary.append(_(record))

    return {
        'is_front': True, 
        'title': 'Capture Summary',
        'records': records,
        'activity_records': activity_summary,
        'activity_stats': activity_stats,
        'report_ref_date': ref_date,
        'report_weekdate_bounds': wkdate_bounds,
    }
Example #20
0
 def freeNodes(self,relpath):
     #causing problems
     """Free up nodes corresponding to file, if possible"""
     bnode = self.basenodes.get(relpath,None)
     if bnode is None:
         print "Missing node for %s" % relpath
         return
     bnode.unlinkNode()
     bnode.freeNode()
     del self.basenodes[relpath]
     pkgid = self.pkg_ids.get(relpath,None)
     if pkgid is None:
         print _("No pkgid found for: %s") % relpath
         return None
     del self.pkg_ids[relpath]
     dups = self.pkgrefs.get(pkgid)
     dups.remove(relpath)
     if len(dups):
         #still referenced
         return
     del self.pkgrefs[pkgid]
     for nodes in self.filesnodes, self.othernodes:
         node = nodes.get(pkgid)
         if node is not None:
             node.unlinkNode()
             node.freeNode()
             del nodes[pkgid]
Example #21
0
def project_view(project_code):
    project = db.Project.get_by_code(project_code)
    xrecords, urecords = [], []

    for f in project.xforms:
        xform = db.XForm.get_by_id(f)
        record = _(id=xform.id_string, title=xform.title)
        captures = db.Capture.get_by_form(f, False)
        if captures.count():
            summary = stats.activity_summary(captures)
            record.update(summary)
        xrecords.append(record)

    for f in project.uforms:
        uform = db.XForm.get_by_id(f)
        record = _(id=uform.id_string, title=uform.title)
        updates = db.Update.get_by_form(f, False)
        if updates.count():
            summary = stats.activity_summary(updates)
            record.update(summary)
        urecords.append(record)

    return {
        'title': 'Project: %s' % project.name,
        'project': project,
        'xrecords': xrecords,
        'urecords': urecords
    }
Example #22
0
 def doActionFor(self, ob, action, wf_id=None, *args, **kw):
     """ Perform the given workflow action on 'ob'.
     """
     wfs = self.getWorkflowsFor(ob)
     if wfs is None:
         wfs = ()
     if wf_id is None:
         if not wfs:
             raise WorkflowException(_(u'No workflows found.'))
         found = 0
         for wf in wfs:
             if wf.isActionSupported(ob, action, **kw):
                 found = 1
                 break
         if not found:
             msg = _(u"No workflow provides the '${action_id}' action.",
                     mapping={'action_id': action})
             raise WorkflowException(msg)
     else:
         wf = self.getWorkflowById(wf_id)
         if wf is None:
             raise WorkflowException(
                 _(u'Requested workflow definition not found.'))
     return self._invokeWithNotification(
         wfs, ob, action, wf.doActionFor, (ob, action) + args, kw)
Example #23
0
def disable_translations(bot, update):
    """Handler for the /disable_translations command"""
    chat = update.message.chat
    user = update.message.from_user
    games = gm.chatid_games.get(chat.id)

    if not games:
        send_async(bot, chat.id,
                   text=_("There is no running game in this chat."))
        return

    game = games[-1]

    if game.owner.id == user.id:
        game.translate = False
        send_async(bot, chat.id, text=_("Disabled multi-translations. "
                                        "Enable them again with "
                                        "/enable_translations"))
        return

    else:
        send_async(bot, chat.id,
                   text=_("Only the game creator ({name}) can do that")
                   .format(name=game.owner.first_name),
                   reply_to_message_id=update.message.message_id)
        return
Example #24
0
	def needConfig(self):
		errorlevel = 0
		try:
			for i in self.sections.keys():
				for j in self.sections[i].keys():
			# 		print self.sections[i][j]
					if type(self.sections[i][j]) not in [type(None), type("")]:
						continue
					if self.sections[i][j] is None or self.sections[i][j] == '' and i not in ("userinfo", "ui", "ticker", "players", "language") and j not in ("incompletedir", "autoreply", 'afterfinish', 'afterfolder', 'geoblockcc', 'downloadregexp', "language"):
						# Repair options set to None with defaults
						if self.sections[i][j] is None and self.defaults[i][j] is not None:
							self.sections[i][j] = self.defaults[i][j]
							self.frame.logMessage(_("Config option reset to default: Section: %(section)s, Option: %(option)s, to: %(default)s") % {'section':i, 'option':j, 'default':self.sections[i][j]})
							if errorlevel == 0:
								errorlevel = 1
						else:
							if errorlevel < 2:
								self.frame.logMessage(_("You need to configure your settings (Server, Username, Password, Download Directory) before connecting..."))
								errorlevel = 2
							
							self.frame.logMessage(_("Config option unset: Section: %(section)s, Option: %(option)s") % {'section':i, 'option':j})
							self.frame.settingswindow.InvalidSettings(i, j)
			
		except Exception, error:
			message = _("Config error: %s") % error
			self.frame.logMessage(message)
			if errorlevel < 3:
				errorlevel = 3
Example #25
0
def select_game(bot, update):
    """Handler for callback queries to select the current game"""

    chat_id = int(update.callback_query.data)
    user_id = update.callback_query.from_user.id
    players = gm.userid_players[user_id]
    for player in players:
        if player.game.chat.id == chat_id:
            gm.userid_current[user_id] = player
            break
    else:
        bot.sendMessage(update.callback_query.message.chat_id,
                        text=_("Game not found."),
                        timeout=TIMEOUT)
        return

    back = [[InlineKeyboardButton(text=_("Back to last group"),
                                  switch_inline_query='')]]

    bot.answerCallbackQuery(update.callback_query.id,
                            text=_("Please switch to the group you selected!"),
                            show_alert=False,
                            timeout=TIMEOUT)

    bot.editMessageText(chat_id=update.callback_query.message.chat_id,
                        message_id=update.callback_query.message.message_id,
                        text=_("Selected group: {group}\n"
                               "<b>Make sure that you switch to the correct "
                               "group!</b>").format(
                            group=gm.userid_current[user_id].game.chat.title),
                        reply_markup=InlineKeyboardMarkup(back),
                        parse_mode=ParseMode.HTML,
                        timeout=TIMEOUT)
Example #26
0
def leave_game(bot, update):
    """Handler for the /leave command"""
    chat = update.message.chat
    user = update.message.from_user

    player = gm.player_for_user_in_chat(user, chat)

    if player is None:
        send_async(bot, chat.id, text=_("You are not playing in a game in "
                                        "this group."),
                   reply_to_message_id=update.message.message_id)
        return

    game = player.game
    user = update.message.from_user

    try:
        gm.leave_game(user, chat)

    except NoGameInChatError:
        send_async(bot, chat.id, text=_("You are not playing in a game in "
                                        "this group."),
                   reply_to_message_id=update.message.message_id)

    except NotEnoughPlayersError:
        gm.end_game(chat, user)
        send_async(bot, chat.id, text=__("Game ended!", game.translate))

    else:
        send_async(bot, chat.id,
                   text=__("Okay. Next Player: {name}", game.translate).format(
                       name=display_name(game.current_player.user)),
                   reply_to_message_id=update.message.message_id)
Example #27
0
def user_password_reset_get_token(username):
    try:
        validate_username(_('Username'), username)
    except ValidationError as err:
        return validation_err_response(err)

    result_getuid = forum.user_get_uid(username)
    if result_getuid[0] != 0:
        return json_response(result_getuid)
    uid = result_getuid[2]['uid']

    result = forum.user_password_reset_get_token(uid)
    if result[0] != 0:
        return json_response(result)
    data = result[2]

    try:
        send_mail(
            subject = _('Password Reset - %s') % config['site_name'],
            addr_from = EMAIL_ADDRESS,
            addr_to = data['mail'],
            content = (
                _('Verification Code: %s (Valid in 90 minutes)')
                % data['token']
            )
        )
        del data['mail']
        del data['token']
        return json_response(result)
    except Exception as err:
        return json_response((253, _('Failed to send mail: %s') % str(err)) )
Example #28
0
    def set_network(self,network,interface):
        """
        Add an interface to a network object.  If network is empty,
        clear the network.
        """
        intf = self.__get_interface(interface)

        if network == intf['network']:
            # setting the existing network is no-op
            return

        if intf['network'] != '':
            # we are currently subscribed to a network, so to join
            # a different one we need to leave this one first.
            net = self.config.networks().find(name=intf['network'])
            if net == None:
                raise CX(_("Network %s does not exist" % network))
            net.unsubscribe_system(self.name, interface)
            intf['network'] = ''

        if network != '': # Join
            net  = self.config.networks().find(name=network)
            if net == None:
                raise CX(_("Network %s does not exist" % network))
            net.subscribe_system(self.name, interface, intf['ip_address'])
            intf['network'] = network

        # FIXME figure out why the network collection doesn't
        # serialize itself out to disk without this
        self.config.serialize()
Example #29
0
    def check_yum(self, status):
        if self.checked_dist in ["debian", "ubuntu"]:
            return

        if not os.path.exists("/usr/bin/createrepo"):
            status.append(
                _(
                    "createrepo package is not installed, needed for cobbler import and cobbler reposync, install createrepo?"
                )
            )
        if not os.path.exists("/usr/bin/reposync"):
            status.append(_("reposync is not installed, need for cobbler reposync, install/upgrade yum-utils?"))
        if not os.path.exists("/usr/bin/yumdownloader"):
            status.append(
                _(
                    "yumdownloader is not installed, needed for cobbler repo add with --rpm-list parameter, install/upgrade yum-utils?"
                )
            )
        if self.settings.reposync_flags.find("-l"):
            if self.checked_dist == "redhat" or self.checked_dist == "suse":
                yum_utils_ver = utils.subprocess_get(
                    self.logger, "/usr/bin/rpmquery --queryformat=%{VERSION} yum-utils", shell=True
                )
                if yum_utils_ver < "1.1.17":
                    status.append(
                        _("yum-utils need to be at least version 1.1.17 for reposync -l, current version is %s")
                        % yum_utils_ver
                    )
Example #30
0
def close_game(bot, update):
    """Handler for the /close command"""
    chat = update.message.chat
    user = update.message.from_user
    games = gm.chatid_games.get(chat.id)

    if not games:
        send_async(bot, chat.id,
                   text=_("There is no running game in this chat."))
        return

    game = games[-1]

    if game.owner.id == user.id:
        game.open = False
        send_async(bot, chat.id, text=_("Closed the lobby. "
                                        "No more players can join this game."))
        return

    else:
        send_async(bot, chat.id,
                   text=_("Only the game creator ({name}) can do that.")
                   .format(name=game.owner.first_name),
                   reply_to_message_id=update.message.message_id)
        return
Example #31
0
def format_date(timestamp, detailed=False):
    # behaviour of this function must be consistent with the front-end
    if detailed:
        return datetime.datetime.fromtimestamp(int(timestamp)).isoformat(' ')
    date = datetime.datetime.fromtimestamp(timestamp)
    delta = round((datetime.datetime.now() - date).total_seconds())
    if delta < 60:
        return _('just now')
    elif delta < 3600:
        minutes = delta / 60
        if minutes == 1:
            return _('a minute ago')
        else:
            return _('%d minutes ago') % minutes
    elif delta < 86400:
        hours = delta / 3600
        if hours == 1:
            return _('an hour ago')
        else:
            return _('%d hours ago') % hours
    # 604800 = 86400*7
    elif delta < 604800:
        days = delta / 86400
        if days == 1:
            return _('a day ago')
        else:
            return _('%d days ago') % days
    # 2629746 = 86400*(31+28+97/400+31+30+31+30+31+31+30+31+30+31)/12
    elif delta < 2629746:
        weeks = delta / 604800
        if weeks == 1:
            return _('a week ago')
        else:
            return _('%d weeks ago') % weeks
    # 31556952 = 86400*(365+97/400)
    elif delta < 31556952:
        months = delta / 2629746
        if months == 1:
            return _('a month ago')
        else:
            return _('%d months ago') % months
    else:
        years = delta / 31556952
        if years == 1:
            return _('a year ago')
        else:
            return _('%d years ago') % years
Example #32
0
    def write_dhcp_file(self):
        """
        DHCP files are written when manage_dhcp is set in
        /var/lib/cobbler/settings.
        """

        template_file = "/etc/cobbler/dhcp.template"
        blender_cache = {}

        try:
            f2 = open(template_file, "r")
        except:
            raise CX(_("error reading template: %s") % template_file)
        template_data = ""
        template_data = f2.read()
        f2.close()

        # use a simple counter for generating generic names where a hostname
        # is not available
        counter = 0

        # we used to just loop through each system, but now we must loop
        # through each network interface of each system.
        dhcp_tags = {"default": {}}
        elilo = "/elilo-3.6-ia64.efi"
        yaboot = "/yaboot-1.3.14"

        for system in self.systems:
            if not system.is_management_supported(cidr_ok=False):
                continue

            profile = system.get_conceptual_parent()
            distro = profile.get_conceptual_parent()

            # if distro is None then the profile is really an image
            # record!

            for (name, interface) in system.interfaces.iteritems():

                # this is really not a per-interface setting
                # but we do this to make the templates work
                # without upgrade
                interface["gateway"] = system.gateway

                mac = interface["mac_address"]
                if interface["interface_type"] in ("slave", "bond_slave",
                                                   "bridge_slave",
                                                   "bonded_bridge_slave"):
                    if interface["interface_master"] not in system.interfaces:
                        # Can't write DHCP entry; master interface does not
                        # exist
                        continue
                    ip = system.interfaces[
                        interface["interface_master"]]["ip_address"]
                    interface["ip_address"] = ip
                    host = system.interfaces[
                        interface["interface_master"]]["dns_name"]
                else:
                    ip = interface["ip_address"]
                    host = interface["dns_name"]

                if distro is not None:
                    interface["distro"] = distro.to_datastruct()

                if mac is None or mac == "":
                    # can't write a DHCP entry for this system
                    continue

                counter = counter + 1

                # the label the entry after the hostname if possible
                if host is not None and host != "":
                    if name != "eth0":
                        interface["name"] = "%s_%s" % (host, name)
                    else:
                        interface["name"] = "%s" % (host)
                else:
                    interface["name"] = "generic%d" % counter

                # add references to the system, profile, and distro
                # for use in the template
                if blender_cache.has_key(system.name):
                    blended_system = blender_cache[system.name]
                else:
                    blended_system = utils.blender(self.api, False, system)
                    blender_cache[system.name] = blended_system

                interface["next_server"] = blended_system["server"]
                interface["netboot_enabled"] = blended_system[
                    "netboot_enabled"]
                interface["hostname"] = blended_system["hostname"]
                interface["owner"] = blended_system["name"]
                interface["enable_gpxe"] = blended_system["enable_gpxe"]

                if not interface["netboot_enabled"] and interface['static']:
                    continue

                interface["filename"] = "/pxelinux.0"
                # can't use pxelinux.0 anymore
                if distro is not None:
                    if distro.arch == "ia64":
                        interface["filename"] = elilo
                    elif distro.arch.startswith("ppc"):
                        interface["filename"] = yaboot

                dhcp_tag = interface["dhcp_tag"]
                if dhcp_tag == "":
                    dhcp_tag = "default"

                if not dhcp_tags.has_key(dhcp_tag):
                    dhcp_tags[dhcp_tag] = {mac: interface}
                else:
                    dhcp_tags[dhcp_tag][mac] = interface

        # we are now done with the looping through each interface of each system
        metadata = {
            "date": time.asctime(time.gmtime()),
            "cobbler_server": self.settings.server,
            "next_server": self.settings.next_server,
            "elilo": elilo,
            "yaboot": yaboot,
            "dhcp_tags": dhcp_tags
        }

        if self.logger is not None:
            self.logger.info("generating %s" % self.settings_file)
        self.templar.render(template_data, metadata, self.settings_file, None)
Example #33
0
    def __write_zone_files(self):
        """
        Write out the forward and reverse zone files for all configured zones
        """
        default_template_file = "/etc/cobbler/zone.template"
        cobbler_server = self.settings.server
        # this could be a config option too
        serial_filename = "/var/lib/cobbler/bind_serial"
        # need a counter for new bind format
        serial = time.strftime("%Y%m%d00")
        try:
            serialfd = open(serial_filename, "r")
            old_serial = serialfd.readline()
            # same date
            if serial[0:8] == old_serial[0:8]:
                if int(old_serial[8:10]) < 99:
                    serial = "%s%.2i" % (serial[0:8], int(old_serial[8:10]) + 1)
            else:
                pass
            serialfd.close()
        except:
            pass

        serialfd = open(serial_filename, "w")
        serialfd.write(serial)
        serialfd.close()

        forward = self.__forward_zones()
        reverse = self.__reverse_zones()

        try:
            f2 = open(default_template_file, "r")
        except:
            raise CX(_("error reading template from file: %s") % default_template_file)
        default_template_data = ""
        default_template_data = f2.read()
        f2.close()

        zonefileprefix = self.settings.bind_chroot_path + self.zonefile_base

        for (zone, hosts) in forward.iteritems():
            metadata = {
                'cobbler_server': cobbler_server,
                'serial': serial,
                'zonetype': 'forward',
                'cname_record': '',
                'host_record': ''
            }

            if ":" in zone:
                long_zone = (self.__expand_IPv6(zone + '::1'))[:19]
                tokens = list(re.sub(':', '', long_zone))
                tokens.reverse()
                zone_origin = '.'.join(tokens) + '.ip6.arpa.'
            else:
                zone_origin = ''
            # grab zone-specific template if it exists
            try:
                fd = open('/etc/cobbler/zone_templates/%s' % zone)
                # If this is an IPv6 zone, set the origin to the zone for this
                # template
                if zone_origin:
                    template_data = "\$ORIGIN " + zone_origin + "\n" + fd.read()
                else:
                    template_data = fd.read()
                fd.close()
            except:
                # If this is an IPv6 zone, set the origin to the zone for this
                # template
                if zone_origin:
                    template_data = "\$ORIGIN " + zone_origin + "\n" + default_template_data
                else:
                    template_data = default_template_data

            metadata['cname_record'] = self.__pretty_print_cname_records(hosts)
            metadata['host_record'] = self.__pretty_print_host_records(hosts)


            zonefilename = zonefileprefix + zone
            if self.logger is not None:
                self.logger.info("generating (forward) %s" % zonefilename)
            self.templar.render(template_data, metadata, zonefilename, None)

        for (zone, hosts) in reverse.iteritems():
            metadata = {
                'cobbler_server': cobbler_server,
                'serial': serial,
                'zonetype': 'reverse',
                'cname_record': '',
                'host_record': ''
            }

            # grab zone-specific template if it exists
            try:
                fd = open('/etc/cobbler/zone_templates/%s' % zone)
                template_data = fd.read()
                fd.close()
            except:
                template_data = default_template_data

            metadata['cname_record'] = self.__pretty_print_cname_records(hosts)
            metadata['host_record'] = self.__pretty_print_host_records(hosts, rectype='PTR')


            zonefilename = zonefileprefix + zone
            if self.logger is not None:
                self.logger.info("generating (reverse) %s" % zonefilename)
            self.templar.render(template_data, metadata, zonefilename, None)
Example #34
0
    def __write_secondary_conf(self):
        """
        Write out the secondary.conf secondary config file from the template.
        """
        settings_file = self.settings.bind_chroot_path + '/etc/secondary.conf'
        template_file = "/etc/cobbler/secondary.template"
        # forward_zones = self.settings.manage_forward_zones
        # reverse_zones = self.settings.manage_reverse_zones

        metadata = {'forward_zones': self.__forward_zones().keys(),
                    'reverse_zones': [],
                    'zone_include': ''}

        for zone in metadata['forward_zones']:
                txt = """
zone "%(zone)s." {
    type slave;
    masters {
        %(master)s;
    };
    file "data/%(zone)s";
};
""" % {'zone': zone, 'master': self.settings.bind_master}
                metadata['zone_include'] = metadata['zone_include'] + txt

        for zone in self.__reverse_zones().keys():
            # IPv6 zones are : delimited
            if ":" in zone:
                # if IPv6, assume xxxx:xxxx:xxxx:xxxx for the zone
                #                 0123456789012345678
                long_zone = (self.__expand_IPv6(zone + '::1'))[:19]
                tokens = list(re.sub(':', '', long_zone))
                tokens.reverse()
                arpa = '.'.join(tokens) + '.ip6.arpa'
            else:
                # IPv4 zones split by '.'
                tokens = zone.split('.')
                tokens.reverse()
                arpa = '.'.join(tokens) + '.in-addr.arpa'
                #
            metadata['reverse_zones'].append((zone, arpa))
            txt = """
zone "%(arpa)s." {
    type slave;
    masters {
        %(master)s;
    };
    file "data/%(zone)s";
};
""" % {'arpa': arpa, 'zone': zone, 'master': self.settings.bind_master}
            metadata['zone_include'] = metadata['zone_include'] + txt

        try:
            f2 = open(template_file, "r")
        except:
            raise CX(_("error reading template from file: %s") % template_file)
        template_data = ""
        template_data = f2.read()
        f2.close()

        if self.logger is not None:
            self.logger.info("generating %s" % settings_file)
        self.templar.render(template_data, metadata, settings_file, None)
Example #35
0
 def set_ipv6_default_gateway(self,address,interface):
     intf = self.__get_interface(interface)
     if address == "" or utils.is_ip(address):
        intf["ipv6_default_gateway"] = address.strip()
        return True
     raise CX(_("invalid format for IPv6 IP address (%s)") % address)
Example #36
0
    def add(self,
            ref,
            save=False,
            with_copy=False,
            with_triggers=True,
            with_sync=True,
            quick_pxe_update=False,
            check_for_duplicate_names=False,
            check_for_duplicate_netinfo=False,
            logger=None):
        """
        Add an object to the collection, if it's valid.  Returns True
        if the object was added to the collection.  Returns False if the
        object specified by ref deems itself invalid (and therefore
        won't be added to the collection).

        with_copy is a bit of a misnomer, but lots of internal add operations
        can run with "with_copy" as False. True means a real final commit, as if
        entered from the command line (or basically, by a user).

        With with_copy as False, the particular add call might just be being run
        during deserialization, in which case extra semantics around the add don't really apply.
        So, in that case, don't run any triggers and don't deal with any actual files.
        """
        if ref is None or ref.name is None:
            return False

        try:
            ref.check_if_valid()
        except CX:
            return False

        if ref.uid == '':
            ref.uid = self.config.generate_uid()

        if save is True:
            now = time.time()
            if ref.ctime == 0:
                ref.ctime = now
            ref.mtime = now

        if self.lite_sync is None:
            self.lite_sync = action_litesync.BootLiteSync(self.config,
                                                          logger=logger)

        # migration path for old API parameter that I've renamed.
        if with_copy and not save:
            save = with_copy

        if not save:
            # for people that aren't quite aware of the API
            # if not saving the object, you can't run these features
            with_triggers = False
            with_sync = False

        # Avoid adding objects to the collection
        # if an object of the same/ip/mac already exists.
        self.__duplication_checks(ref, check_for_duplicate_names,
                                  check_for_duplicate_netinfo)

        if ref.COLLECTION_TYPE != self.collection_type():
            raise CX(_("API error: storing wrong data type in collection"))

        if not save:
            # don't need to run triggers, so add it already ...
            self.lock.acquire()
            try:
                self.listing[ref.name.lower()] = ref
            finally:
                self.lock.release()

        # perform filesystem operations
        if save:
            # failure of a pre trigger will prevent the object from being added
            if with_triggers:
                utils.run_triggers(
                    self.api, ref, "/var/lib/cobbler/triggers/add/%s/pre/*" %
                    self.collection_type(), [], logger)
            self.lock.acquire()
            try:
                self.listing[ref.name.lower()] = ref
            finally:
                self.lock.release()

            # save just this item if possible, if not, save
            # the whole collection
            self.config.serialize_item(self, ref)

            if with_sync:
                if isinstance(ref, item_system.System):
                    # we don't need openvz containers to be network bootable
                    if ref.virt_type == "openvz":
                        ref.netboot_enabled = False
                    self.lite_sync.add_single_system(ref.name)
                elif isinstance(ref, item_profile.Profile):
                    # we don't need openvz containers to be network bootable
                    if ref.virt_type == "openvz":
                        ref.enable_menu = 0
                    self.lite_sync.add_single_profile(ref.name)
                elif isinstance(ref, item_distro.Distro):
                    self.lite_sync.add_single_distro(ref.name)
                elif isinstance(ref, item_image.Image):
                    self.lite_sync.add_single_image(ref.name)
                elif isinstance(ref, item_repo.Repo):
                    pass
                elif isinstance(ref, item_mgmtclass.Mgmtclass):
                    pass
                elif isinstance(ref, item_package.Package):
                    pass
                elif isinstance(ref, item_file.File):
                    pass
                else:
                    print _("Internal error. Object type not recognized: %s"
                            ) % type(ref)
            if not with_sync and quick_pxe_update:
                if isinstance(ref, item_system.System):
                    self.lite_sync.update_system_netboot_status(ref.name)

            # save the tree, so if neccessary, scripts can examine it.
            if with_triggers:
                utils.run_triggers(self.api, ref,
                                   "/var/lib/cobbler/triggers/change/*", [],
                                   logger)
                utils.run_triggers(
                    self.api, ref, "/var/lib/cobbler/triggers/add/%s/post/*" %
                    self.collection_type(), [], logger)

        # update children cache in parent object
        parent = ref.get_parent()
        if parent is not None:
            parent.children[ref.name] = ref

        return True
Example #37
0
def news(bot, update):
    """Handler for the /news command"""
    send_async(bot,
               update.message.chat_id,
               text=_("All news here: https://telegram.me/unobotupdates"),
               disable_web_page_preview=True)
Example #38
0
 def on_title(self, instance, value):
     self.text = _(value)
Example #39
0
 def check_for_default_password(self, status):
     default_pass = self.settings.default_password_crypted
     if default_pass == "$1$mF86/UHC$WvcIcX2t6crBz2onWxyac.":
         status.append(_("The default password used by the sample templates for newly installed machines (default_password_crypted in /etc/cobbler/settings) is still set to 'cobbler' and should be changed, try: \"openssl passwd -1 -salt 'random-phrase-here' 'your-password-here'\" to generate new one"))
Example #40
0
 def check_iptables(self, status):
     if os.path.exists("/etc/rc.d/init.d/iptables"):
         rc = utils.subprocess_call(self.logger, "/sbin/service iptables status >/dev/null 2>/dev/null", shell=True)
         if rc == 0:
             status.append(_("since iptables may be running, ensure 69, 80/443, and %(xmlrpc)s are unblocked") % {"xmlrpc": self.settings.xmlrpc_port})
Example #41
0
def compute_y():
    return {'y': pow(g, _('x'), p)}
Example #42
0
    def __duplication_checks(self, ref, check_for_duplicate_names,
                             check_for_duplicate_netinfo):
        """
        Prevents adding objects with the same name.
        Prevents adding or editing to provide the same IP, or MAC.
        Enforcement is based on whether the API caller requests it.
        """
        # always protect against duplicate names
        if check_for_duplicate_names:
            match = None
            if isinstance(ref, item_system.System):
                match = self.api.find_system(ref.name)
            elif isinstance(ref, item_profile.Profile):
                match = self.api.find_profile(ref.name)
            elif isinstance(ref, item_distro.Distro):
                match = self.api.find_distro(ref.name)
            elif isinstance(ref, item_repo.Repo):
                match = self.api.find_repo(ref.name)
            elif isinstance(ref, item_image.Image):
                match = self.api.find_image(ref.name)
            elif isinstance(ref, item_mgmtclass.Mgmtclass):
                match = self.api.find_mgmtclass(ref.name)
            elif isinstance(ref, item_package.Package):
                match = self.api.find_package(ref.name)
            elif isinstance(ref, item_file.File):
                match = self.api.find_file(ref.name)
            else:
                raise CX("internal error, unknown object type")

            if match:
                raise CX(
                    _("An object already exists with that name.  Try 'edit'?"))

        # the duplicate mac/ip checks can be disabled.
        if not check_for_duplicate_netinfo:
            return

        if isinstance(ref, item_system.System):
            for (name, intf) in ref.interfaces.iteritems():
                match_ip = []
                match_mac = []
                match_hosts = []
                input_mac = intf["mac_address"]
                input_ip = intf["ip_address"]
                input_dns = intf["dns_name"]
                if not self.api.settings(
                ).allow_duplicate_macs and input_mac is not None and input_mac != "":
                    match_mac = self.api.find_system(mac_address=input_mac,
                                                     return_list=True)
                if not self.api.settings(
                ).allow_duplicate_ips and input_ip is not None and input_ip != "":
                    match_ip = self.api.find_system(ip_address=input_ip,
                                                    return_list=True)
                # it's ok to conflict with your own net info.

                if not self.api.settings(
                ).allow_duplicate_hostnames and input_dns is not None and input_dns != "":
                    match_hosts = self.api.find_system(dns_name=input_dns,
                                                       return_list=True)

                for x in match_mac:
                    if x.name != ref.name:
                        raise CX(
                            _("Can't save system %s. The MAC address (%s) is already used by system %s (%s)"
                              ) %
                            (ref.name, intf["mac_address"], x.name, name))
                for x in match_ip:
                    if x.name != ref.name:
                        raise CX(
                            _("Can't save system %s. The IP address (%s) is already used by system %s (%s)"
                              ) % (ref.name, intf["ip_address"], x.name, name))
                for x in match_hosts:
                    if x.name != ref.name:
                        raise CX(
                            _("Can't save system %s.  The dns name (%s) is already used by system %s (%s)"
                              ) % (ref.name, intf["dns_name"], x.name, name))
Example #43
0
class System(item.Item):

    TYPE_NAME = _("system")
    COLLECTION_TYPE = "system"

    def get_fields(self):
        return FIELDS

    def make_clone(self):
        ds = self.to_datastruct()
        cloned = System(self.config)
        cloned.from_datastruct(ds)
        return cloned

    def delete_interface(self,name):
        """
        Used to remove an interface.
        """
        if self.interfaces.has_key(name) and len(self.interfaces) > 1:
            del self.interfaces[name]
        else:
            if not self.interfaces.has_key(name):
                # no interface here to delete
                pass
            else:
                raise CX(_("At least one interface needs to be defined."))

        return True

    def rename_interface(self,names):
        """
        Used to rename an interface.
        """
        (name,newname) = names
        if not self.interfaces.has_key(name):
            raise CX(_("Interface %s does not exist" % name))
        if self.interfaces.has_key(newname):
            raise CX(_("Interface %s already exists" % newname))
        else:
            self.interfaces[newname] = self.interfaces[name]
            del self.interfaces[name]

        return True

    def __get_interface(self,name):

        if name == "" and len(self.interfaces.keys()) == 0:
            raise CX(_("No interfaces defined. Please use --interface <interface_name>"))
        elif name == "" and len(self.interfaces.keys()) == 1:
            name = self.interfaces.keys()[0]
        elif name == "" and len(self.interfaces.keys()) > 1:
            raise CX(_("Multiple interfaces defined. Please use --interface <interface_name>"))
        elif not self.interfaces.has_key(name):
            self.interfaces[name] = {
                "mac_address"          : "",
                "mtu"                  : "",
                "ip_address"           : "",
                "dhcp_tag"             : "",
                "subnet"               : "", # deprecated
                "netmask"              : "",
                "if_gateway"           : "",
                "virt_bridge"          : "",
                "static"               : False,
                "interface_type"       : "",
                "interface_master"     : "",
                "bonding"              : "", # deprecated
                "bonding_master"       : "", # deprecated
                "bonding_opts"         : "",
                "bridge_opts"          : "",
                "management"           : False,
                "dns_name"             : "",
                "static_routes"        : [],
                "ipv6_address"         : "",
                "ipv6_secondaries"     : [],
                "ipv6_mtu"             : "",
                "ipv6_static_routes"   : [],
                "ipv6_default_gateway" : "",
                "cnames"               : [],
            }

        return self.interfaces[name]


    def from_datastruct(self,seed_data):
        # FIXME: most definitely doesn't grok interfaces yet.
        return utils.from_datastruct_from_fields(self,seed_data,FIELDS)

    def get_parent(self):
        """
        Return object next highest up the tree.
        """
        if (self.parent is None or self.parent == '') and self.profile:
            return self.config.profiles().find(name=self.profile)
        elif (self.parent is None or self.parent == '') and self.image:
            return self.config.images().find(name=self.image)
        else:
            return self.config.systems().find(name=self.parent)

    def set_name(self,name):
        """
        Set the name.  If the name is a MAC or IP, and the first MAC and/or IP is not defined, go ahead
        and fill that value in.  
        """

        if self.name not in ["",None] and self.parent not in ["",None] and self.name == self.parent:
            raise CX(_("self parentage is weird"))
        if not isinstance(name, basestring):
            raise CX(_("name must be a string"))
        for x in name:
            if not x.isalnum() and not x in [ "_", "-", ".", ":", "+" ] :
                raise CX(_("invalid characters in name: %s") % x)

        # Stuff here defaults to eth0. Yes, it's ugly and hardcoded, but so was
        # the default interface behaviour that's now removed. ;)
        # --Jasper Capel
        if utils.is_mac(name):
           intf = self.__get_interface("eth0")
           if intf["mac_address"] == "":
               intf["mac_address"] = name
        elif utils.is_ip(name):
           intf = self.__get_interface("eth0")
           if intf["ip_address"] == "":
               intf["ip_address"] = name
        self.name = name 

        return True
    
    def set_redhat_management_key(self,key):
        return utils.set_redhat_management_key(self,key)

    def set_redhat_management_server(self,server):
        return utils.set_redhat_management_server(self,server)

    def set_server(self,server):
        """
        If a system can't reach the boot server at the value configured in settings
        because it doesn't have the same name on it's subnet this is there for an override.
        """
        if server is None or server == "":
            server = "<<inherit>>"
        self.server = server
        return True

    def set_proxy(self,proxy):
        if proxy is None or proxy == "":
            proxy = "<<inherit>>"
        self.proxy = proxy
        return True

    def get_mac_address(self,interface):
        """
        Get the mac address, which may be implicit in the object name or explicit with --mac-address.
        Use the explicit location first.
        """

        intf = self.__get_interface(interface)

        if intf["mac_address"] != "":
            return intf["mac_address"].strip()
        else:
            return None
        
    def get_ip_address(self,interface):
        """
        Get the IP address, which may be implicit in the object name or explict with --ip-address.
        Use the explicit location first.
        """

        intf = self.__get_interface(interface)

        if intf["ip_address"] != "": 
            return intf["ip_address"].strip()
        else:
            return ""

    def is_management_supported(self,cidr_ok=True):
        """
        Can only add system PXE records if a MAC or IP address is available, else it's a koan
        only record.  Actually Itanium goes beyond all this and needs the IP all of the time
        though this is enforced elsewhere (action_sync.py).
        """
        if self.name == "default":
           return True
        for (name,x) in self.interfaces.iteritems():
            mac = x.get("mac_address",None)
            ip  = x.get("ip_address",None)
            if ip is not None and not cidr_ok and ip.find("/") != -1:
                # ip is in CIDR notation
                return False
            if mac is not None or ip is not None:
                # has ip and/or mac
                return True
        return False

    def set_dhcp_tag(self,dhcp_tag,interface):
        intf = self.__get_interface(interface)
        intf["dhcp_tag"] = dhcp_tag
        return True

    def set_dns_name(self,dns_name,interface):
        intf = self.__get_interface(interface)
        # FIXME: move duplicate supression code to the object validation
        # functions to take a harder line on supression?
        if dns_name != "" and not str(self.config._settings.allow_duplicate_hostnames).lower() in [ "1", "y", "yes"]:
           matched = self.config.api.find_items("system", {"dns_name" : dns_name})
           for x in matched:
               if x.name != self.name:
                   raise CX("dns-name duplicated: %s" % dns_name)
               

        intf["dns_name"] = dns_name
        return True
 
    def set_cnames(self,cnames,interface):
        intf = self.__get_interface(interface)
        data = utils.input_string_or_list(cnames)
        intf["cnames"] = data        
        return True
    
    def set_static_routes(self,routes,interface):
        intf = self.__get_interface(interface)
        data = utils.input_string_or_list(routes)
        intf["static_routes"] = data
        return True

    def set_hostname(self,hostname):
        if hostname is None:
           hostname = ""
        self.hostname = hostname
        return True

    def set_status(self,status):
        self.status = status
        return True

    def set_static(self,truthiness,interface):
        intf = self.__get_interface(interface)
        intf["static"] = utils.input_boolean(truthiness)
        return True

    def set_management(self,truthiness,interface):
        intf = self.__get_interface(interface)
        intf["management"] = utils.input_boolean(truthiness)
        return True

    def set_ip_address(self,address,interface):
        """
        Assign a IP or hostname in DHCP when this MAC boots.
        Only works if manage_dhcp is set in /etc/cobbler/settings
        """
        intf = self.__get_interface(interface)

        # FIXME: move duplicate supression code to the object validation
        # functions to take a harder line on supression?
        if address != "" and not str(self.config._settings.allow_duplicate_ips).lower() in [ "1", "y", "yes"]:
           matched = self.config.api.find_items("system", {"ip_address" : address})
           for x in matched:
               if x.name != self.name:
                   raise CX("IP address duplicated: %s" % address)


        if address == "" or utils.is_ip(address):
           intf["ip_address"] = address.strip()
           return True
        raise CX(_("invalid format for IP address (%s)") % address)

    def set_mac_address(self,address,interface):
        if address == "random":
           address = utils.get_random_mac(self.config.api)

        # FIXME: move duplicate supression code to the object validation
        # functions to take a harder line on supression?
        if address != "" and not str(self.config._settings.allow_duplicate_macs).lower() in [ "1", "y", "yes"]:
           matched = self.config.api.find_items("system", {"mac_address" : address})
           for x in matched:
               if x.name != self.name:
                   raise CX("MAC address duplicated: %s" % address)

        intf = self.__get_interface(interface)
        if address == "" or utils.is_mac(address):
           intf["mac_address"] = address.strip()
           return True
        raise CX(_("invalid format for MAC address (%s)" % address))


    def set_gateway(self,gateway):
        if gateway is None:
           gateway = ""
        if utils.is_ip(gateway) or gateway == "":
           self.gateway = gateway
        else:
           raise CX(_("invalid format for gateway IP address (%s)") % gateway)
        return True
 
    def set_name_servers(self,data):
        if data == "<<inherit>>":
           data = []
        data = utils.input_string_or_list(data)
        self.name_servers = data
        return True

    def set_name_servers_search(self,data):
        if data == "<<inherit>>":
           data = []
        data = utils.input_string_or_list(data)
        self.name_servers_search = data
        return True

    def set_netmask(self,netmask,interface):
        intf = self.__get_interface(interface)
        intf["netmask"] = netmask
        return True
    
    def set_if_gateway(self,gateway,interface):
        intf = self.__get_interface(interface)
        if gateway == "" or utils.is_ip(gateway):
            intf["if_gateway"] = gateway
            return True
        raise CX(_("invalid gateway: %s" % gateway))

    def set_virt_bridge(self,bridge,interface):
        if bridge == "":
            bridge = self.settings.default_virt_bridge
        intf = self.__get_interface(interface)
        intf["virt_bridge"] = bridge
        return True

    def set_interface_type(self,type,interface):
        # master and slave are deprecated, and will
        # be assumed to mean bonding slave/master
        interface_types = ["bridge","bridge_slave","bond","bond_slave","bonded_bridge_slave","master","slave","na",""]
        if type not in interface_types:
            raise CX(_("interface type value must be one of: %s or blank" % interface_types.join(",")))
        if type == "na":
            type = ""
        elif type == "master":
            type = "bond"
        elif type == "slave":
            type = "bond_slave"
        intf = self.__get_interface(interface)
        intf["interface_type"] = type
        return True

    def set_interface_master(self,interface_master,interface):
        intf = self.__get_interface(interface)
        intf["interface_master"] = interface_master
        return True

    def set_bonding_opts(self,bonding_opts,interface):
        intf = self.__get_interface(interface)
        intf["bonding_opts"] = bonding_opts
        return True

    def set_bridge_opts(self,bridge_opts,interface):
        intf = self.__get_interface(interface)
        intf["bridge_opts"] = bridge_opts
        return True

    def set_ipv6_autoconfiguration(self,truthiness):
        self.ipv6_autoconfiguration = utils.input_boolean(truthiness)
        return True

    def set_ipv6_default_device(self,interface_name):
        if interface_name is None:
           interface_name = ""
        self.ipv6_default_device = interface_name
        return True

    def set_ipv6_address(self,address,interface):
        """
        Assign a IP or hostname in DHCP when this MAC boots.
        Only works if manage_dhcp is set in /etc/cobbler/settings
        """
        intf = self.__get_interface(interface)
        if address == "" or utils.is_ip(address):
           intf["ipv6_address"] = address.strip()
           return True
        raise CX(_("invalid format for IPv6 IP address (%s)") % address)

    def set_ipv6_secondaries(self,addresses,interface):
        intf = self.__get_interface(interface)
        data = utils.input_string_or_list(addresses)
        secondaries = []
        for address in data:
           if address == "" or utils.is_ip(address):
               secondaries.append(address)
           else:
               raise CX(_("invalid format for IPv6 IP address (%s)") % address)

        intf["ipv6_secondaries"] = secondaries
        return True

    def set_ipv6_default_gateway(self,address,interface):
        intf = self.__get_interface(interface)
        if address == "" or utils.is_ip(address):
           intf["ipv6_default_gateway"] = address.strip()
           return True
        raise CX(_("invalid format for IPv6 IP address (%s)") % address)

    def set_ipv6_static_routes(self,routes,interface):
        intf = self.__get_interface(interface)
        data = utils.input_string_or_list(routes)
        intf["ipv6_static_routes"] = data
        return True

    def set_ipv6_mtu(self,mtu,interface):
        intf = self.__get_interface(interface)
        intf["ipv6_mtu"] = mtu
        return True

    def set_mtu(self,mtu,interface):
        intf = self.__get_interface(interface)
        intf["mtu"] = mtu
        return True

    def set_enable_gpxe(self,enable_gpxe):
        """
        Sets whether or not the system will use gPXE for booting.
        """
        self.enable_gpxe = utils.input_boolean(enable_gpxe)
        return True

    def set_profile(self,profile_name):
        """
        Set the system to use a certain named profile.  The profile
        must have already been loaded into the Profiles collection.
        """
        old_parent = self.get_parent()
        if profile_name in [ "delete", "None", "~", ""] or profile_name is None:
            self.profile = ""
            if isinstance(old_parent, item.Item):
                old_parent.children.pop(self.name, 'pass')
            return True

        self.image = "" # mutual exclusion rule

        p = self.config.profiles().find(name=profile_name)
        if p is not None:
            self.profile = profile_name
            self.depth = p.depth + 1 # subprofiles have varying depths.
            if isinstance(old_parent, item.Item):
                old_parent.children.pop(self.name, 'pass')
            new_parent = self.get_parent()
            if isinstance(new_parent, item.Item):
                new_parent.children[self.name] = self
            return True
        raise CX(_("invalid profile name: %s") % profile_name)

    def set_image(self,image_name):
        """
        Set the system to use a certain named image.  Works like set_profile
        but cannot be used at the same time.  It's one or the other.
        """
        old_parent = self.get_parent()
        if image_name in [ "delete", "None", "~", ""] or image_name is None:
            self.image = ""
            if isinstance(old_parent, item.Item):
                old_parent.children.pop(self.name, 'pass')
            return True

        self.profile = "" # mutual exclusion rule

        img = self.config.images().find(name=image_name)

        if img is not None:
            self.image = image_name
            self.depth = img.depth + 1
            if isinstance(old_parent, item.Item):
                old_parent.children.pop(self.name, 'pass')
            new_parent = self.get_parent()
            if isinstance(new_parent, item.Item):
                new_parent.children[self.name] = self
            return True
        raise CX(_("invalid image name (%s)") % image_name)

    def set_virt_cpus(self,num):
        return utils.set_virt_cpus(self,num)

    def set_virt_file_size(self,num):
        return utils.set_virt_file_size(self,num)

    def set_virt_disk_driver(self,driver):
        return utils.set_virt_disk_driver(self,driver)
 
    def set_virt_auto_boot(self,num):
        return utils.set_virt_auto_boot(self,num)

    def set_virt_pxe_boot(self,num):
        return utils.set_virt_pxe_boot(self,num)

    def set_virt_ram(self,num):
        return utils.set_virt_ram(self,num)

    def set_virt_type(self,vtype):
        return utils.set_virt_type(self,vtype)

    def set_virt_path(self,path):
        return utils.set_virt_path(self,path,for_system=True)

    def set_netboot_enabled(self,netboot_enabled):
        """
        If true, allows per-system PXE files to be generated on sync (or add).  If false,
        these files are not generated, thus eliminating the potential for an infinite install
        loop when systems are set to PXE boot first in the boot order.  In general, users
        who are PXE booting first in the boot order won't create system definitions, so this
        feature primarily comes into play for programmatic users of the API, who want to
        initially create a system with netboot enabled and then disable it after the system installs, 
        as triggered by some action in kickstart %post.   For this reason, this option is not
        surfaced in the CLI, output, or documentation (yet).

        Use of this option does not affect the ability to use PXE menus.  If an admin has machines 
        set up to PXE only after local boot fails, this option isn't even relevant.
        """
        self.netboot_enabled = utils.input_boolean(netboot_enabled)
        return True

    def set_kickstart(self,kickstart):
        """
        Sets the kickstart.  This must be a NFS, HTTP, or FTP URL.
        Or filesystem path. Minor checking of the URL is performed here.

        NOTE -- usage of the --kickstart parameter in the profile
        is STRONGLY encouraged.  This is only for exception cases
        where a user already has kickstarts made for each system
        and can't leverage templating.  Profiles provide an important
        abstraction layer -- assigning systems to defined and repeatable 
        roles.
        """
        if kickstart is None or kickstart in [ "", "delete", "<<inherit>>" ]:
            self.kickstart = "<<inherit>>"
            return True
        kickstart = utils.find_kickstart(kickstart)
        if kickstart:
            self.kickstart = kickstart
            return True
        raise CX(_("kickstart not found: %s" % kickstart))


    def set_power_type(self, power_type):
        # FIXME: modularize this better
        if power_type is None:
            power_type = ""
        choices = utils.get_power_types()
        choices.sort()
        if power_type not in choices:
            raise CX("power management type must be one of: %s" % ",".join(choices))
        self.power_type = power_type
        return True

    def set_power_user(self, power_user):
        if power_user is None:
           power_user = ""
        utils.safe_filter(power_user)
        self.power_user = power_user
        return True 

    def set_power_pass(self, power_pass):
        if power_pass is None:
           power_pass = ""
        utils.safe_filter(power_pass)
        self.power_pass = power_pass
        return True    

    def set_power_address(self, power_address):
        if power_address is None:
           power_address = ""
        utils.safe_filter(power_address)
        self.power_address = power_address
        return True

    def set_power_id(self, power_id):
        if power_id is None:
           power_id = ""
        utils.safe_filter(power_id)
        self.power_id = power_id
        return True

    def modify_interface(self, hash):
        """
        Used by the WUI to modify an interface more-efficiently
        """
        for (key,value) in hash.iteritems():
            (field,interface) = key.split("-",1)
            field = field.replace("_","").replace("-","")
            if field == "macaddress"          : self.set_mac_address(value, interface)
            if field == "mtu"                 : self.set_mtu(value, interface)
            if field == "ipaddress"           : self.set_ip_address(value, interface)
            if field == "dnsname"             : self.set_dns_name(value, interface)
            if field == "static"              : self.set_static(value, interface)
            if field == "dhcptag"             : self.set_dhcp_tag(value, interface)
            if field == "netmask"             : self.set_netmask(value, interface)
            if field == "subnet"              : self.set_netmask(value, interface)
            if field == "ifgateway"           : self.set_if_gateway(value, interface)
            if field == "virtbridge"          : self.set_virt_bridge(value, interface)
            if field == "interfacetype"       : self.set_interface_type(value, interface)
            if field == "interfacemaster"     : self.set_interface_master(value, interface)
            if field == "bonding"             : self.set_interface_type(value, interface)   # deprecated
            if field == "bondingmaster"       : self.set_interface_master(value, interface) # deprecated
            if field == "bondingopts"         : self.set_bonding_opts(value, interface)
            if field == "bridgeopts"          : self.set_bridge_opts(value, interface)
            if field == "management"          : self.set_management(value, interface)
            if field == "staticroutes"        : self.set_static_routes(value, interface)
            if field == "ipv6address"         : self.set_ipv6_address(value, interface)
            if field == "ipv6secondaries"     : self.set_ipv6_secondaries(value, interface)
            if field == "ipv6mtu"             : self.set_ipv6_mtu(value, interface)
            if field == "ipv6staticroutes"    : self.set_ipv6_static_routes(value, interface)
            if field == "ipv6defaultgateway"  : self.set_ipv6_default_gateway(value, interface)
            if field == "cnames"              : self.set_cnames(value, interface)

        return True

    def check_if_valid(self):
        if self.name is None or self.name == "":
            raise CX("name is required")
        if self.profile is None or self.profile == "":
            if self.image is None or self.image == "":
                raise CX("Error with system %s - profile or image is required" % (self.name))
            
    def set_template_remote_kickstarts(self, template):
        """
        Sets whether or not the server is configured to template remote 
        kickstarts.
        """
        self.template_remote_kickstarts = utils.input_boolean(template)
        return True
    
    def set_monit_enabled(self,monit_enabled):
        """
        If true, allows per-system to start Monit to monitor system services such as apache.
        If monit is not running it will start the service.
        
        If false, no management of monit will take place. If monit is not running it will not
        be started. If monit is running it will not be stopped or restarted.
        """
        self.monit_enabled = utils.input_boolean(monit_enabled)
        return True
    
    def set_ldap_enabled(self,ldap_enabled):
        """
        If true, allows per-system to start Monit to monitor system services such as apache.
        If monit is not running it will start the service.
        
        If false, no management of monit will take place. If monit is not running it will not
        be started. If monit is running it will not be stopped or restarted.
        """
        self.ldap_enabled = utils.input_boolean(ldap_enabled)
        return True
    
    def set_repos_enabled(self,repos_enabled):
        """
        If true, allows per-system to start Monit to monitor system services such as apache.
        If monit is not running it will start the service.
        
        If false, no management of monit will take place. If monit is not running it will not
        be started. If monit is running it will not be stopped or restarted.
        """
        self.repos_enabled = utils.input_boolean(repos_enabled)
        return True
    
    def set_ldap_type(self, ldap_type):
        if ldap_type is None:
            ldap_type = ""
        ldap_type = ldap_type.lower()
        self.ldap_type = ldap_type
        return True
Example #44
0
 def set_if_gateway(self,gateway,interface):
     intf = self.__get_interface(interface)
     if gateway == "" or utils.is_ip(gateway):
         intf["if_gateway"] = gateway
         return True
     raise CX(_("invalid gateway: %s" % gateway))
Example #45
0
def compute_c2():
    return {'c2': _('m') * pow(_('y'), _('r'), p)}
Example #46
0
    def rename(self,
               ref,
               newname,
               with_sync=True,
               with_triggers=True,
               logger=None):
        """
        Allows an object "ref" to be given a newname without affecting the rest
        of the object tree.
        """
        # Nothing to do when it is the same name
        if newname == ref.name:
            return True

        # make a copy of the object, but give it a new name.
        oldname = ref.name
        newref = ref.make_clone()
        newref.set_name(newname)

        self.add(newref, with_triggers=with_triggers, save=True)

        # for mgmt classes, update all objects that use it
        if ref.COLLECTION_TYPE == "mgmtclass":
            for what in ["distro", "profile", "system"]:
                items = self.api.find_items(what, {"mgmt_classes": oldname})
                for item in items:
                    for i in range(0, len(item.mgmt_classes)):
                        if item.mgmt_classes[i] == oldname:
                            item.mgmt_classes[i] = newname
                    self.api.add_item(what, item, save=True)

        # for a repo, rename the mirror directory
        if ref.COLLECTION_TYPE == "repo":
            path = "/var/www/cobbler/repo_mirror/%s" % ref.name
            if os.path.exists(path):
                newpath = "/var/www/cobbler/repo_mirror/%s" % newref.name
                os.renames(path, newpath)

        # for a distro, rename the mirror and references to it
        if ref.COLLECTION_TYPE == 'distro':
            path = utils.find_distro_path(self.api.settings(), ref)

            # create a symlink for the new distro name
            utils.link_distro(self.api.settings(), newref)

            # test to see if the distro path is based directly
            # on the name of the distro. If it is, things need
            # to updated accordingly
            if os.path.exists(
                    path
            ) and path == "/var/www/cobbler/ks_mirror/%s" % ref.name:
                newpath = "/var/www/cobbler/ks_mirror/%s" % newref.name
                os.renames(path, newpath)

                # update any reference to this path ...
                distros = self.api.distros()
                for d in distros:
                    if d.kernel.find(path) == 0:
                        d.set_kernel(d.kernel.replace(path, newpath))
                        d.set_initrd(d.initrd.replace(path, newpath))
                        self.config.serialize_item(self, d)

        # now descend to any direct ancestors and point them at the new object allowing
        # the original object to be removed without orphanage.  Direct ancestors
        # will either be profiles or systems.  Note that we do have to care as
        # set_parent is only really meaningful for subprofiles. We ideally want a more
        # generic set_parent.
        kids = ref.get_children()
        for k in kids:
            if k.COLLECTION_TYPE == "distro":
                raise CX(
                    _("internal error, not expected to have distro child objects"
                      ))
            elif k.COLLECTION_TYPE == "profile":
                if k.parent != "":
                    k.set_parent(newname)
                else:
                    k.set_distro(newname)
                self.api.profiles().add(k,
                                        save=True,
                                        with_sync=with_sync,
                                        with_triggers=with_triggers)
            elif k.COLLECTION_TYPE == "system":
                k.set_profile(newname)
                self.api.systems().add(k,
                                       save=True,
                                       with_sync=with_sync,
                                       with_triggers=with_triggers)
            elif k.COLLECTION_TYPE == "repo":
                raise CX(
                    _("internal error, not expected to have repo child objects"
                      ))
            else:
                raise CX(
                    _("internal error, unknown child type (%s), cannot finish rename"
                      % k.COLLECTION_TYPE))

        # now delete the old version
        self.remove(oldname, with_delete=True, with_triggers=with_triggers)
        return True
Example #47
0
    def write_dhcp_file(self):
        """
        DHCP files are written when manage_dhcp is set in
        /var/lib/cobbler/settings.
        """

        settings_file = "/etc/dnsmasq.conf"
        template_file = "/etc/cobbler/dnsmasq.template"

        try:
            f2 = open(template_file, "r")
        except:
            raise CX(_("error writing template to file: %s") % template_file)
        template_data = ""
        template_data = f2.read()
        f2.close()

        # build each per-system definition
        # as configured, this only works for ISC, patches accepted
        # from those that care about Itanium.  elilo seems to be unmaintained
        # so additional maintaince in other areas may be required to keep
        # this working.

        elilo = "/var/lib/cobbler/elilo-3.6-ia64.efi"

        system_definitions = {}
        counter = 0

        # we used to just loop through each system, but now we must loop
        # through each network interface of each system.

        for system in self.systems:

            if not system.is_management_supported(cidr_ok=False):
                continue

            profile = system.get_conceptual_parent()
            distro = profile.get_conceptual_parent()
            for (name, interface) in system.interfaces.iteritems():

                mac = interface["mac_address"]
                ip = interface["ip_address"]
                host = interface["dns_name"]

                if mac is None or mac == "":
                    # can't write a DHCP entry for this system
                    continue

                counter = counter + 1

                # In many reallife situations there is a need to control the IP address
                # and hostname for a specific client when only the MAC address is available.
                # In addition to that in some scenarios there is a need to explicitly
                # label a host with the applicable architecture in order to correctly
                # handle situations where we need something other than pxelinux.0.
                # So we always write a dhcp-host entry with as much info as possible
                # to allow maximum control and flexibility within the dnsmasq config

                systxt = "dhcp-host=net:" + distro.arch.lower() + "," + mac

                if host is not None and host != "":
                    systxt = systxt + "," + host

                if ip is not None and ip != "":
                    systxt = systxt + "," + ip

                systxt = systxt + "\n"

                dhcp_tag = interface["dhcp_tag"]
                if dhcp_tag == "":
                    dhcp_tag = "default"

                if dhcp_tag not in system_definitions:
                    system_definitions[dhcp_tag] = ""
                system_definitions[
                    dhcp_tag] = system_definitions[dhcp_tag] + systxt

        # we are now done with the looping through each interface of each system

        metadata = {
            "insert_cobbler_system_definitions":
            system_definitions.get("default", ""),
            "date":
            time.asctime(time.gmtime()),
            "cobbler_server":
            self.settings.server,
            "next_server":
            self.settings.next_server,
            "elilo":
            elilo
        }

        # now add in other DHCP expansions that are not tagged with "default"
        for x in system_definitions.keys():
            if x == "default":
                continue
            metadata["insert_cobbler_system_definitions_%s" %
                     x] = system_definitions[x]

        self.templar.render(template_data, metadata, settings_file, None)
Example #48
0
def decrypt():
    return {
        'dec': _('c2') * modinv(pow(_('c1'), _('x'), p), p) % p
    }
Example #49
0
 def on_points(self, *args, **kwargs):
     marker = self._get_marker()
     self.status_label.text = self.RANGES[marker].upper(
     ) + "\n" + _("[size=20sp][color=#6666660A]%s POINTS[/color][/size]"
                  ) % self.points
     self.status_image.source = "data/img/status_icons/icon_%s.png" % marker
Example #50
0
def compute_c1():
    return {'c1': pow(g, _('r'), p)}
Example #51
0
 def get_config(self):
     return [{
         "title":
         _("ANALYTICS"),
         "icon":
         "atlas://data/atlas/menu/analytics",
         "tasks": [
             key for key, config in settings.TASKS.items()
             if settings.ANALYTICS_FAMILY in config['families']
             and not config['purchasable']
         ],
         "color":
         settings.ACTIVITY_COLORS[settings.ANALYTICS_FAMILY],
     }, {
         "title":
         _("ATTENTION"),
         "icon":
         "atlas://data/atlas/menu/attention",
         "tasks": [
             key for key, config in settings.TASKS.items()
             if settings.ATTENTION_FAMILY in config['families']
             and not config['purchasable']
         ],
         "color":
         settings.ACTIVITY_COLORS[settings.ATTENTION_FAMILY],
     }, {
         "title":
         _("REACTION"),
         "icon":
         "atlas://data/atlas/menu/reaction",
         "tasks": [
             key for key, config in settings.TASKS.items()
             if settings.REACTION_FAMILY in config['families']
             and not config['purchasable']
         ],
         "color":
         settings.ACTIVITY_COLORS[settings.REACTION_FAMILY],
     }, {
         "title":
         _("MEMORY"),
         "icon":
         "atlas://data/atlas/menu/memory",
         "tasks": [
             key for key, config in settings.TASKS.items()
             if settings.MEMORY_FAMILY in config['families']
         ],
         "color":
         settings.ACTIVITY_COLORS[settings.MEMORY_FAMILY],
     }, {
         "title":
         _("ANALYTICS PREMIUM"),
         "icon":
         "atlas://data/atlas/menu/analytics",
         "tasks": [
             key for key, config in settings.TASKS.items()
             if settings.ANALYTICS_FAMILY in config['families']
         ],
         "color":
         settings.ACTIVITY_COLORS[settings.ANALYTICS_FAMILY],
         "purchases_needed": ['lifetime_premium', 'premium_subscription']
         if settings.INAPP_PURCHASES else []
     }, {
         "title":
         _("ATTENTION PREMIUM"),
         "icon":
         "atlas://data/atlas/menu/attention",
         "tasks": [
             key for key, config in settings.TASKS.items()
             if settings.ATTENTION_FAMILY in config['families']
         ],
         "color":
         settings.ACTIVITY_COLORS[settings.ATTENTION_FAMILY],
         "purchases_needed": ['lifetime_premium', 'premium_subscription']
         if settings.INAPP_PURCHASES else []
     }, {
         "title":
         _("MATH GEEK SET"),
         "icon":
         "atlas://data/atlas/purchases/calculation_arena",
         "tasks": [
             "division_calculation", "percents_calculation",
             "multiplication_calculation"
         ],
         "color":
         settings.ACTIVITY_COLORS[None],
         "purchases_needed": [
             'analytics_arena_pack', 'lifetime_premium',
             'premium_subscription'
         ] if settings.INAPP_PURCHASES else []
     }, {
         "title":
         _("TIME TASKS SET"),
         "icon":
         "atlas://data/atlas/purchases/time_arena",
         "tasks": ["time_subtraction", "time_calculation_minutes"],
         "color":
         settings.ACTIVITY_COLORS[None],
         "purchases_needed":
         ['time_arena_pack', 'lifetime_premium', 'premium_subscription']
         if settings.INAPP_PURCHASES else []
     }, {
         "title":
         _("CLASH TASKS SET"),
         "icon":
         "atlas://data/atlas/purchases/clash_arena",
         "tasks": ["find_figures", "find_primer"],
         "color":
         settings.ACTIVITY_COLORS[None],
         "purchases_needed":
         ['clash_arena_pack', 'lifetime_premium', 'premium_subscription']
         if settings.INAPP_PURCHASES else []
     }]
Example #52
0
class Distro(item.Item):

    TYPE_NAME = _("distro")
    COLLECTION_TYPE = "distro"

    def __init__(self, *args, **kwargs):
        item.Item.__init__(self, *args, **kwargs)
        self.ks_meta = {}
        self.source_repos = []

    def make_clone(self):
        ds = self.to_datastruct()
        cloned = Distro(self.config)
        cloned.from_datastruct(ds)
        return cloned

    def get_fields(self):
        return FIELDS

    def get_parent(self):
        """
        Return object next highest up the tree.
        NOTE: conceptually there is no need for subdistros
        """
        return None

    def set_kernel(self,kernel):
        """
        Specifies a kernel.  The kernel parameter is a full path, a filename
        in the configured kernel directory (set in /etc/cobbler.conf) or a
        directory path that would contain a selectable kernel.  Kernel
        naming conventions are checked, see docs in the utils module
        for find_kernel.
        """
        if kernel is None or kernel == "":
            raise CX("kernel not specified")
        if utils.find_kernel(kernel):
            self.kernel = kernel
            return True
        raise CX("kernel not found: %s" % kernel)

    def set_tree_build_time(self, datestamp):
        """
        Sets the import time of the distro.
        If not imported, this field is not meaningful.
        """
        self.tree_build_time = float(datestamp)
        return True

    def set_breed(self, breed):
        return utils.set_breed(self,breed)

    def set_os_version(self, os_version):
        return utils.set_os_version(self,os_version)

    def set_initrd(self,initrd):
        """
	Specifies an initrd image.  Path search works as in set_kernel.
	File must be named appropriately.
	"""
        if initrd is None or initrd == "":
            raise CX("initrd not specified")
        if utils.find_initrd(initrd):
            self.initrd = initrd
            return True
        raise CX(_("initrd not found"))

    def set_redhat_management_key(self,key):
        return utils.set_redhat_management_key(self,key)

    def set_redhat_management_server(self,server):
        return utils.set_redhat_management_server(self,server)
 
    def set_source_repos(self, repos):
        """
        A list of http:// URLs on the cobbler server that point to
        yum configuration files that can be used to
        install core packages.  Use by cobbler import only.
        """
        self.source_repos = repos

    def set_arch(self,arch):
        """
        The field is mainly relevant to PXE provisioning.

        Should someone have Itanium machines on a network, having
        syslinux (pxelinux.0) be the only option in the config file causes
        problems.

        Using an alternative distro type allows for dhcpd.conf templating
        to "do the right thing" with those systems -- this also relates to
        bootloader configuration files which have different syntax for different
        distro types (because of the bootloaders).

        This field is named "arch" because mainly on Linux, we only care about
        the architecture, though if (in the future) new provisioning types
        are added, an arch value might be something like "bsd_x86".

        Update: (7/2008) this is now used to build fake PXE trees for s390x also
        """
        return utils.set_arch(self,arch)

    def check_if_valid(self):
        if self.name is None:
            raise CX("name is required")
        if self.kernel is None:
            raise CX("Error with distro %s - kernel is required" % (self.name))
        if self.initrd is None:
            raise CX("Error with distro %s - initrd is required" % (self.name))

        if utils.file_is_remote(self.kernel):
            if not utils.remote_file_exists(self.kernel):
                raise CX("Error with distro %s - kernel not found" % (self.name))
        elif not os.path.exists(self.kernel):
            raise CX("Error with distro %s - kernel not found" % (self.name))

        if utils.file_is_remote(self.initrd):
            if not utils.remote_file_exists(self.initrd):
                raise CX("Error with distro %s - initrd path not found" % 
                        (self.name))
        elif not os.path.exists(self.initrd):
            raise CX("Error with distro %s - initrd path not found" % (self.name))
Example #53
0
def compute_X():
    return {'X': pow(g, _('x'), p)}
Example #54
0
 def __init__(self, **kwargs):
     super(TestOutro, self).__init__(**kwargs)
     self.RANGES = {
         50: _("Typing monkey"),
         60: _("H**o erectus"),
         70: _("Slowpoke"),
         80: _("H**o sapiens"),
         90: _("Junkie"),
         100: _("Mr Perfect"),
         110: _("Genius"),
         120: _("Nerd"),
         130: _("Holmes"),
         140: _("Einstein"),
         150: _("Kognimaster")
     }
Example #55
0
def compute_k1():
    return {'K1': pow(_('Y'), _('x'), p)}
Example #56
0
 def on_points(self, instance, value):
     self.text = _("BEST RESULT: [b]%s[/b] POINTS") % value
Example #57
0
class Repo(item.Item):

    TYPE_NAME = _("repo")
    COLLECTION_TYPE = "repo"

    def make_clone(self):
        ds = self.to_datastruct()
        cloned = Repo(self.config)
        cloned.from_datastruct(ds)
        return cloned

    def get_fields(self):
        return FIELDS

    def _guess_breed(self):
        # backwards compatibility
        if (self.breed == "" or self.breed is None):
            if self.mirror.startswith("http://") or self.mirror.startswith(
                    "ftp://"):
                self.set_breed("yum")
            elif self.mirror.startswith("rhn://"):
                self.set_breed("rhn")
            else:
                self.set_breed("rsync")

    def set_mirror(self, mirror):
        """
        A repo is (initially, as in right now) is something that can be rsynced.
        reposync/repotrack integration over HTTP might come later.
        """
        self.mirror = mirror
        if self.arch is None or self.arch == "":
            if mirror.find("x86_64") != -1:
                self.set_arch("x86_64")
            elif mirror.find("x86") != -1 or mirror.find("i386") != -1:
                self.set_arch("i386")
            elif mirror.find("ia64") != -1:
                self.set_arch("ia64")
            elif mirror.find("s390") != -1:
                self.set_arch("s390x")
        self._guess_breed()
        return True

    def set_keep_updated(self, keep_updated):
        """
    This allows the user to disable updates to a particular repo for whatever reason.
    """
        self.keep_updated = utils.input_boolean(keep_updated)
        return True

    def set_yumopts(self, options, inplace=False):
        """
        Kernel options are a space delimited list,
        like 'a=b c=d e=f g h i=j' or a hash.
        """
        (success, value) = utils.input_string_or_hash(options,
                                                      allow_multiples=False)
        if not success:
            raise CX(_("invalid yum options"))
        else:
            if inplace:
                for key in value.keys():
                    self.yumopts[key] = value[key]
            else:
                self.yumopts = value
            return True

    def set_environment(self, options, inplace=False):
        """
        Yum can take options from the environment.  This puts them there before
        each reposync.
        """
        (success, value) = utils.input_string_or_hash(options,
                                                      allow_multiples=False)
        if not success:
            raise CX(_("invalid environment options"))
        else:
            if inplace:
                for key in value.keys():
                    self.environment[key] = value[key]
            else:
                self.environment = value
            return True

    def set_priority(self, priority):
        """
        Set the priority of the repository.  1= highest, 99=default
        Only works if host is using priorities plugin for yum.
        """
        try:
            priority = int(str(priority))
        except:
            raise CX(_("invalid priority level: %s") % priority)
        self.priority = priority
        return True

    def set_rpm_list(self, rpms):
        """
        Rather than mirroring the entire contents of a repository (Fedora Extras, for instance,
        contains games, and we probably don't want those), make it possible to list the packages
        one wants out of those repos, so only those packages + deps can be mirrored.
        """
        self.rpm_list = utils.input_string_or_list(rpms)
        return True

    def set_createrepo_flags(self, createrepo_flags):
        """
        Flags passed to createrepo when it is called.  Common flags to use would be
        -c cache or -g comps.xml to generate group information.
        """
        if createrepo_flags is None:
            createrepo_flags = ""
        self.createrepo_flags = createrepo_flags
        return True

    def set_breed(self, breed):
        if breed:
            return utils.set_repo_breed(self, breed)

    def set_os_version(self, os_version):
        if os_version:
            return utils.set_repo_os_version(self, os_version)

    def set_arch(self, arch):
        """
        Override the arch used for reposync
        """
        return utils.set_arch(self, arch, repo=True)

    def set_mirror_locally(self, value):
        self.mirror_locally = utils.input_boolean(value)
        return True

    def get_parent(self):
        """
        currently the Cobbler object space does not support subobjects of this object
        as it is conceptually not useful.
        """
        return None

    def check_if_valid(self):
        if self.name is None:
            raise CX("name is required")
        if self.mirror is None:
            raise CX("Error with repo %s - mirror is required" % (self.name))
Example #58
0
def compute_k2():
    return {'K2': pow(_('X'), _('y'), p)}
Example #59
0
 def on_points(self, instance, value):
     if self.points:
         self.text = _("%s\n[size=%s]POINTS[/font]") % (
             self.points, int(self.label_size))
     else:
         self.text = ""
Example #60
0
def compute_Y():
    return {'Y': pow(g, _('y'), p)}