-
Notifications
You must be signed in to change notification settings - Fork 6
/
test_collect-logs.py
1321 lines (1126 loc) · 50 KB
/
test_collect-logs.py
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
# Copyright 2016 Canonical Limited. All rights reserved.
# To run: "python -m unittest test_collect-logs"
import errno
from fixtures import EnvironmentVariableFixture, TestWithFixtures
import os
import os.path
import shutil
import subprocess
import sys
import tempfile
from unittest import TestCase
import mock
__file__ = os.path.abspath(__file__)
script = type(sys)("collect-logs")
script.__file__ = os.path.abspath("collect-logs")
execfile("collect-logs", script.__dict__)
class FakeError(Exception):
"""A specific error for which to check."""
def _create_file(filename, data=None):
"""Create (or re-create) the identified file.
If data is provided, it is written to the file. Otherwise it
will be empty.
The file's directory is created if necessary.
"""
dirname = os.path.dirname(os.path.abspath(filename))
try:
os.makedirs(dirname)
except OSError as e:
if e.errno != errno.EEXIST:
raise
with open(filename, "w") as file:
if data:
file.write()
class _BaseTestCase(TestCase):
MOCKED = None
def setUp(self):
super(_BaseTestCase, self).setUp()
self.orig_cwd = os.getcwd()
self.cwd = tempfile.mkdtemp()
os.chdir(self.cwd)
self.tempdir = os.path.join(self.cwd, "tempdir")
os.mkdir(self.tempdir)
self.orig = {}
for attr in self.MOCKED or ():
self.orig[attr] = getattr(script, attr)
setattr(script, attr, mock.Mock())
self.juju = script.Juju()
def tearDown(self):
for attr in self.MOCKED or ():
setattr(script, attr, self.orig[attr])
shutil.rmtree(self.cwd)
os.chdir(self.orig_cwd)
super(_BaseTestCase, self).tearDown()
def _create_tempfile(self, filename, data=None):
"""Create a file at the identified path, but rooted at the temp dir."""
_create_file(os.path.join(self.tempdir, filename), data)
def assert_cwd(self, dirname):
"""Ensure that the CWD matches the given directory."""
cwd = os.getcwd()
self.assertEqual(cwd, dirname)
class GetUnitsTests(TestCase):
def test_get_units_returns_juju_units_with_name_and_ip(self):
"""get_units returns a list of JujuUnits with names and ips."""
status = {
"applications": {
"ubuntu": {
"units": {"ubuntu/1" : {"public-address": "1.2.3.4"}}},
"ntp": {
"units": {"ntp/1" : {"public-address": "1.2.3.5"}}}}
}
expected = [
script.JujuUnit("ubuntu/1", "1.2.3.4"),
script.JujuUnit("ntp/1", "1.2.3.5")]
self.assertItemsEqual(
expected, script.get_units(juju=None, status=status))
def test_get_units_marks_units_with_no_public_address(self):
"""
get_units sets ip to NO_PUBLIC_ADDRESS for JujuUnits which do not
report a public-address key.
"""
status = {
"applications": {
"ubuntu": {
"units": {"ubuntu/1" : {"public-address": "1.2.3.4"}}},
"ntp": {
"units": {"ntp/1" : {}}}}
}
expected = [
script.JujuUnit("ubuntu/1", "1.2.3.4"),
script.JujuUnit("ntp/1", script.NO_PUBLIC_ADDRESS)]
self.assertItemsEqual(
expected, script.get_units(juju=None, status=status))
def test_get_units_ignores_subordinate_applications(self):
"""get_units ignores subordinate units."""
status = {
"applications": {
"ubuntu": {
"units": {"ubuntu/1" : {"public-address": "1.2.3.4"}}},
"landscape-client": {
"subordinate-to": ["ubuntu"],
"units": {
"ceilometer-agent/1" : {"public-address": "1.2.3.5"}}}}
}
expected = [
script.JujuUnit("ubuntu/1", "1.2.3.4")]
self.assertItemsEqual(
expected, script.get_units(juju=None, status=status))
class GetJujuTests(TestWithFixtures):
def test_juju1_outer(self):
"""
get_juju() returns a Juju prepped for a Juju 1 outer model.
"""
juju = script.get_juju(script.JUJU1, inner=False)
expected = script.Juju("juju", model=None)
self.assertEqual(juju, expected)
def test_juju1_inner(self):
"""
get_juju() returns a Juju prepped for a Juju 1 inner model.
"""
cfgdir = "/var/lib/landscape/juju-homes/0"
juju = script.get_juju(script.JUJU1, model=None, cfgdir=cfgdir,
inner=True)
expected = script.Juju("juju", cfgdir=cfgdir)
self.assertEqual(juju, expected)
def test_juju2_outer(self):
"""
get_juju() returns a Juju prepped for a Juju 2 outer model.
"""
juju = script.get_juju(script.JUJU2, inner=False)
expected = script.Juju("juju-2.1", model=None)
self.assertEqual(juju, expected)
def test_get_args_without_ssh_uses_ip_address(self):
"""
When juju_ssh is False, get_juju returns direct ssh commands from
Juju.ssh_args using using the unit's IP address instead of hostname.
"""
self.useFixture(
EnvironmentVariableFixture("JUJU_DATA", "some-dir"))
juju = script.get_juju(script.JUJU2, inner=False, juju_ssh=False)
expected = [
"/usr/bin/ssh", "-o", "StrictHostKeyChecking=no",
"-i", "some-dir/ssh/juju_id_rsa",
"[email protected]", "ls tmp"]
self.assertFalse(juju.juju_ssh)
unit = script.JujuUnit("ubuntu/0", "10.1.1.1")
self.assertEqual(expected, juju.ssh_args(unit,"ls tmp"))
def test_get_args_without_ssh_missing_public_address_uses_juju_ssh(self):
"""
When juju_ssh is False, but juju status doesn't report public-address
for a unit, ssh_args falls back to using 'juju ssh'.
"""
self.useFixture(
EnvironmentVariableFixture("JUJU_DATA", "some-dir"))
juju = script.get_juju(script.JUJU2, inner=False, juju_ssh=False)
expected = ["juju-2.1", "ssh", "ubuntu/0", "ls tmp"]
self.assertFalse(juju.juju_ssh)
unit = script.JujuUnit("ubuntu/0", script.NO_PUBLIC_ADDRESS)
self.assertEqual(expected, juju.ssh_args(unit,"ls tmp"))
def test_pull_args_without_ssh_uses_ip_address(self):
"""
When juju_ssh is False, get_juju returns direct ssh commands from
Juju.pull_args using using the unit's IP address instead of hostname.
"""
self.useFixture(
EnvironmentVariableFixture("JUJU_DATA", "some-dir"))
juju = script.get_juju(script.JUJU2, inner=False, juju_ssh=False)
expected = [
"/usr/bin/scp", "-o", "StrictHostKeyChecking=no",
"-i", "some-dir/ssh/juju_id_rsa",
"[email protected]:file1", "."]
unit = script.JujuUnit("ubuntu/0", "10.1.1.1")
self.assertEqual(expected, juju.pull_args(unit, "file1"))
def test_pull_args_without_ssh_missing_public_address_uses_juju_ssh(self):
"""
When juju_ssh is False, but juju status doesn't report public-address
for a unit, Juju.pull_args falls back to using 'juju ssh'.
"""
self.useFixture(
EnvironmentVariableFixture("JUJU_DATA", "some-dir"))
juju = script.get_juju(script.JUJU2, inner=False, juju_ssh=False)
expected = ["juju-2.1", "scp", "ubuntu/0:file1", "."]
unit = script.JujuUnit("ubuntu/0", script.NO_PUBLIC_ADDRESS)
self.assertEqual(expected, juju.pull_args(unit, "file1"))
def test_push_args_without_ssh_uses_ip_address(self):
"""
When juju_ssh is False, get_juju returns direct ssh commands from
Juju.push_args using using the unit's IP address instead of hostname.
"""
self.useFixture(
EnvironmentVariableFixture("JUJU_DATA", "some-dir"))
juju = script.get_juju(script.JUJU2, inner=False, juju_ssh=False)
expected = [
"/usr/bin/scp", "-o", "StrictHostKeyChecking=no",
"-i", "some-dir/ssh/juju_id_rsa",
"file1", "[email protected]:/tmp/blah"]
unit = script.JujuUnit("ubuntu/0", "10.1.1.1")
self.assertEqual(expected, juju.push_args(unit, "file1", "/tmp/blah"))
def test_push_args_without_ssh_missing_public_address_uses_juju_ssh(self):
"""
When juju_ssh is False, but juju status doesn't report public-address
for a unit, Juju.push_args falls back to using 'juju ssh'.
"""
self.useFixture(
EnvironmentVariableFixture("JUJU_DATA", "some-dir"))
juju = script.get_juju(script.JUJU2, inner=False, juju_ssh=False)
expected = ["juju-2.1", "scp", "file1", "ubuntu/0:/tmp/blah"]
unit = script.JujuUnit("ubuntu/0", script.NO_PUBLIC_ADDRESS)
self.assertEqual(expected, juju.push_args(unit, "file1", "/tmp/blah"))
def test_juju2_inner(self):
"""
get_juju() returns a Juju prepped for a Juju 2 inner model.
"""
cfgdir = "/var/lib/landscape/juju-homes/0"
juju = script.get_juju(script.JUJU2, cfgdir=cfgdir, inner=True)
expected = script.Juju("juju-2.1", model="controller", cfgdir=cfgdir)
self.assertEqual(juju, expected)
class MainTestCase(_BaseTestCase):
MOCKED = ("collect_logs", "collect_inner_logs", "bundle_logs")
def setUp(self):
super(MainTestCase, self).setUp()
self.orig_mkdtemp = script.mkdtemp
script.mkdtemp = lambda: self.tempdir
def tearDown(self):
script.mkdtemp = self.orig_mkdtemp
super(MainTestCase, self).tearDown()
def test_success(self):
"""
main() calls collect_logs(), collect_inner_logs(), and bundle_logs().
"""
tarfile = "/tmp/logs.tgz"
extrafiles = ["spam.py"]
script.main(tarfile, extrafiles, juju=self.juju)
script.collect_logs.assert_called_once_with(self.juju)
script.collect_inner_logs.assert_called_once_with(
self.juju, script.DEFAULT_MODEL)
script.bundle_logs.assert_called_once_with(
self.tempdir, tarfile, extrafiles)
self.assertFalse(os.path.exists(self.tempdir))
def test_in_correct_directories(self):
"""
main() calls its dependencies while in specific directories.
"""
script.collect_logs.side_effect = (
lambda _: self.assert_cwd(self.tempdir))
script.collect_inner_logs.side_effect = (
lambda _: self.assert_cwd(self.tempdir))
script.bundle_logs.side_effect = lambda *a: self.assert_cwd(self.cwd)
tarfile = "/tmp/logs.tgz"
extrafiles = ["spam.py"]
script.main(tarfile, extrafiles, juju=self.juju)
def test_no_script_recursion_for_inner_model(self):
"""
main() will not call collect_inner_logs() if --inner is True.
"""
tarfile = "/tmp/logs.tgz"
extrafiles = ["spam.py"]
cfgdir = "/var/lib/landscape/juju-homes/0"
juju = script.get_juju(script.JUJU2, cfgdir)
script.main(tarfile, extrafiles, juju=juju, inner=True)
script.collect_logs.assert_called_once_with(juju)
script.collect_inner_logs.assert_not_called()
script.bundle_logs.assert_called_once_with(
self.tempdir, tarfile, extrafiles)
self.assertFalse(os.path.exists(self.tempdir))
def test_cleanup(self):
"""
main() cleans up the temp dir it creates.
"""
tarfile = "/tmp/logs.tgz"
extrafiles = ["spam.py"]
script.main(tarfile, extrafiles, juju=self.juju)
self.assertFalse(os.path.exists(self.tempdir))
def test_collect_logs_error(self):
"""
main() doesn't handle the error when collect_logs() fails.
It still cleans up the temp dir.
"""
tarfile = "/tmp/logs.tgz"
extrafiles = ["spam.py"]
script.collect_logs.side_effect = FakeError()
with self.assertRaises(FakeError):
script.main(tarfile, extrafiles, juju=self.juju)
script.collect_logs.assert_called_once_with(self.juju)
script.collect_inner_logs.assert_not_called()
script.bundle_logs.assert_not_called()
self.assertFalse(os.path.exists(self.tempdir))
def test_collect_inner_logs_error(self):
"""
main() ignores the error when collect_inner_logs() fails.
It still cleans up the temp dir.
"""
tarfile = "/tmp/logs.tgz"
extrafiles = ["spam.py"]
script.collect_inner_logs.side_effect = FakeError()
script.main(tarfile, extrafiles, juju=self.juju)
script.collect_logs.assert_called_once_with(self.juju)
script.collect_inner_logs.assert_called_once_with(
self.juju, script.DEFAULT_MODEL)
script.bundle_logs.assert_called_once_with(
self.tempdir, tarfile, extrafiles)
self.assertFalse(os.path.exists(self.tempdir))
def test_bundle_logs_error(self):
"""
main() doesn't handle the error when bundle_logs() fails.
It still cleans up the temp dir.
"""
tarfile = "/tmp/logs.tgz"
extrafiles = ["spam.py"]
script.bundle_logs.side_effect = FakeError()
with self.assertRaises(FakeError):
script.main(tarfile, extrafiles, juju=self.juju)
script.collect_logs.assert_called_once_with(self.juju)
script.collect_inner_logs.assert_called_once_with(
self.juju, script.DEFAULT_MODEL)
script.bundle_logs.assert_called_once_with(
self.tempdir, tarfile, extrafiles)
self.assertFalse(os.path.exists(self.tempdir))
class CreateOutputFilesTestCase(_BaseTestCase):
MOCKED = ("call", "check_output", "get_units", "get_hosts", "mkdtemp")
def setUp(self):
super(CreateOutputFilesTestCase, self).setUp()
self.hosts = [
script.JujuHost("0", "1.2.3.8"),
]
script.get_hosts.return_value = self.hosts[:]
self.tmpdir = tempfile.mkdtemp()
script.mkdtemp.return_value = self.tmpdir
def tearDown(self):
if os.path.exists(self.tmpdir):
# self.tmpdir is returned by the mocked tempfile.mkdtemp()
# Normally, this won't exist as collect-logs should remove it.
shutil.rmtree(self.tmpdir)
super(CreateOutputFilesTestCase, self).tearDown()
def test_get_ps_mem_with_git_clone(self):
"""
Clone the ps_mem repo when there is no local copy.
"""
ps_mem_file = os.path.join(self.tmpdir, "ps_mem.py")
repo_path = os.path.join(self.tmpdir, "ps_mem")
script._get_ps_mem(ps_mem_file, script.PS_MEM_REPO, repo_path)
expected = [
mock.call(["git", "clone", script.PS_MEM_REPO, repo_path],
stderr=subprocess.STDOUT),
]
self.assertEqual(expected, script.check_output.call_args_list)
def test_get_ps_mem_local(self):
"""
Don't clone the ps_mem repo when there is a local copy.
"""
ps_mem_file = os.path.join(self.tmpdir, "ps_mem.py")
with open(ps_mem_file, 'w') as outfile:
outfile.write("# This is a fake ps_mem.py")
repo_path = os.path.join(self.tmpdir, "ps_mem")
result = script._get_ps_mem(ps_mem_file, script.PS_MEM_REPO, repo_path)
self.assertEqual(ps_mem_file, result)
script.check_output.assert_not_called()
def test_upload_ps_mem(self):
"""
Verify that the repo is cloned and file uploaded.
"""
script.upload_ps_mem(self.juju, self.hosts[0])
repo_path = os.path.join(self.tmpdir, "ps_mem")
expected = [
mock.call(["git", "clone", script.PS_MEM_REPO, repo_path],
stderr=subprocess.STDOUT),
]
self.assertEqual(expected, script.check_output.call_args_list)
source = os.path.join(repo_path, "ps_mem.py")
target = "{}:/tmp/ps_mem.py".format(self.hosts[0].name)
expected = [
mock.call(["juju", "scp", source, target],
env=None),
]
self.assertEqual(expected, script.call.call_args_list)
def test_create_ps_mem_output_file(self):
"""
Verify expected commands when creating the ps_mem output.
"""
script._create_ps_mem_output_file(self.juju, self.hosts[0])
repo_path = os.path.join(self.tmpdir, "ps_mem")
expected = [
mock.call([
"juju", "ssh", "0",
"if ! python -V; then sudo apt-get install -y python; fi"],
env=None, stderr=subprocess.STDOUT),
mock.call([
"juju", "ssh", "0",
"sudo /tmp/ps_mem.py -S | sudo tee /var/log/ps_mem.txt"],
env=None, stderr=subprocess.STDOUT),
]
self.assertEqual(expected, script.check_output.call_args_list)
class CollectLogsTestCase(_BaseTestCase):
MOCKED = ("get_units", "get_bootstrap_ip", "check_output", "call",
"get_hosts", "upload_ps_mem", "_create_ps_mem_output_file")
def setUp(self):
super(CollectLogsTestCase, self).setUp()
self.units = [
script.JujuUnit("landscape-server/0", "1.2.3.4"),
script.JujuUnit("postgresql/0", "1.2.3.5"),
script.JujuUnit("rabbitmq-server/0", "1.2.3.6"),
script.JujuUnit("haproxy/0", "1.2.3.7"),
]
script.get_units.return_value = self.units[:]
script.get_bootstrap_ip.return_value = self.units[0].ip
self.hosts = [
script.JujuHost("0", "1.2.3.8"),
]
script.get_hosts.return_value = self.hosts[:]
self.mp_map_orig = script._mp_map
script._mp_map = lambda f, a: map(f, a)
os.chdir(self.tempdir)
def tearDown(self):
script._mp_map = self.mp_map_orig
super(CollectLogsTestCase, self).tearDown()
def _call_side_effect(self, cmd, env=None):
"""Perform the side effect of calling the mocked-out call()."""
if cmd[0] == "tar":
self.assertTrue(os.path.exists(cmd[-1]))
return
self.assertEqual(env, self.juju.env)
self.assertEqual(cmd[0], self.juju.binary_path)
_create_file(os.path.basename(cmd[2]))
def test_success(self):
"""
collect_logs() gathers "ps" output and logs from each unit.
"""
script.call.side_effect = self._call_side_effect
script.collect_logs(self.juju)
script.get_units.assert_called_once_with(self.juju)
expected = []
units = self.units + [script.JujuUnit("0", "1.2.3.3")]
# for _create_ps_output_file()
for unit in units:
cmd = "ps fauxww | sudo tee /var/log/ps-fauxww.txt"
expected.append(mock.call(["juju", "ssh", unit.name, cmd],
stderr=subprocess.STDOUT,
env=None,
))
# for _create_log_tarball()
for unit in units:
tarfile = "/tmp/logs_{}.tar".format(unit.name.replace("/", "-")
if unit.name != "0"
else "bootstrap")
cmd = ("sudo tar --ignore-failed-read"
" --exclude=/var/lib/landscape/client/package/hash-id"
" --exclude=/var/lib/juju/containers/juju-*-lxc-template"
" -cf {}"
" $(sudo sh -c \"ls -1d {} 2>/dev/null\")"
).format(
tarfile,
" ".join(["/var/log",
"/etc/hosts",
"/etc/network",
"/var/crash",
"/var/lib/landscape/client",
"/etc/apache2",
"/etc/haproxy",
"/var/lib/lxc/*/rootfs/var/log",
"/var/lib/juju/containers",
"/etc/nova",
"/etc/swift",
"/etc/neutron",
"/etc/ceph",
"/etc/glance",
]),
)
expected.append(mock.call(["juju", "ssh", unit.name, cmd],
stderr=subprocess.STDOUT,
env=None,
))
expected.append(mock.call(["juju", "ssh", unit.name,
"sudo gzip -f {}".format(tarfile)],
stderr=subprocess.STDOUT,
env=None,
))
self.assertEqual(script.check_output.call_count, len(expected))
script.check_output.assert_has_calls(expected, any_order=True)
# for _create_ps_mem_output_file
script._create_ps_mem_output_file.assert_has_calls([
mock.call(self.juju, self.hosts[0]),
])
# for download_log_from_unit()
expected = []
for unit in units:
if unit.name != "0":
name = unit.name.replace("/", "-")
else:
name = "bootstrap"
filename = "logs_{}.tar.gz".format(name)
source = "{}:/tmp/{}".format(unit.name, filename)
expected.append(mock.call(["juju", "scp", source, "."], env=None))
expected.append(mock.call(["tar", "-C", name, "-xzf", filename]))
self.assertFalse(os.path.exists(filename))
self.assertEqual(script.call.call_count, len(expected))
script.call.assert_has_calls(expected, any_order=True)
def test_inner(self):
"""
collect_logs() gathers "ps" output and logs from each unit.
Running in the inner model produces different commands.
"""
cfgdir = "/var/lib/landscape/juju-homes/0"
juju = script.Juju("juju-2.1", model="controller", cfgdir=cfgdir)
self.juju = juju
script.call.side_effect = self._call_side_effect
script.collect_logs(juju)
script.get_units.assert_called_once_with(juju)
expected = []
units = self.units + [script.JujuUnit("0", "1.2.3.3")]
# for _create_ps_output_file()
for unit in units:
cmd = "ps fauxww | sudo tee /var/log/ps-fauxww.txt"
expected.append(mock.call(["juju-2.1", "ssh",
"-m", "controller", unit.name, cmd],
stderr=subprocess.STDOUT,
env=juju.env,
))
# for _create_log_tarball()
for unit in units:
tarfile = "/tmp/logs_{}.tar".format(unit.name.replace("/", "-")
if unit.name != "0"
else "bootstrap")
cmd = ("sudo tar --ignore-failed-read"
" --exclude=/var/lib/landscape/client/package/hash-id"
" --exclude=/var/lib/juju/containers/juju-*-lxc-template"
" -cf {}"
" $(sudo sh -c \"ls -1d {} 2>/dev/null\")"
).format(
tarfile,
" ".join(["/var/log",
"/etc/hosts",
"/etc/network",
"/var/crash",
"/var/lib/landscape/client",
"/etc/apache2",
"/etc/haproxy",
"/var/lib/lxc/*/rootfs/var/log",
"/var/lib/juju/containers",
"/etc/nova",
"/etc/swift",
"/etc/neutron",
"/etc/ceph",
"/etc/glance",
]),
)
expected.append(mock.call(
["juju-2.1", "ssh", "-m", "controller", unit.name, cmd],
stderr=subprocess.STDOUT,
env=juju.env,
))
expected.append(mock.call(
["juju-2.1", "ssh", "-m", "controller", unit.name,
"sudo gzip -f {}".format(tarfile)],
stderr=subprocess.STDOUT,
env=juju.env,
))
self.assertEqual(script.check_output.call_count, len(expected))
script.check_output.assert_has_calls(expected, any_order=True)
# for _create_ps_mem_output_file
script._create_ps_mem_output_file.assert_has_calls([
mock.call(self.juju, self.hosts[0]),
])
# for download_log_from_unit()
expected = []
for unit in units:
if unit.name != "0":
name = unit.name.replace("/", "-")
else:
name = "bootstrap"
filename = "logs_{}.tar.gz".format(name)
source = "{}:/tmp/{}".format(unit.name, filename)
expected.append(mock.call(
["juju-2.1", "scp", "-m", "controller", source, "."],
env=juju.env))
expected.append(mock.call(["tar", "-C", name, "-xzf", filename]))
self.assertFalse(os.path.exists(filename))
self.assertEqual(script.call.call_count, len(expected))
script.call.assert_has_calls(expected, any_order=True)
def test_get_units_failure(self):
"""
collect_logs() does not handle errors from get_units().
"""
script.get_units.side_effect = FakeError()
with self.assertRaises(FakeError):
script.collect_logs(self.juju)
script.get_units.assert_called_once_with(self.juju)
script.check_output.assert_not_called()
script.call.assert_not_called()
def test_get_hosts_failure(self):
"""
collect_logs() does not handle errors from get_hosts().
"""
script.get_hosts.side_effect = FakeError()
with self.assertRaises(FakeError):
script.collect_logs(self.juju)
script.get_hosts.assert_called_once_with(self.juju)
self.assertEqual(script.check_output.call_count, 5)
script.call.assert_not_called()
def test_check_output_failure(self):
"""
collect_logs() does not handle errors from check_output().
"""
script.check_output.side_effect = [mock.DEFAULT,
FakeError(),
]
with self.assertRaises(FakeError):
script.collect_logs(self.juju)
script.get_units.assert_called_once_with(self.juju)
self.assertEqual(script.check_output.call_count, 2)
script.call.assert_not_called()
def test_call_failure(self):
"""
collect_logs() does not handle errors from call().
"""
def call_side_effect(cmd, env=None):
# second use of call() for landscape-server/0
if script.call.call_count == 2:
raise FakeError()
# first use of call() for postgresql/0
if script.call.call_count == 3:
raise FakeError()
# all other uses of call() default to the normal side effect.
return self._call_side_effect(cmd, env=env)
script.call.side_effect = call_side_effect
script.collect_logs(self.juju)
script.get_units.assert_called_once_with(self.juju)
units = self.units + [script.JujuUnit("0", "1.2.3.3")]
self.assertEqual(script.check_output.call_count, len(units) * 3)
self.assertEqual(script.call.call_count, len(units) * 2 - 1)
for unit in units:
if unit.name != "0":
name = unit.name.replace("/", "-")
else:
name = "bootstrap"
if unit == self.units[1]:
self.assertFalse(os.path.exists(name))
else:
self.assertTrue(os.path.exists(name))
filename = "logs_{}.tar.gz".format(name)
self.assertFalse(os.path.exists(filename))
class CollectInnerLogsTestCase(_BaseTestCase):
MOCKED = ("get_units", "check_output", "call", "check_call",
"upload_ps_mem")
def setUp(self):
super(CollectInnerLogsTestCase, self).setUp()
self.units = [
script.JujuUnit("landscape-server/0" , "1.2.3.4"),
script.JujuUnit("postgresql/0", "1.2.3.5"),
script.JujuUnit("rabbitmq-server/0", "1.2.3.6"),
script.JujuUnit("haproxy/0", "1.2.3.7"),
]
script.get_units.return_value = self.units[:]
script.check_output.return_value = "0\n"
script.call.return_value = 0
os.chdir(self.tempdir)
def assert_clean(self):
"""Ensure that collect_inner_logs cleaned up after itself."""
self.assert_cwd(self.tempdir)
self.assertFalse(os.path.exists("inner-logs.tar.gz"))
def test_juju_2(self):
"""
collect_inner_logs() finds the inner model and runs collect-logs
inside it. The resulting tarball is downloaded, extracted, and
deleted.
"""
def check_call_side_effect(cmd, env=None):
self.assertEqual(env, self.juju.env)
if script.check_call.call_count == 4:
self.assert_cwd(self.tempdir)
self._create_tempfile("inner-logs.tar.gz")
elif script.check_call.call_count == 5:
cwd = os.path.join(self.tempdir, "landscape-0-inner-logs")
self.assert_cwd(cwd)
return None
script.check_call.side_effect = check_call_side_effect
script.collect_inner_logs(self.juju)
# Check get_units() calls.
script.get_units.assert_called_once_with(self.juju)
# Check check_output() calls.
expected = []
cmd = ("sudo JUJU_DATA=/var/lib/landscape/juju-homes/"
"`sudo ls -rt /var/lib/landscape/juju-homes/ | tail -1`"
" juju-2.1 model-config -m controller proxy-ssh=false")
expected.append(mock.call(["juju", "ssh", "landscape-server/0", cmd],
stderr=subprocess.STDOUT,
env=self.juju.env))
expected.append(mock.call(
["juju", "ssh", "landscape-server/0",
"sudo ls -rt /var/lib/landscape/juju-homes/"],
env=self.juju.env))
self.assertEqual(script.check_output.call_count, len(expected))
script.check_output.assert_has_calls(expected, any_order=True)
# Check call() calls.
expected = [
mock.call(["juju", "ssh", "landscape-server/0",
("sudo JUJU_DATA=/var/lib/landscape/juju-homes/0 "
"juju-2.1 status -m controller --format=yaml"),
], env=self.juju.env),
mock.call(["juju", "scp",
os.path.join(os.path.dirname(__file__), "collect-logs"),
"landscape-server/0:/tmp/collect-logs",
], env=self.juju.env),
mock.call(["juju", "ssh",
"landscape-server/0",
"sudo rm -rf /tmp/inner-logs.tar.gz",
], env=self.juju.env),
]
self.assertEqual(script.call.call_count, len(expected))
script.call.assert_has_calls(expected, any_order=True)
# Check check_call() calls.
cmd = ("sudo"
" JUJU_DATA=/var/lib/landscape/juju-homes/0"
" /tmp/collect-logs --inner --juju juju-2.1"
" --model controller"
" --cfgdir /var/lib/landscape/juju-homes/0"
" /tmp/inner-logs.tar.gz")
expected = [
mock.call(["juju", "ssh", "landscape-server/0", cmd],
env=self.juju.env),
mock.call(["juju", "scp",
"landscape-server/0:/tmp/inner-logs.tar.gz",
os.path.join(self.tempdir, "inner-logs.tar.gz"),
], env=self.juju.env),
mock.call(["tar", "-zxf", self.tempdir + "/inner-logs.tar.gz"]),
]
self.assertEqual(script.check_call.call_count, len(expected))
script.check_call.assert_has_calls(expected, any_order=True)
self.assert_clean()
def test_juju_1(self):
"""
collect_inner_logs() finds the inner model and runs collect-logs
inside it. The resulting tarball is downloaded, extracted, and
deleted.
"""
def check_call_side_effect(cmd, env=None):
self.assertEqual(env, self.juju.env)
if script.check_call.call_count == 4:
self.assert_cwd(self.tempdir)
self._create_tempfile("inner-logs.tar.gz")
elif script.check_call.call_count == 5:
cwd = os.path.join(self.tempdir, "landscape-0-inner-logs")
self.assert_cwd(cwd)
return None
script.check_call.side_effect = check_call_side_effect
script.call.side_effect = [1, 0, 0, 0]
err = subprocess.CalledProcessError(1, "...", "<output>")
script.check_output.side_effect = [err,
mock.DEFAULT,
mock.DEFAULT,
]
script.collect_inner_logs(self.juju)
# Check get_units() calls.
script.get_units.assert_called_once_with(self.juju)
# Check check_output() calls.
expected = []
cmd = ("sudo JUJU_DATA=/var/lib/landscape/juju-homes/"
"`sudo ls -rt /var/lib/landscape/juju-homes/ | tail -1`"
" juju-2.1 model-config -m controller proxy-ssh=false")
expected.append(mock.call(["juju", "ssh", "landscape-server/0", cmd],
stderr=subprocess.STDOUT,
env=None))
cmd = ("sudo JUJU_HOME=/var/lib/landscape/juju-homes/"
"`sudo ls -rt /var/lib/landscape/juju-homes/ | tail -1`"
" juju set-env proxy-ssh=false")
expected.append(mock.call(["juju", "ssh", "landscape-server/0", cmd],
stderr=subprocess.STDOUT,
env=None))
expected.append(mock.call(
["juju", "ssh", "landscape-server/0",
"sudo ls -rt /var/lib/landscape/juju-homes/"],
env=None))
self.assertEqual(script.check_output.call_count, len(expected))
script.check_output.assert_has_calls(expected, any_order=True)
# Check call() calls.
expected = [
mock.call(["juju", "ssh", "landscape-server/0",
("sudo JUJU_DATA=/var/lib/landscape/juju-homes/0 "
"juju-2.1 status -m controller --format=yaml"),
], env=None),
mock.call(["juju", "ssh", "landscape-server/0",
("sudo -u landscape "
"JUJU_HOME=/var/lib/landscape/juju-homes/0 "
"juju status --format=yaml"),
], env=None),
mock.call(["juju", "scp",
os.path.join(os.path.dirname(__file__), "collect-logs"),
"landscape-server/0:/tmp/collect-logs",
], env=None),
mock.call(["juju", "ssh",
"landscape-server/0",
"sudo rm -rf /tmp/inner-logs.tar.gz",
], env=None),
]
self.assertEqual(script.call.call_count, len(expected))
script.call.assert_has_calls(expected, any_order=True)
# Check check_call() calls.
cmd = ("sudo -u landscape"
" JUJU_HOME=/var/lib/landscape/juju-homes/0"
" /tmp/collect-logs --inner --juju juju"
" --cfgdir /var/lib/landscape/juju-homes/0"
" /tmp/inner-logs.tar.gz")
expected = [
mock.call(["juju", "ssh", "landscape-server/0", cmd], env=None),
mock.call(["juju", "scp",
"landscape-server/0:/tmp/inner-logs.tar.gz",
os.path.join(self.tempdir, "inner-logs.tar.gz"),
], env=None),
mock.call(["tar", "-zxf", self.tempdir + "/inner-logs.tar.gz"]),
]
self.assertEqual(script.check_call.call_count, len(expected))
script.check_call.assert_has_calls(expected, any_order=True)
self.assert_clean()
def test_with_legacy_landscape_unit(self):
"""
collect_inner_logs() correctly supports legacy landscape installations.
"""
self.units[0] = script.JujuUnit("landscape/0", "1.2.3.4")
script.get_units.return_value = self.units[:]
err = subprocess.CalledProcessError(1, "...", "<output>")
script.check_output.side_effect = [err,
mock.DEFAULT,
mock.DEFAULT,
]
script.collect_inner_logs(self.juju)
expected = []
cmd = ("sudo JUJU_DATA=/var/lib/landscape/juju-homes/"
"`sudo ls -rt /var/lib/landscape/juju-homes/ | tail -1`"
" juju-2.1 model-config -m controller proxy-ssh=false")
expected.append(mock.call(["juju", "ssh", "landscape/0", cmd],
stderr=subprocess.STDOUT,
env=None))
cmd = ("sudo JUJU_HOME=/var/lib/landscape/juju-homes/"
"`sudo ls -rt /var/lib/landscape/juju-homes/ | tail -1`"
" juju set-env proxy-ssh=false")
expected.append(mock.call(["juju", "ssh", "landscape/0", cmd],
stderr=subprocess.STDOUT,
env=None))
expected.append(mock.call(
["juju", "ssh", "landscape/0",
"sudo ls -rt /var/lib/landscape/juju-homes/"],
env=None))
self.assertEqual(script.check_output.call_count, len(expected))
script.check_output.assert_has_calls(expected, any_order=True)
self.assert_clean()
def test_no_units(self):
"""
collect_inner_logs() is a noop if no units are found.
"""
script.get_units.return_value = []
script.collect_inner_logs(self.juju)
script.get_units.assert_called_once_with(self.juju)
script.check_output.assert_not_called()
script.call.assert_not_called()
script.check_call.assert_not_called()
self.assert_clean()
def test_no_landscape_server_unit(self):
"""
collect_inner_logs() is a noop if the landscape unit isn't found.
"""
del self.units[0]
script.get_units.return_value = self.units[:]
script.collect_inner_logs(self.juju)
script.get_units.assert_called_once_with(self.juju)