Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / quotas / management / commands / enforce-resources-cyclades.py @ d56fa78c

History | View | Annotate | Download (8 kB)

1
# Copyright 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
import string
35
from optparse import make_option
36
from django.db import transaction
37

    
38
from synnefo.lib.ordereddict import OrderedDict
39
from synnefo.quotas import util
40
from synnefo.quotas import enforce
41
from synnefo.quotas import errors
42
from snf_django.management.commands import SynnefoCommand, CommandError
43
from snf_django.management.utils import pprint_table
44

    
45

    
46
DEFAULT_RESOURCES = ["cyclades.cpu",
47
                     "cyclades.ram",
48
                     "cyclades.floating_ip",
49
                     ]
50

    
51

    
52
class Command(SynnefoCommand):
53
    help = """Check and fix quota violations for Cyclades resources.
54
    """
55
    option_list = SynnefoCommand.option_list + (
56
        make_option("--max-operations",
57
                    help="Limit operations per backend."),
58
        make_option("--users", dest="users",
59
                    help=("Enforce resources only for the specified list "
60
                          "of users, e.g uuid1,uuid2")),
61
        make_option("--exclude-users",
62
                    help=("Exclude list of users from resource enforcement")),
63
        make_option("--resources",
64
                    help="Specify resources to check, default: %s" %
65
                    ",".join(DEFAULT_RESOURCES)),
66
        make_option("--fix",
67
                    default=False,
68
                    action="store_true",
69
                    help="Fix violations"),
70
        make_option("--force",
71
                    default=False,
72
                    action="store_true",
73
                    help=("Confirm actions that may permanently "
74
                          "remove a vm")),
75
        make_option("--shutdown-timeout",
76
                    help="Force vm shutdown after given seconds."),
77
    )
78

    
79
    def confirm(self):
80
        self.stdout.write("Confirm? [y/N] ")
81
        try:
82
            response = raw_input()
83
        except EOFError:
84
            response = "ABORT"
85
        if string.lower(response) not in ['y', 'yes']:
86
            self.stderr.write("Aborted.\n")
87
            exit()
88

    
89
    def get_handlers(self, resources):
90
        def rem(v):
91
            try:
92
                resources.remove(v)
93
                return True
94
            except ValueError:
95
                return False
96

    
97
        if resources is None:
98
            resources = list(DEFAULT_RESOURCES)
99
        else:
100
            resources = resources.split(",")
101

    
102
        handlers = [h for h in enforce.RESOURCE_HANDLING if rem(h[0])]
103
        if resources:
104
            m = "No such resource '%s'" % resources[0]
105
            raise CommandError(m)
106
        return handlers
107

    
108
    @transaction.commit_on_success
109
    def handle(self, *args, **options):
110
        write = self.stderr.write
111
        fix = options["fix"]
112
        force = options["force"]
113
        maxops = options["max_operations"]
114
        if maxops is not None:
115
            try:
116
                maxops = int(maxops)
117
            except ValueError:
118
                m = "Expected integer max operations."
119
                raise CommandError(m)
120

    
121
        shutdown_timeout = options["shutdown_timeout"]
122
        if shutdown_timeout is not None:
123
            try:
124
                shutdown_timeout = int(shutdown_timeout)
125
            except ValueError:
126
                m = "Expected integer shutdown timeout."
127
                raise CommandError(m)
128

    
129
        users = options['users']
130
        if users is not None:
131
            users = users.split(',')
132

    
133
        excluded = options['exclude_users']
134
        excluded = set(excluded.split(',') if excluded is not None else [])
135

    
136
        handlers = self.get_handlers(options["resources"])
137
        try:
138
            qh_holdings = util.get_qh_users_holdings(users)
139
        except errors.AstakosClientException as e:
140
            raise CommandError(e)
141

    
142
        qh_holdings = sorted(qh_holdings.items())
143
        resources = set(h[0] for h in handlers)
144
        dangerous = bool(resources.difference(DEFAULT_RESOURCES))
145

    
146
        opts = {"shutdown_timeout": shutdown_timeout}
147
        actions = {}
148
        overlimit = []
149
        viol_id = 0
150
        for resource, handle_resource, resource_type in handlers:
151
            if resource_type not in actions:
152
                actions[resource_type] = OrderedDict()
153
            actual_resources = enforce.get_actual_resources(resource_type,
154
                                                            users)
155
            for user, user_quota in qh_holdings:
156
                if user in excluded:
157
                    continue
158
                for source, source_quota in user_quota.iteritems():
159
                    try:
160
                        qh = util.transform_quotas(source_quota)
161
                        qh_value, qh_limit, qh_pending = qh[resource]
162
                    except KeyError:
163
                        write("Resource '%s' does not exist in Quotaholder"
164
                              " for user '%s' and source '%s'!\n" %
165
                              (resource, user, source))
166
                        continue
167
                    if qh_pending:
168
                        write("Pending commission for user '%s', source '%s', "
169
                              "resource '%s'. Skipping\n" %
170
                              (user, source, resource))
171
                        continue
172
                    diff = qh_value - qh_limit
173
                    if diff > 0:
174
                        viol_id += 1
175
                        overlimit.append((viol_id, user, source, resource,
176
                                          qh_limit, qh_value))
177
                        relevant_resources = actual_resources[user]
178
                        handle_resource(viol_id, resource, relevant_resources,
179
                                        diff, actions)
180

    
181
        if not overlimit:
182
            write("No violations.\n")
183
            return
184

    
185
        headers = ("#", "User", "Source", "Resource", "Limit", "Usage")
186
        pprint_table(self.stdout, overlimit, headers,
187
                     options["output_format"], title="Violations")
188

    
189
        if any(actions.values()):
190
            self.stdout.write("\n")
191
            if fix:
192
                if dangerous and not force:
193
                    write("You are enforcing resources that may permanently "
194
                          "remove a vm.\n")
195
                    self.confirm()
196
                write("Applying actions. Please wait...\n")
197
            title = "Applied Actions" if fix else "Suggested Actions"
198
            log = enforce.perform_actions(actions, maxops=maxops, fix=fix,
199
                                          options=opts)
200
            headers = ("Type", "ID", "State", "Backend", "Action", "Violation")
201
            if fix:
202
                headers += ("Result",)
203
            pprint_table(self.stdout, log, headers,
204
                         options["output_format"], title=title)