Ejemplo n.º 1
0
class ConfigureRepos(QtWidgets.QDialog):
    """
    Class to manage the set password dialog...

    @author: Roy Nielsen
    """

    doneConfigure = QtCore.pyqtSignal()

    def __init__(self, conf, parent=None):
        """
        Initialization method...

        @author: Roy Nielsen
        """
        super(ConfigureRepos, self).__init__(parent)

        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        #####
        # initialization of class variables.
        self.conf = conf
        self.environ = Environment()
        self.conf.loggerSelf()
        self.logger = self.conf.getLogger()
        #self.logger = self.conf.get_logger()
        self.logger.log(lp.DEBUG, str(self.logger))
        self.runWith = RunWith(self.logger)
        self.libc = getLibc(self.logger)
        self.chkApp = CheckApplicable(self.environ, self.logger)
        macOsWhiteListApplicable = {
            'type': 'white',
            'os': {
                'Mac OS X': ['10.0.0', 'r', '20.12.10']
            }
        }

        #####
        # Handle button box
        self.ui.buttonBox.button(
            QtWidgets.QDialogButtonBox.Cancel).clicked.connect(self.close)
        self.ui.buttonBox.button(
            QtWidgets.QDialogButtonBox.Ok).clicked.connect(self.okDone)

        #####
        # Handle other buttons
        self.ui.downloadReposButton.clicked.connect(self.downloadRepos)
        self.ui.prepareIsoButton.clicked.connect(self.prepareIso)
        self.ui.gitResetHardButton.clicked.connect(self.resetRepos)
        self.ui.gitPullButton.clicked.connect(self.updateRepos)

        if self.chkApp.isApplicable(macOsWhiteListApplicable):
            self.ui.prepareIsoButton.clicked.connect(self.prepareIso)
        else:
            self.ui.prepareIsoButton.hide()
            self.ui.macosCheckBox.hide()

        #####
        # default boxcutter repo path
        self.reposRoot = self.conf.getRepoRoot()

        #####
        # Future features
        self.ui.winCheckBox.hide()
        self.ui.label_2.hide()
        self.ui.leReposPath.hide()
        self.ui.proxyButton.hide()

        #####
        # Future features
        self.ui.winCheckBox.hide()
        self.ui.label_2.hide()
        self.ui.leReposPath.hide()
        self.ui.proxyButton.hide()

        self.git = "/usr/bin/git"

        #####
        # repos
        self.repos2process = []

        self.getSelected()

    def okDone(self):
        '''
        '''
        self.getSelected()

        #####
        # Validate that the repos selected have a directory in the reporoot
        if self.repos2process:
            for repo in self.repos2process:
                if not os.path.isdir(repo):
                    break
            self.processGitCommand('clone')

        self.doneConfigure.emit()
        self.accept

    def getSelected(self):
        '''
        '''
        if self.ui.debianCheckBox.isChecked():
            self.repos2process.append("debian")
        if self.ui.ubuntuCheckBox.isChecked():
            self.repos2process.append("ubuntu")
        if self.ui.bsdCheckBox.isChecked():
            self.repos2process.append("bsd")
        if self.ui.macosCheckBox.isChecked():
            self.repos2process.append("macos")
        if self.ui.fedoraCheckBox.isChecked():
            self.repos2process.append("fedora")
        if self.ui.centosCheckBox.isChecked():
            self.repos2process.append("centos")
        if self.ui.oracleCheckBox.isChecked():
            self.repos2process.append("oraclelinux")
        if self.ui.winCheckBox.isChecked():
            self.repos2process.append("windows")

        self.logger.log(lp.DEBUG,
                        "Repos to process: " + str(self.repos2process))

    def downloadRepos(self, subcommand=""):
        '''
        Slot to determine how to process the download repos button

        @author: Roy Nielsen
        '''
        QtWidgets.QMessageBox.information(self, "Information",
                                          "...Downloading repos...",
                                          QtWidgets.QMessageBox.Ok)
        self.processGitCommand("clone")

    def resetRepos(self):
        '''
        Slot to determine how to reset repos via the git reset --hard button

        @author: Roy Nielsen
        '''
        QtWidgets.QMessageBox.information(self, "Information",
                                          "...Resetting repos...",
                                          QtWidgets.QMessageBox.Ok)
        self.processGitCommand(["reset", "--hard"])

    def updateRepos(self):
        '''
        Slot to determine how to update repos via the git pull button

        @author: Roy Nielsen
        '''
        QtWidgets.QMessageBox.information(self, "Information",
                                          "...Updating repos...",
                                          QtWidgets.QMessageBox.Ok)
        self.processGitCommand("pull")

    def processGitCommand(self, subcommand=""):
        '''
        Process the git commands via the appropriately called slot

        @author: Roy Nielsen
        '''
        QtWidgets.QMessageBox.information(self, "Information",
                                          "...Processing Repos...",
                                          QtWidgets.QMessageBox.Ok)
        repos2process = []

        self.getSelected()

        #####
        # mkdirs reporoot
        if not os.path.exists(self.reposRoot):
            try:
                os.makedirs(self.reposRoot)
            except OSError, err:
                self.logger.log(lp.INFO, traceback.format_exc())
                raise (err)

        #####
        # Get and set the proxy if there is one
        shellEnviron = os.environ.copy()
        proxy = self.conf.getProxy()
        httpsProxy = self.conf.getHttpsProxy()
        httpProxy = self.conf.getHttpProxy()
        ftpProxy = self.conf.getFtpProxy()
        rsyncProxy = self.conf.getRsyncProxy()
        noProxy = self.conf.getNoProxy()

        if proxy and isinstance(proxy, basestring):
            shellEnviron['http_proxy'] = proxy
            shellEnviron['https_proxy'] = proxy
            shellEnviron['ftp_proxy'] = proxy
            shellEnviron['rsync_proxy'] = proxy
        if httpProxy and isinstance(httpProxy, basestring):
            shellEnviron['http_proxy'] = httpProxy
        if httpsProxy and isinstance(httpsProxy, basestring):
            shellEnviron['https_proxy'] = httpsProxy
        if ftpProxy and isinstance(ftpProxy, basestring):
            shellEnviron['ftp_proxy'] = ftpProxy
        if rsyncProxy and isinstance(rsyncProxy, basestring):
            shellEnviron['rsync_proxy'] = rsyncProxy
        if noProxy and isinstance(noProxy, basestring):
            shellEnviron['no_proxy'] = noProxy

        #####
        # loop through repos and download the ones that have been checked.
        for repo in self.repos2process:
            if not os.path.exists(self.reposRoot + "/" + repo):
                subcommand = "clone"
            returnDir = os.getcwd()
            if not 'clone' == subcommand:
                os.chdir(self.reposRoot + "/" + repo)
            else:
                os.chdir(self.reposRoot)
            self.logger.log(lp.DEBUG, str(os.getcwd()))

            #####
            # Assign the right "subcommand" to the command to be processed
            if isinstance(subcommand, basestring) and subcommand:
                if re.match("clone", subcommand):
                    cmd = [
                        self.git, subcommand,
                        "https://github.com/boxcutter/" + repo + ".git"
                    ]
                else:
                    cmd = [self.git, subcommand]
            if isinstance(subcommand, list) and subcommand:
                cmd = [self.git] + subcommand

            #####
            # Set and execute the built command
            self.runWith.setCommand(cmd, env=shellEnviron)
            output, error, retcode = self.runWith.communicate()

            self.logger.log(lp.DEBUG, "OUT: " + str(output))
            self.logger.log(lp.DEBUG, "ERR: " + str(error))
            self.logger.log(lp.DEBUG, "RETCODE: " + str(retcode))

            os.chdir(returnDir)
Ejemplo n.º 2
0
class RamDisk(object):
    """
    """
    def __init__(self, size=0, mountpoint=False, logger=False, environ=False):
        """
        """
        #####
        # Version/timestamp is
        # <YYYY><MM><DD>.<HH><MM><SS>.<microseconds>
        # in UTC time
        self.module_version = '20160224.032043.009191'
        if not logger:
            self.logger = CyLogger()
        else:
            self.logger = logger
        if not environ:
            self.environ = Environment()
        else:
            self.environ = environ
        self.chkApp = CheckApplicable(self.environ, self.logger)

    ###########################################################################

    def createRamdisk(self, *args, **kwargs):
        """
        """
        #####
        # Check applicability to the current OS
        macApplicable = {
            'type': 'white',
            'family': ['darwin'],
            'os': {
                'Mac OS X': ['10.8', '+']
            }
        }
        macApplicableHere = self.chkApp.isApplicable(macApplicable)

        linuxApplicable = {'type': 'white', 'family': ['linux']}
        linuxApplicableHere = self.chkApp.isApplicable(linuxApplicable)

        if linuxApplicableHere:
            from .linuxTmpfsRamdisk import RamDisk
            self.ramdisk = RamDisk(*args, **kwargs)
        elif macApplicableHere:
            from .macRamdisk import RamDisk
            self.ramdisk = RamDisk(*args, **kwargs)
        else:
            raise NotValidForThisOS("Ramdisk not available here...")

    ###########################################################################

    def getRamdisk(self):
        """
        """
        return self.ramdisk

    ###########################################################################

    def unionOver(self, *args, **kwargs):
        """
        """
        success = False
        success = self.ramdisk.unionOver(*args, **kwargs)
        return success

    ###########################################################################

    def umount(self, *args, **kwargs):
        """
        """
        success = False
        success = self.ramdisk.umount(*args, **kwargs)
        return success

    ###########################################################################

    def getVersion(self):
        """
        """
        return self.ramdisk.getVersion()

    ###########################################################################

    def getDevice(self):
        """
        Getter for the device name the ramdisk is using

        Must be over-ridden to provide OS/Method specific functionality

        @author: Roy Nielsen
        """
        return self.ramdisk.getDevice()

    ###########################################################################

    def getMountPoint(self):
        """
        Getter for the mount point name the ramdisk is using

        Must be over-ridden to provide OS/Method specific functionality

        @author: Roy Nielsen
        """
        return self.ramdisk.getMountPoint()

    ###########################################################################

    def setDevice(self, device=None):
        """
        Setter for the device so it can be ejected.

        Must be over-ridden to provide OS/Method specific functionality

        @author: Roy Nielsen
        """
        self.ramdisk.setDevice(device)
class VirtualMachineBuilder(QtWidgets.QMainWindow):
    """
    Class to manage the dialog...

    @author: Roy Nielsen
    """
    def __init__(self, conf, parent=None):
        """
        Initialization method...

        @author: Roy Nielsen
        """
        super(VirtualMachineBuilder, self).__init__(parent)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #####
        # initialization of class variables.
        self.conf = conf
        self.conf.loggerSelf()
        self.logger = self.conf.getLogger()
        self.environ = Environment()
        #self.logger = self.conf.get_logger()
        self.logger.log(lp.DEBUG, str(self.logger))
        self.runWith = RunWith(self.logger)
        self.libc = getLibc(self.logger)

        #####
        # Set label states
        self.ui.packerLabel.setText(
            "( <a href='https://www.packer.io'>https://www.packer.io</a> - Download and install packer separately )"
        )
        self.ui.boxcutterLabel.setText(
            "( <a href='https://github.com/boxcutter'>https://github.com/boxcutter</a> - Clone repos separately )"
        )

        #####
        # Handle button box
        #
        self.ui.buttonBox.button(
            QtWidgets.QDialogButtonBox.Close).clicked.connect(
                self.closeApplication)
        self.ui.buttonBox.button(
            QtWidgets.QDialogButtonBox.Ok).clicked.connect(self.processVm)

        #####
        # Rename Save button
        self.ui.buttonBox.button(
            QtWidgets.QDialogButtonBox.Save).setText("Configure Repos")
        btn = self.ui.buttonBox.button(QtWidgets.QDialogButtonBox.Save)
        btn.clicked.connect(self.configureRepos)

        #####
        # Rename Apply button
        self.ui.buttonBox.button(
            QtWidgets.QDialogButtonBox.Apply).setText("Install packer")
        btnTwo = self.ui.buttonBox.button(QtWidgets.QDialogButtonBox.Apply)
        btnTwo.clicked.connect(self.installPacker)
        btnTwo.hide()

        self.chkApp = CheckApplicable(self.environ, self.logger)
        self.macOsBlackListApplicable = {
            'type': 'black',
            'os': {
                'Mac OS X': ['10.0.0', 'r', '20.12.10']
            }
        }
        self.linuxWhitelistApplicable = {'type': 'white', 'family': 'linux'}
        self.freebsdWhitelistApplicable = {
            'type': 'white',
            'family': 'freebsd'
        }
        self.macosWhitelistApplicable = {'type': 'white', 'family': 'darwin'}
        #openbsdWhitelistApplicable = {}
        #windowsWhitelistApplicable = {}

        #####
        # Set up the configure dialog
        self.configRepos = ConfigureRepos(self.conf)
        self.configRepos.setWindowTitle("Configure Repos")

        #####
        # Connect the configure 'done' signal to the refreshFamilyComboBox slot
        self.configRepos.doneConfigure.connect(self.refreshFamilyComboBox)

        #####
        # Signal/slot to deal with osFamily combo box change
        self.ui.osFamily.currentIndexChanged.connect(self.osFamilySelected)

        self.refreshFamilyComboBox()
        self.osFamilySelected(0)

        self.logger.log(lp.DEBUG, "Done with VirtualMachineBuilder init...")

    def setOpenExternalLinks(self, set_state=True):
        """
        Use the OS method of opening Links

        @author: Roy Nielsen
        """
        success = False
        if isinstance(set_state, bool):
            if set_state is True:
                self.ui.packerLabel.setOpenExternalLinks(True)
                self.ui.boxcutterLabel.setOpenExternalLinks(True)
                self.logger.log(lp.DEBUG, "Browser links activated...")
                success = True
            else:
                self.ui.packerLabel.setOpenExternalLinks(False)
                self.ui.boxcutterLabel.setOpenExternalLinks(False)
                self.logger.log(lp.DEBUG, "Browser links deactivated...")
                success = True
        else:
            self.logger.log(lp.WARNING, "Invalid value passed in to " + \
                                        "this method: " + str(set_state))

        return success

    def refreshFamilyComboBox(self):
        '''
        Determine what to put in the ComboBoxes
        '''
        #####
        # Fill the OS combo box
        validOSs = [
            "debian", "ubuntu", "bsd", "macos", "fedora", "centos",
            "oraclelinux"
        ]
        if self.chkApp.isApplicable(self.macOsBlackListApplicable):
            validOSs.remove('macos')

        self.repoRoot = self.conf.getRepoRoot()

        try:
            self.osSavailable = os.listdir(self.repoRoot)
        except OSError, err:
            os.makedirs(self.repoRoot)
            self.osSavailable = os.listdir(self.repoRoot)

        self.logger.log(lp.DEBUG, str(self.osSavailable))

        #####
        # temporarily disconnect Signal/slot to deal with osFamily combo box
        #
        # It appears that adding values to the combo box changes the combo
        # box index, which throws the currentIndexChanged signal, therefore
        # we have to disconnect the signal, add the combo box values, then
        # set up the signal again.
        #
        self.ui.osFamily.currentIndexChanged.disconnect(self.osFamilySelected)

        if self.osSavailable:
            self.osComboBoxValues = []
            self.ui.osFamily.clear()
            self.ui.osFamily.addItems(self.osSavailable)
            self.osComboBoxValues += self.osSavailable
        else:
            self.configureRepos()
            return 0

        self.logger.log(lp.DEBUG, str(self.osComboBoxValues))

        self.osVersComboBox = {}
        repoPaths = []
        files = []

        self.logger.log(lp.DEBUG, str(self.osComboBoxValues))

        for mydir in self.osComboBoxValues:
            mydirlist = os.listdir(self.conf.getRepoRoot() + "/" + mydir)
            for item in mydirlist:
                if re.match("^\w+\d+.*\.json", item) and \
                   re.search("%s"%mydir, item):
                    files.append(item)
                    self.logger.log(lp.DEBUG, str(item))
                elif re.match("^ol\d+.*\.json", item):
                    files.append(item)
                    self.logger.log(lp.DEBUG, str(item))
                elif re.match("^win.*\.json", item):
                    files.append(item)
                    self.logger.log(lp.DEBUG, str(item))

            self.osVersComboBox[mydir] = files
            files = []
        self.logger.log(lp.DEBUG, str(self.osVersComboBox))

        #####
        # Signal/slot to deal with osFamily combo box change
        self.ui.osFamily.currentIndexChanged.connect(self.osFamilySelected)