Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (11 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("--projects",
64
                    help=("Enforce resources only for the specified list "
65
                          "of projects, e.g uuid1,uuid2")),
66
        make_option("--exclude-projects",
67
                    help=("Exclude list of projects from resource enforcement")
68
                    ),
69
        make_option("--resources",
70
                    help="Specify resources to check, default: %s" %
71
                    ",".join(DEFAULT_RESOURCES)),
72
        make_option("--fix",
73
                    default=False,
74
                    action="store_true",
75
                    help="Fix violations"),
76
        make_option("--force",
77
                    default=False,
78
                    action="store_true",
79
                    help=("Confirm actions that may permanently "
80
                          "remove a vm")),
81
        make_option("--shutdown-timeout",
82
                    help="Force vm shutdown after given seconds."),
83
    )
84

    
85
    def confirm(self):
86
        self.stdout.write("Confirm? [y/N] ")
87
        try:
88
            response = raw_input()
89
        except EOFError:
90
            response = "ABORT"
91
        if string.lower(response) not in ['y', 'yes']:
92
            self.stderr.write("Aborted.\n")
93
            exit()
94

    
95
    def get_handlers(self, resources):
96
        def rem(v):
97
            try:
98
                resources.remove(v)
99
                return True
100
            except ValueError:
101
                return False
102

    
103
        if resources is None:
104
            resources = list(DEFAULT_RESOURCES)
105
        else:
106
            resources = resources.split(",")
107

    
108
        handlers = [h for h in enforce.RESOURCE_HANDLING if rem(h[0])]
109
        if resources:
110
            m = "No such resource '%s'" % resources[0]
111
            raise CommandError(m)
112
        return handlers
113

    
114
    @transaction.commit_on_success
115
    def handle(self, *args, **options):
116
        write = self.stderr.write
117
        fix = options["fix"]
118
        force = options["force"]
119
        handlers = self.get_handlers(options["resources"])
120
        maxops = options["max_operations"]
121
        if maxops is not None:
122
            try:
123
                maxops = int(maxops)
124
            except ValueError:
125
                m = "Expected integer max operations."
126
                raise CommandError(m)
127

    
128
        shutdown_timeout = options["shutdown_timeout"]
129
        if shutdown_timeout is not None:
130
            try:
131
                shutdown_timeout = int(shutdown_timeout)
132
            except ValueError:
133
                m = "Expected integer shutdown timeout."
134
                raise CommandError(m)
135

    
136
        excluded_users = options['exclude_users']
137
        excluded_users = set(excluded_users.split(',')
138
                             if excluded_users is not None else [])
139

    
140
        users_to_check = options['users']
141
        if users_to_check is not None:
142
            users_to_check = set(users_to_check.split(',')) - excluded_users
143

    
144
        try:
145
            qh_holdings = util.get_qh_users_holdings(users_to_check)
146
        except errors.AstakosClientException as e:
147
            raise CommandError(e)
148

    
149
        excluded_projects = options["exclude_projects"]
150
        excluded_projects = set(excluded_projects.split(',')
151
                                if excluded_projects is not None else [])
152

    
153
        projects_to_check = options["projects"]
154
        if projects_to_check is not None:
155
            projects_to_check = set(projects_to_check.split(',')) - \
156
                excluded_projects
157

    
158
        try:
159
            qh_project_holdings = util.get_qh_project_holdings(
160
                projects_to_check)
161
        except errors.AstakosClientException as e:
162
            raise CommandError(e)
163

    
164
        qh_project_holdings = sorted(qh_project_holdings.items())
165
        qh_holdings = sorted(qh_holdings.items())
166
        resources = set(h[0] for h in handlers)
167
        dangerous = bool(resources.difference(DEFAULT_RESOURCES))
168

    
169
        opts = {"shutdown_timeout": shutdown_timeout}
170
        actions = {}
171
        overlimit = []
172
        viol_id = 0
173

    
174
        for resource, handle_resource, resource_type in handlers:
175
            if resource_type not in actions:
176
                actions[resource_type] = OrderedDict()
177
            actual_resources = enforce.get_actual_resources(
178
                resource_type, projects=projects_to_check)
179
            for project, project_quota in qh_project_holdings:
180
                if enforce.skip_check(project, projects_to_check,
181
                                      excluded_projects):
182
                    continue
183
                try:
184
                    qh = util.transform_project_quotas(project_quota)
185
                    qh_value, qh_limit, qh_pending = qh[resource]
186
                except KeyError:
187
                    write("Resource '%s' does not exist in Quotaholder"
188
                          " for project '%s'!\n" %
189
                          (resource, project))
190
                    continue
191
                if qh_pending:
192
                    write("Pending commission for project '%s', "
193
                          "resource '%s'. Skipping\n" %
194
                          (project, resource))
195
                    continue
196
                diff = qh_value - qh_limit
197
                if diff > 0:
198
                    viol_id += 1
199
                    overlimit.append((viol_id, "project", project, "",
200
                                      resource, qh_limit, qh_value))
201
                    relevant_resources = enforce.pick_project_resources(
202
                        actual_resources[project], users=users_to_check,
203
                        excluded_users=excluded_users)
204
                    handle_resource(viol_id, resource, relevant_resources,
205
                                    diff, actions)
206

    
207
        for resource, handle_resource, resource_type in handlers:
208
            if resource_type not in actions:
209
                actions[resource_type] = OrderedDict()
210
            actual_resources = enforce.get_actual_resources(resource_type,
211
                                                            users_to_check)
212
            for user, user_quota in qh_holdings:
213
                if enforce.skip_check(user, users_to_check, excluded_users):
214
                    continue
215
                for source, source_quota in user_quota.iteritems():
216
                    if enforce.skip_check(source, projects_to_check,
217
                                          excluded_projects):
218
                        continue
219
                    try:
220
                        qh = util.transform_quotas(source_quota)
221
                        qh_value, qh_limit, qh_pending = qh[resource]
222
                    except KeyError:
223
                        write("Resource '%s' does not exist in Quotaholder"
224
                              " for user '%s' and source '%s'!\n" %
225
                              (resource, user, source))
226
                        continue
227
                    if qh_pending:
228
                        write("Pending commission for user '%s', source '%s', "
229
                              "resource '%s'. Skipping\n" %
230
                              (user, source, resource))
231
                        continue
232
                    diff = qh_value - qh_limit
233
                    if diff > 0:
234
                        viol_id += 1
235
                        overlimit.append((viol_id, "user", user, source,
236
                                          resource, qh_limit, qh_value))
237
                        relevant_resources = actual_resources[source][user]
238
                        handle_resource(viol_id, resource, relevant_resources,
239
                                        diff, actions)
240

    
241
        if not overlimit:
242
            write("No violations.\n")
243
            return
244

    
245
        headers = ("#", "Type", "Holder", "Source", "Resource", "Limit",
246
                   "Usage")
247
        pprint_table(self.stdout, overlimit, headers,
248
                     options["output_format"], title="Violations")
249

    
250
        if any(actions.values()):
251
            self.stdout.write("\n")
252
            if fix:
253
                if dangerous and not force:
254
                    write("You are enforcing resources that may permanently "
255
                          "remove a vm.\n")
256
                    self.confirm()
257
                write("Applying actions. Please wait...\n")
258
            title = "Applied Actions" if fix else "Suggested Actions"
259
            log = enforce.perform_actions(actions, maxops=maxops, fix=fix,
260
                                          options=opts)
261
            headers = ("Type", "ID", "State", "Backend", "Action", "Violation")
262
            if fix:
263
                headers += ("Result",)
264
            pprint_table(self.stdout, log, headers,
265
                         options["output_format"], title=title)