goa/tools/laxctl.py
branchtls-sprint
changeset 1802 d628defebc17
parent 1131 544609e83317
child 1977 606923dff11b
equal deleted inserted replaced
1801:672acc730ce5 1802:d628defebc17
    21 APPLROOT = osp.abspath(osp.join(osp.dirname(osp.abspath(__file__)), '..'))
    21 APPLROOT = osp.abspath(osp.join(osp.dirname(osp.abspath(__file__)), '..'))
    22 
    22 
    23 
    23 
    24 def initialize_vregistry(applroot):
    24 def initialize_vregistry(applroot):
    25     # apply monkey patches first
    25     # apply monkey patches first
    26     from cubicweb.goa import do_monkey_patch    
    26     from cubicweb.goa import do_monkey_patch
    27     do_monkey_patch()
    27     do_monkey_patch()
    28     from cubicweb.goa.goavreg import GAERegistry
    28     from cubicweb.goa.goavreg import GAERegistry
    29     from cubicweb.goa.goaconfig import GAEConfiguration
    29     from cubicweb.goa.goaconfig import GAEConfiguration
    30     #WebConfiguration.ext_resources['JAVASCRIPTS'].append('DATADIR/goa.js')
    30     #WebConfiguration.ext_resources['JAVASCRIPTS'].append('DATADIR/goa.js')
    31     config = GAEConfiguration('toto', applroot)
    31     config = GAEConfiguration('toto', applroot)
    32     vreg = GAERegistry(config)
    32     vreg = GAERegistry(config)
    33     vreg.set_schema(config.load_schema())
    33     vreg.set_schema(config.load_schema())
    34     return vreg
    34     return vreg
    35         
    35 
    36 def alistdir(directory):
    36 def alistdir(directory):
    37     return [osp.join(directory, f) for f in os.listdir(directory)]
    37     return [osp.join(directory, f) for f in os.listdir(directory)]
    38 
    38 
    39 
    39 
    40 class LaxCommand(Command):
    40 class LaxCommand(Command):
    41     """base command class for all lax commands
    41     """base command class for all lax commands
    42     creates vreg, schema and calls 
    42     creates vreg, schema and calls
    43     """
    43     """
    44     min_args = max_args = 0
    44     min_args = max_args = 0
    45 
    45 
    46     def run(self, args):
    46     def run(self, args):
    47         self.vreg = initialize_vregistry(APPLROOT)
    47         self.vreg = initialize_vregistry(APPLROOT)
    48         self._run(args)
    48         self._run(args)
    49         
    49 
    50 
    50 
    51 class GenerateSchemaCommand(LaxCommand):
    51 class GenerateSchemaCommand(LaxCommand):
    52     """generates the schema's png file"""
    52     """generates the schema's png file"""
    53     name = 'genschema'
    53     name = 'genschema'
    54 
    54 
    55     def _run(self, args):
    55     def _run(self, args):
    56         assert not args, 'no argument expected'
    56         assert not args, 'no argument expected'
    57         from yams import schema2dot        
    57         from yams import schema2dot
    58         schema = self.vreg.schema
    58         schema = self.vreg.schema
    59         skip_rels = ('owned_by', 'created_by', 'identity', 'is', 'is_instance_of')
    59         skip_rels = ('owned_by', 'created_by', 'identity', 'is', 'is_instance_of')
    60         path = osp.join(APPLROOT, 'data', 'schema.png')
    60         path = osp.join(APPLROOT, 'data', 'schema.png')
    61         schema2dot.schema2dot(schema, path, #size=size,
    61         schema2dot.schema2dot(schema, path, #size=size,
    62                               skiprels=skip_rels, skipmeta=True)
    62                               skiprels=skip_rels, skipmeta=True)
   105 
   105 
   106 
   106 
   107 class GetSessionIdHandler(urllib2.HTTPRedirectHandler):
   107 class GetSessionIdHandler(urllib2.HTTPRedirectHandler):
   108     def __init__(self, config):
   108     def __init__(self, config):
   109         self.config = config
   109         self.config = config
   110         
   110 
   111     def http_error_303(self, req, fp, code, msg, headers):
   111     def http_error_303(self, req, fp, code, msg, headers):
   112         cookie = SimpleCookie(headers['Set-Cookie'])
   112         cookie = SimpleCookie(headers['Set-Cookie'])
   113         sessionid = cookie['__session'].value
   113         sessionid = cookie['__session'].value
   114         print 'session id', sessionid
   114         print 'session id', sessionid
   115         setattr(self.config, 'cookie', '__session=' + sessionid)
   115         setattr(self.config, 'cookie', '__session=' + sessionid)
   116         return 1 # on exception should be raised
   116         return 1 # on exception should be raised
   117 
   117 
   118     
   118 
   119 class URLCommand(LaxCommand):
   119 class URLCommand(LaxCommand):
   120     """abstract class for commands doing stuff by accessing the web application
   120     """abstract class for commands doing stuff by accessing the web application
   121     """
   121     """
   122     min_args = max_args = 1
   122     min_args = max_args = 1
   123     arguments = '<site url>'
   123     arguments = '<site url>'
   136          {'short': 'p', 'type' : 'string', 'metavar': 'password',
   136          {'short': 'p', 'type' : 'string', 'metavar': 'password',
   137           'default': None,
   137           'default': None,
   138           'help': 'user password instead of giving raw cookie string (require '
   138           'help': 'user password instead of giving raw cookie string (require '
   139           'lax based authentication).'}),
   139           'lax based authentication).'}),
   140         )
   140         )
   141     
   141 
   142     def _run(self, args):
   142     def _run(self, args):
   143         baseurl = args[0]
   143         baseurl = args[0]
   144         if not baseurl.startswith('http'):
   144         if not baseurl.startswith('http'):
   145             baseurl = 'http://' + baseurl
   145             baseurl = 'http://' + baseurl
   146         if not baseurl.endswith('/'):
   146         if not baseurl.endswith('/'):
   152             print 'opening session for', self.config.user
   152             print 'opening session for', self.config.user
   153             opener = urllib2.build_opener(GetSessionIdHandler(self.config))
   153             opener = urllib2.build_opener(GetSessionIdHandler(self.config))
   154             urllib2.install_opener(opener)
   154             urllib2.install_opener(opener)
   155             data = urlencode(dict(__login=self.config.user,
   155             data = urlencode(dict(__login=self.config.user,
   156                                   __password=self.config.password))
   156                                   __password=self.config.password))
   157             self.open_url(urllib2.Request(baseurl, data))            
   157             self.open_url(urllib2.Request(baseurl, data))
   158         opener = urllib2.build_opener(NoRedirectHandler())
   158         opener = urllib2.build_opener(NoRedirectHandler())
   159         urllib2.install_opener(opener)        
   159         urllib2.install_opener(opener)
   160         self.do_base_url(baseurl)
   160         self.do_base_url(baseurl)
   161 
   161 
   162     def build_req(self, url):
   162     def build_req(self, url):
   163         req = urllib2.Request(url)
   163         req = urllib2.Request(url)
   164         if self.config.cookie:
   164         if self.config.cookie:
   165             req.headers['Cookie'] = self.config.cookie
   165             req.headers['Cookie'] = self.config.cookie
   166         return req
   166         return req
   167     
   167 
   168     def open_url(self, req):
   168     def open_url(self, req):
   169         try:
   169         try:
   170             return urllib2.urlopen(req)
   170             return urllib2.urlopen(req)
   171         except urllib2.HTTPError, ex:
   171         except urllib2.HTTPError, ex:
   172             if ex.code == 302:
   172             if ex.code == 302:
   192         match = re.search(r'<div class="message">(.*?)</div>', data.read(), re.M|re.S)
   192         match = re.search(r'<div class="message">(.*?)</div>', data.read(), re.M|re.S)
   193         if match:
   193         if match:
   194             msg = remove_html_tags(match.group(1))
   194             msg = remove_html_tags(match.group(1))
   195             print msg
   195             print msg
   196             return msg
   196             return msg
   197         
   197 
   198     def do_base_url(self, baseurl):
   198     def do_base_url(self, baseurl):
   199         raise NotImplementedError()
   199         raise NotImplementedError()
   200 
   200 
   201         
   201 
   202 class DSInitCommand(URLCommand):
   202 class DSInitCommand(URLCommand):
   203     """initialize the datastore"""
   203     """initialize the datastore"""
   204     name = 'db-init'
   204     name = 'db-init'
   205 
   205 
   206     options = URLCommand.options + (
   206     options = URLCommand.options + (
   208          {'short': 's', 'type' : 'int', 'metavar': 'nb seconds',
   208          {'short': 's', 'type' : 'int', 'metavar': 'nb seconds',
   209           'default': None,
   209           'default': None,
   210           'help': 'number of seconds to wait between each request to avoid '
   210           'help': 'number of seconds to wait between each request to avoid '
   211           'going out of quota.'}),
   211           'going out of quota.'}),
   212         )
   212         )
   213         
   213 
   214     def do_base_url(self, baseurl):
   214     def do_base_url(self, baseurl):
   215         req = self.build_req(baseurl + '?vid=contentinit')
   215         req = self.build_req(baseurl + '?vid=contentinit')
   216         while True:
   216         while True:
   217             try:
   217             try:
   218                 data = self.open_url(req)
   218                 data = self.open_url(req)
   238     name = "cleansessions"
   238     name = "cleansessions"
   239     def do_base_url(self, baseurl):
   239     def do_base_url(self, baseurl):
   240         req = self.build_req(baseurl + '?vid=cleansessions')
   240         req = self.build_req(baseurl + '?vid=cleansessions')
   241         data = self.open_url(req)
   241         data = self.open_url(req)
   242         self.extract_message(data)
   242         self.extract_message(data)
   243             
   243 
   244     
   244 
   245 register_commands([GenerateSchemaCommand,
   245 register_commands([GenerateSchemaCommand,
   246                    PopulateDataDirCommand,
   246                    PopulateDataDirCommand,
   247                    DSInitCommand,
   247                    DSInitCommand,
   248                    CleanSessionsCommand,
   248                    CleanSessionsCommand,
   249                    ])
   249                    ])
   250 
   250 
   251 def run():
   251 def run():
   252     main_run(sys.argv[1:])
   252     main_run(sys.argv[1:])
   253     
   253 
   254 if __name__ == '__main__':
   254 if __name__ == '__main__':
   255     run()
   255     run()