Ejemplo n.º 1
0
 def my_account_password_update(self):
     c.active = 'password'
     self.__load_data()
     _form = PasswordChangeForm(c.rhodecode_user.username)()
     try:
         form_result = _form.to_python(request.POST)
         UserModel().update_user(c.rhodecode_user.user_id, **form_result)
         instance = c.rhodecode_user.get_instance()
         instance.update_userdata(force_password_change=False)
         Session().commit()
         session.setdefault('rhodecode_user',
                            {}).update({'password': md5(instance.password)})
         session.save()
         h.flash(_("Successfully updated password"), category='success')
     except formencode.Invalid as errors:
         return htmlfill.render(render('admin/my_account/my_account.html'),
                                defaults=errors.value,
                                errors=errors.error_dict or {},
                                prefix_error=False,
                                encoding="UTF-8",
                                force_defaults=False)
     except Exception:
         log.exception("Exception updating password")
         h.flash(_('Error occurred during update of user password'),
                 category='error')
     return render('admin/my_account/my_account.html')
Ejemplo n.º 2
0
    def __call__(self, message, typ=None, **kw):
        from pylons import session
        message = AdvFlash.Message(message)
        message.type = typ or self.type

        info = self.defaults.copy()
        info.update(kw)

        for k,v in info.items():
            setattr(message,k,v)

        session.setdefault(self.key, []).append(message)
        session.save()
Ejemplo n.º 3
0
	def __before__(self):
		action = self.routingargs.get('action', '')
		if action == 'ipn': # nothing else needs to be done for IPN
			return

		c.title = 'Scorekeeper Registration'
		c.stylesheets = ['/css/register.css', '/css/redmond/jquery-ui-1.8.2.custom.css']
		c.javascript = ['/js/register.js', '/js/jquery-1.4.2.min.js', '/js/jquery-ui-1.8.2.custom.min.js', '/js/jquery.validate.min.js']
		c.tabflags = {}
		c.sponsorlink = self.settings.sponsorlink
		c.seriesname = self.settings.seriesname

		ipsession = session.setdefault(self.srcip, {})

		if self.database is not None:
			self.user = ipsession.setdefault(self.database, {})
			c.driverid = self.user.get('driverid', 0)
			c.firstname = self.user.get('firstname', '')
			c.lastname = self.user.get('lastname', '')
			c.previouserror = self.user.get('previouserror', '')
			self.user['previouserror'] = ''

			if action in ['index', 'events', 'cars', 'profile'] and c.driverid < 1:
				session.save()
				redirect(url_for(action='login'))

			if action not in ['view'] and self.settings.locked:
				# Delete any saved session data for this person
				del ipsession[self.database]
				session.save()
				raise BeforePage(render_mako('/register/locked.mako'))

			c.events = self.session.query(Event).all()
			c.cars = self.session.query(Car).filter(Car.driverid==c.driverid).order_by(Car.classcode,Car.number).all()
			session.save()
Ejemplo n.º 4
0
    def __call__(self, message, category=None, ignore_duplicate=False):
        """Add a message to the session.

        ``message`` is the message text.

        ``category`` is the message's category. If not specified, the default
        category will be used.  Raise ``ValueError`` if the category is not
        in the list of allowed categories.
        
        If ``ignore_duplicate`` is true, don't add the message if another
        message with identical text has already been added. If the new
        message has a different category than the original message, change the
        original message to the new category.
        
        """
        if not category:
            category = self.default_category
        elif self.categories and category not in self.categories:
            raise ValueError("unrecognized category %r" % (category, ))
        # Don't store Message objects in the session, to avoid unpickling
        # errors in edge cases.
        new_message_tuple = (category, message)
        from pylons import session
        messages = session.setdefault(self.session_key, [])
        # ``messages`` is a mutable list, so changes to the local variable are
        # reflected in the session.
        if ignore_duplicate:
            for i, m in enumerate(messages):
                if m[1] == message:
                    if m[0] != category:
                        messages[i] = new_message_tuple
                        session.save()
                    return  # Original message found, so exit early.
        messages.append(new_message_tuple)
        session.save()
Ejemplo n.º 5
0
    def __call__(self, message, category=None, ignore_duplicate=False):
        """Add a message to the session.

        ``message`` is the message text.

        ``category`` is the message's category. If not specified, the default
        category will be used.  Raise ``ValueError`` if the category is not
        in the list of allowed categories.
        
        If ``ignore_duplicate`` is true, don't add the message if another
        message with identical text has already been added. If the new
        message has a different category than the original message, change the
        original message to the new category.
        
        """
        if not category:
            category = self.default_category
        elif self.categories and category not in self.categories:
            raise ValueError("unrecognized category %r" % (category,))
        # Don't store Message objects in the session, to avoid unpickling
        # errors in edge cases.
        new_message_tuple = (category, message)
        from pylons import session
        messages = session.setdefault(self.session_key, [])
        # ``messages`` is a mutable list, so changes to the local variable are
        # reflected in the session.
        if ignore_duplicate:
            for i, m in enumerate(messages):
                if m[1] == message:
                    if m[0] != category:
                        messages[i] = new_message_tuple
                        session.save()
                    return    # Original message found, so exit early.
        messages.append(new_message_tuple)
        session.save()
Ejemplo n.º 6
0
 def __call__(self,
              message,
              category=None,
              ignore_duplicate=False,
              allow_html=False):
     if not category:
         category = self.default_category
     elif self.categories and category not in self.categories:
         raise ValueError("unrecognized category %r" % (category, ))
     # Don't store Message objects in the session, to avoid unpickling
     # errors in edge cases.
     new_message_tuple = (category, message, allow_html)
     from pylons import session
     messages = session.setdefault(self.session_key, [])
     # ``messages`` is a mutable list, so changes to the local variable are
     # reflected in the session.
     if ignore_duplicate:
         for i, m in enumerate(messages):
             if m[1] == message:
                 if m[0] != category:
                     messages[i] = new_message_tuple
                     session.save()
                 return  # Original message found, so exit early.
     messages.append(new_message_tuple)
     session.save()
Ejemplo n.º 7
0
 def new_page(self, user, **fields):
     assert('almanac_id' not in fields)
     assert('user_id' not in fields)
     userid = session.setdefault('userid', None)
     if isinstance(user, FullUser) and userid:
         # Check to see if there is an Anonymous user and suck that page
         # in...
         anon_user = meta.Session.query(AnonymousUser).get(userid)
         if anon_user:
             user.pages += anon_user.pages
             meta.Session.delete(anon_user)
             meta.Session.commit()
         # Don't forget to clean up the session
         session['userid'] = None
         session.save()
     try:
         page = meta.Session.query(Page).filter(and_(Page.published == False, Page.almanac_id == self.id, Page.user_id == user.id)).one()
         modified = False
         for field, value in fields.iteritems():
             if hasattr(page, field) and getattr(page, field) != value:
                 setattr(page, field, value)
                 modified = True
         if modified:
             meta.Session.commit()
         return page
     except exc.MultipleResultsFound:
         # It's time to combine these pages and chew bubblegum... and I'm
         # all out of gum...
         pages = list(meta.Session.query(Page).filter(and_(Page.published == False, Page.almanac_id == self.id, Page.user_id == user.id)))
         winner = pages[0]
         if winner.name is None:
             winner.name = u''
         if winner.slug is None:
             winner.slug = Page.name_page(self, u'Page')
         for loser in pages[1:]:
             if loser.name != winner.name:
                 if loser.name is not None:
                     if winner.name:
                         winner.name += u', %s' % loser.name
                     else:
                         winner.name = loser.name
             winner.media += loser.media
             meta.Session.delete(loser)
         meta.Session.add(winner)
         meta.Session.commit()
         return winner
     except exc.NoResultFound:
         pass
     page = Page(published=False, almanac_id=self.id, user_id=user.id, **fields)
     meta.Session.add(page)
     meta.Session.commit()
     return page
Ejemplo n.º 8
0
    def login(self):
        password = request.POST.get("password")
        ipsession = session.setdefault(self.srcip, {})
        tokens = ipsession.setdefault("authtokens", set())

        if password == self.settings.password:
            tokens.add("series")

        for event in c.events:
            if password == event.password:
                tokens.add(event.id)

        session.save()
        redirect(url_for(action=""))
Ejemplo n.º 9
0
	def __before__(self):
		action = self.routingargs.get('action', '')

		if action in ('available'):
			return
		if not self.database or action == 'index':
			raise BeforePage("")

		try:
			digestinfo = session.setdefault('digest', {})
			passwords = Password.load(self.session)
			authCheck(digestinfo, self.database, {"admin" : passwords['series'] }, request)
			# at this point, they are verified as knowing the password for database:series
		finally:
			session.save()
Ejemplo n.º 10
0
    def __before__(self):
        action = self.routingargs.get('action', '')

        if action in ('available'):
            return
        if not self.database or action == 'index':
            raise BeforePage("")

        try:
            digestinfo = session.setdefault('digest', {})
            passwords = Password.load(self.session)
            authCheck(digestinfo, self.database,
                      {"admin": passwords['series']}, request)
            # at this point, they are verified as knowing the password for database:series
        finally:
            session.save()
Ejemplo n.º 11
0
	def _checkauth(self, event):
		if self.srcip == '127.0.0.1':
			c.isAdmin = True
			return

		try:
			digestinfo = session.setdefault(('digest', self.srcip), {})
			pwdict = Password.load(self.session)
			passwords = { "admin" : pwdict["series"] }
			if event is not None and str(event.id) in pwdict:
				passwords["event"] = pwdict[str(event.id)]

			authname = authCheck(digestinfo, self.database, passwords, request)
			if authname == "admin":
				c.isAdmin = True
		finally:
			session.save()
Ejemplo n.º 12
0
 def ensure_user(self):
     if c.user:
         return c.user
     # Check for session user
     userid = session.setdefault('userid', None)
     if userid:
         user = meta.Session.query(User).get(userid)
         if user:
             return user
         # The failing case should only happen when a valid session exists
         # with a reference to a user that has been deleted.
     user = AnonymousUser()
     meta.Session.add(user)
     meta.Session.commit()
     session['userid'] = user.id
     session.save()
     return user
Ejemplo n.º 13
0
	def __before__(self):
		action = self.routingargs.get('action', '')
		if action == 'ipn': # nothing else needs to be done for IPN
			return

		c.title = 'Scorekeeper Registration'
		c.stylesheets = ['/css/register.css']
		c.javascript = ['/js/register.js']

		c.activeSeries = self._activeSeries()
		if self.database is None:
			return

		self.user = UserSession(session.setdefault(('register', self.srcip), {}), self.database) 

		c.settings = self.settings
		c.database = self.database
		c.driverid = self.user.getDriverId()
		c.previouserror = self.user.getPreviousError()
		c.classdata = ClassData(self.session)
		c.eventmap = dict()
		now = datetime.datetime.now()
		for event in self.session.query(Event):
			event.closed = now > event.regclosed 
			event.opened = now > event.regopened
			event.isOpen = not event.closed and event.opened
			c.eventmap[event.id] = event

		c.events = sorted(c.eventmap.values(), key=lambda obj: obj.date)

		if action not in ('view') and self.settings.locked:
			# Delete any saved session data for this person
			raise BeforePage(render_mako('/register/locked.mako'))

		if action in ('index', 'events', 'cars', 'profile') and c.driverid < 1:
			c.activecreds = self.user.activeCreds()
			for cred in c.activecreds:
				driver = self._verifyID(**cred.__dict__)
				if driver is not None:
					self.user.setLoginInfo(driver)
					c.driverid = self.user.getDriverId()
					return # continue on to regular page, we are now verified

			c.fields = self.session.query(DriverField).all()
			c.otherseries = self.user.activeSeries()
			raise BeforePage(render_mako('/register/login.mako'))
Ejemplo n.º 14
0
    def _checkauth(self, event):
        if self.srcip == '127.0.0.1':
            c.isAdmin = True
            return

        try:
            digestinfo = session.setdefault(('digest', self.srcip), {})
            pwdict = Password.load(self.session)
            passwords = {"admin": pwdict["series"]}
            if event is not None and str(event.id) in pwdict:
                passwords["event"] = pwdict[str(event.id)]

            authname = authCheck(digestinfo, self.database, passwords, request)
            if authname == "admin":
                c.isAdmin = True
        finally:
            session.save()
Ejemplo n.º 15
0
 def __call__(self, message, category=None, ignore_duplicate=False, allow_html=False):
     if not category:
         category = self.default_category
     elif self.categories and category not in self.categories:
         raise ValueError("unrecognized category %r" % (category,))
     # Don't store Message objects in the session, to avoid unpickling
     # errors in edge cases.
     new_message_tuple = (category, message, allow_html)
     messages = session.setdefault(self.session_key, [])
     # ``messages`` is a mutable list, so changes to the local variable are
     # reflected in the session.
     if ignore_duplicate:
         for i, m in enumerate(messages):
             if m[1] == message:
                 if m[0] != category:
                     messages[i] = new_message_tuple
                     session.save()
                 return  # Original message found, so exit early.
     messages.append(new_message_tuple)
     session.save()
Ejemplo n.º 16
0
    def evaluate(self, environ, credentials):

        user = c.user
        if not user:
            userid = session.setdefault('userid', None)
            if not userid:
                self.unmet()
            user = meta.Session.query(User).get(userid)
            if not user:
                self.unmet()

        media_id = environ['pylons.routes_dict']['media_id']
        media = h.get_media_by_id(media_id)

        if media.page.user_id == user.id:
            return
        if credentials and \
           'manage' in credentials.get('permissions'):
            return
        self.unmet()
Ejemplo n.º 17
0
    def _checkauth(self, eventid, event):
        if self.srcip == "127.0.0.1":
            c.isAdmin = True
            return

        if event is None and eventid != "s":
            c.text = "<h3>No such event for %s</h3>" % eventid
            raise BeforePage(render_mako("/admin/simple.mako"))

        ipsession = session.setdefault(self.srcip, {})
        tokens = ipsession.setdefault("authtokens", set())
        c.isAdmin = "series" in tokens
        if event is not None:
            if int(eventid) in tokens or "series" in tokens:
                return
            c.request = "Need authentication token for %s" % event.name
            raise BeforePage(render_mako("/admin/login.mako"))
        else:
            if c.isAdmin:
                return
            c.request = "Need authentication token for the series"
            raise BeforePage(render_mako("/admin/login.mako"))
Ejemplo n.º 18
0
    def evaluate(self, environ, credentials):

        user = c.user
        if not user:
            userid = session.setdefault('userid', None)
            if not userid:
                self.unmet()
            user = meta.Session.query(User).get(userid)
            if not user:
                self.unmet()

        almanac_slug = environ['pylons.routes_dict']['almanac_slug']
        page_slug = environ['pylons.routes_dict']['page_slug']

        almanac = h.get_almanac_by_slug(almanac_slug)
        page = h.get_page_by_slug(almanac, page_slug)

        if page.user_id == user.id:
            return
        if credentials and \
           'manage' in credentials.get('permissions'):
            return
        self.unmet()
Ejemplo n.º 19
0
 def __call__(self, message):
     from pylons import session
     session.setdefault(self.session_key, []).append(message)
     session.save()
Ejemplo n.º 20
0
    def _rungccom(self, reqparams, model_dict, mode):
        # Static strings for template (stateless)
        dbgstr='';
        errstr='';
        c.cwuser = session['user_id']
        c.account_id = int(model_dict['hostname'])
        resource = app_globals.jodis.manager.getResource(c.account_id)
        log.info('GCOM HOSTNAME= %s' % resource.host)
        c.mode = mode
        c.menu = 'gccom_%s' % c.mode
        c.model_param_hdrs = Gccom.model_params['hdrs']
        c.model_key = model_dict['model_key']
        c.grid_key = Gccom.model_info[c.model_key]['grid_key']
        for i in ['name', 'IMax', 'JMax', 'KMax']:
            setattr(c, 'grid_%s' % i.lower(), Gccom.bath_grid[c.grid_key][i])
        session.setdefault(c.model_key, {})

        for k, v in model_dict.items():
            setattr(c, k, v)

        if c.jobstate == 'submit':
            log.debug('submit job')
            for i in ('jobstate','hostname', 'jobname','model_params','mode','jobdescription'):
                session[c.model_key][i] = reqparams.get(i,'')
                setattr(c, i, session[c.model_key][i])
                if i == 'model_params':
                    # This is not secure at all
                    session[c.model_key][i] = eval(session[c.model_key][i])

            # Retrieve model parameters & update c.model_params using the form data
            c.model_params = session[c.model_key]['model_params']
            for key, value in dict(reqparams).items():
                if key.strip().endswith('.paramval'):
                    key_str = key.split('.')[0]
                    value_str = str(value) or 'none'
                    count = 0
                    for i in c.model_params:
                        if key_str.find(str(i[0])) >= 0:
                            c.model_params[count][2] = value_str
                            count += 1

            # build parameter file and copy to host 
            paramfilestr = '&params\n'
            for p in c.model_params:
                paramfilestr += ('%s = %s      ! %s\n' % ( p[0], p[2], p[1]) )
            paramfilestr += '/\n'

            # Create job. This gives us jobid and creates a unique name
            try:
                account = meta.Session.query(Account).filter(Account.id == int(c.account_id)).first()
                if not account: raise
                log.debug('GCOMJOB: acct[uname: %s, res_id: %s, serv_id: %s], account_id: %d' , \
                           account.username, account.resource_id, account.service_id, account.id)
                service = meta.Session.query(Service).filter(Service.id == account.service_id).first()
                if not service: raise
            except Exception as e:
                errstr = 'Problem creating job on hostname: %s, err: %s' % (resource.host, str(e))
                log.error(errstr)
                session['error_flash'] = [errstr]
                session.save()
                return redirect(url(controller='gccom', action = '%s_%s' % (c.mode.lower(), c.model_key) ))
            infostr = ('GCOMJOB: [JobName: %s] [hostname: %s, accountID: %d] [Serv: ID=%s, %s @ %s] ' % ( \
                       c.jobname, resource.host, account.id, service.id, service.service_name, service.resource ) )
            log.info(infostr)
            sj = app_globals.jodis.createJob(service.id, session.get('user_id', 0), c.jobname)
            c.jobid = sj.id
            c.jobname = sj.name
            log.info('GCOMJOB: jobname:%s,  jobid: %s' % (c.jobname,c.jobid) )

            # Copy the session data from the setup model_key dictionary to the job id.
            # We then delete the model_key dictionary so that the user can start a new job
            # with no conflicts.
            session[c.jobid] = {1:{}}
            mytask = session.get(c.model_key, {}).copy()
            if not mytask.keys():
                log.error('Uh oh! We have session no data for model: %s', c.model_key)
            mytask['jobname'] = c.jobname
            mytask['model_key'] = c.model_key
            mytask['cwuser'] = c.cwuser
            mytask['jobid'] = c.jobid

            dt = strftime('%Y-%m-%d %H:%M:%S')
            del session[c.model_key]

            # get cyberweb home dir
            (home,err)  = resource.raw('pwd')
            # directories and file names for job to be run
            userdir           = ('%s/%s/%s' % (home,config.get('cw.cwuser_rem','.'), c.cwuser ))
            jobdir            = ('%s/%s' % ( userdir,c.jobname) )
            mytask['userdir'] = userdir

            # remote host: make the job directory for job using jobid  (cwrj_)
            cmd     = ('mkdir -p %s' % jobdir )
            out, err = resource.raw( cmd )
            log.info("GCOMJOB: mkdir userdir: output:[ %s], error:[%s]",out.splitlines(),err.splitlines())

            gcemdir       = ('%s/%s'  % (home, Gccom.gcem_dir) )
            gccomdir      = ('%s/%s'  % (gcemdir, Gccom.gccom_dir ) )
            modelname     = Gccom.model_info[c.model_key]['modelname']
            modeldir      = ('%s/%s'  % (gccomdir, c.model_key) ) 
            ###job_modelname = ('%s/%s'  % (jobdir,modelname))
            job_modelname = ('%s/%s'  % (jobdir, Gccom.model_info[c.model_key]['modelname'] ) )
            log.debug('GCOMJOB: TRY to copy model files: FROM: %s, TO: %s\n\n ' , modeldir, jobdir )
            # move GCOM model files over to job dir; rename for job runs
            out,err = resource.raw('cp -r %s/* %s' % (modeldir, jobdir) )
            log.debug('GCOMJOB: CP STATUS: OUT: %s \nERR: %s\n' , out.splitlines(), err.splitlines() )


            # rename application to include jobID
            fname_old   = job_modelname
            job_modelname  = '%s.%s' % (fname_old, str(c.jobid))
            resource.raw('mv %s %s' % (fname_old, job_modelname))
            resource.raw('chmod 755 %s/' % (modelname))
            out,err = resource.raw('ls -al %s' % jobdir )
            log.debug('GCOMJOB: DIR: %s \n LISTING: OUT:  %s \n ERR: %s\n' ,jobdir,out.splitlines(),err.splitlines() )

            ### -------------- GOOD TO HERE  ---------------###
 
            # Create the job submit file. This will be used in the qsub process
            # and for error checking later
            # name of batch script on the remote host
            batchscript_file = ('%s/batch.%s.%s' % (jobdir, modelname, c.jobid))    
            batchscript_contents = self.batchScript_PBS(modelname,c.jobid,jobdir,job_modelname)
            log.debug('After Script Build: batchscript_file: %s\n, CONTENTS: \n  %s', 
                       batchscript_file, batchscript_contents)
            #
            tmpfile = ('/tmp/%s.batch.%s.%s' % (c.cwuser, modelname, c.jobid))
            try:
                with open(tmpfile, 'w') as fh:
                    fh.write( batchscript_contents )
                log.debug('created file: %s',tmpfile)
            except:
                log.error("Can't write batch script %s" % tmpfile)

            # move application files over to job dir and rename
            out = resource.ssh.scp(None, None, tmpfile, resource.ssh.user, resource.host, batchscript_file)
            #out = resource.ssh.scpTo( resource.ssh.user, mytask.get('hostname'), tmpfile, batchscript_file )

            log.debug('GCOMJOB: SCP FROM: %s, TO: %s\n for USER: %s  @ HOST: %s, \n OUT: %s \n  ', \
                tmpfile, batchscript_file, resource.ssh.user, mytask.get('hostname'), out.splitlines() ) 
            sj.addTask(account.id, submitfile=batchscript_file)
            log.debug('GCOMJOB: Task added to JOB_ID: %s', sj.id)

            qsub_result = app_globals.jodis.submitJob(sj.name)
            if qsub_result:
                sj.start()
            else:
                log.error('Job submission didn\'t return anything. Changing state of %s to error', sj.id)
                sj.error()

            # build this array to associate batch queue job id with cw job number.
            if 'qsubid_list' not in mytask:
                mytask['qsubid_list'] = []
            mytask['qsubid_list'].append((sj.id, c.jobid))
            mytask['qsubids'] = sj.id
            c.grid_fname = Gccom.bath_grid[c.grid_key]['fname']
            c.grid_name  = Gccom.bath_grid[c.grid_key]['name']
            gridfname    = Gccom.bath_grid[c.grid_key]['fname']

            fstr = 'JOB HISTORY FOR JOB: ' + str(c.jobname) + '\n'
            fstr += '          Date: ' + dt + '\n'
            fstr += '    Model Type: ' + c.model_key + '\n'
            fstr += '  Submitted By: ' + c.cwuser + '\n'
            fstr += '          Host: ' + mytask['hostname'] + '\n'
            fstr += '       JobName: ' + mytask['jobname'] + '\n'
            fstr += '     Grid Name: ' + c.grid_name + '\n'
            fstr += 'Grid File Name: ' + gridfname + '\n'
            fstr += ('  Problem Size: [%s x %s x %s]\n' % (c.grid_imax, c.grid_jmax, c.grid_kmax))
            fstr += '  Batch Queue Job Info:  ' + mytask['qsubids'] + '\n'

            log.info('queue job history: %s' % fstr)
            resource.raw('echo \"%s\" >> %s/job.history.%s' % (fstr.replace('\n','\\n'), jobdir, c.jobid) )

            fstr =  ('JOBID = %s \\n' % (sj.id) )
            fstr += 'gridname = ' + c.grid_name + '\\n'
            fstr += 'gridfname = ' + gridfname + '\\n'
            fstr += ('Imax = %s \\n' % (c.grid_imax) )
            fstr += ('Jmax = %s \\n' % (c.grid_jmax) )
            fstr += ('Kmax = %s \\n' % (c.grid_kmax) )
            fstr += ('MaxFileNo = %s \\n' % ( Gccom.model_params[c.model_key][2][2]  ) ) 
            fstr += ('wrthz = %s \n' % ( Gccom.model_params[c.model_key][3][2]  ) ) 
            fstr += 'jobtype = ser' + '\\n' 
            fstr += 'PROCS = 1 \\n'
            fstr += 'Pi = 1 \\n'
            fstr += 'Pj = 1 \\n'
            fstr += 'Pk = 1 \\n'

            log.info('queue job info: %s' % fstr)
            resource.raw('echo \"%s\" >> %s/job.info.%s' % (fstr.replace('\n','\\n'), jobdir, c.jobid) )

            log.info('User %s submitted job %s' % (session['user'],mytask['qsubids']))
            c.jobstate = 'submitted'

            # Save the task to the database
            mytaskdb = model.Task(
                              int(c.jobid),
                              queuejob_id=mytask['qsubids'],
                              environment=mytask['hostname'],
                              state=sj.state,
                              type=c.model_key,
                              owner=session['user_id'],
                             )
            try:
                meta.Session.add(mytaskdb)
                meta.Session.commit()
            except:
                log.warn('Couldn\'t commit job')
                meta.Session.rollback()
            else:
                meta.Session.close()
        elif c.jobstate == 'monitor':
            log.info('Redirect to Job Monitor')
            return redirect(url(controller='gccom', action='jobmonitor'))
        else:
            c.jobstate = 'jobstate_error: submit'
            c.jobmsg = 'Invalid job state'
            log.debug(c.jobmsg)
            return render('/gcem/gccom/app_%s.mako' % mode.lower())
        session.save()
        return render('/gcem/gccom/app_%s.mako' % mode.lower())
Ejemplo n.º 21
0
 def session_increment(self):
     session.setdefault('counter', -1)
     session['counter'] += 1
     session.save()
     return 'session incrementer'
Ejemplo n.º 22
0
def flash(msg):
    """Add 'msg' to the users flashest list in the users session"""
    flashes = session.setdefault('_admin_flashes', [])
    flashes.append(msg)
    session.save()
Ejemplo n.º 23
0
	def __call__(self, message, message_type=None):
		from pylons import session
		message = Message(message)
		message.type = message_type or self.type
		session.setdefault(self.key, []).append(message)
		session.save()
Ejemplo n.º 24
0
 def __call__(self, message):
     from pylons import session
     session.setdefault(self.session_key, []).append(message)
     session.save()
Ejemplo n.º 25
0
def flash(s):
    """add the string "s" to the session's flash store"""
    session.setdefault('flash', []).append(s)
    session.save()
Ejemplo n.º 26
0
def flash(msg):
    """Add 'msg' to the users flashest list in the users session"""
    flashes = session.setdefault('_admin_flashes', [])
    flashes.append(msg)
    session.save()
Ejemplo n.º 27
0
 def session_increment(self):
     session.setdefault("counter", -1)
     session["counter"] += 1
     session.save()
     return "session incrementer"
Ejemplo n.º 28
0
 def session_increment(self):
     session.setdefault('counter', -1)
     session['counter'] += 1
     session.save()
     return 'session incrementer'
Ejemplo n.º 29
0
def add_session_message(type, message):
    session.setdefault('messagetotal', 0)
    session['messagetotal'] += 1
    session.setdefault('messages', {})
    session['messages']['session_%d' % session['messagetotal']] = (type, message)
    session.save()