code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if parent is not None:
cmd = ["btrfs", "send", "-p", parent, targetPath]
else:
cmd = ["btrfs", "send", targetPath]
if Store.skipDryRun(logger, self.dryrun and allowDryRun)("Command: %s", cmd):
return None
process = subprocess.Popen(
... | def send(self, targetPath, parent, diff, showProgress=True, allowDryRun=True) | Return context manager for stream to send a (incremental) snapshot. | 5.104212 | 4.753343 | 1.073815 |
measureSize = False
if self.measureSize:
for sink in sinks:
if sink.isRemote:
measureSize = True
# Use destination (already uploaded) edges first
sinks = list(sinks)
sinks.reverse()
self.dest = sinks[0]
de... | def analyze(self, chunkSize, *sinks) | Figure out the best diffs to use to reach all our required volumes. | 5.222275 | 4.968009 | 1.051181 |
nodes = [None]
height = 1
def sortKey(node):
if node is None:
return None
return (node.intermediate, self._totalSize(node))
while len(nodes) > 0:
logger.debug("Analyzing %d nodes for height %d...", len(nodes), height)
... | def _analyzeDontMeasure(self, chunkSize, willMeasureLater, *sinks) | Figure out the best diffs to use to reach all our required volumes. | 3.818101 | 3.773661 | 1.011776 |
nodes = self.nodes.values()
nodes.sort(key=lambda node: self._height(node))
for node in nodes:
yield node.diff | def iterDiffs(self) | Return all diffs used in optimal network. | 5.006516 | 4.374624 | 1.144445 |
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]:
# logger.debug("Removing unnecessary node %s"... | def _prune(self) | Get rid of all intermediate nodes that aren't needed. | 4.636243 | 3.719424 | 1.246495 |
result = {}
for k, v in dic.iteritems():
if isinstance(v, types.ListType) and len(v) == 1:
if k not in ('msExchMailboxSecurityDescriptor', 'msExchSafeSendersHash', 'msExchBlockedSendersHash',
'replicationSignature', 'msExchSafeRecipientsH... | def __compress_attributes(self, dic) | 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.
:param dic:
:return: | 8.347741 | 7.466589 | 1.118013 |
with self.btrfs as mount:
for bv in mount.subvolumes:
if not bv.readOnly:
continue
vol = self._btrfsVol2StoreVol(bv)
if vol is None:
continue
path = bv.fullPath
if path... | def _fillVolumesAndPaths(self, paths) | Fill in paths.
:arg paths: = { Store.Volume: ["linux path",]} | 6.313319 | 6.015134 | 1.049573 |
if fromVol is None:
for toVol in self.paths:
yield Store.Diff(self, toVol, fromVol, toVol.size)
return
if fromVol not in self.paths:
return
fromBVol = self.butterVolumes[fromVol.uuid]
parentUUID = fromBVol.parent_uuid
... | def getEdges(self, fromVol) | Return the edges available from fromVol. | 4.629341 | 4.613497 | 1.003434 |
if not self.dryrun:
self._fileSystemSync()
path = self.selectReceivePath(paths)
if os.path.exists(path):
raise Exception(
"Path %s exists, can't receive %s" % (path, diff.toUUID)
)
return self.butter.receive(path, diff, self... | def receive(self, diff, paths) | Return Context Manager for a file-like (stream) object to store a diff. | 9.182008 | 8.791501 | 1.044419 |
path = self.selectReceivePath(paths)
path = path + Store.theInfoExtension
if Store.skipDryRun(logger, self.dryrun)("receive info to %s", path):
return None
return open(path, "w") | def receiveVolumeInfo(self, paths) | Return Context Manager for a file-like (stream) object to store volume info. | 21.044493 | 15.059114 | 1.397459 |
self._fileSystemSync()
sendContext = self.butter.send(
self.getSendPath(diff.toVol),
self.getSendPath(diff.fromVol),
diff,
showProgress=self.showProgress is not False,
allowDryRun=False,
)
class _Measure(io.RawIOBase)... | def measureSize(self, diff, chunkSize) | Spend some time to get an accurate size. | 4.252357 | 4.155299 | 1.023358 |
if not self.dryrun:
self._fileSystemSync()
return self.butter.send(
self.getSendPath(diff.toVol),
self.getSendPath(diff.fromVol),
diff,
self.showProgress is True,
) | def send(self, diff) | Write the diff (toVol from fromVol) to the stream context manager. | 12.244701 | 8.750844 | 1.399259 |
self._keepVol(diff.toVol)
self._keepVol(diff.fromVol) | def keep(self, diff) | Mark this diff (or volume) to be kept in path. | 14.555737 | 9.540895 | 1.525615 |
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]]
n... | def _keepVol(self, vol) | Mark this volume to be kept in path. | 6.872766 | 6.464991 | 1.063074 |
for (vol, path) in self.extraVolumes.items():
if not path.endswith(".part"):
continue
if self._skipDryRun(logger, 'INFO', dryrun=dryrun)("Delete subvolume %s", path):
continue
self.butterVolumes[vol.uuid].destroy() | def deletePartials(self, dryrun=False) | Delete any old partial uploads/downloads in path. | 15.560642 | 15.022298 | 1.035836 |
if isinstance(typeDef, Structure):
return (name, typeDef.fmt, typeDef)
if len != 1:
size = struct.calcsize(typeDef)
if typeDef not in "xspP":
typeDef = 's'
typeDef = str(len * size) + typeDef
fmtChar = typeDef[-1:]
... | def _parseDefinition(typeDef, name, len=1, reader=None, writer=None) | Return (name, format, type) for field.
type.popValue() and type.yieldArgs() must be implemented. | 6.065344 | 5.853687 | 1.036158 |
try:
keyArgs = keyArgs._asdict() if keyArgs else {}
except AttributeError:
pass
logger.debug('Args: %s', keyArgs)
for (name, typeObj) in self._types.items():
logger.debug('Yielding %s: %s', name, typeObj)
for arg in typeObj.yieldAr... | def yieldArgs(self, keyArgs) | Take (nested) dict(s) of args to set, and return flat list of args. | 3.394863 | 3.482483 | 0.97484 |
# bytearray doesn't work with fcntl
args = array.array('B', (0,) * self.size)
self._struct.pack_into(args, 0, *list(self.yieldArgs(keyArgs)))
return args | def write(self, keyArgs) | Write specified key arguments into data structure. | 7.707436 | 7.850152 | 0.98182 |
# return self._Tuple(*[name for (name, typeObj) in self._types.items()])
return self._Tuple(*[typeObj.popValue(argList) for (name, typeObj) in self._types.items()]) | def popValue(self, argList) | Take a flat arglist, and pop relevent values and return as a value or tuple. | 4.953573 | 4.72145 | 1.049164 |
if isinstance(data, Buffer):
return data.read(self)
try:
args = list(self._struct.unpack_from(data, offset))
except TypeError as error:
# Working around struct.unpack_from issue #10212
logger.debug("error: %s", error)
args = l... | def read(self, data, offset=0) | Read data structure and return (nested) named tuple(s). | 5.253538 | 5.031143 | 1.044204 |
start = self.offset
self.skip(structure.size)
return structure.read(self.buf, start) | def read(self, structure) | Read and advance. | 5.87206 | 4.714751 | 1.245466 |
if newLength is None:
newLength = self.len
result = self.peekView(newLength)
self.skip(newLength)
return result | def readView(self, newLength=None) | Return a view of the next newLength bytes, and skip it. | 3.788551 | 3.20411 | 1.182403 |
# Note: In Python 2.7, memoryviews can't be written to
# by the struct module. (BUG)
return memoryview(self.buf)[self.offset:self.offset + newLength] | def peekView(self, newLength) | Return a view of the next newLength bytes. | 9.085143 | 8.193732 | 1.108792 |
result = Buffer(self.buf, self.offset, newLength)
self.skip(newLength)
return result | def readBuffer(self, newLength) | Read next chunk as another buffer. | 5.045607 | 4.528277 | 1.114244 |
control = cls(dir, op, structure)
def do(dev, **args):
return control(dev, **args)
return do | def _IOC(cls, dir, op, structure=None) | Encode an ioctl id. | 8.068003 | 8.358295 | 0.965269 |
return cls._IOC(READ | WRITE, op, structure) | def IOWR(cls, op, structure) | Returns an ioctl Device method with READ and WRITE arguments. | 14.239271 | 8.133161 | 1.750767 |
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:]) | def bytes2uuid(b) | Return standard human-friendly UUID. | 2.142489 | 2.079977 | 1.030054 |
logger.debug("Link %d-%d-%d '%s%s'", dirTree, dirID, dirSeq, dirPath, name)
# assert dirTree != 0, (dirTree, dirID, dirSeq, dirPath, name)
assert (dirTree, dirID, dirSeq) not in self.links, (dirTree, dirID, dirSeq)
self.links[(dirTree, dirID, dirSeq)] = (dirPath, name)
... | def _addLink(self, dirTree, dirID, dirSeq, dirPath, name) | Add tree reference and name. (Hardlink). | 3.252141 | 3.061816 | 1.062161 |
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:... | def fullPath(self) | Return full butter path from butter root. | 8.166467 | 7.763216 | 1.051944 |
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] | def linuxPaths(self) | Return full paths from linux root.
The first path returned will be the path through the top-most mount.
(Usually the root). | 7.004802 | 7.259306 | 0.964941 |
path = next(iter(self.linuxPaths))
directory = _Directory(os.path.dirname(path))
with directory as device:
device.SNAP_DESTROY(name=str(os.path.basename(path)), ) | def destroy(self) | Delete this subvolume from the filesystem. | 16.730654 | 15.482584 | 1.080611 |
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:
des... | def copy(self, path) | Make another snapshot of this into dirName. | 5.490897 | 5.233372 | 1.049208 |
self.SYNC()
self._getDevices()
self._getRoots()
self._getMounts()
self._getUsage()
volumes = self.volumes.values()
volumes.sort(key=(lambda v: v.fullPath))
return volumes | def subvolumes(self) | Subvolumes contained in this mount. | 8.599795 | 8.012157 | 1.073343 |
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.Q... | def _rescanSizes(self, force=True) | Zero and recalculate quota sizes to subvolume sizes will be correct. | 6.544363 | 6.204071 | 1.05485 |
attrView = attrs[attrNum]
if format == 's':
format = str(attrView.len) + format
try:
(result,) = struct.unpack_from(format, attrView.buf, attrView.offset)
except TypeError:
# Working around struct.unpack_from issue #10212
(result,) = struct.unpack_from(format, str(by... | def TLV_GET(attrs, attrNum, format) | Get a tag-length-value encoded attribute. | 4.18215 | 4.263057 | 0.981021 |
attrView = attrs[attrNum]
if format == 's':
format = str(attrView.len) + format
struct.pack_into(format, attrView.buf, attrView.offset, value) | def TLV_PUT(attrs, attrNum, format, value) | Put a tag-length-value encoded attribute. | 4.635469 | 4.917673 | 0.942614 |
def decorator(fn):
commands[name] = fn.__name__
_Client._addMethod(fn.__name__, name, mode)
return fn
return decorator | def command(name, mode) | Label a method as a command with name. | 6.780758 | 6.11065 | 1.109662 |
if diff is None:
return None
return dict(
toVol=diff.toUUID,
fromVol=diff.fromUUID,
size=diff.size,
sizeIsEstimated=diff.sizeIsEstimated,
) | def diff(self, diff) | Serialize to a dictionary. | 6.209923 | 5.19461 | 1.195455 |
for (volDict, volPaths) in self._client.fillVolumesAndPaths():
vol = Store.Volume(**volDict)
paths[vol] = volPaths | def _fillVolumesAndPaths(self, paths) | Fill in paths.
:arg paths: = { Store.Volume: ["linux path",]} | 10.172731 | 7.626014 | 1.333951 |
return [
self.toObj.diff(diff)
for diff in self._client.getEdges(self.toArg.vol(fromVol))
] | def getEdges(self, fromVol) | Return the edges available from fromVol. | 14.754767 | 13.951896 | 1.057546 |
(toUUID, fromUUID) = self.toArg.diff(diff)
isInteractive = sys.stderr.isatty()
return self.toObj.diff(self._client.measureSize(
toUUID,
fromUUID,
diff.size,
chunkSize,
isInteractive,
)) | def measureSize(self, diff, chunkSize) | Spend some time to get an accurate size. | 9.306044 | 8.895638 | 1.046136 |
if Store.skipDryRun(logger, self.dryrun)("send %s", diff):
return None
(diffTo, diffFrom) = self.toArg.diff(diff)
self._client.send(diffTo, diffFrom)
progress = DisplayProgress(diff.size) if self.showProgress is True else None
return _SSHStream(self._client... | def send(self, diff) | Return Context Manager for a file-like (stream) object to send a diff. | 14.353644 | 12.432491 | 1.154527 |
path = self.selectReceivePath(paths)
path = self._relativePath(path)
if Store.skipDryRun(logger, self.dryrun)("receive to %s", path):
return None
(diffTo, diffFrom) = self.toArg.diff(diff)
self._client.receive(path, diffTo, diffFrom)
progress = Dis... | def receive(self, diff, paths) | Return Context Manager for a file-like (stream) object to store a diff. | 11.60487 | 10.264308 | 1.130604 |
path = self.selectReceivePath(paths)
path = path + Store.theInfoExtension
if Store.skipDryRun(logger, self.dryrun)("receive info to %s", path):
return None
self._client.receiveInfo(path)
return _SSHStream(self._client) | def receiveVolumeInfo(self, paths) | Return Context Manager for a file-like (stream) object to store volume info. | 20.680328 | 15.962123 | 1.295588 |
(toUUID, fromUUID) = self.toArg.diff(diff)
self._client.keep(toUUID, fromUUID)
logger.debug("Kept %s", diff) | def keep(self, diff) | Mark this diff (or volume) to be kept in path. | 12.069077 | 10.233559 | 1.179363 |
if self.dryrun:
self._client.listUnused()
else:
self._client.deleteUnused() | def deleteUnused(self) | Delete any old snapshots in path, if not kept. | 8.292638 | 7.487585 | 1.107518 |
if self.dryrun:
self._client.listPartials()
else:
self._client.deletePartials() | def deletePartials(self) | Delete any old partial uploads/downloads in path. | 6.412327 | 5.304012 | 1.208958 |
if self._process is not None:
return
cmd = [
'ssh',
self._host,
'sudo',
'buttersink',
'--server',
'--mode',
self._mode,
self._directory
]
logger.debug("Connecting with: %... | def _open(self) | Open connection to remote host. | 4.097122 | 3.82411 | 1.071392 |
if self._process is None:
return
self.quit()
self._process.stdin.close()
logger.debug("Waiting for ssh process to finish...")
self._process.wait() # Wait for ssh session to finish.
# self._process.terminate()
# self._process.kill()
... | def _close(self) | Close connection to remote host. | 4.41031 | 3.911325 | 1.127574 |
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=... | def run(self) | Run the server. Returns with system error code. | 6.302905 | 5.824775 | 1.082086 |
# logger.debug("Result: %s", 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() | def _sendResult(self, result) | Send parseable json result of command. | 3.683643 | 3.36822 | 1.093647 |
return dict(
buttersink=theVersion,
btrfs=self.butterStore.butter.btrfsVersion,
linux=platform.platform(),
) | def version(self) | Return kernel and btrfs version. | 22.1383 | 15.321767 | 1.444892 |
diff = self.toObj.diff(diffTo, diffFrom)
self._open(self.butterStore.send(diff)) | def send(self, diffTo, diffFrom) | Do a btrfs send. | 14.526685 | 13.595059 | 1.068527 |
diff = self.toObj.diff(diffTo, diffFrom)
self._open(self.butterStore.receive(diff, [path, ])) | def receive(self, path, diffTo, diffFrom) | Receive a btrfs diff. | 15.841477 | 15.728245 | 1.007199 |
size = int(size)
if size == 0:
self._close()
return
self._sendResult(dict(message="writing...", stream=True, size=size))
data = sys.stdin.read(size)
self.stream.write(data) | def streamWrite(self, size) | Send or receive a chunk of data.
:arg size: Amount of data. 0 indicates EOT. | 5.405608 | 6.770351 | 0.798424 |
size = int(size)
data = self.stream.read(size)
size = len(data)
if size == 0:
self._close()
return dict(message="Finished", size=0)
self._sendResult(dict(message="reading...", stream=True, size=size))
sys.stdout.write(data) | def streamRead(self, size) | Send or receive a chunk of data.
:arg size: Amount of data requested. | 5.032277 | 6.22227 | 0.808753 |
return [
(self.toDict.vol(vol), paths)
for vol, paths in self.butterStore.paths.items()
] | def fillVolumesAndPaths(self) | Get all volumes for initialization. | 17.640848 | 14.969651 | 1.178441 |
return [self.toDict.diff(d) for d in self.butterStore.getEdges(self.toObj.vol(fromVol))] | def getEdges(self, fromVol) | Return the edges available from fromVol. | 18.393951 | 16.499136 | 1.114843 |
diff = self.toObj.diff(diffTo, diffFrom, estimatedSize)
isInteractive = self.toObj.bool(isInteractive)
self.butterStore.showProgress = None if isInteractive else False
self.butterStore.measureSize(diff, int(chunkSize))
return self.toDict.diff(diff) | def measureSize(self, diffTo, diffFrom, estimatedSize, chunkSize, isInteractive) | Spend some time to get an accurate size. | 7.899531 | 7.309112 | 1.080779 |
diff = self.toObj.diff(diffTo, diffFrom)
self.butterStore.keep(diff) | def keep(self, diffTo, diffFrom) | Mark this diff (or volume) to be kept in path. | 11.626371 | 11.492064 | 1.011687 |
mapping = dict(zip(keys, values))
return mapper(mapping, _nt_name=name) | def load_lists(keys=[], values=[], name='NT') | Map namedtuples given a pair of key, value lists. | 8.907781 | 9.321383 | 0.955629 |
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') | def load_json(data=None, path=None, name='NT') | Map namedtuples with json data. | 4.871009 | 4.563128 | 1.067471 |
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') | def load_yaml(data=None, path=None, name='NT') | Map namedtuples with yaml data. | 3.624022 | 3.412867 | 1.06187 |
NT = namedtuple(name, keys)
if use_getpass:
values = [os.getenv(x) or getpass.getpass(x) for x in keys]
else:
values = [os.getenv(x) or input(x) for x in keys]
return NT(*values) | def load_env(keys=[], name='NT', use_getpass=False) | Returns a namedtuple from a list of environment variables.
If not found in shell, gets input with *input* or *getpass*. | 2.378519 | 2.32934 | 1.021113 |
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 ... | def mapper(mapping, _nt_name='NT') | Convert mappings to namedtuples recursively. | 3.125115 | 2.626757 | 1.189724 |
if isinstance(mapping, Mapping):
return AsDict(mapping)
elif isinstance(mapping, list):
return [ignore(item) for item in mapping]
return mapping | def ignore(mapping) | Use ignore to prevent a mapping from being mapped to a namedtuple. | 3.496676 | 3.330761 | 1.049813 |
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 | def ensure_dir(dir_path) | 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. | 3.676323 | 3.627061 | 1.013582 |
try:
if host1 == host2:
return True
else:
ips1 = get_host_ips(host1)
ips2 = get_host_ips(host2)
return len(set(ips1) & set(ips2)) > 0
except Exception, ex:
log_exception(ex)
return False | def is_same_host(host1, host2) | Returns true if host1 == host2 OR map to the same host (using DNS) | 2.18699 | 2.15976 | 1.012608 |
hostport1 = addr1.split(":")
hostport2 = addr2.split(":")
return (is_same_host(hostport1[0], hostport2[0]) and
hostport1[1] == hostport2[1]) | def is_same_address(addr1, addr2) | Where the two addresses are in the host:port
Returns true if ports are equals and hosts are the same using is_same_host | 2.447302 | 2.16843 | 1.128606 |
try:
open_ssl_exe = which("openssl")
if not open_ssl_exe:
raise Exception("No openssl exe found in path")
try:
# execute a an invalid command to get output with available options
# since openssl does not have a --help option unfortunately
... | def validate_openssl() | Validates OpenSSL to ensure it has TLS_FALLBACK_SCSV supported | 6.883953 | 5.587395 | 1.232051 |
# if rs is not configured yet then there is nothing to validate
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 ... | def validate_against_current_config(self, current_rs_conf) | 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
2- If there is a member in current config with host resolving to my
host then ensure that ... | 3.300334 | 2.909266 | 1.134421 |
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().g... | def get_dump_best_secondary(self, max_repl_lag=None) | Returns the best secondary member to be used for dumping
best = passives with least lags, if no passives then least lag | 2.502053 | 2.468341 | 1.013658 |
# it's possible isMaster returns an "incomplete" result if we
# query a replica set member while it's loading the replica set config
# https://jira.mongodb.org/browse/SERVER-13458
# let's try to detect this state before proceeding
# seems like if the "secondary" field i... | def is_replicaset_initialized(self) | iterate on all members and check if any has joined the replica | 10.829464 | 9.866689 | 1.097578 |
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 | def match_member_id(self, member_conf, current_member_confs) | 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 | 2.939477 | 3.017877 | 0.974022 |
log_info("Checking if there are any users that need to be added for "
"server '%s'..." % server.id)
seed_users = server.get_seed_users()
count_new_users = 0
# Note: If server member of a replica then don't setup admin
# users because primary server will do that at replinit... | def setup_server_users(server) | Seeds all users returned by get_seed_users() IF there are no users seed yet
i.e. system.users collection is empty | 5.330492 | 5.111954 | 1.042751 |
cred0 = get_global_login_user(server, "admin")
if cred0 and cred0["username"] and cred0["password"]:
log_verbose("Seeding : CRED0 to the front of the line!")
return [cred0] + other_users if other_users else [cred0]
else:
return other_users | def prepend_global_admin_user(other_users, server) | When making lists of administrative users -- e.g., seeding a new server --
it's useful to put the credentials supplied on the command line at the head
of the queue. | 8.233437 | 7.349882 | 1.120213 |
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 | def get_os_dist_info() | Returns the distribution info | 2.813348 | 2.618313 | 1.074489 |
cmd_options = super(MongosServer, self).export_cmd_options(
options_override=options_override)
# Add configServers arg
cluster = self.get_validate_cluster()
cmd_options["configdb"] = cluster.get_config_db_address()
return cmd_options | def export_cmd_options(self, options_override=None, standalone=False) | Override!
:return: | 6.058919 | 6.355231 | 0.953375 |
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 | def get_mongo_version(self) | Gets mongo version of the server if it is running. Otherwise return
version configured in mongoVersion property | 2.757666 | 2.590905 | 1.064364 |
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):
# this is a pymongo 3.6.1 regression whe... | def get_server_build_info(self) | issues a buildinfo command | 5.749879 | 5.370949 | 1.070552 |
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 "pass... | def authenticate_db(self, db, dbname, retry=True) | Returns True if we manage to auth to the given db, else False. | 3.46671 | 3.427277 | 1.011506 |
login_user = None
# this will authenticate and update login user
self.get_db(database, username=username, password=password,
never_auth_with_admin=True)
login_user = self.get_login_user(database)
if login_user:
username = login_user["... | def get_working_login(self, database, username=None, password=None) | authenticate to the specified database starting with specified
username/password (if present), try to return a successful login
within 3 attempts | 4.969137 | 5.121218 | 0.970304 |
log_debug("Checking if server '%s' needs to auth on db '%s'...." %
(self.id, dbname))
try:
client = self.get_mongo_client()
db = client.get_database(dbname)
db.collection_names()
result = False
except (RuntimeError,Excep... | def needs_to_auth(self, dbname) | Determines if the server needs to authenticate to the database.
NOTE: we stopped depending on is_auth() since its only a configuration
and may not be accurate | 5.22566 | 5.120834 | 1.020471 |
cluster = self.get_cluster()
return (self.supports_repl_key() and
cluster is not None and cluster.get_repl_key() is not None) | def needs_repl_key(self) | We need a repl key if you are auth + a cluster member +
version is None or >= 2.0.0 | 5.110581 | 4.153295 | 1.230488 |
exe = exact_exe_version_match(executable_name,
exe_version_tuples,
version)
if not exe:
exe = minor_exe_version_match(executable_name,
exe_version_tuples,
... | def exact_or_minor_exe_version_match(executable_name,
exe_version_tuples,
version) | IF there is an exact match then use it
OTHERWISE try to find a minor version match | 2.003459 | 2.154636 | 0.929836 |
# check if value is an id string
id_path = value.split("/")
id = id_path[0]
return len(id_path) <= 2 and (repository.lookup_server(id) or
repository.lookup_cluster(id)) | def is_server_or_cluster_db_address(value) | checks if the specified value is in the form of
[server or cluster id][/database] | 6.840094 | 6.106785 | 1.120081 |
end = time
# Convert datetime to unix timestamp and adjust for locality
if isinstance(time, datetime):
zoneDiff = pytime.time() - (datetime.now()- datetime(1970, 1, 1)).total_seconds()
end = (time - datetime(1970, 1, 1)).total_seconds() + zoneDiff
# Type check
if not isinstanc... | def until(time) | Pause your program until a specific end time.
'time' is either a valid datetime object or unix timestamp in seconds (i.e. seconds since Unix epoch) | 4.508637 | 4.468794 | 1.008916 |
now = pytime.time()
end = now + num
until(end) | def seconds(num) | Pause for this many seconds | 15.001471 | 14.069299 | 1.066256 |
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("W... | def _pre_mongod_server_start(server, options_override=None) | Does necessary work before starting a server
1- An efficiency step for arbiters running with --no-journal
* there is a lock file ==>
* server must not have exited cleanly from last run, and does not know
how to auto-recover (as a journalled server would)
* however: this is an arb... | 4.41306 | 3.866903 | 1.141239 |
log_info("Preparing server '%s' for use as configured..." %
server.id)
cluster = server.get_cluster()
# setup the local users if server supports that
if server.supports_local_users():
users.setup_server_local_users(server)
if not server.is_cluster_member() or server.is_st... | def prepare_mongod_server(server) | Contains post start server operations | 5.67294 | 5.447771 | 1.041332 |
if one_val < 0 or nother_val < 0 :
return max(one_val, nother_val)
else:
return min(one_val, nother_val) | def _rlimit_min(one_val, nother_val) | Returns the more stringent rlimit value. -1 means no limit. | 2.211318 | 2.047576 | 1.079969 |
command = []
if mongod_needs_numactl():
log_info("Running on a NUMA machine...")
command = apply_numactl(command)
# append the mongod executable
command.append(get_server_executable(server))
# create the command args
cmd_options = server.export_cmd_options(options_overrid... | def generate_start_command(server, options_override=None, standalone=False) | Check if we need to use numactl if we are running on a NUMA box.
10gen recommends using numactl on NUMA. For more info, see
http://www.mongodb.org/display/DOCS/NUMA | 6.149754 | 4.975574 | 1.235989 |
home_dir = super(MongodServer, self).get_server_home()
if not home_dir:
home_dir = self.get_db_path()
return home_dir | def get_server_home(self) | Override!
:return: | 4.094238 | 4.298272 | 0.952531 |
cmd_options = super(MongodServer, self).export_cmd_options(
options_override=options_override)
# reset some props to exporting vals
cmd_options['dbpath'] = self.get_db_path()
if 'repairpath' in cmd_options:
cmd_options['repairpath'] = resolve_path(cmd_o... | def export_cmd_options(self, options_override=None, standalone=False) | Override!
:return: | 3.637297 | 3.667837 | 0.991674 |
seed_users = super(MongodServer, self).get_seed_users()
# exempt database users for config servers
if seed_users and self.is_config_server():
for dbname in seed_users.keys():
if dbname not in ["admin", "local", "config"]:
del seed_users[db... | def get_seed_users(self) | Override!
:return: | 5.144785 | 5.17563 | 0.99404 |
member_status = self.get_member_rs_status()
if not member_status:
raise MongoctlException("Unable to determine replicaset status for"
" member '%s'" %
self.id)
return get_member_repl_lag(member_status,... | def get_repl_lag(self, master_status) | Given two 'members' elements from rs.status(),
return lag between their optimes (in secs). | 5.35988 | 4.78 | 1.121314 |
kwargs = kwargs or {}
connection_timeout_ms = kwargs.get("connectTimeoutMS") or CONN_TIMEOUT_MS
kwargs.update({
"socketTimeoutMS": connection_timeout_ms,
"connectTimeoutMS": connection_timeout_ms,
"maxPoolSize": 1
})
if pymongo.get_version_string().startswith("3.2"):
... | def mongo_client(*args, **kwargs) | wrapper around mongo client
:param args:
:param kwargs:
:return: | 3.104482 | 3.136197 | 0.989888 |
graph = self._init_graph()
# ensure is NetJSON NetworkGraph object
if 'type' not in data or data['type'] != 'NetworkGraph':
raise ParserError('Parse error, not a NetworkGraph object')
# ensure required keys are present
required_keys = ['protocol', 'version', ... | def parse(self, data) | Converts a NetJSON 'NetworkGraph' object
to a NetworkX Graph object,which is then returned.
Additionally checks for protocol version, revision and metric. | 2.869676 | 2.431046 | 1.180428 |
# initialize graph and list of aggregated nodes
graph = self._init_graph()
server = self._server_common_name
# add server (central node) to graph
graph.add_node(server)
# data may be empty
if data is None:
clients = []
links = []
... | def parse(self, data) | Converts a OpenVPN JSON to a NetworkX Graph object
which is then returned. | 3.058187 | 3.042991 | 1.004994 |
try:
return super(BatmanParser, self).to_python(data)
except ConversionException as e:
return self._txtinfo_to_python(e.data) | def to_python(self, data) | Adds support for txtinfo format | 8.131726 | 5.137048 | 1.582957 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.