예제 #1
0
def doReset():
    activeVersion = getActiveMongoVersion()

    # if not a version activated, then abort
    if activeVersion == '':
        print('No currently activated MongoDB Version')
        return False

    # Admin required
    if not lxtools.getIfAdmin():
        print(config.getMessage('REQUIREADMIN'))
        return False

    # If folder exits but not an symlink, then abort
    if activeVersion is False:
        print('ERROR: Folder is not a symlink.')
        return False

    print('Deactivate MongoDB v' + activeVersion)

    # Run Script file
    pkginfo = lxtools.loadjson(os.path.join(mongosymlink, config.getConfigKey('configfile')))
    package.runScript(pkginfo, ['remove', 'safe', 'hidden'])

    # Check if *all* symbolic links removed, when not remove it
    symlinks = config.getConfigKey('mongo.links', None)
    if symlinks:
        for names in symlinks:
            target = os.path.join(symlinks[names]['target'], names)

            if os.path.exists(target) and lxtools.getIfSymbolicLink(target):
                os.remove(target)

    if not resetMongo():
        return False
예제 #2
0
def doUpgrade():
    if os.path.isdir(mongosymlink) and not lxtools.getIfSymbolicLink(mongosymlink):
        # Upgrade
        print('Upgrade needed...')

        # Check if admin
        if not lxtools.getIfAdmin():
            print(config.getMessage('REQUIREADMIN'))
            return False

        # Load package file
        pkginfo = lxtools.loadjson(os.path.join(mongosymlink, config.getConfigKey('configfile')))
        mongoversion = pkginfo.get('version', None)

        # Execute Patches
        patches = config.getConfigKey('mongo.patches', None)
        patch.doPatch(mongosymlink, patches)

        # Stop Service/Daemon and de-register Service/Daemon, safe-remove
        print('Stop Service/Daemon...')
        package.runScript(pkginfo, ['remove', 'safe', 'hidden'])

        # Check if *all* symbolic links removed, when not remove it
        symlinks = config.getConfigKey('mongo.links', {})
        if symlinks:
            for names in symlinks:
                target = symlinks[names]['target']

                if os.path.exists(target) and lxtools.getIfSymbolicLink(target):
                    os.remove(target)

        # Move Directory to mongodb/{version}/
        print('Move files...')
        mongodir = os.path.join(mongobasedir, mongoversion)

        # Create new mongodb directory and move installed version
        os.makedirs(mongobasedir)
        os.rename(mongosymlink, mongodir)

        # Create Symlink
        print('Create symlinks...')
        lxtools.setDirectoryLink(mongosymlink, mongodir)

        # Start Daemon/Service
        print('Start Service/Daemon...')
        package.runScript(pkginfo, ['install', 'hidden'])

        print('Done')
        return True
    else:
        return None
예제 #3
0
def resetNode():
    # If User Admin?
    if not lxtools.getIfAdmin():
        print(config.getMessage('REQUIREADMIN'))
        return False

    # Windows
    if sys.platform == 'win32':
        # Delete old LINK Directory when exits
        if os.path.exists(lxBinPath):
            # If Directory a Symbolic Link
            if not lxtools.getIfSymbolicLink(lxBinPath):
                print(
                    'ERROR: Target Directory is not a link and can not be removed.'
                )
                return False

            # Remove Link
            try:
                os.remove(lxBinPath)
            except BaseException as e:
                print('ERROR:', e)
                return False

        return True

    # Unix
    if sys.platform.startswith('linux') or sys.platform == 'darwin':
        links = config.getConfigKey('node.links')

        # Unlink old version
        for names in links:
            target = os.path.join(links[names]['target'], names)
            options = links[names].get('options', [])

            # Check if link, when true then remove it
            if os.path.islink(target):
                try:
                    os.remove(target)
                except BaseException as e:
                    print('ERROR:', e)
                    return False
            else:
                # Check if "fullname" a real existing path/file, then raise Exception
                if os.path.isdir(target) or os.path.isfile(target):
                    if 'remove_if_exists' in options:
                        try:
                            print('Remove Directory', target)
                            lxtools.rmDirectory(target)
                        except BaseException as e:
                            print('ERROR:', e)
                            return False
                    else:
                        print('UUh, a target is not a link...', target)
                        return False

        return True

    # No operation for that system :(
    return False
예제 #4
0
def getIfMongoVersionAvailable(mongoversion):
    if os.path.exists(os.path.join(mongobasedir, mongoversion)):
        pkginfo = lxtools.loadjson(
            os.path.join(mongobasedir, mongoversion, config.getConfigKey('configfile')),
            reporterror=False
        )

        # has package file
        if pkginfo:
            binlist = pkginfo.get('binary', None)

            # Check if binarys exists
            if binlist:
                if isinstance(binlist, str):
                    binlist = [binlist]

                if isinstance(binlist, list):
                    for binname in binlist:
                        if not os.path.exists(os.path.join(mongobasedir, mongoversion, binname)):
                            return False

                return True

    # No installed
    return False
예제 #5
0
def upgrade():
    rootdir = lxtools.getBaboonStackDirectory()
    prev_catalogfilename = os.path.join(rootdir, config.lxPreviousPackage)

    # No Upgrade required
    if not os.path.isfile(prev_catalogfilename):
        return False

    # Check if admin
    if not lxtools.getIfAdmin():
        print('Catalog Upgrade required!', config.getMessage('REQUIREADMIN'))
        return True

    catalogdata = lxtools.loadjson(prev_catalogfilename, False)
    pkgdata = catalogdata.get('packages', {})

    for pkgname in pkgdata:
        if getIfPackageInstalled(pkgdata[pkgname]):
            pkgfilename = os.path.join(rootdir, pkgdata[pkgname].get('dirname'), config.getConfigKey('configfile'))
            if not os.path.isfile(pkgfilename):
                pkginfo = pkgdata[pkgname].copy()

                # Add some informations
                pkginfo['name'] = pkgname
                pkginfo['bbsversion'] = catalogdata.get('version', '0.0.0')

                if not lxtools.savejson(pkgfilename, pkginfo):
                    print('Upgrade failure...')
                    return False

    os.remove(prev_catalogfilename)
    print('Upgrade successfull...')
    return True
예제 #6
0
def resetNode():
    # If User Admin?
    if not lxtools.getIfAdmin():
        print(config.getMessage('REQUIREADMIN'))
        return False

    # Windows
    if sys.platform == 'win32':
        # Delete old LINK Directory when exits
        if os.path.exists(lxBinPath):
            # If Directory a Symbolic Link
            if not lxtools.getIfSymbolicLink(lxBinPath):
                print('ERROR: Target Directory is not a link and can not be removed.')
                return False

            # Remove Link
            try:
                os.remove(lxBinPath)
            except BaseException as e:
                print('ERROR:', e)
                return False

        return True

    # Unix
    if sys.platform.startswith('linux') or sys.platform == 'darwin':
        links = config.getConfigKey('node.links')

        # Unlink old version
        for names in links:
            target = os.path.join(links[names]['target'], names)
            options = links[names].get('options', [])

            # Check if link, when true then remove it
            if os.path.islink(target):
                try:
                    os.remove(target)
                except BaseException as e:
                    print('ERROR:', e)
                    return False
            else:
                # Check if "fullname" a real existing path/file, then raise Exception
                if os.path.isdir(target) or os.path.isfile(target):
                    if 'remove_if_exists' in options:
                        try:
                            print('Remove Directory', target)
                            lxtools.rmDirectory(target)
                        except BaseException as e:
                            print('ERROR:', e)
                            return False
                    else:
                        print('UUh, a target is not a link...', target)
                        return False

        return True

    # No operation for that system :(
    return False
예제 #7
0
def getRemoteCatalog(localcatalogonly=False):
    catalog = dict()
    bbscatalogfile = os.path.join(lxtools.getBaboonStackDirectory(), 'baboonstack.package.conf')

    # First, try to read local package file if not exists then
    if os.path.exists(bbscatalogfile):
        catalogdata = lxtools.loadjson(bbscatalogfile)
        packages = catalogdata.get('packages', {})
        for pkgname in packages:
            catalog[pkgname] = {
                'version': [packages[pkgname].get('version')],
                'source': 'catalog',
                'info': packages[pkgname]
            }

        if localcatalogonly:
            return catalog

    # Download Filelist
    data = lxtools.getRemoteData(config.lxServer + '/')

    # If Exception occured
    if data == -1:
        return []

    # Gets the Package Name Mask for this OS
    packagenamemask = str(
        config.getConfigKey('packagemask')
    ).format(
        lxtools.getOsArchitecture()
    )

    # Get the available packages for this OS
    filelist = regex.findall('">(' + packagenamemask + ')<\/a', data)
    filelist.sort()

    # Add all versions
    for entry in filelist:
        a = os.path.splitext(entry)[0].split('-')

        if a[0] == 'baboonstack':
            continue

        if a[0] not in catalog:
            catalog[a[0]] = {
                'version': [],
                'source': 'server'
            }

        catalog[a[0]]['version'].append(a[1][1:])
        catalog[a[0]]['source'] = 'server'

    return catalog
예제 #8
0
def getLatestRemoteVersion():
    # Download Filelist
    data = lxtools.getRemoteData(config.lxServer + '/')

    # If Exception occured
    if data == -1:
        return ''

    # Get the available BaboonStack Packages for this OS
    packageName = str(config.getConfigKey('update', '')).format(lxtools.getOsArchitecture())
    versionList = regex.findall('">(' + packageName + ')<\/a', data)
    versionList.sort()

    # If list empty?
    if len(versionList) == 0:
        return ''

    # Returns the LAST entry
    return versionList.pop()
예제 #9
0
# Global
msiexecArguments = 'msiexec /quiet /a {0} /qb targetdir={1}'

# NodeJS
tempNodeDir = os.path.join(tempfile.gettempdir(), 'node')

# Node Directory
lxBasePath = lxtools.getBaboonStackDirectory()
lxNodePath = os.path.join(lxBasePath, 'node')

if sys.platform == 'win32':
    lxBinPath = os.path.join(lxBasePath, 'bbs', 'Node')
else:
    # Unix Systems are below
    lxBinPath = os.path.join(config.getConfigKey('node.links.node.target'), 'node')

# CleanUp
def cleanUp():
    # Remove temporary internet files
    lxtools.cleanUpTemporaryFiles()

    # Clear temporary node directory
    if os.path.exists(tempNodeDir):
        lxtools.rmDirectory(tempNodeDir)

# Returns if nodeversion the correct format
def getIfNodeVersionFormat(nodeversion):
    return regex.match('[0-9]+\.[0-9]+\.[0-9]+', nodeversion) is not None

# Returns if nodeversion installed
예제 #10
0
def doUpdate():
    # Get latest Version on Server
    print('Check for update...')
    versionRemote = getLatestRemoteVersion()

    # No files?
    if versionRemote == '':
        print('No Baboonstack Update available...')
        return False

    # Get local version
    packageName = str(config.getConfigKey('update', '')).replace('{0}', '{1}').replace('.*', 'v{0}')
    versionLocal = packageName.format(config.lxVersion, lxtools.getOsArchitecture())

    # Update required?
    if not versionRemote.lower() > versionLocal.lower():
        # No Update required
        print('No Baboonstack Update available...')
        return False

    # Check if admin
    if not lxtools.getIfAdmin():
        print(config.getMessage('REQUIREADMIN'))
        return False

    # Download Update
    print('Update {0} => {1}...'.format(versionLocal, versionRemote))

    # Build
    url = config.lxServer + '/' + versionRemote
    localPacket = os.path.join(tempfile.gettempdir(), versionRemote)

    # Download Packet with Progressbar
    result = lxtools.getRemoteFile(url, localPacket)

    # Exception or canceled
    if result == -1:
        return False

    # Verify (if availabled)
    print('Get Checksum from Server...')
    remoteChecksum = getRemoteChecksum(versionRemote)

    if remoteChecksum != '':
        print('Verify Checksum...')
        localChecksum = lxtools.getSHAChecksum(localPacket)

        # Check Checksum
        if (localChecksum == remoteChecksum):
            print('Checksum correct...')
        else:
            print('Checksum missmatch... Abort!')
            print('Filename  ' + versionRemote)
            print('Remote SHA' + remoteChecksum)
            print('Local  SHA' + localChecksum)
            return False

    # Run Installation and exit under Windows
    if sys.platform == 'win32':
        print('Execute installer...')
        os.startfile(localPacket)
        print('Installation routine will start separately, exit now...')
        return True

    # Under Unix we must do all stuff
    if sys.platform.startswith('linux') or sys.platform == 'darwin':
        tempupdatedir = os.path.join(tempfile.gettempdir(), localPacket.rstrip('.tar.gz'))

        # Extract TAR Package
        try:
            tar = tarfile.open(localPacket)
            tar.extractall(tempupdatedir)
            tar.close()
        except BaseException as e:
            lxtools.cleanUpTemporaryFiles()
            print('ERROR:', e)
            return False

        updatescriptfile = os.path.join(tempupdatedir, 'lxupdate.sh')
        if os.path.exists(updatescriptfile):
            # Rename package catalog file
            if os.path.exists(config.lxPackage):
                os.rename(
                    os.path.join(lxtools.getBaboonStackDirectory(), config.lxPackage),
                    os.path.join(lxtools.getBaboonStackDirectory(), config.lxPreviousPackage)
                )

            # Execute Update script
            print('Execute Update...')
            subprocess.Popen([updatescriptfile, tempupdatedir, lxtools.getBaboonStackDirectory()])
            sys.exit(23)
        else:
            # Clean up temporary internet files
            lxtools.cleanUpTemporaryFiles()

            # Clean up temporary update files
            lxtools.rmDirectory(tempupdatedir)

        return True

    # No Update method found for that system
    return False
예제 #11
0
def setLocalNodeVersion(nodeversion):
    # Retrive local available Version
    versionList = getLocalNodeVersionList(nodeversion)

    # No Version found
    if len(versionList) == 0:
        print('Sorry, no existing Node version {0} found locally.'.format(
            nodeversion))
        return False

    # Get the last element from list
    nodeversion = versionList.pop()

    # Inform User about the version choose (only if more items exists)
    if len(versionList) != 0:
        print('Take Node v{0}...'.format(nodeversion))

    # If version already active?
    if getIfNodeVersionActive(nodeversion):
        print('Node v{0} already active.'.format(nodeversion))
        return False

    # Get original Path
    nodeDir = os.path.join(lxNodePath, nodeversion)

    # If Node Version installed?
    if not os.path.exists(nodeDir):
        print('Node v{0} not found locally.'.format(nodeDir))
        return False

    # If User Admin?
    if not lxtools.getIfAdmin():
        print(config.getMessage('REQUIREADMIN'))
        return False

    # Windows
    if sys.platform == 'win32':
        # Delete old LINK Directory when exits
        if not resetNode():
            return False

        # Set new link
        if not lxtools.setDirectoryLink(lxBinPath, nodeDir):
            print('ERROR while link to new Node Version.')
            return False

        print('Switched to Node v{0}...'.format(nodeversion))
        return True

    # Unix
    if sys.platform.startswith('linux') or sys.platform == 'darwin':
        links = config.getConfigKey('node.links')

        # check if all required source directories exits
        pathexists = True
        for names in links:
            linkoptions = links[names].get('options', [])

            if 'absolute_source' in linkoptions:
                fullname = links[names]['source']
            else:
                fullname = os.path.join(nodeDir, links[names]['source'], names)

            # absolute_source
            # Check, if required source not found
            if 'no_source_check' not in linkoptions and not os.path.isfile(
                    fullname) and not os.path.isdir(fullname):
                print('ERROR: Required Element "' +
                      os.path.join(links[names]['source'], names) + '" in "' +
                      nodeDir + '" not found...')
                pathexists = False

        # A required Source was not found, abort
        if not pathexists:
            return False

        # Unlink old version
        if not resetNode():
            return False

        # link new version
        for names in links:
            linkoptions = links[names].get('options', [])

            if 'absolute_source' in linkoptions:
                source = links[names]['source']
            else:
                source = os.path.join(nodeDir, links[names]['source'], names)

            target = os.path.join(links[names]['target'], names)
            #source = os.path.join(nodeDir, links[names]['source'], names)

            # Link
            if not lxtools.setDirectoryLink(target, source):
                raise Exception('Link creation failed!\n' + source + ' => ' +
                                target)

        # run Cache fix
        runCacheFix()

        # show hint
        print('Note: Force a ´npm update -g´ to update global modules...')
        print('\nSwitched to Node v{0}...'.format(nodeversion))

        return True

    return False
예제 #12
0
# Global
msiexecArguments = 'msiexec /quiet /a {0} /qb targetdir={1}'

# NodeJS
tempNodeDir = os.path.join(tempfile.gettempdir(), 'node')

# Node Directory
lxBasePath = lxtools.getBaboonStackDirectory()
lxNodePath = os.path.join(lxBasePath, 'node')

if sys.platform == 'win32':
    lxBinPath = os.path.join(lxBasePath, 'bbs', 'Node')
else:
    # Unix Systems are below
    lxBinPath = os.path.join(config.getConfigKey('node.links.node.target'),
                             'node')


# CleanUp
def cleanUp():
    # Remove temporary internet files
    lxtools.cleanUpTemporaryFiles()

    # Clear temporary node directory
    if os.path.exists(tempNodeDir):
        lxtools.rmDirectory(tempNodeDir)


# Returns if nodeversion the correct format
def getIfNodeVersionFormat(nodeversion):
예제 #13
0
def doChange(version):
    activeVersion = getActiveMongoVersion()

    # Admin required
    if not lxtools.getIfAdmin():
        print(config.getMessage('REQUIREADMIN'))
        return False

    # If folder exits but not an symlink, then abort
    if activeVersion is False:
        print('ERROR: Folder is not a symlink.')
        return False

    # Version already active
    if activeVersion == version:
        print('Version', version, 'already active.')
        return False

    # If version locally available
    if not getIfMongoVersionAvailable(version):
        print('Version', version, 'not available locally.')
        return False

    # Check if selected version currently activ in pidlist
    pidfile = 'mongo-' + version + '.pids'
    pidlist = lxtools.loadFileFromUserSettings(pidfile, returntype=[])

    if len(pidlist) != 0:
        # Get a list with active pids from a list with pids
        alive = lxtools.getActiveProcessFromPidList(pidlist)

        if len(alive) != 0:
            print('Version is in use and can not be registered as a service.')
            return False

    # if version already set, then deactivate
    if activeVersion != '':
        doReset()

    # Mongo dir
    mongodir = os.path.join(mongobasedir, version)

    # Create Symlink
    print('Activate Mongo v' + version)
    lxtools.setDirectoryLink(mongosymlink, mongodir)

    # Run Script file
    pkginfo = lxtools.loadjson(os.path.join(mongosymlink, config.getConfigKey('configfile')))
    package.runScript(pkginfo, ['install', 'hidden'])

    # Check if *all* symbolic links successfully linked
    symlinks = config.getConfigKey('mongo.links', None)

    if symlinks is not None:
        print('Create symlinks...')
        for names in symlinks:
            source = os.path.join(mongosymlink, symlinks[names]['source'], names)
            target = os.path.join(symlinks[names]['target'], names)

            # Link
            if not lxtools.setDirectoryLink(target, source):
                raise Exception('Link creation failed!\n' + source + ' => ' + target)

    print('\nDone, nice!')
    pass
예제 #14
0
def doInstall(version, options):
    print("Install mongo version " + version + "...")

    # Check if correct version
    if not getIfMongoVersionFormat(version):
        print('The specified string is not a correct mongo version format.')
        return False

    # Check if already installed
    if getIfMongoVersionAvailable(version):
        print('Version already installed, Abort!')
        return False

    # Check if admin
    if not lxtools.getIfAdmin():
        print(config.getMessage('REQUIREADMIN'))
        return False

    fullmongodir = os.path.join(mongobasedir, version)

    # Download mongo binary
    pkgurl = config.getConfigKey('mongo.package.' + lxtools.getOsArchitecture(), '').format(version)
    pkgfile = tempfile.mktemp('', 'bbs_pkg')
    pkgpath = tempfile.mkdtemp('', 'bbs_pkg')

    # Download mongo helper
    hlpurl = config.getConfigKey('mongo.helper.' + lxtools.getOsArchitecture(), '').format(version)
    hlpfile = tempfile.mktemp('', 'bbs_pkg')
    hlppath = tempfile.mkdtemp('', 'bbs_pkg')

    # Get mongo binarys
    print('Download Mongo binarys...')
    result = lxtools.getRemoteFile(
        pkgurl,
        pkgfile
    )

    if result == -1:
        print('Error while downloading Mongo Binarys. Version really exists?')
        return -1

    # Get Helper file
    print('Download Mongo helpers...')
    result = lxtools.getRemoteFile(
        hlpurl,
        hlpfile
    )

    if result == -1:
        print('Error while downloading Mongo Helpers. Try again later.')
        return -1

    # Extract files
    print('Extract files...')
    lxtools.doExtract(pkgfile, pkgpath)
    lxtools.doExtract(hlpfile, hlppath)

    # Move and Merge files
    print('Move files...')

    # Create target directory
    if not os.path.exists(fullmongodir):
        os.makedirs(fullmongodir)

    fileslist = []

    # Move helper files
    fileslist += lxtools.moveDirectory(hlppath, fullmongodir)

    # Move *all* directories to target directory
    dir_moved = False
    for name in os.listdir(pkgpath):
        if os.path.isdir(os.path.join(pkgpath, name)):
            fileslist += lxtools.moveDirectory(os.path.join(pkgpath, name), fullmongodir)
            dir_moved = True

    if not dir_moved:
        print('Sorry, no files from binary archive was moved!')
        return False

    # Save filelist as files.lst
    if len(fileslist) != 0:
        lstname = os.path.join(fullmongodir, 'files.lst')

        try:
            fileslst = open(lstname, 'w')
            fileslst.write('\n'.join(fileslist))
            fileslst.close()
        except BaseException as e:
            print('Error while saving files.lst!')
            print(e)

    # Clen up
    print('Clean up...')
    lxtools.rmDirectory(pkgpath)
    lxtools.rmDirectory(hlppath)

    # Done
    print('Done...')

    # User want to not switch
    if 'noswitch' in options:
        return

    if 'force' in options:
        key = 'y'
    else:
        key = lxtools.readkey('Would you like to activate the new Mongo version?')

    if key == 'y':
        doChange(version)
예제 #15
0
def install(pkgname, options=list()):
    if pkgname is None:
        return False

    # if pkgname is list, then install multiple
    if isinstance(pkgname, list):
        pkgcnt = 0
        for name in pkgname:
            print('Install package "' + name + '"...')
            if install(name, options):
                pkgcnt += 1
            print('')

        print(' {0} of {1} packages successfully installed'.format(str(pkgcnt), str(len(pkgname))))
        return True

    # Install ALL packages?
    if pkgname == '':
        if 'force' not in options and 'ask' not in options:
            options.append('ask')

        pkgname = []
        for pkg in localcatalog:
            # Only install if not installed locally
            if not localcatalog[pkg].getIfInstalled():
                pkgname.append(pkg.get('name', None))

        if len(pkgname) == 0:
            print('Sorry, no packages available to install.')
            return False

        # Rerun
        return install(pkgname, options)

    #
    # Start install single package
    #

    # Check, if package available
    if pkgname not in remotecatalog:
        print('Unknow Package "' + pkgname + '"...')
        return False

    # pkginfo = {}

    # Collect pkginfo and if package already installed
    if pkgname in localcatalog:
        if localcatalog[pkgname].getIfInstalled():
            print('Package "' + pkgname + '" already installed locally...')
            return False

    pkgdata = remotecatalog[pkgname]
    latestversion = getLastVersion(pkgdata)
    fullpackagename = str(config.getConfigKey('package')).format(
        pkgname,
        latestversion,
        lxtools.getOsArchitecture()
    )

    print('Source:', pkgdata.get('source', '<unknow>'))

    # Get catalog info
    # if pkgdata['source'] == 'catalog':
    pkginfo = pkgdata.get('info', {})

    # Check if admin
    if not lxtools.getIfAdmin():
        print(config.getMessage('REQUIREADMIN'))
        return False

    # Ask
    if 'ask' in options:
        key = lxtools.readkey('Do you really want to install "' + pkgname + '"...', 'Yn')

        if key == 'n':
            return False

    # If Download require
    if pkginfo.get('nodownload', False) is True:
        # No Download require, then create dir and exit
        basedir = os.path.join(lxtools.getBaboonStackDirectory(), pkginfo.get('dirname'))
        print('Create Directory...')
        try:
            os.mkdir(basedir, 0o755)

            # Execute scripts
            runScript(pkginfo, ['install'])
        except BaseException as e:
            print('ERROR:', e)
            return False

        print('Done...')
        return True

    # # Download Filelist
    # if not getLatestRemoteVersion(fullpackagename):
    #     print('SERVER ERROR: Package not found on server...')
    #     return False

    # Retrieve package checksum
    packagechecksum = getRemoteChecksum(fullpackagename)

    # Build
    url = config.lxServer + '/' + fullpackagename
    dirname = None
    iserror = False
    localpacketname = os.path.join(tempfile.gettempdir(), fullpackagename)

    # Download Packet with Progressbar
    print('Download ' + fullpackagename + '...')
    result = lxtools.getRemoteFile(url, localpacketname)

    # Exception or canceled
    if result == -1:
        return False

    # Check package checksum
    if packagechecksum:
        print('Verify Checksum...')
        localchecksum = lxtools.getSHAChecksum(localpacketname)

        # Check Checksum
        if localchecksum == packagechecksum:
            print('Checksum are correct...')
        else:
            print('Checksum missmatch... Abort!')
            print('Filename  ' + fullpackagename)
            print('Remote SHA' + str(packagechecksum))
            print('Local  SHA' + localchecksum)
            return False
    else:
        print('WARNING: No Checksum for this package available...')

    # Extract Archive Package
    try:
        print('Extracting...')
        tempdirectory = tempfile.mkdtemp()
        archive_filelist = []

        # Unix specified
        if sys.platform.startswith('linux') or sys.platform == 'darwin':
            # Extract files
            mytar = tarfile.open(localpacketname)

            # Find and Read package description file, if exists
            for tarinfo in mytar:
                if os.path.basename(tarinfo.name) == config.getConfigKey('configfile', 'package.bbs.conf'):
                    print('Read package description file...')
                    try:
                        # Extract file
                        mytar.extract(tarinfo.name, tempdirectory)

                        # Read package
                        pkginfo = lxtools.loadjson(os.path.join(tempdirectory, tarinfo.name), True)
                    except BaseException as e:
                        print(e)
                        return False

                    # Exit
                    break

            # Get dirname
            dirname = os.path.join(pkginfo.get('dirname'), '')

            # Check dependencies, if set
            if getIfDependenciesInstalled(pkginfo):
                # Get the filelist from tarfile
                for tarinfo in mytar:
                    normpath = os.path.normpath(tarinfo.name)
                    if normpath.startswith(dirname):
                        archive_filelist.append(normpath[len(dirname):])

                # Extract files
                try:
                    mytar.extractall(lxtools.getBaboonStackDirectory())
                except BaseException as e:
                    print('Error in TAR, see error below.')
                    print(e)
            else:
                iserror = True

            mytar.close()

        # Windows specified
        if sys.platform == 'win32':
            if zipfile.is_zipfile(localpacketname):
                myzip = zipfile.ZipFile(localpacketname, 'r')

                # Find and Read package description file, if exists
                for filename in myzip.namelist():
                    if os.path.basename(filename) == config.getConfigKey('configfile', 'package.bbs.conf'):
                        print('Read package description file...')
                        try:
                            # Extract file
                            myzip.extract(filename, tempdirectory)

                            # Read package
                            pkginfo = lxtools.loadjson(os.path.join(tempdirectory, filename), True)
                        except BaseException as e:
                            print(e)
                            return False

                        # Exit
                        break

                # Get dirname
                dirname = os.path.join(pkginfo.get('dirname'), '')

                # Check dependencies, if set
                if getIfDependenciesInstalled(pkginfo):
                    # Get the filelist from zipfile
                    for filename in myzip.namelist():
                        normpath = os.path.normpath(filename)
                        if normpath.startswith(dirname):
                            archive_filelist.append(normpath[len(dirname):])

                    # Extract files
                    try:
                        myzip.extractall(lxtools.getBaboonStackDirectory())
                    except BaseException as e:
                        print('Error in ZIP, see error below.')
                        print(e)
                else:
                    iserror = True

                myzip.close()
            else:
                print('ERROR: Archive is not a ZIP File.')
                return False

        # Remove temporary directory
        lxtools.rmDirectory(tempdirectory)

        # If error occured
        if iserror:
            return False

        # Has dirname
        if not dirname:
            print('ERROR: No "dirname" in description file...')
            return False

        # Some file and directories will be include or exclude for removing
        files_rules = pkginfo.get('files', None)
        if files_rules is not None:
            files_includes = files_rules.get('include', [])
            files_excludes = files_rules.get('exclude', [])

            # Include files or directory
            if files_includes:
                # If single string, then build array
                if isinstance(files_includes, str):
                    files_includes = [files_includes]

                if isinstance(files_includes, list):
                    for fileentry in files_includes:
                        archive_filelist.append(os.path.normpath(fileentry))

            # Exclude files or directory
            if files_excludes:
                # If single string, then build array
                if isinstance(files_excludes, str):
                    files_excludes = [files_excludes]

                if isinstance(files_excludes, list):
                    for fileentry in files_excludes:
                        fullname = os.path.normpath(fileentry)

                        # Remove every item
                        tmpfilelist = archive_filelist.copy()
                        for archiveentry in tmpfilelist:
                            if str(archiveentry).startswith(fullname):
                                archive_filelist.remove(archiveentry)

        # Save filelist into program directory for remove
        if len(archive_filelist) != 0:
            lstname = os.path.join(lxtools.getBaboonStackDirectory(), dirname, 'files.lst')
            try:
                fileslst = open(lstname, 'w')
                fileslst.write('\n'.join(archive_filelist))
                fileslst.close()
            except BaseException as e:
                print('Error while saving filelist!')
                print(e)

        print('Installing...')
        scriptoption = ['install']

        # Execute scripts
        runScript(pkginfo, scriptoption)
    except BaseException as e:
        print('ERROR:', e)
        return False

    lxtools.cleanUpTemporaryFiles()
    print('Done...')

    return True
예제 #16
0
def setLocalNodeVersion(nodeversion):
    # Retrive local available Version
    versionList = getLocalNodeVersionList(nodeversion)

    # No Version found
    if len(versionList) == 0:
        print('Sorry, no existing Node version {0} found locally.'.format(nodeversion))
        return False

    # Get the last element from list
    nodeversion = versionList.pop()

    # Inform User about the version choose (only if more items exists)
    if len(versionList) != 0:
        print('Take Node v{0}...'.format(nodeversion))

    # If version already active?
    if getIfNodeVersionActive(nodeversion):
        print('Node v{0} already active.'.format(nodeversion))
        return False

    # Get original Path
    nodeDir = os.path.join(lxNodePath, nodeversion)

    # If Node Version installed?
    if not os.path.exists(nodeDir):
        print('Node v{0} not found locally.'.format(nodeDir))
        return False

    # If User Admin?
    if not lxtools.getIfAdmin():
        print(config.getMessage('REQUIREADMIN'))
        return False

    # Windows
    if sys.platform == 'win32':
        # Delete old LINK Directory when exits
        if not resetNode():
            return False

        # Set new link
        if not lxtools.setDirectoryLink(lxBinPath, nodeDir):
            print('ERROR while link to new Node Version.')
            return False

        print('Switched to Node v{0}...'.format(nodeversion))
        return True

    # Unix
    if sys.platform.startswith('linux') or sys.platform == 'darwin':
        links = config.getConfigKey('node.links')

        # check if all required source directories exits
        pathexists = True
        for names in links:
            linkoptions = links[names].get('options', [])

            if 'absolute_source' in linkoptions:
                fullname = links[names]['source']
            else:
                fullname = os.path.join(nodeDir, links[names]['source'], names)

            # absolute_source
            # Check, if required source not found
            if 'no_source_check' not in linkoptions and not os.path.isfile(fullname) and not os.path.isdir(fullname):
                print('ERROR: Required Element "' +
                      os.path.join(links[names]['source'], names) +
                      '" in "' +
                      nodeDir +
                      '" not found...')
                pathexists = False

        # A required Source was not found, abort
        if not pathexists:
            return False

        # Unlink old version
        if not resetNode():
            return False

        # link new version
        for names in links:
            linkoptions = links[names].get('options', [])

            if 'absolute_source' in linkoptions:
                source = links[names]['source']
            else:
                source = os.path.join(nodeDir, links[names]['source'], names)

            target = os.path.join(links[names]['target'], names)
            #source = os.path.join(nodeDir, links[names]['source'], names)

            # Link
            if not lxtools.setDirectoryLink(target, source):
                raise Exception('Link creation failed!\n' + source + ' => ' + target)

        # run Cache fix
        runCacheFix()

        # show hint
        print('Note: Force a ´npm update -g´ to update global modules...')
        print('\nSwitched to Node v{0}...'.format(nodeversion))

        return True

    return False
예제 #17
0
def doStart(version, params):
    if not getIfMongoVersionAvailable(version):
        print('Version not available locally.')
        return False

    print('Start MongoDB Instance v' + version + '...')

    pidfile = 'mongo-' + version + '.pids'
    pidlist = lxtools.loadFileFromUserSettings(pidfile, False, returntype=[])

    mongodir = os.path.join(mongobasedir, version)
    mongodaemon = os.path.join(mongodir, config.getConfigKey('mongo.binary.mongod'))

    # Check if binary exists
    if not os.path.isfile(mongodaemon):
        print('Mongo daemon binary not found.')
        return False

    mongodatadir = mongodir

    # Create db and log folder if not exists
    try:
        if not os.path.exists(os.path.join(mongodatadir, 'db')):
            os.makedirs(os.path.join(mongodatadir, 'db'))

        if not os.path.exists(os.path.join(mongodatadir, 'log')):
            os.makedirs(os.path.join(mongodatadir, 'log'))
    except IOError as e:
        print('ERROR:', e)
        print('Abort and exit!')
        return False

    args = [
        mongodaemon,
    ]

    defaultargs = {
        '--port': '27017',
        '--dbpath': os.path.join(mongodatadir, 'db')
        # '--logpath': os.path.join(mongodatadir, 'log', 'db.log')
    }

    if not isinstance(params, list):
        params = []

    # Lower case parameters
    plist = []
    for i in range(0, len(params) - 1):
        if params[i][0] == '-':
            plist.append(params[i].lower())

    # Merge
    args.extend(params)

    # Fill with default values
    for argv in defaultargs:
        if argv not in plist:
            print(' Add parameter:', argv, defaultargs[argv])
            args.append(argv)
            args.append(defaultargs[argv])

    print('Start MongoDB v' + version + '...')
    # print('Mongod parameters:', str(' ').join(args[1:]))
    print('*** Please wait for 5 second(s) to validate success ***')

    # if sys.platform == 'win32':
    #     creationflags = 0
    # else:
    #     creationflags = 0

    # Start Mongo process
    mongoprocess = subprocess.Popen(
        args,
        cwd=mongodir,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL
        # creationflags=creationflags
    )

    # # Update Output
    # mongoprocess.stdout = subprocess.PIPE
    # mongoprocess.stderr = subprocess.PIPE

    # Wait for response for 3 seconds, to validate success
    try:
        mongoprocess.communicate(timeout=3)
    except subprocess.TimeoutExpired:
        print('\nProcess successfully launched, PID #' + str(mongoprocess.pid))

        # Save pid to file
        if str(mongoprocess.pid) not in pidlist:
            pidlist.append(str(mongoprocess.pid))
            lxtools.saveFileToUserSettings(pidfile, pidlist)
    else:
        print('\nProcess exits, Mongo returns', mongoprocess.returncode)
        return mongoprocess.returncode

    pass