summaryrefslogtreecommitdiffstats
path: root/glusternagios/glustercli.py
blob: 18caa7951b3c1394fafbd085c0a30fac72de531f (plain)
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
# Copyright 2014 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#

import xml.etree.cElementTree as etree
import ethtool

import utils
from utils import CommandPath
from hostname import getHostNameFqdn, HostNameException

glusterCmdPath = CommandPath("gluster",
                             "/usr/sbin/gluster")


# Class for exception definition
class GlusterCmdFailedException(Exception):
    message = "command execution failed"

    def __init__(self, rc=0, out=(), err=()):
        self.rc = rc
        self.out = out
        self.err = err

    def __str__(self):
        o = '\n'.join(self.out)
        e = '\n'.join(self.err)
        if o and e:
            m = o + '\n' + e
        else:
            m = o or e

        s = self.message
        if m:
            s += '\nerror: ' + m
        if self.rc:
            s += '\nreturn code: %s' % self.rc
        return s


if hasattr(etree, 'ParseError'):
    _etreeExceptions = (etree.ParseError, AttributeError, ValueError)
else:
    _etreeExceptions = (SyntaxError, AttributeError, ValueError)


def _getGlusterVolCmd():
    return [glusterCmdPath.cmd, "--mode=script", "volume"]


def _getGlusterPeerCmd():
    return [glusterCmdPath.cmd, "--mode=script", "peer"]


def _getGlusterSystemCmd():
    return [glusterCmdPath.cmd, "system::"]


class HostStatus:
    CONNECTED = 'CONNECTED'
    DISCONNECTED = 'DISCONNECTED'
    UNKNOWN = 'UNKNOWN'


class VolumeStatus:
    ONLINE = 'ONLINE'
    OFFLINE = 'OFFLINE'


class VolumeQuotaStatus:
    DISABLED = 'DISABLED'
    OK = 'OK'
    SOFT_LIMIT_EXCEEDED = 'SOFT_LIMIT_EXCEEDED'
    HARD_LIMIT_EXCEEDED = 'HARD_LIMIT_EXCEEDED'


class VolumeSplitBrainStatus:
    NOTAPPLICABLE = 'NA'
    OK = 'OK'
    SPLITBRAIN = 'SPLITBRAIN'


class GeoRepStatus:
    OK = 'OK'
    NOT_STARTED = "NOT_STARTED"
    FAULTY = "FAULTY"
    PARTIAL_FAULTY = "PARTIAL_FAULTY"
    STOPPED = "STOPPED"


class TransportType:
    TCP = 'TCP'
    RDMA = 'RDMA'


class TaskType:
    REBALANCE = 'REBALANCE'
    REPLACE_BRICK = 'REPLACE_BRICK'
    REMOVE_BRICK = 'REMOVE_BRICK'


def _getaddr(dev):
    dev_info_list = ethtool.get_interfaces_info(dev.encode('utf8'))
    addr = dev_info_list[0].ipv4_address
    if addr is None:
        addr = ''
    return addr


def _getIpAddresses():
    devinfo = {}
    for dev in ethtool.get_active_devices():
        try:
            devinfo[dev] = ethtool.get_ipaddr(dev)
        except IOError, e:
            print e

    return devinfo


def _getGlusterHostName():
    try:
        return getHostNameFqdn()
    except HostNameException:
        return ''


def _getLocalIpAddress():
    for ip in _getIpAddresses():
        if not ip.startswith('127.'):
            return ip
    return ''


def _execGluster(cmd):
    return utils.execCmd(cmd)


def _execGlusterXml(cmd):
    cmd.append('--xml')
    rc, out, err = utils.execCmd(cmd)
    if rc != 0:
        raise GlusterCmdFailedException(rc, out, err)
    try:
        tree = etree.fromstring('\n'.join(out))
        rv = int(tree.find('opRet').text)
        msg = tree.find('opErrstr').text
        errNo = int(tree.find('opErrno').text)
    except _etreeExceptions:
        raise GlusterCmdFailedException(err=out)
    if rv == 0:
        return tree
    else:
        if errNo != 0:
            rv = errNo
        raise GlusterCmdFailedException(rc=rv, err=[msg])


def hostUUIDGet():
    command = _getGlusterSystemCmd() + ["uuid", "get"]
    rc, out, err = _execGluster(command)
    if rc == 0:
        for line in out:
            if line.startswith('UUID: '):
                return line[6:]

    raise GlusterCmdFailedException()


def _parseVolumeStatus(tree):
    status = {'name': tree.find('volStatus/volumes/volume/volName').text,
              'bricks': [],
              'nfs': [],
              'shd': []}
    hostname = _getLocalIpAddress() or _getGlusterHostName()
    for el in tree.findall('volStatus/volumes/volume/node'):
        value = {}

        for ch in el.getchildren():
            value[ch.tag] = ch.text or ''

        if value['path'] == 'localhost':
            value['path'] = hostname

        if value['status'] == '1':
            value['status'] = 'ONLINE'
        else:
            value['status'] = 'OFFLINE'

        if value['hostname'] == 'NFS Server':
            status['nfs'].append({'hostname': value['path'],
                                  'port': value['port'],
                                  'status': value['status'],
                                  'pid': value['pid']})
        elif value['hostname'] == 'Self-heal Daemon':
            status['shd'].append({'hostname': value['path'],
                                  'status': value['status'],
                                  'pid': value['pid']})
        else:
            status['bricks'].append({'brick': '%s:%s' % (value['hostname'],
                                                         value['path']),
                                     'port': value['port'],
                                     'status': value['status'],
                                     'pid': value['pid']})
    return status


def _parseVolumeStatusDetail(tree):
    status = {'name': tree.find('volStatus/volumes/volume/volName').text,
              'bricks': []}
    for el in tree.findall('volStatus/volumes/volume/node'):
        value = {}

        for ch in el.getchildren():
            value[ch.tag] = ch.text or ''

        sizeTotal = int(value['sizeTotal'])
        value['sizeTotal'] = sizeTotal / (1024.0 * 1024.0)
        sizeFree = int(value['sizeFree'])
        value['sizeFree'] = sizeFree / (1024.0 * 1024.0)
        status['bricks'].append({'brick': '%s:%s' % (value['hostname'],
                                                     value['path']),
                                 'sizeTotal': '%.3f' % (value['sizeTotal'],),
                                 'sizeFree': '%.3f' % (value['sizeFree'],),
                                 'device': value['device'],
                                 'blockSize': value['blockSize'],
                                 'mntOptions': value['mntOptions'],
                                 'fsName': value['fsName']})
    return status


def _parseVolumeStatusClients(tree):
    status = {'name': tree.find('volStatus/volumes/volume/volName').text,
              'bricks': []}
    for el in tree.findall('volStatus/volumes/volume/node'):
        hostname = el.find('hostname').text
        path = el.find('path').text

        clientsStatus = []
        for c in el.findall('clientsStatus/client'):
            clientValue = {}
            for ch in c.getchildren():
                clientValue[ch.tag] = ch.text or ''
            clientsStatus.append({'hostname': clientValue['hostname'],
                                  'bytesRead': clientValue['bytesRead'],
                                  'bytesWrite': clientValue['bytesWrite']})

        status['bricks'].append({'brick': '%s:%s' % (hostname, path),
                                 'clientsStatus': clientsStatus})
    return status


def _parseVolumeStatusMem(tree):
    status = {'name': tree.find('volStatus/volumes/volume/volName').text,
              'bricks': []}
    for el in tree.findall('volStatus/volumes/volume/node'):
        brick = {'brick': '%s:%s' % (el.find('hostname').text,
                                     el.find('path').text),
                 'mallinfo': {},
                 'mempool': []}

        for ch in el.find('memStatus/mallinfo').getchildren():
            brick['mallinfo'][ch.tag] = ch.text or ''

        for c in el.findall('memStatus/mempool/pool'):
            mempool = {}
            for ch in c.getchildren():
                mempool[ch.tag] = ch.text or ''
            brick['mempool'].append(mempool)

        status['bricks'].append(brick)
    return status


def volumeStatus(volumeName, brick=None, option=None):
    """
    Get volume status

    Arguments:
       * VolumeName
       * brick
       * option = 'detail' or 'clients' or 'mem' or None
    Returns:
       When option=None,
         {'name': NAME,
          'bricks': [{'brick': BRICK,
                      'port': PORT,
                      'status': STATUS,
                      'pid': PID}, ...],
          'nfs': [{'hostname': HOST,
                   'port': PORT,
                   'status': STATUS,
                   'pid': PID}, ...],
          'shd: [{'hostname': HOST,
                  'status': STATUS,
                  'pid': PID}, ...]}

      When option='detail',
         {'name': NAME,
          'bricks': [{'brick': BRICK,
                      'sizeTotal': SIZE,
                      'sizeFree': FREESIZE,
                      'device': DEVICE,
                      'blockSize': BLOCKSIZE,
                      'mntOptions': MOUNTOPTIONS,
                      'fsName': FSTYPE}, ...]}

       When option='clients':
         {'name': NAME,
          'bricks': [{'brick': BRICK,
                      'clientsStatus': [{'hostname': HOST,
                                         'bytesRead': BYTESREAD,
                                         'bytesWrite': BYTESWRITE}, ...]},
                    ...]}

       When option='mem':
         {'name': NAME,
          'bricks': [{'brick': BRICK,
                      'mallinfo': {'arena': int,
                                   'fordblks': int,
                                   'fsmblks': int,
                                   'hblkhd': int,
                                   'hblks': int,
                                   'keepcost': int,
                                   'ordblks': int,
                                   'smblks': int,
                                   'uordblks': int,
                                   'usmblks': int},
                      'mempool': [{'allocCount': int,
                                   'coldCount': int,
                                   'hotCount': int,
                                   'maxAlloc': int,
                                   'maxStdAlloc': int,
                                   'name': NAME,
                                   'padddedSizeOf': int,
                                   'poolMisses': int},...]}, ...]}
    """
    command = _getGlusterVolCmd() + ["status", volumeName]
    if brick:
        command.append(brick)
    if option:
        command.append(option)
    try:
        xmltree = _execGlusterXml(command)
    except GlusterCmdFailedException as e:
        raise GlusterCmdFailedException(rc=e.rc, err=e.err)
    try:
        if option == 'detail':
            return _parseVolumeStatusDetail(xmltree)
        elif option == 'clients':
            return _parseVolumeStatusClients(xmltree)
        elif option == 'mem':
            return _parseVolumeStatusMem(xmltree)
        else:
            return _parseVolumeStatus(xmltree)
    except _etreeExceptions:
        raise GlusterCmdFailedException(err=[etree.tostring(xmltree)])


def _parseVolumeInfo(tree):
    """
        {VOLUMENAME: {'brickCount': BRICKCOUNT,
                      'bricks': [BRICK1, BRICK2, ...],
                      'options': {OPTION: VALUE, ...},
                      'transportType': [TCP,RDMA, ...],
                      'uuid': UUID,
                      'volumeName': NAME,
                      'volumeStatus': STATUS,
                      'volumeType': TYPE}, ...}
    """
    volumes = {}
    for el in tree.findall('volInfo/volumes/volume'):
        value = {}
        value['volumeName'] = el.find('name').text
        value['uuid'] = el.find('id').text
        value['volumeType'] = el.find('typeStr').text.upper().replace('-', '_')
        status = el.find('statusStr').text.upper()
        if status == 'STARTED':
            value["volumeStatus"] = VolumeStatus.ONLINE
        else:
            value["volumeStatus"] = VolumeStatus.OFFLINE
        value['brickCount'] = el.find('brickCount').text
        value['distCount'] = el.find('distCount').text
        value['stripeCount'] = el.find('stripeCount').text
        value['replicaCount'] = el.find('replicaCount').text
        transportType = el.find('transport').text
        if transportType == '0':
            value['transportType'] = [TransportType.TCP]
        elif transportType == '1':
            value['transportType'] = [TransportType.RDMA]
        else:
            value['transportType'] = [TransportType.TCP, TransportType.RDMA]
        value['bricks'] = []
        value['options'] = {}
        value['bricksInfo'] = []
        for b in el.findall('bricks/brick'):
            value['bricks'].append(b.text)
        for o in el.findall('options/option'):
            value['options'][o.find('name').text] = o.find('value').text
        for d in el.findall('bricks/brick'):
            brickDetail = {}
            # this try block is to maintain backward compatibility
            # it returns an empty list when gluster doesnot return uuid
            try:
                brickDetail['name'] = d.find('name').text
                brickDetail['hostUuid'] = d.find('hostUuid').text
                value['bricksInfo'].append(brickDetail)
            except AttributeError:
                break
        volumes[value['volumeName']] = value
    return volumes


def volumeInfo(volumeName=None, remoteServer=None):
    """
    Returns:
        {VOLUMENAME: {'brickCount': BRICKCOUNT,
                      'bricks': [BRICK1, BRICK2, ...],
                      'options': {OPTION: VALUE, ...},
                      'transportType': [TCP,RDMA, ...],
                      'uuid': UUID,
                      'volumeName': NAME,
                      'volumeStatus': STATUS,
                      'volumeType': TYPE}, ...}
    """
    command = _getGlusterVolCmd() + ["info"]
    if remoteServer:
        command += ['--remote-host=%s' % remoteServer]
    if volumeName:
        command.append(volumeName)
    try:
        xmltree = _execGlusterXml(command)
    except GlusterCmdFailedException as e:
        raise GlusterCmdFailedException(rc=e.rc, err=e.err)
    try:
        return _parseVolumeInfo(xmltree)
    except _etreeExceptions:
        raise GlusterCmdFailedException(err=[etree.tostring(xmltree)])


def _parseVolumeQuotaStatus(out, isDisabled=False):
    status_detail = {'status': VolumeQuotaStatus.OK,
                     'soft_ex_dirs': [],
                     'hard_ex_dirs': []}

    if isDisabled or out[0].startswith('quota: No quota'
                                       ) or out[0].find('not enabled') > -1:
        status_detail['status'] = VolumeQuotaStatus.DISABLED
        return status_detail
    for line in out[2:]:
        l = line.split()
        if l[-1].find('Yes') > -1:
            status_detail[
                'status'] = VolumeQuotaStatus.HARD_LIMIT_EXCEEDED
            status_detail['hard_ex_dirs'].append(l[0])
            continue
        elif l[-2].find('Yes') > -1:
            if status_detail['status'
                             ] != VolumeQuotaStatus.HARD_LIMIT_EXCEEDED:
                status_detail['status'] = VolumeQuotaStatus.SOFT_LIMIT_EXCEEDED
            status_detail['soft_ex_dirs'].append(l[0])

    return status_detail


def _parseVolumeSelfHealSplitBrainInfo(out):
    value = {}
    splitbrainentries = 0
    for line in out:
        if line.startswith('Number of entries:'):
            entries = int(line.split(':')[1])
            if entries > 0:
                splitbrainentries += entries
    if splitbrainentries > 0:
        value['status'] = VolumeSplitBrainStatus.SPLITBRAIN
    else:
        value['status'] = VolumeSplitBrainStatus.OK
    value['unsyncedentries'] = splitbrainentries
    return value


def _parseVolumeGeoRepStatus(volumeName, out):
    # https://bugzilla.redhat.com/show_bug.cgi?id=1090910 - opened for xml
    # output. For now parsing below string output format
    # MASTER NODE                MASTER VOL    MASTER BRICK
    # SLAVE                     STATUS     CHECKPOINT STATUS  CRAWL STATUS
    slaves = {}
    other_status = ['ACTIVE', 'INITIALIZING...']
    for line in out[3:]:
        tempstatus = None
        nodeline = line.split()
        node = nodeline[0]
        brick = nodeline[2]
        slave = nodeline[3][nodeline[3].find('::') + 2:]
        if slaves.get(slave) is None:
            slaves[slave] = {'nodecount': 0,
                             'faulty': 0,
                             'notstarted': 0,
                             'stopped': 0,
                             'passive': 0,
                             'detail': '',
                             'status': GeoRepStatus.OK,
                             'name': nodeline[3]
                             }
        slaves[slave]['nodecount'] += 1
        if GeoRepStatus.FAULTY in line.upper():
            slaves[slave]['faulty'] += 1
            tempstatus = GeoRepStatus.FAULTY
        elif "NOT STARTED" in line.upper():
            slaves[slave]['notstarted'] += 1
            tempstatus = GeoRepStatus.NOT_STARTED
        elif "PASSIVE" in line.upper():
            slaves[slave]['passive'] += 1
            tempstatus = "PASSIVE"
        elif GeoRepStatus.STOPPED in line.upper():
            slaves[slave]['stopped'] += 1
            tempstatus = GeoRepStatus.STOPPED
        elif not any(gstatus in line.upper() for gstatus in other_status):
            tempstatus = nodeline[4]

        if tempstatus:
            slaves[slave]['detail'] += ("%s:%s - %s;" % (node,
                                                         brick,
                                                         tempstatus))
    volumes = volumeInfo(volumeName)
    brickCount = int(volumes[volumeName]["brickCount"])
    if "REPLICATE" in volumes[volumeName]["volumeType"]:
        replicaCount = int(volumes[volumeName]["replicaCount"])
    else:
        replicaCount = brickCount

    for slave, count_dict in slaves.iteritems():
        if count_dict['nodecount'] > brickCount:
            # There are multiple slave volumes with same name, the output
            # may be wrong
            slaves[slave]['detail'] += "NOTE:Multiple slave session aggregated"
        if count_dict['faulty'] > 0:
            # georep cli status does not give the node name in the same way as
            # gluster volume info - there's no way to compare and get the
            # subvolume. So if fault+passive > than num of primary bricks,
            # moving to faulty
            if (count_dict['faulty'] + count_dict['passive']
                    >= count_dict['nodecount']/replicaCount):
                slaves[slave]['status'] = GeoRepStatus.FAULTY
            else:
                slaves[slave]['status'] = GeoRepStatus.PARTIAL_FAULTY
        elif (count_dict['notstarted'] > 0 and
              slaves[slave]['status'] == GeoRepStatus.OK):
            slaves[slave]['status'] = GeoRepStatus.NOT_STARTED
        elif (count_dict['stopped'] > 0 and
              slaves[slave]['status'] == GeoRepStatus.OK):
            slaves[slave]['status'] = GeoRepStatus.STOPPED
    return {volumeName: {'slaves': slaves}}


def volumeGeoRepStatus(volumeName, remoteServer=None):
    """
    Arguments:
       * VolumeName
    Returns:
        {VOLUMENAME: {'slaves': [{SLAVENAME:{
                                   'nodecount': COUNT,
                                   'faulty': COUNT,
                                   'notstarted': COUNT,
                                   'stopped': COUNT,
                                   'passive':COUNT,
                                   'detail': detailed message,
                                   'status': GEOREPSTATUS,
                                   'name': SLAVESESSIONNAME}}
                                ]}
    """
    command = _getGlusterVolCmd() + ["geo-replication", volumeName, "status"]
    if remoteServer:
        command += ['--remote-host=%s' % remoteServer]

    rc, out, err = _execGluster(command)

    if rc == 0:
        return _parseVolumeGeoRepStatus(volumeName, out)
    raise GlusterCmdFailedException(rc=rc, err=err)


def volumeHealSplitBrainStatus(volumeName, remoteServer=None):
    """
    Arguments:
       * VolumeName
    Returns:
        {VOLUMENAME: {'status': SELFHEALSTATUS,
                      'unsyncedentries': ENTRYCOUNT}}
    """
    command = _getGlusterVolCmd() + ["heal", volumeName, "info"]
    if remoteServer:
        command += ['--remote-host=%s' % remoteServer]

    rc, out, err = _execGluster(command)
    volume = {}
    value = {}
    if rc == 0:
        value = _parseVolumeSelfHealSplitBrainInfo(out)
        volume[volumeName] = value
        return volume
    else:
        if len(err) > 0 and err[0].find("is not of type replicate") > -1:
            value['status'] = VolumeSplitBrainStatus.NOTAPPLICABLE
            value['unsyncedentries'] = 0
            volume[volumeName] = value
            return volume
    raise GlusterCmdFailedException(rc=rc, err=err)


def volumeQuotaStatus(volumeName, remoteServer=None):
    """
    Returns:

        {status: OK|SOFT_LIMIT_EXCEEDED|HARD_LIMIT_EXCEEDED|DISABLED,
         soft_ex_dirs: ["dir1","dir2".....],
         hard_ex_dirs: ["dir1","dir2".....]}

    """
    command = _getGlusterVolCmd() + ["quota", volumeName, "list"]
    if remoteServer:
        command += ['--remote-host=%s' % remoteServer]

    rc, out, err = _execGluster(command)
    if rc == 0:
        return _parseVolumeQuotaStatus(out, isDisabled=False)
    else:
        if len(err) > 0 and err[0].find("Quota is disabled") > -1:
            return _parseVolumeQuotaStatus(out, isDisabled=True)
    raise GlusterCmdFailedException(rc, err)


def _parsePeerStatus(tree, gHostName, gUuid, gStatus):
    hostList = [{'hostname': gHostName,
                 'uuid': gUuid,
                 'status': gStatus}]

    for el in tree.findall('peerStatus/peer'):
        if el.find('state').text != '3':
            status = HostStatus.UNKNOWN
        elif el.find('connected').text == '1':
            status = HostStatus.CONNECTED
        else:
            status = HostStatus.DISCONNECTED
        hostList.append({'hostname': el.find('hostname').text,
                         'uuid': el.find('uuid').text,
                         'status': status})

    return hostList


def peerStatus():
    """
    Returns:
        [{'hostname': HOSTNAME, 'uuid': UUID, 'status': STATE}, ...]

    Note: Current host will be the first entry in the list with name as
    'localhost' and status as CONNECTED

    """
    command = _getGlusterPeerCmd() + ["status"]
    try:
        xmltree = _execGlusterXml(command)
    except GlusterCmdFailedException as e:
        raise GlusterCmdFailedException(rc=e.rc, err=e.err)
    try:
        return _parsePeerStatus(xmltree, "localhost", hostUUIDGet(),
                                HostStatus.CONNECTED)
    except _etreeExceptions:
        raise GlusterCmdFailedException(err=[etree.tostring(xmltree)])