Revision 225cea18 snf-cyclades-app/synnefo/management/common.py

b/snf-cyclades-app/synnefo/management/common.py
31 31
# interpreted as representing official policies, either expressed
32 32
# or implied, of GRNET S.A.
33 33

  
34

  
35
import ipaddr
36
from datetime import datetime
37

  
38
from django.utils.timesince import timesince, timeuntil
39

  
40 34
from django.core.management import CommandError
41 35
from synnefo.db.models import Backend, VirtualMachine, Network, Flavor
42 36
from synnefo.api.util import get_image as backend_get_image
43 37
from synnefo.api.faults import ItemNotFound, BadRequest, OverLimit
44
from django.core.exceptions import FieldError
45 38

  
46 39
from synnefo.api.util import validate_network_params
47 40
from synnefo.settings import (CYCLADES_ASTAKOS_SERVICE_TOKEN as ASTAKOS_TOKEN,
......
49 42
from synnefo.logic.rapi import GanetiApiError, GanetiRapiClient
50 43
from synnefo.lib import astakos
51 44

  
52
from synnefo.util.text import uenc
53

  
54 45
import logging
55 46
log = logging.getLogger(__name__)
56 47

  
57 48

  
58
def format_bool(b):
59
    return 'YES' if b else 'NO'
60

  
61

  
62
def parse_bool(string):
63
    if string == "True":
64
        return True
65
    elif string == "False":
66
        return False
67
    else:
68
        raise Exception("Can not parse string %s to bool" % string)
69

  
70

  
71
def format_date(d):
72
    if not d:
73
        return ''
74

  
75
    if d < datetime.now():
76
        return timesince(d) + ' ago'
77
    else:
78
        return 'in ' + timeuntil(d)
79

  
80

  
81 49
def format_vm_state(vm):
82 50
    if vm.operstate == "BUILD":
83 51
        return "BUILD(" + str(vm.buildpercentage) + "%)"
......
159 127
                           " available flavor IDs." % flavor_id)
160 128

  
161 129

  
162
def filter_results(objects, filter_by):
163
    filter_list = filter_by.split(",")
164
    filter_dict = {}
165
    exclude_dict = {}
166

  
167
    def map_field_type(query):
168
        def fix_bool(val):
169
            if val.lower() in ("yes", "true", "t"):
170
                return True
171
            if val.lower() in ("no", "false", "f"):
172
                return False
173
            return val
174

  
175
        if "!=" in query:
176
            key, val = query.split("!=")
177
            exclude_dict[key] = fix_bool(val)
178
            return
179
        OP_MAP = {
180
            ">=": "__gte",
181
            "=>": "__gte",
182
            ">":  "__gt",
183
            "<=": "__lte",
184
            "=<": "__lte",
185
            "<":  "__lt",
186
            "=":  "",
187
        }
188
        for op, new_op in OP_MAP.items():
189
            if op in query:
190
                key, val = query.split(op)
191
                filter_dict[key + new_op] = fix_bool(val)
192
                return
193

  
194
    map(lambda x: map_field_type(x), filter_list)
195

  
196
    try:
197
        objects = objects.filter(**filter_dict)
198
        return objects.exclude(**exclude_dict)
199
    except FieldError as e:
200
        raise CommandError(e)
201
    except Exception as e:
202
        raise CommandError("Can not filter results: %s" % e)
203

  
204

  
205 130
def check_backend_credentials(clustername, port, username, password):
206 131
    try:
207 132
        client = GanetiRapiClient(clustername, port, username, password)
......
218 143
                           " Ganeti Cluster name: %s" % info_name)
219 144

  
220 145

  
221
def pprint_table(out, table, headers=None, separator=None):
222
    """Print a pretty, aligned string representation of table.
223

  
224
    Works by finding out the max width of each column and padding to data
225
    to this value.
226
    """
227

  
228
    assert(isinstance(table, (list, tuple))), "Invalid table type"
229
    sep = separator if separator else "  "
230

  
231
    if headers:
232
        assert(isinstance(headers, (list, tuple))), "Invalid headers type"
233
        table.insert(0, headers)
234

  
235
    # Find out the max width of each column
236
    widths = [max(map(len, col)) for col in zip(*table)]
237

  
238
    t_length = sum(widths) + len(sep) * (len(widths) - 1)
239
    if headers:
240
        # pretty print the headers
241
        print >> out, sep.join((str(val).rjust(width)
242
                               for val, width in zip(headers, widths)))
243
        print >> out, "-" * t_length
244
        # remove headers
245
        table = table[1:]
246

  
247
    # print the rest table
248
    for row in table:
249
        print >> out, sep.join(uenc(val.rjust(width))
250
                               for val, width in zip(row, widths))
251

  
252

  
253 146
class UserCache(object):
254 147
    """uuid<->displayname user 'cache'"""
255 148

  

Also available in: Unified diff