forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtestpath_usage.py
More file actions
3413 lines (2805 loc) · 124 KB
/
Copy pathtestpath_usage.py
File metadata and controls
3413 lines (2805 loc) · 124 KB
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
""" Test cases for Usage Test Path
"""
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import (cleanup_resources,
validateList,
verifyRouterState,
get_process_status)
from marvin.lib.base import (Account,
ServiceOffering,
VirtualMachine,
Template,
Iso,
DiskOffering,
Volume,
Snapshot,
PublicIPAddress,
LoadBalancerRule,
EgressFireWallRule,
Router,
VmSnapshot,
Usage,
Configurations,
FireWallRule,
NATRule,
StaticNATRule,
Network,
Vpn,
VpnUser,
VpcOffering,
VPC,
NetworkACL)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
createEnabledNetworkOffering,
get_builtin_template_info,
findSuitableHostForMigration,
list_hosts,
list_volumes,
list_routers)
from marvin.codes import (PASS, FAIL, ERROR_NO_HOST_FOR_MIGRATION)
from marvin.sshClient import SshClient
import time
def CreateEnabledNetworkOffering(apiclient, networkServices):
"""Create network offering of given services and enable it"""
result = createEnabledNetworkOffering(apiclient, networkServices)
assert result[0] == PASS,\
"Network offering creation/enabling failed due to %s" % result[2]
return result[1]
class TestUsage(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestUsage, cls).getClsTestClient()
cls.hypervisor = testClient.getHypervisorInfo()
cls.apiclient = testClient.getApiClient()
cls.testdata = testClient.getParsedTestDataConfig()
cls._cleanup = []
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.mgtSvrDetails = cls.config.__dict__["mgtSvr"][0].__dict__
isUsageJobRunning = cls.IsUsageJobRunning()
cls.usageJobNotRunning = False
if not isUsageJobRunning:
cls.usageJobNotRunning = True
return
if cls.testdata["configurableData"][
"setUsageConfigurationThroughTestCase"]:
cls.setUsageConfiguration()
cls.RestartServers()
else:
currentMgtSvrTime = cls.getCurrentMgtSvrTime()
dateTimeSplit = currentMgtSvrTime.split("/")
cls.curDate = dateTimeSplit[0]
cls.hypervisor = testClient.getHypervisorInfo()
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.testdata["ostype"])
try:
# If local storage is enabled, alter the offerings to use
# localstorage
if cls.zone.localstorageenable:
cls.testdata["service_offering"]["storagetype"] = 'local'
# Create 2 service offerings with different values for
# for cpunumber, cpuspeed, and memory
cls.testdata["service_offering"]["cpunumber"] = "1"
cls.testdata["service_offering"]["cpuspeed"] = "128"
cls.testdata["service_offering"]["memory"] = "256"
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"]
)
cls._cleanup.append(cls.service_offering)
cls.testdata["service_offering"]["cpunumber"] = "2"
cls.testdata["service_offering"]["cpuspeed"] = "256"
cls.testdata["service_offering"]["memory"] = "512"
cls.service_offering_2 = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"]
)
cls._cleanup.append(cls.service_offering_2)
# Create isolated network offering
cls.isolated_network_offering = CreateEnabledNetworkOffering(
cls.apiclient,
cls.testdata["isolated_network_offering"]
)
cls._cleanup.append(cls.isolated_network_offering)
cls.isolated_network_offering_2 = CreateEnabledNetworkOffering(
cls.apiclient,
cls.testdata["isolated_network_offering"]
)
cls._cleanup.append(cls.isolated_network_offering_2)
cls.isolated_network_offering_vpc = CreateEnabledNetworkOffering(
cls.apiclient,
cls.testdata["nw_offering_isolated_vpc"]
)
cls._cleanup.append(cls.isolated_network_offering_vpc)
cls.testdata["shared_network_offering_all_services"][
"specifyVlan"] = "True"
cls.testdata["shared_network_offering_all_services"][
"specifyIpRanges"] = "True"
cls.shared_network_offering = CreateEnabledNetworkOffering(
cls.apiclient,
cls.testdata["shared_network_offering_all_services"]
)
cls._cleanup.append(cls.shared_network_offering)
configs = Configurations.list(
cls.apiclient,
name='usage.stats.job.aggregation.range'
)
# Set the value for one more minute than
# actual range to be on safer side
cls.usageJobAggregationRange = (
int(configs[0].value) + 1) * 60 # in seconds
except Exception as e:
cls.tearDownClass()
raise e
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
if self.usageJobNotRunning:
self.skipTest("Skipping test because usage job not running")
# Create an account
self.account = Account.create(
self.apiclient,
self.testdata["account"],
domainid=self.domain.id
)
self.cleanup.append(self.account)
# Create user api client of the account
self.userapiclient = self.testClient.getUserApiClient(
UserName=self.account.name,
DomainName=self.account.domain
)
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def setUsageConfiguration(cls):
""" Set the configuration parameters so that usage job runs
every 10 miuntes """
Configurations.update(
cls.apiclient,
name="enable.usage.server",
value="true"
)
Configurations.update(
cls.apiclient,
name="usage.aggregation.timezone",
value="GMT"
)
Configurations.update(
cls.apiclient,
name="usage.execution.timezone",
value="GMT"
)
Configurations.update(
cls.apiclient,
name="usage.stats.job.aggregation.range",
value="10"
)
currentMgtSvrTime = cls.getCurrentMgtSvrTime()
dateTimeSplit = currentMgtSvrTime.split("/")
cls.curDate = dateTimeSplit[0]
timeSplit = dateTimeSplit[1].split(":")
minutes = int(timeSplit[1])
minutes += 5
usageJobExecTime = timeSplit[0] + ":" + str(minutes)
Configurations.update(
cls.apiclient,
name="usage.stats.job.exec.time",
value=usageJobExecTime
)
return
@classmethod
def getCurrentMgtSvrTime(cls, format='%Y-%m-%d/%H:%M'):
""" Get the current time from Management Server """
sshClient = SshClient(
cls.mgtSvrDetails["mgtSvrIp"],
22,
cls.mgtSvrDetails["user"],
cls.mgtSvrDetails["passwd"]
)
command = "date +%s" % format
return sshClient.execute(command)[0]
@classmethod
def RestartServers(cls):
""" Restart management server and usage server """
sshClient = SshClient(
cls.mgtSvrDetails["mgtSvrIp"],
22,
cls.mgtSvrDetails["user"],
cls.mgtSvrDetails["passwd"]
)
command = "service cloudstack-management restart"
sshClient.execute(command)
command = "service cloudstack-usage restart"
sshClient.execute(command)
return
@classmethod
def IsUsageJobRunning(cls):
""" Check that usage job is running on Management server or not"""
sshClient = SshClient(
cls.mgtSvrDetails["mgtSvrIp"],
22,
cls.mgtSvrDetails["user"],
cls.mgtSvrDetails["passwd"]
)
command = "service cloudstack-usage status"
response = str(sshClient.execute(command)).lower()
if "running" not in response:
return False
return True
def getLatestUsageJobExecutionTime(self):
""" Get the end time of latest usage job that has run successfully"""
try:
qresultset = self.dbclient.execute(
"SELECT max(end_date) FROM usage_job WHERE success=1;",
db="cloud_usage")
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
lastUsageJobExecutionTime = qresultset[0][0]
self.debug(
"last usage job exec time: %s" %
lastUsageJobExecutionTime)
return [PASS, lastUsageJobExecutionTime]
except Exception as e:
return [FAIL, e]
def getEventCreatedDateTime(self, resourceName):
""" Get the created date/time of particular entity
from cloud_usage.usage_event table """
try:
# Checking exact entity creation time
qresultset = self.dbclient.execute(
"select created from usage_event where resource_name = '%s';" %
str(resourceName), db="cloud_usage")
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
eventCreatedDateTime = qresultset[0][0]
except Exception as e:
return [FAIL, e]
return [PASS, eventCreatedDateTime]
def listUsageRecords(self, usagetype, apiclient=None, startdate=None,
enddate=None, account=None, sleep=True):
"""List and return the usage record for given account
and given usage type"""
if sleep:
# Sleep till usage job has run at least once after the operation
self.debug(
"Sleeping for %s seconds" %
self.usageJobAggregationRange)
time.sleep(self.usageJobAggregationRange)
if not startdate:
startdate = self.curDate
if not enddate:
enddate = self.curDate
if not account:
account = self.account
if not apiclient:
self.apiclient
Usage.generateRecords(
self.apiclient,
startdate=startdate,
enddate=enddate)
try:
usageRecords = Usage.listRecords(
self.apiclient,
startdate=startdate,
enddate=enddate,
account=account.name,
domainid=account.domainid,
type=usagetype)
self.assertEqual(
validateList(usageRecords)[0],
PASS,
"usage records list validation failed")
return [PASS, usageRecords]
except Exception as e:
return [FAIL, e]
return
def getCommandResultFromRouter(self, router, command):
"""Run given command on router and return the result"""
if (self.hypervisor.lower() == 'vmware'
or self.hypervisor.lower() == 'hyperv'):
result = get_process_status(
self.apiclient.connection.mgtSvr,
22,
self.apiclient.connection.user,
self.apiclient.connection.passwd,
router.linklocalip,
command,
hypervisor=self.hypervisor
)
else:
hosts = list_hosts(
self.apiclient,
id=router.hostid,
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check for list hosts response return valid data"
)
host = hosts[0]
host.user = self.testdata["configurableData"]["host"]["username"]
host.passwd = self.testdata["configurableData"]["host"]["password"]
result = get_process_status(
host.ipaddress,
22,
host.user,
host.passwd,
router.linklocalip,
command
)
return result
@attr(tags=["advanced"], required_hardware="True")
def test_01_positive_tests_usage(self):
""" Positive test for usage test path
# 1. Register a template and verify that usage usage is generated
for correct size of template
# 2. Register an ISO, verify usage is generate for the correct size
of ISO
# 3. Deploy a VM from the template and verify usage is generated
for the VM with correct Service Offering and template id
# 4. Delete template and iso
# 5. Stop and start the VM
# 6. Verify that allocated VM usage should be greater than
running VM usage
# 7. Destroy the Vm and recover it
# 8. Verify that the running VM usage stays the same after delete and
and after recover operation
# 9. Verify that allocated VM usage should be greater after recover
operation than after destroy operation
# 10. Change service offering of the VM
# 11. Verify that VM usage is generated for the VM with correct
service offering
# 12. Start the VM
# 13. Verify that the running VM usage after start operation is less
than the allocated VM usage
# 14. Verify that the running VM usage after start vm opearation
is greater running VM usage after recover VM operation
"""
# Step 1
# Register a private template in the account
builtin_info = get_builtin_template_info(
self.apiclient,
self.zone.id
)
self.testdata["privatetemplate"]["url"] = builtin_info[0]
self.testdata["privatetemplate"]["hypervisor"] = builtin_info[1]
self.testdata["privatetemplate"]["format"] = builtin_info[2]
# Register new template
template = Template.register(
self.userapiclient,
self.testdata["privatetemplate"],
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.cleanup.append(template)
template.download(self.userapiclient)
templates = Template.list(
self.userapiclient,
listall=True,
id=template.id,
templatefilter="self")
self.assertEqual(
validateList(templates)[0],
PASS,
"Templates list validation failed")
# Checking template usage
response = self.listUsageRecords(usagetype=7)
self.assertEqual(response[0], PASS, response[1])
templateUsageRecords = [record for record in response[1]
if template.id == record.usageid]
self.assertEqual(templateUsageRecords[0].virtualsize,
templates[0].size,
"The template size in the usage record and \
does not match with the created template size")
# Getting last usage job execution time
response = self.getLatestUsageJobExecutionTime()
self.assertEqual(response[0], PASS, response[1])
lastUsageJobExecTime = response[1]
# Checking exact template creation time
response = self.getEventCreatedDateTime(template.name)
self.assertEqual(response[0], PASS, response[1])
templateCreatedDateTime = response[1]
self.debug("Template creation date: %s" % templateCreatedDateTime)
# We have to get the expected usage count in hours as the rawusage returned by listUsageRecords
# is also in hours
expectedUsage = format(
((lastUsageJobExecTime - templateCreatedDateTime).total_seconds() / 3600),
".2f")
actualUsage = format(sum(float(record.rawusage)
for record in templateUsageRecords), ".2f")
self.assertEqual(
expectedUsage,
actualUsage,
"expected usage %s and actual usage %s not matching" %
(expectedUsage,
actualUsage))
# step 2
iso = Iso.create(
self.userapiclient,
self.testdata["iso"],
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
self.cleanup.append(iso)
iso.download(self.apiclient)
isos = Iso.list(
self.userapiclient,
id=iso.id,
listall=True)
self.assertEqual(
validateList(isos)[0],
PASS,
"Iso list validation failed"
)
# Checking usage for Iso
response = self.listUsageRecords(usagetype=8)
self.assertEqual(response[0], PASS, response[1])
isoUsageRecords = [record for record in response[1]
if iso.id == record.usageid]
self.assertEqual(isoUsageRecords[0].size,
isos[0].size,
"The iso size in the usage record and \
does not match with the created iso size")
# Getting last usage job execution time
response = self.getLatestUsageJobExecutionTime()
self.assertEqual(response[0], PASS, response[1])
lastUsageJobExecTime = response[1]
# Checking exact Iso creation time
response = self.getEventCreatedDateTime(iso.name)
self.assertEqual(response[0], PASS, response[1])
isoCreatedDateTime = response[1]
self.debug("Iso creation date: %s" % isoCreatedDateTime)
# We have to get the expected usage count in hours as the rawusage returned by listUsageRecords
# is also in hours
expectedUsage = format(
((lastUsageJobExecTime - isoCreatedDateTime).total_seconds() / 3600),
".2f")
actualUsage = format(sum(float(record.rawusage)
for record in isoUsageRecords), ".2f")
self.assertEqual(
expectedUsage,
actualUsage,
"expected usage %s and actual usage %s not matching" %
(expectedUsage,
actualUsage))
# step 3
# Create VM in account
vm = VirtualMachine.create(
self.userapiclient,
self.testdata["small"],
templateid=template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id
)
# Checking running VM usage
response = self.listUsageRecords(usagetype=1)
self.assertEqual(response[0], PASS, response[1])
vmRunningUsageRecords = [record for record in response[1]
if record.virtualmachineid == vm.id]
vmRunningRawUsage = sum(float(record.rawusage)
for record in vmRunningUsageRecords)
self.assertEqual(vmRunningUsageRecords[0].offeringid,
self.service_offering.id,
"The service offering id in the usage record\
does not match with id of service offering\
with which the VM was created")
self.assertEqual(vmRunningUsageRecords[0].templateid,
template.id,
"The template id in the usage record\
does not match with id of template\
with which the VM was created")
response = self.listUsageRecords(usagetype=2, sleep=False)
self.assertEqual(response[0], PASS, response[1])
vmAllocatedUsageRecords = [record for record in response[1]
if record.virtualmachineid == vm.id]
vmAllocatedRawUsage = sum(float(record.rawusage)
for record in vmAllocatedUsageRecords)
self.debug("running vm usage: %s" % vmRunningRawUsage)
self.debug("allocated vm usage: %s" % vmAllocatedRawUsage)
self.assertTrue(
vmRunningRawUsage < vmAllocatedRawUsage,
"Allocated VM usage should be greater than Running VM usage")
# Getting last usage job execution time
response = self.getLatestUsageJobExecutionTime()
self.assertEqual(response[0], PASS, response[1])
lastUsageJobExecTime = response[1]
# Checking exact VM creation time
response = self.getEventCreatedDateTime(vm.name)
self.assertEqual(response[0], PASS, response[1])
vmCreatedDateTime = response[1]
self.debug("Vm creation date: %s" % vmCreatedDateTime)
# We have to get the expected usage count in hours as the rawusage returned by listUsageRecords
# is also in hours
expectedUsage = format(
((lastUsageJobExecTime - vmCreatedDateTime).total_seconds() / 3600),
".2f")
self.debug("VM expected usage: %s" % expectedUsage)
actualUsage = format(vmAllocatedRawUsage, ".2f")
self.assertEqual(
expectedUsage,
actualUsage,
"expected usage %s and actual usage %s not matching" %
(expectedUsage,
actualUsage))
# Step 4 - Deleting template and ISO
template.delete(self.userapiclient)
self.cleanup.remove(template)
iso.delete(self.userapiclient)
self.cleanup.remove(iso)
# Verifying that usage for template and ISO is stopped
response = self.listUsageRecords(usagetype=7)
self.assertEqual(response[0], PASS, response[1])
templateUsageRecords = response[1]
usageForTemplateAfterDeletion_1 = sum(
float(
record.rawusage) for record in [
record for record in templateUsageRecords
if template.id == record.usageid])
response = self.listUsageRecords(usagetype=8, sleep=False)
self.assertEqual(response[0], PASS, response[1])
isoUsageRecords = response[1]
usageForIsoAfterDeletion_1 = sum(
float(
record.rawusage) for record in [
record for record in isoUsageRecords
if iso.id == record.usageid])
response = self.listUsageRecords(usagetype=7)
self.assertEqual(response[0], PASS, response[1])
templateUsageRecords = response[1]
usageForTemplateAfterDeletion_2 = sum(
float(
record.rawusage) for record in [
record for record in templateUsageRecords
if template.id == record.usageid])
response = self.listUsageRecords(usagetype=8, sleep=False)
self.assertEqual(response[0], PASS, response[1])
isoUsageRecords = response[1]
usageForIsoAfterDeletion_2 = sum(
float(
record.rawusage) for record in [
record for record in isoUsageRecords
if iso.id == record.usageid])
self.assertTrue(usageForTemplateAfterDeletion_1 ==
usageForTemplateAfterDeletion_2,
"usage for template after deletion should remain the same\
after specific intervals of time")
self.assertTrue(usageForIsoAfterDeletion_1 ==
usageForIsoAfterDeletion_2,
"usage for iso after deletion should remain the same\
after specific intervals of time")
# Step 5
vm.stop(self.userapiclient)
# Sleep to get difference between allocated and running usage
time.sleep(120)
vm.start(self.userapiclient)
# Step 6: Verifying allocated usage is greater than running usage
response = self.listUsageRecords(usagetype=1)
self.assertEqual(response[0], PASS, response[1])
vmRunningUsageRecords = [record for record in response[1]
if record.virtualmachineid == vm.id]
vmRunningRawUsage = sum(float(record.rawusage)
for record in vmRunningUsageRecords)
response = self.listUsageRecords(usagetype=2, sleep=False)
self.assertEqual(response[0], PASS, response[1])
vmAllocatedUsageRecords = [record for record in response[1]
if record.virtualmachineid == vm.id]
vmAllocatedRawUsage = sum(float(record.rawusage)
for record in vmAllocatedUsageRecords)
self.debug("running vm usage: %s" % vmRunningRawUsage)
self.debug("allocated vm usage: %s" % vmAllocatedRawUsage)
self.assertTrue(
vmRunningRawUsage < vmAllocatedRawUsage,
"Allocated VM usage should be greater than Running VM usage")
# Step 7
vm.delete(self.userapiclient, expunge=False)
response = self.listUsageRecords(usagetype=1, sleep=False)
self.assertEqual(response[0], PASS, response[1])
vmRunningUsageRecordAfterDestroy = sum(
float(
record.rawusage) for record in response[1] if
record.virtualmachineid == vm.id)
response = self.listUsageRecords(usagetype=2, sleep=False)
self.assertEqual(response[0], PASS, response[1])
vmAllocatedUsageRecordAfterDestroy = sum(
float(
record.rawusage) for record in response[1] if record.virtualmachineid == vm.id)
vm.recover(self.apiclient)
# Step 8
response = self.listUsageRecords(usagetype=1)
self.assertEqual(response[0], PASS, response[1])
vmRunningUsageRecordAfterRecover = sum(
float(
record.rawusage) for record in response[1] if
record.virtualmachineid == vm.id)
response = self.listUsageRecords(usagetype=2, sleep=False)
self.assertEqual(response[0], PASS, response[1])
vmAllocatedUsageRecordAfterRecover = sum(
float(
record.rawusage) for record in response[1] if
record.virtualmachineid == vm.id)
self.debug(
"running vm usage T1: %s" %
vmRunningUsageRecordAfterDestroy)
self.debug(
"allocated vm usage T1: %s" %
vmRunningUsageRecordAfterRecover)
self.assertEqual(
format(vmRunningUsageRecordAfterDestroy, ".1f"),
format(vmRunningUsageRecordAfterRecover, ".1f"),
"Running usage should remain the same")
self.debug(
"allocated vm usage T2: %s" %
vmAllocatedUsageRecordAfterDestroy)
self.debug(
"allocated vm usage T2: %s" %
vmAllocatedUsageRecordAfterRecover)
# Step 9
self.assertTrue(
vmAllocatedUsageRecordAfterDestroy <
vmAllocatedUsageRecordAfterRecover,
"Allocated VM usage after recover should be greater than\
before")
# Step 10
# Change service offering of VM and verify that it is changed
vm.change_service_offering(
self.userapiclient,
serviceOfferingId=self.service_offering_2.id
)
response = self.listUsageRecords(usagetype=2)
self.assertEqual(response[0], PASS, response[1])
vmAllocatedUsageRecord = response[1][-1]
# Step 11: Veriying vm usage for new service offering
self.assertEqual(vmAllocatedUsageRecord.offeringid,
self.service_offering_2.id,
"The service offering id in the usage record\
does not match with id of new service offering")
# Step 12
vm.start(self.userapiclient)
response = self.listUsageRecords(usagetype=1)
self.assertEqual(response[0], PASS, response[1])
vmRunningUsageRecordAfterStart = sum(
float(
record.rawusage) for record in response[1] if
record.virtualmachineid == vm.id)
response = self.listUsageRecords(usagetype=2, sleep=False)
self.assertEqual(response[0], PASS, response[1])
vmAllocatedUsageRecordAfterStart = sum(
float(
record.rawusage) for record in response[1] if
record.virtualmachineid == vm.id)
self.debug("running vm usage T3: %s" % vmRunningUsageRecordAfterStart)
self.debug(
"allocated vm usage T3: %s" %
vmAllocatedUsageRecordAfterStart)
# Step 13
self.assertTrue(
vmRunningUsageRecordAfterStart <
vmAllocatedUsageRecordAfterStart,
"Allocated VM usage should be greater than Running usage")
# Step 14
self.assertTrue(
vmRunningUsageRecordAfterRecover <
vmRunningUsageRecordAfterStart,
"Running VM usage after start VM should be greater than\
that after recover operation")
return
@attr(tags=["advanced"], required_hardware="true")
def test_02_positive_tests_usage(self):
""" Positive test for usage test path
# 1. Scale up VM and check that usage is generated for
new cpu and ram value (Check in usage_vm_instance table)
# 2. Scale down VM and check that usage is generated for
new cpu and ram value (Check in usage_vm_instance table)
# 3. Attach disk to VM and check that volume usage is
generated for correct disk offering
# 4. Detach volume from and verify that usage for volue remains
the same there afterwards
# 5. Create snapshot of the root disk and verify correct usage is
generated for snapshot with correct size
# 6. Create template from root disk and check correct usage is
generated for template with correct size
# 7. Delete the template and verify that usage is stopped for
template
# 8. Create volume from snaopshot and verify correct disk usage
is generated
# 9. Delete the volume and verify that the usage is stopped
# 10. Create template from snapshot and verify correct usage
is generated for the template with correct size
"""
# Step 1
# Create dynamic and static service offering
self.testdata["service_offering"]["cpunumber"] = ""
self.testdata["service_offering"]["cpuspeed"] = ""
self.testdata["service_offering"]["memory"] = ""
serviceOffering_dynamic = ServiceOffering.create(
self.apiclient,
self.testdata["service_offering"]
)
self.cleanup.append(serviceOffering_dynamic)
customcpunumber = 1
customcpuspeed = 256
custommemory = 128
# Deploy VM with dynamic service offering
virtualMachine = VirtualMachine.create(
self.userapiclient,
self.testdata["virtual_machine"],
serviceofferingid=serviceOffering_dynamic.id,
templateid=self.template.id,
zoneid=self.zone.id,
accountid=self.account.name,
domainid=self.account.domainid,
customcpunumber=customcpunumber,
customcpuspeed=customcpuspeed,
custommemory=custommemory
)
# Stop VM and verify that it is in stopped state
virtualMachine.stop(self.userapiclient)
scaledcpunumber = 2
scaledcpuspeed = 512
scaledmemory = 256
# Scale up VM
virtualMachine.scale(
self.userapiclient,
serviceOfferingId=serviceOffering_dynamic.id,
customcpunumber=scaledcpunumber,
customcpuspeed=scaledcpuspeed,
custommemory=scaledmemory
)
self.listUsageRecords(usagetype=1)
qresultset = self.dbclient.execute(
"select cpu_cores, memory, cpu_speed from usage_vm_instance where vm_name = '%s';" %
str(virtualMachine.name), db="cloud_usage")
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
dbcpucores = qresultset[-1][0]
dbmemory = qresultset[-1][1]
dbcpuspeed = qresultset[-1][2]
self.assertEqual(int(dbcpucores), scaledcpunumber,
"scaled cpu number not matching with db record")
self.assertEqual(int(dbmemory), scaledmemory,
"scaled memory not matching with db record")
self.assertEqual(int(dbcpuspeed), scaledcpuspeed,
"scaled cpu speed not matching with db record")
scaledcpunumber = 1
scaledcpuspeed = 512
scaledmemory = 256
# Step 2
# Scale down VM
virtualMachine.scale(
self.userapiclient,
serviceOfferingId=serviceOffering_dynamic.id,
customcpunumber=scaledcpunumber,
customcpuspeed=scaledcpuspeed,
custommemory=scaledmemory
)
self.listUsageRecords(usagetype=1)
qresultset = self.dbclient.execute(
"select cpu_cores, memory, cpu_speed from usage_vm_instance where vm_name = '%s';" %
str(virtualMachine.name), db="cloud_usage")
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
dbcpucores = qresultset[-1][0]
dbmemory = qresultset[-1][1]
dbcpuspeed = qresultset[-1][2]
self.assertEqual(int(dbcpucores), scaledcpunumber,
"scaled cpu number not matching with db record")
self.assertEqual(int(dbmemory), scaledmemory,
"scaled memory not matching with db record")
self.assertEqual(int(dbcpuspeed), scaledcpuspeed,
"scaled cpu speed not matching with db record")
disk_offering = DiskOffering.create(