views.py 56.4 KB
Newer Older
BERJON Matthieu's avatar
BERJON Matthieu committed
1
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-
"""Main view module

This module handles most of the front-end for the Allgo system. You'll find
all the logic (controller) in an MVC pattern.

Attributes:
    log: module level variable to save information as a log data.

"""
# Python standard libraries
12
import glob
BERJON Matthieu's avatar
BERJON Matthieu committed
13
import io
14
import itertools
15
16
import json
import logging
17
import re
18
import os
19
import re
20
import shutil
21
import tempfile
22
import zipfile
23

BERJON Matthieu's avatar
BERJON Matthieu committed
24
# Third party imports
25
26
27
import iso8601
import natsort
import requests
28
import robot_detection
29
from django.conf import settings
30
from django.contrib import messages
31
from django.contrib.auth.forms import PasswordChangeForm
32
from django.contrib.auth.mixins import LoginRequiredMixin
BERJON Matthieu's avatar
BERJON Matthieu committed
33
from django.contrib.auth.models import User
34
from django.contrib.contenttypes.models import ContentType
35
from django.contrib.messages.views import SuccessMessageMixin
36
from django.core.exceptions import ObjectDoesNotExist
37
from django.core.validators import ValidationError
CAMPION Sebastien's avatar
CAMPION Sebastien committed
38
from django.core.urlresolvers import reverse
39
from django.db import transaction
BERJON Matthieu's avatar
BERJON Matthieu committed
40
from django.db.models import Count
41
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect, FileResponse, Http404
BERJON Matthieu's avatar
BERJON Matthieu committed
42
from django.shortcuts import render, get_object_or_404, redirect
43
from django.urls import reverse, reverse_lazy
44
from django.utils.crypto import get_random_string
45
from django.utils.text import slugify
46
from django.views.decorators.csrf import csrf_exempt
BERJON Matthieu's avatar
BERJON Matthieu committed
47
from django.views.generic import (
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
48
49
50
    CreateView,
    DeleteView,
    DetailView,
51
    FormView,
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
52
53
54
55
56
    ListView,
    RedirectView,
    TemplateView,
    UpdateView,
    View,
BERJON Matthieu's avatar
BERJON Matthieu committed
57
)
58
from django.views.generic.detail import SingleObjectMixin
BERJON Matthieu's avatar
BERJON Matthieu committed
59
from taggit.models import Tag
BERJON Matthieu's avatar
BERJON Matthieu committed
60

BERJON Matthieu's avatar
BERJON Matthieu committed
61
from .forms import (
CAMPION Sebastien's avatar
cosmit    
CAMPION Sebastien committed
62
63
64
65
66
    UserForm,
    HomeSignupForm,
    JobForm,
    SSHForm,
    RunnerForm,
67
68
    WebappForm,
    WebappSandboxForm,
69
    WebappImportForm,
CAMPION Sebastien's avatar
cosmit    
CAMPION Sebastien committed
70
)
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
71
# Local imports
BAIRE Anthony's avatar
BAIRE Anthony committed
72
import config
73
from .helpers import get_base_url, get_ssh_data, upload_data, notify_controller, lookup_job_file, get_request_user, query_webapps_for_user
74
from .mixins import UserAccessMixin, ProviderAccessMixin, AllAccessMixin, JobAuthMixin
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
75
76
from .models import (
    AllgoUser,
77
    DockerOs,
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
78
    Job,
79
    JobQueue,
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
80
81
82
    Quota,
    Runner,
    Webapp,
83
    WebappParameter,
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
84
    WebappVersion,
BERJON Matthieu's avatar
BERJON Matthieu committed
85
    Tos,
86
    UserAgreement,
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
87
)
BAIRE Anthony's avatar
BAIRE Anthony committed
88
from .signals import job_post_save
89
from .templatetags.converters import status_icon
BERJON Matthieu's avatar
BERJON Matthieu committed
90

BERJON Matthieu's avatar
BERJON Matthieu committed
91
# Start logger
92
log = logging.getLogger('allgo')
CAMPION Sebastien's avatar
CAMPION Sebastien committed
93

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
def error_handler(status, reason, default, request, exception=None):
    """Generic error handler

    Since django is unable to handle per-app error handlers, we have to define
    global ones.

    The behaviour of this view is to generate a json-formatted message
    {"error": "something"} when the url starts with /api/, otherwise it just
    uses django's default error handler.
    """
    if request.path_info.startswith("/api/"):
        return JsonResponse({"error": "%d %s" % (status, reason)}, status=status)
    else:
        return default(request, exception)

CAMPION Sebastien's avatar
CAMPION Sebastien committed
109

BAIRE Anthony's avatar
BAIRE Anthony committed
110
class IndexDetail(AllAccessMixin, TemplateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
111
112
113
114
115
116
117
118
119
    """Home view

    Generate the home as a standard `TemplateView` by calling a specific
    template. Most of the data are handled in the template itself, only few
    contexte data are provided for specific use.

    Attributes:
        template_name:  filename of the template used.

120
    """
BERJON Matthieu's avatar
BERJON Matthieu committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        """ Generate specific data to pass on in the context of the template.

        Returns:
            user_nb (int): number of users recorded in the database.
            webapp_nb (int): number of webapps recorded in the database.
            job_nb (int): number of jobs recorded in the database.
            signup_form: form specific for signin-up directly on the home page.
        """
        context = super(IndexDetail, self).get_context_data(**kwargs)
        users = User.objects.all().count()
        webapps = Webapp.objects.all().count()
        jobs = Job.objects.all().count()

        context['user_nb'] = users
        context['webapp_nb'] = webapps
        context['job_nb'] = jobs
        context['signup_form'] = HomeSignupForm()

        return context
BERJON Matthieu's avatar
BERJON Matthieu committed
143
144


BAIRE Anthony's avatar
BAIRE Anthony committed
145
146
147
148
149
150
151
152
153
# Legacy views
class LegacyWebappDetail(SingleObjectMixin, RedirectView):
    model = Webapp
    permanent = True
    slug_field = "docker_name"
    def get_redirect_url(self, **kwargs):
        return reverse("main:webapp_detail",
                args=(self.get_object().docker_name,))

154
155
# WEBAPPS
# -----------------------------------------------------------------------------
BAIRE Anthony's avatar
BAIRE Anthony committed
156
157
158

# FIXME: should merge WebappList with UserWebappList
# FIXME: should filter out webapps that have not published versions and that do not belong to the current user
BAIRE Anthony's avatar
BAIRE Anthony committed
159
class WebappList(AllAccessMixin, ListView):
BERJON Matthieu's avatar
BERJON Matthieu committed
160
    """ Display a paginated list of available webapps.
161

BERJON Matthieu's avatar
BERJON Matthieu committed
162
163
    The webapps are filtered from the most recent to the oldest and no private
    apps are displayed.
164

BERJON Matthieu's avatar
BERJON Matthieu committed
165
166
167
168
169
170
171
    Attributes:
        model:  Webapp model is used.
        context_object_name:    the name used in the template to display each
                                variable.
        paginate_by: the number of occurences per page
        template_name: name of the template loaded with this view.
        queryset: a specific queryset designed to filter the data.
172

BERJON Matthieu's avatar
BERJON Matthieu committed
173
174
175
    Todo:
        - the number of occurences per page could be loaded from the config
        file.
176
177

    """
BERJON Matthieu's avatar
BERJON Matthieu committed
178
    model = Webapp
BERJON Matthieu's avatar
BERJON Matthieu committed
179
    context_object_name = 'webapps'
BERJON Matthieu's avatar
BERJON Matthieu committed
180
181
    paginate_by = 10
    template_name = 'webapp_list.html'
182

183
184
    def get_queryset(self):
        return query_webapps_for_user(self.request.user).order_by('-created_at')
BERJON Matthieu's avatar
BERJON Matthieu committed
185

BAIRE Anthony's avatar
BAIRE Anthony committed
186
class UserWebappList(AllAccessMixin, ListView):
BERJON Matthieu's avatar
BERJON Matthieu committed
187
188
189
190
191
192
193
194
195
196
197
198
199
    """List of user's webapp

    Returns all the webapps owned by a specific user. Only the user can its
    apps.

    Attributes:
        model: database model
        context_object_name: variable name used in the template to display the
                            data.
        paginate_by: number of occurences by page.
        template_name: template filename.
                            
    """
BERJON Matthieu's avatar
BERJON Matthieu committed
200
201
202
203
204
205
206
    model = Webapp
    context_object_name = 'webapps'
    paginate_by = 10
    template_name = 'webapp_list.html'

    def get_queryset(self):
        """Filter apps for a given user"""
BAIRE Anthony's avatar
BAIRE Anthony committed
207
        # FIXME: infoleak: any user can display all the apps of any user
BERJON Matthieu's avatar
BERJON Matthieu committed
208
209
210
211
212
        user = User.objects.get(username=self.kwargs['username'])
        queryset = Webapp.objects.filter(user=user)
        return queryset


213
class WebappUpdate(UserAccessMixin, SuccessMessageMixin, UpdateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
214
215
216
217
218
219
220
221
    """Form to update the webapp data

    Attributes:
        form_class: form object.
        template_name: template filename.
        success_message: message when the form is properly submitted.

    """
222
223
    form_class = WebappForm
    template_name = 'webapp_add_update.html'
BERJON Matthieu's avatar
BERJON Matthieu committed
224
    success_message = 'Your app has been successfully updated.'
225
    error_message = 'The email doesn\'t belong to any registered user. Please enter a valid owner email address.'
BERJON Matthieu's avatar
BERJON Matthieu committed
226
227

    def get_success_url(self):
228
229
        """If successful redirect to the webapp details page"""
        return reverse('main:webapp_detail', args=(self.object.docker_name,))
BERJON Matthieu's avatar
BERJON Matthieu committed
230
231

    def get_object(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
232
        """Returns the object according to its docker name or a 404 error"""
BERJON Matthieu's avatar
BERJON Matthieu committed
233
234
235
236
        data = self.kwargs.get('docker_name', None)
        queryset = get_object_or_404(Webapp, docker_name=data, user_id=self.request.user.id)
        return queryset

BAIRE Anthony's avatar
BAIRE Anthony committed
237
238
239
    def get_context_data(self, **kwargs):
        ctx=super().get_context_data(**kwargs)
        ctx["action"] = "Update"
240
241
242
243
244

        # we expand the 'advanced' tab if any of its field has a validation error
        ctx["show_advanced"] = bool(set(ctx["form"].errors)
                .intersection(ctx["form"].ADVANCED_FIELDS))

BAIRE Anthony's avatar
BAIRE Anthony committed
245
246
        return ctx

247
248
249
250
251
252
    def get_form(self):
        form = super().get_form()
        if not self.request.user.is_superuser:
            form.fields['memory_limit_mb'].widget.attrs['readonly'] = True
        return form

BERJON Matthieu's avatar
BERJON Matthieu committed
253
    def form_valid(self, form):
BERJON Matthieu's avatar
BERJON Matthieu committed
254
        """Save data coming from the form in the database """
BERJON Matthieu's avatar
BERJON Matthieu committed
255
        obj = form.save(commit=False)
256

BERJON Matthieu's avatar
BERJON Matthieu committed
257
258
259
        try:
            user = User.objects.get(username=form.cleaned_data['owner'])
            obj.user_id = user.id
260
            obj.memory_limit = form.get_memory_limit(self.request)
BERJON Matthieu's avatar
BERJON Matthieu committed
261
            form.save()
BERJON Matthieu's avatar
BERJON Matthieu committed
262
263
            # Add the tag to the database (specific because it's a many to 
            # many relationship)
264
            form.save_m2m()
BERJON Matthieu's avatar
BERJON Matthieu committed
265
            if user != self.request.user:
266
                messages.success(self.request, self.success_message)
BERJON Matthieu's avatar
BERJON Matthieu committed
267
268
                return redirect('main:user_webapp_list', self.request.user.username)
            else:
269
                return super().form_valid(form)
BERJON Matthieu's avatar
BERJON Matthieu committed
270
        except User.DoesNotExist:
271
            messages.error(self.request, self.error_message)
272
            return super().form_invalid(form)
BERJON Matthieu's avatar
BERJON Matthieu committed
273
274


275
class WebappCreate(ProviderAccessMixin, SuccessMessageMixin, CreateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
276
277
278
279
280
281
282
283
284
285
    """Create a new webapp

    Attributes:
        model: model to use in this class.
        form_class: form object passed to the template.
        success_message: successfull message sent to the template
        template_name: template filename.
        group_required: groups that user must belong to.

    """
286
287
288
    model = Webapp
    form_class = WebappForm
    success_message = 'Webapp created successfully.'
289
    template_name = 'webapp_add_update.html'
290
    #  group_required = ['inria', ]
291
292

    def get_success_url(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
293
        """If successful redirect to the webapp list page"""
294
        return reverse('main:webapp_sandbox_panel', args=(self.webapp.docker_name,))
295

296
297
298
299
300
301
    def get_form(self):
        form = super().get_form()
        if not self.request.user.is_superuser:
            form.fields['memory_limit_mb'].widget.attrs['readonly'] = True
        return form

BAIRE Anthony's avatar
BAIRE Anthony committed
302
303
304
    def get_context_data(self, **kwargs):
        ctx=super().get_context_data(**kwargs)
        ctx["action"] = "Create"
305
        ctx["show_advanced"] = False
BAIRE Anthony's avatar
BAIRE Anthony committed
306
307
        return ctx

308
    def form_valid(self, form):
BERJON Matthieu's avatar
BERJON Matthieu committed
309
        """Save data coming from the form in the database """
310
311
312
313
        obj = form.save(commit=False)
        obj.user_id = self.request.user.id
        if not form.cleaned_data['contact']:
            obj.contact = self.request.user.email
314
        obj.sandbox_state = Webapp.IDLE
315
316
317
        # Ensure that all specials characters are removed, spaces are replaced
        # by hyphens and everything is lower-cased
        obj.docker_name = slugify(form.cleaned_data['name'])
318
        obj.memory_limit = form.get_memory_limit(self.request)
319
320
321
322
323
324
325
326
327
328

        # validate the Webapp record before saving
        # (this is a safety measure, do not remove)
        # FIXME: currently this raises an exception if the slugify-generated
        #        docker_name does not comply with the model constraints
        #        (for example: 'root' and 'sshd' are reserved names)
        #        To solve this, i think we should let the user choose the
        #        docker_name
        obj.full_clean()

329
330
331
        obj.save()

        # set up the docker container for the app
332
        Quota(user=self.request.user, webapp=obj).save()
333
334
335
336
        # pass on the webapp data to get_successful_url to redirect with the
        # correct arguments (for instance the docker_name)
        self.webapp = obj
        return super().form_valid(form)
BERJON Matthieu's avatar
BERJON Matthieu committed
337

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def get_rails_webapp_metadata(*, webapp_id=None, docker_name=None):
    """Download the metadata of a webapp from the legacy rails server
    
    Must provide either `webapp_id` or `docker_name`, but not both
    """
    assert bool(webapp_id) != bool(docker_name)

    if docker_name:
        url = "%s/app/%s/export" % (config.env.ALLGO_IMPORT_URL, docker_name)
    else:
        url = "%s/webapp/%d/export" % (config.env.ALLGO_IMPORT_URL, webapp_id)
    try:
        # use a 1s timeout to avoid blocking the django thread if the rails
        # server is not responding
        rep = requests.get(url, timeout=1)
        if rep.status_code == 404:
            raise Http404()
        rep.raise_for_status()
        js = rep.json()
        if (webapp_id not in (None, js["id"])
                or docker_name not in ("", js["docker_name"])):
            raise Exception("rails returned a webapp with inconsistent id or docker_name")
        return js
    except Exception as e:
        log.error("webapp import error: failed to get %s (%s)", url, e)
        raise

365
class WebappImport(ProviderAccessMixin, SuccessMessageMixin, FormView):
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
    """Import a new webapp

    This only creates the Webapp entry (along with the tags and webapp
    parameters), versions are imported separately.

    Once the webapp is imported, the Webapp entry is created with
    imported=True which enables the WebappVersionImport view (for import the
    actual versions, including the docker images).

    A webapp can be imported only if the e-mail of the current user strictly
    matches the owner e-mail of the imported app. If not, then the app has to
    be imported by a superuser, who can then transfer its ownership to the
    requesting user.

    An imported webapp will keep the same id and docker_name (to preserve the
    published urls). The import fails the id or docker_name is already used by
    another webapp.

    """
    model = Webapp
    form_class = WebappImportForm
    success_message = 'Webapp imported successfully.'
    template_name = 'webapp_import.html'

    def get_success_url(self):
        return reverse('main:webapp_version_import', args=(self.object.docker_name,))

    def get_context_data(self, **kwargs):
        ctx=super().get_context_data()
        ctx["import_url"] = config.env.ALLGO_IMPORT_URL+"/apps"
396
397
        ctx["imported_apps"] = Webapp.objects.filter(
                imported=True, user=self.request.user).order_by("name")
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
        return ctx

    def form_valid(self, form):
        def error(msg = "500 Internal Server Error"):
            messages.error(self.request, "Import failed : " + msg)
            return self.form_invalid(form)

        # parse the form parameters an prepare the import url
        webapp_id = form.cleaned_data["webapp_id"]
        docker_name = form.cleaned_data["docker_name"]
        if bool(webapp_id) == bool(docker_name):
            return error("You must provide either a name or an id")
            
        # get the metadata from the rails server an store them in var 'js'
        try:
            js = get_rails_webapp_metadata(webapp_id=webapp_id,
                    docker_name=docker_name)
        except Http404:
            return error("application not found")
        except Exception as e:
            return error()

        webapp_id   = js["id"]
        docker_name = js["docker_name"]

        # ensure this app does not already exist locally
        if Webapp.objects.filter(docker_name=docker_name).exists():
            return error("webapp named %r already exists" % docker_name)
        if Webapp.objects.filter(id=webapp_id).exists():
            return error("webapp id %r already exists" % webapp_id)
        
        current_user = self.request.user
        if not current_user.is_superuser:
431
            # get the user EmailAddress that matches the owner of the imported app
432
433
            email_addr = current_user.email_addresses.filter(
                    email=js["user"]).first()
434

435
            # ensure this app has the same owner
436
            if email_addr is None:
437
438
439
                return error("""this webapp belongs to another user (different
                e-mail address). If this other e-mail address belongs to you,
                then you should add it to your profile.""")
440
441

            # ensure the user email is verified
442
            if not email_addr.verified:
443
444
445
446
                messages.error(self.request,
                        "Webapp %r belongs to %r but this address is still not verified"
                        % (docker_name, email_addr.email))
                return redirect("main:user_need_validation")
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468

        # We can import the webapp !

        webapp = Webapp(user=current_user, imported=True,
                docker_os=DockerOs.objects.first())
        # TODO: import logo+readme (but they are not yet implemented in django)
        for field_name in ("id", "docker_name", "name", "description",
                "contact", "default_quota", "entrypoint", "private",
                "memory_limit"):
            setattr(webapp, field_name, js[field_name])

        # try to use job queue with same name or fallback to the default queue
        webapp.job_queue = JobQueue.objects.filter(name=js["default_job_queue"]
                ).first() or JobQueue.objects.filter(is_default=True).first()

        webapp.save()

        # import the tags and parameters
        webapp.tags.add(*js["tags"])
        for param in js["parameters"]:
            if (param["value"], param["name"], param["detail"]) != (
                    None, None, None):
469
                WebappParameter(webapp=webapp,
470
                        name=param["name"], value=param["value"],
471
                        detail=param["detail"]).save()
472
473
474
475

        self.object = webapp
        return super().form_valid(form)

476
class WebappVersionImport(UserAccessMixin, DetailView):
477
478
479
480
481
482
483
484
485
486
487
488
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    """Import version

    This view is enabled only for webapps created with imported=True

    The GET view lists the current status of remote version along with the
    local version (if any). If the remote version can be imported, it displays
    a checkbox to allow requesting its import.

    The POST view creates the WebappVersion entries with state=IMPORT and
    notifies the controller (which performs the actual import). The import is
    considered done as soon as the entry reaches the COMMITTED state.
    """
    template_name = 'webapp_version_import.html'

    def get_object(self):
        """Returns the object according to its docker name or a 404 error"""
        data = self.kwargs.get('docker_name', None)
        queryset = get_object_or_404(Webapp, docker_name=data, user_id=self.request.user.id)
        return queryset

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        webapp = self.object

        if not webapp.imported:
            raise Http404()

        # url of this webapp on the legacy server
        ctx["import_url"] = "%s/app/%s" % (
                config.env.ALLGO_IMPORT_URL, webapp.docker_name)

        # get the webapp metadata from the legacy server
        remote_versions = get_rails_webapp_metadata(
                docker_name=webapp.docker_name)["versions"]

        # dict of local webapp versions (indexed by the number) 
        # (if multiple entries exist with the same number (this happens if a
        # commit/push/import is in progress), we keep the one with the highest
        # id)
        local_versions = {}
        for v in WebappVersion.objects.filter(webapp=webapp).exclude(
                state__in=(WebappVersion.ERROR,
                    WebappVersion.REPLACED)).order_by("id"):
            local_versions[v.number] = v

        # list of versions to be displayed on the page
        versions = {}
        for remote in remote_versions:
            number = remote["number"]
            assert number not in versions, "rails must not export duplicated versions"
            local_version = local_versions.get(number)
            in_progress = getattr(local_version, "state", None) == WebappVersion.IMPORT
            versions[number] = {
                    "number":    number,
                    "remote_ts": iso8601.parse_date(remote["updated_at"]),
                    "local_ts":         "-" if in_progress else getattr(local_version, "updated_at", ""),
                    "local_imported":   None if in_progress else getattr(local_version, "imported", None),
                    "in_progress":      in_progress,
                    }
        ctx["versions"] = natsort.versorted(versions.values(),
                key=lambda v: v["number"], reverse=True)

        return ctx

    def post(self, request, *, docker_name):
        webapp = self.get_object()
        if not webapp.imported:
            raise Http404()

        remote_versions = get_rails_webapp_metadata(
                docker_name=webapp.docker_name)["versions"]

        for remote in remote_versions:
            number = remote["number"]
            if request.POST.get("version_"+number):
                log.info("import version %s", number)
                version = WebappVersion.objects.update_or_create({
                    "imported": True,
                    "published":         remote["published"],
                    "description":       remote["changelog"],
                    "docker_image_size": remote["docker_image_size"],
                    },
                    webapp=webapp,
                    number=number,
                    state=WebappVersion.IMPORT)[0]
                version.created_at = remote["created_at"]
                version.updated_at = remote["updated_at"]
                version.save()

        transaction.on_commit(lambda: notify_controller(webapp))

        return HttpResponseRedirect(request.path_info)

BERJON Matthieu's avatar
BERJON Matthieu committed
570

571
class WebappJson(UserAccessMixin, DetailView):
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
    """json variant of the application details
    
    (used by the /aio/apps/<DOCKER_NAME>/events endpoint)
    """

    def get_object(self):
        """Returns the object according to its docker name or a 404 error"""
        data = self.kwargs.get('docker_name', None)
        queryset = get_object_or_404(Webapp, docker_name=data)
        return queryset

    def render_to_response(self, context, **kwargs):
        webapp = context["webapp"]
        return JsonResponse({
            "id":               webapp.id,
            "sandbox_state":    webapp.get_sandbox_state_display(),
            })

590
class WebappSandboxPanel(UserAccessMixin, TemplateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
591
592
593
594
595
596
597
598
    """Create a new sandbox for a given application

    Attributes:
        form_class: form object to pass on the template.
        model: model to use in this class
        template_name: template filename

    """
599
    template_name = 'webapp_sandbox_panel.html'
600
601

    def get_object(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
602
        """Returns the object according to its docker name or a 404 error"""
603
        data = self.kwargs.get('docker_name', None)
604
        queryset = get_object_or_404(Webapp, docker_name=data, user_id=self.request.user.id)
605
606
607
        return queryset

    def get_context_data(self, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
608
609
610
611
612
613
614
        """Recover data to pass on to the template context
        
        In order to give the user a feedback regarding the way to push its image
        to the registry, we need to pass both the webapp `docker_name` and the
        `registry` URL.

        """
615
        context = super().get_context_data(**kwargs)
616
        context['webapp'] = self.get_object()
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631

        context["ssh_command"] = "ssh%s %s@%s" % (
                (" -p %s" % config.env.ALLGO_SSH_PORT
                    if config.env.ALLGO_SSH_PORT != "22" else ""),
                (kwargs["docker_name"]),
                (config.env.ALLGO_SSH_HOST))

        # candidate docker os (start from scratch)
        context['docker_os_list'] = DockerOs.objects.all()

        # candidate versions (start from an existing version)
        versions = {}
        for state in (WebappVersion.READY, WebappVersion.COMMITTED):
            versions.update((v.number, v) for v in WebappVersion.objects.filter(
                webapp=context["webapp"], state=state))
632
633
        context['versions'] = natsort.versorted(versions.values(), key=lambda v: v.number)
        context['versions'].reverse()
634
635
        return context

636
637
638
    def post(self, request, *, docker_name):
        log.info("POST %r", request.POST)

639
        webapp = self.get_object()
640
641
        action = request.POST["action"]

BAIRE Anthony's avatar
BAIRE Anthony committed
642
643
644
645
646
        def stop_sandbox():
            webapp.sandbox_state = Webapp.STOPPING
            webapp.sandbox_version_id = None
            webapp.save()

647
648
        log.info("action %r", request.POST["action"])
        if action == "start":
BAIRE Anthony's avatar
BAIRE Anthony committed
649
650
651
652
653
            if webapp.sandbox_state != Webapp.IDLE:
                messages.error(request,
                        "unable to start sandbox %r because it not idle"
                        % webapp.name)
            else:
654
655
656
657
658
659
660
661
662
                if "webapp_version_id" in request.POST:
                    # start from an existing version
                    webapp.sandbox_version_id = int(request.POST["webapp_version_id"])
                else:
                    # start from scratch
                    webapp.docker_os_id = request.POST["docker_os_id"]
                    webapp.sandbox_version = None
                webapp.sandbox_state = Webapp.STARTING
                webapp.save()
BAIRE Anthony's avatar
BAIRE Anthony committed
663
                messages.success(request, "starting sandbox %r" % webapp.name)
664
665

        elif action == "commit":
BAIRE Anthony's avatar
BAIRE Anthony committed
666
667
668
669
670
            if webapp.sandbox_state != Webapp.RUNNING:
                messages.error(request,
                        "unable to commit sandbox %r because it is not running"
                        % webapp.name)
            else:
671
672
673
674
675
                # query previous active versions of this webapp
                previous = WebappVersion.objects.filter(webapp=webapp,
                            state__in = (WebappVersion.READY, WebappVersion.COMMITTED))
                extra = {}

676
677
                if request.POST["version-action"] == "replace-version":
                    number = request.POST["version-select"]
678
679
                    # keep the previous 'created_at' timestamp when replacing an image
                    extra["created_at"] = getattr(previous.filter(number=number).first(), "created_at")
680
681
                else:
                    number = request.POST["version-new"]
682
683
684

                    # ensure that this version number does not already exist
                    if previous.filter(number=number).exists():
685
686
687
                        messages.error(request, "unable to commit because version %r already exists"
                                " (if you want to overwrite this version, then use"
                                "  'replace version' instead)" % number)
BAIRE Anthony's avatar
BAIRE Anthony committed
688
                        return HttpResponseRedirect(request.path_info)
689

690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
                try:
                    version = WebappVersion(
                            webapp=webapp,
                            number=number,
                            state=WebappVersion.SANDBOX,
                            published=True,
                            description=request.POST["description"],
                            **extra)
                    version.save()
                except ValidationError as e:
                    if tuple(e.error_dict) != ("number",):
                        raise
                    messages.error(request,
                            "invalid version number (must be a valid docker tag)")
                else:
                    stop_sandbox()
706

707
708
                    messages.success(request, "committing sandbox %r version %r"
                            % (webapp.name, number))
709

710
711
        elif action == "rollback":
            if webapp.sandbox_state == Webapp.RUNNING:
BAIRE Anthony's avatar
BAIRE Anthony committed
712
                stop_sandbox()
BAIRE Anthony's avatar
BAIRE Anthony committed
713
714
715
716
                messages.success(request, "rolling back sandbox %r" % webapp.name)
            else:
                messages.error(request, "unable to roll back, sandbox %r is not running"
                        % webapp.name)
717
718
719

        elif action == "abort":
            if webapp.sandbox_state == Webapp.START_ERROR:
BAIRE Anthony's avatar
BAIRE Anthony committed
720
                stop_sandbox()
BAIRE Anthony's avatar
BAIRE Anthony committed
721
                messages.success(request, "reset sandbox %r" % webapp.name)
722
723
724
725
726

        elif action == "retry":
            if webapp.sandbox_state == Webapp.START_ERROR:
                webapp.sandbox_state = Webapp.STARTING
                webapp.save()
BAIRE Anthony's avatar
BAIRE Anthony committed
727
                messages.success(request, "starting sandbox %r" % webapp.name)
728
            elif webapp.sandbox_state == Webapp.STOP_ERROR:
BAIRE Anthony's avatar
BAIRE Anthony committed
729
                stop_sandbox()
BAIRE Anthony's avatar
BAIRE Anthony committed
730
                messages.success(request, "stopping sandbox %r" % webapp.name)
731

BAIRE Anthony's avatar
BAIRE Anthony committed
732
        log.debug("new sandbox state: %r -> %r",
733
                webapp.docker_name, webapp.get_sandbox_state_display())
734

BAIRE Anthony's avatar
BAIRE Anthony committed
735
736
737
738
739
        # NOTE: we return a 302 redirect to the same page (instead of rendering
        # it directly) to force the browser to make a separate GET request.
        # This prevent reexecuting the POST request if the user refreshes the
        # page.
        return HttpResponseRedirect(request.path_info)
740

741
742
743
# TAGS
# -----------------------------------------------------------------------------

BAIRE Anthony's avatar
BAIRE Anthony committed
744
class TagList(AllAccessMixin, ListView):
745
746
747
748
749
750
751
752
    """List all available tag along with their number of occurences

    Attributes:
        model: database model
        context_object_name: variable name used in the template to display the
                            data.
        template_name: template filename.
    """
BERJON Matthieu's avatar
BERJON Matthieu committed
753
    model = Tag
754
755
756
757
758
    context_object_name = 'tags'
    template_name = 'tag_list.html'

    def get_queryset(self):
        """Return all available tags
BERJON Matthieu's avatar
BERJON Matthieu committed
759

760
761
        Each tag return as well the number of webapps attached to it
        """
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787

        
        # Compute the list of tags with the count of webapps visible by this user
        #
        # We need a raw request because filtering on Count() is not supported
        # in django 1.11.
        #
        # In django>=2.0 we should be able to write something like:
        #    tags = Tag.objects.annotate(num_tag=Count('taggit_taggeditem_items',
        #                                              filter = Q(...)))
        #
    
        # list of webapp ids visible by the current user
        webapp_ids = tuple(itertools.chain(
            *query_webapps_for_user(self.request.user).values_list("id")))
        # webapp content id (to select onl the tags on Webapp objects)
        webapp_content_id = ContentType.objects.get(app_label="main", model="Webapp").id
        # compute the list of tags with the webapp count (in the webapp_ids subset)
        tags = Tag.objects.raw("""
            SELECT taggit_tag.*, count(*) as num_tag
                FROM taggit_tag JOIN taggit_taggeditem
                ON taggit_tag.id=taggit_taggeditem.tag_id
                WHERE content_type_id=%s AND object_id in %s
                GROUP BY tag_id
                """, (webapp_content_id, webapp_ids))

788
789
790
        return tags


BAIRE Anthony's avatar
BAIRE Anthony committed
791
class TagWebappList(AllAccessMixin, ListView):
792
793
794
795
796
797
798
799
800
    """List all available webapps for a given tag

    Attributes:
        model: database model
        context_object_name: variable name used in the template to display the
                            data.
        paginated_by: number of occurences per page.
        template_name: template filename.
    """
BERJON Matthieu's avatar
BERJON Matthieu committed
801
    model = Webapp
802
803
804
805
806
    context_object_name = 'webapps'
    paginated_by = 10
    template_name = 'tag_webapp_list.html'

    def get_queryset(self):
807
808
        return query_webapps_for_user(self.request.user
                ).filter(tags__slug=self.kwargs['slug'])
809

810
811
812
    def get_context_data(self, **kwargs):
        return super().get_context_data(tag=self.kwargs["slug"], **kwargs)

813

814
815
# PROFILE
# -----------------------------------------------------------------------------
816
class UserUpdate(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
817
818
819
820
821
822
823
    """Update the user profile

    Attributes:
        form_class: form object to pass on the template.
        template_name: template filename
        success_message: successfull message sent to the template
    """
824
    form_class = UserForm
825
    template_name = "user_update.html"
826
827
828
    success_message = 'Profile updated successfully.'

    def get_success_url(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
829
        """If successful redirect to the user page"""
830
831
832
        return reverse('main:user_detail')

    def get_object(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
833
        """Only get the User record for the user making the request"""
834
835
836
        return User.objects.get(username=self.request.user.username)

    def get_context_data(self, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
837
838
839
840
841
842
843
        """Recover data to pass on to the template

        In order to display specific data, I process the SSH key to get its
        fingerprint and comment. Both the SSH key, fingerprint, comment and
        token to context template.

        """
844
845
846
847
848
        queryset = AllgoUser.objects.get(user_id=self.request.user.id)
        key = queryset.sshkey
        token = queryset.token
        if key:
            fingerprint, comment = get_ssh_data(key)
BERJON Matthieu's avatar
BERJON Matthieu committed
849
            kwargs['sshkey'] = True
850
851
852
853
            kwargs['ssh_comment'] = comment
            kwargs['ssh_fingerprint'] = fingerprint
        if token:
            kwargs['token'] = token
854
855
856
857

        kwargs['agreements'] = UserAgreement.objects.filter(
                user=self.request.user).order_by("-created_at")
        
858
859
860
861
        return super(UserUpdate, self).get_context_data(**kwargs)


class UserToken(LoginRequiredMixin, RedirectView):
BERJON Matthieu's avatar
BERJON Matthieu committed
862
    """Regenerate the user token"""
863

864
865
    success_message = 'Token generated successfully.'

866
    def dispatch(self, request, *args, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
867
        """Generate the token and save it into the database"""
868
869
870
871
872
873
        queryset = AllgoUser.objects.get(user_id=self.request.user.id)
        queryset.token = get_random_string(length=32)
        queryset.save()
        return super(UserToken, self).dispatch(request, *args, **kwargs)

    def get_redirect_url(self, *args, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
874
        """Redirect the user to the user page and display a successful message"""
875
        messages.success(self.request, self.success_message)
876
877
        return reverse('main:user_detail')

BERJON Matthieu's avatar
BERJON Matthieu committed
878

879
class UserSSHAdd(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
880
881
882
883
884
885
886
    """Save a SSH key to the database.
    
    Attributes:
        form_class: form object to pass on the template.
        template_name: template filename
        success_message: successfull message sent to the template
    """
BERJON Matthieu's avatar
BERJON Matthieu committed
887
    form_class = SSHForm
888
    template_name = 'user_ssh_add.html'
BERJON Matthieu's avatar
BERJON Matthieu committed
889
890
891
    success_message = 'SSH key added successfully.'

    def get_success_url(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
892
        """If successful redirect to the user page"""
BERJON Matthieu's avatar
BERJON Matthieu committed
893
894
895
        return reverse('main:user_detail')

    def get_object(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
896
        """Only get the User record for the user making the request"""
BERJON Matthieu's avatar
BERJON Matthieu committed
897
        return AllgoUser.objects.get(user_id=self.request.user.id)
898
899
900


class UserSSHDelete(LoginRequiredMixin, RedirectView):
BERJON Matthieu's avatar
BERJON Matthieu committed
901
    """Delete the user SSH key"""
902

903
904
    success_message = 'The SSH key has been successfully deleted.'

905
    def dispatch(self, request, *args, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
906
        """Generate an empty SSH key and save it into the database"""
907
908
909
910
911
912
        queryset = AllgoUser.objects.get(user_id=request.user.id)
        queryset.sshkey = ''
        queryset.save()
        return super(UserSSHDelete, self).dispatch(request, *args, **kwargs)

    def get_redirect_url(self, *args, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
913
        """If successful redirect to the user page"""
914
        messages.success(self.request, self.success_message)
915
916
917
        return reverse('main:user_detail')


918
class UserPasswordUpdate(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
919
    """Update the user's password.
920
921
922

    We reuse the Django password form system in order to keep something robust
    even if it dedicates a specific view for it.
BERJON Matthieu's avatar
BERJON Matthieu committed
923
924
925
926
927
928

    Attributes:
        success_url: URL or handle where the user will be redirected.
        form_class: form object to pass on the template.
        template_name: template filename
        success_message: successfull message sent to the template
929
930
931
    """
    success_url = reverse_lazy('main:user_detail')
    form_class = PasswordChangeForm
932
    template_name = "user_password_update.html"
933
934
935
    success_message = 'Password updated successfully.'

    def get_object(self, queryset=None):
BERJON Matthieu's avatar
BERJON Matthieu committed
936
937
938
939
940
        """Return the user data
        
        Todo:
            - Not sure the relevance of getting this information to the template
        """
941
942
943
        return self.request.user

    def get_form_kwargs(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
944
        """Return the arguments related to the user"""
945
946
947
948
949
        kwargs = super(UserPasswordUpdate, self).get_form_kwargs()
        kwargs['user'] = kwargs.pop('instance')
        return kwargs

    def dispatch(self, request, *args, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
950
951
952
953
954
955
        """
        Todo:
            - I'm not sure why I wrote that and why it is useful in the present
              case. It needs to be investigated.

        """
956
957
        return super(UserPasswordUpdate, self) \
            .dispatch(request, *args, **kwargs)
BERJON Matthieu's avatar
BERJON Matthieu committed
958

959
960
961
962
963
964
965
966
967
968
969
class UserNeedValidation(LoginRequiredMixin, DetailView):
    """This page is displayed when the user has not completed the registration process

    Causes:
    - email address needs verification
    """
    template_name = "user_need_validation.html"

    def get_object(self):
        return None

970
971
972
973
    def get_context_data(self, **kwargs):

        # last ToS agreement by the user
        agreement = UserAgreement.objects.filter(user=self.request.user
974
                ).order_by("-created_at").first()
975
976
977
978
979
980
981
982
983
984
985

        # next ToS to be signed
        next_tos = Tos.get_latest()

        if agreement is not None and agreement.tos == next_tos:
            # latest agreement already signed
            next_tos = None

        return super().get_context_data(
                agreement=agreement, next_tos=next_tos, **kwargs)

986
    def get(self, request):
987
988
        if all(addr.verified for addr in request.user.email_addresses
                ) and request.user.has_agreed_tos:
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
            # redirect to the main page if validation is complete
            messages.success(request, "Your account is fully validated")
            return redirect("main:home")
        else:
            return super().get(request)

    def post(self, request):
        # re-send a confirmation e-mail if 'confirm_address_id' is provided
        try:
            email_addr = request.user.email_addresses.get(
                    id=request.POST["confirm_address_id"])
        except (KeyError, ValueError, ObjectDoesNotExist):
            pass
        else:
            if not email_addr.verified:
                email_addr.send_confirmation(request)
                messages.info(self.request, 
                        "Confirmation e-mail sent to %s" % email_addr.email)

1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
        # store user agreement
        if "yes_i_agree" in request.POST:
            try:
                tos = Tos.objects.get(id=int(request.POST["agree_tos_id"]))
            except (KeyError, ValueError, ObjectDoesNotExist):
                pass
            else:
                if UserAgreement.objects.get_or_create(
                        tos=tos, user=request.user)[1]:
                    messages.success(self.request,
                            "Terms of Service version %s agreed" % tos.version)

1020
1021
        return redirect(request.path_info)

BERJON Matthieu's avatar
BERJON Matthieu committed
1022
1023
1024
# JOBS
# -----------------------------------------------------------------------------

1025
class JobList(UserAccessMixin, ListView):
BERJON Matthieu's avatar
BERJON Matthieu committed
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
    """Display the list of jobs for a given identified user

    Attributes:
        model:  model used in the view.
        context_object_name:    the name used in the template to display each
                                variable.
        paginate_by: the number of occurences per page
        template_name: name of the template loaded with this view.
        redirect_field_name: None

    Todo:
        - Check the relevance of `redirect_field_name` and delete it if necessary
BERJON Matthieu's avatar
BERJON Matthieu committed
1038
1039
1040
1041
1042
1043
1044
1045
1046
    """
    model = Job
    context_object_name = 'job_list'
    template_name = 'job_list.html'
    paginate_by = 10
    redirect_field_name = 'redirect_to'

    def get_queryset(self):
        """Filter jobs for a given user"""
1047
1048
        queryset = Job.objects.filter(user_id=self.request.user.id
                ).exclude(state__in=(Job.DELETED, Job.ARCHIVED)).order_by('-id')
BERJON Matthieu's avatar
BERJON Matthieu committed
1049
        return queryset
BERJON Matthieu's avatar
BERJON Matthieu committed
1050

1051

1052
class JobDetail(JobAuthMixin, DetailView):
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
    """Get a job detail for a specific user

    Attributes:
        model:  model used in the view.
        context_object_name:    the name used in the template to display each
                                variable.
        template_name: name of the template loaded with this view.

    """
    model = Job
    template_name = 'job_detail.html'
    context_object_name = 'job'

    def get_context_data(self, **kwargs):
        """Recover the logs and files related to this job"""
BERJON Matthieu's avatar
BERJON Matthieu committed
1068
1069
        job = Job.objects.get(pk=self.object.pk)

1070
1071
1072
        if job.state == Job.DONE:
            # job is done
            # -> read the `allgo.log` file
1073
            log_file = os.path.join(job.data_dir, 'allgo.log')
1074
            try:
1075
                with open(log_file, 'r', errors="replace") as log_data:
BERJON Matthieu's avatar
BERJON Matthieu committed
1076
                    logs = log_data.read()
1077
1078
1079
1080
1081
1082
1083
            except OSError as e:
                logs = '(logs not available)'
                log.error("Log file not available for job #%d (%s)", job.id, e)
        else:
            # job is pending
            # -> logs will be streamed (ajax request)
            logs = ""
BERJON Matthieu's avatar
BERJON Matthieu committed
1084
1085
        kwargs['logs'] = logs

1086
1087
1088
        # Hide the logs panel if the job is not yet started
        kwargs["logs_hidden"] = "hidden" if job.state in (Job.NEW, Job.WAITING) else ""

BERJON Matthieu's avatar
BERJON Matthieu committed
1089
1090
        # Get the files and some metadata such as the webapp version
        webapp = Webapp.objects.get(docker_name=self.object.webapp.docker_name)
1091
1092
1093
1094
1095
1096

        # List all job files
        # NOTE: calling lookup_job_file is a security feature
        kwargs['files'] = [x for x in os.listdir(job.data_dir)
                if lookup_job_file(job.id, x)]

BERJON Matthieu's avatar
BERJON Matthieu committed
1097
        return super().get_context_data(**kwargs)
1098

1099
1100
    def render_to_response(self, context, **kwargs):
        if self.request.META.get("HTTP_ACCEPT") == "application/json":
1101
1102
            # json variant of the job details
            # (used by the /aio/jobs/<ID>/events endpoint)
1103
1104
1105
1106
            job = context["job"]
            return JsonResponse({
                "id":           job.id,
                "state":        job.get_state_display(),
1107
                "result":       job.get_result_display(),
1108
1109
1110
1111
1112
                "rendered_status": status_icon(job),
                "exec_time":    job.exec_time,
                })
        else:
            return super().render_to_response(context, **kwargs)
1113

1114

BAIRE Anthony's avatar
BAIRE Anthony committed
1115
class JobCreate(AllAccessMixin, SuccessMessageMixin, CreateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
1116
1117
    """ Display the data related a specific web and create a job instance
        into the database
BERJON Matthieu's avatar
BERJON Matthieu committed
1118
1119
1120
1121
1122
1123
1124
1125
1126

    Attributes:
        model:  model used in the view.
        form_class: form object to pass on the template.
        success_url: URL or handle where the user will be redirected.
        success_message: successfull message sent to the template
        template_name: name of the template loaded with this view.

    """
1127
1128
1129
    model = Job
    form_class = JobForm
    success_message = 'Job created successfully.'
BERJON Matthieu's avatar
BERJON Matthieu committed
1130
    template_name = 'webapp_detail.html'
1131

1132
1133
1134
    def get_success_url(self):
        return reverse('main:job_detail', args=(self.job_id,))

1135
    def form_valid(self, form):
BERJON Matthieu's avatar
BERJON Matthieu committed
1136
        """Save data coming from the form in the database """
1137
1138
        webapp = Webapp.objects.get(docker_name=self.kwargs['docker_name'])

BERJON Matthieu's avatar
BERJON Matthieu committed
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
        # If the user isn't identified, we send back an error message and
        # and redirect the user.
        if self.request.user.is_anonymous():
            messages.add_message(self.request, messages.ERROR, 'You must be identified to create a job.')
            log.warning("Someone tried to run a job without being identified.")
            return redirect('main:webapp_detail', webapp.docker_name)
        else:
            obj = form.save(commit=False)
            obj.queue_id = form.cleaned_data.get('queue_id').id
            obj.state = Job.NEW
            obj.result = 0
            obj.user_id = self.request.user.id
            obj.webapp_id = webapp.id
            obj.version = form.cleaned_data.get('version')
            obj.save()
1154

BERJON Matthieu's avatar
BERJON Matthieu committed
1155
            # Upload files if there are any
1156
            upload_data(self.request.FILES.getlist('files'), obj)
BERJON Matthieu's avatar
BERJON Matthieu committed
1157

BERJON Matthieu's avatar
BERJON Matthieu committed
1158
1159
1160
            # start the job
            obj.state = Job.WAITING
            obj.save()
1161
            self.job_id = obj.id
1162

BERJON Matthieu's avatar
BERJON Matthieu committed
1163
            return super().form_valid(form)
1164
1165

    def get_context_data(self, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
1166
        """Pass on the docker name to the template"""
1167
        webapp = Webapp.objects.get(docker_name=self.kwargs['docker_name'])
BERJON Matthieu's avatar
BERJON Matthieu committed
1168
1169
        kwargs['webapp'] = webapp

1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
        # Private apps should not be indexed by search engines
        #
        # -> return 404 if we detect a robot
        #    (but we let authenticated user through, so that the app is still
        #     usable if robot_detection gets broken)
        if (webapp.private and self.request.user.is_anonymous() and
                robot_detection.is_robot(
                    self.request.META.get("HTTP_USER_AGENT") or " ")):
            raise Http404

BERJON Matthieu's avatar
BERJON Matthieu committed
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
        # Check if a readme is declared in the database
        if webapp.readme:
            readme_file = os.path.join(
                settings.MEDIA_ROOT,
                self.object.docker_name,
                'Readme')
            if os.path.exists(readme_file):
                with open(readme_file, 'r') as md_data:
                    kwargs['readme'] = md_data.read()
            else:
                log.warning("No README available for app %s", self.model.name)
        else:
            readme_file = None
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209

        # select the list of versions to be displayed
        versions = natsort.versorted(set(v for v, in WebappVersion.objects
                .filter(webapp=webapp, state__in=(  WebappVersion.SANDBOX,
                                                    WebappVersion.COMMITTED,
                                                    WebappVersion.READY))
                .values_list("number")))

        # also list 'sandbox' if the sandbox is running and if the current user
        # is allowed to use the sandbox
        if webapp.sandbox_state == Webapp.RUNNING and (
            webapp.is_pushable_by(self.request.user)):
            versions.append("sandbox")
        
        versions.reverse()
        kwargs['versions'] = versions

1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
        # build the sample command lines for using the REST API
        base_url = get_base_url(self.request)
        user = self.request.user
        auth = "Authorization: Token token=" + (
                user.allgouser.token if user.is_authenticated else "<your private_token>")

        kwargs["job_create_cmd"] = ["curl", "-H", auth,
                "-X", "POST", base_url + reverse("api:jobs"),
                None, "-F", "job[webapp_id]=" + str(webapp.id),
                None, "-F", "job[param]=",
1220
                None, "-F", "job[queue]=" + webapp.job_queue.name,
1221
1222
1223
1224
1225
1226
1227
                None, "-F", "files[0]=@test.txt",
                None, "-F", "files[1]=@test2.csv",
                None, "-F", "job[file_url]=<my_file_url>",
                None, "-F", "job[dataset]=<my_dataset_name>",
                ]

        kwargs["job_result_cmd"] = ["curl", "-H", auth,
1228
                base_url + reverse("api:job", args=(42,)).replace("42", "<job_id>")]
1229

BERJON Matthieu's avatar
BERJON Matthieu committed
1230
        return super().get_context_data(**kwargs)
1231

1232
1233
    def get_form_kwargs(self):
        """Return webapp data"""
BERJON Matthieu's avatar
BERJON Matthieu committed
1234
        kwargs = super().get_form_kwargs()
1235
1236
1237
1238
        queryset = Webapp.objects.get(docker_name=self.kwargs['docker_name'])
        kwargs['webapp'] = queryset
        return kwargs