Projet

Général

Profil

0001-general-move-cron-jobs-in-app-configs-28000.patch

Frédéric Péters, 14 novembre 2018 17:55

Télécharger (16,4 ko)

Voir les différences:

Subject: [PATCH] general: move cron jobs in app configs (#28000)

 combo/apps/dashboard/__init__.py              | 10 ++++
 combo/apps/dashboard/management/__init__.py   |  0
 .../dashboard/management/commands/__init__.py |  0
 .../management/commands/clean_autotiles.py    | 28 -----------
 combo/apps/lingo/__init__.py                  | 35 +++++++++++++
 .../management/commands/notify_payments.py    | 41 ----------------
 combo/apps/momo/__init__.py                   | 27 ++++++++++
 combo/apps/momo/management/__init__.py        |  0
 .../apps/momo/management/commands/__init__.py |  0
 .../commands/update_momo_manifest.py          | 49 -------------------
 debian/combo.cron.hourly                      |  5 +-
 tests/test_dashboard.py                       |  4 +-
 tests/test_lingo_payment.py                   | 12 ++---
 tests/test_momo.py                            |  1 -
 14 files changed, 82 insertions(+), 130 deletions(-)
 delete mode 100644 combo/apps/dashboard/management/__init__.py
 delete mode 100644 combo/apps/dashboard/management/commands/__init__.py
 delete mode 100644 combo/apps/dashboard/management/commands/clean_autotiles.py
 delete mode 100644 combo/apps/lingo/management/commands/notify_payments.py
 delete mode 100644 combo/apps/momo/management/__init__.py
 delete mode 100644 combo/apps/momo/management/commands/__init__.py
 delete mode 100644 combo/apps/momo/management/commands/update_momo_manifest.py
combo/apps/dashboard/__init__.py
12 12
# GNU Affero General Public License for more details.
13 13

  
14 14
import django.apps
15
from django.utils.timezone import now, timedelta
15 16
from django.utils.translation import ugettext_lazy as _
16 17

  
17 18
class AppConfig(django.apps.AppConfig):
......
22 23
        from . import urls
23 24
        return urls.urlpatterns
24 25

  
26
    def hourly(self):
27
        self.clean_autotiles()
28

  
29
    def clean_autotiles(self):
30
        from combo.data.models import ConfigJsonCell
31
        ConfigJsonCell.objects.filter(placeholder='_auto_tile',
32
                last_update_timestamp__lte=now() - timedelta(days=2)).delete()
33

  
34

  
25 35
default_app_config = 'combo.apps.dashboard.AppConfig'
combo/apps/dashboard/management/commands/clean_autotiles.py
1
# combo - content management system
2
# Copyright (C) 2014-2018  Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
17
from django.core.management.base import BaseCommand
18
from django.utils.timezone import now, timedelta
19

  
20
from combo.data.models import ConfigJsonCell
21

  
22

  
23
class Command(BaseCommand):
24
    help = 'Delete automatically created tile cells that are more than 2 days old'
25

  
26
    def handle(self, *args, **options):
27
        ConfigJsonCell.objects.filter(placeholder='_auto_tile',
28
                last_update_timestamp__lte=now() - timedelta(days=2)).delete()
combo/apps/lingo/__init__.py
14 14
# You should have received a copy of the GNU Affero General Public License
15 15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 16

  
17
import datetime
18
import logging
19

  
17 20
import django.apps
18 21
from django.core.urlresolvers import reverse
22
from django.utils import timezone
19 23
from django.utils.translation import ugettext_lazy as _
20 24

  
21 25

  
......
31 35
        return [{'href': reverse('lingo-manager-homepage'),
32 36
                'text': _('Online Payment')}]
33 37

  
38
    def hourly(self):
39
        self.update_transactions()
40

  
41
    def update_transactions(self):
42
        from .models import Transaction, EXPIRED
43
        logger = logging.getLogger(__name__)
44
        now = timezone.now()
45
        for transaction in Transaction.objects.filter(
46
                start_date__lt=now-datetime.timedelta(hours=1),
47
                end_date__isnull=True):
48
            logger.info('transaction %r is expired', transaction.order_id)
49
            transaction.status = EXPIRED
50
            transaction.save()
51

  
52
        for transaction in Transaction.objects.filter(to_be_paid_remote_items__isnull=False):
53
            transaction.retry_notify_remote_items_of_payments()
54

  
55
    def notify_payments(self):
56
        from combo.apps.lingo.models import BasketItem
57
        logger = logging.getLogger(__name__)
58
        now = timezone.now()
59
        for item in BasketItem.objects.filter(
60
                notification_date__isnull=True,
61
                cancellation_date__isnull=True,
62
                payment_date__lt=now-datetime.timedelta(minutes=5),
63
                payment_date__gt=now-datetime.timedelta(minutes=300)):
64
            try:
65
                item.notify_payment()
66
            except:
67
                logger.exception('error in async notification for basket item %s', item.id)
68

  
34 69
default_app_config = 'combo.apps.lingo.AppConfig'
combo/apps/lingo/management/commands/notify_payments.py
1
# -*- coding: utf-8 -*-
2
#
3
# lingo - basket and payment system
4
# Copyright (C) 2017  Entr'ouvert
5
#
6
# This program is free software: you can redistribute it and/or modify it
7
# under the terms of the GNU Affero General Public License as published
8
# by the Free Software Foundation, either version 3 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU Affero General Public License for more details.
15
#
16
# You should have received a copy of the GNU Affero General Public License
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18

  
19
import datetime
20
import logging
21

  
22
from django.core.management.base import BaseCommand
23
from django.utils import timezone
24

  
25
from combo.apps.lingo.models import BasketItem
26

  
27

  
28
class Command(BaseCommand):
29

  
30
    def handle(self, *args, **kwargs):
31
        logger = logging.getLogger(__name__)
32
        now = timezone.now()
33
        for item in BasketItem.objects.filter(
34
                notification_date__isnull=True,
35
                cancellation_date__isnull=True,
36
                payment_date__lt=now-datetime.timedelta(minutes=5),
37
                payment_date__gt=now-datetime.timedelta(minutes=300)):
38
            try:
39
                item.notify_payment()
40
            except:
41
                logger.exception('error in async notification for basket item %s', item.id)
combo/apps/momo/__init__.py
17 17
import django.apps
18 18
from django.conf import settings
19 19
from django.core.urlresolvers import reverse
20
from django.db import connection
21
from django.test.client import RequestFactory
22
from django.utils import translation
23
from django.utils.six.moves.urllib.parse import urlparse
20 24
from django.utils.translation import ugettext_lazy as _
21 25

  
22 26
class AppConfig(django.apps.AppConfig):
......
34 38
        return [{'href': reverse('momo-manager-homepage'),
35 39
                'text': _('Mobile Application')}]
36 40

  
41
    def hourly(self):
42
        from .utils import GenerationInfo
43
        try:
44
            self.update_momo_manifest()
45
        except GenerationInfo:
46
            pass
47

  
48
    def update_momo_manifest(self):
49
        from .utils import generate_manifest
50
        tenant = connection.get_tenant()
51
        parsed_base_url = urlparse(tenant.get_base_url())
52
        if ':' in parsed_base_url.netloc:
53
            server_name, server_port = parsed_base_url.netloc.split(':')
54
        else:
55
            server_name = parsed_base_url.netloc
56
            server_port = '80' if parsed_base_url.scheme == 'http' else '443'
57
        request = RequestFactory().get('/', SERVER_NAME=server_name,
58
                SERVER_PORT=server_port)
59
        request._get_scheme = lambda: parsed_base_url.scheme
60

  
61
        with translation.override(settings.LANGUAGE_CODE):
62
            generate_manifest(request)
63

  
37 64
default_app_config = 'combo.apps.momo.AppConfig'
combo/apps/momo/management/commands/update_momo_manifest.py
1
# combo - content management system
2
# Copyright (C) 2016  Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
17
from django.conf import settings
18
from django.core.management.base import BaseCommand, CommandError
19
from django.db import connection
20
from django.test.client import RequestFactory
21
from django.utils import translation
22
from django.utils.six.moves.urllib.parse import urlparse
23

  
24
from combo.apps.momo.utils import generate_manifest, GenerationError, GenerationInfo
25

  
26
class Command(BaseCommand):
27
    def handle(self, *args, **kwargs):
28
        if not getattr(settings, 'ENABLE_MOMO', False):
29
            return
30
        tenant = connection.get_tenant()
31
        parsed_base_url = urlparse(tenant.get_base_url())
32
        if ':' in parsed_base_url.netloc:
33
            server_name, server_port = parsed_base_url.netloc.split(':')
34
        else:
35
            server_name = parsed_base_url.netloc
36
            server_port = '80' if parsed_base_url.scheme == 'http' else '443'
37
        request = RequestFactory().get('/', SERVER_NAME=server_name,
38
                SERVER_PORT=server_port)
39
        request._get_scheme = lambda: parsed_base_url.scheme
40

  
41
        translation.activate(settings.LANGUAGE_CODE)
42
        try:
43
            generate_manifest(request)
44
        except GenerationError as e:
45
            raise CommandError(e.message)
46
        except GenerationInfo as e:
47
            if int(kwargs.get('verbosity')) > 0:
48
                print(e.message)
49
        translation.deactivate()
debian/combo.cron.hourly
1 1
#!/bin/sh
2 2

  
3
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command cron --all-tenants
3 4
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command clearsessions --all-tenants
4
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command update_transactions --all-tenants
5
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command update_momo_manifest --all-tenants -v0
6 5
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command update_index --remove --all-tenants -v0
7
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command notify_payments --all-tenants -v0
8
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command clean_autotiles --all-tenants -v0
tests/test_dashboard.py
4 4
import pytest
5 5
from webtest import TestApp
6 6

  
7
from django.apps import apps
7 8
from django.conf import settings
8 9
from django.contrib.auth.models import User
9 10
from django.core.management import call_command
......
208 209
            assert resp.text.strip() == '/var1=one/var2=/'
209 210

  
210 211
def test_clean_autotiles(app, site):
211
    call_command('clean_autotiles')
212
    appconfig = apps.get_app_config('dashboard')
213
    appconfig.clean_autotiles()
tests/test_lingo_payment.py
7 7
import json
8 8
import mock
9 9

  
10
from django.apps import apps
10 11
from django.contrib.auth.models import User
11 12
from django.core.urlresolvers import reverse
12 13
from django.core.wsgi import get_wsgi_application
......
19 20
from combo.data.models import Page
20 21
from combo.apps.lingo.models import (Regie, BasketItem, Transaction,
21 22
        TransactionOperation, RemoteItem, EXPIRED, LingoBasketCell)
22
from combo.apps.lingo.management.commands.update_transactions import Command as UpdateTransactionsCommand
23
from combo.apps.lingo.management.commands.notify_payments import Command as NotifyPaymentsCommand
24 23
from combo.utils import sign_url
25 24

  
26 25
from .test_manager import login
......
674 673
    t2 = Transaction(status=0)
675 674
    t2.save()
676 675

  
677
    cmd = UpdateTransactionsCommand()
678
    cmd.handle()
676
    appconfig = apps.get_app_config('lingo')
677
    appconfig.update_transactions()
679 678

  
680 679
    assert Transaction.objects.get(id=t1.id).status == EXPIRED
681 680
    assert Transaction.objects.get(id=t2.id).status == 0
......
861 860
    assert not BasketItem.objects.get(id=item.id).notification_date
862 861

  
863 862
    # too soon
864
    NotifyPaymentsCommand().handle()
863
    appconfig = apps.get_app_config('lingo')
864
    appconfig.notify_payments()
865 865
    assert BasketItem.objects.get(id=item.id).payment_date
866 866
    assert not BasketItem.objects.get(id=item.id).notification_date
867 867

  
......
874 874
        mock_response = mock.Mock()
875 875
        mock_response.status_code = 200
876 876
        request.return_value = mock_response
877
        NotifyPaymentsCommand().handle()
877
        appconfig.notify_payments()
878 878
        url = request.call_args[0][1]
879 879
        assert url.startswith('http://example.org/testitem/jump/trigger/paid')
880 880
    assert BasketItem.objects.get(id=item.id).payment_date
tests/test_momo.py
8 8
from django.conf import settings
9 9

  
10 10
from combo.data.models import Page, CellBase, TextCell, LinkCell, FeedCell
11
from combo.apps.momo.management.commands.update_momo_manifest import Command as UpdateCommand
12 11

  
13 12
from .test_manager import login, admin_user
14 13

  
15
-