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
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
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
def bbsHelp(): print('Usage:\n') print(' bbs version Displays the version number') print(' bbs upgrade Search and Install BaboonStack Updates') print(' bbs install [packagename] Install packages') print(' bbs update [packagename] Update a single packages') #print(' bbs search [packagename] Updates packages') print(' bbs remove [packagename] Removes packages') print(' bbs ls Lists available packages') #print(' bbs uninstall Uninstall Baboonstack') print('') # Enable NVM und SERVICE module only if Node Component installed if lxtools.getIfNodeModuleEnabled(): print(' bbs node Node Module Controls') print(' bbs service Service Module Controls for Node.JS') # Enable MONGO module only if MongoDB installed if lxtools.getIfMongoModuleEnabled(): print(' bbs mongo Mongo Module Controls') # Enable REDIS module only if RedisIO installed # if lxtools.getIfRedisModuleEnabled(): # print(' bbs redis Redis Module Controls') print('') print(' Some operations required "{0}" rights.'.format(config.getMessage('ADMINNAME'))) pass
def rmLocalNodeVersion(nodeversion): # Check if admin if not lxtools.getIfAdmin(): print(config.getMessage('REQUIREADMIN')) return False # Check if syntax correct if not getIfNodeVersionFormat(nodeversion): print('{0} is not a Node Version Format.'.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(nodeversion)) return False # If Version active then abort if getIfNodeVersionActive(nodeversion): print('Cannot uninstall currently-active node version v{0}'.format( nodeversion)) return False # Removes the Directory print('Remove Node v{0} from System.'.format(nodeversion)) try: lxtools.rmDirectory(nodeDir) return True except Exception as e: print('ERROR: Node v{0} could not be removed.'.format(nodeversion)) print('EXCEPTION:', e) return False
def rmLocalNodeVersion(nodeversion): # Check if admin if not lxtools.getIfAdmin(): print(config.getMessage('REQUIREADMIN')) return False # Check if syntax correct if not getIfNodeVersionFormat(nodeversion): print('{0} is not a Node Version Format.'.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(nodeversion)) return False # If Version active then abort if getIfNodeVersionActive(nodeversion): print('Cannot uninstall currently-active node version v{0}'.format(nodeversion)) return False # Removes the Directory print('Remove Node v{0} from System.'.format(nodeversion)) try: lxtools.rmDirectory(nodeDir) return True except Exception as e: print('ERROR: Node v{0} could not be removed.'.format(nodeversion)) print('EXCEPTION:', e) return False
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
def doRemove(version, options): activeVersion = getActiveMongoVersion() # Admin required if not lxtools.getIfAdmin(): print(config.getMessage('REQUIREADMIN')) return False # Version already active if activeVersion == version: print('Currently activated version can not be removed.') return False # If version locally available if not getIfMongoVersionAvailable(version): print('A non-installed version can not be removed. Since there is no magic.') return False mongodir = os.path.join(mongobasedir, version) lstname = os.path.join(mongodir, 'files.lst') # Load files.lst, if exists if os.path.exists(lstname): dir_filelist = ['files.lst'] try: fileslst = open(lstname, 'r') for line in fileslst.readlines(): dir_filelist.append(line.rstrip('\n')) fileslst.close() except BaseException as e: print('Error while saving filelist!') print(e) else: dir_filelist = [] # saferemove = None if 'safe' in options: saferemove = True if 'force' in options: saferemove = False # If no safe or force options choosen, then ask user if saferemove is None: saferemove = ( lxtools.readkey('Would you like to remove *ALL* files? Includes database/log files/etc', 'yN') != 'y' ) # Has files? if len(dir_filelist) != 0: # Remove every file from directory and marks directories print('Remove files...') lxtools.removeFilesFromList(mongodir, dir_filelist, saferemove) print('Removed...') pass
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
def runCacheFix(): # Under windows os, not needed if lxtools.getPlatformName() == 'win32': return True # Check if admin if not lxtools.getIfAdmin(): print(config.getMessage('REQUIREADMIN')) return False # Get User home dir and .npm cache homedir = os.path.expanduser('~') npmcachedir = os.path.join(homedir, '.npm') if os.path.isdir(npmcachedir): homedir_stat = os.stat(homedir) print('Fix ´.npm´ cache permissions...') return lxtools.chown(npmcachedir, homedir_stat.st_uid, homedir_stat.st_gid) return True
def resetMongo(): # If User Admin? if not lxtools.getIfAdmin(): print(config.getMessage('REQUIREADMIN')) return False # Delete old LINK Directory when exits if os.path.exists(mongosymlink): # If Directory a Symbolic Link if not lxtools.getIfSymbolicLink(mongosymlink): print('ERROR: Mongo folder is not a link and can not be removed.') return False # Remove Link try: os.remove(mongosymlink) except BaseException as e: print('ERROR:', e) return False return True
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
def getRemoteNodeVersion(nodeversion, options): # Check if admin if not lxtools.getIfAdmin(): print(config.getMessage('REQUIREADMIN')) return False # Check if version available on remote server print('Retrieve available version...') versionList = getRemoteNodeVersionList(nodeversion + '.*') # No Version found if len(versionList) == 0: print('Node v{0} not found on remote server.'.format(nodeversion)) return # 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)) # Build target Path targetDirectory = os.path.join(lxNodePath, nodeversion) # Check if already installed if os.path.exists(targetDirectory): print('Version already installed.') return False # Get the Os specified Node Remote Package remoteFilename = config.lxConfig['node']['package'][ lxtools.getOsArchitecture()].format(nodeversion) # Get Checksumlist from remote Server print('Retrieve Checksum list...') checksumList = getRemoteChecksumList("http://nodejs.org/dist/v" + nodeversion) remoteChecksum = '' # Find Checksum for the Binary if len(checksumList) != '': for checksumEntry in checksumList: value = checksumEntry.split(' ') if len(value) > 1 and value[1] == remoteFilename: remoteChecksum = value[0] break # If Checksum found? if remoteChecksum == '': print('No checksum for remote Binary, if exists?\nTry to retrieve...') # Download Binary from Server print('Retrieve Node Version v{0} Installation packet...'.format( nodeversion)) tempRemoteFile = lxtools.getRemoteFile("http://nodejs.org/dist/v" + nodeversion + '/' + remoteFilename) # Abort or Exception if tempRemoteFile == -1: return False # Generate Checksum of downloaded Binary print('Generate Checksum...') localChecksum = lxtools.getSHAChecksum(tempRemoteFile) # Check Checksum if (localChecksum == remoteChecksum): print('Checksum correct...') else: print('Checksum missmatch... Abort!') print('Filename ' + remoteFilename) print('Remote SHA' + remoteChecksum) print('Local SHA' + localChecksum) return False # Default temp Directory moveNodeDir = tempNodeDir # Remove temp, if exists if os.path.exists(tempNodeDir): try: lxtools.rmDirectory(tempNodeDir) except Exception as e: raise e # Windows specified stuff if sys.platform == 'win32': moveNodeDir = os.path.join(tempNodeDir, 'nodejs') # Extract MSI Package print('Execute installation package...') try: retcode = subprocess.call(msiexecArguments.format( tempRemoteFile, tempNodeDir), shell=False) # If return code otherwise then 0, ERROR if retcode != 0: print( 'ABORT: Huh? Installer reports error!\n\nDo you canceled it? Returncode {0}' .format(retcode)) cleanUp() return False except: print('ERROR: Install package error!') cleanUp() return False # Unix specified stuff if sys.platform.startswith('linux') or sys.platform == 'darwin': moveNodeDir = os.path.join(tempNodeDir, remoteFilename.rstrip('.tar.gz')) # Extract TAR Package try: tar = tarfile.open(tempRemoteFile) tar.extractall(tempNodeDir) tar.close() except BaseException as e: print('ERROR:', e) cleanUp() return False # Now copies node print('Copy files...') if os.path.exists(moveNodeDir): # MOVE os.rename(moveNodeDir, targetDirectory) else: print('Uuuh! Something is wrong! Abort!') return False # Deletes the shit of temporary files print('Clean up...') cleanUp() if not 'noswitch' in options: return setLocalNodeVersion(nodeversion) else: return True
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
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)
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
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
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
def getRemoteNodeVersion(nodeversion, options): # Check if admin if not lxtools.getIfAdmin(): print(config.getMessage('REQUIREADMIN')) return False # Check if version available on remote server print('Retrieve available version...') versionList = getRemoteNodeVersionList(nodeversion + '.*') # No Version found if len(versionList) == 0: print('Node v{0} not found on remote server.'.format(nodeversion)) return # 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)) # Build target Path targetDirectory = os.path.join(lxNodePath, nodeversion) # Check if already installed if os.path.exists(targetDirectory): print('Version already installed.') return False # Get the Os specified Node Remote Package remoteFilename = config.lxConfig['node']['package'][lxtools.getOsArchitecture()].format(nodeversion) # Get Checksumlist from remote Server print('Retrieve Checksum list...') checksumList = getRemoteChecksumList("http://nodejs.org/dist/v" + nodeversion) remoteChecksum = '' # Find Checksum for the Binary if len(checksumList) != '': for checksumEntry in checksumList: value = checksumEntry.split(' ') if len(value) > 1 and value[1] == remoteFilename: remoteChecksum = value[0] break # If Checksum found? if remoteChecksum == '': print('No checksum for remote Binary, if exists?\nTry to retrieve...') # Download Binary from Server print('Retrieve Node Version v{0} Installation packet...'.format(nodeversion)) tempRemoteFile = lxtools.getRemoteFile("http://nodejs.org/dist/v" + nodeversion + '/' + remoteFilename) # Abort or Exception if tempRemoteFile == -1: return False # Generate Checksum of downloaded Binary print('Generate Checksum...') localChecksum = lxtools.getSHAChecksum(tempRemoteFile) # Check Checksum if (localChecksum == remoteChecksum): print('Checksum correct...') else: print('Checksum missmatch... Abort!') print('Filename ' + remoteFilename) print('Remote SHA' + remoteChecksum) print('Local SHA' + localChecksum) return False # Default temp Directory moveNodeDir = tempNodeDir # Remove temp, if exists if os.path.exists(tempNodeDir): try: lxtools.rmDirectory(tempNodeDir) except Exception as e: raise e # Windows specified stuff if sys.platform == 'win32': moveNodeDir = os.path.join(tempNodeDir, 'nodejs') # Extract MSI Package print('Execute installation package...') try: retcode = subprocess.call(msiexecArguments.format(tempRemoteFile, tempNodeDir), shell=False) # If return code otherwise then 0, ERROR if retcode != 0: print('ABORT: Huh? Installer reports error!\n\nDo you canceled it? Returncode {0}'.format(retcode)) cleanUp() return False except: print('ERROR: Install package error!') cleanUp() return False # Unix specified stuff if sys.platform.startswith('linux') or sys.platform == 'darwin': moveNodeDir = os.path.join(tempNodeDir, remoteFilename.rstrip('.tar.gz')) # Extract TAR Package try: tar = tarfile.open(tempRemoteFile) tar.extractall(tempNodeDir) tar.close() except BaseException as e: print('ERROR:', e) cleanUp() return False # Now copies node print('Copy files...') if os.path.exists(moveNodeDir): # MOVE os.rename(moveNodeDir, targetDirectory) else: print('Uuuh! Something is wrong! Abort!') return False # Deletes the shit of temporary files print('Clean up...') cleanUp() if not 'noswitch' in options: return setLocalNodeVersion(nodeversion) else: return True
def remove(pkgname, options=list()): if pkgname is None: return False # if pkgname is list, then remove multiple if isinstance(pkgname, list): if 'force' not in options and 'ask' not in options: options.append('ask') pkgcnt = 0 for name in pkgname: if 'ask' in options: key = lxtools.readkey('Remove package "' + name + '"...', 'yNa') # User selected no, keep package if key == 'n': continue # User selected abort, stop all if key == 'a': print(' Abort!!!') break else: print('Remove package "' + name + '"...') if remove(name, options): pkgcnt += 1 print('') print(' {0} of {1} packages successfully removed'.format(str(pkgcnt), str(len(pkgname)))) return True # Removes ALL packages? if pkgname == '': pkgname = [] for pkg in localcatalog: # Only remove if installed locally if localcatalog[pkg].getIfInstalled(): pkgname.append(pkg) if len(pkgname) == 0: print('Sorry, no packages available to remove.') return False # Rerun return remove(pkgname, options) # Get package info pkginfo = None if pkgname in localcatalog: # Check, if package already installed if not localcatalog[pkgname].getIfInstalled(): print('Package "' + pkgname + '" NOT installed locally...') return False pkginfo = localcatalog[pkgname].getPackageInfo() # Check, if package available if not pkginfo: print('Unknow Package "' + pkgname + '"...') return False # Check if admin if not lxtools.getIfAdmin(): print(config.getMessage('REQUIREADMIN')) return # Ask if 'ask' in options: key = lxtools.readkey('Really remove "' + pkgname + '"...', 'Ny') if key == 'n': return False # Script options scriptoption = ['remove'] saferemove = pkginfo.get('saferemove') is True # If saferemove option overwritten? if 'force' in options or 'safe' in options: if 'force' in options: saferemove = False if 'safe' in options: saferemove = True else: # Ask for remove databases, cfg if saferemove TRUE if saferemove: key = lxtools.readkey('Would you like to keep their databases, configuration files?') if key != 'y': saferemove = False if not saferemove: scriptoption.append('all') print('Remove package "' + pkgname + '"...') # Run remove script runScript(pkginfo, scriptoption) # Delete files dirname = os.path.join(pkginfo.get('dirname'), '') basedir = os.path.join(lxtools.getBaboonStackDirectory(), dirname) lstname = os.path.join(basedir, 'files.lst') # Load files.lst, if exists if os.path.exists(lstname): dir_filelist = ['files.lst'] try: fileslst = open(lstname, 'r') for line in fileslst.readlines(): dir_filelist.append(line.rstrip('\n')) fileslst.close() except BaseException as e: print('Error while saving filelist!') print(e) else: dir_filelist = [] # Has files? if len(dir_filelist) != 0: # Remove every file from directory and marks directories print('Remove files...') lxtools.removeFilesFromList(basedir, dir_filelist, saferemove) # Done print('Done...') return True