summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDan Callaghan <dcallagh@redhat.com>2013-07-26 16:10:43 +1000
committerGerrit Code Review <gerrit@beaker-project.org>2013-10-09 01:57:16 +0000
commita228c67f581dca30186bf13cbf9e8fa2e33af615 (patch)
tree10938e19d02ce2c21d14c3cdf8a20b82ad4349bc
parenta3b99c6ab7efe65f690bf8008957e1c80def00c0 (diff)
/distribution/inventory: extracted beaker-system-scanbeaker-distribution-inventory-1_2-3
-rw-r--r--Tasks/distribution/inventory/Makefile35
-rw-r--r--Tasks/distribution/inventory/disks.py92
-rwxr-xr-xTasks/distribution/inventory/getdriver.sh66
-rw-r--r--Tasks/distribution/inventory/hvm_detect.c86
-rw-r--r--Tasks/distribution/inventory/i18n.py37
-rwxr-xr-xTasks/distribution/inventory/procfs.py453
-rwxr-xr-xTasks/distribution/inventory/pushInventory.py464
-rwxr-xr-xTasks/distribution/inventory/runtest.sh8
-rw-r--r--Tasks/distribution/inventory/software.py62
-rwxr-xr-xTasks/distribution/inventory/utilist.py38
10 files changed, 10 insertions, 1331 deletions
diff --git a/Tasks/distribution/inventory/Makefile b/Tasks/distribution/inventory/Makefile
index 633d674..1545feb 100644
--- a/Tasks/distribution/inventory/Makefile
+++ b/Tasks/distribution/inventory/Makefile
@@ -26,7 +26,7 @@ PACKAGE_NAME=
RELATIVE_PATH=inventory
# Version of the Test. Used with make tag.
-export TESTVERSION=1.1
+export TESTVERSION=1.2
# The combined namespace of the test.
export TEST=/$(TOPLEVEL_NAMESPACE)/$(RELATIVE_PATH)
@@ -39,36 +39,17 @@ export TEST=/$(TOPLEVEL_NAMESPACE)/$(RELATIVE_PATH)
# name, and to improve performance.
.PHONY: all install download clean
-BINFILE=hvm_detect
-hvm_detect: hvm_detect.c
- if which gcc; then \
- gcc $(BINFILE).c -o ./$(BINFILE) ;\
- chmod a+x ./$(BINFILE) ;\
- fi;
-
-# executables to be built should be added here, they will be generated on the system under test.
-BUILT_FILES=
-ifeq ($(shell arch),x86_64)
- BUILT_FILES+=hvm_detect
-endif
-
# data files, .c files, scripts anything needed to either compile the test and/or run it.
-FILES=$(METADATA) runtest.sh Makefile PURPOSE \
- software.py i18n.py disks.py pushInventory.py procfs.py \
- utilist.py getdriver.sh hvm_detect.c
+FILES=$(METADATA) runtest.sh Makefile PURPOSE
run: $(FILES) build
./runtest.sh
-build: $(BUILT_FILES)
+build:
chmod a+x ./runtest.sh
clean: $(TARGET)-clean
- rm -f *~ *.rpm $(BUILT_FILES)
-
-# You may need to add other targets e.g. to build executables from source code
-# Add them here:
-
+ rm -f *~ *.rpm
# Include Common Makefile
include /usr/share/rhts/lib/rhts-make.include
@@ -77,7 +58,7 @@ include /usr/share/rhts/lib/rhts-make.include
$(METADATA): Makefile
@touch $(METADATA)
# Change to the test owner's name
- @echo "Owner: Bill Peck <bpeck@redhat.com>" > $(METADATA)
+ @echo "Owner: Beaker Developers <beaker-devel@lists.fedorahosted.org>" > $(METADATA)
@echo "Name: $(TEST)" >> $(METADATA)
@echo "Path: $(TEST_DIR)" >> $(METADATA)
@echo "License: GPL" >> $(METADATA)
@@ -85,12 +66,8 @@ $(METADATA): Makefile
@echo "TestVersion: $(TESTVERSION)" >> $(METADATA)
@echo "Description: This refreshes the database with the hardware inventory of the machine its run on">> $(METADATA)
@echo "TestTime: 15m" >> $(METADATA)
- @echo "Requires: smolt" >> $(METADATA)
@echo "Requires: kvm" >> $(METADATA)
- @echo "Requires: iasl" >> $(METADATA)
- @echo "Requires: gcc" >> $(METADATA)
@echo "Requires: make" >> $(METADATA)
- @echo "Requires: device-mapper-multipath" >> $(METADATA)
- @echo "Requires: python-ctypes" >> $(METADATA)
+ @echo "Requires: beaker-system-scan" >> $(METADATA)
diff --git a/Tasks/distribution/inventory/disks.py b/Tasks/distribution/inventory/disks.py
deleted file mode 100644
index c66377a..0000000
--- a/Tasks/distribution/inventory/disks.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/python
-
-from ctypes import *
-
-class PedCHSGeometry(Structure):
- _fields_ = [("cylinders", c_int), ("heads", c_int), ("sectors", c_int)]
-
-class PedDevice(Structure):
- pass
-PedDevice._fields_ = [("next", POINTER(PedDevice)),
- ("model", c_char_p),
- ("path", c_char_p),
- ("type", c_int),
- ("sector_size", c_longlong),
- ("phys_sector_size", c_longlong),
- ("length", c_longlong),
- ("open_count", c_int),
- ("read_only", c_int),
- ("external_mode", c_int),
- ("dirty", c_int),
- ("boot_dirty", c_int),
- ("hw_geom", PedCHSGeometry),
- ("bios_geom", PedCHSGeometry),
- ("host", c_short),
- ("did", c_short),
- ("arch_specific", c_void_p),
- ]
-
-class Disk(object):
- def __init__(self, disk):
- self.length = disk.length
- self.size = disk.length * disk.sector_size
- self.sector_size = disk.sector_size
- self.phys_sector_size = disk.phys_sector_size
- self.model = disk.model
-
- def to_dict(self):
- # need to send size as an XML-RPC string as it is likely to overflow
- # the 32-bit size limit for XML-RPC ints
- return dict( size = str(self.size),
- sector_size = self.sector_size,
- phys_sector_size = self.phys_sector_size,
- model = self.model)
-
-class Disks(object):
- def __init__(self):
- """
- """
- self.disks = []
-
- try:
- parted = CDLL("libparted-1.8.so.0")
- except:
- try:
- parted = CDLL("libparted-2.1.so.0")
- except:
- parted = CDLL("libparted.so.0")
-
- parted.ped_device_get_next.restype = POINTER(PedDevice)
- parted.ped_device_probe_all(None)
-
- disk = None
- try:
- while True:
- disk = parted.ped_device_get_next(disk)
- if disk[0].type in [1, 2, 6, 9, 15] and "/dev/sr" not in disk[0].path:
- self.disks.append(Disk(disk[0]))
- except ValueError:
- pass
-
- def __iter__(self):
- return self.disks.__iter__()
-
- def nr_disks(self):
- return len(self.disks)
-
- nr_disks = property(nr_disks)
-
- def disk_space(self):
- diskspace = 0
- for disk in self.disks:
- diskspace += disk.size
- return diskspace
-
- disk_space = property(disk_space)
-
-if __name__ == '__main__':
- disks = Disks()
- for disk in disks:
- print disk.to_dict()
- print disks.nr_disks
- print disks.disk_space
diff --git a/Tasks/distribution/inventory/getdriver.sh b/Tasks/distribution/inventory/getdriver.sh
deleted file mode 100755
index aba103f..0000000
--- a/Tasks/distribution/inventory/getdriver.sh
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/bin/sh
-#
-# Find all modules and drivers for a given class device.
-#
-
-if [ $# != "1" ] ; then
- echo
- echo "Script to display the drivers and modules for a specified sysfs class device"
- echo "usage: $0 <CLASS_NAME>"
- echo
- echo "example usage:"
- echo " $0 sda"
- echo "Will show all drivers and modules for the sda block device."
- echo
- exit 1
-fi
-
-DEV=$1
-
-if test -e "$1"; then
- DEVPATH=$1
-else
- # find sysfs device directory for device
- DEVPATH=$(find /sys/class -name "$1" | head -1)
- test -z "$DEVPATH" && DEVPATH=$(find /sys/block -name "$1" | head -1)
- test -z "$DEVPATH" && DEVPATH=$(find /sys/bus -name "$1" | head -1)
- if ! test -e "$DEVPATH"; then
- exit 1
- fi
-fi
-
-if test -L "$DEVPATH"; then
- # resolve class device link to device directory
- DEVPATH=$(readlink -f $DEVPATH)
-fi
-
-if test -d "$DEVPATH"; then
- # resolve old-style "device" link to the parent device
- PARENT="$DEVPATH";
- while test "$PARENT" != "/"; do
- if test -L "$PARENT/device"; then
- DEVPATH=$(readlink -f $PARENT/device)
- break
- fi
- PARENT=$(dirname $PARENT)
- done
-fi
-
-while test "$DEVPATH" != "/"; do
- DRIVERPATH=
- DRIVER=
- MODULEPATH=
- MODULE=
- if test -e $DEVPATH/driver; then
- DRIVERPATH=$(readlink -f $DEVPATH/driver)
- DRIVER=$(basename $DRIVERPATH)
- echo $DRIVER
- if test -e $DRIVERPATH/module; then
- MODULEPATH=$(readlink -f $DRIVERPATH/module)
- MODULE=$(basename $MODULEPATH)
- echo $MODULE
- fi
- fi
-
- DEVPATH=$(dirname $DEVPATH)
-done
diff --git a/Tasks/distribution/inventory/hvm_detect.c b/Tasks/distribution/inventory/hvm_detect.c
deleted file mode 100644
index 1d20fb8..0000000
--- a/Tasks/distribution/inventory/hvm_detect.c
+++ /dev/null
@@ -1,86 +0,0 @@
-/******************************************************************************
- *
- * Based on XenSource's xen_detect.c file.
- * determines execution on xen HVM or KVM platforms.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-static int pv_context;
-
-static void cpuid(uint32_t idx,
- uint32_t *eax,
- uint32_t *ebx,
- uint32_t *ecx,
- uint32_t *edx)
-{
- asm volatile (
- "test %1,%1 ; jz 1f ; ud2a ; .ascii \"xen\" ; 1: cpuid"
- : "=a" (*eax), "=b" (*ebx), "=c" (*ecx), "=d" (*edx)
- : "0" (idx), "1" (pv_context) );
-}
-
-static int check_for_hvm(void)
-{
- uint32_t eax, ebx, ecx, edx;
- char signature[13];
-
- cpuid(0x40000000, &eax, &ebx, &ecx, &edx);
- *(uint32_t *)(signature + 0) = ebx;
- *(uint32_t *)(signature + 4) = ecx;
- *(uint32_t *)(signature + 8) = edx;
- signature[12] = '\0';
-
- /* is this a kvm guest? */
- if ( !strcmp("KVMKVMKVM", signature) ) {
- printf("KVM guest.\n");
- return 1;
- } else if ( !strcmp("XenVMMXenVMM", signature) ) {
- printf("Xen HVM guest.\n");
- return 1;
- } else if ( !strcmp("Microsoft Hv", signature) ) {
- printf("Microsoft Hv guest.\n");
- return 1;
- } else if ( !strcmp("VMwareVMware", signature) ) {
- printf("VMWare guest.\n");
- return 1;
- } else {
- printf("No KVM or Xen HVM\n");
- return 0;
- }
- return 0;
-}
-
-int main(void)
-{
- /* Check for execution in HVM context. */
- if ( check_for_hvm() )
- return 0;
- else
- return 1;
-
-}
diff --git a/Tasks/distribution/inventory/i18n.py b/Tasks/distribution/inventory/i18n.py
deleted file mode 100644
index a198990..0000000
--- a/Tasks/distribution/inventory/i18n.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# smolt - Fedora hardware profiler
-#
-# Copyright (C) 2007 Mike McGrath
-#
-# 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.
-
-import locale
-try:
- locale.setlocale(locale.LC_ALL, '')
-except locale.Error:
- locale.setlocale(locale.LC_ALL, 'C')
-
-import os
-
-import gettext
-
-if os.path.isdir('po'):
- # if there is a local directory called 'po' use it so we can test
- # without installing
- t = gettext.translation('smolt', 'po', fallback = True)
-
-else:
- t = gettext.translation('smolt', fallback = True)
-
-_ = t.gettext
diff --git a/Tasks/distribution/inventory/procfs.py b/Tasks/distribution/inventory/procfs.py
deleted file mode 100755
index 22f11f9..0000000
--- a/Tasks/distribution/inventory/procfs.py
+++ /dev/null
@@ -1,453 +0,0 @@
-#! /usr/bin/python
-# -*- python -*-
-# -*- coding: utf-8 -*-
-
-import os, time, utilist
-
-VERSION="0.2"
-
-def process_cmdline(pid_info):
- if pid_info.has_key("cmdline"):
- return reduce(lambda a, b: a + " %s" % b, pid_info["cmdline"]).strip()
-
- return pid_info["stat"]["comm"]
-
-class pidstats:
- proc_stat_fields = [ "pid", "comm", "state", "ppid", "pgrp", "session",
- "tty_nr", "tpgid", "flags", "minflt", "cminflt",
- "majflt", "cmajflt", "utime", "stime", "cutime",
- "cstime", "priority", "nice", "num_threads",
- "itrealvalue", "starttime", "vsize", "rss",
- "rlim", "startcode", "endcode", "startstack",
- "kstkesp", "kstkeip", "signal", "blocked",
- "sigignore", "sigcatch", "wchan", "nswap",
- "cnswap", "exit_signal", "processor",
- "rt_priority", "policy",
- "delayacct_blkio_ticks" ]
-
- def __init__(self, basedir = "/proc"):
- self.basedir = basedir
- self.processes = {}
- self.reload()
-
- def __getitem__(self, key):
- return self.processes[key]
-
- def __delitem__(self, key):
- # not clear on why this can fail, but it can
- try:
- del self.processes[key]
- except:
- pass
-
- def keys(self):
- return self.processes.keys()
-
- def has_key(self, key):
- return self.processes.has_key(key)
-
- def read_stat_entry(self, pid):
- f = open("%s/%d/stat" % (self.basedir, pid))
- tags = {}
- fields = f.readline().strip().split()
- nr_fields = min(len(fields), len(self.proc_stat_fields))
- for i in range(nr_fields):
- tags[self.proc_stat_fields[i]] = fields[i]
- tags["comm"] = tags["comm"].strip('()')
- f.close()
- return tags
-
- def read_status_entry(self, pid):
- f = open("%s/%d/status" % (self.basedir, pid))
- tags = {}
- for line in f.readlines():
- fields = line.split(":")
- tags[fields[0]] = fields[1].strip()
- f.close()
- return tags
-
- def reload(self):
- del self.processes
- self.processes = {}
- pids = os.listdir(self.basedir)
- for spid in pids:
- try:
- pid = int(spid)
- except:
- continue
-
- self.processes[pid] = {}
- try:
- self.processes[pid]["stat"] = self.read_stat_entry(pid)
- except:
- del self.processes[pid]
- continue
-
- try:
- self.processes[pid]["status"] = self.read_status_entry(pid)
- except:
- del self.processes[pid]
-
- def reload_threads(self):
- for pid in self.processes.keys():
- try:
- threads = pidstats("/proc/%d/task/" % pid)
- # remove thread leader
- del threads[pid]
- if not threads.keys():
- continue
- self.processes[pid]["threads"] = threads
- except OSError:
- # process vanished, remove it
- del self.processes[pid]
-
- def load_cmdline(self):
- for pid in self.processes.keys():
- if self.processes[pid].has_key("cmdline"):
- continue
- try:
- f = file("/proc/%d/cmdline" % pid)
- line = f.readline()
- if line:
- self.processes[pid]["cmdline"] = line.strip().split('\0')
- f.close()
- except IOError:
- # process vanished, remove it
- del self.processes[pid]
-
- def find_by_name(self, name):
- name = name[:15]
- pids = []
- for pid in self.processes.keys():
- if self.processes[pid]["stat"]["comm"] == name:
- pids.append(pid)
- return pids
-
- def find_by_regex(self, regex):
- pids = []
- for pid in self.processes.keys():
- if regex.match(self.processes[pid]["stat"]["comm"]):
- pids.append(pid)
- return pids
-
- def find_by_cmdline_regex(self, regex):
- pids = []
- for pid in self.processes.keys():
- if regex.match(process_cmdline(self.processes[pid])):
- pids.append(pid)
- return pids
-
- def get_per_cpu_rtprios(self, basename):
- cpu = 0
- priorities=""
- processed_pids = []
- while True:
- name = "%s/%d" % (basename, cpu)
- pids = self.find_by_name(name)
- if not pids or len([n for n in pids if n not in processed_pids]) == 0:
- break
- for pid in pids:
- priorities += "%s," % self.processes[pid]["stat"]["rt_priority"]
- processed_pids += pids
- cpu += 1
-
- priorities = priorities.strip(',')
- return priorities
-
- def get_rtprios(self, name):
- cpu = 0
- priorities=""
- processed_pids = []
- while True:
- pids = self.find_by_name(name)
- if not pids or len([n for n in pids if n not in processed_pids]) == 0:
- break
- for pid in pids:
- priorities += "%s," % self.processes[pid]["stat"]["rt_priority"]
- processed_pids += pids
- cpu += 1
-
- priorities = priorities.strip(',')
- return priorities
-
-class interrupts:
- def __init__(self):
- self.interrupts = {}
- self.reload()
-
- def __getitem__(self, key):
- return self.interrupts[str(key)]
-
- def keys(self):
- return self.interrupts.keys()
-
- def has_key(self, key):
- return self.interrupts.has_key(str(key))
-
- def reload(self):
- del self.interrupts
- self.interrupts = {}
- f = open("/proc/interrupts")
-
- for line in f.readlines():
- line = line.strip()
- fields = line.split()
- if fields[0][:3] == "CPU":
- self.nr_cpus = len(fields)
- continue
- irq = fields[0].strip(":")
- self.interrupts[irq] = {}
- self.interrupts[irq] = self.parse_entry(fields[1:], line)
- try:
- nirq = int(irq)
- except:
- continue
- self.interrupts[irq]["affinity"] = self.parse_affinity(nirq)
-
- f.close()
-
- def parse_entry(self, fields, line):
- dict = {}
- dict["cpu"] = []
- dict["cpu"].append(int(fields[0]))
- nr_fields = len(fields)
- if nr_fields >= self.nr_cpus:
- dict["cpu"] += [int(i) for i in fields[1:self.nr_cpus]]
- if nr_fields > self.nr_cpus:
- dict["type"] = fields[self.nr_cpus]
- # look if there are users (interrupts 3 and 4 haven't)
- if nr_fields > self.nr_cpus + 1:
- dict["users"] = [a.strip() for a in line[line.index(fields[self.nr_cpus + 1]):].split(',')]
- else:
- dict["users"] = []
- return dict
-
- def parse_affinity(self, irq):
- if os.getuid() != 0:
- return
- try:
- f = file("/proc/irq/%s/smp_affinity" % irq)
- line = f.readline()
- f.close()
- return utilist.bitmasklist(line, self.nr_cpus)
- except IOError:
- return [ 0, ]
-
- def find_by_user(self, user):
- for i in self.interrupts.keys():
- if self.interrupts[i].has_key("users") and \
- user in self.interrupts[i]["users"]:
- return i
- return None
-
-class cmdline:
- def __init__(self):
- self.options = {}
- self.parse()
-
- def parse(self):
- f = file("/proc/cmdline")
- for option in f.readline().strip().split():
- fields = option.split("=")
- if len(fields) == 1:
- self.options[fields[0]] = True
- else:
- self.options[fields[0]] = fields[1]
-
- f.close()
-
-class cpuinfo:
- def __init__(self, filename="/proc/cpuinfo"):
- self.tags = {}
- self.nr_cpus = 0
- self.sockets = []
- self.parse(filename)
-
- def __getitem__(self, key):
- return self.tags[key.lower()]
-
- def keys(self):
- return self.tags.keys()
-
- def parse(self, filename):
- f = file(filename)
- for line in f.readlines():
- line = line.strip()
- if len(line) == 0:
- continue
- fields = line.split(":")
- tagname = fields[0].strip().lower()
- if tagname == "processor":
- self.nr_cpus += 1
- continue
- elif tagname == "core id":
- continue
- self.tags[tagname] = fields[1].strip()
- if tagname == "physical id":
- socket_id = self.tags[tagname]
- if socket_id not in self.sockets:
- self.sockets.append(socket_id)
-
- f.close()
- self.nr_sockets = self.sockets and len(self.sockets) or \
- (self.nr_cpus / ("siblings" in self.tags and int(self.tags["siblings"]) or 1))
- self.nr_cores = ("cpu cores" in self.tags and int(self.tags["cpu cores"]) or 1) * self.nr_sockets
-
-class smaps_lib:
- def __init__(self, lines):
- fields = lines[0].split()
- self.vm_start, self.vm_end = map(lambda a: int(a, 16), fields[0].split("-"))
- self.perms = fields[1]
- self.offset = int(fields[2], 16)
- self.major, self.minor = fields[3].split(":")
- self.inode = int(fields[4])
- if len(fields) > 5:
- self.name = fields[5]
- else:
- self.name = None
- self.tags = {}
- for line in lines[1:]:
- fields = line.split()
- self.tags[fields[0][:-1].lower()] = int(fields[1])
-
- def __getitem__(self, key):
- return self.tags[key.lower()]
-
- def keys(self):
- return self.tags.keys()
-
-
-class smaps:
- def __init__(self, pid):
- self.pid = pid
- self.entries = []
- self.reload()
-
- def parse_entry(self, f, line):
- lines = []
- if not line:
- line = f.readline().strip()
- if not line:
- return
- lines.append(line)
- while True:
- line = f.readline()
- if not line:
- break
- line = line.strip()
- if len(line.split()) < 4:
- lines.append(line)
- else:
- break
- self.entries.append(smaps_lib(lines))
- return line
-
- def reload(self):
- f = file("/proc/%d/smaps" % self.pid)
- line = None
- while True:
- line = self.parse_entry(f, line)
- if not line:
- break
- f.close()
- self.nr_entries = len(self.entries)
-
- def find_by_name_fragment(self, fragment):
- result = []
- for i in range(self.nr_entries):
- if self.entries[i].name and \
- self.entries[i].name.find(fragment) >= 0:
- result.append(self.entries[i])
-
- return result
-
-class cpustat:
- def __init__(self, fields):
- self.name = fields[0]
- (self.user,
- self.nice,
- self.system,
- self.idle,
- self.iowait,
- self.irq,
- self.softirq,
- self.steal) = [int(i) for i in fields[1:9]]
- if len(fields) > 8:
- self.guest = int(fields[8])
-
-class cpusstats:
- def __init__(self):
- self.entries = []
- self.time = None
- self.hertz = os.sysconf(2)
- self.reload()
-
- def __iter__(self):
- return iter(self.entries)
-
- def __getitem__(self, key):
- return self.entries[key]
-
- def __len__(self):
- return len(self.entries)
-
- def reload(self):
- last_entries = self.entries
- self.entries = []
- f = file("/proc/stat")
- for line in f.readlines():
- fields = line.strip().split()
- if fields[0][:3].lower() != "cpu":
- continue
- self.entries.append(cpustat(fields))
- f.close()
- last_time = self.time
- self.time = time.time()
- if len(last_entries) > 0:
- delta_sec = self.time - last_time
- interval_hz = delta_sec * self.hertz
- for cpu in range(len(last_entries)):
- curr = self.entries[cpu]
- prev = last_entries[cpu]
- delta = (curr.user - prev.user) + \
- (curr.nice - prev.nice) + \
- (curr.system - prev.system)
- curr.usage = (delta / interval_hz) * 100
- if curr.usage > 100:
- curr.usage = 100
-
-if __name__ == '__main__':
- import sys
-
- ints = interrupts()
-
- for i in ints.interrupts.keys():
- print "%s: %s" % (i, ints.interrupts[i])
-
- options = cmdline()
- for o in options.options.keys():
- print "%s: %s" % (o, options.options[o])
-
- cpu = cpuinfo()
- print "\ncpuinfo data: %d processors" % cpu.nr_cpus
- for tag in cpu.keys():
- print "%s=%s" % (tag, cpu[tag])
-
- print "smaps:\n" + ("-" * 40)
- s = smaps(int(sys.argv[1]))
- for i in range(s.nr_entries):
- print "%#x %s" % (s.entries[i].vm_start, s.entries[i].name)
- print "-" * 40
- for a in s.find_by_name_fragment(sys.argv[2]):
- print a["Size"]
-
- ps = pidstats()
- print ps[1]
-
- cs = cpusstats()
- while True:
- time.sleep(1)
- cs.reload()
- for cpu in cs:
- print "%s: %d" % (cpu.name, cpu.usage)
- print "-" * 10
diff --git a/Tasks/distribution/inventory/pushInventory.py b/Tasks/distribution/inventory/pushInventory.py
deleted file mode 100755
index af3b029..0000000
--- a/Tasks/distribution/inventory/pushInventory.py
+++ /dev/null
@@ -1,464 +0,0 @@
-#!/usr/bin/python
-# Copyright (c) 2006 Red Hat, Inc. All rights reserved. This copyrighted material
-# is made available to anyone wishing to use, modify, copy, or
-# redistribute it subject to the terms and conditions of the GNU General
-# Public License v.2.
-#
-# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-# Author: Bill Peck
-#
-
-import sys, getopt
-import xmlrpclib
-import string
-import os
-import commands
-import pprint
-import math
-import re
-import shutil
-import glob
-import tempfile
-from subprocess import Popen, PIPE
-
-sys.path.append('.')
-sys.path.append("/usr/share/smolt/client")
-import smolt
-from disks import Disks
-import procfs
-
-USAGE_TEXT = """
-Usage: pushInventory.py [-d] [[-h <HOSTNAME>] [-S server]]
-"""
-
-def push_inventory(method, hostname, inventory):
- session = xmlrpclib.Server(lab_server, allow_none=True)
- try:
- resp = getattr(session, method)(hostname, inventory)
- if(resp != 0) :
- raise NameError, "ERROR: Pushing Inventory for host %s." % hostname
- except:
- raise
-
-def check_for_virt_iommu():
-
- virt_iommu = 0
- cpu_info = smolt.read_cpuinfo()
- cpu_info_pat = re.compile("x86")
-
- if not cpu_info_pat.search(cpu_info['platform']):
- #only x86 boxes support virt iommu
- return 0
-
- #test what type of system we are on
- if os.path.exists("/sys/firmware/acpi/tables/DMAR"):
- # alright we are on an Intel vt-d box
- hwu = False
- ba = False
-
- # iasl can't read directly from /sys
- shutil.copyfile('/sys/firmware/acpi/tables/DMAR', 'DMAR.dat')
-
- # create ascii file
- os.system("iasl -d DMAR.dat > /dev/null 2>&1")
- if os.path.exists("DMAR.dsl"):
- f = open("DMAR.dsl", 'r')
-
- #look for keywords to validate ascii file
- hwu_pat = re.compile ('Hardware Unit')
- ba_pat = re.compile ('Base Address')
- ba_inv_pat = re.compile ('0000000000000000|FFFFFFFFFFFFFFFF')
-
- for line in f.readlines():
- if hwu_pat.search(line):
- hwu = True
- if ba_pat.search(line):
- if ba_inv_pat.search(line):
- print "VIRT_IOMMU: Invalid Base address: 0's or F's"
- else:
- ba = True
- if not hwu:
- print "VIRT_IOMMU: No Hardware Unit"
- elif not ba:
- print "VIRT_IOMMU: No Base Address"
- else:
- virt_iommu = 1
- else:
- print "VIRT_IOMMU: Failed to create DMAR.dsl"
-
- elif os.path.exists("/sys/firmware/acpi/tables/IVRS"):
- # alright we are on an AMD iommu box
- # we don't have a good way to validate this
- virt_iommu = 1
-
- return virt_iommu
-
-def kernel_inventory():
- data = {}
- data['VIRT_IOMMU'] = False
-
- ##########################################
- # check for virtual iommu/vt-d capability
- # if this passes, assume we pick up sr-iov for free
-
- if check_for_virt_iommu():
- data['VIRT_IOMMU'] = True
-
- ##########################################
- # determine which stroage controller has a disk behind it
- path = "/sys/block"
- virt_pat = re.compile('virtual')
- floppy_pat = re.compile('fd[0-9]')
- sr_pat = re.compile('sr[0-9]')
- for block in glob.glob( os.path.join(path, '*')):
- #skip read only/floppy devices
- if sr_pat.search(block) or floppy_pat.search(block):
- continue
-
- #skip block devices that don't point to a device
- if not os.path.islink(block + "/device"):
- continue
- sysfs_link = os.readlink(block + "/device")
-
- #skip virtual devices
- if virt_pat.search(sysfs_link):
- continue
-
- #cheap way to create an absolute path, there is probably a better way
- sysfs_path = sysfs_link.replace('../..','/sys')
-
- #start abusing hal to give us the info we want
- cmd = 'hal-find-by-property --key linux.sysfs_path --string %s' % sysfs_path
- status,udi = commands.getstatusoutput(cmd)
- if status:
- print "DISK_CONTROLLER: hal-find-by-property failed: %d" % status
- continue
-
- while udi:
- cmd = 'hal-get-property --udi %s --key info.linux.driver 2>/dev/null' % udi
- status, driver = commands.getstatusoutput(cmd)
- if status == 0 and driver != "sd" and driver != "sr":
- #success
- data['DISK_CONTROLLER'] = driver
- break
-
- #get the parent and try again
- cmd = 'hal-get-property --udi %s --key info.parent' % udi
- status,udi = commands.getstatusoutput(cmd)
- if status:
- print "DISK_CONTROLLER: hal-get-property failed: %d" % status
- break
-
- if not udi:
- print "DISK_CONTROLLER: can not determine driver for %s" %block
-
- ##########################################
- # determine if machine is using multipath or not
-
- #ok, I am really lazy
- #remove the default blacklist in /etc/multipath.conf
- os.system("sed -i '/^blacklist/,/^}$/d' /etc/multipath.conf")
-
- #restart multipathd to see what it detects
- #this spits out errors if the root device is on a
- #multipath device, I guess ignore for now and hope the code
- #correctly figures things out
- os.system("service multipathd restart")
-
- #the multipath commands will display the topology if it
- #exists otherwise nothing
- #filter out vbds and single device paths
- status, mpaths = commands.getstatusoutput("multipath -ll")
- mp = False
- if status:
- print "MULTIPATH: multipath -ll failed with %d" % status
- else:
- count = 0
- mpath_pat = re.compile(" dm-[0-9]* ")
- sd_pat = re.compile(" sd[a-z]")
- for line in mpaths.split('\n'):
- #reset when a new section starts
- if mpath_pat.search(line):
- # found at least one mp instance, declare success
- if count > 1:
- mp = True
- break
- count = 0
-
- #a hit! increment to indicate this
- if sd_pat.search(line):
- count = count + 1
-
- if mp == True:
- data['DISK_MULTIPATH'] = True
- else:
- data['DISK_MULTIPATH'] = False
-
- return data
-
-def legacy_inventory(inv):
- # Take the gathered inventory data, fill legacy key/value schema with it
- # and gather any missing bits.
- data = {}
- data['MODULE'] = []
- data['HVM'] = False
- data['DISK'] = []
- data['BOOTDISK'] = []
- data['DISKSPACE'] = 0
- data['NR_DISKS'] = 0
- data['NR_ETH'] = 0
- data['NR_IB'] = 0
-
- data['ARCH'] = inv['Arch'][0]
- data['CPUFAMILY'] = "%s" % inv['Cpu']['family']
- data['CPUVENDOR'] = inv['Cpu']['vendor']
- data['CPUMODEL'] = inv['Cpu']['modelName']
- data['CPUMODELNUMBER'] = "%s" % inv['Cpu']['model']
- data['PROCESSORS'] = inv['Cpu']['processors']
- data['VENDOR'] = inv['vendor']
- data['MODEL'] = inv['model']
- data['FORMFACTOR'] = inv['formfactor']
- data['CPUFLAGS'] = inv['Cpu']['CpuFlags']
- data['PCIID'] = ["%s:%s" % (d['vendorID'], d['deviceID']) for d in inv['Devices'] if d['bus'] == 'pci']
- data['USBID'] = ["%s:%s" % (d['vendorID'], d['deviceID']) for d in inv['Devices'] if d['bus'] == 'usb']
-
- # The below data (and kernel_inventory()) has not (yet) made it to the new schema
- # (and formfactor above)
-
- modules = commands.getstatusoutput('/sbin/lsmod')[1].split('\n')[1:]
- for module in modules:
- data['MODULE'].append(module.split()[0])
-
- # Find Active Storage Driver(s)
- bootdisk = None
- bootregex = re.compile(r'/dev/([^ ]+) on /boot')
- disks = commands.getstatusoutput('/bin/mount')[1].split('\n')[1:]
- for disk in disks:
- if bootregex.search(disk):
- # Replace / with !, needed for cciss
- bootdisk = bootregex.search(disk).group(1).replace('/','!')
-
- if bootdisk:
- drivers = commands.getstatusoutput('./getdriver.sh %s' % bootdisk)[1].split('\n')[1:]
- for driver in drivers:
- data['BOOTDISK'].append(driver)
-
- # Find Active Network interface
- iface = None
- for line in commands.getstatusoutput('route -n')[1].split('\n'):
- if line.find('0.0.0.0') == 0:
- iface = line.split()[-1:][0] #eth0, eth1, etc..
- if iface:
- drivers = commands.getstatusoutput('./getdriver.sh %s' % iface)[1].split('\n')
- if len(drivers) == 1:
- data['NETWORK'] = drivers[0]
- else:
- data['NETWORK'] = drivers[1:][0]
-
- # disk sizes are converted to GiB in key-values for backwards compatibility
- disks = Disks()
- data['DISK'] = []
- for disk in disks:
- data['DISK'].append(disk.size / 1024**2)
- data['DISKSPACE'] = disks.disk_space / 1024**2
- data['NR_DISKS'] = disks.nr_disks
-
- # finding out eth and ib interfaces...
- eth_pat = re.compile ('^ *eth\d+:')
- ib_pat = re.compile ('^ *ib\d+:')
- for line in open("/proc/net/dev", "r"):
- if eth_pat.match(line):
- data['NR_ETH'] += 1
- elif ib_pat.match(line):
- data['NR_IB'] += 1
-
- # checking for whether or not the machine is hvm-enabled.
- caps = ""
- if os.path.exists("/sys/module/kvm_amd") or \
- os.path.exists("/sys/module/kvm_intel"):
- data['HVM'] = True
- elif os.path.exists('/proc/pal/cpu0/processor_info'): # ia64
- for line in open('/proc/pal/cpu0/processor_info', 'r'):
- if re.match('Virtual machine features.*: On', line):
- data['HVM'] = True
-
- if os.path.exists("/root/NETBOOT_METHOD.TXT"):
- data['NETBOOT_METHOD'] = open('/root/NETBOOT_METHOD.TXT', 'r').readline()[:-1]
- return data
-
-def read_inventory():
- # get the data from SMOLT but modify it for how RHTS expects to see it
- # Eventually we'll switch over to SMOLT properly.
- data = {}
- flags = []
- data['Devices'] = []
-
- procCpu = procfs.cpuinfo()
- smoltCpu = smolt.read_cpuinfo()
- memory = smolt.read_memory()
- profile = smolt.Hardware()
-
- arch = smoltCpu['platform']
-
- if arch in ["i386", "x86_64"]:
- for cpuflag in procCpu.tags['flags'].split(" "):
- flags.append(cpuflag)
- cpu = dict(vendor = smoltCpu['type'],
- model = int(procCpu.tags['model']),
- modelName = smoltCpu['model'],
- speed = float(procCpu.tags['cpu mhz']),
- processors = int(procCpu.nr_cpus),
- cores = int(procCpu.nr_cores),
- sockets = int(procCpu.nr_sockets),
- CpuFlags = flags,
- family = int(smoltCpu['model_number']),
- stepping = int(procCpu.tags['stepping']),
- )
- elif arch in ["ppc", "ppc64"]:
- cpu = dict(vendor = "IBM",
- model = 0,
- modelName = str(procCpu.tags['cpu']),
- speed = float(re.findall('\d+.+\d+', procCpu.tags['clock'])[0]),
- processors = int(procCpu.nr_cpus),
- cores = 0,
- sockets = 0,
- CpuFlags = flags,
- family = 0,
- stepping = 0,
- )
- elif arch in ["s390", "s390x"]:
- for cpuflag in procCpu.tags['features'].split(" "):
- flags.append(cpuflag)
- proc = dict([tuple(s.strip() for s in kv.split('=')) for kv in procCpu.tags['processor 0'].split(',')])
- cpu = dict(vendor = str(procCpu.tags['vendor_id']),
- model = 0,
- modelName = str(proc['machine']),
- processors = int(procCpu.tags['# processors']),
- cores = 0,
- sockets = 0,
- CpuFlags = flags,
- family = 0,
- speed = 0,
- stepping = 0,
- )
- elif arch == "ia64":
- for cpuflag in procCpu.tags['features'].split(","):
- flags.append(cpuflag.strip())
- cpu = dict(vendor = smoltCpu['type'],
- model = int(procCpu.tags['model']),
- modelName = smoltCpu['model'],
- speed = float(procCpu.tags['cpu mhz']),
- processors = int(procCpu.nr_cpus),
- cores = int(procCpu.nr_cores),
- sockets = int(procCpu.nr_sockets),
- CpuFlags = flags,
- family = int(smoltCpu['model_rev']),
- stepping = 0,
- )
-
- data['Cpu'] = cpu
- data['Arch'] = [arch]
- data['vendor'] = "%s" % profile.host.systemVendor
- data['model'] = "%s" % profile.host.systemModel
- data['formfactor'] = "%s" % profile.host.formfactor
- data['memory'] = int(memory['ram'])
-
- disklist = []
- diskdata = {}
- disks = Disks()
- for disk in Disks():
- disklist.append(disk.to_dict())
- diskdata['Disks'] = disklist
-
- data['Disk'] = diskdata
-
- if hasattr(profile.host, 'numaNodes'):
- data['Numa'] = {'nodes': profile.host.numaNodes}
- else:
- data['Numa'] = {
- 'nodes': len(glob.glob('/sys/devices/system/node/node*')), #: number of NUMA nodes in the system, or 0 if not supported
- }
-
- if os.path.exists('./hvm_detect'):
- hypervisor = Popen(['./hvm_detect'], stdout=PIPE).communicate()[0]
- hvm_map = {"No KVM or Xen HVM\n" : None,
- "KVM guest.\n" : u'KVM',
- "Xen HVM guest.\n" : u'Xen',
- "Microsoft Hv guest.\n" : u'HyperV',
- "VMWare guest.\n" : u'VMWare',
- }
- data['Hypervisor'] = hvm_map[hypervisor]
-
- for VendorID, DeviceID, SubsysVendorID, SubsysDeviceID, Bus, Driver, Type, Description in profile.deviceIter():
- device = dict ( vendorID = "%04x" % (VendorID and VendorID or 0),
- deviceID = "%04x" % (DeviceID and DeviceID or 0),
- subsysVendorID = "%04x" % (SubsysVendorID and SubsysVendorID or 0),
- subsysDeviceID = "%04x" % (SubsysDeviceID and SubsysDeviceID or 0),
- bus = str(Bus),
- driver = str(Driver),
- type = str(Type),
- description = str(Description))
- data['Devices'].append(device)
-
- return data
-
-def usage():
- print USAGE_TEXT
- sys.exit(-1)
-
-def main():
- global lab_server, hostname
-
- lab_server = None
- hostname = None
- debug = 0
-
- if ('LAB_SERVER' in os.environ.keys()):
- lab_server = os.environ['LAB_SERVER']
- if ('HOSTNAME' in os.environ.keys()):
- hostname = os.environ['HOSTNAME']
-
- args = sys.argv[1:]
- try:
- opts, args = getopt.getopt(args, 'dh:S', ['server='])
- except:
- usage()
- for opt, val in opts:
- if opt in ('-d', '--debug'):
- debug = 1
- if opt in ('-h', '--hostname'):
- hostname = val
- if opt in ('-S', '--server'):
- lab_server = val
-
- inventory = read_inventory()
- legacy_inv = legacy_inventory(inventory)
- legacy_inv.update(kernel_inventory())
- del inventory['formfactor']
- if debug:
- print "Legacy inventory:\n%s\nData:\n%s" % (
- pprint.pformat(legacy_inv), pprint.pformat(inventory))
- else:
- if not hostname:
- print "You must specify a hostname with the -h switch"
- sys.exit(1)
-
- if not lab_server:
- print "You must specify a lab_server with the -S switch"
- sys.exit(1)
-
- push_inventory("legacypush", hostname, legacy_inv)
- push_inventory("push", hostname, inventory)
-
-
-if __name__ == '__main__':
- main()
- sys.exit(0)
-
diff --git a/Tasks/distribution/inventory/runtest.sh b/Tasks/distribution/inventory/runtest.sh
index 0b2edc8..fa50c50 100755
--- a/Tasks/distribution/inventory/runtest.sh
+++ b/Tasks/distribution/inventory/runtest.sh
@@ -33,16 +33,16 @@ rlJournalStart
rlRun "modprobe kvm" 0,1
rlRun "modprobe kvm_amd" 0,1
rlRun "modprobe kvm_intel" 0,1
- rlRun "yum -y install smolt"
- rlAssertRpm "smolt"
+ rlRun "yum -y install beaker-system-scan"
+ rlAssertRpm "beaker-system-scan"
rlPhaseEnd
rlPhaseStartTest
if [ -n "$INVENTORY_DEBUG" ] ; then
- rlRun -l "./pushInventory.py -d >inventory.out"
+ rlRun -l "beaker-system-scan -d >inventory.out"
rlFileSubmit inventory.out
else
- rlRun -l "./pushInventory.py --server $server -h $hostname"
+ rlRun -l "beaker-system-scan --server $server -h $hostname"
fi
rlPhaseEnd
rlJournalPrintText
diff --git a/Tasks/distribution/inventory/software.py b/Tasks/distribution/inventory/software.py
deleted file mode 100644
index e8443a0..0000000
--- a/Tasks/distribution/inventory/software.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# smolt - Fedora hardware profiler
-#
-# Copyright (C) 2007 Mike McGrath
-#
-# 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.
-
-import os
-import commands
-import re
-import sys
-
-def read_lsb_release():
- if os.access('/usr/bin/lsb_release', os.X_OK):
- return commands.getstatusoutput('/usr/bin/lsb_release')[1].strip()
- return ''
-
-initdefault_re = re.compile(r':(\d+):initdefault:')
-
-def read_runlevel():
- defaultRunlevel = 'Unknown'
- try:
- inittab = file('/etc/inittab').read()
- match = initdefault_re.search(inittab)
- if match:
- defaultRunlevel = match.group(1)
- except IOError:
- try:
- defaultRunlevel = commands.getstatusoutput('/sbin/runlevel')[1].split()[1].strip()
- except:
- sys.stderr.write('Cannot Determine Runlevel')
- return defaultRunlevel.strip()
-
-def read_os():
- try:
- return file('/etc/redhat-release').read().strip()
- except IOError:
- pass
- try:
- return file('/etc/SuSE-release').read().split('\n')[0].strip()
- except IOError:
- pass
- try:
- #this is a bit of a kludge, as /etc/debian-release is
- #somewhat incomplete in what it gives you
- #I also figure this should work better in
- #ubuntu
- return file('/etc/issue.net').read().strip()
- except IOError:
- pass
- return 'Unknown'
diff --git a/Tasks/distribution/inventory/utilist.py b/Tasks/distribution/inventory/utilist.py
deleted file mode 100755
index 23fa171..0000000
--- a/Tasks/distribution/inventory/utilist.py
+++ /dev/null
@@ -1,38 +0,0 @@
-#! /usr/bin/python
-# -*- python -*-
-# -*- coding: utf-8 -*-
-
-def hexbitmask(l, nr_entries):
- hexbitmask = []
- bit = 0
- mask = 0
- for entry in range(nr_entries):
- if entry in l:
- mask |= (1 << bit)
- bit += 1
- if bit == 32:
- bit = 0
- hexbitmask.insert(0, mask)
- mask = 0
-
- if bit < 32 and mask != 0:
- hexbitmask.insert(0, mask)
-
- return hexbitmask
-
-def bitmasklist(line, nr_entries):
- fields = line.strip().split(",")
- bitmasklist = []
- entry = 0
- for i in range(len(fields) - 1, -1, -1):
- mask = int(fields[i], 16)
- while mask != 0:
- if mask & 1:
- bitmasklist.append(entry)
- mask >>= 1
- entry += 1
- if entry == nr_entries:
- break
- if entry == nr_entries:
- break
- return bitmasklist