add nick
[laas.git] / src / dashboard / testing_utils.py
1 ##############################################################################
2 # Copyright (c) 2018 Parker Berberian, Sawyer Bergeron, and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 from django.contrib.auth.models import User
11 from django.core.files.base import ContentFile
12 from django.utils import timezone
13
14 import json
15 from datetime import timedelta
16
17 from booking.models import Booking
18 from account.models import UserProfile, Lab, LabStatus, VlanManager, PublicNetwork
19 from resource_inventory.models import (
20     ResourceTemplate,
21     ResourceProfile,
22     ResourceConfiguration,
23     InterfaceProfile,
24     InterfaceConfiguration,
25     Server,
26     DiskProfile,
27     CpuProfile,
28     Opsys,
29     Image,
30     Scenario,
31     Installer,
32     OPNFVRole,
33     RamProfile,
34     Network,
35 )
36 from resource_inventory.resource_manager import ResourceManager
37
38 """
39 Info for make_booking() function:
40 [topology] argument structure:
41     the [topology] argument should describe the structure of the pod
42     the top level should be a dictionary, with each key being a hostname
43     each value in the top level should be a dictionary with two keys:
44         "type" should map to a host profile instance
45         "nets" should map to a list of interfaces each with a list of
46             dictionaries each defining a network in the format
47             { "name": "netname", "tagged": True|False, "public": True|False }
48             each network is defined if a matching name is not found
49
50     sample argument structure:
51         topology={
52             "host1": {
53                       "type": instanceOf HostProfile,
54                       "role": instanceOf OPNFVRole
55                       "image": instanceOf Image
56                       "nets": [
57                                 0: [
58                                         0: { "name": "public", "tagged": True, "public": True },
59                                         1: { "name": "private", "tagged": False, "public": False },
60                                    ]
61                                 1: []
62                               ]
63                   }
64         }
65 """
66
67
68 def make_booking(owner=None, start=timezone.now(),
69                  end=timezone.now() + timedelta(days=1),
70                  lab=None, purpose="my_purpose",
71                  project="my_project", collaborators=[],
72                  topology={}, installer=None, scenario=None):
73
74     resource_template = make_resource_template()
75     resource = ResourceManager.getInstance().convertResourceBundle(resource_template)
76     if not resource:
77         raise Exception("Resource not created")
78
79     return Booking.objects.create(
80         resource=resource,
81         start=start,
82         end=end,
83         owner=owner,
84         purpose=purpose,
85         project=project,
86         lab=lab,
87     )
88
89
90 def make_network(name, lab, grb, public):
91     network = Network(name=name, bundle=grb, is_public=public)
92     if public:
93         public_net = lab.vlan_manager.get_public_vlan()
94         if not public_net:
95             raise Exception("No more public networks available")
96         lab.vlan_manager.reserve_public_vlan(public_net.vlan)
97         network.vlan_id = public_net.vlan
98     else:
99         private_nets = lab.vlan_manager.get_vlans(count=1)
100         if not private_nets:
101             raise Exception("No more generic vlans are available")
102         lab.vlan_manager.reserve_vlans(private_nets)
103         network.vlan_id = private_nets[0]
104
105     network.save()
106     return network
107
108
109 def make_resource_template(owner=None, lab=None, name="Test Template"):
110     if owner is None:
111         owner = make_user(username="template_owner")
112     if lab is None:
113         lab = make_lab(name="template_lab")
114     rt = ResourceTemplate.objects.create(name=name, owner=owner, lab=lab, public=True)
115     config = make_resource_config(rt)
116     make_interface_config(config)
117     return rt
118
119
120 def make_resource_config(template, profile=None, image=None):
121     if profile is None:
122         profile = make_resource_profile(lab=template.lab)
123
124     if image is None:
125         image = make_image(profile, lab=template.lab)
126
127     return ResourceConfiguration.objects.create(profile=profile, image=image, template=template)
128
129
130 def make_interface_config(resource_config):
131     # lets just grab one of the iface profiles from the related host
132     iface_profile = resource_config.profile.interfaceprofile.all()[0]
133
134     # not adding any connections here
135     return InterfaceConfiguration.objects.create(profile=iface_profile, resource_config=resource_config)
136
137
138 def make_user(is_superuser=False, username="testuser",
139               password="testpassword", email="default_email@user.com"):
140     user = User.objects.get_or_create(username=username, email=email, password=password)[0]
141
142     user.is_superuser = is_superuser
143     user.save()
144
145     return user
146
147
148 def make_user_profile(user=None, email_addr="email@email.com",
149                       company="company", full_name="John Doe",
150                       booking_privledge=True, ssh_file=None):
151     user = user or make_user()
152     profile = UserProfile.objects.get_or_create(
153         email_addr=email_addr,
154         company=company,
155         full_name=full_name,
156         booking_privledge=booking_privledge,
157         user=user
158     )[0]
159     profile.ssh_public_key.save("user_ssh_key", ssh_file if ssh_file else ContentFile("public key content string"))
160
161     return profile
162
163
164 def make_vlan_manager(vlans=None, block_size=20, allow_overlapping=False, reserved_vlans=None):
165     if not vlans:
166         vlans = [vlan % 2 for vlan in range(4095)]
167     if not reserved_vlans:
168         reserved_vlans = [0 for i in range(4095)]
169
170     return VlanManager.objects.create(
171         vlans=json.dumps(vlans),
172         reserved_vlans=json.dumps(vlans),
173         block_size=block_size,
174         allow_overlapping=allow_overlapping
175     )
176
177
178 def make_lab(user=None, name="Test_Lab_Instance",
179              status=LabStatus.UP, vlan_manager=None,
180              pub_net_count=5):
181     if Lab.objects.filter(name=name).exists():
182         return Lab.objects.get(name=name)
183
184     if not vlan_manager:
185         vlan_manager = make_vlan_manager()
186
187     if not user:
188         user = make_user(username=name + " user")
189
190     lab = Lab.objects.create(
191         lab_user=user,
192         name=name,
193         contact_email='test_lab@test_site.org',
194         contact_phone='603 123 4567',
195         status=status,
196         vlan_manager=vlan_manager,
197         description='test lab instantiation',
198         api_token='12345678'
199     )
200
201     for i in range(pub_net_count):
202         make_public_net(vlan=i * 2 + 1, lab=lab)
203
204     return lab
205
206
207 """
208 resource_inventory instantiation section for permanent resources
209 """
210
211
212 def make_resource_profile(lab, name="test_hostprofile"):
213     if ResourceProfile.objects.filter(name=name).exists():
214         return ResourceProfile.objects.get(name=name)
215
216     resource_profile = ResourceProfile.objects.create(
217         name=name,
218         description='test resourceprofile instance'
219     )
220     resource_profile.labs.add(lab)
221
222     RamProfile.objects.create(host=resource_profile, amount=8, channels=2)
223     CpuProfile.objects.create(cores=4, architecture="x86_64", cpus=1, host=resource_profile)
224     DiskProfile.objects.create(
225         name="test disk profile",
226         size=256,
227         media_type="SSD",
228         host=resource_profile
229     )
230
231     InterfaceProfile.objects.create(
232         host=resource_profile,
233         name="test interface profile",
234         speed=1000,
235         nic_type="pcie"
236     )
237
238     return resource_profile
239
240
241 def make_image(resource_profile, lab=None, lab_id="4", owner=None, os=None,
242                public=True, name="default image", description="default image"):
243     if lab is None:
244         lab = make_lab()
245
246     if owner is None:
247         owner = make_user()
248
249     if os is None:
250         os = make_os()
251
252     return Image.objects.create(
253         from_lab=lab,
254         lab_id=lab_id,
255         os=os,
256         host_type=resource_profile,
257         public=public,
258         name=name,
259         description=description
260     )
261
262
263 def make_scenario(name="test scenario"):
264     return Scenario.objects.create(name=name)
265
266
267 def make_installer(scenarios, name="test installer"):
268     installer = Installer.objects.create(name=name)
269     for scenario in scenarios:
270         installer.sup_scenarios.add(scenario)
271
272     return installer
273
274
275 def make_os(installers=None, name="test OS"):
276     if not installers:
277         installers = [make_installer([make_scenario()])]
278     os = Opsys.objects.create(name=name)
279     for installer in installers:
280         os.sup_installers.add(installer)
281
282     return os
283
284
285 def make_server(host_profile, lab, labid="test_host", name="test_host",
286                 booked=False, working=True, config=None,
287                 bundle=None, model="Model 1", vendor="ACME"):
288     return Server.objects.create(
289         lab=lab,
290         profile=host_profile,
291         name=name,
292         booked=booked,
293         working=working,
294         config=config,
295         bundle=bundle,
296         model=model,
297         vendor=vendor
298     )
299
300
301 def make_opnfv_role(name="Jumphost", description="test opnfvrole"):
302     return OPNFVRole.objects.create(
303         name=name,
304         description=description
305     )
306
307
308 def make_public_net(vlan, lab, in_use=False,
309                     cidr="0.0.0.0/0", gateway="0.0.0.0"):
310     return PublicNetwork.objects.create(
311         lab=lab,
312         vlan=vlan,
313         cidr=cidr,
314         gateway=gateway
315     )