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 cleanUp(): # Remove temporary internet files lxtools.cleanUpTemporaryFiles() # Clear temporary node directory if os.path.exists(tempNodeDir): lxtools.rmDirectory(tempNodeDir)
def cleanUp(): # Remove temporary internet files lxtools.cleanUpTemporaryFiles() # Clear temporary node directory if os.path.exists(tempNodeDir): lxtools.rmDirectory(tempNodeDir)
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 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 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 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
import sys import stat import subprocess from cx_Freeze import Executable, Freezer, setup import lxtools from cx_Freeze import main srcdir = '.' distdir = os.path.join(srcdir, 'build') iconfile = os.path.join(srcdir, 'ressources', 'baboonstack.ico') scriptFiles = [os.path.join(srcdir, 'bbs.py')] # Remove build directory if os.path.exists(distdir): lxtools.rmDirectory(distdir) #main() executables = {} for scriptFile in scriptFiles: if sys.platform.startswith('win'): ex = Executable( scriptFile, icon=iconfile, appendScriptToExe=True, ) else: # Unix Build ex = Executable(scriptFile, )
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 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 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
import subprocess from cx_Freeze import Executable, Freezer, setup import lxtools from cx_Freeze import main srcdir = '.' distdir = os.path.join(srcdir, 'build') iconfile = os.path.join(srcdir, 'ressources', 'baboonstack.ico') scriptFiles = [ os.path.join(srcdir, 'bbs.py') ] # Remove build directory if os.path.exists(distdir): lxtools.rmDirectory(distdir) #main() executables = {} for scriptFile in scriptFiles: if sys.platform.startswith('win'): ex = Executable( scriptFile, icon=iconfile, appendScriptToExe=True, ) else: # Unix Build ex = Executable(