Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _restore_backup(self):
input_filename, input_file = self._get_backup_file(database=self.database_name,
servername=self.servername)
self.logger.info("Restoring backup for database '%s' and... | [
"Restore the specified database."
] |
Please provide a description of the function:def handle(self, *args, **options):
self.verbosity = int(options.get('verbosity'))
self.quiet = options.get('quiet')
self._set_logger_level()
self.servername = options.get('servername')
self.decrypt = options.get('decrypt')
... | [
"Django command handler."
] |
Please provide a description of the function:def get_connector(database_name=None):
from django.db import connections, DEFAULT_DB_ALIAS
# Get DB
database_name = database_name or DEFAULT_DB_ALIAS
connection = connections[database_name]
engine = connection.settings_dict['ENGINE']
connector_se... | [
"\n Get a connector from its database key in setttings.\n "
] |
Please provide a description of the function:def settings(self):
if not hasattr(self, '_settings'):
sett = self.connection.settings_dict.copy()
sett.update(settings.CONNECTORS.get(self.database_name, {}))
self._settings = sett
return self._settings | [
"Mix of database and connector settings."
] |
Please provide a description of the function:def run_command(self, command, stdin=None, env=None):
cmd = shlex.split(command)
stdout = SpooledTemporaryFile(max_size=settings.TMP_FILE_MAX_SIZE,
dir=settings.TMP_DIR)
stderr = SpooledTemporaryFile(max_... | [
"\n Launch a shell command line.\n\n :param command: Command line to launch\n :type command: str\n :param stdin: Standard input of command\n :type stdin: file\n :param env: Environment variable used in command\n :type env: dict\n :return: Standard output of co... |
Please provide a description of the function:def _assign_zones(self):
for zone_id in range(1, 5):
zone = \
RainCloudyFaucetZone(
parent=self._parent,
controller=self._controller,
faucet=self,
zon... | [
"Assign all RainCloudyFaucetZone managed by faucet."
] |
Please provide a description of the function:def _find_zone_by_id(self, zone_id):
if not self.zones:
return None
zone = list(filter(
lambda zone: zone.id == zone_id, self.zones))
return zone[0] if zone else None | [
"Return zone by id."
] |
Please provide a description of the function:def _set_zone_name(self, zoneid, name):
# zone starts with index 0
zoneid -= 1
data = {
'_set_zone_name': 'Set Name',
'select_zone': str(zoneid),
'zone_name': name,
}
self._controller.post(d... | [
"Private method to override zone name."
] |
Please provide a description of the function:def _set_watering_time(self, zoneid, value):
if value not in MANUAL_WATERING_ALLOWED:
raise ValueError(
'Valid options are: {}'.format(
', '.join(map(str, MANUAL_WATERING_ALLOWED)))
)
if is... | [
"Private method to set watering_time per zone."
] |
Please provide a description of the function:def watering_time(self):
# zone starts with index 0
index = self.id - 1
auto_watering_time =\
self._attributes['rain_delay_mode'][index]['auto_watering_time']
manual_watering_time =\
self._attributes['rain_del... | [
"Return watering_time from zone."
] |
Please provide a description of the function:def _set_rain_delay(self, zoneid, value):
# current index for rain_delay starts in 0
zoneid -= 1
if isinstance(value, int):
if value > MAX_RAIN_DELAY_DAYS or value < 0:
return None
elif value == 0:
... | [
"Generic method to set auto_watering program."
] |
Please provide a description of the function:def _set_auto_watering(self, zoneid, value):
if not isinstance(value, bool):
return None
ddata = self.preupdate()
attr = 'zone{}_program_toggle'.format(zoneid)
try:
if not value:
ddata.pop(attr... | [
"Private method to set auto_watering program."
] |
Please provide a description of the function:def auto_watering(self):
value = "zone{}".format(self.id)
return find_program_status(self._parent.html['home'], value) | [
"Return if zone is configured to automatic watering."
] |
Please provide a description of the function:def _to_dict(self):
return {
'auto_watering':
getattr(self, "auto_watering"),
'droplet':
getattr(self, "droplet"),
'is_watering':
getattr(self, "is_watering"),
'n... | [
"Method to build zone dict."
] |
Please provide a description of the function:def preupdate(self, force_refresh=True):
ddata = MANUAL_OP_DATA.copy()
# force update to make sure status is accurate
if force_refresh:
self.update()
# select current controller and faucet
ddata['select_controlle... | [
"Return a dict with all current options prior submitting request."
] |
Please provide a description of the function:def submit_action(self, ddata):
self._controller.post(ddata,
url=HOME_ENDPOINT,
referer=HOME_ENDPOINT) | [
"Post data."
] |
Please provide a description of the function:def _authenticate(self):
# to obtain csrftoken, remove Referer from headers
headers = HEADERS.copy()
headers.pop('Referer')
# initial GET request
self.client = requests.Session()
self.client.proxies = self._proxies
... | [
"Authenticate."
] |
Please provide a description of the function:def controller(self):
if hasattr(self, 'controllers'):
if len(self.controllers) > 1:
# in the future, we should support more controllers
raise TypeError("Only one controller per account.")
return self.c... | [
"Show current linked controllers."
] |
Please provide a description of the function:def _assign_faucets(self, faucets):
if not faucets:
raise TypeError("Controller does not have a faucet assigned.")
for faucet_id in faucets:
self.faucets.append(
RainCloudyFaucet(self._parent, self, faucet_id)... | [
"Assign RainCloudyFaucet objects to self.faucets."
] |
Please provide a description of the function:def post(self, ddata, url=SETUP_ENDPOINT, referer=SETUP_ENDPOINT):
headers = HEADERS.copy()
if referer is None:
headers.pop('Referer')
else:
headers['Referer'] = referer
# append csrftoken
if 'csrfmidd... | [
"Method to update some attributes on namespace."
] |
Please provide a description of the function:def _get_cu_and_fu_status(self):
# adjust headers
headers = HEADERS.copy()
headers['Accept'] = '*/*'
headers['X-Requested-With'] = 'XMLHttpRequest'
headers['X-CSRFToken'] = self._parent.csrftoken
args = '?controller_s... | [
"Submit GET request to update information."
] |
Please provide a description of the function:def _refresh_html_home(self):
req = self._parent.client.get(HOME_ENDPOINT)
if req.status_code == 403:
self._parent.login()
self.update()
elif req.status_code == 200:
self._parent.html['home'] = generate_sou... | [
"\n Function to refresh the self._parent.html['home'] object\n which provides the status if zones are scheduled to\n start automatically (program_toggle).\n "
] |
Please provide a description of the function:def name(self, value):
data = {
'_set_controller_name': 'Set Name',
'controller_name': value,
}
self.post(data, url=SETUP_ENDPOINT, referer=SETUP_ENDPOINT) | [
"Set a new name to controller."
] |
Please provide a description of the function:def faucet(self):
if hasattr(self, 'faucets'):
if len(self.faucets) > 1:
# in the future, we should support more faucets
raise TypeError("Only one faucet per account.")
return self.faucets[0]
ra... | [
"Show current linked faucet."
] |
Please provide a description of the function:def serial_finder(data):
if not isinstance(data, BeautifulSoup):
raise TypeError("Function requires BeautifulSoup HTML element.")
try:
# The setup page contains a select box for each controller and each
# faucet
controllersEleme... | [
"\n Find controller serial and faucet_serial from the setup page.\n\n <select id=\"id_select_controller2\" name=\"select_controller\" >\n <option value='0' selected='selected'>1 - Controller001</option>\n </select>\n\n :param data: text to be parsed\n :type data: BeautilSoup object\n :retur... |
Please provide a description of the function:def find_program_status(data, zone):
if not isinstance(data, BeautifulSoup):
raise TypeError("Function requires BeautilSoup HTML element.")
try:
child = data.find_all('input', {'class': 'switch'})
zone_id = 'id_{0}_program_toggle'.format... | [
"\n Find on the HTML document if zoneX has the configuration\n of the auto-schedule/program (auto_watering) enabled.\n\n # expected result if enabled\n #<input checked=\"checked\" class=\"switch\" id=\"id_zone2_program_toggle\" \\\n name=\"zone2_program_toggle\" onchange=\"submit()\" type=\"check... |
Please provide a description of the function:def find_controller_or_faucet_name(data, p_type):
if not isinstance(data, BeautifulSoup):
raise TypeError("Function requires BeautilSoup HTML element.")
if not (p_type == 'controller' or p_type == 'faucet'):
raise TypeError("Function p_type must... | [
"\n Find on the HTML document the controller name.\n\n # expected result\n <label for=\"select_controller\">\n <span class=\"more_info\" id=\"#styling-type-light\" data-hasqtip=\"26\" \\\n title=\"Select Control Unit to display.\" >Control Unit:</span></label><br/>\n <select class=\"simpleselec... |
Please provide a description of the function:def find_zone_name(data, zone_id):
if not isinstance(data, BeautifulSoup):
raise TypeError("Function requires BeautilSoup HTML element.")
table = data.find('table', {'class': 'zone_table'})
table_body = table.find('tbody')
rows = table_body.find... | [
"\n Find on the HTML document the zone name.\n\n # expected result\n <span class=\"more_info\" \\\n title=\"Zone can be renamed on Setup tab\">1 - zone1</span>,\n\n :param data: BeautifulSoup object\n :param zone: zone id\n :return: zone name\n :rtype: string\n :raises TypeError: if d... |
Please provide a description of the function:def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
payment.amount = order.total
payment.currency = order.currency
logger.debug("new_payment_query_listener, amount=%s, currency=%s",
payment.amount, payment.currency) | [
"\n Here we fill only two obligatory fields of payment, and leave signal handler\n "
] |
Please provide a description of the function:def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
logger.debug("payment_status_changed_listener, old=%s, new=%s", old_status,
new_status)
if old_status != 'paid' and new_status == 'paid':
# Ensures ... | [
"\n Here we will actually do something, when payment is accepted.\n E.g. lets change an order status.\n "
] |
Please provide a description of the function:def register_to_payment(order_class, **kwargs):
global Payment
global Order
class Payment(PaymentFactory.construct(order=order_class, **kwargs)):
objects = PaymentManager()
class Meta:
ordering = ('-created_on',)
ver... | [
"\n A function for registering unaware order class to ``getpaid``. This will\n generate a ``Payment`` model class that will store payments with\n ForeignKey to original order class\n\n This also will build a model class for every enabled backend.\n "
] |
Please provide a description of the function:def get_backend_choices(currency=None):
choices = []
backends_names = getattr(settings, 'GETPAID_BACKENDS', [])
for backend_name in backends_names:
backend = import_module(backend_name)
if currency:
if currency in backend.Payment... | [
"\n Get active backends modules. Backend list can be filtered by\n supporting given currency.\n "
] |
Please provide a description of the function:def online(cls, payload, ip, req_sig):
from getpaid.models import Payment
params = json.loads(payload)
order_data = params.get('order', {})
pos_id = order_data.get('merchantPosId')
payment_id = order_data.get('extOrderId')
... | [
"\n Receive and analyze request from payment service with information on payment status change.\n "
] |
Please provide a description of the function:def get_gateway_url(self, request):
grant_type = self.get_backend_setting('grant_type', 'client_credentials')
if grant_type == 'client_credentials':
client_id = self.get_backend_setting('client_id')
client_secret = self.get_b... | [
"\n Tricky process that requires to get auth key, send order via POST and\n then present final URL for redirection to finalize payment.\n "
] |
Please provide a description of the function:def get_order_description(self, payment, order):
template = getattr(settings, 'GETPAID_ORDER_DESCRIPTION', None)
if template:
return Template(template).render(Context({"payment": payment, "order": order}))
else:
return... | [
"\n Renders order description using django template provided in ``settings.GETPAID_ORDER_DESCRIPTION``\n or if not provided return unicode representation of ``Order object``.\n "
] |
Please provide a description of the function:def get_backend_setting(cls, name, default=None):
backend_settings = get_backend_settings(cls.BACKEND)
if default is not None:
return backend_settings.get(name, default)
else:
try:
return backend_settin... | [
"\n Reads ``name`` setting from backend settings dictionary.\n\n If `default` value is omitted, raises ``ImproperlyConfigured`` when\n setting ``name`` is not available.\n "
] |
Please provide a description of the function:def get_gateway_url(self, request):
params = {
'id': self.get_backend_setting('id'),
'description': self.get_order_description(self.payment, self.payment.order),
'amount': self.payment.amount,
'currency': self.... | [
"\n Routes a payment to Gateway, should return URL for redirection.\n "
] |
Please provide a description of the function:def channel_ready_future(channel):
fut = channel._loop.create_future()
def _set_result(state):
if not fut.done() and state is _grpc.ChannelConnectivity.READY:
fut.set_result(None)
fut.add_done_callback(lambda f: channel.unsubscribe(_set_r... | [
"Creates a Future that tracks when a Channel is ready.\n\n Cancelling the Future does not affect the channel's state machine.\n It merely decouples the Future from channel state machine.\n\n Args:\n channel: A Channel object.\n\n Returns:\n A Future object that matures when the channel connectivity is\n ... |
Please provide a description of the function:def insecure_channel(target, options=None, *, loop=None, executor=None,
standalone_pool_for_streaming=False):
return Channel(_grpc.insecure_channel(target, options), loop, executor, standalone_pool_for_streaming) | [
"Creates an insecure Channel to a server.\n\n Args:\n target: The server address\n options: An optional list of key-value pairs (channel args in gRPC runtime)\n to configure the channel.\n\n Returns:\n A Channel object.\n "
] |
Please provide a description of the function:def secure_channel(target, credentials, options=None, *, loop=None, executor=None,
standalone_pool_for_streaming=False):
return Channel(_grpc.secure_channel(target, credentials, options),
loop, executor, standalone_pool_for_stre... | [
"Creates a secure Channel to a server.\n\n Args:\n target: The server address.\n credentials: A ChannelCredentials instance.\n options: An optional list of key-value pairs (channel args in gRPC runtime)\n to configure the channel.\n\n Returns:\n A Channel object.\n "
] |
Please provide a description of the function:def future(self, request, timeout=None, metadata=None, credentials=None):
return _utils.wrap_future_call(self._inner.future(request, timeout, metadata, credentials),
self._loop, self._executor) | [
"Asynchronously invokes the underlying RPC.\n\n Args:\n request: The request value for the RPC.\n timeout: An optional duration of time in seconds to allow for the RPC.\n metadata: Optional :term:`metadata` to be transmitted to the\n service-side of the RPC.\n credentials: An optional ... |
Please provide a description of the function:def with_scope(self, request, timeout=None, metadata=None, credentials=None,
*, standalone_pool = None):
return _utils.IteratorScope(self(request, timeout, metadata, credentials, standalone_pool=standalone_pool)) | [
"\n Return an ASYNC context manager to ensure the call is closed outside the scope::\n \n async with mystub.mymethod.with_scope(...) as iter:\n async for i in iter:\n ...\n "
] |
Please provide a description of the function:async def with_call(self,
request_iterator,
timeout=None,
metadata=None,
credentials=None):
fut = self.future(request_iterator, timeout, metadata, credentials)
try:
r... | [
"Synchronously invokes the underlying RPC on the client.\n\n Args:\n request_iterator: An ASYNC iterator that yields request values for the RPC.\n timeout: An optional duration of time in seconds to allow for the RPC.\n If None, the timeout is considered infinite.\n metadata: Optiona... |
Please provide a description of the function:def future(self,
request_iterator,
timeout=None,
metadata=None,
credentials=None):
return _utils.wrap_future_call(
self._inner.future(
_utils.WrappedAsync... | [
"Asynchronously invokes the underlying RPC on the client.\n\n Args:\n request_iterator: An ASYNC iterator that yields request values for the RPC.\n timeout: An optional duration of time in seconds to allow for the RPC.\n If None, the timeout is considered infinite.\n metadata: Option... |
Please provide a description of the function:def close(self):
return self._loop.run_in_executor(self._executor, self._channel.close) | [
"\n This method returns a future, so you should use `await channel.close()`, but call\n `channel.close()` also close it (but did not wait for the closing)\n "
] |
Please provide a description of the function:def config_field_type(field, cls):
return defs.ConfigField(lambda _: isinstance(_, cls),
lambda: CONFIG_FIELD_TYPE_ERROR.format(field, cls.__name__)) | [
"Validate a config field against a type.\n\n Similar functionality to :func:`validate_field_matches_type` but returns :obj:`honeycomb.defs.ConfigField`\n "
] |
Please provide a description of the function:def validate_config(config_json, fields):
for field_name, validator_obj in six.iteritems(fields):
field_value = config_json.get(field_name, None)
if field_value is None:
raise exceptions.ConfigFieldMissing(field_name)
if not vali... | [
"Validate a JSON file configuration against list of :obj:`honeycomb.defs.ConfigField`."
] |
Please provide a description of the function:def get_config_parameters(plugin_path):
json_config_path = os.path.join(plugin_path, defs.CONFIG_FILE_NAME)
with open(json_config_path, "r") as f:
config = json.load(f)
return config.get(defs.PARAMETERS, []) | [
"Return the parameters section from config.json."
] |
Please provide a description of the function:def validate_config_parameters(config_json, allowed_keys, allowed_types):
custom_fields = config_json.get(defs.PARAMETERS, [])
for field in custom_fields:
validate_field(field, allowed_keys, allowed_types)
default = field.get(defs.DEFAULT)
... | [
"Validate parameters in config file."
] |
Please provide a description of the function:def validate_field_matches_type(field, value, field_type, select_items=None, _min=None, _max=None):
if (field_type == defs.TEXT_TYPE and not isinstance(value, six.string_types)) or \
(field_type == defs.STRING_TYPE and not isinstance(value, six.string_types))... | [
"Validate a config field against a specific type."
] |
Please provide a description of the function:def get_truetype(value):
if value in ["true", "True", "y", "Y", "yes"]:
return True
if value in ["false", "False", "n", "N", "no"]:
return False
if value.isdigit():
return int(value)
return str(value) | [
"Convert a string to a pythonized parameter."
] |
Please provide a description of the function:def validate_field(field, allowed_keys, allowed_types):
for key, value in field.items():
if key not in allowed_keys:
raise exceptions.ParametersFieldError(key, "property")
if key == defs.TYPE:
if value not in allowed_types:
... | [
"Validate field is allowed and valid."
] |
Please provide a description of the function:def is_valid_field_name(value):
leftovers = re.sub(r"\w", "", value)
leftovers = re.sub(r"-", "", leftovers)
if leftovers != "" or value[0].isdigit() or value[0] in ["-", "_"] or " " in value:
return False
return True | [
"Ensure field name is valid."
] |
Please provide a description of the function:def process_config(ctx, configfile):
from honeycomb.commands.service.run import run as service_run
# from honeycomb.commands.service.logs import logs as service_logs
from honeycomb.commands.service.install import install as service_install
from honeycomb... | [
"Process a yaml config with instructions.\n\n This is a heavy method that loads lots of content, so we only run the imports if its called.\n "
] |
Please provide a description of the function:def list(ctx, remote):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
click.secho("[*] Installed services:")
home = ctx.obj["HOME"]
services_path = os.pat... | [
"List services."
] |
Please provide a description of the function:def get_plugin_path(home, plugin_type, plugin_name, editable=False):
if editable:
plugin_path = plugin_name
else:
plugin_path = os.path.join(home, plugin_type, plugin_name)
return os.path.realpath(plugin_path) | [
"Return path to plugin.\n\n :param home: Path to honeycomb home\n :param plugin_type: Type of plugin (:obj:`honeycomb.defs.SERVICES` pr :obj:`honeycomb.defs.INTEGRATIONS`)\n :param plugin_name: Name of plugin\n :param editable: Use plugin_name as direct path instead of loading from honeycomb home folder... |
Please provide a description of the function:def install_plugin(pkgpath, plugin_type, install_path, register_func):
service_name = os.path.basename(pkgpath)
if os.path.exists(os.path.join(install_path, service_name)):
raise exceptions.PluginAlreadyInstalled(pkgpath)
if os.path.exists(pkgpath):... | [
"Install specified plugin.\n\n :param pkgpath: Name of plugin to be downloaded from online repo or path to plugin folder or zip file.\n :param install_path: Path where plugin will be installed.\n :param register_func: Method used to register and validate plugin.\n "
] |
Please provide a description of the function:def install_deps(pkgpath):
if os.path.exists(os.path.join(pkgpath, "requirements.txt")):
logger.debug("installing dependencies")
click.secho("[*] Installing dependencies")
pipargs = ["install", "--target", os.path.join(pkgpath, defs.DEPS_DIR)... | [
"Install plugin dependencies using pip.\n\n We import pip here to reduce load time for when its not needed.\n "
] |
Please provide a description of the function:def copy_file(src, dst):
try:
fin = os.open(src, READ_FLAGS)
stat = os.fstat(fin)
fout = os.open(dst, WRITE_FLAGS, stat.st_mode)
for x in iter(lambda: os.read(fin, BUFFER_SIZE), b""):
os.write(fout, x)
finally:
... | [
"Copy a single file.\n\n :param src: Source name\n :param dst: Destination name\n "
] |
Please provide a description of the function:def copy_tree(src, dst, symlinks=False, ignore=[]):
names = os.listdir(src)
if not os.path.exists(dst):
os.makedirs(dst)
errors = []
for name in names:
if name in ignore:
continue
srcname = os.path.join(src, name)
... | [
"Copy a full directory structure.\n\n :param src: Source path\n :param dst: Destination path\n :param symlinks: Copy symlinks\n :param ignore: Subdirs/filenames to ignore\n "
] |
Please provide a description of the function:def install_dir(pkgpath, install_path, register_func, delete_after_install=False):
logger.debug("%s is a directory, attempting to validate", pkgpath)
plugin = register_func(pkgpath)
logger.debug("%s looks good, copying to %s", pkgpath, install_path)
try:... | [
"Install plugin from specified directory.\n\n install_path and register_func are same as :func:`install_plugin`.\n :param delete_after_install: Delete pkgpath after install (used in :func:`install_from_zip`).\n "
] |
Please provide a description of the function:def install_from_zip(pkgpath, install_path, register_func, delete_after_install=False):
logger.debug("%s is a file, attempting to load zip", pkgpath)
pkgtempdir = tempfile.mkdtemp(prefix="honeycomb_")
try:
with zipfile.ZipFile(pkgpath) as pkgzip:
... | [
"Install plugin from zipfile."
] |
Please provide a description of the function:def install_from_repo(pkgname, plugin_type, install_path, register_func):
rsession = requests.Session()
rsession.mount("https://", HTTPAdapter(max_retries=3))
logger.debug("trying to install %s from online repo", pkgname)
pkgurl = "{}/{}s/{}.zip".format... | [
"Install plugin from online repo."
] |
Please provide a description of the function:def uninstall_plugin(pkgpath, force):
pkgname = os.path.basename(pkgpath)
if os.path.exists(pkgpath):
if not force:
click.confirm("[?] Are you sure you want to delete `{}` from honeycomb?".format(pkgname),
abort=True... | [
"Uninstall a plugin.\n\n :param pkgpath: Path to package to uninstall (delete)\n :param force: Force uninstall without asking\n "
] |
Please provide a description of the function:def list_remote_plugins(installed_plugins, plugin_type):
click.secho("\n[*] Additional plugins from online repository:")
try:
rsession = requests.Session()
rsession.mount("https://", HTTPAdapter(max_retries=3))
r = rsession.get("{0}/{1}s... | [
"List remote plugins from online repo."
] |
Please provide a description of the function:def list_local_plugins(plugin_type, plugins_path, plugin_details):
installed_plugins = list()
for plugin in next(os.walk(plugins_path))[1]:
s = plugin_details(plugin)
installed_plugins.append(plugin)
click.secho(s)
if not installed_p... | [
"List local plugins with details."
] |
Please provide a description of the function:def parse_plugin_args(command_args, config_args):
parsed_args = dict()
for arg in command_args:
kv = arg.split("=")
if len(kv) != 2:
raise click.UsageError("Invalid parameter '{}', must be in key=value format".format(arg))
par... | [
"Parse command line arguments based on the plugin's parameters config.\n\n :param command_args: Command line arguments as provided by the user in `key=value` format.\n :param config_args: Plugin parameters parsed from config.json.\n\n :returns: Validated dictionary of parameters that will be passed to plug... |
Please provide a description of the function:def get_select_items(items):
option_items = list()
for item in items:
if isinstance(item, dict) and defs.VALUE in item and defs.LABEL in item:
option_items.append(item[defs.VALUE])
else:
raise exceptions.ParametersFieldErr... | [
"Return list of possible select items."
] |
Please provide a description of the function:def print_plugin_args(plugin_path):
args = config_utils.get_config_parameters(plugin_path)
args_format = "{:20} {:10} {:^15} {:^10} {:25}"
title = args_format.format(defs.NAME.upper(), defs.TYPE.upper(), defs.DEFAULT.upper(),
d... | [
"Print plugin parameters table."
] |
Please provide a description of the function:def show(ctx, service, remote):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
service_path = plugin_utils.get_plugin_path(home, defs.S... | [
"Show detailed information about a package."
] |
Please provide a description of the function:def configure_integration(path):
integration = register_integration(path)
integration_args = {}
try:
with open(os.path.join(path, ARGS_JSON)) as f:
integration_args = json.loads(f.read())
except Exception as exc:
logger.debug(... | [
"Configure and enable an integration."
] |
Please provide a description of the function:def send_alert_to_subscribed_integrations(alert):
valid_configured_integrations = get_valid_configured_integrations(alert)
for configured_integration in valid_configured_integrations:
threading.Thread(target=create_integration_alert_and_call_send, args=... | [
"Send Alert to relevant integrations."
] |
Please provide a description of the function:def get_valid_configured_integrations(alert):
if not configured_integrations:
return []
# Collect all integrations that are configured for specific alert_type
# or have no specific supported_event_types (i.e., all alert types)
valid_configured_i... | [
"Return a list of integrations for alert filtered by alert_type.\n\n :returns: A list of relevant integrations\n "
] |
Please provide a description of the function:def create_integration_alert_and_call_send(alert, configured_integration):
integration_alert = IntegrationAlert(
alert=alert,
configured_integration=configured_integration,
status=IntegrationAlertStatuses.PENDING.name,
retries=configu... | [
"Create an IntegrationAlert object and send it to Integration."
] |
Please provide a description of the function:def send_alert_to_configured_integration(integration_alert):
try:
alert = integration_alert.alert
configured_integration = integration_alert.configured_integration
integration = configured_integration.integration
integration_actions_i... | [
"Send IntegrationAlert to configured integration."
] |
Please provide a description of the function:def poll_integration_information_for_waiting_integration_alerts():
if not polling_integration_alerts:
return
logger.debug("Polling information for waiting integration alerts")
for integration_alert in polling_integration_alerts:
configured_... | [
"poll_integration_information_for_waiting_integration_alerts."
] |
Please provide a description of the function:def poll_integration_alert_data(integration_alert):
logger.info("Polling information for integration alert %s", integration_alert)
try:
configured_integration = integration_alert.configured_integration
integration_actions_instance = configured_in... | [
"Poll for updates on waiting IntegrationAlerts."
] |
Please provide a description of the function:def status(ctx, services, show_all):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
services_path = os.path.join(home, SERVICES)
d... | [
"Show status of installed service(s)."
] |
Please provide a description of the function:def wait_until(func,
check_return_value=True,
total_timeout=60,
interval=0.5,
exc_list=None,
error_message="",
*args,
**kwargs):
start_function = time.time()
... | [
"Run a command in a loop until desired result or timeout occurs.\n\n :param func: Function to call and wait for\n :param bool check_return_value: Examine return value\n :param int total_timeout: Wait timeout,\n :param float interval: Sleep interval between retries\n :param list exc_list: Acceptable e... |
Please provide a description of the function:def search_json_log(filepath, key, value):
try:
with open(filepath, "r") as fh:
for line in fh.readlines():
log = json.loads(line)
if key in log and log[key] == value:
return log
... | [
"Search json log file for a key=value pair.\n\n :param filepath: Valid path to a json file\n :param key: key to match\n :param value: value to match\n :returns: First matching line in json log file, parsed by :py:func:`json.loads`\n "
] |
Please provide a description of the function:def list_commands(self, ctx):
rv = []
files = [_ for _ in next(os.walk(self.folder))[2] if not _.startswith("_") and _.endswith(".py")]
for filename in files:
rv.append(filename[:-3])
rv.sort()
return rv | [
"List commands from folder."
] |
Please provide a description of the function:def get_command(self, ctx, name):
plugin = os.path.basename(self.folder)
try:
command = importlib.import_module("honeycomb.commands.{}.{}".format(plugin, name))
except ImportError:
raise click.UsageError("No such comma... | [
"Fetch command from folder."
] |
Please provide a description of the function:def cli(ctx, home, iamroot, config, verbose):
_mkhome(home)
setup_logging(home, verbose)
logger.debug("Honeycomb v%s", __version__, extra={"version": __version__})
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
ex... | [
"Honeycomb is a honeypot framework."
] |
Please provide a description of the function:def setup_logging(home, verbose):
logging.setLoggerClass(MyLogger)
logging.config.dictConfig({
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"console": {
"format": "%(levelname)-8s [%(asctime... | [
"Configure logging for honeycomb."
] |
Please provide a description of the function:def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
# See below commented section for a simple example of what the docstring refers to
if six.PY2:
rv = logging.LogRecord(name, level, fn, lno... | [
"Override default logger to allow overriding of internal attributes."
] |
Please provide a description of the function:def stop(ctx, service, editable):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
service_path = plugin_utils.get_plugin_path(home, SERV... | [
"Stop a running service daemon."
] |
Please provide a description of the function:def show(ctx, integration, remote):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
integration_path = plugin_utils.get_plugin_path(home... | [
"Show detailed information about a package."
] |
Please provide a description of the function:def logs(ctx, services, num, follow):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
services_path = os.path.join(home, SERVICES)
... | [
"Show logs of daemonized service."
] |
Please provide a description of the function:def get_integration_module(integration_path):
# add custom paths so imports would work
paths = [
os.path.join(__file__, "..", ".."), # to import integrationmanager
os.path.join(integration_path, ".."), # to import integration itself
os.... | [
"Add custom paths to sys and import integration module.\n\n :param integration_path: Path to integration folder\n "
] |
Please provide a description of the function:def register_integration(package_folder):
logger.debug("registering integration %s", package_folder)
package_folder = os.path.realpath(package_folder)
if not os.path.exists(package_folder):
raise IntegrationNotFound(os.path.basename(package_folder))
... | [
"Register a honeycomb integration.\n\n :param package_folder: Path to folder with integration to load\n :returns: Validated integration object\n :rtype: :func:`honeycomb.utils.defs.Integration`\n "
] |
Please provide a description of the function:def list(ctx, remote):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
click.secho("[*] Installed integrations:")
home = ctx.obj["HOME"]
integrations_path ... | [
"List integrations."
] |
Please provide a description of the function:def run(ctx, service, args, show_args, daemon, editable, integration):
home = ctx.obj["HOME"]
service_path = plugin_utils.get_plugin_path(home, SERVICES, service, editable)
service_log_path = os.path.join(service_path, LOGS_DIR)
logger.debug("running co... | [
"Load and run a specific service."
] |
Please provide a description of the function:def read_lines(self, file_path, empty_lines=False, signal_ready=True):
file_handler, file_id = self._get_file(file_path)
file_handler.seek(0, os.SEEK_END)
if signal_ready:
self.signal_ready()
while self.thread_server.is_... | [
"Fetch lines from file.\n\n In case the file handler changes (logrotate), reopen the file.\n\n :param file_path: Path to file\n :param empty_lines: Return empty lines\n :param signal_ready: Report signal ready on start\n "
] |
Please provide a description of the function:def on_server_start(self):
self._container = self._docker_client.containers.run(self.docker_image_name, detach=True, **self.docker_params)
self.signal_ready()
for log_line in self.get_lines():
try:
alert_dict = se... | [
"Service run loop function.\n\n Run the desired docker container with parameters and start parsing the monitored file for alerts.\n "
] |
Please provide a description of the function:def on_server_shutdown(self):
if not self._container:
return
self._container.stop()
self._container.remove(v=True, force=True) | [
"Stop the container before shutting down."
] |
Please provide a description of the function:def uninstall(ctx, yes, integrations):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
for integration in integrations:
integra... | [
"Uninstall a integration."
] |
Please provide a description of the function:def install(ctx, services, delete_after_install=False):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
services_path = os.path.join(hom... | [
"Install a honeypot service from the online library, local path or zipfile."
] |
Please provide a description of the function:def uninstall(ctx, yes, services):
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
for service in services:
service_path = plug... | [
"Uninstall a service."
] |
Please provide a description of the function:def get_service_module(service_path):
# add custom paths so imports would work
paths = [
os.path.dirname(__file__), # this folder, to catch base_service
os.path.realpath(os.path.join(service_path, "..")), # service's parent folder for import
... | [
"Add custom paths to sys and import service module.\n\n :param service_path: Path to service folder\n "
] |
Please provide a description of the function:def register_service(package_folder):
logger.debug("registering service %s", package_folder)
package_folder = os.path.realpath(package_folder)
if not os.path.exists(package_folder):
raise ServiceNotFound(os.path.basename(package_folder))
json_co... | [
"Register a honeycomb service.\n\n :param package_folder: Path to folder with service to load\n :returns: Validated service object\n :rtype: :func:`honeycomb.utils.defs.ServiceType`\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.