Beispiel #1
0
    def run(self, params, args):

        (networks, address) = self.fillSetNetworkParams(args, 'address')
        if len(networks) > 1:
            raise ArgUnique(self, 'network')

        network = networks[0]
        rows = self.db.select("""
			mask from subnets where name='%s'
			""" % network)

        if not rows:
            raise CommandError(self, 'network "%s" doesn\'t exist' % name)

        mask = rows[0][0]
        try:
            if ipaddress.IPv4Network(u"%s/%s" % (address, mask)):
                pass
        except:
            msg = '%s/%s is not a valid network address and subnet mask combination'
            raise CommandError(self, msg % (address, mask))

        for network in networks:
            self.db.execute("""
				update subnets set address='%s' where
				subnets.name='%s'
				""" % (address, network))
Beispiel #2
0
    def run(self, params, args):

        (profile, hashit, chapter) = self.fillParams([('profile', 'native'),
                                                      ('hash', 'n'),
                                                      ('chapter', None)])

        xmlinput = ''
        osname = None

        # If the command is not on a TTY, then try to read XML input.

        if not sys.stdin.isatty():
            for line in sys.stdin.readlines():
                if line.find('<stack:profile stack:os="') == 0:
                    osname = line.split()[1][9:].strip('"')
                xmlinput += line
        if xmlinput and not osname:
            raise CommandError(self, "OS name not specified in profile")

        self.beginOutput()

        # If there's no XML input, either we have TTY, or we're running
        # in an environment where TTY cannot be created (ie. apache)

        if not xmlinput:
            hosts = self.getHostnames(args)
            if len(hosts) != 1:
                raise ArgUnique(self, 'host')
            host = hosts[0]

            osname = self.db.getHostOS(host)
            xmlinput = self.command('list.host.xml', [host])

            self.runImplementation(osname, (xmlinput, profile, chapter))

        # If we DO have XML input, simply parse it.

        else:
            self.runImplementation(osname, (xmlinput, profile, chapter))

        self.endOutput(padChar='')

        if self.str2bool(hashit):
            import hashlib

            #
            # remove lines that contain attributes which we know will change after
            # the host installs
            #
            m = hashlib.md5()

            skip = ['nukedisks', 'nukecontroller']
            for line in self.getText().split('\n'):
                if any(s in line for s in skip):
                    continue

                l = line + '\n'
                m.update(l.encode())

            sys.stderr.write('%s  profile\n' % m.hexdigest())
Beispiel #3
0
	def getBootActionTypeOS(self, params, args):
		if not len(args):
			raise ArgRequired(self, 'action')
		if len(args) != 1:
			raise ArgUnique(self, 'action')

		b_action = args[0]

		(b_type, b_os) = self.fillParams([
			('type', None, True),
			('os', '')
		])

		if b_type not in [ 'os', 'install' ]:
			raise ParamValue(self, 'type', '"os" or "install"')

		# If bootaction type is not os, then get the default
		# os so code doesn't break.
		if not b_os and b_type != 'os':
			b_os = self.os

		if b_os:
			b_os = self.getOSNames([b_os])[0]

		return (b_action, b_type, b_os)
Beispiel #4
0
    def run(self, params, args):

        if len(args) == 0:
            raise ArgRequired(self, 'host')

        hosts = self.getHostnames(args)

        (group, ) = self.fillParams([('group', None, True)])

        if not hosts:
            raise ArgRequired(self, 'host')
        if not len(hosts) == 1:
            raise ArgUnique(self, 'host')

        membership = {}
        for row in self.call('list.host.group'):
            membership[row['host']] = row['groups']
        for host in hosts:
            if group not in membership[host]:
                raise CommandError(self,
                                   '%s is not a member of %s' % (host, group))

        for host in hosts:
            self.db.execute("""
				delete from memberships 
				where
				nodeid = (select id from nodes where name='%s')
				and
				groupid = (select id from groups where name='%s')
				""" % (host, group))
Beispiel #5
0
	def run(self, params, args):
		if len(args) == 0:
			raise ArgRequired(self, 'host')

		hosts = self.getHostnames(args)

		if not hosts:
			raise ArgRequired(self, 'host')

		if not len(hosts) == 1:
			raise ArgUnique(self, 'host')

		alias, interface, = self.fillParams([
			('alias', None),
			('interface', None)
		])

		query = """
			DELETE aliases
			FROM aliases
			LEFT JOIN networks ON aliases.network = networks.id
			LEFT JOIN nodes ON networks.node = nodes.id
			WHERE nodes.name = %s
		"""
		values = [hosts[0]]

		if alias:
			query += ' AND aliases.name = %s'
			values.append(alias)

		if interface:
			query += ' AND networks.device = %s'
			values.append(interface)

		self.db.execute(query, values)
Beispiel #6
0
    def _get_single_host(self, args):
        hosts = self._get_hosts(args)

        if len(hosts) != 1:
            raise ArgUnique(self, 'host')

        return hosts[0]
Beispiel #7
0
    def run(self, params, args):

        (pallet, debug) = self.fillParams([('pallet', ), ('debug', 'false')])

        debug = self.str2bool(debug)

        hosts = self.getHostnames(args)
        if len(hosts) != 1:
            raise ArgUnique(self, 'host')
        host = hosts[0]

        self.beginOutput()

        # Call "stack list node xml" with attrs{} dictionary
        # set from the database.

        attrs = {}
        for row in self.call('list.host.attr', [host]):
            attrs[row['attr']] = row['value']

        args = [attrs['node']]
        args.append('attrs=%s' % attrs)
        if pallet:
            args.append('pallet=%s' % pallet)
        xml = self.command('list.node.xml', args)
        if not debug:
            for line in xml.split('\n'):
                self.addOutput(host, line)

        self.endOutput(padChar='', trimOwner=True)
Beispiel #8
0
    def run(self, params, args):

        hosts = self.getHostnames(args)
        (ip, interface, mac) = self.fillParams([('ip', None, True),
                                                ('interface', None),
                                                ('mac', None)])

        if not interface and not mac:
            raise ParamRequired(self, ('interface', 'mac'))
        if len(hosts) != 1:
            raise ArgUnique(self, 'host')

        ip = ip.upper()  # null -> NULL
        host = hosts[0]

        if interface:
            self.db.execute("""
				update networks, nodes set 
				networks.ip=NULLIF('%s','NULL') where
				nodes.name='%s' and networks.node=nodes.id and
				networks.device like '%s'
				""" % (ip, host, interface))
        else:
            self.db.execute("""
				update networks, nodes set 
				networks.ip=NULLIF('%s','NULL') where
				nodes.name='%s' and networks.node=nodes.id and
				networks.mac like '%s'
				""" % (ip, host, mac))
Beispiel #9
0
    def run(self, params, args):
        if len(args) == 0:
            raise ArgRequired(self, 'host')

        hosts = self.getHostnames(args)
        if not hosts:
            raise ArgRequired(self, 'host')

        if len(hosts) > 1:
            raise ArgUnique(self, 'host')

        (key_id, ) = self.fillParams([('id', None, True)])

        host = hosts[0]

        if self.db.count(
                """
			(ID) from public_keys
			where id=%s and node=(
				select id from nodes where name=%s
			)""", (key_id, host)) == 0:
            raise CommandError(
                self,
                f"public key with id {key_id} doesn't exist for host {host}")

        self.db.execute('delete from public_keys where id=%s', (key_id, ))
Beispiel #10
0
	def run(self, params, args):

		hosts = self.getHostnames(args)
		(name, interface, mac) = self.fillParams([
			('name',      None, True),
			('interface', None),
			('mac',       None)
			])

		if len(name.split('.')) > 1:
			raise ParamType(self, 'name', 'non-FQDN (base hostname)')
		if not interface and not mac:
			raise ParamRequired(self, ('interface', 'mac'))
		if len(hosts) != 1:
			raise ArgUnique(self, 'host')

		host = hosts[0]		

		if name.upper() == "NULL":
			name = host

		if interface:
			self.db.execute("""
				update networks, nodes set 
				networks.name='%s' where nodes.name='%s'
				and networks.node=nodes.id and
				networks.device like '%s'
				""" % (name, host, interface))
		else:
			self.db.execute("""
				update networks, nodes set 
				networks.name='%s' where nodes.name='%s'
				and networks.node=nodes.id and
				networks.mac like '%s'
				""" % (name, host, mac))
Beispiel #11
0
    def run(self, params, args):

        if len(args) != 1:
            raise ArgUnique(self, 'switch')

        switchname = args[0].lower()

        self.addSwitch(switchname, params)
Beispiel #12
0
 def validate_args(self, args):
     """Validate that there is only one implementation name passed."""
     # Require a implementation name
     if not args:
         raise ArgRequired(cmd=self.owner, arg="name")
     # Should only be one
     if len(args) != 1:
         raise ArgUnique(cmd=self.owner, arg="name")
Beispiel #13
0
 def validate_args(self, args):
     """Validate that a version number is provided and that there is only one."""
     # Require a version name
     if not args:
         raise ArgRequired(cmd=self.owner, arg="version")
     # should only be one version name
     if len(args) != 1:
         raise ArgUnique(cmd=self.owner, arg="version")
Beispiel #14
0
    def run(self, params, args):
        if len(args) == 0:
            raise ArgRequired(self, 'host')

        hosts = self.getHostnames(args)

        if not hosts:
            raise ArgRequired(self, 'host')

        if not len(hosts) == 1:
            raise ArgUnique(self, 'host')

        (
            alias,
            interface,
        ) = self.fillParams([('alias', None), ('interface', None)])

        for host in self.getHostnames(args):
            if not alias and not interface:
                self.db.execute(
                    """
					delete from aliases
					where network IN (
						select id from networks where node=(
							select id from nodes where name=%s
						)
					)
				""", (host, ))
            elif not alias:
                self.db.execute(
                    """
					delete from aliases
					where network IN (
						select id from networks where node=(
							select id from nodes where name=%s
						) and device=%s
					)
				""", (host, interface))
            elif not interface:
                self.db.execute(
                    """
					delete from aliases
					where network IN (
						select id from networks where node=(
							select id from nodes where name=%s
						)
					) and name=%s
				""", (host, alias))
            else:
                self.db.execute(
                    """
					delete from aliases
					where network=(
						select id from networks where node=(
							select id from nodes where name=%s
						) and device=%s
					) and name=%s
				""", (host, interface, alias))
Beispiel #15
0
    def validate_args(self, args):
        """Validate that the arguments to this plugin are as expected."""
        # Require a version regex
        if not args:
            raise ArgRequired(cmd=self.owner, arg="regex")

        # Should only be one
        if len(args) != 1:
            raise ArgUnique(cmd=self.owner, arg="regex")
Beispiel #16
0
    def run(self, params, args):
        hosts = self.getHostnames(args)

        if len(hosts) != 1:
            raise ArgUnique(self, 'host')

        self.beginOutput()
        self.addOutput(
            '', str(self.call('list.host.storage.controller', [hosts[0]])))
        self.endOutput(padChar='')
Beispiel #17
0
    def run(self, params, args):

        (networks, gateway) = self.fillSetNetworkParams(args, 'gateway')
        if len(networks) > 1:
            raise ArgUnique(self, 'network')

        network = networks[0]

        self.db.execute('update subnets set gateway=%s where name=%s',
                        (gateway, network))
Beispiel #18
0
    def run(self, params, args):
        (host, interface, port) = self.fillParams([('host', None),
                                                   ('interface', None),
                                                   ('port', None)])

        switches = self.getSwitchNames(args)
        if len(switches) == 0:
            raise ArgRequired(self, 'switch')
        if len(switches) > 1:
            raise ArgUnique(self, 'switch')
        switch = switches[0]

        hosts = self.getHostnames([host])
        host = hosts[0]

        if not host:
            raise ParamRequired(self, ('host'))
        if not interface:
            raise ParamRequired(self, ('interface'))
        if not port:
            raise ParamRequired(self, ('port'))

        try:
            port = int(port)
        except:
            raise ParamType(self, 'port', 'integer')

        #
        # check if the host/port is defined for this switch
        #
        found = False
        for o in self.call('list.switch.host', [switch]):
            if o['host'] == host and o['port'] == port:
                found = True
        if not found:
            raise ArgError(self, 'host/port',
                           '"%s/%s" not found' % (host, port))

        #
        # see if the interface exists for this host
        #
        row = self.db.select("""net.id from networks net, nodes n
			where n.name='%s' and net.device='%s'
			and net.node = n.id""" % (host, interface))

        if not row:
            raise CommandError(
                self, 'interface "%s" does not exist for host "%s"' %
                (interface, host))

        interfaceid, = row[0]

        self.db.execute("""update switchports set interface=%s
			where port=%s and switch=(select id from nodes where name='%s')
			""" % (interfaceid, port, switch))
Beispiel #19
0
    def run(self, params, args):

        (networks, zone) = self.fillSetNetworkParams(args, 'zone')
        if len(networks) > 1:
            raise ArgUnique(self, 'network')

        for network in networks:
            self.db.execute("""
				update subnets set zone='%s' where
				subnets.name='%s'
				""" % (zone, network))
Beispiel #20
0
    def run(self, params, args):
        if not len(args):
            raise ArgRequired(self, 'group')
        if len(args) > 1:
            raise ArgUnique(self, 'group')

        group = args[0]

        if self.db.count('(ID) from groups where name=%s', (group, )) > 0:
            raise CommandError(self, '"%s" group already exists' % group)

        self.db.execute('insert into groups(name) values (%s)', (group, ))
Beispiel #21
0
	def run(self, params, args):

		(networks, zone) = self.fillSetNetworkParams(args, 'zone')
		if len(networks) > 1:
			raise ArgUnique(self, 'network')

		network = networks[0]

		self.db.execute(
			'update subnets set zone=%s where name=%s',
			(zone, network)
		)
Beispiel #22
0
	def run(self, params, args):
		hosts = self.getHostnames(args)

		self.beginOutput()

		if len(hosts) == 0:
			output = []
			self.addOutput('', '%s' % output)
			self.endOutput(padChar='')
			return
		elif len(hosts) > 1:
			raise ArgUnique(self, 'host')

		host = hosts[0]

		#
		# first see if there is a storage partition configuration for
		# this specific host
		#
		output = self.call('list.storage.partition', [ host ])
		if output:
			self.addOutput('', '%s' % output)
			self.endOutput(padChar='')
			return

		# 
		# now check at the appliance level
		# 
		appliance = self.getHostAttr(host, 'appliance')

		output = self.call('list.storage.partition', [ appliance ])
		if output:
			self.addOutput('', '%s' % output)
			self.endOutput(padChar='')
			return

		#
		# finally check the global level
		#
		output = self.call('list.storage.partition', ['globalOnly=y'])
		if output:
			self.addOutput('', '%s' % output)
			self.endOutput(padChar='')
			return

		#
		# if we made it here, there is no storage partition
		# configuration for this host
		#
		output = []
		self.addOutput('', '%s' % output)
		self.endOutput(padChar='')
Beispiel #23
0
    def run(self, params, args):

        (networks, name) = self.fillSetNetworkParams(args, 'name')
        if len(networks) > 1:
            raise ArgUnique(self, 'network')

        if ' ' in name:
            raise CommandError(self, 'network name must not contain a space')

        network = networks[0]

        self.db.execute('update subnets set name=%s where name=%s',
                        (name, network))
Beispiel #24
0
    def run(self, params, args):
        if len(args) != 1:
            raise ArgUnique(self, 'box')

        box = args[0]

        if box in self.getBoxNames():
            raise CommandError(self, 'box "%s" exists' % box)

        OS, = self.fillParams([('os', self.os)])

        self.db.execute("""insert into boxes (name, os) values
			('%s', (select id from oses where name='%s'))""" % (box, OS))
Beispiel #25
0
	def run(self, params, args):

		(networks, name) = self.fillSetNetworkParams(args, 'name')
		if len(networks) > 1:
			raise ArgUnique(self, 'network')
					
		if ' ' in name:
			raise CommandError(self, 'network name must not contain a space')

		for network in networks:
			self.db.execute("""
				update subnets set name='%s' where
				subnets.name='%s'
				""" % (name, network))
Beispiel #26
0
	def run(self, params, args):

		(document, ) = self.fillParams([
			('document', None)
		])

		if not document:
			if not args:
				raise ArgRequired(self, 'filename')
			if len(args) > 1:
				raise ArgUnique(self, 'filename')
			document = self.load_file(args[0])

		self.main(document)
Beispiel #27
0
    def run(self, params, args):

        if len(args) != 1:
            raise ArgUnique(self, 'appliance')
        appliance = args[0]

        (longname, node, public) = self.fillParams([('longname', None),
                                                    ('node', ''),
                                                    ('public', 'y')])

        public = self.bool2str(self.str2bool(public))

        if not longname:
            longname = str.capitalize(appliance)

        #
        # check for duplicates
        #
        rows = self.db.execute("""
			select * from appliances where name='%s'
			""" % appliance)
        if rows > 0:
            raise CommandError(self,
                               'appliance "%s" already exists' % appliance)

        #
        # ok, we're good to go
        #
        self.db.execute("""
			insert into appliances (name, longname, public) values
			('%s', '%s', '%s')
			""" % (appliance, longname, public))

        # by default, appliances shouldn't be managed or kickstartable...
        implied_attrs = {'kickstartable': False, 'managed': False}

        # ... but if the user specified node, they probably want those to be True
        if node:
            self.command('add.appliance.attr',
                         [appliance, 'attr=node',
                          'value=%s' % node])
            implied_attrs['kickstartable'] = True
            implied_attrs['managed'] = True

        for attr, value in implied_attrs.items():
            self.command(
                'add.appliance.attr',
                [appliance, 'attr=%s' % attr,
                 'value=%s' % value])
Beispiel #28
0
    def run(self, params, args):
        if len(args) == 0:
            raise ArgRequired(self, 'network')

        if len(args) != 1:
            raise ArgUnique(self, 'network')

        name = args[0]

        if ' ' in name:
            raise CommandError(self, 'network name must not contain a space')

        (address, mask, gateway, mtu, zone, dns,
         pxe) = self.fillParams([('address', None, True), ('mask', None, True),
                                 ('gateway', None), ('mtu', '1500'),
                                 ('zone', name), ('dns', 'n'), ('pxe', 'n')])

        dns = self.str2bool(dns)
        pxe = self.str2bool(pxe)

        # A None gateway is a blank string
        if gateway is None:
            gateway = ''

        # The mtu parameter needs to be an int
        if mtu:
            try:
                mtu = int(mtu)
            except:
                raise ParamType(self, 'mtu', 'integer')

        # Make sure the network doesn't already exist
        if self.db.count('(ID) from subnets where name=%s', (name, )) != 0:
            raise CommandError(self, 'network "%s" exists' % name)

        # Check that we are a valid network
        try:
            if ipaddress.IPv4Network(u"%s/%s" % (address, mask)):
                pass
        except:
            msg = '%s/%s is not a valid network address and subnet mask combination'
            raise CommandError(self, msg % (address, mask))

        # Insert our data
        self.db.execute(
            """
			insert into subnets (name, address, mask, gateway, mtu, zone, dns, pxe)
			values (%s, %s, %s, %s, %s, %s, %s, %s)
		""", (name, address, mask, gateway, mtu, zone, dns, pxe))
Beispiel #29
0
    def run(self, params, args):
        hosts = self.getHostnames(args)

        if len(hosts) != 1:
            raise ArgUnique(self, 'host')

        self.beginOutput()

        # Get the partitions, removing 'source' to keep the existing output structure
        partitions = self.call('list.host.storage.partition', [hosts[0]])
        for partition in partitions:
            partition.pop('source', None)

        self.addOutput('', str(partitions))
        self.endOutput(padChar='')
Beispiel #30
0
	def run(self, params, args):
		switches = self.getSwitchNames(args)
		if not switches:
			raise ArgRequired(self, 'switch')
		elif len(switches) > 1:
			raise ArgUnique(self, 'switch')
		switch = switches[0]

		(host, interface, port) = self.fillParams([
			('host', None),
			('interface', None),
			('port', None)
		])

		hosts = self.getHostnames([host])
		if not hosts:
			raise ParamRequired(self, ('host'))
		elif len(hosts) > 1:
			raise ParamUnique(self, 'host')
		host = hosts[0]

		try:
			port = int(port)
		except:
			raise ParamType(self, 'port', 'integer')

		# Check if the host/port is defined for this switch
		for row in self.call('list.switch.host', [switch]):
			if row['host'] == host and row['port'] == port:
				break
		else:
			raise ArgError(self, 'host/port', f'"{host}/{port}" not found')

		# See if the interface exists for this host
		row = self.db.select("""
			networks.id FROM networks, nodes
			WHERE nodes.name=%s AND networks.device=%s AND networks.node=nodes.id
		""", (host, interface))

		if not row:
			raise CommandError(
				self, f'interface "{interface}" does not exist for host "{host}"'
			)

		self.db.execute("""
			UPDATE switchports SET interface=%s
			WHERE port=%s AND switch=(SELECT id FROM nodes WHERE name=%s)
		""", (row[0][0], port, switch))