summaryrefslogtreecommitdiff
path: root/openstack_dashboard/api/tuskar.py
blob: 240d8b93dd17414e6e31ca96b1765c07df13c20b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
# vim: tabstop=4 shiftwidth=4 softtabstop=4

#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import copy
import logging
from datetime import timedelta
from random import randint

from django.conf import settings
from django.db.models import Sum, Max
from django.utils.translation import ugettext_lazy as _

from tuskarclient.v1 import client as tuskar_client

from openstack_dashboard.api import base
import openstack_dashboard.dashboards.infrastructure.models as dummymodels


LOG = logging.getLogger(__name__)
TUSKAR_ENDPOINT_URL = getattr(settings, 'TUSKAR_ENDPOINT_URL')


# FIXME: request isn't used right in the tuskar client right now, but looking
# at other clients, it seems like it will be in the future
def tuskarclient(request):
    c = tuskar_client.Client(TUSKAR_ENDPOINT_URL)
    return c


class StringIdAPIResourceWrapper(base.APIResourceWrapper):
    # horizon DataTable class expects ids to be string,
    # if it's not string, then comparison in
    # horizon/tables/base.py:get_object_by_id fails.
    # Because of this, ids returned from dummy api are converted to string
    # (luckily django autoconverts strings to integers when passing string to
    # django model id)
    @property
    def id(self):
        return str(self._apiresource.id)

    def set_request(self, request):
        self.request = request


class Capacity(StringIdAPIResourceWrapper):
    """Wrapper for the Capacity object returned by the
    dummy model.
    """
    _attrs = ['name', 'value', 'unit']

    @classmethod
    def create(cls, request, content_object, name, value, unit):
        c = dummymodels.Capacity(
            content_object=content_object,
            name=name,
            value=value,
            unit=unit)
        c.save()
        return Capacity(c)

    @classmethod
    def update(cls, request, capacity_id, content_object, name, value, unit):
        c = dummymodels.Capacity.objects.get(id=capacity_id)
        c.content_object = content_object
        c.name = name
        c.value = value
        c.unit = unit
        c.save()
        return cls(c)

    # defines a random usage of capacity - API should probably be able to
    # determine usage of capacity based on capacity value and obejct_id
    @property
    def usage(self):
        if not hasattr(self, '_usage'):
            self._usage = randint(0, self.value)
        return self._usage

    # defines a random average of capacity - API should probably be able to
    # determine average of capacity based on capacity value and obejct_id
    @property
    def average(self):
        if not hasattr(self, '_average'):
            self._average = randint(0, self.value)
        return self._average


class Node(StringIdAPIResourceWrapper):
    """Wrapper for the Node object  returned by the
    dummy model.
    """
    _attrs = ['name', 'mac_address', 'ip_address', 'status', 'usage', 'rack']

    @classmethod
    def get(cls, request, node_id):
        return cls(dummymodels.Node.objects.get(id=node_id))

    @classmethod
    def list_unracked(cls, request):
        return [cls(h) for h in dummymodels.Node.objects.all() if (
            h.rack is None)]

    @classmethod
    def create(cls, request, name, mac_address, ip_address, status,
               usage, rack):
        node = dummymodels.Node(name=name, mac_address=mac_address,
                                ip_address=ip_address, status=status,
                                usage=usage, rack=rack)
        node.save()

    @property
    def capacities(self):
        if not hasattr(self, '_capacities'):
            self._capacities = [Capacity(c) for c in
                                self._apiresource.capacities.all()]
        return self._capacities

    @property
    def rack(self):
        if not hasattr(self, '_rack'):
            self._rack = self._apiresource.rack
        return self._rack

    @property
    def cpu(self):
        if not hasattr(self, '_cpu'):
            try:
                cpu = dummymodels.Capacity.objects\
                            .filter(node=self._apiresource)\
                            .filter(name='cpu')[0]
            except:
                cpu = dummymodels.Capacity(
                            name='cpu',
                            value=_('Unable to retrieve '
                                    '(Is the node configured properly?)'),
                            unit='')
            self._cpu = Capacity(cpu)
        return self._cpu

    @property
    def ram(self):
        if not hasattr(self, '_ram'):
            try:
                ram = dummymodels.Capacity.objects\
                            .filter(node=self._apiresource)\
                            .filter(name='ram')[0]
            except:
                ram = dummymodels.Capacity(
                            name='ram',
                            value=_('Unable to retrieve '
                                    '(Is the node configured properly?)'),
                            unit='')
            self._ram = Capacity(ram)
        return self._ram

    @property
    def storage(self):
        if not hasattr(self, '_storage'):
            try:
                storage = dummymodels.Capacity.objects\
                                .filter(node=self._apiresource)\
                                .filter(name='storage')[0]
            except:
                storage = dummymodels.Capacity(
                                name='storage',
                                value=_('Unable to retrieve '
                                        '(Is the node configured properly?)'),
                                unit='')
            self._storage = Capacity(storage)
        return self._storage

    @property
    def network(self):
        if not hasattr(self, '_network'):
            try:
                network = dummymodels.Capacity.objects\
                                .filter(node=self._apiresource)\
                                .filter(name='network')[0]
            except:
                network = dummymodels.Capacity(
                                name='network',
                                value=_('Unable to retrieve '
                                        '(Is the node configured properly?)'),
                                unit='')
            self._network = Capacity(network)
        return self._network

    @property
    def vm_capacity(self):
        if not hasattr(self, '_vm_capacity'):
            try:
                value = dummymodels.ResourceClassFlavor.objects\
                            .filter(
                                resource_class__rack__node=self._apiresource)\
                            .aggregate(Max("max_vms"))['max_vms__max']
            except:
                value = _("Unable to retrieve vm capacity")

            vm_capacity = dummymodels.Capacity(name=_("Max VMs"),
                                               value=value,
                                               unit=_("VMs"))
            self._vm_capacity = Capacity(vm_capacity)
        return self._vm_capacity


class Rack(StringIdAPIResourceWrapper):
    """Wrapper for the Rack object  returned by the
    dummy model.
    """
    _attrs = ['id', 'name', 'location', 'subnet', 'nodes', 'state']

    @classmethod
    def create(cls, request, name, resource_class_id, location, subnet,
               nodes=[]):
        ## FIXME: set nodes here
        rack = tuskarclient(request).racks.create(
                name=name,
                location=location,
                subnet=subnet,
                nodes=nodes,
                resource_class={'id': resource_class_id},
                slots=0)
        return cls(rack)

    @classmethod
    def update(cls, request, rack_id, kwargs):
        ## FIXME: set nodes here
        correct_kwargs = copy.copy(kwargs)
        # remove rack_id from kwargs (othervise it is duplicated)
        correct_kwargs.pop('rack_id', None)
        # correct data mapping for resource_class
        if 'resource_class_id' in correct_kwargs:
            correct_kwargs['resource_class'] = {
                'id': correct_kwargs.pop('resource_class_id', None)}

        rack = tuskarclient(request).racks.update(rack_id, **correct_kwargs)
        return cls(rack)

    @classmethod
    def list(cls, request, only_free_racks=False):
        if only_free_racks:
            return [Rack(r) for r in
                    tuskarclient(request).racks.list() if (
                        r.resource_class is None)]
        else:
            return [Rack(r) for r in
                    tuskarclient(request).racks.list()]

    @classmethod
    def get(cls, request, rack_id):
        rack = cls(tuskarclient(request).racks.get(rack_id))
        rack.set_request(request)
        return rack

    @property
    def resource_class_id(self):
        rclass = getattr(self._apiresource, 'resource_class', None)
        return rclass['id'] if rclass else None

    @property
    def capacities(self):
        if not hasattr(self, '_capacities'):
            self._capacities = [Capacity(c) for c in
                                self._apiresource.capacities.all()]
        return self._capacities

    @property
    def cpu(self):
        if not hasattr(self, '_cpu'):
            try:
                attrs = dummymodels.Capacity.objects\
                        .filter(node__rack=self._apiresource)\
                        .values('name', 'unit').annotate(value=Sum('value'))\
                        .filter(name='cpu')[0]
            except:
                attrs = {'name': 'cpu',
                         'value': _('Unable to retrieve '
                                    '(Are the nodes configured properly?)'),
                         'unit': ''}
            cpu = dummymodels.Capacity(name=attrs['name'],
                                       value=attrs['value'],
                                       unit=attrs['unit'])
            self._cpu = Capacity(cpu)
        return self._cpu

    @property
    def ram(self):
        if not hasattr(self, '_ram'):
            try:
                attrs = dummymodels.Capacity.objects\
                        .filter(node__rack=self._apiresource)\
                        .values('name', 'unit').annotate(value=Sum('value'))\
                        .filter(name='ram')[0]
            except:
                attrs = {'name': 'ram',
                         'value': _('Unable to retrieve '
                                    '(Are the nodes configured properly?)'),
                         'unit': ''}
            ram = dummymodels.Capacity(name=attrs['name'],
                                       value=attrs['value'],
                                       unit=attrs['unit'])
            self._ram = Capacity(ram)
        return self._ram

    @property
    def storage(self):
        if not hasattr(self, '_storage'):
            try:
                attrs = dummymodels.Capacity.objects\
                        .filter(node__rack=self._apiresource)\
                        .values('name', 'unit').annotate(value=Sum('value'))\
                        .filter(name='storage')[0]
            except:
                attrs = {'name': 'storage',
                         'value': _('Unable to retrieve '
                                    '(Are the nodes configured properly?)'),
                         'unit': ''}
            storage = dummymodels.Capacity(name=attrs['name'],
                                           value=attrs['value'],
                                           unit=attrs['unit'])
            self._storage = Capacity(storage)
        return self._storage

    @property
    def network(self):
        if not hasattr(self, '_network'):
            try:
                attrs = dummymodels.Capacity.objects\
                        .filter(node__rack=self._apiresource)\
                        .values('name', 'unit').annotate(value=Sum('value'))\
                        .filter(name='network')[0]
            except:
                attrs = {'name': 'network',
                         'value': _('Unable to retrieve '
                                    '(Are the nodes configured properly?)'),
                         'unit': ''}
            network = dummymodels.Capacity(name=attrs['name'],
                                           value=attrs['value'],
                                           unit=attrs['unit'])
            self._network = Capacity(network)
        return self._network

    @property
    def vm_capacity(self):
        if not hasattr(self, '_vm_capacity'):
            try:
                value = dummymodels.ResourceClassFlavor.objects\
                            .filter(resource_class__rack=self._apiresource)\
                            .aggregate(Max("max_vms"))['max_vms__max']
            except:
                value = _("Unable to retrieve vm capacity")

            vm_capacity = dummymodels.Capacity(name=_("Max VMs"),
                                               value=value,
                                               unit=_("VMs"))
            self._vm_capacity = Capacity(vm_capacity)
        return self._vm_capacity

    @classmethod
    def delete(cls, request, rack_id):
        tuskarclient(request).racks.delete(rack_id)

    ## FIXME: this will have to be rewritten to ultimately
    ## fetch nodes from nova baremetal
    @property
    def list_nodes(self):
        return []
        #if not hasattr(self, '_nodes'):
        #    self._nodes = [Node(h) for h in self._apiresource.node_set.all()]
        #return self._nodes

    def nodes_count(self):
        return len(self._apiresource.nodes)

    # The idea here is to take a list of MAC addresses and assign them to
    # our rack. I'm attaching this here so that we can take one list, versus
    # potentially making a long series of API calls.
    # The present implementation makes no attempt at optimization since this
    # is likely short-lived until a real API is implemented.
    @classmethod
    def register_nodes(cls, rack_id, nodes_list):
        for mac in nodes_list:
            # search for MAC
            try:
                node = dummymodels.Node.objects.get(mac_address=mac)
                if node is not None:
                    node.rack_id = rack_id
                    node.save()
            except:
                # FIXME: It is unclear what we're supposed to do in this case.
                # I create a new Node, but it's possible we should not
                # allow new entries here.
                # FIXME: If this stays, we should probably add Capabilities
                # here so that graphs work as expected.
                Node.create(None, mac, mac, None, None, None, rack_id)

    @property
    def resource_class(self):
        if not hasattr(self, '_resource_class'):
            rclass = getattr(self._apiresource, 'resource_class', None)
            if rclass:
                self._resource_class = ResourceClass.get(self.request,
                        rclass['id'])
            else:
                self._resource_class = None
        return self._resource_class


class ResourceClass(StringIdAPIResourceWrapper):
    """Wrapper for the ResourceClass object  returned by the
    dummy model.
    """
    _attrs = ['id', 'name', 'service_type', 'racks']

    @classmethod
    def get(cls, request, resource_class_id):
        rc = cls(tuskarclient(request).resource_classes.get(resource_class_id))
        rc.set_request(request)
        return rc

    @classmethod
    def create(self, request, name, service_type):
        return ResourceClass(
            tuskarclient(request).resource_classes.create(
                name=name,
                service_type=service_type))

    @classmethod
    def list(self, request):
        return [ResourceClass(rc) for rc in
                tuskarclient(request).resource_classes.list()]

    @classmethod
    def update(cls, request, resource_class_id, **kwargs):
        return cls(tuskarclient(request).resource_classes.update(
                resource_class_id, **kwargs))

    @classmethod
    def delete(cls, request, resource_class_id):
        tuskarclient(request).resource_classes.delete(resource_class_id)

    @property
    def racks_ids(self):
        """ List of unicode ids of racks added to resource class """
        return [
            unicode(rack['id']) for rack in (
                self._apiresource.racks)]

    @property
    def list_racks(self):
        """ List of racks added to ResourceClass """
        if not hasattr(self, '_racks'):
            self._racks = [Rack.get(self.request, rid) for rid in (
                self.racks_ids)]
        return self._racks

    @property
    def all_racks(self):
        """ List of racks added to ResourceClass + list of free racks,
        meaning racks that don't belong to any ResourceClass"""
        if not hasattr(self, '_all_racks'):
            self._all_racks =\
                [r for r in (
                    Rack.list(self.request)) if (
                        r.resource_class_id is None or
                        str(r.resource_class_id) == self.id)]
        return self._all_racks

    @property
    def resource_class_flavors(self):
        """ Relation table resourceclassflavor """
        if not hasattr(self, '_resource_class_flavors'):
            self._resource_class_flavors = [ResourceClassFlavor(r) for r in (
                self._apiresource.resourceclassflavor_set.all())]
        return self._resource_class_flavors

    ## FIXME: this isn't currently supported by the client library, so would
    ## have to be done through curl
    @property
    def flavors_ids(self):
        """ List of unicode ids of flavors added to resource class """
        #return [
        #    unicode(flavor.flavor.id) for flavor in (
        #        self.resource_class_flavors)]
        return []

    ## FIXME: this isn't currently supported by the client library, so would
    ## have to be done through curl
    @property
    def list_flavors(self):
        """ Joined relation table resourceclassflavor and flavor together """
        #if not hasattr(self, '_flavors'):
        #    added_flavors = self.resource_class_flavors
        #    self._flavors = []
        #    for f in added_flavors:
        #        flavor_obj = Flavor.get(self.request, f.flavor.id)
        #        flavor_obj.set_max_vms(f.max_vms)
        #        self._flavors.append(flavor_obj)
        #return self._flavors
        return []

    ## FIXME: this isn't currently supported by the client library, so would
    ## have to be done through curl
    @property
    def all_flavors(self):
        """ Joined relation table resourceclassflavor with all global flavors
        """
        #if not hasattr(self, '_all_flavors'):
        #    all_flavors = Flavor.list(self.request)

        #    added_resourceclassflavors = \
        #        self._apiresource.resourceclassflavor_set.all()
        #    added_flavors = {}
        #    for added_flavor in added_resourceclassflavors:
        #        added_flavors[str(added_flavor.flavor_id)] = added_flavor

        #    self._all_flavors = []
        #    for f in all_flavors:
        #        added_flavor = added_flavors.get(f.id)
        #        if added_flavor:
        #            f.set_max_vms(added_flavor.max_vms)
        #        self._all_flavors.append(f)

        #return self._all_flavors
        return []

    @property
    def nodes(self):
        if not hasattr(self, '_nodes'):
            nodes_array = [rack.nodes for rack in self.racks]
            self._nodes = [node for nodes in nodes_array for node in nodes]
        return self._nodes

    @property
    def nodes_count(self):
        return len(self.nodes)

    @property
    def racks_count(self):
        return len(self.racks)

    @property
    def running_virtual_machines(self):
        if not hasattr(self, '_running_virtual_machines'):
            self._running_virtual_machines =\
                                    copy.deepcopy(self.resource_class_flavors)
            for vm in self._running_virtual_machines:
                vm.max_vms /= (vm.max_vms % 7) + 1
        return self._running_virtual_machines

    @property
    def cpu(self):
        if not hasattr(self, '_cpu'):
            try:
                attrs = dummymodels.Capacity.objects\
                        .filter(node__rack__resource_class=self._apiresource)\
                        .values('name', 'unit').annotate(value=Sum('value'))\
                        .filter(name='cpu')[0]
            except:
                attrs = {'name': 'cpu',
                         'value': _('Unable to retrieve '
                                    '(Are the nodes configured properly?)'),
                         'unit': ''}
            cpu = dummymodels.Capacity(name=attrs['name'],
                                             value=attrs['value'],
                                             unit=attrs['unit'])
            self._cpu = Capacity(cpu)
        return self._cpu

    @property
    def ram(self):
        if not hasattr(self, '_ram'):
            try:
                attrs = dummymodels.Capacity.objects\
                        .filter(node__rack__resource_class=self._apiresource)\
                        .values('name', 'unit').annotate(value=Sum('value'))\
                        .filter(name='ram')[0]
            except:
                attrs = {'name': 'ram',
                         'value': _('Unable to retrieve '
                                    '(Are the nodes configured properly?)'),
                         'unit': ''}
            ram = dummymodels.Capacity(name=attrs['name'],
                                             value=attrs['value'],
                                             unit=attrs['unit'])
            self._ram = Capacity(ram)
        return self._ram

    @property
    def storage(self):
        if not hasattr(self, '_storage'):
            try:
                attrs = dummymodels.Capacity.objects\
                        .filter(node__rack__resource_class=self._apiresource)\
                        .values('name', 'unit').annotate(value=Sum('value'))\
                        .filter(name='storage')[0]
            except:
                attrs = {'name': 'storage',
                         'value': _('Unable to retrieve '
                                    '(Are the nodes configured properly?)'),
                         'unit': ''}
            storage = dummymodels.Capacity(name=attrs['name'],
                                                 value=attrs['value'],
                                                 unit=attrs['unit'])
            self._storage = Capacity(storage)
        return self._storage

    @property
    def network(self):
        if not hasattr(self, '_network'):
            try:
                attrs = dummymodels.Capacity.objects\
                        .filter(node__rack__resource_class=self._apiresource)\
                        .values('name', 'unit').annotate(value=Sum('value'))\
                        .filter(name='network')[0]
            except:
                attrs = {'name': 'network',
                         'value': _('Unable to retrieve '
                                    '(Are the nodes configured properly?)'),
                         'unit': ''}
            network = dummymodels.Capacity(name=attrs['name'],
                                           value=attrs['value'],
                                           unit=attrs['unit'])
            self._network = Capacity(network)
        return self._network

    @property
    def vm_capacity(self):
        if not hasattr(self, '_vm_capacity'):
            try:
                value = dummymodels.ResourceClassFlavor.objects\
                            .filter(resource_class=self._apiresource)\
                            .aggregate(Max("max_vms"))['max_vms__max']
            except:
                value = _("Unable to retrieve vm capacity")

            vm_capacity = dummymodels.Capacity(name=_("Max VMs"),
                                               value=value,
                                               unit=_("VMs"))
            self._vm_capacity = Capacity(vm_capacity)
        return self._vm_capacity

    ## FIXME: this will have to be done some other way
    def set_flavors(self, request, flavors_ids, max_vms=None):
        return
        # simply delete all and create new flavors, that'is
        # how the horizon flavors work
        #max_vms = max_vms or {}

        #for flavor_id in self.flavors_ids:
        #    ResourceClassFlavor.delete(request,
        #                               self.id,
        #                               flavor_id)

        #for flavor_id in flavors_ids:
        #    flavor = Flavor.get(request, flavor_id)
        #    ResourceClassFlavor.create(
        #        request,
        #        max_vms=max_vms.get(flavor.id),
        #        flavor=flavor._apiresource,
        #        resource_class=self._apiresource)

    def set_racks(self, request, racks_ids):
        # FIXME: there is a bug now in tuskar, we have to remove all racks at
        # first and then add new ones:
        # https://github.com/tuskar/tuskar/issues/37
        tuskarclient(request).resource_classes.update(self.id, racks=[])
        racks = [{'id': rid} for rid in racks_ids]
        tuskarclient(request).resource_classes.update(self.id, racks=racks)


class Flavor(StringIdAPIResourceWrapper):
    """Wrapper for the Flavor object returned by the
    dummy model.
    """
    _attrs = ['name']

    @property
    def max_vms(self):
        return getattr(self, '_max_vms', '0')

    def set_max_vms(self, value='0'):
        self._max_vms = value

    @classmethod
    def list(cls, request, only_free_racks=False):
        return [cls(f) for f in dummymodels.Flavor.objects.all()]

    @classmethod
    def get(cls, request, flavor_id):
        return cls(dummymodels.Flavor.objects.get(id=flavor_id))

    @classmethod
    def create(cls, request,
               name, vcpu, ram, root_disk, ephemeral_disk, swap_disk):
        flavor = dummymodels.Flavor(name=name)
        flavor.save()
        Capacity.create(request, flavor, 'vcpu', vcpu, '')
        Capacity.create(request, flavor, 'ram', ram, 'MB')
        Capacity.create(request, flavor, 'root_disk', root_disk, 'GB')
        Capacity.create(request,
                        flavor, 'ephemeral_disk', ephemeral_disk, 'GB')
        Capacity.create(request, flavor, 'swap_disk', swap_disk, 'MB')

    @property
    def capacities(self):
        if not hasattr(self, '_capacities'):
            self._capacities = [Capacity(c) for c in
                                self._apiresource.capacities.all()]
        return self._capacities

    def capacity(self, capacity_name):
        key = "_%s" % capacity_name
        if not hasattr(self, key):
            try:
                capacity = [c for c in self.capacities if (
                    c.name == capacity_name)][0]
            except:
                capacity = dummymodels.Capacity(
                    name=capacity_name,
                    value=_('Unable to retrieve '
                            '(Is the flavor configured properly?)'),
                    unit='')
            setattr(self, key, capacity)
        return getattr(self, key)

    @property
    def vcpu(self):
        return self.capacity('vcpu')

    @property
    def ram(self):
        return self.capacity('ram')

    @property
    def root_disk(self):
        return self.capacity('root_disk')

    @property
    def ephemeral_disk(self):
        return self.capacity('ephemeral_disk')

    @property
    def swap_disk(self):
        return self.capacity('swap_disk')

    @property
    def resource_class_flavors(self):
        if not hasattr(self, '_resource_class_flavors'):
            self._resource_class_flavors = [ResourceClassFlavor(r) for r in (
                self._apiresource.resourceclassflavor_set.all())]
        return self._resource_class_flavors

    @property
    def resource_classes(self):
        if not hasattr(self, '_resource_classes'):
            added_flavors = self.resource_class_flavors
            self._resource_classes = []
            for f in added_flavors:
                self._resource_classes.append(ResourceClass(f.resource_class))

        return self._resource_classes

    @property
    def running_virtual_machines(self):
        # arbitrary number
        return len(self.resource_classes) * 2

    # defines a random average of capacity - API should probably be able to
    # determine average of capacity based on capacity value and obejct_id
    def vms_over_time(self, start_time, end_time):
        values = []
        current_time = start_time
        while current_time <= end_time:
            values.append({'date': current_time,
                           'value': randint(0, self.running_virtual_machines)})
            current_time += timedelta(hours=1)

        return values

    @classmethod
    def update(cls, request, flavor_id, name, vcpu, ram, root_disk,
               ephemeral_disk, swap_disk):
        f = dummymodels.Flavor.objects.get(id=flavor_id)
        f.name = name
        f.save()
        flavor = cls(f)
        Capacity.update(request, flavor.vcpu.id, flavor._apiresource,
                        'vcpu', vcpu, '')
        Capacity.update(request, flavor.ram.id, flavor._apiresource,
                        'ram', ram, 'MB')
        Capacity.update(request, flavor.root_disk.id, flavor._apiresource,
                        'root_disk', root_disk, 'GB')
        Capacity.update(request, flavor.ephemeral_disk.id, flavor._apiresource,
                        'ephemeral_disk', ephemeral_disk, 'GB')
        Capacity.update(request, flavor.swap_disk.id, flavor._apiresource,
                        'swap_disk', swap_disk, 'MB')
        return flavor

    @classmethod
    def delete(cls, request, flavor_id):
        dummymodels.Flavor.objects.get(id=flavor_id).delete()


class ResourceClassFlavor(StringIdAPIResourceWrapper):
    """ FIXME this class will probably go away when connected to real API,
    real API doesn't have this realtion Table as separate entity"""

    """Wrapper for the ResourceClassFlavor object  returned by the
    dummy model.
    """

    _attrs = ['max_vms', 'flavor', 'resource_class']

    @property
    def flavor(self):
        if not hasattr(self, '_flavor'):
            self._flavor = self._apiresource.flavor
        return self._flavor

    @property
    def resource_class(self):
        if not hasattr(self, '_resource_class'):
            self._resource_class = self._apiresource.resource_class
        return self._resource_class

    @classmethod
    def create(cls, request, resource_class, flavor, max_vms=0):
        rc = dummymodels.ResourceClassFlavor(
            max_vms=max_vms,
            resource_class=resource_class,
            flavor=flavor)
        rc.save()
        return ResourceClassFlavor(rc)

    @classmethod
    def delete(cls, request, resource_class_id, flavor_id):
        dummymodels.ResourceClassFlavor.objects.filter(
            resource_class_id=resource_class_id,
            flavor_id=flavor_id).delete()