cc1  v2.1
CC1 source code docs
 All Classes Namespaces Files Functions Variables Pages
user_network.py
Go to the documentation of this file.
1 # -*- coding: utf-8 -*-
2 # @COPYRIGHT_begin
3 #
4 # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 # @COPYRIGHT_end
19 
20 ##
21 # @package src.cm.views.user.network
22 # @author Maciej Nabo┼╝ny <mn@mnabozny.pl>
23 #
24 #
25 # Database model describing user network
26 #
27 
28 from django.db import models
29 
30 from cm.models.lease import Lease
31 from cm.utils.exception import CMException
32 from netaddr import IPNetwork
33 
34 
35 class UserNetwork(models.Model):
36  address = models.CharField(max_length=20)
37  mask = models.IntegerField()
38  available_network = models.ForeignKey('AvailableNetwork')
39  user = models.ForeignKey('User')
40  name = models.CharField(max_length=200)
41 
42  class Meta:
43  app_label = 'cm'
44 
45  def __unicode__(self):
46  return "%s/%d" % (self.address, self.mask)
47 
48  @property
49  def dict(self):
50  d = {}
51 
52  d['total_leases'] = self.lease_set.count()
53  d['used_leases'] = d['total_leases'] - Lease.objects.filter(user_network=self).filter(vm=None).count()
54  d['network_id'] = self.id
55  d['address'] = self.address
56  d['mask'] = self.mask
57  d['available_network_id'] = self.available_network.id
58  d['user_id'] = self.user.id
59  d['name'] = self.name
60  return d
61 
62  def to_cidr(self):
63  return self.address + "/" + str(self.mask)
64 
65  def to_ipnetwork(self):
66  return IPNetwork(self.address + "/" + str(self.mask))
67 
68  def is_in_use(self):
69  for lease in self.lease_set.all():
70  if lease.vm != None:
71  return True
72  return False
73 
74  def allocate(self):
75  host_id = 0
76  for host in self.to_ipnetwork().iter_hosts():
77  host_id += 1
78  # TODO: change it when using bridge networking model
79  if host_id % 4 == 0:
80  lease = Lease()
81  lease.address = host
82  lease.user_network = self
83  lease.save()
84 
85  ##
86  #
87  # Remove all leases from this network
88  #
89  def release(self):
90  if self.is_in_use():
91  raise CMException('network_in_use')
92 
93  for lease in self.lease_set.all():
94  lease.delete()
95 
96  def get_unused(self):
97  leases = filter(lambda x: x.vm == None, self.lease_set.all())
98  if len(leases) == 0:
99  raise CMException('lease_not_found')
100  else:
101  return leases[0]
102