Beispiel #1
0
def run_job(data, workers = None):
    if workers is None:
        workers = [("localhost", DEFAULT_PORT)]
    f = Foreman()
    f.mapfn = MAPPER
    f.reducefn = REDUCER
    f.datasource = data
    return f.run(workers)
a = {}
a["admin"] = conf["foreman"]["admin"]
a["password"] = conf["foreman"]["password"]
a["ip"] = conf["foreman"]["ip"]

# Update args with values from config file
args.update(a)
del a

# p.list_id(args)

##############################################
p.header("Load Foreman topology")
##############################################
foreman = Foreman(  login=args["admin"],
                    password=args["password"],
                    ip=args["ip"])

##############################################
p.header("Check puppet classes")
##############################################
p_ids = {}
for name in conf['opensteak']['vm_list']:
    p_ids[name] = {}
    if conf['vm'][name]['puppet_classes']:
        for pclass in conf['vm'][name]['puppet_classes']:
            p_ids[name][pclass] = foreman.puppetClasses[pclass]['id']
            p.config('Puppet Class', pclass, p_ids[name][pclass])

##############################################
p.header("Controllers attributes")
Beispiel #3
0
def main(argv):
    foreman_host = os.environ.get('FOREMAN_HOST', '127.0.0.1')
    foreman_port = os.environ.get('FOREMAN_PORT', '443')
    foreman_username = os.environ.get('FOREMAN_USERNAME', 'foreman')
    foreman_password = os.environ.get('FOREMAN_PASSWORD', 'changme')    
    config_file = None
    config = {}
    try:
        opts, args = getopt.getopt(argv, "c:f:hu:p:s:", ["config=", "foreman=", "username="******"port=", "secret="])
    except getopt.GetoptError:
        show_help()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-c', '--config'):
            config_file = arg
        elif opt in ('-f', '--foreman'):
            foreman_host = arg
        elif opt == '-h':
            show_help()
            sys.exit()
        elif opt in ('-u', '--username'):
            foreman_username = arg
        elif opt in ('-p', '--port'):
            foreman_port = arg
        elif opt in ('-s', '--secret'):
            foreman_password = arg

    f = Foreman(foreman_host, foreman_port, foreman_username, foreman_password)
    if config_file:
        with open(config_file, 'r') as cfgfile:
            config = yaml.load(cfgfile)
    
    # Test Architectures
    for item in config.get('architectures'):
        obj = f.get_architecture_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_architecture(data=item)
        print "Architecture: %s" % (json.dumps(obj))
    
    # Test Compute Resources
    for item in config.get('compute_resources'):
        obj = f.get_compute_resource_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_compute_resource(data=item)
        print "Compute Resource: %s" % (json.dumps(obj))
    
    # Test Domains
    for item in config.get('domains'):
        obj = f.get_domain_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_domain(data=item)
        print "Domain: %s" % (json.dumps(obj))
    
    # Test Environments
    for item in config.get('environments'):
        obj = f.get_environment_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_environment(data=item)
        print "Environment: %s" % (json.dumps(obj))
    
    # Test Locations
    for item in config.get('locations'):
        obj = f.get_location_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_location(data=item)
        print "Location: %s" % (json.dumps(obj))
            
    # Test Media
    for item in config.get('medias'):
        obj = f.get_media_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_media(data=item)
        else:
            print "Media exist: %s" % (json.dumps(obj))

    # Test Operatingsystems
    for item in config.get('operatingsystems'):
        obj = f.get_operatingsystem_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_operatingsystem(data=item)
        print "Operatingsystem exist: %s" % (json.dumps(obj))
            
    # Test Organizations
    for item in config.get('organizations'):
        obj = f.get_organization_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_organization(data=item)
        print "Organization exist: %s" % (json.dumps(obj))
            
    # Test Partition Tables
    for item in config.get('partition_tables'):
        obj = f.get_partition_table_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_partition_table(data=item)
        print "Partition Table exist: %s" % (json.dumps(obj))
            
    # Test Smart Proxies
    for item in config.get('smart_proxies'):
        obj = f.get_smart_proxy_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_smart_proxy(data=item)
        print "Smart Proxy exist: %s" % (json.dumps(obj))
a = {}
a["admin"] = conf["foreman"]["admin"]
a["password"] = conf["foreman"]["password"]
a["ip"] = conf["foreman"]["ip"]
# Update args with values from config file
args.update(a)
del a

# p.list_id(args)

#
# Prepare classes
#
foreman = Foreman(login=args["admin"],
                  password=args["password"],
                  ip=args["ip"])

##############################################
p.header("Check smart proxy")
##############################################

smartProxy = conf['smart_proxies']
smartProxyId = foreman.smartProxies[smartProxy]['id']
p.status(bool(smartProxyId), 'Check smart proxy ' + smartProxy + ' exists')

##############################################
p.header("Check and create - Environment production")
##############################################

environment = conf['environments']
Beispiel #5
0
#!/usr/bin/python
"""foreman sample to use without ovirt(baremetal stuff)"""

import sys
from foreman import Foreman

foremanhost = '192.168.8.223'
foremanport = 443
foremanuser = '******'
foremanpassword = '******'
foremansecure = True
name = 'satriani1'
dns = 'xxx.org'
ip1 = '192.168.8.226'
hostgroup = 'base6'
compute = 'bumblefoot'
profile = '1-Small'

f = Foreman(foremanhost, foremanport, foremanuser, foremanpassword, foremansecure)
f.create(name=name, dns=dns, ip=ip1, hostgroup=hostgroup, compute=compute, profile=profile, build=True)
Beispiel #6
0
 def __init__(self, *args, **kwargs):
     super(HostResource, self).__init__(*args, **kwargs)
     self.foreman = Foreman()
Beispiel #7
0
class HostResource(Resource):

    name = fields.CharField(attribute='name')
    modified = fields.IntegerField(attribute='modified', null=True)
    puppet_status = fields.IntegerField(attribute='puppet_status', null=True)
    build = fields.BooleanField(attribute='build')
    console_url = fields.CharField(attribute='console_url',
                                   null=True,
                                   readonly=True)
    parameters = fields.ApiField(attribute='parameters', null=True)
    hostgroups = fields.ApiField(attribute='hostgroups', null=True)
    hostgroups_id = fields.ApiField(attribute='hostgroups_id', null=True)
    hostgroup_id = fields.CharField(attribute='hostgroup_id', null=True)

    def __init__(self, *args, **kwargs):
        super(HostResource, self).__init__(*args, **kwargs)
        self.foreman = Foreman()

    class Meta:
        resource_name = 'host'
        object_class = HostObject
        authorization = Authorization()

    def detail_uri_kwargs(self, bundle_or_obj):
        kwargs = {}

        if isinstance(bundle_or_obj, Bundle):
            kwargs['pk'] = bundle_or_obj.obj.name
        else:
            kwargs['pk'] = bundle_or_obj.name

        return kwargs

    def get_object_list(self, request):
        #TODO: check if anon
        if request.user:
            query = self.foreman.get_hosts_by_user(request.user.username)
            results = []
            for host in query:
                new_host = HostObject(initial=host)
                results.append(new_host)
            return results
        return []

    def obj_get_list(self, bundle, **kwargs):
        return self.get_object_list(bundle.request)

    def obj_get(self, bundle, **kwargs):
        host = self.foreman.get_host(kwargs['pk'])
        return HostObject(initial=host)

    def obj_create(self, bundle, **kwargs):
        pass

    def put_detail(self, request, **kwargs):

        hostnames = self.foreman.get_hostnames_by_user(request.user.username)
        if kwargs['pk'] not in hostnames:
            raise ApiException('Permission denied')

        return super(HostResource, self).put_detail(request, **kwargs)

    def obj_update(self, bundle, **kwargs):
        bundle.obj = HostObject(initial=kwargs)
        bundle = self.full_hydrate(bundle)

        self.foreman.update_host(bundle.obj)

    def obj_delete_list(self, bundle, **kwargs):
        pass

    def obj_delete(self, bundle, **kwargs):
        pass

    def rollback(self, bundles):
        pass
Beispiel #8
0
#!/usr/bin/python
"""foreman sample to use without ovirt(baremetal stuff)"""

import sys
from foreman import Foreman

foremanhost = '192.168.8.223'
foremanport = 443
foremanuser = '******'
foremanpassword = '******'
foremansecure = True
name = 'satriani1'
dns = 'xxx.org'
ip1 = '192.168.8.226'
hostgroup = 'base6'
compute = 'bumblefoot'
profile = '1-Small'

f = Foreman(foremanhost, foremanport, foremanuser, foremanpassword,
            foremansecure)
f.create(name=name,
         dns=dns,
         ip=ip1,
         hostgroup=hostgroup,
         compute=compute,
         profile=profile,
         build=True)
def main():
    global WORKING_BUNDLE_PATH
    global WORKING_TARGET_DEVICE
    global WORKING_TARGET_BUILD
    global WORKING_TARGET_IOSVER
    global VERBOSE_LOGGING_ENABLED
    # just print out our version and exit, else print it anyways
    if args.version:
        print_version()
        exit(0)
    else:
        print_version()
    # enable verbose logging
    if args.verbose:
        LOGGING.setVerbose(True)
        LOGGING.DEBUG("Verbose logging enabled")
    # check if 'img4' exists in our users PATH
    if checkIfimg4libBinaryExists() is not True:
        LOGGING.PRINT(
            "Fatal Error!\nimg4 was not found on your machine's PATH.\nPlease compile and install it from xerub's img4lib.",
            True, '\n', 'light_red')
        exit(-1)  # exit early
    # check the .firmwares cache
    checkFirmwaresFileCache()
    # argument logic
    if args.generate:  # do generate
        WORKING_BUNDLE_PATH = Path(args.generate)
        if args.boardconfig:
            WORKING_TARGET_DEVICE = findModelByBoardConfig(args.boardconfig)
            LOGGING.DEBUG("WORKING_TARGET_DEVICE => " + WORKING_TARGET_DEVICE)
        else:
            WORKING_TARGET_DEVICE = args.model
        if WORKING_TARGET_DEVICE is None:  # check our arg
            LOGGING.PRINT("Please specify --model", True, '\n', 'light_red')
            exit(-1)  # exit early
        WORKING_TARGET_BUILD = args.build
        WORKING_TARGET_IOSVER = args.iosver
        if WORKING_TARGET_BUILD is None and WORKING_TARGET_IOSVER is None:  # check our arg
            LOGGING.PRINT("Please specify --build or --iosver", True, '\n',
                          'light_red')
            exit(-1)  # exit early
        if checkIfDirectoryExists(WORKING_BUNDLE_PATH, True):
            generateConfig()  # branch out to generateConfig
        else:
            LOGGING.PRINT(
                "Directory doesn't exist and couldn't be created! mkdir this path and verify your permissions.",
                True, '\n', 'light_red')
            exit(-1)  # exit early
    elif args.decryptimages:  # run decryption
        WORKING_BUNDLE_PATH = Path(args.decryptimages)
        loadConfig()  # load our config
        beginProcessingImages()
    elif args.download:  # run download
        WORKING_BUNDLE_PATH = Path(args.download)
        loadConfig()  # load our config
        handleDownloading()
    elif args.extractkbags:  # grab kbags
        WORKING_BUNDLE_PATH = Path(args.extractkbags)
        loadConfig()  # load our config
        handleKBAGExtraction()
    elif args.decryptkbags:  # decrypt kbags
        WORKING_BUNDLE_PATH = Path(args.decryptkbags)
        loadConfig()  # load our config
        handleKBAGDecryption()
    elif args.automate:  # do "automate"
        WORKING_BUNDLE_PATH = Path(args.automate)
        loadConfig()  # load our config
        automate_start_time = time.time()
        handleDownloading()
        handleKBAGExtraction()
        handleKBAGDecryption()
        beginProcessingImages()
        automate_end_time = time.time()
        LOGGING.PRINT("Automate finished in " +
                      str(automate_end_time - automate_start_time) +
                      " seconds")
        if args.autosubmit:
            loadConfig()  # reload the config before submitting
            Foreman().submit(LOADED_CONFIG)
        elif args.noprompt is False:
            shouldWeForeman = confirmationPrompt(
                "Would you like to try and submit to Foreman?")
            if shouldWeForeman:
                loadConfig()  # reload the config before submitting
                Foreman().submit(LOADED_CONFIG)
    elif args.scanusb:  # scan for usb dfu / recovery mode devices
        foundDevice = DeviceFinder().findAllUSBDevices()
        if foundDevice is not None:
            LOGGING.PRINT("Found USB device!\n" + foundDevice)
        else:
            LOGGING.PRINT("Did not find any DFU or recovery mode device.",
                          True, '\n', 'light_red')
    elif args.foreman:  # submit our gm.config to the Foreman server
        WORKING_BUNDLE_PATH = Path(args.foreman)
        loadConfig()
        Foreman().submit(LOADED_CONFIG)
    elif args.foremanbags:  # submit our gm.config to the Foreman server for keybag decryption
        WORKING_BUNDLE_PATH = Path(args.foremanbags)
        loadConfig()
        Foreman().submitKeybags(LOADED_CONFIG)
    else:
        parser.print_help()
    LOGGING.PRINT("\nGoodbye!", False, '\n', 'green')
    exit(0)
Beispiel #10
0
def main(argv):
    foreman_host = os.environ.get('FOREMAN_HOST', '127.0.0.1')
    foreman_port = os.environ.get('FOREMAN_PORT', '443')
    foreman_username = os.environ.get('FOREMAN_USERNAME', 'foreman')
    foreman_password = os.environ.get('FOREMAN_PASSWORD', 'changme')
    config_file = None
    config = {}
    try:
        opts, args = getopt.getopt(
            argv, "c:f:hu:p:s:",
            ["config=", "foreman=", "username="******"port=", "secret="])
    except getopt.GetoptError:
        show_help()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-c', '--config'):
            config_file = arg
        elif opt in ('-f', '--foreman'):
            foreman_host = arg
        elif opt == '-h':
            show_help()
            sys.exit()
        elif opt in ('-u', '--username'):
            foreman_username = arg
        elif opt in ('-p', '--port'):
            foreman_port = arg
        elif opt in ('-s', '--secret'):
            foreman_password = arg

    f = Foreman(foreman_host, foreman_port, foreman_username, foreman_password)
    if config_file:
        with open(config_file, 'r') as cfgfile:
            config = yaml.load(cfgfile)

    # Test Architectures
    for item in config.get('architectures'):
        obj = f.get_architecture_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_architecture(data=item)
        print "Architecture: %s" % (json.dumps(obj))

    # Test Compute Resources
    for item in config.get('compute_resources'):
        obj = f.get_compute_resource_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_compute_resource(data=item)
        print "Compute Resource: %s" % (json.dumps(obj))

    # Test Domains
    for item in config.get('domains'):
        obj = f.get_domain_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_domain(data=item)
        print "Domain: %s" % (json.dumps(obj))

    # Test Environments
    for item in config.get('environments'):
        obj = f.get_environment_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_environment(data=item)
        print "Environment: %s" % (json.dumps(obj))

    # Test Locations
    for item in config.get('locations'):
        obj = f.get_location_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_location(data=item)
        print "Location: %s" % (json.dumps(obj))

    # Test Media
    for item in config.get('medias'):
        obj = f.get_media_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_media(data=item)
        else:
            print "Media exist: %s" % (json.dumps(obj))

    # Test Operatingsystems
    for item in config.get('operatingsystems'):
        obj = f.get_operatingsystem_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_operatingsystem(data=item)
        print "Operatingsystem exist: %s" % (json.dumps(obj))

    # Test Organizations
    for item in config.get('organizations'):
        obj = f.get_organization_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_organization(data=item)
        print "Organization exist: %s" % (json.dumps(obj))

    # Test Partition Tables
    for item in config.get('partition_tables'):
        obj = f.get_partition_table_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_partition_table(data=item)
        print "Partition Table exist: %s" % (json.dumps(obj))

    # Test Smart Proxies
    for item in config.get('smart_proxies'):
        obj = f.get_smart_proxy_by_name(name=item.get('name'))
        if not obj:
            obj = f.set_smart_proxy(data=item)
        print "Smart Proxy exist: %s" % (json.dumps(obj))
Beispiel #11
0
 def __init__(self, *args, **kwargs):
     super(HostResource, self).__init__(*args, **kwargs)
     self.foreman = Foreman()
Beispiel #12
0
class HostResource(Resource):

    name = fields.CharField(attribute="name")
    modified = fields.IntegerField(attribute="modified", null=True)
    puppet_status = fields.IntegerField(attribute="puppet_status", null=True)
    build = fields.BooleanField(attribute="build")
    console_url = fields.CharField(attribute="console_url", null=True, readonly=True)
    parameters = fields.ApiField(attribute="parameters", null=True)
    hostgroups = fields.ApiField(attribute="hostgroups", null=True)
    hostgroups_id = fields.ApiField(attribute="hostgroups_id", null=True)
    hostgroup_id = fields.CharField(attribute="hostgroup_id", null=True)

    def __init__(self, *args, **kwargs):
        super(HostResource, self).__init__(*args, **kwargs)
        self.foreman = Foreman()

    class Meta:
        resource_name = "host"
        object_class = HostObject
        authorization = Authorization()

    def detail_uri_kwargs(self, bundle_or_obj):
        kwargs = {}

        if isinstance(bundle_or_obj, Bundle):
            kwargs["pk"] = bundle_or_obj.obj.name
        else:
            kwargs["pk"] = bundle_or_obj.name

        return kwargs

    def get_object_list(self, request):
        # TODO: check if anon
        if request.user:
            query = self.foreman.get_hosts_by_user(request.user.username)
            results = []
            for host in query:
                new_host = HostObject(initial=host)
                results.append(new_host)
            return results
        return []

    def obj_get_list(self, bundle, **kwargs):
        return self.get_object_list(bundle.request)

    def obj_get(self, bundle, **kwargs):
        host = self.foreman.get_host(kwargs["pk"])
        return HostObject(initial=host)

    def obj_create(self, bundle, **kwargs):
        pass

    def put_detail(self, request, **kwargs):

        hostnames = self.foreman.get_hostnames_by_user(request.user.username)
        if kwargs["pk"] not in hostnames:
            raise ApiException("Permission denied")

        return super(HostResource, self).put_detail(request, **kwargs)

    def obj_update(self, bundle, **kwargs):
        bundle.obj = HostObject(initial=kwargs)
        bundle = self.full_hydrate(bundle)

        self.foreman.update_host(bundle.obj)

    def obj_delete_list(self, bundle, **kwargs):
        pass

    def obj_delete(self, bundle, **kwargs):
        pass

    def rollback(self, bundles):
        pass