idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
61,400
def mergeNewSeqs ( seqArray , mergedDir , numProcs , areUniform , logger ) : MSBWTGen . clearAuxiliaryData ( mergedDir ) midPoint = len ( seqArray ) / 3 mergedDir1 = mergedDir + '0' mergedDir2 = mergedDir + '1' mergedDir3 = mergedDir + '2' try : shutil . rmtree ( mergedDir1 ) except : pass try : shutil . rmtree ( mergedDir2 ) except : pass try : shutil . rmtree ( mergedDir3 ) except : pass os . makedirs ( mergedDir1 ) os . makedirs ( mergedDir2 ) os . makedirs ( mergedDir3 ) createMSBWTFromSeqs ( seqArray [ 0 : midPoint ] , mergedDir1 , numProcs , areUniform , logger ) createMSBWTFromSeqs ( seqArray [ midPoint : 2 * midPoint ] , mergedDir2 , numProcs , areUniform , logger ) createMSBWTFromSeqs ( seqArray [ 2 * midPoint : ] , mergedDir3 , numProcs , areUniform , logger ) MSBWTGen . mergeNewMSBWT ( mergedDir , [ mergedDir1 , mergedDir2 , mergedDir3 ] , numProcs , logger )
This function takes a series of sequences and creates a big BWT by merging the smaller ones Mostly a test function no real purpose to the tool as of now
61,401
def compareKmerProfiles ( profileFN1 , profileFN2 ) : fp1 = open ( profileFN1 , 'r' ) fp2 = open ( profileFN2 , 'r' ) oneNorm = 0 twoNorm = 0 sumDeltas = 0 dotProduct = 0 tot1 = float ( fp1 . readline ( ) . strip ( '\n' ) . split ( ',' ) [ 1 ] ) tot2 = float ( fp2 . readline ( ) . strip ( '\n' ) . split ( ',' ) [ 1 ] ) ( seq1 , count1 ) = parseProfileLine ( fp1 ) ( seq2 , count2 ) = parseProfileLine ( fp2 ) while seq1 != None or seq2 != None : if seq1 == seq2 : delta = abs ( count1 / tot1 - count2 / tot2 ) dotProduct += ( count1 / tot1 ) * ( count2 / tot2 ) ( seq1 , count1 ) = parseProfileLine ( fp1 ) ( seq2 , count2 ) = parseProfileLine ( fp2 ) elif seq2 == None or ( seq1 != None and seq1 < seq2 ) : delta = count1 / tot1 ( seq1 , count1 ) = parseProfileLine ( fp1 ) else : delta = count2 / tot2 ( seq2 , count2 ) = parseProfileLine ( fp2 ) if delta > oneNorm : oneNorm = delta twoNorm += delta * delta sumDeltas += delta fp1 . close ( ) fp2 . close ( ) twoNorm = math . sqrt ( twoNorm ) return ( oneNorm , twoNorm , sumDeltas , dotProduct )
This function takes two kmer profiles and compare them for similarity .
61,402
def parseProfileLine ( fp ) : nextLine = fp . readline ( ) if nextLine == None or nextLine == '' : return ( None , None ) else : pieces = nextLine . strip ( '\n' ) . split ( ',' ) return ( pieces [ 0 ] , int ( pieces [ 1 ] ) )
Helper function for profile parsing
61,403
def reverseComplement ( seq ) : revComp = '' complement = { 'A' : 'T' , 'C' : 'G' , 'G' : 'C' , 'T' : 'A' , 'N' : 'N' , '$' : '$' } for c in reversed ( seq ) : revComp += complement [ c ] return revComp
Helper function for generating reverse - complements
61,404
def countOccurrencesOfSeq ( self , seq , givenRange = None ) : if givenRange == None : if not self . searchCache . has_key ( seq [ - self . cacheDepth : ] ) : res = self . findIndicesOfStr ( seq [ - self . cacheDepth : ] ) self . searchCache [ seq [ - self . cacheDepth : ] ] = ( int ( res [ 0 ] ) , int ( res [ 1 ] ) ) l , h = self . searchCache [ seq [ - self . cacheDepth : ] ] seq = seq [ 0 : - self . cacheDepth ] else : l = givenRange [ 0 ] h = givenRange [ 1 ] revSeq = [ self . charToNum [ c ] for c in reversed ( seq ) ] for c in revSeq : l = self . getOccurrenceOfCharAtIndex ( c , l ) h = self . getOccurrenceOfCharAtIndex ( c , h ) if l == h : return 0 return h - l
This function counts the number of occurrences of the given sequence
61,405
def recoverString ( self , strIndex , withIndex = False ) : retNums = [ ] indices = [ ] currIndex = strIndex prevChar = self . getCharAtIndex ( currIndex ) currIndex = self . getOccurrenceOfCharAtIndex ( prevChar , currIndex ) while currIndex != strIndex : retNums . append ( prevChar ) if withIndex : indices . append ( currIndex ) prevChar = self . getCharAtIndex ( currIndex ) currIndex = self . getOccurrenceOfCharAtIndex ( prevChar , currIndex ) for i in xrange ( 0 , self . vcLen ) : if strIndex < self . endIndex [ i ] : retNums . append ( i ) break if withIndex : indices . append ( strIndex ) ret = '' . join ( self . numToChar [ retNums [ : : - 1 ] ] ) if withIndex : return ( ret , indices [ : : - 1 ] ) else : return ret
This will return the string that starts at the given index
61,406
def getOccurrenceOfCharAtIndex ( self , sym , index ) : binID = index >> self . bitPower if ( binID << self . bitPower ) == index : ret = self . partialFM [ binID ] [ sym ] else : ret = self . partialFM [ binID ] [ sym ] + np . bincount ( self . bwt [ binID << self . bitPower : index ] , minlength = 6 ) [ sym ] return int ( ret )
This functions gets the FM - index value of a character at the specified position
61,407
def loadMsbwt ( self , dirName , logger ) : self . dirName = dirName self . bwt = np . load ( self . dirName + '/comp_msbwt.npy' , 'r' ) self . constructTotalCounts ( logger ) self . constructIndexing ( ) self . constructFMIndex ( logger )
This functions loads a BWT file and constructs total counts indexes start positions and constructs an FM index in memory
61,408
def getCharAtIndex ( self , index ) : binID = index >> self . bitPower bwtIndex = self . refFM [ binID ] trueIndex = np . sum ( self . partialFM [ binID ] ) - self . offsetSum dist = index - trueIndex if binID == self . refFM . shape [ 0 ] - 1 : endRange = self . bwt . shape [ 0 ] else : endRange = self . refFM [ binID + 1 ] + 1 while endRange < self . bwt . shape [ 0 ] and ( self . bwt [ endRange ] & self . mask ) == ( self . bwt [ endRange - 1 ] & self . mask ) : endRange += 1 letters = np . bitwise_and ( self . bwt [ bwtIndex : endRange ] , self . mask ) counts = np . right_shift ( self . bwt [ bwtIndex : endRange ] , self . letterBits , dtype = '<u8' ) i = 1 same = ( letters [ 0 : - 1 ] == letters [ 1 : ] ) while np . count_nonzero ( same ) > 0 : ( counts [ i : ] ) [ same ] *= self . numPower i += 1 same = np . bitwise_and ( same [ 0 : - 1 ] , same [ 1 : ] ) cs = np . cumsum ( counts ) x = np . searchsorted ( cs , dist , 'right' ) return letters [ x ]
Used for searching this function masks the complexity behind retrieving a specific character at a specific index in our compressed BWT .
61,409
def getBWTRange ( self , start , end ) : startBlockIndex = start >> self . bitPower endBlockIndex = int ( math . floor ( float ( end ) / self . binSize ) ) trueStart = startBlockIndex * self . binSize return self . decompressBlocks ( startBlockIndex , endBlockIndex ) [ start - trueStart : end - trueStart ]
This function masks the complexity of retrieving a chunk of the BWT from the compressed format
61,410
def decompressBlocks ( self , startBlock , endBlock ) : expectedIndex = startBlock * self . binSize trueIndex = np . sum ( self . partialFM [ startBlock ] ) - self . offsetSum dist = expectedIndex - trueIndex startRange = self . refFM [ startBlock ] if endBlock >= self . refFM . shape [ 0 ] - 1 : endRange = self . bwt . shape [ 0 ] returnSize = self . binSize * ( endBlock - startBlock ) + ( self . totalSize % self . binSize ) else : endRange = self . refFM [ endBlock + 1 ] + 1 returnSize = self . binSize * ( endBlock - startBlock + 1 ) while endRange < self . bwt . shape [ 0 ] and ( self . bwt [ endRange ] & self . mask ) == ( self . bwt [ endRange - 1 ] & self . mask ) : endRange += 1 ret = np . zeros ( dtype = '<u1' , shape = ( returnSize , ) ) letters = np . bitwise_and ( self . bwt [ startRange : endRange ] , self . mask ) counts = np . right_shift ( self . bwt [ startRange : endRange ] , self . letterBits , dtype = '<u8' ) i = 1 same = ( letters [ 0 : - 1 ] == letters [ 1 : ] ) while np . count_nonzero ( same ) > 0 : ( counts [ i : ] ) [ same ] *= self . numPower i += 1 same = np . bitwise_and ( same [ 0 : - 1 ] , same [ 1 : ] ) s = 0 lInd = 0 while dist > 0 : if counts [ lInd ] < dist : dist -= counts [ lInd ] lInd += 1 else : counts [ lInd ] -= dist dist = 0 while s < ret . shape [ 0 ] : if lInd >= letters . shape [ 0 ] : pass ret [ s : s + counts [ lInd ] ] = letters [ lInd ] s += counts [ lInd ] lInd += 1 return ret
This is mostly a helper function to get BWT range but I wanted it to be a separate thing for use possibly in decompression
61,411
def decode_html ( html ) : if isinstance ( html , unicode ) : return html match = CHARSET_META_TAG_PATTERN . search ( html ) if match : declared_encoding = match . group ( 1 ) . decode ( "ASCII" ) with ignored ( LookupError ) : return html . decode ( declared_encoding , "ignore" ) with ignored ( UnicodeDecodeError ) : return html . decode ( "utf8" ) text = TAG_MARK_PATTERN . sub ( to_bytes ( " " ) , html ) diff = text . decode ( "utf8" , "ignore" ) . encode ( "utf8" ) sizes = len ( diff ) , len ( text ) if abs ( len ( text ) - len ( diff ) ) < max ( sizes ) * 0.01 : return html . decode ( "utf8" , "ignore" ) encoding = "utf8" encoding_detector = chardet . detect ( text ) if encoding_detector [ "encoding" ] : encoding = encoding_detector [ "encoding" ] return html . decode ( encoding , "ignore" )
Converts bytes stream containing an HTML page into Unicode . Tries to guess character encoding from meta tag of by chardet library .
61,412
def build_document ( html_content , base_href = None ) : assert html_content is not None if isinstance ( html_content , unicode ) : html_content = html_content . encode ( "utf8" , "xmlcharrefreplace" ) try : document = document_fromstring ( html_content , parser = UTF8_PARSER ) except ( ParserError , XMLSyntaxError ) : raise ValueError ( "Failed to parse document contents." ) if base_href : document . make_links_absolute ( base_href , resolve_base_href = True ) else : document . resolve_base_href ( ) return document
Requires that the html_content not be None
61,413
def _parse_properties ( self ) : props_dict = self . data . get ( 'properties' , { } ) for prop_name in self . KNOWN_PROPERTIES : if prop_name in props_dict : setattr ( self , prop_name , props_dict . get ( prop_name ) ) else : setattr ( self , prop_name , None )
Nodes have properties which are facts like the name description url etc . Loop through each of them and set it as attributes on this company so that we can make calls like company . name person . description
61,414
def _parse_relationship ( self ) : rs_dict = self . data . get ( 'relationships' , { } ) for rs_name in self . KNOWN_RELATIONSHIPS : if rs_name in rs_dict : setattr ( self , rs_name , Relationship ( rs_name , rs_dict . get ( rs_name ) ) ) else : setattr ( self , rs_name , NoneRelationshipSingleton )
Nodes have Relationships and similarly to properties we set it as an attribute on the Organization so we can make calls like company . current_team person . degrees
61,415
def open ( self ) : self . startTime = datetime . datetime . now ( ) self . offset = 0 return self
Reset time and counts .
61,416
def update ( self , sent ) : self . offset = sent now = datetime . datetime . now ( ) elapsed = ( now - self . startTime ) . total_seconds ( ) if elapsed > 0 : mbps = ( sent * 8 / ( 10 ** 6 ) ) / elapsed else : mbps = None self . _display ( sent , now , self . name , mbps )
Update self and parent with intermediate progress .
61,417
def _display ( self , sent , now , chunk , mbps ) : if self . parent is not None : self . parent . _display ( self . parent . offset + sent , now , chunk , mbps ) return elapsed = now - self . startTime if sent > 0 and self . total is not None and sent <= self . total : eta = ( self . total - sent ) * elapsed . total_seconds ( ) / sent eta = datetime . timedelta ( seconds = eta ) else : eta = None self . output . write ( "\r %s: Sent %s%s%s ETA: %s (%s) %s%20s\r" % ( elapsed , util . humanize ( sent ) , "" if self . total is None else " of %s" % ( util . humanize ( self . total ) , ) , "" if self . total is None else " (%d%%)" % ( int ( 100 * sent / self . total ) , ) , eta , "" if not mbps else "%.3g Mbps " % ( mbps , ) , chunk or "" , " " , ) ) self . output . flush ( )
Display intermediate progress .
61,418
def close ( self ) : if self . parent : self . parent . update ( self . parent . offset + self . offset ) return self . output . write ( "\n" ) self . output . flush ( )
Stop overwriting display or update parent .
61,419
def _printUUID ( uuid , detail = 'word' ) : if not isinstance ( detail , int ) : detail = detailNum [ detail ] if detail > detailNum [ 'word' ] : return uuid if uuid is None : return None return "%s...%s" % ( uuid [ : 4 ] , uuid [ - 4 : ] )
Return friendly abbreviated string for uuid .
61,420
def skipDryRun ( logger , dryRun , level = logging . DEBUG ) : if not isinstance ( level , int ) : level = logging . getLevelName ( level ) return ( functools . partial ( _logDryRun , logger , level ) if dryRun else functools . partial ( logger . log , level ) )
Return logging function .
61,421
def listVolumes ( self ) : for ( vol , paths ) in self . paths . items ( ) : for path in paths : if path . startswith ( '/' ) : continue if path == '.' : continue if self . userVolume is not None and os . path . basename ( path ) != self . userVolume : continue yield vol break
Return list of all volumes in this Store s selected directory .
61,422
def getSendPath ( self , volume ) : try : return self . _fullPath ( next ( iter ( self . getPaths ( volume ) ) ) ) except StopIteration : return None
Get a path appropriate for sending the volume from this Store .
61,423
def selectReceivePath ( self , paths ) : logger . debug ( "%s" , paths ) if not paths : path = os . path . basename ( self . userPath ) + '/Anon' try : path = [ p for p in paths if not p . startswith ( "/" ) ] [ 0 ] except IndexError : path = os . path . relpath ( list ( paths ) [ 0 ] , self . userPath ) return self . _fullPath ( path )
From a set of source paths recommend a destination path .
61,424
def _relativePath ( self , fullPath ) : if fullPath is None : return None assert fullPath . startswith ( "/" ) , fullPath path = os . path . relpath ( fullPath , self . userPath ) if not path . startswith ( "../" ) : return path elif self . ignoreExtraVolumes : return None else : return fullPath
Return fullPath relative to Store directory .
61,425
def setSize ( self , size , sizeIsEstimated ) : self . _size = size self . _sizeIsEstimated = sizeIsEstimated if self . fromVol is not None and size is not None and not sizeIsEstimated : Diff . theKnownSizes [ self . toUUID ] [ self . fromUUID ] = size
Update size .
61,426
def sendTo ( self , dest , chunkSize ) : vol = self . toVol paths = self . sink . getPaths ( vol ) if self . sink == dest : logger . info ( "Keep: %s" , self ) self . sink . keep ( self ) else : skipDryRun ( logger , dest . dryrun , 'INFO' ) ( "Xfer: %s" , self ) receiveContext = dest . receive ( self , paths ) sendContext = self . sink . send ( self ) transfer ( sendContext , receiveContext , chunkSize ) if vol . hasInfo ( ) : infoContext = dest . receiveVolumeInfo ( paths ) if infoContext is None : pass else : with infoContext as stream : vol . writeInfo ( stream )
Send this difference to the dest Store .
61,427
def writeInfoLine ( self , stream , fromUUID , size ) : if size is None or fromUUID is None : return if not isinstance ( size , int ) : logger . warning ( "Bad size: %s" , size ) return stream . write ( str ( "%s\t%s\t%d\n" % ( self . uuid , fromUUID , size , ) ) )
Write one line of diff information .
61,428
def writeInfo ( self , stream ) : for ( fromUUID , size ) in Diff . theKnownSizes [ self . uuid ] . iteritems ( ) : self . writeInfoLine ( stream , fromUUID , size )
Write information about diffs into a file stream for use later .
61,429
def hasInfo ( self ) : count = len ( [ None for ( fromUUID , size ) in Diff . theKnownSizes [ self . uuid ] . iteritems ( ) if size is not None and fromUUID is not None ] ) return count > 0
Will have information to write .
61,430
def readInfo ( stream ) : try : for line in stream : ( toUUID , fromUUID , size ) = line . split ( ) try : size = int ( size ) except Exception : logger . warning ( "Bad size: %s" , size ) continue logger . debug ( "diff info: %s %s %d" , toUUID , fromUUID , size ) Diff . theKnownSizes [ toUUID ] [ fromUUID ] = size except Exception as error : logger . warn ( "Can't read .bs info file (%s)" , error )
Read previously - written information about diffs .
61,431
def make ( cls , vol ) : if isinstance ( vol , cls ) : return vol elif vol is None : return None else : return cls ( vol , None )
Convert uuid to Volume if necessary .
61,432
def hasEdge ( self , diff ) : return diff . toVol in [ d . toVol for d in self . diffs [ diff . fromVol ] ]
Test whether edge is in this sink .
61,433
def _parseKeyName ( self , name ) : if name . endswith ( Store . theInfoExtension ) : return { 'type' : 'info' } match = self . keyPattern . match ( name ) if not match : return None match = match . groupdict ( ) match . update ( type = 'diff' ) return match
Returns dict with fullpath to from .
61,434
def humanize ( number ) : units = ( 'bytes' , 'KiB' , 'MiB' , 'GiB' , 'TiB' ) base = 1024 if number is None : return None pow = int ( math . log ( number , base ) ) if number > 0 else 0 pow = min ( pow , len ( units ) - 1 ) mantissa = number / ( base ** pow ) return "%.4g %s" % ( mantissa , units [ pow ] )
Return a human - readable string for number .
61,435
def receive ( self , path , diff , showProgress = True ) : directory = os . path . dirname ( path ) cmd = [ "btrfs" , "receive" , "-e" , directory ] if Store . skipDryRun ( logger , self . dryrun ) ( "Command: %s" , cmd ) : return None if not os . path . exists ( directory ) : os . makedirs ( directory ) process = subprocess . Popen ( cmd , stdin = subprocess . PIPE , stderr = subprocess . PIPE , stdout = DEVNULL , ) _makeNice ( process ) return _Writer ( process , process . stdin , path , diff , showProgress )
Return a context manager for stream that will store a diff .
61,436
def iterDiffs ( self ) : nodes = self . nodes . values ( ) nodes . sort ( key = lambda node : self . _height ( node ) ) for node in nodes : yield node . diff
Return all diffs used in optimal network .
61,437
def _prune ( self ) : done = False while not done : done = True for node in [ node for node in self . nodes . values ( ) if node . intermediate ] : if not [ dep for dep in self . nodes . values ( ) if dep . previous == node . volume ] : del self . nodes [ node . volume ] done = False
Get rid of all intermediate nodes that aren t needed .
61,438
def __compress_attributes ( self , dic ) : result = { } for k , v in dic . iteritems ( ) : if isinstance ( v , types . ListType ) and len ( v ) == 1 : if k not in ( 'msExchMailboxSecurityDescriptor' , 'msExchSafeSendersHash' , 'msExchBlockedSendersHash' , 'replicationSignature' , 'msExchSafeRecipientsHash' , 'sIDHistory' , 'msRTCSIP-UserRoutingGroupId' , 'mSMQDigests' , 'mSMQSignCertificates' , 'msExchMasterAccountSid' , 'msExchPreviousAccountSid' , 'msExchUMPinChecksum' , 'userSMIMECertificate' , 'userCertificate' , 'userCert' , 'msExchDisabledArchiveGUID' , 'msExchUMPinChecksum' , 'msExchUMSpokenName' , 'objectSid' , 'objectGUID' , 'msExchArchiveGUID' , 'thumbnailPhoto' , 'msExchMailboxGuid' ) : try : result [ k ] = v [ 0 ] . decode ( 'utf-8' ) except Exception as e : logging . error ( "Failed to decode attribute: %s -- %s" % ( k , e ) ) result [ k ] = v [ 0 ] return result
This will convert all attributes that are list with only one item string into simple string . It seems that LDAP always return lists even when it doesn t make sense .
61,439
def _keepVol ( self , vol ) : if vol is None : return if vol in self . extraVolumes : del self . extraVolumes [ vol ] return if vol not in self . paths : raise Exception ( "%s not in %s" % ( vol , self ) ) paths = [ os . path . basename ( path ) for path in self . paths [ vol ] ] newPath = self . selectReceivePath ( paths ) if self . _skipDryRun ( logger , 'INFO' ) ( "Copy %s to %s" , vol , newPath ) : return self . butterVolumes [ vol . uuid ] . copy ( newPath )
Mark this volume to be kept in path .
61,440
def write ( self , keyArgs ) : args = array . array ( 'B' , ( 0 , ) * self . size ) self . _struct . pack_into ( args , 0 , * list ( self . yieldArgs ( keyArgs ) ) ) return args
Write specified key arguments into data structure .
61,441
def popValue ( self , argList ) : return self . _Tuple ( * [ typeObj . popValue ( argList ) for ( name , typeObj ) in self . _types . items ( ) ] )
Take a flat arglist and pop relevent values and return as a value or tuple .
61,442
def read ( self , structure ) : start = self . offset self . skip ( structure . size ) return structure . read ( self . buf , start )
Read and advance .
61,443
def readView ( self , newLength = None ) : if newLength is None : newLength = self . len result = self . peekView ( newLength ) self . skip ( newLength ) return result
Return a view of the next newLength bytes and skip it .
61,444
def peekView ( self , newLength ) : return memoryview ( self . buf ) [ self . offset : self . offset + newLength ]
Return a view of the next newLength bytes .
61,445
def readBuffer ( self , newLength ) : result = Buffer ( self . buf , self . offset , newLength ) self . skip ( newLength ) return result
Read next chunk as another buffer .
61,446
def _IOC ( cls , dir , op , structure = None ) : control = cls ( dir , op , structure ) def do ( dev , ** args ) : return control ( dev , ** args ) return do
Encode an ioctl id .
61,447
def IOWR ( cls , op , structure ) : return cls . _IOC ( READ | WRITE , op , structure )
Returns an ioctl Device method with READ and WRITE arguments .
61,448
def bytes2uuid ( b ) : if b . strip ( chr ( 0 ) ) == '' : return None s = b . encode ( 'hex' ) return "%s-%s-%s-%s-%s" % ( s [ 0 : 8 ] , s [ 8 : 12 ] , s [ 12 : 16 ] , s [ 16 : 20 ] , s [ 20 : ] )
Return standard human - friendly UUID .
61,449
def fullPath ( self ) : for ( ( dirTree , dirID , dirSeq ) , ( dirPath , name ) ) in self . links . items ( ) : try : path = self . fileSystem . volumes [ dirTree ] . fullPath if path is not None : return path + ( "/" if path [ - 1 ] != "/" else "" ) + dirPath + name except Exception : logging . debug ( "Haven't imported %d yet" , dirTree ) if self . id == BTRFS_FS_TREE_OBJECTID : return "/" else : return None
Return full butter path from butter root .
61,450
def linuxPaths ( self ) : for ( ( dirTree , dirID , dirSeq ) , ( dirPath , name ) ) in self . links . items ( ) : for path in self . fileSystem . volumes [ dirTree ] . linuxPaths : yield path + "/" + dirPath + name if self . fullPath in self . fileSystem . mounts : yield self . fileSystem . mounts [ self . fullPath ]
Return full paths from linux root .
61,451
def destroy ( self ) : path = next ( iter ( self . linuxPaths ) ) directory = _Directory ( os . path . dirname ( path ) ) with directory as device : device . SNAP_DESTROY ( name = str ( os . path . basename ( path ) ) , )
Delete this subvolume from the filesystem .
61,452
def copy ( self , path ) : directoryPath = os . path . dirname ( path ) if not os . path . exists ( directoryPath ) : os . makedirs ( directoryPath ) logger . debug ( 'Create copy of %s in %s' , os . path . basename ( path ) , directoryPath ) with self . _snapshot ( ) as source , _Directory ( directoryPath ) as dest : dest . SNAP_CREATE_V2 ( flags = BTRFS_SUBVOL_RDONLY , name = str ( os . path . basename ( path ) ) , fd = source . fd , ) with SnapShot ( path ) as destShot : flags = destShot . SUBVOL_GETFLAGS ( ) destShot . SUBVOL_SETFLAGS ( flags = flags . flags & ~ BTRFS_SUBVOL_RDONLY ) destShot . SET_RECEIVED_SUBVOL ( uuid = self . received_uuid or self . uuid , stransid = self . sent_gen or self . current_gen , stime = timeOrNone ( self . info . stime ) or timeOrNone ( self . info . ctime ) or 0 , flags = 0 , ) destShot . SUBVOL_SETFLAGS ( flags = flags . flags )
Make another snapshot of this into dirName .
61,453
def subvolumes ( self ) : self . SYNC ( ) self . _getDevices ( ) self . _getRoots ( ) self . _getMounts ( ) self . _getUsage ( ) volumes = self . volumes . values ( ) volumes . sort ( key = ( lambda v : v . fullPath ) ) return volumes
Subvolumes contained in this mount .
61,454
def _rescanSizes ( self , force = True ) : status = self . QUOTA_CTL ( cmd = BTRFS_QUOTA_CTL_ENABLE ) . status logger . debug ( "CTL Status: %s" , hex ( status ) ) status = self . QUOTA_RESCAN_STATUS ( ) logger . debug ( "RESCAN Status: %s" , status ) if not status . flags : if not force : return self . QUOTA_RESCAN ( ) logger . warn ( "Waiting for btrfs quota usage scan..." ) self . QUOTA_RESCAN_WAIT ( )
Zero and recalculate quota sizes to subvolume sizes will be correct .
61,455
def TLV_GET ( attrs , attrNum , format ) : attrView = attrs [ attrNum ] if format == 's' : format = str ( attrView . len ) + format try : ( result , ) = struct . unpack_from ( format , attrView . buf , attrView . offset ) except TypeError : ( result , ) = struct . unpack_from ( format , str ( bytearray ( attrView . buf ) ) , attrView . offset ) return result
Get a tag - length - value encoded attribute .
61,456
def TLV_PUT ( attrs , attrNum , format , value ) : attrView = attrs [ attrNum ] if format == 's' : format = str ( attrView . len ) + format struct . pack_into ( format , attrView . buf , attrView . offset , value )
Put a tag - length - value encoded attribute .
61,457
def command ( name , mode ) : def decorator ( fn ) : commands [ name ] = fn . __name__ _Client . _addMethod ( fn . __name__ , name , mode ) return fn return decorator
Label a method as a command with name .
61,458
def diff ( self , diff ) : if diff is None : return None return dict ( toVol = diff . toUUID , fromVol = diff . fromUUID , size = diff . size , sizeIsEstimated = diff . sizeIsEstimated , )
Serialize to a dictionary .
61,459
def _open ( self ) : if self . _process is not None : return cmd = [ 'ssh' , self . _host , 'sudo' , 'buttersink' , '--server' , '--mode' , self . _mode , self . _directory ] logger . debug ( "Connecting with: %s" , cmd ) self . _process = subprocess . Popen ( cmd , stdin = subprocess . PIPE , stderr = sys . stderr , stdout = subprocess . PIPE , ) version = self . version ( ) logger . info ( "Remote version: %s" , version )
Open connection to remote host .
61,460
def _close ( self ) : if self . _process is None : return self . quit ( ) self . _process . stdin . close ( ) logger . debug ( "Waiting for ssh process to finish..." ) self . _process . wait ( ) self . _process = None
Close connection to remote host .
61,461
def run ( self ) : normalized = os . path . normpath ( self . path ) + ( "/" if self . path . endswith ( "/" ) else "" ) if self . path != normalized : sys . stderr . write ( "Please use full path '%s'" % ( normalized , ) ) return - 1 self . butterStore = ButterStore . ButterStore ( None , self . path , self . mode , dryrun = False ) self . toObj = _Arg2Obj ( self . butterStore ) self . toDict = _Obj2Dict ( ) self . running = True with self . butterStore : with self : while self . running : self . _processCommand ( ) return 0
Run the server . Returns with system error code .
61,462
def _sendResult ( self , result ) : try : result = json . dumps ( result ) except Exception as error : result = json . dumps ( self . _errorInfo ( command , error ) ) sys . stdout . write ( result ) sys . stdout . write ( "\n" ) sys . stdout . flush ( )
Send parseable json result of command .
61,463
def version ( self ) : return dict ( buttersink = theVersion , btrfs = self . butterStore . butter . btrfsVersion , linux = platform . platform ( ) , )
Return kernel and btrfs version .
61,464
def send ( self , diffTo , diffFrom ) : diff = self . toObj . diff ( diffTo , diffFrom ) self . _open ( self . butterStore . send ( diff ) )
Do a btrfs send .
61,465
def receive ( self , path , diffTo , diffFrom ) : diff = self . toObj . diff ( diffTo , diffFrom ) self . _open ( self . butterStore . receive ( diff , [ path , ] ) )
Receive a btrfs diff .
61,466
def fillVolumesAndPaths ( self ) : return [ ( self . toDict . vol ( vol ) , paths ) for vol , paths in self . butterStore . paths . items ( ) ]
Get all volumes for initialization .
61,467
def load_lists ( keys = [ ] , values = [ ] , name = 'NT' ) : mapping = dict ( zip ( keys , values ) ) return mapper ( mapping , _nt_name = name )
Map namedtuples given a pair of key value lists .
61,468
def load_json ( data = None , path = None , name = 'NT' ) : if data and not path : return mapper ( json . loads ( data ) , _nt_name = name ) if path and not data : return mapper ( json . load ( path ) , _nt_name = name ) if data and path : raise ValueError ( 'expected one source and received two' )
Map namedtuples with json data .
61,469
def load_yaml ( data = None , path = None , name = 'NT' ) : if data and not path : return mapper ( yaml . load ( data ) , _nt_name = name ) if path and not data : with open ( path , 'r' ) as f : data = yaml . load ( f ) return mapper ( data , _nt_name = name ) if data and path : raise ValueError ( 'expected one source and received two' )
Map namedtuples with yaml data .
61,470
def mapper ( mapping , _nt_name = 'NT' ) : if isinstance ( mapping , Mapping ) and not isinstance ( mapping , AsDict ) : for key , value in list ( mapping . items ( ) ) : mapping [ key ] = mapper ( value ) return namedtuple_wrapper ( _nt_name , ** mapping ) elif isinstance ( mapping , list ) : return [ mapper ( item ) for item in mapping ] return mapping
Convert mappings to namedtuples recursively .
61,471
def ignore ( mapping ) : if isinstance ( mapping , Mapping ) : return AsDict ( mapping ) elif isinstance ( mapping , list ) : return [ ignore ( item ) for item in mapping ] return mapping
Use ignore to prevent a mapping from being mapped to a namedtuple .
61,472
def ensure_dir ( dir_path ) : exists = dir_exists ( dir_path ) if not exists : try : os . makedirs ( dir_path ) except ( Exception , RuntimeError ) , e : raise Exception ( "Unable to create directory %s. Cause %s" % ( dir_path , e ) ) return exists
If DIR_PATH does not exist makes it . Failing that raises Exception . Returns True if dir already existed ; False if it had to be made .
61,473
def validate_openssl ( ) : try : open_ssl_exe = which ( "openssl" ) if not open_ssl_exe : raise Exception ( "No openssl exe found in path" ) try : execute_command ( [ open_ssl_exe , "s_client" , "invalidDummyCommand" ] ) except subprocess . CalledProcessError as e : if "fallback_scsv" not in e . output : raise Exception ( "openssl does not support TLS_FALLBACK_SCSV" ) except Exception as e : raise MongoctlException ( "Unsupported OpenSSL. %s" % e )
Validates OpenSSL to ensure it has TLS_FALLBACK_SCSV supported
61,474
def validate_against_current_config ( self , current_rs_conf ) : if not current_rs_conf : return my_host = self . get_host ( ) current_member_confs = current_rs_conf [ 'members' ] err = None for curr_mem_conf in current_member_confs : if ( self . id and self . id == curr_mem_conf [ '_id' ] and not is_same_address ( my_host , curr_mem_conf [ 'host' ] ) ) : err = ( "Member config is not consistent with current rs " "config. \n%s\n. Both have the sam _id but addresses" " '%s' and '%s' do not resolve to the same host." % ( document_pretty_string ( curr_mem_conf ) , my_host , curr_mem_conf [ 'host' ] ) ) elif ( is_same_address ( my_host , curr_mem_conf [ 'host' ] ) and self . id and self . id != curr_mem_conf [ '_id' ] ) : err = ( "Member config is not consistent with current rs " "config. \n%s\n. Both addresses" " '%s' and '%s' resolve to the same host but _ids '%s'" " and '%s' are not equal." % ( document_pretty_string ( curr_mem_conf ) , my_host , curr_mem_conf [ 'host' ] , self . id , curr_mem_conf [ '_id' ] ) ) if err : raise MongoctlException ( "Invalid member configuration:\n%s \n%s" % ( self , err ) )
Validates the member document against current rs conf 1 - If there is a member in current config with _id equals to my id then ensure hosts addresses resolve to the same host
61,475
def get_dump_best_secondary ( self , max_repl_lag = None ) : secondary_lag_tuples = [ ] primary_member = self . get_primary_member ( ) if not primary_member : raise MongoctlException ( "Unable to determine primary member for" " cluster '%s'" % self . id ) master_status = primary_member . get_server ( ) . get_member_rs_status ( ) if not master_status : raise MongoctlException ( "Unable to determine replicaset status for" " primary member '%s'" % primary_member . get_server ( ) . id ) for member in self . get_members ( ) : if member . get_server ( ) . is_secondary ( ) : repl_lag = member . get_server ( ) . get_repl_lag ( master_status ) if max_repl_lag and repl_lag > max_repl_lag : log_info ( "Excluding member '%s' because it's repl lag " "(in seconds)%s is more than max %s. " % ( member . get_server ( ) . id , repl_lag , max_repl_lag ) ) continue secondary_lag_tuples . append ( ( member , repl_lag ) ) def best_secondary_comp ( x , y ) : x_mem , x_lag = x y_mem , y_lag = y if x_mem . is_passive ( ) : if y_mem . is_passive ( ) : return x_lag - y_lag else : return - 1 elif y_mem . is_passive ( ) : return 1 else : return x_lag - y_lag if secondary_lag_tuples : secondary_lag_tuples . sort ( best_secondary_comp ) return secondary_lag_tuples [ 0 ] [ 0 ]
Returns the best secondary member to be used for dumping best = passives with least lags if no passives then least lag
61,476
def is_replicaset_initialized ( self ) : for member in self . get_members ( ) : server = member . get_server ( ) if server . has_joined_replica ( ) : return True return False
iterate on all members and check if any has joined the replica
61,477
def match_member_id ( self , member_conf , current_member_confs ) : if current_member_confs is None : return None for curr_mem_conf in current_member_confs : if is_same_address ( member_conf [ 'host' ] , curr_mem_conf [ 'host' ] ) : return curr_mem_conf [ '_id' ] return None
Attempts to find an id for member_conf where fom current members confs there exists a element . Returns the id of an element of current confs WHERE member_conf . host and element . host are EQUAL or map to same host
61,478
def get_os_dist_info ( ) : distribution = platform . dist ( ) dist_name = distribution [ 0 ] . lower ( ) dist_version_str = distribution [ 1 ] if dist_name and dist_version_str : return dist_name , dist_version_str else : return None , None
Returns the distribution info
61,479
def get_mongo_version ( self ) : if self . _mongo_version : return self . _mongo_version mongo_version = self . read_current_mongo_version ( ) if not mongo_version : mongo_version = self . get_configured_mongo_version ( ) self . _mongo_version = mongo_version return self . _mongo_version
Gets mongo version of the server if it is running . Otherwise return version configured in mongoVersion property
61,480
def get_server_build_info ( self ) : if self . is_online ( ) : try : return self . get_mongo_client ( ) . server_info ( ) except OperationFailure , ofe : log_exception ( ofe ) if "there are no users authenticated" in str ( ofe ) : admin_db = self . get_db ( "admin" , no_auth = False ) return admin_db . command ( "buildinfo" ) except Exception , e : log_exception ( e ) return None
issues a buildinfo command
61,481
def authenticate_db ( self , db , dbname , retry = True ) : log_verbose ( "Server '%s' attempting to authenticate to db '%s'" % ( self . id , dbname ) ) login_user = self . get_login_user ( dbname ) username = None password = None auth_success = False if login_user : username = login_user [ "username" ] if "password" in login_user : password = login_user [ "password" ] no_tries = 0 while not auth_success and no_tries < 3 : if not username : username = read_username ( dbname ) if not password : password = self . lookup_password ( dbname , username ) if not password : password = read_password ( "Enter password for user '%s\%s'" % ( dbname , username ) ) try : auth_success = db . authenticate ( username , password ) log_verbose ( "Authentication attempt #%s to db '%s' result: %s" % ( no_tries , dbname , auth_success ) ) except OperationFailure , ofe : if "auth fails" in str ( ofe ) : auth_success = False if auth_success or not retry : break else : log_error ( "Invalid login!" ) username = None password = None no_tries += 1 if auth_success : self . set_login_user ( dbname , username , password ) log_verbose ( "Authentication Succeeded!" ) else : log_verbose ( "Authentication failed" ) return auth_success
Returns True if we manage to auth to the given db else False .
61,482
def needs_repl_key ( self ) : cluster = self . get_cluster ( ) return ( self . supports_repl_key ( ) and cluster is not None and cluster . get_repl_key ( ) is not None )
We need a repl key if you are auth + a cluster member + version is None or > = 2 . 0 . 0
61,483
def exact_or_minor_exe_version_match ( executable_name , exe_version_tuples , version ) : exe = exact_exe_version_match ( executable_name , exe_version_tuples , version ) if not exe : exe = minor_exe_version_match ( executable_name , exe_version_tuples , version ) return exe
IF there is an exact match then use it OTHERWISE try to find a minor version match
61,484
def seconds ( num ) : now = pytime . time ( ) end = now + num until ( end )
Pause for this many seconds
61,485
def _pre_mongod_server_start ( server , options_override = None ) : lock_file_path = server . get_lock_file_path ( ) no_journal = ( server . get_cmd_option ( "nojournal" ) or ( options_override and "nojournal" in options_override ) ) if ( os . path . exists ( lock_file_path ) and server . is_arbiter_server ( ) and no_journal ) : log_warning ( "WARNING: Detected a lock file ('%s') for your server '%s'" " ; since this server is an arbiter, there is no need for" " repair or other action. Deleting mongod.lock and" " proceeding..." % ( lock_file_path , server . id ) ) try : os . remove ( lock_file_path ) except Exception , e : log_exception ( e ) raise MongoctlException ( "Error while trying to delete '%s'. " "Cause: %s" % ( lock_file_path , e ) )
Does necessary work before starting a server
61,486
def prepare_mongod_server ( server ) : log_info ( "Preparing server '%s' for use as configured..." % server . id ) cluster = server . get_cluster ( ) if server . supports_local_users ( ) : users . setup_server_local_users ( server ) if not server . is_cluster_member ( ) or server . is_standalone_config_server ( ) : users . setup_server_users ( server ) if cluster and server . is_primary ( ) : users . setup_cluster_users ( cluster , server )
Contains post start server operations
61,487
def _rlimit_min ( one_val , nother_val ) : if one_val < 0 or nother_val < 0 : return max ( one_val , nother_val ) else : return min ( one_val , nother_val )
Returns the more stringent rlimit value . - 1 means no limit .
61,488
def parse ( self , data ) : graph = self . _init_graph ( ) if 'type' not in data or data [ 'type' ] != 'NetworkGraph' : raise ParserError ( 'Parse error, not a NetworkGraph object' ) required_keys = [ 'protocol' , 'version' , 'metric' , 'nodes' , 'links' ] for key in required_keys : if key not in data : raise ParserError ( 'Parse error, "{0}" key not found' . format ( key ) ) self . protocol = data [ 'protocol' ] self . version = data [ 'version' ] self . revision = data . get ( 'revision' ) self . metric = data [ 'metric' ] for node in data [ 'nodes' ] : graph . add_node ( node [ 'id' ] , label = node [ 'label' ] if 'label' in node else None , local_addresses = node . get ( 'local_addresses' , [ ] ) , ** node . get ( 'properties' , { } ) ) for link in data [ 'links' ] : try : source = link [ "source" ] dest = link [ "target" ] cost = link [ "cost" ] except KeyError as e : raise ParserError ( 'Parse error, "%s" key not found' % e ) properties = link . get ( 'properties' , { } ) graph . add_edge ( source , dest , weight = cost , ** properties ) return graph
Converts a NetJSON NetworkGraph object to a NetworkX Graph object which is then returned . Additionally checks for protocol version revision and metric .
61,489
def parse ( self , data ) : graph = self . _init_graph ( ) server = self . _server_common_name graph . add_node ( server ) if data is None : clients = [ ] links = [ ] else : clients = data . client_list . values ( ) links = data . routing_table . values ( ) for client in clients : if client . common_name == 'UNDEF' : continue client_properties = { 'label' : client . common_name , 'real_address' : str ( client . real_address . host ) , 'port' : int ( client . real_address . port ) , 'connected_since' : client . connected_since . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) , 'bytes_received' : int ( client . bytes_received ) , 'bytes_sent' : int ( client . bytes_sent ) } local_addresses = [ str ( route . virtual_address ) for route in data . routing_table . values ( ) if route . real_address == client . real_address ] if local_addresses : client_properties [ 'local_addresses' ] = local_addresses graph . add_node ( str ( client . real_address . host ) , ** client_properties ) for link in links : if link . common_name == 'UNDEF' : continue graph . add_edge ( server , str ( link . real_address . host ) , weight = 1 ) return graph
Converts a OpenVPN JSON to a NetworkX Graph object which is then returned .
61,490
def _txtinfo_to_python ( self , data ) : self . _format = 'txtinfo' lines = data . split ( '\n' ) try : start = lines . index ( 'Table: Topology' ) + 2 except ValueError : raise ParserError ( 'Unrecognized format' ) topology_lines = [ line for line in lines [ start : ] if line ] parsed_lines = [ ] for line in topology_lines : values = line . split ( ' ' ) parsed_lines . append ( { 'source' : values [ 0 ] , 'target' : values [ 1 ] , 'cost' : float ( values [ 4 ] ) } ) return parsed_lines
Converts txtinfo format to python
61,491
def _get_primary_address ( self , mac_address , node_list ) : for local_addresses in node_list : if mac_address in local_addresses : return local_addresses [ 0 ] return mac_address
Uses the _get_aggregated_node_list structure to find the primary mac address associated to a secondary one if none is found returns itself .
61,492
def _get_aggregated_node_list ( self , data ) : node_list = [ ] for node in data : local_addresses = [ node [ 'primary' ] ] if 'secondary' in node : local_addresses += node [ 'secondary' ] node_list . append ( local_addresses ) return node_list
Returns list of main and secondary mac addresses .
61,493
def _parse_alfred_vis ( self , data ) : graph = self . _init_graph ( ) if 'source_version' in data : self . version = data [ 'source_version' ] if 'vis' not in data : raise ParserError ( 'Parse error, "vis" key not found' ) node_list = self . _get_aggregated_node_list ( data [ 'vis' ] ) for node in data [ "vis" ] : for neigh in node [ "neighbors" ] : graph . add_node ( node [ 'primary' ] , ** { 'local_addresses' : node . get ( 'secondary' , [ ] ) , 'clients' : node . get ( 'clients' , [ ] ) } ) primary_neigh = self . _get_primary_address ( neigh [ 'neighbor' ] , node_list ) graph . add_edge ( node [ 'primary' ] , primary_neigh , weight = float ( neigh [ 'metric' ] ) ) return graph
Converts a alfred - vis JSON object to a NetworkX Graph object which is then returned . Additionally checks for source_vesion to determine the batman - adv version .
61,494
def json ( self , dict = False , ** kwargs ) : try : graph = self . graph except AttributeError : raise NotImplementedError ( ) return _netjson_networkgraph ( self . protocol , self . version , self . revision , self . metric , graph . nodes ( data = True ) , graph . edges ( data = True ) , dict , ** kwargs )
Outputs NetJSON format
61,495
def diff ( old , new ) : protocol = new . protocol version = new . version revision = new . revision metric = new . metric in_both = _find_unchanged ( old . graph , new . graph ) added_nodes , added_edges = _make_diff ( old . graph , new . graph , in_both ) removed_nodes , removed_edges = _make_diff ( new . graph , old . graph , in_both ) changed_edges = _find_changed ( old . graph , new . graph , in_both ) if added_nodes . nodes ( ) or added_edges . edges ( ) : added = _netjson_networkgraph ( protocol , version , revision , metric , added_nodes . nodes ( data = True ) , added_edges . edges ( data = True ) , dict = True ) else : added = None if removed_nodes . nodes ( ) or removed_edges . edges ( ) : removed = _netjson_networkgraph ( protocol , version , revision , metric , removed_nodes . nodes ( data = True ) , removed_edges . edges ( data = True ) , dict = True ) else : removed = None if changed_edges : changed = _netjson_networkgraph ( protocol , version , revision , metric , [ ] , changed_edges , dict = True ) else : changed = None return OrderedDict ( ( ( 'added' , added ) , ( 'removed' , removed ) , ( 'changed' , changed ) ) )
Returns differences of two network topologies old and new in NetJSON NetworkGraph compatible format
61,496
def _make_diff ( old , new , both ) : diff_edges = new . copy ( ) not_different = [ tuple ( edge ) for edge in both ] diff_edges . remove_edges_from ( not_different ) diff_nodes = new . copy ( ) not_different = [ ] for new_node in new . nodes ( ) : if new_node in old . nodes ( ) : not_different . append ( new_node ) diff_nodes . remove_nodes_from ( not_different ) return diff_nodes , diff_edges
calculates differences between topologies old and new returns a tuple with two network graph objects the first graph contains the added nodes the secnod contains the added links
61,497
def _find_unchanged ( old , new ) : edges = [ ] old_edges = [ set ( edge ) for edge in old . edges ( ) ] new_edges = [ set ( edge ) for edge in new . edges ( ) ] for old_edge in old_edges : if old_edge in new_edges : edges . append ( set ( old_edge ) ) return edges
returns edges that are in both old and new
61,498
def _find_changed ( old , new , both ) : old_edges = [ ] for edge in old . edges ( data = True ) : if set ( ( edge [ 0 ] , edge [ 1 ] ) ) not in both : continue cost = ( edge [ 2 ] [ 'weight' ] , ) old_edges . append ( set ( ( edge [ 0 ] , edge [ 1 ] , cost ) ) ) new_edges = [ ] for edge in new . edges ( data = True ) : if set ( ( edge [ 0 ] , edge [ 1 ] ) ) not in both : continue cost = ( edge [ 2 ] [ 'weight' ] , ) new_edges . append ( set ( ( edge [ 0 ] , edge [ 1 ] , cost ) ) ) changed = [ ] for new_edge in new_edges : if new_edge not in old_edges : new_edge = list ( new_edge ) for item in new_edge : if isinstance ( item , tuple ) : cost = { 'weight' : item [ 0 ] } new_edge . remove ( item ) changed . append ( ( new_edge [ 0 ] , new_edge [ 1 ] , cost ) ) return changed
returns links that have changed cost
61,499
def parse ( self , data ) : graph = self . _init_graph ( ) if len ( data ) != 0 : if "links" not in data [ 0 ] : raise ParserError ( 'Parse error, "links" key not found' ) for node in data : for link in node [ 'links' ] : cost = ( link [ 'txRate' ] + link [ 'rxRate' ] ) / 2.0 graph . add_edge ( node [ 'name' ] , link [ 'name' ] , weight = cost , tx_rate = link [ 'txRate' ] , rx_rate = link [ 'rxRate' ] ) return graph
Converts a BMX6 b6m JSON to a NetworkX Graph object which is then returned .