Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / quotas / management / commands / reconcile-resources-cyclades.py @ 9122ffab

History | View | Annotate | Download (5.9 kB)

1
# Copyright 2012, 2013 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from datetime import datetime
35
from django.core.management.base import BaseCommand
36
from optparse import make_option
37

    
38

    
39
from synnefo import quotas
40
from synnefo.quotas.util import (get_db_holdings, get_quotaholder_holdings,
41
                                 transform_quotas)
42
from synnefo.webproject.management.utils import pprint_table
43
from synnefo.settings import CYCLADES_SERVICE_TOKEN as ASTAKOS_TOKEN
44

    
45

    
46
class Command(BaseCommand):
47
    help = """Reconcile resource usage of Astakos with Cyclades DB.
48

49
    Detect unsynchronized usage between Astakos and Cyclades DB resources and
50
    synchronize them if specified so.
51

52
    """
53
    option_list = BaseCommand.option_list + (
54
        make_option("--userid", dest="userid",
55
                    default=None,
56
                    help="Reconcile resources only for this user"),
57
        make_option("--fix", dest="fix",
58
                    default=False,
59
                    action="store_true",
60
                    help="Synchronize Astakos quotas with Cyclades DB."),
61
        make_option("--force",
62
                    default=False,
63
                    action="store_true",
64
                    help="Override Astakos quotas. Force Astakos to impose"
65
                         " the Cyclades quota, independently of their value.")
66
    )
67

    
68
    def handle(self, *args, **options):
69
        write = self.stdout.write
70
        userid = options['userid']
71

    
72
        # Get holdings from Cyclades DB
73
        db_holdings = get_db_holdings(userid)
74
        # Get holdings from QuotaHolder
75
        qh_holdings = get_quotaholder_holdings(userid)
76

    
77
        users = set(db_holdings.keys())
78
        users.update(qh_holdings.keys())
79
        # Remove 'None' user
80
        users.discard(None)
81

    
82
        if userid and userid not in users:
83
            write("User '%s' does not exist in Quotaholder!", userid)
84
            return
85

    
86
        pending_exists = False
87
        unknown_user_exists = False
88
        unsynced = []
89
        for user in users:
90
            db = db_holdings.get(user, {})
91
            try:
92
                qh_all = qh_holdings[user]
93
            except KeyError:
94
                write("User '%s' does not exist in Quotaholder!\n" %
95
                      user)
96
                unknown_user_exists = True
97
                continue
98

    
99
            # Assuming only one source
100
            qh = qh_all.get(quotas.DEFAULT_SOURCE, {})
101
            qh = transform_quotas(qh)
102
            for resource in quotas.RESOURCES:
103
                db_value = db.pop(resource, 0)
104
                try:
105
                    qh_value, _, qh_pending = qh[resource]
106
                except KeyError:
107
                    write("Resource '%s' does not exist in Quotaholder"
108
                          " for user '%s'!\n" % (resource, user))
109
                    continue
110
                if qh_pending:
111
                    write("Pending commission. User '%s', resource '%s'.\n" %
112
                          (user, resource))
113
                    pending_exists = True
114
                    continue
115
                if db_value != qh_value:
116
                    data = (user, resource, db_value, qh_value)
117
                    unsynced.append(data)
118

    
119
        headers = ("User", "Resource", "Database", "Quotaholder")
120
        if unsynced:
121
            pprint_table(self.stderr, unsynced, headers)
122
            if options["fix"]:
123
                qh = quotas.Quotaholder.get()
124
                request = {}
125
                request["force"] = options["force"]
126
                request["auto_accept"] = True
127
                request["name"] = \
128
                    ("client: reconcile-resources-cyclades, time: %s"
129
                     % datetime.now())
130
                request["provisions"] = map(create_provision, unsynced)
131
                try:
132
                    qh.issue_commission(ASTAKOS_TOKEN, request)
133
                except quotas.QuotaLimit:
134
                    write("Reconciling failed because a limit has been "
135
                          "reached. Use --force to ignore the check.\n")
136
                    return
137
                write("Fixed unsynced resources\n")
138

    
139
        if pending_exists:
140
            write("Found pending commissions. Run 'snf-manage"
141
                  " reconcile-commissions-cyclades'\n")
142
        elif not (unsynced or unknown_user_exists):
143
            write("Everything in sync.\n")
144

    
145

    
146
def create_provision(provision_info):
147
    user, resource, db_value, qh_value = provision_info
148
    return {"holder": user,
149
            "source": quotas.DEFAULT_SOURCE,
150
            "resource": resource,
151
            "quantity": db_value - qh_value}