This file is indexed.

/usr/share/heartbeat/cts/CM_hb.py is in heartbeat 1:3.0.5-3ubuntu2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
#!/usr/bin/python

'''CTS: Cluster Testing System: heartbeat dependent modules...

Classes related to testing high-availability clusters...

Lots of things are implemented.

Lots of things are not implemented.

We have many more ideas of what to do than we've implemented.
 '''

__copyright__='''
Copyright (C) 2000,2001,2005 Alan Robertson <alanr@unix.sh>
Licensed under the GNU GPL.
'''

#
# 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

from CTS import *


class HeartbeatCM(ClusterManager):
    '''
    The heartbeat cluster manager class.
    It implements the things we need to talk to and manipulate
    heartbeat clusters
    '''

    def __init__(self, Environment, randseed=None):

        self.ResourceDirs = ["/etc/ha.d/resource.d", "/etc/rc.d/init.d", "/etc/rc.d/"]
        self.ResourceFile = Environment["HAdir"] + "/haresources"
        self.ConfigFile = Environment["HAdir"]+ "/ha.cf"
        ClusterManager.__init__(self, Environment, randseed=randseed)
        self.update({
            "Name"           : "heartbeat",
            "DeadTime"       : 30,
            "StableTime"     : 30,
            "StartCmd"       : "/usr/lib/heartbeat/ha_logd -d >/dev/null 2>&1; MALLOC_CHECK_=2 /usr/lib/heartbeat/heartbeat >/dev/null 2>&1",
            "StopCmd"        : "/usr/lib/heartbeat/heartbeat -k",
            "StatusCmd"      : "/usr/lib/heartbeat/heartbeat -s",
            "RereadCmd"      : "/usr/lib/heartbeat/heartbeat -r",
            "StartDRBDCmd"   : "/etc/init.d/drbd start >/dev/null 2>&1",
            "StopDRBDCmd"    : "/etc/init.d/drbd stop",
            "StatusDRBDCmd"  : "/etc/init.d/drbd status",
            "DRBDCheckconf"  : "/etc/init.d/drbd checkconfig >/var/run/drbdconf 2>&1",
            "BreakCommCmd"   : "/usr/share/heartbeat/TestHeartbeatComm break-communication >/dev/null 2>&1",
            "FixCommCmd"     : "/usr/share/heartbeat/TestHeartbeatComm fix-communication >/dev/null 2>&1",
            "DelFileCommCmd" : "/usr/share/heartbeat/TestHeartbeatComm delete-testingfile >/dev/null 2>&1",
            "SaveFileCmd"    : "/usr/share/heartbeat/TestHeartbeatComm save-testingfile /tmp/OnlyForTesting >/dev/null 2>&1",
            "ReduceCommCmd"  : "/usr/share/heartbeat/TestHeartbeatComm reduce-communication %s %s>/dev/null 2>&1",
            "RestoreCommCmd" : "/usr/share/heartbeat/TestHeartbeatComm restore-communication /tmp/OnlyForTesting >/dev/null 2>&1",
            "IPaddrCmd"      : "/etc/ha.d/resource.d/IPaddr %s status",
            "Standby"        : "/usr/share/heartbeat/hb_standby >/dev/null 2>&1",
            "TestConfigDir"  : "/etc/ha.d/testconfigs",
            "LogFileName"    : Environment["LogFileName"],

            # Patterns to look for in the log files for various occasions...
            "Pat:We_started"       : " (%s) .* Initial resource acquisition complete",
            "Pat:They_started"     : " (%s) .* Initial resource acquisition complete",
            "Pat:We_stopped"       : "%s heartbeat.*Heartbeat shutdown complete",
            "Pat:Logd_stopped"     : "%s logd:.*Exiting write process",
            "Pat:They_stopped"     : "%s heartbeat.*node (%s).*: is dead",
            "Pat:They_dead"        : "node (%s).*: is dead",
            "Pat:All_stopped"      : " (%s).*heartbeat.*Heartbeat shutdown complete",
            "Pat:StandbyOK"        : "Standby resource acquisition done",
            "Pat:StandbyNONE"      : "No reply to standby request",
            "Pat:StandbyTRANSIENT" : "standby message.*ignored.*in flux",
            "Pat:Return_partition" : "Cluster node %s returning after partition",

            # Bad news Regexes.  Should never occur.
            "BadRegexes"   : (
                r"Shutting down\.",
                     r"Forcing shutdown\.",
                     r"Both machines own .* resources!",
                     r"No one owns .* resources!",
                     r", exiting\.",
                     r"ERROR:",
                     r"CRIT.*:",
            ),
        })
        
        self.cf=HBConfig(Environment["HAdir"])
        self._finalConditions()

    def SetClusterConfig(self, configpath="default", nodelist=None):
        '''Activate the named test configuration throughout the cluster.
        This code is specialized to heartbeat.
        '''
        rc=1
        Command='''
        cd %s%s%s;                : cd to test configuration directory
        for j in *
        do
          if
            [ -f "/etc/ha.d/$j" ];
          then
            if
              cmp $j /etc/ha.d/$j >/dev/null 2>&1;
            then
              : Config file $j is already up to correct.
            else
              echo "Touching $j"
              cp $j /etc/ha.d/$j
            fi
          fi
        done
        ''' % (self["TestConfigDir"], os.sep, configpath)

        if nodelist == None:
            nodelist=self.Env["nodes"]
        for node in nodelist:
            if not self.rsh(node, Command): rc=None

        self.rereadall()
        return rc


    def ResourceGroups(self):
        '''
        Return the list of resources groups defined in this configuration.

        This code is specialized to heartbeat.
        We make the assumption that the resource file on the local machine
        is the same as that of a cluster member.

        We aren't necessarily a member of the cluster
        (In fact, we usually aren't).
        '''
        RscGroups=[]
        file = open(self.ResourceFile, "r")
        while (1):

            line = file.readline()
            if line == "":   break

            idx=string.find(line, '#')
            if idx >= 0:
                line=line[:idx]
            if line == "":    continue
            line = string.strip(line)

            # Is this wrong?
            tokens = re.split("[ \t]+", line)

            # Ignore the default server for this resource group
            del tokens[0]

            Group=[]
            for token in tokens:
                if token != "":
                    idx=string.find(token, "::")
                    if idx > 0:
                        tuple=string.split(token, "::")
                    else:
                        #
                        # Is this an IPaddr default resource type?
                        #
                        if re.match("^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$"
                        ,        token):
                            tuple=["IPaddr", token]
                        else:
                            tuple = [token, None]
                    Resource = self.hbResource(tuple[0], tuple[1])
                    Group.append(Resource)

            RscGroups.append(Group)
            
        file.close()
        return RscGroups

    def InternalCommConfig(self):
        '''
        Return a list of communication  paths. Each path consists of a tuple like this:
               mediatype                serial | ip
               interface/dev name       eth0 | /dev/ttyS0...
               protocol                 tcp?? | udp | None 
               port                     Number | None
        '''

        Path = {"mediatype" : None, "interface": None, "protocol" : None, "port": None}
        cf = self.cf
        for cfp in cf.Parameters:
            if cfp == "serial":
                if Path["mediatype"] == None:
                     Path["mediatype"] = ["serial"]
                else: Path["mediatype"].append("serial")

                if Path["interface"] == None:
                     Path["interface"] = cf.Parameters["serial"]
                else:
                    for serial in cf.Parameters["serial"]:
                         Path["interface"].append(serial)

            if cfp == "bcast" or cfp == "mcast" or cfp == "ucast" :
                if Path["mediatype"] == None:
                    Path["mediatype"] = ["ip"]
                else: Path["mediatype"].append("ip")

                if cfp == "bcast":
                    interfaces = cf.Parameters[cfp]
                if cfp == "ucast":
                    interfaces = [cf.Parameters[cfp][0]]
                if cfp == "mcast":
                    Path["port"] = [cf.Parameters[cfp][0][2]]
                    Path["protocol"] = "udp"
                    interfaces = [cf.Parameters[cfp][0][0]]

                if Path["interface"] == None:
                   Path["interface"] = interfaces
                else:
                    for interface in interfaces:
                        if interface not in Path["interface"]:
                            Path["interface"].append(interface)

            if cfp == "udpport":
                Path["port"] = cf.Parameters["udpport"]
                Path["protocol"] = ["udp"]

            if Path["port"] == None:
                Path["port"] = [694]

        return Path
                
    def HasQuorum(self, node_list):
        (
'''Return TRUE if the cluster currently has quorum.  According to
current heartbeat code this means one node is up.
''')
        return self.upcount() >= 1

    def hbResource(self, type, instance):
        '''
        Our job is to create the right kind of resource.  For most
        resources, we just create an HBResource object, but for
        IP addresses, we create an HBipResource instead.
        Some other types of resources may also be added as special
        cases.
        '''

        if type == "IPaddr":
            return HBipResource(self, type, instance)

        return HBResource(self, type, instance)


class HBResource(Resource):

    def IsRunningOn(self, nodename):
        '''
        This member function returns true if our resource is running
        on the given node in the cluster.
        We call the status operation for the resource script.
        '''

        return self._ResourceOperation("status", "OK|running", nodename)

    def _ResourceOperation(self, operation, pattern, nodename):
        '''
        We call the requested operation for the resource script.
        We don't care what kind of operation we were called to do
        particularly.
        When we were created, we were bound to a cluster manager, which
        has its own remote execution method (which we use here).
        '''
        if self.Instance == None:
            instance = ""
        else:
            instance = self.Instance

        Rlist = 'LIST="'
        for dir in self.CM.ResourceDirs:
          Rlist = Rlist + " " + dir
        Rlist = Rlist + '"; '

        Script= Rlist + '''
        T="''' + self.ResourceType + '''";
        I="''' + instance + '''";
        for dir in $LIST;
        do
          if
            [ -f "$dir/$T" -a  -x "$dir/$T" ]
          then
            "$dir/$T" $I ''' + operation + '''
            exit $?
          fi
        done 2>&1;
        exit 1;'''

        #print "Running " + Script + "\n"

        line = self.CM.rsh.readaline(nodename, Script)
        if operation == "status":
          if re.search(pattern, line):
              return 1
        return self.CM.rsh.lastrc == 0

    def Start(self, nodename):
        '''
        This member function starts or activates the resource.
        '''
        return self._ResourceOperation("start", None, nodename)

    def Stop(self, nodename):
        '''
        This member function stops or deactivates the resource.
        '''
        return self._ResourceOperation("stop", None, nodename)

        
#    def IsWorkingCorrectly(self, nodename):
#        "We default to returning TRUE for this one..."
#        if self.Instance == None:
#          self.CM.log("Faking out: " + self.ResourceType)
#        else:
#          self.CM.log("Faking out: " + self.ResourceType + self.Instance)
#        return 1

    def IsWorkingCorrectly(self, nodename):
        return self._ResourceOperation("monitor", "OK", nodename)

class HBipResource(HBResource):
    '''
    We are a specialized IP address resource which knows how to test
    to see if our resource type is actually being served.
    We are cheat and run the IPaddr resource script on
    the current machine, because it's a more interesting case.
    '''

    def IsWorkingCorrectly(self, nodename):
        return self._ResourceOperation("monitor", "OK", self.CM.OurNode)



#
#        A heartbeat configuration class...
#        It reads and parses the heartbeat config
#        files
#

class HBConfig:

    # Which options have multiple words on the line?
    MultiTokenKeywords = {"mcast" : None , "stonith_host": None}

    def __init__(self, configdir="/etc/ha.d"):
        self.Parameters = {}
        self.ResourceGroups = {}

        self._ReadConfig(os.path.join(configdir, "ha.cf"))
        
        FirstUp_NodeSelection()
        LastUp_NodeSelection()
        no_failback = NoAutoFailbackPolicy()
        auto_failback = AutoFailbackPolicy()

        #
        # We allow each resource group to have its own failover/back
        # policies
        #
        if self.Parameters.has_key("nice_failback")         \
        and                self.Parameters["nice_failback"] == "on":
            HBConfig.DefaultFailbackPolicy = no_failback
        elif self.Parameters.has_key("auto_failback")         \
        and                self.Parameters["auto_failback"] == "off":
            HBConfig.DefaultFailbackPolicy = no_failback
        else:
            HBConfig.DefaultFailbackPolicy = auto_failback
        HBConfig.DefaultNodeSelectionPolicy = NodeSelectionPolicies["FirstUp"]

        self._ReadResourceGroups(os.path.join(configdir, "haresources"))

    # Read ha.cf config file
    def _ReadConfig(self, ConfigFile):
        self.ConfigPath = ConfigFile;
        fp = open(ConfigFile)

        while 1:
            line=fp.readline()
            if not line:
                return
            line = re.sub("#.*", "", line)
            line = string.rstrip(line)
            if len(line) < 1:
                continue
            tokens = line.split()
            key = tokens[0]
            values = tokens[1:]

            if HBConfig.MultiTokenKeywords.has_key(key):
                # group items from this line together, and separate
                # from the items on other lines
                values = [values]
            if self.Parameters.has_key(key):
                if key == "node":
                    self.Parameters[key].extend(values)
                else:
                    self.Parameters[key].append(values[0])
            else:
                self.Parameters[key] = values

    # Read a line from the haresources file...
    # - allow for \ continuations...
    def _GetRscLine(self, fp):
        linesofar = None
        continuation=1
        while continuation:
            continuation = 0
            line=fp.readline()
            if not line:
                break
            line = re.sub("#.*", "", line)

            if line[len(line)-2] == "\\":
               line = line[0:len(line)-2] + "\n"
               continuation=1

            if linesofar == None:
                linesofar = line
            else:
                linesofar = linesofar + line
        return linesofar


    def _ReadResourceGroups(self, RscFile):
        self.RscPath = RscFile;
        fp = open(RscFile)

        thisline = ""
        while 1:
            line=self._GetRscLine(fp)
            if not line:
                return
            line = line.strip()
            if len(line) < 1:
                continue
            tokens = line.split()
            node = tokens[0]
            resources = tokens[1:]
            rscargs=[]
            for resource in resources:
                name=resource.split("::", 1)
                if len(name) > 1:
                    args=name[1].split("::")
                else:
                    args=None
                name = name[0]
                rscargs.append(Resource(name, args))
            name = tokens[0] + "__" + tokens[1]

            assert not self.ResourceGroups.has_key(name)

            #
            #        Create the resource group
            #
            self.ResourceGroups[name] = ResourceGroup(name \
            ,        rscargs
            ,        node.split(",")
                # Provide default value
            ,        HBConfig.DefaultNodeSelectionPolicy
            ,        HBConfig.DefaultFailbackPolicy)
#
#        Return the list of nodes in the cluster...
#

    def nodes(self):
        result = self.Parameters["node"]
        result.sort()
        return result

class ClusterState:
    pass

class ResourceGroup:
    def __init__(self, name, resourcelist, possiblenodes
    ,        nodeselection_policy, failback_policy):
        self.name = name
        self.resourcelist = resourcelist
        self.possiblenodes = possiblenodes
        self.nodeselection_policy = nodeselection_policy
        self.failback_policy = failback_policy
        self.state = None
        self.attributes = {}
        self.history = []

    def __str__(self):
        result = string.join(self.possiblenodes, ",")
        for rsc in self.resourcelist:
            result = result + " " + str(rsc)
        return result

class Resource:
    def __init__(self, name, arguments=None):
        self.name = name
        self.arguments = arguments

    def __str__(self):
        result = self.name
        try:
            for arg in self.arguments:
                result = result + "::" + arg
        except TypeError:
            pass
        return result


#######################################################################
#
#        Base class defining policies for where we put resources
#        when we're starting, or when a failure has occurred...
#
#######################################################################
NodeSelectionPolicies = {}

class NodeSelectionPolicy:
    def __init__(self, name):
        self.name = name
        NodeSelectionPolicies[name] = self

    def name(self):
        return self.name

#
#        nodenames: the list of nodes eligible to run this resource
#        ResourceGroup:        the group to be started...
#        ClusterState:        Cluster state information
#
    def SelectNode(self, nodenames, ResourceGroup, ClusterState):
        return None

#
#        Choose the first node in the list...
#
class FirstUp_NodeSelection(NodeSelectionPolicy):
    def __init__(self):
        NodeSelectionPolicy.__init__(self, "FirstUp")

    def SelectNode(self, nodenames, ResourceGroup, ClusterState):
        return nodenames[0]

#
#        Choose the last node in the list...
#        (kind of a dumb example)
#
class LastUp_NodeSelection(NodeSelectionPolicy):
    def __init__(self):
        NodeSelectionPolicy.__init__(self, "LastUp")

    def SelectNode(self, nodenames, ResourceGroup, ClusterState):
        return nodenames[len(nodenames)-1]

#######################################################################
#
#        Failback policies...
#
#        Where to locate a resource group when an eligible node rejoins
#        the cluster...
#
#######################################################################
FailbackPolicies = {}

class FailbackPolicy:
    def __init__(self, name):
        self.name = name
        FailbackPolicies[name] = self

    def name(self):
        return self.name

        #
        # currentnode:  The node the service is currently on
        # returningnode:  The node which just rejoined
        # eligiblenodes:  Permitted nodes which are up
        # SelectionPolicy:  the normal NodeSelectionPolicy
        # Cluster state information...
        #
    def SelectNewNode(self, currentnode, returningnode, eligiblenodes
    ,                SelectionPolicy, ResourceGroup, ClusterState):
        return None

#
#        This FailbackPolicy is like "normal failback" in heartbeat
#
class AutoFailbackPolicy(FailbackPolicy):
    def __init__(self):
        FailbackPolicy.__init__(self, "failback")

    def SelectNewNode(self, currentnode, returningnode, eligiblenodes
    ,                SelectionPolicy, ResourceGroup, ClusterState):

        # Select where it should run based on current normal policy
        # just as though we were starting it for the first time.

        return SelectionPolicy(eligiblenodes, ResourceGroup, ClusterState)
#
#        This FailbackPolicy is like "nice failback" in heartbeat
#
class NoAutoFailbackPolicy(FailbackPolicy):
    def __init__(self):
        FailbackPolicy.__init__(self, "failuresonly")

    def SelectNewNode(self, currentnode, returningnode, eligiblenodes
    ,                SelectionPolicy, ResourceGroup):

        # Always leave the resource where it is...

        return currentnode


#######################################################################
#
#   A little test code...
#
#   Which you are advised to completely ignore...
#
#######################################################################
if __name__ == '__main__': 
        FirstUp_NodeSelection()
        LastUp_NodeSelection()

        no_failback = NoAutoFailbackPolicy()
        auto_failback = AutoFailbackPolicy()
        

        cf=HBConfig("/etc/ha.d")


        print "Cluster configuration:\n"

        print "Nodes:", cf.nodes(), "\n"
        print "Config Parameters:", cf.Parameters, "\n"

        for groupname in cf.ResourceGroups.keys():
            print "Resource Group %s:\n\t%s\n" % (groupname, cf.ResourceGroups[groupname])