server.py 26.6 KB
Newer Older
1
2
#
# Copyright (C) 2015 INRA
Celine Noirot's avatar
Celine Noirot committed
3
#
4
5
6
7
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
Celine Noirot's avatar
Celine Noirot committed
8
#
9
10
11
12
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
Celine Noirot's avatar
Celine Noirot committed
13
#
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import cherrypy
import cgi
import tempfile
import json
import sys
import datetime
from functools import wraps
import time
import os
import argparse

29
30
import logging

31
32
from argparse import ArgumentTypeError

33
34
from jflow.exceptions import RuleException, RuleIgnore

35
36
from collections import OrderedDict

37
38
39
from .workflows_manager import WorkflowsManager
from .config_reader import JFlowConfigReader
from .workflow import Workflow
Ibouniyamine Nabihoudine's avatar
Ibouniyamine Nabihoudine committed
40
from .parameter import browsefile, localfile, urlfile, inputfile, create_test_function, MiltipleAction, MiltipleAppendAction, MultipleParameters
41
from workflows.types import *
42
from . import utils
43
from cctools.util import time_format
Ibouniyamine Nabihoudine's avatar
Ibouniyamine Nabihoudine committed
44
from .utils import get_octet_string_representation
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

# function in charge to upload large files
class UploadFieldStorage(cgi.FieldStorage):
    """Our version uses a named temporary file instead of the default
    non-named file; keeping it visibile (named), allows us to create a
    2nd link after the upload is done, thus avoiding the overhead of
    making a copy to the destination filename."""

    def get_tmp_directory(self):
        jflowconf = JFlowConfigReader()
        return jflowconf.get_tmp_directory()

    def get_file_name(self):
        self.tmpfile = None
        # if this is a file object, just return the name of the file
        if hasattr( self.file, 'name' ):
            return self.file.name
        # if not, this is a cStringIO.StringO, write it down
        # and return the file name
        else:
            tmp_folder = self.get_tmp_directory()
            if not os.path.exists( tmp_folder ):
                try : os.mkdir(tmp_folder)
                except : pass
69
70
            fh = open(os.path.join(tmp_folder, self.filename), "wb+")
            fh_name = fh.name
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
            fh.write(self.file.getvalue())
            fh.close()
            return fh_name

    def __del__(self):
        try:
            self.file.close()
        except AttributeError:
            pass
        try:
            tmp_folder = self.get_tmp_directory()
            os.remove(os.path.join(tmp_folder, self.filename))
        except:
            pass

    def make_file(self, binary=None):
        tmp_folder = self.get_tmp_directory()
        if not os.path.exists( tmp_folder ):
            try : os.mkdir(tmp_folder)
            except : pass
        return tempfile.NamedTemporaryFile(dir=tmp_folder)


def noBodyProcess():
    """Sets cherrypy.request.process_request_body = False, giving
    us direct control of the file upload destination. By default
    cherrypy loads it to memory, we are directing it to disk."""
    cherrypy.request.process_request_body = False

cherrypy.tools.noBodyProcess = cherrypy.Tool('before_request_body', noBodyProcess)

# define functions in charge to handle cross domain calls
def CORS():
    cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
    cherrypy.response.headers['Access-Control-Allow-Methods'] = 'OPTIONS, GET, POST'
    cherrypy.response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Content-Range, Content-Disposition'
cherrypy.tools.CORS = cherrypy.Tool('before_finalize', CORS)

class JFlowJSONEncoder (json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.strftime( JFlowConfigReader().get_date_format() )
        else:
            return json.JSONEncoder.default(self, obj)

class JFlowServer (object):

    MULTIPLE_TYPE_SPLITER = "___"
    APPEND_PARAM_SPLITER = "::-::"
    JFLOW_WDATA = "data"

    def __init__(self):
        # Create a workflow manager to get access to our workflows
        self.wfmanager = WorkflowsManager()
        self.jflow_config_reader = JFlowConfigReader()
126
127

    @staticmethod
128
    def get_browse_root_dir():
129
        jflowconf = JFlowConfigReader()
130
        return jflowconf.get_browse_root_dir()
Celine Noirot's avatar
Celine Noirot committed
131

Jerome Mariette's avatar
Jerome Mariette committed
132
    @staticmethod
Jerome Mariette's avatar
Jerome Mariette committed
133
    def quickstart(server_class, config=None, daemon=False):
Celine Noirot's avatar
Celine Noirot committed
134

Jerome Mariette's avatar
Jerome Mariette committed
135
136
137
138
        # daemonize the server if asked to
        if daemon:
            from cherrypy.process.plugins import Daemonizer
            Daemonizer(cherrypy.engine).subscribe()
Celine Noirot's avatar
Celine Noirot committed
139

Jerome Mariette's avatar
Jerome Mariette committed
140
141
142
        # define the socket host and port
        jflowconf = JFlowConfigReader()
        socket_opts = jflowconf.get_socket_options()
Celine Noirot's avatar
Celine Noirot committed
143
        ssl_opts = jflowconf.get_ssl_files()
Jerome Mariette's avatar
Jerome Mariette committed
144
145
        
        # add the result directory
146
        if config is None or not '/' in config:
Jerome Mariette's avatar
Jerome Mariette committed
147
148
            config['/'] = {'tools.staticdir.root': jflowconf.get_work_directory()}
        else:
Jerome Mariette's avatar
Jerome Mariette committed
149
150
151
            link = os.path.join(config['/']['tools.staticdir.root'], "data")
            if not os.path.islink(link):
                os.symlink(jflowconf.get_work_directory(), link)
Celine Noirot's avatar
Celine Noirot committed
152

Jerome Mariette's avatar
Jerome Mariette committed
153
154
        config[os.path.join('/', JFlowServer.JFLOW_WDATA)] = {'tools.staticdir.on'  : True,
                                                              'tools.staticdir.dir' : jflowconf.get_work_directory()}
Celine Noirot's avatar
Celine Noirot committed
155

Jerome Mariette's avatar
Jerome Mariette committed
156
157
158
        # remove any limit on the request body size; cherrypy's default is 100MB
        # (maybe we should just increase it ?)
        cherrypy.server.max_request_body_size = 0
Celine Noirot's avatar
Celine Noirot committed
159

Jerome Mariette's avatar
Jerome Mariette committed
160
161
162
        # increase server socket timeout to 60s; we are more tolerant of bad
        # quality client-server connections (cherrypy's default is 10s)
        cherrypy.server.socket_timeout = 60
Celine Noirot's avatar
Celine Noirot committed
163

Jerome Mariette's avatar
Jerome Mariette committed
164
165
        cherrypy.config.update({'server.socket_host': socket_opts[0],
                                'server.socket_port': socket_opts[1]})
Celine Noirot's avatar
Celine Noirot committed
166

gerald2545's avatar
gerald2545 committed
167
168
169
170
171
        if len(ssl_opts)==3:
            cherrypy.config.update({'server.ssl_module': 'builtin',
                                    'server.ssl_certificate': ssl_opts[0],
                                'server.ssl_certificate_chain': ssl_opts[1],
                                'server.ssl_private_key': ssl_opts[2]})
Jerome Mariette's avatar
Jerome Mariette committed
172
173
        # start the server
        cherrypy.quickstart(server_class(), config=config)
Celine Noirot's avatar
Celine Noirot committed
174

175
176
177
178
179
180
181
    def jsonify(func):
        '''JSON and JSONP decorator for CherryPy'''
        @wraps(func)
        def wrapper(*args, **kw):
            value = func(*args, **kw)
            cherrypy.response.headers["Content-Type"] = "application/json"
            # if JSONP request
Celine Noirot's avatar
Celine Noirot committed
182
            if "callback" in kw:
183
                return ('%s(%s)' % (kw["callback"], json.dumps(value, cls=JFlowJSONEncoder))).encode('utf8')
184
            # else return the JSON
185
            else: return json.dumps(value, cls=JFlowJSONEncoder).encode('utf8')
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
        return wrapper

    def jsonify_workflow_status(self, workflow, init_to_zero=False):
        if workflow.start_time: start_time = time.asctime(time.localtime(workflow.start_time))
        else: start_time = "-"
        if workflow.start_time and workflow.end_time: elapsed_time = str(workflow.end_time-workflow.start_time)
        elif workflow.start_time: elapsed_time = str(time.time()-workflow.start_time)
        else: elapsed_time = "-"
        if workflow.end_time: end_time = time.asctime(time.localtime(workflow.end_time))
        else: end_time = "-"
        if init_to_zero:
            return {"id":utils.get_nb_string(workflow.id),
                    "name": workflow.name,
                    "status": Workflow.STATUS_STARTED,
                    "elapsed_time": str(elapsed_time),
                    "start_time": start_time,
                    "end_time": end_time,
                    "components": []}
        else:
            components = []
206
            components_status = workflow.get_components_status()
207
            for i, component in enumerate(workflow.get_components_nameid()):
208
                status_info = components_status[component]
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
                try: perc_waiting = (status_info["waiting"]*100.0)/status_info["tasks"]
                except: perc_waiting = 0
                try: perc_running = (status_info["running"]*100.0)/status_info["tasks"]
                except: perc_running = 0
                try: perc_failed = (status_info["failed"]*100.0)/status_info["tasks"]
                except: perc_failed = 0
                try: perc_aborted = (status_info["aborted"]*100.0)/status_info["tasks"]
                except: perc_aborted = 0
                try: perc_completed = (status_info["completed"]*100.0)/status_info["tasks"]
                except: perc_completed = 0
                components.append({"name": component,
                                  "elapsed_time": time_format(status_info["time"]),
                                  "total": status_info["tasks"],
                                  "waiting": status_info["waiting"],
                                  "failed": status_info["failed"],
                                  "running": status_info["running"],
                                  "aborted": status_info["aborted"],
                                  "completed": status_info["completed"]})

            status = {"id":utils.get_nb_string(workflow.id),
                      "errors": workflow.get_errors(),
                      "name": workflow.name,
                      "metadata": workflow.metadata,
                      "status": workflow.get_status(),
                      "elapsed_time": "-" if elapsed_time == "-" else str(datetime.timedelta(seconds=int(str(elapsed_time).split(".")[0]))),
                      "start_time": start_time,
                      "end_time": end_time,
                      "components": components}

            return status

    @cherrypy.expose
    @jsonify
    def get_available_workflows(self, **kwargs):
        workflows = []
244
245
246
247
        filter_groups = None
        select = False
        if 'filter_groups' in kwargs : filter_groups = kwargs['filter_groups'].split(',')
        if 'select' in kwargs : select = kwargs['select'] in ['True', 'true', '1', 1]
248

249
        wf_instances, wf_methodes = self.wfmanager.get_available_workflows(filter_groups = filter_groups  , select = select)
250
        for instance in wf_instances:
251
            parameters, parameters_per_groups, ordered_groups = [], {}, ["default"]
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
            for param in instance.get_parameters():
                # if it's a multiple action change the action by the name
                if param.action == MiltipleAction:
                    action = "MiltipleAction"
                elif param.action == MiltipleAppendAction:
                    action = "MiltipleAppendAction"
                else:
                    action = param.action
                try:
                    cparam_help = param.global_help
                except:
                    cparam_help = param.help
                hash_param = {"help": cparam_help,
                              "required": param.required,
                              "default": param.default,
                              "choices": param.choices,
                              "action": action,
                              "type": param.get_type(),
                              "name": param.name,
                              "display_name": param.display_name,
                              "group": param.group}
                if hash_param["type"] == "date":
                    hash_param["format"] = self.jflow_config_reader.get_date_format()
                    if hash_param["format"] == '%d/%m/%Y':
                        hash_param["format"] = 'dd/mm/yyyy'
                    elif hash_param["format"] == '%d/%m/%y':
                        hash_param["format"] = 'dd/mm/yy'
                    elif hash_param["format"] == '%Y/%m/%d':
                        hash_param["format"] = 'yyyy/mm/dd'
                    elif hash_param["format"] == '%y/%m/%d':
                        hash_param["format"] = 'yy/mm/dd'
283
284
                if param.rules is not None:
                    hash_param["rules"] = param.rules
285
286
287
288
289
290
291
292
293
294
295
296
297
                # if it's a multiple type add sub parameters
                if type(param.type) == MultipleParameters:
                    hash_param["sub_parameters"] = []
                    for sub_param in param.sub_parameters:
                        hash_param["sub_parameters"].append({"help": sub_param.help,
                              "required": sub_param.required,
                              "default": sub_param.default,
                              "choices": sub_param.choices,
                              "action": sub_param.action,
                              "type": sub_param.get_type(),
                              "name": param.name + JFlowServer.MULTIPLE_TYPE_SPLITER + sub_param.flag,
                              "display_name": sub_param.display_name,
                              "group": sub_param.group})
298
299
                        if hasattr(param, "paired_columns"):
                            hash_param["paired_columns"] = param.paired_columns
300
301
302
303
304
305
306
307
308
309
                        if hash_param["sub_parameters"][-1]["type"] == "date":
                            hash_param["sub_parameters"][-1]["format"] = self.jflow_config_reader.get_date_format()
                            if hash_param["sub_parameters"][-1]["format"] == '%d/%m/%Y':
                                hash_param["sub_parameters"][-1]["format"] = 'dd/mm/yyyy'
                            elif hash_param["sub_parameters"][-1]["format"] == '%d/%m/%y':
                                hash_param["sub_parameters"][-1]["format"] = 'dd/mm/yy'
                            elif hash_param["sub_parameters"][-1]["format"] == '%Y/%m/%d':
                                hash_param["sub_parameters"][-1]["format"] = 'yyyy/mm/dd'
                            elif hash_param["sub_parameters"][-1]["format"] == '%y/%m/%d':
                                hash_param["sub_parameters"][-1]["format"] = 'yy/mm/dd'
310
311
                        if sub_param.rules is not None:
                            hash_param["sub_parameters"][-1]["rules"] = sub_param.rules
312
                parameters.append(hash_param)
313
                if param.group in parameters_per_groups:
314
315
                    parameters_per_groups[param.group].append(hash_param)
                else: parameters_per_groups[param.group] = [hash_param]
316
317
                if param.group not in ordered_groups:
                    ordered_groups.append(param.group)
318
319
            workflows.append({"name": instance.name,
                              "help": instance.description,
Ibouniyamine Nabihoudine's avatar
Ibouniyamine Nabihoudine committed
320
                              "class": instance.__class__.__name__,
321
322
                              "parameters": parameters,
                              "parameters_per_groups": parameters_per_groups,
323
                              "groups": ordered_groups})
324
325
326
327
328
329
        return workflows

    @cherrypy.expose
    @jsonify
    def run_workflow(self, **kwargs):
        try:
330
            kwargs_modified = self.__update_kwargs(kwargs)
331
332
333
334
335
            workflow = self.wfmanager.run_workflow(kwargs_modified["workflow_class"], kwargs_modified)
            return { "status" : 0, "content" : self.jsonify_workflow_status(workflow, True) }
        except Exception as err:
            return { "status" : 1, "content" : str(err) }

336
337
338
    @cherrypy.expose
    @jsonify
    def validate_workflow(self, **kwargs):
339
        kwargs_modified = self.__update_kwargs(kwargs)
340
341
342
        workflow = self.wfmanager.get_workflow_by_class(kwargs_modified["workflow_class"])
        try:
            workflow.check_parameters_rules(kwargs_modified)
343
        except RuleException as e:
344
            return {"status": 1, "content": str(e)}
345
346
        except RuleIgnore:
            pass
347
348
        return {"status": 0}

349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
    @cherrypy.expose
    @jsonify
    def delete_workflow(self, **kwargs):
        self.wfmanager.delete_workflow(kwargs["workflow_id"])

    @cherrypy.expose
    @jsonify
    def rerun_workflow(self, **kwargs):
        workflow = self.wfmanager.rerun_workflow(kwargs["workflow_id"])
        return self.jsonify_workflow_status(workflow)

    @cherrypy.expose
    @jsonify
    def reset_workflow_component(self, **kwargs):
        workflow = self.wfmanager.reset_workflow_component(kwargs["workflow_id"], kwargs["component_name"])
        return self.jsonify_workflow_status(workflow)

    @cherrypy.expose
    def upload_light(self, **kwargs):
        uniq_directory = ""
369
        for key in list(kwargs.keys()):
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
            if key == "uniq_directory":
                uniq_directory = kwargs['uniq_directory']
            else:
                file_param = key

        # the file transfer can take a long time; by default cherrypy
        # limits responses to 300s; we increase it to 1h
        cherrypy.response.timeout = 3600

        # upload file by chunks
        file_dir = os.path.join( self.jflow_config_reader.get_tmp_directory(), uniq_directory )
        os.mkdir( file_dir )

        if isinstance(kwargs[file_param], list):
            for cfile in kwargs[file_param]:
385
                FH_sever_file = open(os.path.join(file_dir, cfile.filename), "w")
386
387
388
389
390
391
392
                while True:
                    data = cfile.file.read(8192)
                    if not data:
                        break
                    FH_sever_file.write(data)
                FH_sever_file.close()
        else:
393
            FH_sever_file = open(os.path.join(file_dir, kwargs[file_param].filename), "w")
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
            while True:
                data = kwargs[file_param].file.read(8192)
                if not data:
                    break
                FH_sever_file.write(data)
            FH_sever_file.close()

    @cherrypy.expose
    @cherrypy.tools.noBodyProcess()
    @cherrypy.tools.CORS()
    def upload(self):
        # the file transfer can take a long time; by default cherrypy
        # limits responses to 300s; we increase it to 1h
        cherrypy.response.timeout = 3600

        # convert the header keys to lower case
        lcHDRS = {}
411
        for key, val in cherrypy.request.headers.items():
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
            lcHDRS[key.lower()] = val

        # at this point we could limit the upload on content-length...
        # incomingBytes = int(lcHDRS['content-length'])

        # create our version of cgi.FieldStorage to parse the MIME encoded
        # form data where the file is contained
        formFields = UploadFieldStorage(fp=cherrypy.request.rfile,
                                        headers=lcHDRS,
                                        environ={'REQUEST_METHOD':'POST'},
                                        keep_blank_values=True)

        # we now create a link to the file, using the submitted
        # filename; if we renamed, there would be a failure because
        # the NamedTemporaryFile, used by our version of cgi.FieldStorage,
        # explicitly deletes the original filename
428
        for current in list(formFields.keys()):
429
430
431
432
433
434
435
436
            if current != 'uniq_directory':
                currentFile = formFields[current]
                fileDir = os.path.join(self.jflow_config_reader.get_tmp_directory(), formFields.getvalue("uniq_directory"))
                os.mkdir(fileDir)
                if isinstance(currentFile, list):
                    for cfile in currentFile:
                        os.link(
                                cfile.get_file_name(),
437
                                os.path.join(fileDir, cfile.filename)
438
439
440
441
                        )
                else:
                    os.link(
                            currentFile.get_file_name(),
442
                            os.path.join(fileDir, currentFile.filename)
443
444
445
446
447
448
449
450
                    )

    @cherrypy.expose
    @jsonify
    def get_workflows_status(self, **kwargs):
        status = []
        workflows = self.wfmanager.get_workflows(use_cache=True)
        for workflow in workflows:
451
            if "metadata_filter" in kwargs:
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
                is_ok = False
                for wf_meta in workflow.metadata:
                    for metadata in kwargs["metadata_filter"].split(","):
                        if wf_meta == metadata:
                            is_ok = True
                            break
                    if is_ok: break
                if is_ok: status.append(self.jsonify_workflow_status(workflow))
            else:
                status.append(self.jsonify_workflow_status(workflow))
        return status

    @cherrypy.expose
    @jsonify
    def get_workflow_status(self, **kwargs):
        workflow = self.wfmanager.get_workflow(kwargs["workflow_id"])
        if kwargs["display"] == "list":
            return self.jsonify_workflow_status(workflow)
        elif kwargs["display"] == "graph":
            g = workflow.get_execution_graph()
            status = self.jsonify_workflow_status(workflow)
            nodes = []
            for node in g.nodes():
                if Workflow.INPUTFILE_GRAPH_LABEL in g.node_attributes(node):
                    nodes.append({"name": node, "display_name": g.node_attributes(node)[1], "type": "inputfile"})
                elif Workflow.INPUTFILES_GRAPH_LABEL in g.node_attributes(node):
                    nodes.append({"name": node, "display_name": g.node_attributes(node)[1], "type": "inputfiles"})
                elif Workflow.INPUTDIRECTORY_GRAPH_LABEL in g.node_attributes(node):
Celine Noirot's avatar
Celine Noirot committed
480
                    nodes.append({"name": node, "display_name": g.node_attributes(node)[1], "type": "inputdirectory"})
481
482
483
484
485
486
                elif Workflow.COMPONENT_GRAPH_LABEL in g.node_attributes(node):
                    nodes.append({"name": node, "display_name": g.node_attributes(node)[1], "type": "component"})
            status["nodes"] = nodes
            status["edges"] = g.edges()
            return status

Floreal Cabanettes's avatar
Floreal Cabanettes committed
487
    def __update_kwargs(self, kwargs):
488
        kwargs_modified = {}
Celine Noirot's avatar
Celine Noirot committed
489

490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
        # handle MultiParameterList
        multi_sub_params = {}
        for key in list(kwargs.keys()):
            parts = key.split(JFlowServer.MULTIPLE_TYPE_SPLITER)
            if len(parts) == 3:
                if not parts[0] in kwargs_modified:
                    kwargs_modified[parts[0]] = []
                    multi_sub_params[parts[0]] = {}
                if parts[2] in multi_sub_params[parts[0]]:
                    multi_sub_params[parts[0]][parts[2]].append((parts[1], kwargs[key]))
                else:
                    multi_sub_params[parts[0]][parts[2]] = [(parts[1], kwargs[key])]

        for key in list(kwargs.keys()):
            parts = key.split(JFlowServer.MULTIPLE_TYPE_SPLITER)
            # split append values
            new_values = kwargs[key].split(JFlowServer.APPEND_PARAM_SPLITER)
            if len(new_values) == 1:
                new_values = new_values[0]
            # if this is a classic Parameter
            if len(parts) == 1:
                kwargs_modified[key] = new_values
            # if this is a MultiParameter
            elif len(parts) == 2:
                if parts[0] in kwargs_modified:
                    kwargs_modified[parts[0]].append((parts[1], new_values))
                else:
                    kwargs_modified[parts[0]] = [(parts[1], new_values)]

        # handle MultiParameterList
        for param in multi_sub_params:
            kwargs_modified[param] = []
            for sub_param in multi_sub_params[param]:
                kwargs_modified[param].append(multi_sub_params[param][sub_param])

        return kwargs_modified
Celine Noirot's avatar
Celine Noirot committed
526

527

528
529
530
531
    def _webify_outputs(self, web_path, path):
        work_dir  = self.jflow_config_reader.get_work_directory()
        if work_dir.endswith("/"): work_dir = work_dir[:-1]
        socket_opt = self.jflow_config_reader.get_socket_options()
532
533
534
535
536
537
        if not os.path.isdir(path):
            return {
                    'url':'http://' + socket_opt[0] + ':' + str(socket_opt[1]) + '/' + path.replace(work_dir, web_path),
                    'size': get_octet_string_representation(os.path.getsize(os.path.abspath(path))),
                    'extension': os.path.splitext(path)[1]
                   }
538
539
        else:  # Remove directories from the list
            return None
Floreal Cabanettes's avatar
Floreal Cabanettes committed
540
        # TODO: show output directories and add the possibility to browse them
541
542
543
544

    @cherrypy.expose
    @jsonify
    def get_workflow_outputs(self, **kwargs):
545
        on_disk_outputs, on_web_outputs = self.wfmanager.get_workflow_outputs(kwargs["workflow_id"]), OrderedDict()
546
        for cpt_name in list(on_disk_outputs.keys()):
547
548
549
            on_web_outputs[cpt_name] = {}
            for outf in on_disk_outputs[cpt_name]:
                on_web_outputs[cpt_name][outf] = self._webify_outputs(JFlowServer.JFLOW_WDATA, on_disk_outputs[cpt_name][outf])
550
551
                if on_web_outputs[cpt_name][outf] is None:  # Remove directories from the list
                    del on_web_outputs[cpt_name][outf]
552
553
554
555
556
557
558
        return on_web_outputs

    @cherrypy.expose
    @jsonify
    def validate_field(self, **kwargs):
        try:
            value_key = None
559
            for key in list(kwargs.keys()):
Celine Noirot's avatar
Celine Noirot committed
560
                if key != "type" and key != "callback" and key != "_" and key != "action":
561
562
563
564
565
                    value_key = key
                    break
            # if it's an append parameter, let's check each value
            if kwargs["action"] == "append":
                for cval in kwargs[value_key].split("\n"):
566
                    create_test_function(kwargs["type"])(cval)
567
            else:
568
                create_test_function(kwargs["type"])(kwargs[value_key])
569
            return True
570
        except Exception as e:
571
            return str(e)
572
573
574
575
576
577
578
579
580
581
582

    @staticmethod
    def sort_files(all_files, parent_directory):
        dirs = []
        files = []
        for f in all_files:
            if f[0] != ".":
                if os.path.isdir(parent_directory + "/" + f):
                    dirs.append(f)
                else:
                    files.append(f)
583
584
        dirs.sort(key=lambda s: s.lower())
        files.sort(key=lambda s: s.lower())
585
586
587
588
589
590
591
592
        return dirs + files

    @cherrypy.expose
    def get_user_files(self, **kwargs):
        checkbox = "<input type='checkbox' style='display: None;' />" if "multiSelect" in kwargs and kwargs["multiSelect"] else ""
        r=['<ul class="jqueryFileTree" style="display: none;">']
        try:
            r=['<ul class="jqueryFileTree" style="display: none;">']
593
            d=kwargs["dir"] if kwargs["dir"] != "/" else self.get_browse_root_dir()
594
595
596
597
598
599
600
601
602
603
604
605
            for f in self.sort_files(os.listdir(d), d):
                ff=os.path.join(d,f)
                if os.path.isdir(ff):
                    r.append('<li class="directory collapsed"><a rel="%s/">%s</a></li>' % (ff,f))
                else:
                    e=os.path.splitext(f)[1][1:] # get .ext and remove dot
                    r.append(('<li class="file ext_%s">' + str(checkbox) + '<a rel="%s">%s</a></li>') % (e,ff,f))
            r.append('</ul>')
        except Exception as e:
            r.append('Could not load directory: %s' % str(e))
        r.append('</ul>')
        return ''.join(r)