Statistics
| Branch: | Tag: | Revision:

root / snf-pithos-app / pithos / api / management / commands / pithos-reset-usage.py @ 384dee7e

History | View | Annotate | Download (6.5 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 collections import namedtuple
37
from optparse import make_option
38
from sqlalchemy import func
39
from sqlalchemy.sql import select, and_, or_
40

    
41
from pithos.api.util import get_backend
42
from pithos.backends.modular import (
43
    CLUSTER_NORMAL, CLUSTER_HISTORY, CLUSTER_DELETED
44
)
45
clusters = (CLUSTER_NORMAL, CLUSTER_HISTORY, CLUSTER_DELETED)
46

    
47
Statistics = namedtuple('Statistics', ('node', 'path', 'size', 'cluster'))
48

    
49
ResetHoldingPayload = namedtuple('ResetHoldingPayload', (
50
                'entity', 'resource', 'key',
51
                'imported', 'exported', 'returned', 'released'))
52
ENTITY_KEY = '1'
53

    
54
backend = get_backend()
55
table = {}
56
table['nodes'] = backend.node.nodes
57
table['versions'] = backend.node.versions
58
table['statistics'] = backend.node.statistics
59
table['policy'] = backend.node.policy
60
conn = backend.node.conn
61

    
62

    
63
def _compute_statistics(nodes):
64
    statistics = []
65
    append = statistics.append
66
    for path, node in nodes:
67
        select_children = select(
68
            [table['nodes'].c.node]).where(table['nodes'].c.parent == node)
69
        select_descendants = select([table['nodes'].c.node]).where(
70
            or_(table['nodes'].c.parent.in_(select_children),
71
                table['nodes'].c.node.in_(select_children)))
72
        s = select([table['versions'].c.cluster,
73
                    func.sum(table['versions'].c.size)])
74
        s = s.group_by(table['versions'].c.cluster)
75
        s = s.where(table['nodes'].c.node == table['versions'].c.node)
76
        s = s.where(table['nodes'].c.node.in_(select_descendants))
77
        d2 = dict(conn.execute(s).fetchall())
78

    
79
        for cluster in clusters:
80
            try:
81
                size = d2[cluster]
82
            except KeyError:
83
                size = 0
84
            append(Statistics(
85
                node=node,
86
                path=path,
87
                size=size,
88
                cluster=cluster))
89
    return statistics
90

    
91

    
92
def _get_verified_usage(statistics):
93
    """Verify statistics and set quotaholder account usage"""
94
    reset_holding = []
95
    append = reset_holding.append
96
    for item in statistics:
97
        s = select([table['statistics'].c.size])
98
        s = s.where(table['statistics'].c.node == item.node)
99
        s = s.where(table['statistics'].c.cluster == item.cluster)
100
        db_item = conn.execute(s).fetchone()
101
        if not db_item:
102
            continue
103
        try:
104
            assert item.size == db_item.size, \
105
                    '%d[%s][%d], size: %d != %d' % (
106
                            item.node, item.path, item.cluster,
107
                            item.size, db_item.size)
108
        except AssertionError, e:
109
            print e
110
        if item.cluster == CLUSTER_NORMAL:
111
            append(ResetHoldingPayload(
112
                    entity=item.path,
113
                    resource='pithos+.diskspace',
114
                    key=ENTITY_KEY,
115
                    imported=item.size,
116
                    exported=0,
117
                    returned=0,
118
                    released=0))
119
    return reset_holding
120

    
121

    
122
class Command(NoArgsCommand):
123
    help = "Set quotaholder account usage"
124

    
125
    option_list = NoArgsCommand.option_list + (
126
        make_option('-a',
127
                    dest='accounts',
128
                    action='append',
129
                    help="Account to reset quota"),
130
    )
131

    
132
    def handle_noargs(self, **options):
133
        try:
134
            if not backend.quotaholder_url:
135
                raise CommandError('Quotaholder component url is not set')
136

    
137
            if not backend.quotaholder_token:
138
                raise CommandError('Quotaholder component token is not set')
139

    
140
            # retrieve account nodes
141
            s = select([table['nodes'].c.path, table['nodes'].c.node])
142
            s = s.where(and_(table['nodes'].c.node != 0,
143
                             table['nodes'].c.parent == 0))
144
            if options['accounts']:
145
                s = s.where(table['nodes'].c.path.in_(options['accounts']))
146
            account_nodes = conn.execute(s).fetchall()
147

    
148
            if not account_nodes:
149
                raise CommandError('No accounts found.')
150

    
151
            # compute account statistics
152
            statistics = _compute_statistics(account_nodes)
153

    
154
            # verify and send usage
155
            reset_holding = _get_verified_usage(statistics)
156

    
157
            while True:
158
                result = backend.quotaholder.reset_holding(
159
                    context={},
160
                    clientkey='pithos',
161
                    reset_holding=reset_holding)
162

    
163
                if not result:
164
                    break
165

    
166
                missing_entities = [reset_holding[x].entity for x in result]
167
                self.stdout.write(
168
                        'Unknown quotaholder accounts: %s\n' %
169
                        ', '.join(missing_entities))
170
                m = 'Retrying sending quota usage for the rest...\n'
171
                self.stdout.write(m)
172
                missing_indexes = set(result)
173
                reset_holding = [x for i, x in enumerate(reset_holding)
174
                                 if i not in missing_indexes]
175
        finally:
176
            backend.close()