PageRenderTime 37ms CodeModel.GetById 23ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/galaxy/web/api/histories.py

https://bitbucket.org/cistrome/cistrome-harvard/
Python | 163 lines | 121 code | 16 blank | 26 comment | 26 complexity | e0642c2e02b7204d1f87e7cf58ee5843 MD5 | raw file
  1"""
  2API operations on a history.
  3"""
  4import logging, os, string, shutil, urllib, re, socket
  5from cgi import escape, FieldStorage
  6from galaxy import util, datatypes, jobs, web, util
  7from galaxy.web.base.controller import *
  8from galaxy.util.sanitize_html import sanitize_html
  9from galaxy.model.orm import *
 10import galaxy.datatypes
 11from galaxy.util.bunch import Bunch
 12
 13log = logging.getLogger( __name__ )
 14
 15class HistoriesController( BaseAPIController, UsesHistory ):
 16
 17    @web.expose_api
 18    def index( self, trans, deleted='False', **kwd ):
 19        """
 20        GET /api/histories
 21        GET /api/histories/deleted
 22        Displays a collection (list) of histories.
 23        """               
 24        rval = []
 25        deleted = util.string_as_bool( deleted )
 26
 27        try:
 28            query = trans.sa_session.query( trans.app.model.History ).filter_by( user=trans.user, deleted=deleted ).order_by(
 29                desc(trans.app.model.History.table.c.update_time)).all()           
 30        except Exception, e:
 31            rval = "Error in history API"
 32            log.error( rval + ": %s" % str(e) )
 33            trans.response.status = 500
 34            
 35        if not rval:
 36            try:
 37                for history in query:
 38                    item = history.get_api_value(value_mapper={'id':trans.security.encode_id})
 39                    item['url'] = url_for( 'history', id=trans.security.encode_id( history.id ) )
 40                    rval.append( item )
 41            except Exception, e:
 42                rval = "Error in history API at constructing return list"
 43                log.error( rval + ": %s" % str(e) )
 44                trans.response.status = 500
 45        return rval
 46
 47    @web.expose_api
 48    def show( self, trans, id, deleted='False', **kwd ):
 49        """
 50        GET /api/histories/{encoded_history_id}
 51        GET /api/histories/deleted/{encoded_history_id}
 52        Displays information about a history.
 53        """
 54        history_id = id
 55        params = util.Params( kwd )
 56        deleted = util.string_as_bool( deleted )
 57        
 58        def traverse( datasets ):
 59            rval = {}
 60            states = trans.app.model.Dataset.states
 61            for key, state in states.items():
 62                rval[state] = 0
 63            for dataset in datasets:
 64                item = dataset.get_api_value( view='element' )
 65                if not item['deleted']:
 66                    rval[item['state']] = rval[item['state']] + 1
 67            return rval
 68            
 69        try:
 70            history = self.get_history( trans, history_id, check_ownership=True, check_accessible=True, deleted=deleted )
 71        except Exception, e:
 72            return str( e )
 73            
 74        try:
 75            item = history.get_api_value(view='element', value_mapper={'id':trans.security.encode_id})
 76            num_sets = len( [hda.id for hda in history.datasets if not hda.deleted] )            
 77            states = trans.app.model.Dataset.states
 78            state = states.ERROR
 79            if num_sets == 0:
 80                state = states.NEW
 81            else:
 82                summary = traverse(history.datasets)
 83                if summary[states.ERROR] > 0 or summary[states.FAILED_METADATA] > 0:
 84                    state = states.ERROR
 85                elif summary[states.RUNNING] > 0 or summary[states.SETTING_METADATA] > 0:
 86                    state = states.RUNNING
 87                elif summary[states.QUEUED] > 0:
 88                    state = states.QUEUED
 89                elif summary[states.OK] == num_sets:
 90                    state = states.OK                       
 91            item['contents_url'] = url_for( 'history_contents', history_id=history_id )
 92            item['state'] = state
 93            item['state_details'] = summary
 94        except Exception, e:
 95            item = "Error in history API at showing history detail"
 96            log.error(item + ": %s" % str(e))
 97            trans.response.status = 500
 98        return item
 99
100    @web.expose_api
101    def create( self, trans, payload, **kwd ):
102        """
103        POST /api/histories
104        Creates a new history.
105        """
106        params = util.Params( payload )
107        hist_name = None
108        if payload.get( 'name', None ):
109            hist_name = util.restore_text( payload['name'] )
110        new_history = trans.app.model.History( user=trans.user, name=hist_name )
111        
112        trans.sa_session.add( new_history )
113        trans.sa_session.flush()
114        item = new_history.get_api_value(view='element', value_mapper={'id':trans.security.encode_id})
115        return item
116
117    @web.expose_api
118    def delete( self, trans, id, **kwd ):
119        """
120        DELETE /api/histories/{encoded_history_id}
121        Deletes a history
122        """
123        history_id = id
124        # a request body is optional here
125        purge = False
126        if kwd.get( 'payload', None ):
127            purge = util.string_as_bool( kwd['payload'].get( 'purge', False ) )        
128        
129        try:
130            history = self.get_history( trans, history_id, check_ownership=True, check_accessible=False, deleted=True )
131        except Exception, e:
132            return str( e )
133
134        history.deleted = True
135        if purge and trans.app.config.allow_user_dataset_purge:
136            for hda in history.datasets:
137                if hda.purged:
138                    continue
139                hda.purged = True
140                trans.sa_session.add( hda )
141                trans.sa_session.flush()
142                if hda.dataset.user_can_purge:
143                    try:
144                        hda.dataset.full_delete()
145                        trans.sa_session.add( hda.dataset )
146                    except:
147                        pass
148                    trans.sa_session.flush()
149
150        trans.sa_session.flush()
151        return 'OK'
152
153    @web.expose_api
154    def undelete( self, trans, id, **kwd ):
155        """
156        POST /api/histories/deleted/{encoded_quota_id}/undelete
157        Undeletes a quota
158        """
159        history = self.get_history( trans, history_id, check_ownership=True, check_accessible=False, deleted=True )
160        history.deleted = False
161        trans.sa_session.add( history )
162        trans.sa_session.flush()
163        return 'OK'