summaryrefslogtreecommitdiffstats
path: root/regressions/test-launch-race.pl
blob: 892353e143ad226400be05c3bea3fab3fabb4b37 (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
#!/usr/bin/perl
# Copyright (C) 2010 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., 675 Mass Ave, Cambridge, MA 02139, USA.

# Test that 2 simultaneous launches in a clean cache directory will both succeed

use strict;
use warnings;

use File::Temp qw(tempdir);
use POSIX;

use Sys::Guestfs;

# Use a temporary TMPDIR to ensure it's clean
my $tmpdir = tempdir (CLEANUP => 1);
$ENV{TMPDIR} = $tmpdir;

my $testimg = $tmpdir.'/test.img';
system ("touch $testimg");

my $pid = fork();
die ("fork failed: $!") if ($pid < 0);

if ($pid == 0) {
  my $g = Sys::Guestfs->new ();
  $g->add_drive ($testimg);
  $g->launch ();
  _exit (0);
}

my $g = Sys::Guestfs->new ();
$g->add_drive ($testimg);
$g->launch ();
$g = undef;

waitpid ($pid, 0) or die ("waitpid: $!");
die ("child failed") unless ($? == 0);

# Check that only 1 temporary cache directory was created.
#
# No cache directory is OK too (as long as the appliance launched w/o
# failure) because it indicates we're not using supermin.
my $dh;
opendir ($dh, $tmpdir) or die ("Failed to open $tmpdir: $!");
my @cachedirs = grep { /^guestfs\./ } readdir ($dh);
closedir ($dh) or die ("Failed to close $tmpdir: $!");

my $ncachedirs = scalar(@cachedirs);
die "Expected 0 or 1 cachedir, found $ncachedirs"
    unless $ncachedirs == 0 || $ncachedirs == 1;
04 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
"""
Command line interface for cobbler, a network provisioning configuration
library.  Consult 'man cobbler' for general info.  This class serves
as a good reference on how to drive the API (api.py).

Copyright 2006, Red Hat, Inc
Michael DeHaan <mdehaan@redhat.com>

This software may be freely redistributed under the terms of the GNU
general public license.

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., 675 Mass Ave, Cambridge, MA 02139, USA.
"""

import sys
import api
import os
import os.path
import traceback

import cobbler_msg
import cexceptions

LOCKING_ENABLED = True 
LOCKFILE="/var/lib/cobbler/lock"

class BootCLI:


    def __init__(self,args):
        """
        Build the command line parser and API instances, etc.
        """
        self.args = args
        self.api = api.BootAPI()
        self.commands = {}
        self.commands['distro'] = {
            'add'     :  self.distro_add,
            'edit'    :  self.distro_edit,
            'copy'    :  self.distro_copy,
            'rename'  :  self.distro_rename,
            'delete'  :  self.distro_remove,
            'remove'  :  self.distro_remove,
            'list'    :  self.distro_list,
            'report'  :  self.distro_report
        }
        self.commands['profile'] = {
            'add'     :  self.profile_add,
            'edit'    :  self.profile_edit,
            'copy'    :  self.profile_copy,
            'rename'  :  self.profile_rename,
            'delete'  :  self.profile_remove,
            'remove'  :  self.profile_remove,
            'list'    :  self.profile_list,
            'report'  :  self.profile_report
        }
        self.commands['system'] = {
            'add'     :  self.system_add,
            'edit'    :  self.system_edit,
            'rename'  :  self.system_rename,
            'copy'    :  self.system_copy,
            'delete'  :  self.system_remove,
            'remove'  :  self.system_remove,
            'list'    :  self.system_list,
            'report'  :  self.system_report
        }
        self.commands['repo'] = {
            'add'     :  self.repo_add,
            'edit'    :  self.repo_edit,
            'rename'  :  self.repo_rename,
            'copy'    :  self.repo_copy,
            'delete'  :  self.repo_remove,
            'remove'  :  self.repo_remove,
            'list'    :  self.repo_list,
            'report'  :  self.repo_report,
            'sync'    :  self.reposync
        }
        self.commands['toplevel'] = {
            'check'        : self.check,
            'list'         : self.list,
            'report'       : self.report,
            'distros'      : self.distro,
            'distro'       : self.distro,
            'profiles'     : self.profile,
            'profile'      : self.profile,
            'systems'      : self.system,
            'system'       : self.system,
            'repos'        : self.repo,
            'repo'         : self.repo,
            'sync'         : self.sync,
            'reposync'     : self.reposync,
            'import'       : self.import_tree,
            'enchant'      : self.enchant,
            'clobber'      : self.enchant,
            'transmogrify' : self.enchant,
            'status'       : self.status,
            'reserialize'  : self.reserialize,
            'help'         : self.usage,
            '--help'       : self.usage,
            '/?'           : self.usage
        }

    def run(self):
        """
        Run the command line and return system exit code
        """
        self.api.deserialize()
        self.curry_args(self.args[1:], self.commands['toplevel'])

    def usage(self,args):
        """
        Print out abbreviated help if user gives bad syntax
        """
        print cobbler_msg.USAGE


    ###########################################################
    # REPORTING FUNCTIONS

    def distro_report(self,args):
        if len(args) > 0:
           return self.__list_names2(self.api.distros(), args)
        else:
           return self.__print_sorted(self.api.distros())

    def system_report(self,args):
        if len(args) > 0:
           return self.__list_names2(self.api.systems(), args)
        else:
           return self.__print_sorted(self.api.systems())

    def profile_report(self,args):
        if len(args) > 0:
           return self.__list_names2(self.api.profiles(), args)
        else:
           return self.__print_sorted(self.api.profiles())

    def repo_report(self,args):
        if len(args) > 0:
           return self.__list_names2(self.api.repos(), args)
        else:
           return self.__print_sorted(self.api.repos())

    def report(self,args):

        args.append("") # filler
        match = False
        for a in args:
            if a == '--distros' or len(args) == 1:
                self.distro_report([])
                match = True
            if a == '--repos' or len(args) == 1:
                self.repo_report([])
                match = True
            if a == '--profiles' or len(args) == 1:
                self.profile_report([])
                match = True
            if a == '--systems' or len(args) == 1:
                self.system_report([])
                match = True
            if not match and a is not None and a != "":
                raise cexceptions.CobblerException("unknown_cmd",a)
            match = False

    #############################################
    # LISTING FUNCTIONS

    def list(self,args):
        # FIXME: inefficient
        for d in self.api.distros():
            print "distribution   : %s" % d.name
            for p in self.api.profiles():
                if p.distro == d.name:
                    print "  profile      :   %s" % p.name
                    for s in self.api.systems():
                        if s.profile == p.name:
                            print "    system     :     %s" % s.name
        for r in self.api.repos():
            print "repo           : %s" % r.name

    def __list_names(self, collection):
        names = [ x.name for x in collection]
        names.sort() # sorted() is 2.4 only
        for name in names:
           print "   %s" % name
        return True

    def __list_names2(self, collection, args):
        for p in args:
            obj = collection.find(p)
            if obj is not None:
                print obj.printable()
        return True

    def system_list(self, args):
        if len(args) > 0:
           self.__list_names2(self.api.systems(), args)
        else:
           return self.__list_names(self.api.systems())
    
    def distro_list(self, args):
        if len(args) > 0:
           return self.__list_names2(self.api.distros(),args)
        else:
           return self.__list_names(self.api.distros())
    
    def profile_list(self, args):
        if len(args) > 0:
           return self.__list_names2(self.api.profiles(),args)
        else:
           return self.__list_names(self.api.profiles())
    
    def repo_list(self, args):
        if len(args) > 0:
           return self.__list_names2(self.api.repos(),args)
        else:
           return self.__list_names(self.api.repos())

    ###############################################################
    # UTILITY FUNCTIONS
 
    def find_arg(self,haystack,needle):
        for arg in haystack:
           arg2 = arg.replace('"','')
           if arg2.startswith(needle):
               tokens = arg2.split("=")
               if len(tokens) >= 1:
                   return "".join(tokens[1:])
        return None

    def replace_names(self,haystack,newname):
        args2 = []
        for arg in haystack:
            if arg.startswith("--name"):
                args2.append("--name=%s" % newname) 
            else:
                args2.append(arg)
        return args2


    def __sorter(self, a, b):
        return cmp(a.name, b.name)

    def __print_sorted(self, collection):
        collection = [x for x in collection]
        collection.sort(self.__sorter)
        for x in collection:
            print x.printable()
        return True

    ######################################################################
    # BASIC FRAMEWORK

    def __generic_add(self,args,new_fn,control_fn):
        obj = new_fn()
        control_fn(args,obj)

    def __generic_edit(self,args,collection_fn,control_fn,exc_msg):
        obj = collection_fn().find(self.find_arg(args,"--name"))
        name2 = self.find_arg(args,"--newname")
        if name2 is not None:
            raise cexceptions.CobblerException("no_rename")
        if obj is None:
            raise cexceptions.CobblerException(exc_msg)
        control_fn(args,obj)

    def __generic_copy(self,args,collection_fn,control_fn,exc_msg):
        obj = collection_fn().find(self.find_arg(args,"--name"))
        obj2 = self.find_arg(args,"--newname")
        if obj is None:
            raise cexceptions.CobblerException(exc_msg)
        args = self.replace_names(args, obj2)
        obj3 = obj.make_clone()
        obj3.set_name(obj2)
        control_fn(args,obj3)

    def __generic_rename(self,args,collection_fn,control_fn,exc_msg):
        objname = self.find_arg(args,"--name")
        if objname is None:
            raise cexceptions.CobblerException("bad_param")
        objname2 = self.find_arg(args,"--newname")
        if objname2 is None:
            raise cexceptions.CobblerException("bad_param")
        self.__generic_copy(args,collection_fn,control_fn,exc_msg)
        if objname != objname2:
            collection_fn().remove(objname, with_delete=self.api.sync_flag)
        self.api.serialize()

    def __generic_remove(self,args,alias1,alias2,collection_fn):
        commands = {
            "--%s" % alias1 : lambda(a):  collection_fn().remove(a, with_delete=self.api.sync_flag),
            "--%s" % alias2 : lambda(a):  collection_fn().remove(a, with_delete=self.api.sync_flag)
        }
        on_ok = lambda: True
        return self.apply_args(args,commands,on_ok)

    ####################################################################
    # REMOVAL FUNCTIONS
  
    def distro_remove(self,args):
        return self.__generic_remove(args,"distro","name",self.api.distros)
    
    def profile_remove(self,args):
        return self.__generic_remove(args,"profile","name",self.api.profiles)

    def system_remove(self,args):
        return self.__generic_remove(args,"system","name",self.api.systems)
    
    def repo_remove(self,args):
        return self.__generic_remove(args,"repo","name",self.api.repos)
 
    ####################################################################
    # COPY FUNCTIONS
 
    def distro_copy(self,args):
        self.__generic_copy(args,self.api.distros,self.__distro_control,"no_distro")
    
    def profile_copy(self,args):
        self.__generic_copy(args,self.api.profiles,self.__profile_control,"no_profile")
    
    def system_copy(self,args):
        self.__generic_copy(args,self.api.systems,self.__system_control,"no_system")
        
    def repo_copy(self,args):
        self.__generic_copy(args,self.api.repos,self.__repo_control,"no_repo")

    #####################################################################
    # RENAME FUNCTIONS

    def distro_rename(self,args):
        self.__generic_rename(args,self.api.distros,self.__distro_control,"no_distro")

    def profile_rename(self,args):
        self.__generic_rename(args,self.api.profiles,self.__profile_control,"no_profile")

    def system_rename(self,args):
        self.__generic_rename(args,self.api.systems,self.__system_control,"no_system")

    def repo_rename(self,args):
        self.__generic_rename(args,self.api.repos,self.__repo_control,"no_repo")

    #####################################################################
    # EDIT FUNCTIONS

    def distro_edit(self,args):
        self.__generic_edit(args,self.api.distros,self.__distro_control,"no_distro")
    
    def profile_edit(self,args):
        self.__generic_edit(args,self.api.profiles,self.__profile_control,"no_profile")
    
    def system_edit(self,args):
        self.__generic_edit(args,self.api.systems,self.__system_control,"no_system")
    
    def repo_edit(self,args):
        self.__generic_edit(args,self.api.repos,self.__repo_control,"no_repo")
   
    #####################################################################
    # ADD FUNCTIONS
 
    def distro_add(self,args):
        self.__generic_add(args,self.api.new_distro,self.__distro_control)

    def profile_add(self,args):
        self.__generic_add(args,self.api.new_profile,self.__profile_control)    

    def system_add(self,args):
        self.__generic_add(args,self.api.new_system,self.__system_control)

    def repo_add(self,args):
        self.__generic_add(args,self.api.new_repo,self.__repo_control)


    ###############################################################
    # CONTROL IMPLEMENTATIONS

    def __profile_control(self,args,profile,newname=None):
        """
        Create/Edit a profile:  'cobbler profile edit --name='foo' ...
        """
        commands = {
            '--name'            :  lambda(a) : profile.set_name(a),
            '--newname'         :  lambda(a) : True,
            '--profile'         :  lambda(a) : profile.set_name(a),
            '--distro'          :  lambda(a) : profile.set_distro(a),
            '--kickstart'       :  lambda(a) : profile.set_kickstart(a),
            '--kick-start'      :  lambda(a) : profile.set_kickstart(a),
            '--answers'         :  lambda(a) : profile.set_kickstart(a),
            '--kopts'           :  lambda(a) : profile.set_kernel_options(a),
            '--virt-file-size'  :  lambda(a) : profile.set_virt_file_size(a),
            '--virt-ram'        :  lambda(a) : profile.set_virt_ram(a),
            '--ksmeta'          :  lambda(a) : profile.set_ksmeta(a),
            '--repos'           :  lambda(a) : profile.set_repos(a)
        }
        def on_ok():
            if newname is not None:
                profile.set_name(newname)
            self.api.profiles().add(profile, with_copy=self.api.sync_flag)
        return self.apply_args(args,commands,on_ok)

    def __repo_control(self,args,repo,newname=None):
        """
        Create/edit a repo:  'cobbler repo add --name='foo' ...
        """
        commands = {
           '--name'             :  lambda(a): repo.set_name(a),
           '--newname'          :  lambda(a): True,
           '--mirror-name'      :  lambda(a): repo.set_name(a),
           '--mirror'           :  lambda(a): repo.set_mirror(a),
           '--keep-updated'     :  lambda(a): repo.set_keep_updated(a),
           '--local-filename'   :  lambda(a): repo.set_local_filename(a),
           '--rpm-list'         :  lambda(a): repo.set_rpm_list(a)
        }
        def on_ok():
            if newname is not None:
                repo.set_name(newname)
            self.api.repos().add(repo)
        return self.apply_args(args,commands,on_ok)

    def __distro_control(self,args,distro):
        """
        Create/Edit a distro:  'cobbler distro edit --name='foo' ...
        """
        commands = {
            '--name'      :  lambda(a) : distro.set_name(a),
            '--newname'   :  lambda(a) : True,
            '--distro'    :  lambda(a) : distro.set_name(a),
            '--kernel'    :  lambda(a) : distro.set_kernel(a),
            '--initrd'    :  lambda(a) : distro.set_initrd(a),
            '--kopts'     :  lambda(a) : distro.set_kernel_options(a),
            '--arch'      :  lambda(a) : distro.set_arch(a),
            '--ksmeta'    :  lambda(a) : distro.set_ksmeta(a),
            '--breed'     :  lambda(a) : distro.set_breed(a)
        }
        def on_ok():
            self.api.distros().add(distro, with_copy=self.api.sync_flag)
        return self.apply_args(args,commands,on_ok)

    def __system_control(self,args,sys):
        """
        Create/Edit a system:  'cobbler system edit --name='foo' ...
        """
        commands = {
           '--name'        :  lambda(a) : sys.set_name(a),
           '--newname'     :  lambda(a) : True,
           '--system'      :  lambda(a) : sys.set_name(a),
           '--profile'     :  lambda(a) : sys.set_profile(a),
           '--kopts'       :  lambda(a) : sys.set_kernel_options(a),
           '--ksmeta'      :  lambda(a) : sys.set_ksmeta(a),
           '--pxe-address' :  lambda(a) : sys.set_pxe_address(a)
        }
        def on_ok():
            self.api.systems().add(sys, with_copy=self.api.sync_flag)
        return self.apply_args(args,commands,on_ok)

    ###################################################################################
    # PARSING FUNCTIONS

    def apply_args(self,args,input_routines,on_ok):
        """
        Custom CLI handling, instead of getopt/optparse.
        Parses arguments of the form --foo=bar.
        'on_ok' is a callable that is run if all arguments are parsed
        successfully.  'input_routines' is a dispatch table of routines
        that parse the arguments.  See distro_edit for an example.
        """
        if len(args) == 0:
            raise cexceptions.CobblerException("no_args")
        for x in args:
            try:
                key, value = x.split("=",1)
                value = value.replace('"','').replace("'",'')
            except:
                raise cexceptions.CobblerException("bad_arg",x)
            if input_routines.has_key(key):
                input_routines[key](value)
            else:
                raise cexceptions.CobblerException("weird_arg", key)
        on_ok()
        self.api.serialize()

    def curry_args(self, args, commands):
        """
        Lookup command args[0] in the dispatch table and
        feed it the remaining args[1:-1] as arguments.
        """
        if args is None or len(args) == 0:
            print cobbler_msg.USAGE
            return True
        if args[0] in commands:
            commands[args[0]](args[1:])
        else:
            raise cexceptions.CobblerException("unknown_cmd", args[0])
        return True