summaryrefslogtreecommitdiff
path: root/devtools/flocktest
blob: 286cb7586631ca48ab1ca3a9282597ccaf223214 (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
#!/usr/bin/env python
#
"""\
flocktest - shepherd script for the GPSD test flock

usage: flocktest [-d subdir] [-k key] -v [-x exclude] [-?]

The -? makes flocktest prints this help and exits.

The -k mode installs a specified ssh public key an all machines

Otherwise, the remote flockdriver script is executed on each machine.

The -d option passes it a name for the remote test subdirectory

The -v option shows all ssh commands issued and runs flockdriver with -x set.

The -x option specifies a comma-separated list of items that are
either remote hostnames or architecture tags.  Matching sites are
excluded.  You may wish to use this to avoid doing remote tests that
are redundant with your local ones.

If you have a .flocktest file, it is interpreted as a set of
attribute/value pairs, one per line separated by '='.  The following
attributes are recognized:

subdir = a default test directory name (-d)
exclude = a default exclusion set (-x)

If you do not specify a subdirectory name either with -d or in the
.flocktest file, the value of $LOGNAME will be used.
"""

import os, sys, ConfigParser, getopt, socket, threading, commands

flockdriver = '''
#!/bin/sh
#
# flockdriver - conduct regression tests as an agent for a remote flocktest
#
# usage: flockdriver -d subdir
#
# The -d argument must be a subdirectory name
#
#  This will perform the following steps:
#
#  * If required, create the origin repo in a directory named after 
#     you beneath the test account home,
#
#   * git pull and build in that repo.
#
#   * make check, capturing the output
#
#   * Notify the project channel of success or failure via CIA
#
#   * mail the output back to you if the test failed.
#

# Project-specific configuration
project=%(project)s
origin=%(origin)s
generator="http://gpsd.berlios.de/flockdriver"

# No project-specific stuff below this line

while getopts d opt
do
    case $opt in
        d) subdir=$2; shift; shift ;;
    esac
done

site=`hostname --fqdn`

if [ -f "flockdriver.lock" ]
then
    logmessage="A test was already running when you initiated this one."
    cd $subdir
    mailback=no
else
    (
	echo "Test begins: "`date`

	echo "Site: $site" 
	echo "Directory: ${PWD}/${subdir}"
    ) >"flockdriver-${subdir}.log"

    # Set up or update the repo
    if [ ! -d $subdir ]
    then
	git clone $origin $subdir >>"flockdriver-${subdir}.log" 2>&1
	cd $subdir
    else
	cd $subdir; git pull >>"../flockdriver-${subdir}.log" 2>&1
    fi

    # Perform the test
    if ( %(regression)s ) >>"../flockdriver-${subdir}.log" 2>&1
    then
	logmessage="Regression test succeeded."
	status=0
    else
	logmessage="Regression test failed."
	status=1
    fi

    echo "Test ends: "`date` >>"../flockdriver-${subdir}.log" 2>&1
    mv "../flockdriver-${subdir}.log" TEST.LOG
fi

# Here is where we abuse CIA to do our notfications for us.

# Addresses for the e-mail
from="FLOCKDRIVER-NOREPLY@${site}"
to="cia@cia.navi.cx"

# SMTP client to use
sendmail="sendmail -t -f ${from}"

# Should include all places sendmail is likely to lurk. 
PATH="$PATH:/usr/sbin/"

# Identify what just succeeded or failed
merged=$(git rev-parse HEAD)
rev=$(git describe ${merged} 2>/dev/null)
[ -z ${rev} ] && rev=${merged}
refname=$(git symbolic-ref HEAD 2>/dev/null)
refname=${refname##refs/heads/}

# And the git version
gitver=$(git --version)
gitver=${gitver##* }

${sendmail} << EOM
Message-ID: <${merged}.${subdir}.blip@${project}>
From: ${from}
To: ${to}
Content-type: text/xml
Subject: DeliverXML

<message>
  <generator>
    <name>${project} Remote Test Flock Driver</name>
    <version>${gitver}</version>
    <url>${generator}</url>
  </generator>
  <source>
    <project>${project}</project>
    <branch>${refname}@${site}</branch>
  </source>
  <timestamp>`date`</timestamp>
  <body>
    <commit>
      <author>${subdir}</author>
      <revision>${rev}</revision>
      <log>${logmessage}</log>
    </commit>
  </body>
</message>
EOM

exit $status
# End.
'''

class FlockThread(threading.Thread):
    def __init__(self, site, command):
        threading.Thread.__init__(self)
        self.site = site
        self.command = command
    def run(self):
        (self.status, self.output) = commands.getstatusoutput(self.command)

class TestSite:
    "Methods for performing tests on a single remote site."
    def __init__(self, fqdn, config, execute=True):
        self.fqdn = fqdn
        self.config = config
        self.execute = execute
        self.me = self.config["login"] + "@" + self.fqdn
    def error(self, msg):
        "Report an error while executing a remote command."
        sys.stderr.write("%s: %s\n" % (self.fqdn, msg))
    def do_remote(self, remote):
        "Execute a command on a specified remote host."
        command = "ssh "
        if "port" in self.config:
            command += "-p %s " % self.config["port"]
        command += "%s '%s'" %  (self.me, remote)
        if self.verbose:
            print command
        current =  FlockThread(self, command)
        current.start()
        return current
    def update_remote(self, filename):
        "Copy a specified file to the remote home."
        command = "scp %s %s:~" % (filename, self.me)
        if self.verbose:
            print command
        status = os.system(command)
        if status:
            self.error("copy with '%s' failed" % command)
        return status
    def do_append(self, filename, string):
        "Append a line to a specified remote file, in foreground."
        self.do_remote("echo \"%s\" >>%s" % (string.strip(), filename))
    def do_flockdriver(self):
        "Copy flockdriver to the remote site and run it."
        ofp = os.popen("ssh -p %s %s 'cat >flockdriver.%s'" \
                       % (self.config.get("port", "22"), self.me, subdir),
                       "w")
        ofp.write(flockdriver % self.config)
        if ofp.close():
            # FIXME: Error handling is unsatisfactory if this failes
            print >>sys.stderr, "flocktest: flockdriver copy failed"
        else:
            command = "sh flockdriver.%s -d %s" % (subdir, subdir,)
            if self.verbose > 1:
                command = "sh -x " + command
            return self.do_remote(command)

class TestFlock:
    "Methods for performing parallel tests on a flock of remote sites."
    ssh_options = "no-port-forwarding,no-X11-forwarding," \
                 "no-agent-forwarding,no-pty "
    def __init__(self, sitelist):
        self.sitelist = sitelist
    def update_remote(self, filename):
        "Copy a specified file to the remote home on all machines."
        for site in self.sitelist:
            site.update_remote(filename)
    def do_remotes(self):
        "Execute a command on all machines in the flock."
        slaves = []
        for site in self.sitelist:
            slaves.append(site.do_flockdriver())
        for slave in slaves:
            slave.join()
        for slave in slaves:
            print "From %s:" % slave.site.fqdn
            print "Status:", slave.status
            if slave.status:
                print slave.output
    def exclude(self, exclusions):
        "Delete matching sites."
        self.sitelist = filter(lambda x: x.fqdn not in exclusions and x.config["arch"] not in exclusions, self.sitelist)
    def add_key(self, key):
        "Add the specified public key to all sites."
        for site in self.sitelist:
            site.do_append(".ssh/authorized_keys",
                           TestFlock.ssh_options + " " + key)
    def listdump(self):
        "Return a dump of the site list."
        return ", ".join(map(lambda x: x.fqdn, self.sitelist))

if __name__ == '__main__':
    try:
        (options, arguments) = getopt.getopt(sys.argv[1:], "dk:vx:?")
    except getopt.GetoptError, msg:
        print "flocktest: " + str(msg)
        raise SystemExit, 1

    exclusions = []
    subdir = None
    key = None
    verbose = False
    for (switch, val) in options:
        if  switch == 'd':
            subdir = val
        elif  switch == '-k':
            key = val
        elif  switch == '-N':
            execute = False
        elif switch == '-v':
            verbose = True
        elif switch == '-x':
            exclusions = map(lambda x: x.strip(), val.split(","))
        else: # switch == '-?':
            print __doc__
            sys.exit(0)

    config = ConfigParser.RawConfigParser()
    config.read(["flock-sites.ini"])
    sites = []
    for site in config.sections():
        newsite = TestSite(site, dict(config.items(site)))
        newsite.verbose = verbose
        if newsite.config["status"].lower() == "up":
            sites.append(newsite)
    flock = TestFlock(sites)

    controls = {}
    try:
        myconfig = open(".flocktest")
        controls = dict(map(lambda x: map(lambda y: y.strip(), x.split("=")), myconfig.readlines()))
    except IOError:
        pass

    if exclusions:
        flock.exclude(exclusions)
    elif 'exclude' in controls:
        flock.exclude(controls.get('exclude'))

    if key:
        flock.add_key(val)
    else:
        if subdir:
            pass
        elif 'subdir' in controls:
            subdir = controls.get('subdir')
        else:
            subdir = sys.getenv("LOGNAME")
        if not subdir:
            print "flocktest: you don't exist, go away!"
            sys.exit(1)
        print "Testing at", flock.listdump()
        flock.do_remotes()

# The following sets edit modes for GNU EMACS
# Local Variables:
# mode:python
# End: