summaryrefslogtreecommitdiffstats
path: root/puppet/sync_and_run.pl
blob: 6ae9c2145164e8bb7dfe73aeb0069ecf32c23b53 (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
#!/usr/bin/env perl
#############################################################################
##
## Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
## Contact: http://www.qt-project.org/legal
##
## This file is part of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:LGPL$
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and Digia.  For licensing terms and
## conditions see http://qt.digia.com/licensing.  For further information
## use the contact form at http://qt.digia.com/contact-us.
##
## GNU Lesser General Public License Usage
## Alternatively, this file may be used under the terms of the GNU Lesser
## General Public License version 2.1 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU Lesser General Public License version 2.1 requirements
## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
##
## In addition, as a special exception, Digia gives you certain additional
## rights.  These rights are described in the Digia Qt LGPL Exception
## version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 3.0 as published by the Free Software
## Foundation and appearing in the file LICENSE.GPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU General Public License version 3.0 requirements will be
## met: http://www.gnu.org/copyleft/gpl.html.
##
##
## $QT_END_LICENSE$
##
#############################################################################

package QtQA::Puppet::SyncAndRun;
use strict;
use warnings;

# This script syncs this repo to latest and does a single puppet run.
# Intended to be used from a cron job.
#
# Important: do not use non-core perl modules here!
# Most things listed in "perldoc perlmodlib" should be safe.

use Carp;
use Cwd qw( abs_path );
use English qw( -no_match_vars );
use File::Path qw( mkpath );
use File::Spec::Functions;
use File::stat;
use FindBin;
use Getopt::Long;
use IO::Socket::INET;
use Time::Piece;
use Time::Seconds;
use POSIX;

if ($^O =~ m/mswin32/i) {
    require Win32::Process;
    Win32::Process->import;
}

# export a few things so that autotests can find and run puppet without
# duplicating our code
use parent 'Exporter';
our @EXPORT = qw(
    find_puppet
);

$SIG{'INT'} = sub { END };

my $LOCKFILE = "./sync_and_run.lck";
my $LOCKFILEHANDLE;
my $SECOND_INSTANCE = 0;
my $MAXLOCKOUTTIME = 90;

our $DIR = abs_path( $FindBin::Bin );
our $CACHEDIR = catfile( $DIR, 'cache' );
our $WINDOWS = ($OSNAME =~ m{win32}i);

# Avoid any usage of the git_mirror.pl from within puppet
local $ENV{ HARDGIT_SKIP } = 1;

sub create_lockfile {
    my $lockf = shift;

    if (-e $lockf) {
        my $fs = stat ($lockf);
        my $locktime = (localtime) - (localtime $fs->mtime());
        open ($LOCKFILEHANDLE,"<$lockf") or die "Unable to open file $lockf: $!\n";
        my $runpid = <$LOCKFILEHANDLE>;

        if ($locktime->minutes > $MAXLOCKOUTTIME) {
            print "$lockf in place, but it's modification time exceeds "
                 ."\$MAXLOCKOUTTIME. Killing process and removing lock.\n";
            if ($^O =~ m/mswin32/i) {
                my $exitcode = 0;
                Win32::Process::KillProcess($runpid, $exitcode);
                print "Process terminated with exitcode \"$exitcode\"\n";
            } else {
                my $cnt = kill (-9, $runpid);
                print "Signal sent to $cnt process(es)\n";
            }
            #remove lock file after process has been killed
            unlink ($lockf);
        } else {
            print "Already running (PID: $runpid).\n";
            $SECOND_INSTANCE = 1;
            exit 1;
        }
    }
    open ($LOCKFILEHANDLE, ">$lockf") or die "Unable to open file $lockf: $!\n";
    print $LOCKFILEHANDLE $$;
    close $LOCKFILEHANDLE;
}

sub chdir_or_die
{
    my ($dir) = @_;

    chdir( $dir ) || die "chdir $dir: $!";

    return;
}

sub system_or_carp
{
    my (@cmd) = @_;

    system( @cmd );
    if ($? != 0) {
        carp "system @cmd: $?";
    }

    return;
}

# Prints --help message and exits.
sub usage
{
    warn <<'END_USAGE';
Usage: sync_and_run.pl [OPTIONS]

Update sysadmin repository and run puppet.

Options:

  --help                        Print this help.

  --facts-from-reverse-dns      Override some facter facts according to the results of a reverse
                                DNS lookup on the current host.

                                This is a workaround for systems whose local idea of their FQDN
                                do not match reality (for example, Windows systems who don't set
                                their hostname via DHCP).

                                To improve reliability, the reverse DNS lookup results are cached
                                on disk.  If the lookup fails for any reason, the values from
                                cache are used instead.

                                At least the 'hostname', 'domain' and 'fqdn' facts are affected
                                by this option.

END_USAGE

    exit 2;
}

# Returns the "primary" IP address of this machine, where "primary"
# means the IP address used for outgoing connections to a world-accessible
# host.
# Dies on error.
sub find_primary_ip
{
    # This may be any host with a high likelihood of never going away.
    # 8.8.8.8:53 == Google Public DNS
    my $remotehost = '8.8.8.8';
    my $remoteport = 53;

    my $socket = IO::Socket::INET->new(
        PeerAddr => $remotehost,
        PeerPort => $remoteport,
        Proto => 'tcp',
    );
    if (!$socket) {
        die "connect to $remotehost:$remoteport: $!";
    }

    return $socket->sockhost( );
}

# Returns the "primary" FQDN for this machine, meaning the FQDN
# according to a reverse DNS lookup of the return value of find_primary_ip().
# This function invokes the "nslookup" utility.
# Dies on error.
sub find_primary_fqdn
{
    my ($ip) = find_primary_ip( );

    my $output = qx(nslookup $ip 2>&1);
    if ($? != 0) {
        die "nslookup failed: $?\noutput: $output\n";
    }

    my $name;
    while (
        $output =~ m{
            (?:
                # unix style
                # 113.136.30.172.in-addr.arpa     name = bq-menoetius.example.com.
                \Qin-addr.arpa\E
                \s+
                name
                \s*
                =
                \s*
                (?<name>[^\s]+)
                \.
                \s
            )
            |
            (?:
                # windows style
                # Name:    bq-menoetius.example.com
                Name:
                \s+
                (?<name>[^\s]+)
                \s
            )
        }xmsg
    ) {
        $name = $+{ name };
    }

    if (!$name) {
        die "fqdn not found by reverse dns. nslookup output:\n$output\n";
    }

    return $name;
}

# Returns a cached value for $key.
# Dies on error or if there is no cached value.
sub cached
{
    my ($key) = @_;
    my $cachefile = catfile( $CACHEDIR, $key );
    open( my $fh, '<', $cachefile ) || die "open $cachefile: $!";

    my $value = <$fh>;
    chomp $value;

    $value || die "$cachefile is empty";

    return $value;
}

# Writes $value to the on-disk cache, under the given $key.
# Dies on error.
sub write_cache
{
    my ($key, $value) = @_;

    if (! -d $CACHEDIR) {
        mkpath( $CACHEDIR );
    }

    my $cachefile = catfile( $CACHEDIR, $key );
    open( my $fh, '>', $cachefile ) || die "open $cachefile for write: $!";
    print $fh "$value\n";

    return;
}

# Returns a value either from $sub_ref->(), or from the cache
# entry for $key.
#
# If $sub_ref succeeds, the calculated value is written to the cache.
# Otherwise, a warning is printed and the value is read from the cache.
#
# Dies if $sub_ref fails and reading from the cache also fails.
sub get_cacheable_value
{
    my ($key, $sub_ref) = @_;

    my $value;

    eval {
        $value = $sub_ref->();
    };

    my $error;
    if (!($error = $@)) {
        eval {
            write_cache( $key, $value );
        };
        if (my $error = $@) {
            warn "while writing $key to cache: $error\n";
        }
        return $value;
    }

    warn "$error\nTrying to use cached $key...\n";

    return cached( $key );
}

# Writes some values to the hashref $env which, if set in the system environment,
# will override some facter facts according to the values returned by a reverse
# DNS lookup.
#
# This is a workaround for machines whose local set hostname and/or domain name
# can't be trusted.  Notably, most Windows machines fall into this category,
# because they generally don't set their hostname via DHCP and may also be
# limited to a host name with max length of 15 characters (for NetBIOS).
sub modify_env_from_rdns
{
    my ($env) = @_;

    my $fqdn;
    eval {
        $fqdn = get_cacheable_value( 'fqdn', \&find_primary_fqdn );
    };
    if (my $error = $@) {
        warn "$error\nWarning: could not set environment from reverse DNS!\n";
        return;
    }

    # 'bq-menoetius.example.com' => ('bq-menoetius', 'example.com')
    my ($hostname, $domain) = split( /\./, $fqdn, 2 );

    $env->{ FACTER_hostname } = $hostname;
    $env->{ FACTER_domain } = $domain;
    # No need to set FACTER_fqdn, it is calculated from the above two

    return;
}

sub update_git_dir
{
    my ($gitdir) = @_;

    return unless (-d $gitdir);

    chdir_or_die( $gitdir );

    # If our git repo has somehow become out of sync, these commands will warn about it.
    # Note that we warn, instead of dying, because puppet should still run if at all possible
    # (e.g. puppet should still run if the git server is down).
    system_or_carp( qw(git pull) );
    system_or_carp( qw(git --no-pager diff) );

    chdir_or_die( $DIR );

    return;
}

sub find_puppet
{
    return 'puppet' unless $WINDOWS;

    foreach my $key ('ProgramFiles', 'ProgramFiles(x86)') {
        my $path = $ENV{ $key };
        next unless $path;

        my $candidate = "$path\\Puppet Labs\\Puppet\\bin\\puppet.bat";
        if (-f $candidate) {
            return $candidate;
        }
    }

    return 'puppet';
}

sub run_and_exit
{
    my (@cmd) = @_;

    print (+ @cmd);
    system( @cmd );
    exit $?;
}

sub determine_puppet_version
{
    my ($puppet_bin) = @_;
    my $puppet_version_string = qx("$puppet_bin" "--version");
    if ($? != 0) {
        die "'$puppet_bin --version' failed\n";
    }
    $puppet_version_string =~ /(\d)\.(\d)\.(\d+)/;

    my $puppet_version = {
        major => $1,
        minor => $2,
        build => $3,
    };

    return $puppet_version;
}

sub run_puppet
{
    my @puppet_command = (
        find_puppet( ),
    );

    my $version = determine_puppet_version(@puppet_command);
    if ($version->{major} >= 3 || $version->{major} >= 2 && $version->{minor} >= 6) {
        push @puppet_command, (
            # 'apply' is the command we want; we just don't use it always because
            # we still have some very old puppet installations which don't support it.
            'apply'
        );
    }

    if ($WINDOWS) {
        push @puppet_command, (
            # On Windows, we need to use a separate config file
            '--config', "$DIR/puppet-win32.conf"
        );
    } else {
        push @puppet_command, (
            '--logdest', 'syslog',
        );
    }

    push @puppet_command, (
        '--confdir', $DIR,
        "$DIR/manifests/site.pp",
    );

    run_and_exit( @puppet_command );

    return;
}

sub run_takeown
{
    # Use the takeown command to ensure the current user has rights to the puppet
    # directory (on Windows).
    #
    # Errors are not fatal.
    #
    system( qw(takeown /F . /R /D Y) );

    return;
}

sub run
{
    chdir_or_die( $DIR );

    create_lockfile ($LOCKFILE);

    if (-f 'disable_puppet') {
        print "not doing anything because $DIR/disable_puppet exists\n";
        return;
    }

    if ($WINDOWS) {
        run_takeown( );
    }

    my $facts_from_reverse_dns = 0;
    GetOptions(
        'facts-from-reverse-dns' => \$facts_from_reverse_dns,
        'help|h|?' => \&usage,
    );

    local %ENV = %ENV;
    if ($facts_from_reverse_dns) {
        modify_env_from_rdns( \%ENV );
    }

    update_git_dir( $DIR );

    run_puppet( );

    return;
}

run( ) unless caller;

END {
    unlink $LOCKFILE if (!$SECOND_INSTANCE);
}
1;