File: vmUtils.py

package info (click to toggle)
zvmcloudconnector 1.4.1-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 6,092 kB
  • sloc: ansic: 45,973; python: 29,045; sh: 2,732; makefile: 790
file content (1139 lines) | stat: -rw-r--r-- 42,473 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
# Virtual Machine Utilities for Systems Management Ultra Thin Layer
#
# Copyright 2017 IBM Corp.
#
#    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 re
import subprocess
from subprocess import CalledProcessError
import time

from smutLayer import msgs

modId = 'VMU'
version = '1.0.0'         # Version of this script


def disableEnableDisk(rh, userid, vaddr, option):
    """
    Disable or enable a disk.

    Input:
       Request Handle:
          owning userid
          virtual address
          option ('-e': enable, '-d': disable)

    Output:
       Dictionary containing the following:
          overallRC - overall return code, 0: success, non-zero: failure
          rc        - rc from the chccwdev command or IUCV transmission.
          rs        - rs from the chccwdev command or IUCV transmission.
          results   - possible error message from the IUCV transmission.
    """

    rh.printSysLog("Enter vmUtils.disableEnableDisk, userid: " + userid +
        " addr: " + vaddr + " option: " + option)

    results = {
              'overallRC': 0,
              'rc': 0,
              'rs': 0,
              'response': ''
             }

    """
    Can't guarantee the success of online/offline disk, need to wait
    Until it's done because we may detach the disk after -d option
    or use the disk after the -e option
    """
    for secs in [0.1, 0.4, 1, 1.5, 3, 7, 15, 32, 30, 30,
                60, 60, 60, 60, 60]:
        strCmd = "sudo /sbin/chccwdev " + option + " " + vaddr + " 2>&1"
        results = execCmdThruIUCV(rh, userid, strCmd)
        if results['overallRC'] == 0:
            break
        elif (results['overallRC'] == 2 and results['rc'] == 8 and
            results['rs'] == 1 and option == '-d'):
            # Linux does not know about the disk being disabled.
            # Ok, nothing to do.  Treat this as a success.
            results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'response': ''}
            break
        time.sleep(secs)

    rh.printSysLog("Exit vmUtils.disableEnableDisk, rc: " +
        str(results['overallRC']))
    return results


def execCmdThruIUCV(rh, userid, strCmd, hideInLog=[]):
    """
    Send a command to a virtual machine using IUCV.

    Input:
       Request Handle
       Userid of the target virtual machine
       Command string to send
       (Optional) List of strCmd words (by index) to hide in
          sysLog by replacing the word with "<hidden>".

    Output:
       Dictionary containing the following:
          overallRC - overall return code, 0: success, 2: failure
          rc        - RC returned from iucvclnt if overallRC != 0.
          rs        - RS returned from iucvclnt if overallRC != 0.
          errno     - Errno returned from iucvclnt if overallRC != 0.
          response  - Output of the iucvclnt command or this routine.

    Notes:
       1) This routine does not use the Request Handle printLn function.
          This is because an error might be expected and we might desire
          to suppress it.  Instead, any error messages are put in the
          response dictionary element that is returned.
    """
    if len(hideInLog) == 0:
        rh.printSysLog("Enter vmUtils.execCmdThruIUCV, userid: " +
                       userid + " cmd: " + strCmd)
    else:
        logCmd = strCmd.split(' ')
        for i in hideInLog:
            logCmd[i] = '<hidden>'
        rh.printSysLog("Enter vmUtils.execCmdThruIUCV, userid: " +
                       userid + " cmd: " + ' '.join(logCmd))

    iucvpath = '/opt/zthin/bin/IUCV/'
    results = {
              'overallRC': 0,
              'rc': 0,
              'rs': 0,
              'errno': 0,
              'response': [],
             }

    cmd = ['sudo',
           iucvpath + "iucvclnt",
           userid,
           strCmd]
    try:
        results['response'] = subprocess.check_output(
                cmd,
                stderr=subprocess.STDOUT,
                close_fds=True)
        if isinstance(results['response'], bytes):
            results['response'] = bytes.decode(results['response'])
    except CalledProcessError as e:
        msg = []
        results['overallRC'] = 2
        results['rc'] = e.returncode
        output = bytes.decode(e.output)

        match = re.search('Return code (.+?),', output)
        if match:
            try:
                results['rc'] = int(match.group(1))
            except ValueError:
                # Return code in response from IUCVCLNT is not an int.
                msg = msgs.msg['0311'][1] % (modId, userid, strCmd,
                    results['rc'], match.group(1), output)

        if not msg:
            # We got the rc. Now, get the rs.
            match = re.search('Reason code (.+?)\.', output)
            if match:
                try:
                    results['rs'] = int(match.group(1))
                except ValueError:
                    # Reason code in response from IUCVCLNT is not an int.
                    msg = msgs.msg['0312'][1] % (modId, userid, strCmd,
                        results['rc'], match.group(1), output)

        if msg:
            # Already produced an error message.
            pass
        elif results['rc'] == 1:
            # Command was not authorized or a generic Linux error.
            msg = msgs.msg['0313'][1] % (modId, userid, strCmd,
                results['rc'], results['rs'], output)
        elif results['rc'] == 2:
            # IUCV client parameter error.
            msg = msgs.msg['0314'][1] % (modId, userid, strCmd,
                results['rc'], results['rs'], output)
        elif results['rc'] == 4:
            # IUCV socket error
            msg = msgs.msg['0315'][1] % (modId, userid, strCmd,
                results['rc'], results['rs'], output)
        elif results['rc'] == 8:
            # Executed command failed
            msg = msgs.msg['0316'][1] % (modId, userid, strCmd,
                results['rc'], results['rs'], output)
        elif results['rc'] == 16:
            # File Transport failed
            msg = msgs.msg['0317'][1] % (modId, userid, strCmd,
                results['rc'], results['rs'], output)
        elif results['rc'] == 32:
            # IUCV server file was not found on this system.
            msg += msgs.msg['0318'][1] % (modId, userid, strCmd,
                results['rc'], results['rs'], output)
        else:
            # Unrecognized IUCV client error
            msg = msgs.msg['0319'][1] % (modId, userid, strCmd,
                results['rc'], results['rs'], output)
        results['response'] = msg

    except Exception as e:
        # Other exceptions from this system (i.e. not the managed system).
        results = msgs.msg['0421'][0]
        msg = msgs.msg['0421'][1] % (modId, strCmd,
            type(e).__name__, str(e))
        results['response'] = msg

    rh.printSysLog("Exit vmUtils.execCmdThruIUCV, rc: " +
                   str(results['rc']))
    return results


def getPerfInfo(rh, useridlist):
    """
    Get the performance information for a userid

    Input:
       Request Handle
       Userid to query <- may change this to a list later.

    Output:
       Dictionary containing the following:
          overallRC - overall return code, 0: success, non-zero: failure
          rc        - RC returned from SMCLI if overallRC = 0.
          rs        - RS returned from SMCLI if overallRC = 0.
          errno     - Errno returned from SMCLI if overallRC = 0.
          response  - Stripped and reformatted output of the SMCLI command.
    """
    rh.printSysLog("Enter vmUtils.getPerfInfo, userid: " + useridlist)
    parms = ["-T", rh.userid,
             "-c", "1"]
    results = invokeSMCLI(rh, "Image_Performance_Query", parms)
    if results['overallRC'] != 0:
        # SMCLI failed.
        rh.printLn("ES", results['response'])
        rh.printSysLog("Exit vmUtils.getPerfInfo, rc: " +
                       str(results['overallRC']))
        return results

    lines = results['response'].split("\n")
    usedTime = 0
    totalCpu = 0
    totalMem = 0
    usedMem = 0
    try:
        for line in lines:
            if "Used CPU time:" in line:
                usedTime = line.split()[3].strip('"')
                # Value is in us, need make it seconds
                usedTime = int(usedTime) / 1000000
            if "Guest CPUs:" in line:
                totalCpu = line.split()[2].strip('"')
            if "Max memory:" in line:
                totalMem = line.split()[2].strip('"')
                # Value is in Kb, need to make it Mb
                totalMem = int(totalMem) / 1024
            if "Used memory:" in line:
                usedMem = line.split()[2].strip('"')
                usedMem = int(usedMem) / 1024
    except Exception as e:
        msg = msgs.msg['0412'][1] % (modId, type(e).__name__,
            str(e), results['response'])
        rh.printLn("ES", msg)
        results['overallRC'] = 4
        results['rc'] = 4
        results['rs'] = 412

    if results['overallRC'] == 0:
        memstr = "Total Memory: %iM\n" % totalMem
        usedmemstr = "Used Memory: %iM\n" % usedMem
        procstr = "Processors: %s\n" % totalCpu
        timestr = "CPU Used Time: %i sec\n" % usedTime
        results['response'] = memstr + usedmemstr + procstr + timestr
    rh.printSysLog("Exit vmUtils.getPerfInfo, rc: " +
                   str(results['rc']))
    return results


def installFS(rh, vaddr, mode, fileSystem, diskType):
    """
    Install a filesystem on a virtual machine's dasd.

    Input:
       Request Handle:
          userid - Userid that owns the disk
       Virtual address as known to the owning system.
       Access mode to use to get the disk.
       Disk Type - 3390 or 9336

    Output:
       Dictionary containing the following:
          overallRC - overall return code, 0: success, non-zero: failure
          rc        - RC returned from SMCLI if overallRC = 0.
          rs        - RS returned from SMCLI if overallRC = 0.
          errno     - Errno returned from SMCLI if overallRC = 0.
          response  - Output of the SMCLI command.
    """

    rh.printSysLog("Enter vmUtils.installFS, userid: " + rh.userid +
        ", vaddr: " + str(vaddr) + ", mode: " + mode + ", file system: " +
        fileSystem + ", disk type: " + diskType)

    results = {
              'overallRC': 0,
              'rc': 0,
              'rs': 0,
              'errno': 0,
             }

    out = ''
    diskAccessed = False

    # Get access to the disk.
    cmd = ["sudo",
           "/opt/zthin/bin/linkdiskandbringonline",
           rh.userid,
           vaddr,
           mode]
    strCmd = ' '.join(cmd)
    rh.printSysLog("Invoking: " + strCmd)
    try:
        out = subprocess.check_output(cmd, close_fds=True)
        if isinstance(out, bytes):
            out = bytes.decode(out)
        diskAccessed = True
    except CalledProcessError as e:
        rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
            e.returncode, e.output))
        results = msgs.msg['0415'][0]
        results['rs'] = e.returncode
        rh.updateResults(results)
    except Exception as e:
        # All other exceptions.
        results = msgs.msg['0421'][0]
        rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
            type(e).__name__, str(e)))

    if results['overallRC'] == 0:
        """
        sample output:
        linkdiskandbringonline maint start time: 2017-03-03-16:20:48.011
        Success: Userid maint vdev 193 linked at ad35 device name dasdh
        linkdiskandbringonline exit time: 2017-03-03-16:20:52.150
        """
        match = re.search('Success:(.+?)\n', out)
        if match:
            parts = match.group(1).split()
            if len(parts) > 9:
                device = "/dev/" + parts[9]
            else:
                strCmd = ' '.join(cmd)
                rh.printLn("ES", msgs.msg['0416'][1] % (modId,
                    'Success:', 10, strCmd, out))
                results = msgs.msg['0416'][0]
                rh.updateResults(results)
        else:
            strCmd = ' '.join(cmd)
            rh.printLn("ES", msgs.msg['0417'][1] % (modId,
                'Success:', strCmd, out))
            results = msgs.msg['0417'][0]
            rh.updateResults(results)

    if results['overallRC'] == 0 and diskType == "3390":
        # dasdfmt the disk
        cmd = ["sudo",
            "/sbin/dasdfmt",
            "-y",
            "-b", "4096",
            "-d", "cdl",
            "-f", device]
        strCmd = ' '.join(cmd)
        rh.printSysLog("Invoking: " + strCmd)
        try:
            out = subprocess.check_output(cmd, close_fds=True)
            if isinstance(out, bytes):
                out = bytes.decode(out)
        except CalledProcessError as e:
            rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
                e.returncode, e.output))
            results = msgs.msg['0415'][0]
            results['rs'] = e.returncode
            rh.updateResults(results)
        except Exception as e:
            # All other exceptions.
            strCmd = " ".join(cmd)
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                type(e).__name__, str(e)))
            results = msgs.msg['0421'][0]
            rh.updateResults(results)

    if results['overallRC'] == 0 and diskType == "3390":
        # Settle the devices so we can do the partition.
        strCmd = ("which udevadm &> /dev/null && " +
            "udevadm settle || udevsettle")
        rh.printSysLog("Invoking: " + strCmd)
        try:
            subprocess.check_output(
                strCmd,
                stderr=subprocess.STDOUT,
                close_fds=True,
                shell=True)
            if isinstance(out, bytes):
                out = bytes.decode(out)
        except CalledProcessError as e:
            rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
                e.returncode, e.output))
            results = msgs.msg['0415'][0]
            results['rs'] = e.returncode
            rh.updateResults(results)
        except Exception as e:
            # All other exceptions.
            strCmd = " ".join(cmd)
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                type(e).__name__, str(e)))
            results = msgs.msg['0421'][0]
            rh.updateResults(results)

    if results['overallRC'] == 0 and diskType == "3390":
        # Prepare the partition with fdasd
        cmd = ["sudo", "/sbin/fdasd", "-a", device]
        strCmd = ' '.join(cmd)
        rh.printSysLog("Invoking: " + strCmd)
        try:
            out = subprocess.check_output(cmd,
                stderr=subprocess.STDOUT, close_fds=True)
            if isinstance(out, bytes):
                out = bytes.decode(out)
        except CalledProcessError as e:
            rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
                e.returncode, e.output))
            results = msgs.msg['0415'][0]
            results['rs'] = e.returncode
            rh.updateResults(results)
        except Exception as e:
            # All other exceptions.
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                type(e).__name__, str(e)))
            results = msgs.msg['0421'][0]
            rh.updateResults(results)

    if results['overallRC'] == 0 and diskType == "9336":
        # Delete the existing partition in case the disk already
        # has a partition in it.
        cmd = "sudo /sbin/fdisk " + device + " << EOF\nd\nw\nEOF"
        rh.printSysLog("Invoking: /sbin/fdsik " + device +
            " << EOF\\nd\\nw\\nEOF ")
        try:
            out = subprocess.check_output(cmd,
                stderr=subprocess.STDOUT,
                close_fds=True,
                shell=True)
            if isinstance(out, bytes):
                out = bytes.decode(out)
        except CalledProcessError as e:
            rh.printLn("ES", msgs.msg['0415'][1] % (modId, cmd,
                e.returncode, e.output))
            results = msgs.msg['0415'][0]
            results['rs'] = e.returncode
            rh.updateResults(results)
        except Exception as e:
            # All other exceptions.
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, cmd,
                type(e).__name__, str(e)))
            results = msgs.msg['0421'][0]
            rh.updateResults(results)

    if results['overallRC'] == 0 and diskType == "9336":
        # Prepare the partition with fdisk
        cmd = "sudo /sbin/fdisk " + device + " << EOF\nn\np\n1\n\n\nw\nEOF"
        rh.printSysLog("Invoking: sudo /sbin/fdisk " + device +
            " << EOF\\nn\\np\\n1\\n\\n\\nw\\nEOF")
        try:
            out = subprocess.check_output(cmd,
                stderr=subprocess.STDOUT,
                close_fds=True,
                shell=True)
            if isinstance(out, bytes):
                out = bytes.decode(out)
        except CalledProcessError as e:
            rh.printLn("ES", msgs.msg['0415'][1] % (modId, cmd,
                e.returncode, e.output))
            results = msgs.msg['0415'][0]
            results['rs'] = e.returncode
            rh.updateResults(results)
        except Exception as e:
            # All other exceptions.
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, cmd,
                type(e).__name__, str(e)))
            results = msgs.msg['0421'][0]
            rh.updateResults(results)

    if results['overallRC'] == 0:
        # Settle the devices so we can do the partition.
        strCmd = ("which udevadm &> /dev/null && " +
            "udevadm settle || udevsettle")
        rh.printSysLog("Invoking: " + strCmd)
        try:
            subprocess.check_output(
                strCmd,
                stderr=subprocess.STDOUT,
                close_fds=True,
                shell=True)
            if isinstance(out, bytes):
                out = bytes.decode(out)
        except CalledProcessError as e:
            rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
                e.returncode, e.output))
            results = msgs.msg['0415'][0]
            results['rs'] = e.returncode
            rh.updateResults(results)
        except Exception as e:
            # All other exceptions.
            strCmd = " ".join(cmd)
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                type(e).__name__, str(e)))
            results = msgs.msg['0421'][0]
            rh.updateResults(results)

    if results['overallRC'] == 0:
        # Install the file system into the disk.
        device = device + "1"       # Point to first partition
        if fileSystem != 'swap':
            if fileSystem == 'xfs':
                cmd = ["sudo", "mkfs.xfs", "-f", device]
            else:
                cmd = ["sudo", "mkfs", "-F", "-t", fileSystem, device]
            strCmd = ' '.join(cmd)
            rh.printSysLog("Invoking: " + strCmd)
            try:
                out = subprocess.check_output(cmd,
                    stderr=subprocess.STDOUT, close_fds=True)
                if isinstance(out, bytes):
                    out = bytes.decode(out)
                rh.printLn("N", "File system: " + fileSystem +
                    " is installed.")
            except CalledProcessError as e:
                rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
                    e.returncode, e.output))
                results = msgs.msg['0415'][0]
                results['rs'] = e.returncode
                rh.updateResults(results)
            except Exception as e:
                # All other exceptions.
                rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                    type(e).__name__, str(e)))
                results = msgs.msg['0421'][0]
                rh.updateResults(results)
        else:
            rh.printLn("N", "File system type is swap. No need to install " +
                "a filesystem.")

    if diskAccessed:
        # Give up the disk.
        cmd = ["sudo", "/opt/zthin/bin/offlinediskanddetach",
               rh.userid,
               vaddr]
        strCmd = ' '.join(cmd)
        rh.printSysLog("Invoking: " + strCmd)
        try:
            out = subprocess.check_output(cmd, close_fds=True)
            if isinstance(out, bytes):
                out = bytes.decode(out)
        except CalledProcessError as e:
            rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
                e.returncode, e.output))
            results = msgs.msg['0415'][0]
            results['rs'] = e.returncode
            rh.updateResults(results)
        except Exception as e:
            # All other exceptions.
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                type(e).__name__, str(e)))
            results = msgs.msg['0421'][0]
            rh.updateResults(results)

    rh.printSysLog("Exit vmUtils.installFS, rc: " + str(results['rc']))
    return results


def invokeSMCLI(rh, api, parms, hideInLog=[]):
    """
    Invoke SMCLI and parse the results.

    Input:
       Request Handle
       API name,
       SMCLI parms as an array
       (Optional) List of parms (by index) to hide in
          sysLog by replacing the parm with "<hidden>".

    Output:
       Dictionary containing the following:
          overallRC - overall return code, 0: success, non-zero: failure
          rc        - RC returned from SMCLI if overallRC = 0.
          rs        - RS returned from SMCLI if overallRC = 0.
          errno     - Errno returned from SMCLI if overallRC = 0.
          response  - String output of the SMCLI command.

    Note:
       - If the first three words of the header returned from smcli
         do not do not contain words that represent valid integer
         values or contain too few words then one or more error
         messages are generated. THIS SHOULD NEVER OCCUR !!!!
    """
    if len(hideInLog) == 0:
        rh.printSysLog("Enter vmUtils.invokeSMCLI, userid: " +
                       rh.userid + ", function: " + api +
                       ", parms: " + str(parms))
    else:
        logParms = parms
        for i in hideInLog:
            logParms[i] = '<hidden>'
        rh.printSysLog("Enter vmUtils.invokeSMCLI, userid: " +
               rh.userid + ", function: " + api +
               ", parms: " + str(logParms))
    goodHeader = False

    results = {
              'overallRC': 0,
              'rc': 0,
              'rs': 0,
              'errno': 0,
              'response': [],
              'strError': '',
             }

    cmd = []
    cmd.append('sudo')
    cmd.append('/opt/zthin/bin/smcli')
    cmd.append(api)
    cmd.append('--addRCheader')

    try:
        smcliResp = subprocess.check_output(cmd + parms,
            close_fds=True)
        if isinstance(smcliResp, bytes):
            smcliResp = bytes.decode(smcliResp, errors='replace')

        smcliResp = smcliResp.split('\n', 1)
        results['response'] = smcliResp[1]
        results['overallRC'] = 0
        results['rc'] = 0

    except CalledProcessError as e:
        strCmd = " ".join(cmd + parms)

        # Break up the RC header into its component parts.
        if e.output == '':
            smcliResp = ['']
        else:
            smcliResp = bytes.decode(e.output).split('\n', 1)

        # Split the header into its component pieces.
        rcHeader = smcliResp[0].split('(details)', 1)
        if len(rcHeader) == 0:
            rcHeader = ['', '']
        elif len(rcHeader) == 1:
            # No data after the details tag.  Add empty [1] value.
            rcHeader.append('')
        codes = rcHeader[0].split(' ')

        # Validate the rc, rs, and errno.
        if len(codes) < 3:
            # Unexpected number of codes.  Need at least 3.
            results = msgs.msg['0301'][0]
            results['response'] = msgs.msg['0301'][1] % (modId, api,
                strCmd, rcHeader[0], rcHeader[1])
        else:
            goodHeader = True
            # Convert the first word (overall rc from SMAPI) to an int
            # and set the SMUT overall rc based on this value.
            orcError = False
            try:
                results['overallRC'] = int(codes[0])
                if results['overallRC'] not in [8, 24, 25]:
                    orcError = True
            except ValueError:
                goodHeader = False
                orcError = True
            if orcError:
                results['overallRC'] = 25    # SMCLI Internal Error
                results = msgs.msg['0302'][0]
                results['response'] = msgs.msg['0302'][1] % (modId,
                    api, codes[0], strCmd, rcHeader[0], rcHeader[1])

            # Convert the second word to an int and save as rc.
            try:
                results['rc'] = int(codes[1])
            except ValueError:
                goodHeader = False
                results = msgs.msg['0303'][0]
                results['response'] = msgs.msg['0303'][1] % (modId,
                    api, codes[1], strCmd, rcHeader[0], rcHeader[1])

            # Convert the second word to an int and save it as either
            # the rs or errno.
            try:
                word3 = int(codes[2])
                if results['overallRC'] == 8:
                    results['rs'] = word3    # Must be an rs
                elif results['overallRC'] == 25:
                    results['errno'] = word3    # Must be the errno
                # We ignore word 3 for everyone else and default to 0.
            except ValueError:
                goodHeader = False
                results = msgs.msg['0304'][0]
                results['response'] = msgs.msg['0304'][1] % (modId,
                    api, codes[1], strCmd, rcHeader[0], rcHeader[1])

        results['strError'] = rcHeader[1].lstrip()

        if goodHeader:
            # Produce a message that provides the error info.
            results['response'] = msgs.msg['0300'][1] % (modId,
                    api, results['overallRC'], results['rc'],
                    results['rs'], results['errno'],
                    strCmd, smcliResp[1])

    except Exception as e:
        # All other exceptions.
        strCmd = " ".join(cmd + parms)
        results = msgs.msg['0305'][0]
        results['response'] = msgs.msg['0305'][1] % (modId, strCmd,
            type(e).__name__, str(e))

    rh.printSysLog("Exit vmUtils.invokeSMCLI, rc: " +
        str(results['overallRC']))
    return results


def isLoggedOn(rh, userid):
    """
    Determine whether a virtual machine is logged on.

    Input:
       Request Handle:
          userid being queried

    Output:
       Dictionary containing the following:
          overallRC - overall return code, 0: success, non-zero: failure
          rc        - 0: if we got status.  Otherwise, it is the
                        error return code from the commands issued.
          rs        - Based on rc value.  For rc==0, rs is:
                      0: if we determined it is logged on.
                      1: if we determined it is logged off.
    """

    rh.printSysLog("Enter vmUtils.isLoggedOn, userid: " + userid)

    results = {
              'overallRC': 0,
              'rc': 0,
              'rs': 0,
             }

    cmd = ["sudo", "/sbin/vmcp", "query", "user", userid]
    strCmd = ' '.join(cmd)
    rh.printSysLog("Invoking: " + strCmd)
    try:
        subprocess.check_output(
            cmd,
            close_fds=True,
            stderr=subprocess.STDOUT)
    except CalledProcessError as e:
        search_pattern = '(^HCP\w\w\w045E|^HCP\w\w\w361E)'.encode()
        match = re.search(search_pattern, e.output)
        if match:
            # Not logged on
            results['rs'] = 1
        else:
            # Abnormal failure
            rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
                e.returncode, e.output))
            results = msgs.msg['0415'][0]
            results['rs'] = e.returncode
    except Exception as e:
        # All other exceptions.
        results = msgs.msg['0421'][0]
        rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
            type(e).__name__, str(e)))

    rh.printSysLog("Exit vmUtils.isLoggedOn, overallRC: " +
        str(results['overallRC']) + " rc: " + str(results['rc']) +
        " rs: " + str(results['rs']))
    return results


def punch2reader(rh, userid, fileLoc, spoolClass):
    """
    Punch a file to a virtual reader of the specified virtual machine.

    Input:
       Request Handle - for general use and to hold the results
       userid         - userid of the virtual machine
       fileLoc        - File to send
       spoolClass     - Spool class

    Output:
       Request Handle updated with the results.
       Return code - 0: ok, non-zero: error
    """

    rh.printSysLog("Enter punch2reader.punchFile")
    results = {}

    # Setting rc to time out rc code as default and its changed during runtime
    results['rc'] = 9

    # Punch to the current user intially and then change the spool class.
    cmd = ["sudo", "/usr/sbin/vmur", "punch", "-r", fileLoc]
    strCmd = ' '.join(cmd)
    for secs in [1, 2, 3, 5, 10]:
        rh.printSysLog("Invoking: " + strCmd)
        try:
            results['response'] = subprocess.check_output(cmd,
                                        close_fds=True,
                                        stderr=subprocess.STDOUT)
            if isinstance(results['response'], bytes):
                results['response'] = bytes.decode(results['response'])
            results['rc'] = 0
            rh.updateResults(results)
            break
        except CalledProcessError as e:
            results['response'] = e.output
            # Check if we have concurrent instance of vmur active
            to_find = "A concurrent instance of vmur is already active"
            to_find = to_find.encode()
            if results['response'].find(to_find) == -1:
                # Failure in VMUR punch update the rc
                results['rc'] = 7
                break
            else:
                # if concurrent vmur is active try after sometime
                rh.printSysLog("Punch in use. Retrying after " +
                               str(secs) + " seconds")
                time.sleep(secs)
        except Exception as e:
            # All other exceptions.
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                type(e).__name__, str(e)))
            results = msgs.msg['0421'][0]
            rh.updateResults(results)

    if results['rc'] == 7:
        # Failure while issuing vmur command (For eg: invalid file given)
        msg = msgs.msg['0401'][1] % (modId, fileLoc, userid,
                                     results['response'])
        rh.printLn("ES", msg)
        rh.updateResults(msgs.msg['0401'][0])

    elif results['rc'] == 9:
        # Failure due to vmur timeout
        msg = msgs.msg['0406'][1] % (modId, fileLoc)
        rh.printLn("ES", msg)
        rh.updateResults(msgs.msg['0406'][0])

    if rh.results['overallRC'] == 0:
        # On VMUR success change the class of the spool file
        spoolId = re.findall(r'\d+', str(results['response']))
        cmd = ["sudo", "vmcp", "change", "rdr", str(spoolId[0]), "class",
               spoolClass]
        strCmd = " ".join(cmd)
        rh.printSysLog("Invoking: " + strCmd)
        try:
            results['response'] = subprocess.check_output(cmd,
                                        close_fds=True,
                                        stderr=subprocess.STDOUT)
            if isinstance(results['response'], bytes):
                results['response'] = bytes.decode(results['response'])
            rh.updateResults(results)
        except CalledProcessError as e:
            msg = msgs.msg['0404'][1] % (modId,
                                         spoolClass,
                                         e.output)
            rh.printLn("ES", msg)
            rh.updateResults(msgs.msg['0404'][0])
            # Class change failed
            # Delete the punched file from current userid
            cmd = ["sudo", "vmcp", "purge", "rdr", spoolId[0]]
            strCmd = " ".join(cmd)
            rh.printSysLog("Invoking: " + strCmd)
            try:
                results['response'] = subprocess.check_output(cmd,
                                            close_fds=True,
                                            stderr=subprocess.STDOUT)
                if isinstance(results['response'], bytes):
                    results['response'] = bytes.decode(results['response'])
            # We only need to issue the printLn.
            # Don't need to change return/reason code values
            except CalledProcessError as e:
                msg = msgs.msg['0403'][1] % (modId,
                                             spoolId[0],
                                             e.output)
                rh.printLn("ES", msg)
            except Exception as e:
                # All other exceptions related to purge.
                # We only need to issue the printLn.
                # Don't need to change return/reason code values
                rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                    type(e).__name__, str(e)))
        except Exception as e:
            # All other exceptions related to change rdr.
            results = msgs.msg['0421'][0]
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                type(e).__name__, str(e)))
            rh.updateResults(msgs.msg['0421'][0])

    if rh.results['overallRC'] == 0:
        # Transfer the file from current user to specified user
        cmd = ["sudo", "vmcp", "transfer", "*", "rdr", str(spoolId[0]), "to",
                userid, "rdr"]
        strCmd = " ".join(cmd)
        rh.printSysLog("Invoking: " + strCmd)
        try:
            results['response'] = subprocess.check_output(cmd,
                                        close_fds=True,
                                        stderr=subprocess.STDOUT)
            if isinstance(results['response'], bytes):
                results['response'] = bytes.decode(results['response'])
            rh.updateResults(results)
        except CalledProcessError as e:
            msg = msgs.msg['0424'][1] % (modId,
                                         fileLoc,
                                         userid, e.output)
            rh.printLn("ES", msg)
            rh.updateResults(msgs.msg['0424'][0])

            # Transfer failed so delete the punched file from current userid
            cmd = ["sudo", "vmcp", "purge", "rdr", spoolId[0]]
            strCmd = " ".join(cmd)
            rh.printSysLog("Invoking: " + strCmd)
            try:
                results['response'] = subprocess.check_output(cmd,
                                            close_fds=True,
                                            stderr=subprocess.STDOUT)
                if isinstance(results['response'], bytes):
                    results['response'] = bytes.decode(results['response'])
                # We only need to issue the printLn.
                # Don't need to change return/reason code values
            except CalledProcessError as e:
                msg = msgs.msg['0403'][1] % (modId,
                                             spoolId[0],
                                             e.output)
                rh.printLn("ES", msg)
            except Exception as e:
                # All other exceptions related to purge.
                rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                    type(e).__name__, str(e)))
        except Exception as e:
            # All other exceptions related to transfer.
            results = msgs.msg['0421'][0]
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                type(e).__name__, str(e)))
            rh.updateResults(msgs.msg['0421'][0])

    rh.printSysLog("Exit vmUtils.punch2reader, rc: " +
        str(rh.results['overallRC']))
    return rh.results['overallRC']


def waitForOSState(rh, userid, desiredState, maxQueries=90, sleepSecs=5):
    """
    Wait for the virtual OS to go into the indicated state.

    Input:
       Request Handle
       userid whose state is to be monitored
       Desired state, 'up' or 'down', case sensitive
       Maximum attempts to wait for desired state before giving up
       Sleep duration between waits

    Output:
       Dictionary containing the following:
          overallRC - overall return code, 0: success, non-zero: failure
          rc        - RC returned from execCmdThruIUCV if overallRC = 0.
          rs        - RS returned from execCmdThruIUCV if overallRC = 0.
          errno     - Errno returned from execCmdThruIUCV if overallRC = 0.
          response  - Updated with an error message if wait times out.

    Note:

    """

    rh.printSysLog("Enter vmUtils.waitForOSState, userid: " + userid +
                           " state: " + desiredState +
                           " maxWait: " + str(maxQueries) +
                           " sleepSecs: " + str(sleepSecs))

    results = {}

    strCmd = "echo 'ping'"
    stateFnd = False

    for i in range(1, maxQueries + 1):
        results = execCmdThruIUCV(rh, rh.userid, strCmd)
        if results['overallRC'] == 0:
            if desiredState == 'up':
                stateFnd = True
                break
        else:
            if desiredState == 'down':
                stateFnd = True
                break

        if i < maxQueries:
            time.sleep(sleepSecs)

    if stateFnd is True:
        results = {
                'overallRC': 0,
                'rc': 0,
                'rs': 0,
            }
    else:
        maxWait = maxQueries * sleepSecs
        rh.printLn("ES", msgs.msg['0413'][1] % (modId, userid,
            desiredState, maxWait))
        results = msgs.msg['0413'][0]

    rh.printSysLog("Exit vmUtils.waitForOSState, rc: " +
        str(results['overallRC']))
    return results


def waitForVMState(rh, userid, desiredState, maxQueries=90, sleepSecs=5):
    """
    Wait for the virtual machine to go into the indicated state.

    Input:
       Request Handle
       userid whose state is to be monitored
       Desired state, 'on' or 'off', case sensitive
       Maximum attempts to wait for desired state before giving up
       Sleep duration between waits

    Output:
       Dictionary containing the following:
          overallRC - overall return code, 0: success, non-zero: failure
          rc        - RC returned from SMCLI if overallRC = 0.
          rs        - RS returned from SMCLI if overallRC = 0.

    Note:

    """

    rh.printSysLog("Enter vmUtils.waitForVMState, userid: " + userid +
                           " state: " + desiredState +
                           " maxWait: " + str(maxQueries) +
                           " sleepSecs: " + str(sleepSecs))

    results = {}

    cmd = ["sudo", "/sbin/vmcp", "query", "user", userid]
    strCmd = " ".join(cmd)
    stateFnd = False

    for i in range(1, maxQueries + 1):
        rh.printSysLog("Invoking: " + strCmd)
        try:
            out = subprocess.check_output(
                cmd,
                close_fds=True,
                stderr=subprocess.STDOUT)
            if isinstance(out, bytes):
                out = bytes.decode(out)
            if desiredState == 'on':
                stateFnd = True
                break
        except CalledProcessError as e:
            match = re.search('(^HCP\w\w\w045E|^HCP\w\w\w361E)', e.output)
            if match:
                # Logged off
                if desiredState == 'off':
                    stateFnd = True
                    break
            else:
                # Abnormal failure
                out = e.output
                rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
                    e.returncode, out))
                results = msgs.msg['0415'][0]
                results['rs'] = e.returncode
                break
        except Exception as e:
            # All other exceptions.
            rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
                type(e).__name__, str(e)))
            results = msgs.msg['0421'][0]

        if i < maxQueries:
            # Sleep a bit before looping.
            time.sleep(sleepSecs)

    if stateFnd is True:
        results = {
                'overallRC': 0,
                'rc': 0,
                'rs': 0,
            }
    else:
        maxWait = maxQueries * sleepSecs
        rh.printLn("ES", msgs.msg['0414'][1] % (modId, userid,
            desiredState, maxWait))
        results = msgs.msg['0414'][0]

    rh.printSysLog("Exit vmUtils.waitForVMState, rc: " +
        str(results['overallRC']))
    return results


def purgeReader(rh):
    """
    Purge reader of the specified userid.

    Input:
       Request Handle

    Output:
       Dictionary containing the following:
          overallRC - overall return code, 0: success, non-zero: failure
          rc        - RC returned from SMCLI if overallRC = 0.
          rs        - RS returned from SMCLI if overallRC = 0.
          errno     - Errno returned from SMCLI if overallRC = 0.
          response  - Updated with an error message.

    Note:

    """
    rh.printSysLog("Enter vmUtils.purgeRDR, userid: " + rh.userid)
    results = {'overallRC': 0,
               'rc': 0,
               'rs': 0,
               'response': []}

    parms = ['-T', rh.userid, '-k', 'spoolids=all']

    results = invokeSMCLI(rh, "System_RDR_File_Manage", parms)

    if results['overallRC'] != 0:
        rh.printLn("ES", results['response'])
        rh.updateResults(results)

    rh.printSysLog("Exit vmUtils.purgeReader, rc: " +
                   str(results['overallRC']))
    return results