Statistics
| Branch: | Tag: | Revision:

root / snf-pithos-app / pithos / api / management / commands / reconcile-resources-pithos.py @ 3248f20a

History | View | Annotate | Download (6.6 kB)

1
# Copyright 2012 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 django.core.management.base import NoArgsCommand, CommandError
35

    
36
from optparse import make_option
37

    
38
from pithos.api.util import get_backend
39
from pithos.api.resources import resources
40
from pithos.backends.modular import CLUSTER_NORMAL, DEFAULT_SOURCE
41

    
42
from synnefo.webproject.management import utils
43

    
44
from astakosclient.errors import QuotaLimit
45

    
46
backend = get_backend()
47

    
48

    
49
class Command(NoArgsCommand):
50
    help = """Reconcile resource usage of Astakos with Pithos DB.
51

52
    Detect unsynchronized usage between Astakos and Pithos DB resources and
53
    synchronize them if specified so.
54

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

    
71
    def handle_noargs(self, **options):
72
        try:
73
            backend.pre_exec()
74
            qh_result = backend.astakosclient.service_get_quotas(
75
                backend.service_token)
76

    
77
            users = (options['userid'],) if options['userid'] else None
78
            account_nodes = backend.node.node_accounts(users)
79
            if not account_nodes:
80
                raise CommandError('No users found.')
81

    
82
            db_usage = {}
83
            for path, node in account_nodes:
84
                size = backend.node.node_account_usage(node, CLUSTER_NORMAL)
85
                db_usage[path] = size or 0
86

    
87
            users = set(qh_result.keys())
88
            users.update(db_usage.keys())
89

    
90
            pending_exists = False
91
            unknown_user_exists = False
92
            unsynced = []
93
            for uuid in users:
94
                db_value = db_usage.get(uuid, 0)
95
                try:
96
                    qh_all = qh_result[uuid]
97
                except KeyError:
98
                    self.stdout.write(
99
                        "User '%s' does not exist in Quotaholder!\n" % uuid
100
                    )
101
                    unknown_user_exists = True
102
                    continue
103
                else:
104
                    qh = qh_all.get(DEFAULT_SOURCE, {})
105
                    for resource in [r['name'] for r in resources]:
106
                        try:
107
                            qh_resource = qh[resource]
108
                        except KeyError:
109
                            self.stdout.write(
110
                                "Resource '%s' does not exist in Quotaholder "
111
                                "for user '%s'!\n" % (resource, uuid))
112
                            continue
113

    
114
                        if qh_resource['pending']:
115
                            self.stdout.write(
116
                                "Pending commission. "
117
                                "User '%s', resource '%s'.\n" %
118
                                (uuid, resource)
119
                            )
120
                            pending_exists = True
121
                            continue
122

    
123
                        qh_value = qh_resource['usage']
124

    
125
                        if  db_value != qh_value:
126
                            data = (uuid, resource, db_value, qh_value)
127
                            unsynced.append(data)
128

    
129
            if unsynced:
130
                headers = ("User", "Resource", "Database", "Quotaholder")
131
                utils.pprint_table(self.stdout, unsynced, headers)
132
                if options['fix']:
133
                    request = {}
134
                    request['force'] = options['force']
135
                    request['auto_accept'] = True
136
                    request['name'] = "RECONCILE"
137
                    request['provisions'] = map(create_provision, unsynced)
138
                    try:
139
                        backend.astakosclient.issue_commission(
140
                            backend.service_token, request)
141
                    except QuotaLimit:
142
                        self.stdout.write(
143
                            "Reconciling failed because a limit has been "
144
                            "reached. Use --force to ignore the check.\n")
145
                        return
146
                    self.stdout.write("Fixed unsynced resources\n")
147

    
148
            if pending_exists:
149
                self.stdout.write(
150
                    "Found pending commissions. Run 'snf-manage"
151
                    " reconcile-commissions-pithos'\n"
152
                )
153
            elif not (unsynced or unknown_user_exists):
154
                self.stdout.write("Everything in sync.\n")
155
        except:
156
            backend.post_exec(False)
157
        else:
158
            backend.post_exec(True)
159
        finally:
160
            backend.close()
161

    
162

    
163
def create_provision(provision_info):
164
    user, resource, db_value, qh_value = provision_info
165
    return {"holder": user,
166
            "source": DEFAULT_SOURCE,
167
            "resource": resource,
168
            "quantity": db_value - qh_value}