id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
13,500
tchellomello/raincloudy
raincloudy/faucet.py
RainCloudyFaucetZone._set_auto_watering
def _set_auto_watering(self, zoneid, value): """Private method to set auto_watering program.""" if not isinstance(value, bool): return None ddata = self.preupdate() attr = 'zone{}_program_toggle'.format(zoneid) try: if not value: ddata.pop(attr) else: ddata[attr] = 'on' except KeyError: pass self.submit_action(ddata) return True
python
def _set_auto_watering(self, zoneid, value): """Private method to set auto_watering program.""" if not isinstance(value, bool): return None ddata = self.preupdate() attr = 'zone{}_program_toggle'.format(zoneid) try: if not value: ddata.pop(attr) else: ddata[attr] = 'on' except KeyError: pass self.submit_action(ddata) return True
[ "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", ")", "else", ":", "ddata", "[", "attr", "]", "=", "'on'", "except", "KeyError", ":", "pass", "self", ".", "submit_action", "(", "ddata", ")", "return", "True" ]
Private method to set auto_watering program.
[ "Private", "method", "to", "set", "auto_watering", "program", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/faucet.py#L291-L306
13,501
tchellomello/raincloudy
raincloudy/faucet.py
RainCloudyFaucetZone.auto_watering
def auto_watering(self): """Return if zone is configured to automatic watering.""" value = "zone{}".format(self.id) return find_program_status(self._parent.html['home'], value)
python
def auto_watering(self): """Return if zone is configured to automatic watering.""" value = "zone{}".format(self.id) return find_program_status(self._parent.html['home'], value)
[ "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.
[ "Return", "if", "zone", "is", "configured", "to", "automatic", "watering", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/faucet.py#L309-L312
13,502
tchellomello/raincloudy
raincloudy/faucet.py
RainCloudyFaucetZone._to_dict
def _to_dict(self): """Method to build zone dict.""" return { 'auto_watering': getattr(self, "auto_watering"), 'droplet': getattr(self, "droplet"), 'is_watering': getattr(self, "is_watering"), 'name': getattr(self, "name"), 'next_cycle': getattr(self, "next_cycle"), 'rain_delay': getattr(self, "rain_delay"), 'watering_time': getattr(self, "watering_time"), }
python
def _to_dict(self): """Method to build zone dict.""" return { 'auto_watering': getattr(self, "auto_watering"), 'droplet': getattr(self, "droplet"), 'is_watering': getattr(self, "is_watering"), 'name': getattr(self, "name"), 'next_cycle': getattr(self, "next_cycle"), 'rain_delay': getattr(self, "rain_delay"), 'watering_time': getattr(self, "watering_time"), }
[ "def", "_to_dict", "(", "self", ")", ":", "return", "{", "'auto_watering'", ":", "getattr", "(", "self", ",", "\"auto_watering\"", ")", ",", "'droplet'", ":", "getattr", "(", "self", ",", "\"droplet\"", ")", ",", "'is_watering'", ":", "getattr", "(", "self", ",", "\"is_watering\"", ")", ",", "'name'", ":", "getattr", "(", "self", ",", "\"name\"", ")", ",", "'next_cycle'", ":", "getattr", "(", "self", ",", "\"next_cycle\"", ")", ",", "'rain_delay'", ":", "getattr", "(", "self", ",", "\"rain_delay\"", ")", ",", "'watering_time'", ":", "getattr", "(", "self", ",", "\"watering_time\"", ")", ",", "}" ]
Method to build zone dict.
[ "Method", "to", "build", "zone", "dict", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/faucet.py#L324-L341
13,503
tchellomello/raincloudy
raincloudy/faucet.py
RainCloudyFaucetZone.preupdate
def preupdate(self, force_refresh=True): """Return a dict with all current options prior submitting request.""" 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_controller'] = \ self._parent.controllers.index(self._controller) ddata['select_faucet'] = \ self._controller.faucets.index(self._faucet) # check if zone is scheduled automatically (zone1_program_toggle) # only add zoneX_program_toogle to ddata when needed, # otherwise the field will be always on for zone in self._faucet.zones: attr = 'zone{}_program_toggle'.format(zone.id) if zone.auto_watering: ddata[attr] = 'on' # check if zone current watering manually (zone1_select_manual_mode) for zone in self._faucet.zones: attr = 'zone{}_select_manual_mode'.format(zone.id) if zone.watering_time and attr in ddata.keys(): ddata[attr] = zone.watering_time # check if rain delay is selected (zone0_rain_delay_select) for zone in self._faucet.zones: attr = 'zone{}_rain_delay_select'.format(zone.id - 1) value = zone.rain_delay if value and attr in ddata.keys(): if int(value) >= 2 and int(value) <= 7: value = str(value) + 'days' else: value = str(value) + 'day' ddata[attr] = value return ddata
python
def preupdate(self, force_refresh=True): """Return a dict with all current options prior submitting request.""" 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_controller'] = \ self._parent.controllers.index(self._controller) ddata['select_faucet'] = \ self._controller.faucets.index(self._faucet) # check if zone is scheduled automatically (zone1_program_toggle) # only add zoneX_program_toogle to ddata when needed, # otherwise the field will be always on for zone in self._faucet.zones: attr = 'zone{}_program_toggle'.format(zone.id) if zone.auto_watering: ddata[attr] = 'on' # check if zone current watering manually (zone1_select_manual_mode) for zone in self._faucet.zones: attr = 'zone{}_select_manual_mode'.format(zone.id) if zone.watering_time and attr in ddata.keys(): ddata[attr] = zone.watering_time # check if rain delay is selected (zone0_rain_delay_select) for zone in self._faucet.zones: attr = 'zone{}_rain_delay_select'.format(zone.id - 1) value = zone.rain_delay if value and attr in ddata.keys(): if int(value) >= 2 and int(value) <= 7: value = str(value) + 'days' else: value = str(value) + 'day' ddata[attr] = value return ddata
[ "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_controller'", "]", "=", "self", ".", "_parent", ".", "controllers", ".", "index", "(", "self", ".", "_controller", ")", "ddata", "[", "'select_faucet'", "]", "=", "self", ".", "_controller", ".", "faucets", ".", "index", "(", "self", ".", "_faucet", ")", "# check if zone is scheduled automatically (zone1_program_toggle)", "# only add zoneX_program_toogle to ddata when needed,", "# otherwise the field will be always on", "for", "zone", "in", "self", ".", "_faucet", ".", "zones", ":", "attr", "=", "'zone{}_program_toggle'", ".", "format", "(", "zone", ".", "id", ")", "if", "zone", ".", "auto_watering", ":", "ddata", "[", "attr", "]", "=", "'on'", "# check if zone current watering manually (zone1_select_manual_mode)", "for", "zone", "in", "self", ".", "_faucet", ".", "zones", ":", "attr", "=", "'zone{}_select_manual_mode'", ".", "format", "(", "zone", ".", "id", ")", "if", "zone", ".", "watering_time", "and", "attr", "in", "ddata", ".", "keys", "(", ")", ":", "ddata", "[", "attr", "]", "=", "zone", ".", "watering_time", "# check if rain delay is selected (zone0_rain_delay_select)", "for", "zone", "in", "self", ".", "_faucet", ".", "zones", ":", "attr", "=", "'zone{}_rain_delay_select'", ".", "format", "(", "zone", ".", "id", "-", "1", ")", "value", "=", "zone", ".", "rain_delay", "if", "value", "and", "attr", "in", "ddata", ".", "keys", "(", ")", ":", "if", "int", "(", "value", ")", ">=", "2", "and", "int", "(", "value", ")", "<=", "7", ":", "value", "=", "str", "(", "value", ")", "+", "'days'", "else", ":", "value", "=", "str", "(", "value", ")", "+", "'day'", "ddata", "[", "attr", "]", "=", "value", "return", "ddata" ]
Return a dict with all current options prior submitting request.
[ "Return", "a", "dict", "with", "all", "current", "options", "prior", "submitting", "request", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/faucet.py#L347-L386
13,504
tchellomello/raincloudy
raincloudy/faucet.py
RainCloudyFaucetZone.submit_action
def submit_action(self, ddata): """Post data.""" self._controller.post(ddata, url=HOME_ENDPOINT, referer=HOME_ENDPOINT)
python
def submit_action(self, ddata): """Post data.""" self._controller.post(ddata, url=HOME_ENDPOINT, referer=HOME_ENDPOINT)
[ "def", "submit_action", "(", "self", ",", "ddata", ")", ":", "self", ".", "_controller", ".", "post", "(", "ddata", ",", "url", "=", "HOME_ENDPOINT", ",", "referer", "=", "HOME_ENDPOINT", ")" ]
Post data.
[ "Post", "data", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/faucet.py#L388-L392
13,505
tchellomello/raincloudy
raincloudy/core.py
RainCloudy.controller
def controller(self): """Show current linked controllers.""" 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.controllers[0] raise AttributeError("There is no controller assigned.")
python
def controller(self): """Show current linked controllers.""" 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.controllers[0] raise AttributeError("There is no controller assigned.")
[ "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", ".", "controllers", "[", "0", "]", "raise", "AttributeError", "(", "\"There is no controller assigned.\"", ")" ]
Show current linked controllers.
[ "Show", "current", "linked", "controllers", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/core.py#L123-L130
13,506
tchellomello/raincloudy
raincloudy/controller.py
RainCloudyController._assign_faucets
def _assign_faucets(self, faucets): """Assign RainCloudyFaucet objects to 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))
python
def _assign_faucets(self, faucets): """Assign RainCloudyFaucet objects to 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))
[ "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.
[ "Assign", "RainCloudyFaucet", "objects", "to", "self", ".", "faucets", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/controller.py#L48-L55
13,507
tchellomello/raincloudy
raincloudy/controller.py
RainCloudyController.post
def post(self, ddata, url=SETUP_ENDPOINT, referer=SETUP_ENDPOINT): """Method to update some attributes on namespace.""" headers = HEADERS.copy() if referer is None: headers.pop('Referer') else: headers['Referer'] = referer # append csrftoken if 'csrfmiddlewaretoken' not in ddata.keys(): ddata['csrfmiddlewaretoken'] = self._parent.csrftoken req = self._parent.client.post(url, headers=headers, data=ddata) if req.status_code == 200: self.update()
python
def post(self, ddata, url=SETUP_ENDPOINT, referer=SETUP_ENDPOINT): """Method to update some attributes on namespace.""" headers = HEADERS.copy() if referer is None: headers.pop('Referer') else: headers['Referer'] = referer # append csrftoken if 'csrfmiddlewaretoken' not in ddata.keys(): ddata['csrfmiddlewaretoken'] = self._parent.csrftoken req = self._parent.client.post(url, headers=headers, data=ddata) if req.status_code == 200: self.update()
[ "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", "'csrfmiddlewaretoken'", "not", "in", "ddata", ".", "keys", "(", ")", ":", "ddata", "[", "'csrfmiddlewaretoken'", "]", "=", "self", ".", "_parent", ".", "csrftoken", "req", "=", "self", ".", "_parent", ".", "client", ".", "post", "(", "url", ",", "headers", "=", "headers", ",", "data", "=", "ddata", ")", "if", "req", ".", "status_code", "==", "200", ":", "self", ".", "update", "(", ")" ]
Method to update some attributes on namespace.
[ "Method", "to", "update", "some", "attributes", "on", "namespace", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/controller.py#L64-L78
13,508
tchellomello/raincloudy
raincloudy/controller.py
RainCloudyController._get_cu_and_fu_status
def _get_cu_and_fu_status(self): """Submit GET request to update information.""" # adjust headers headers = HEADERS.copy() headers['Accept'] = '*/*' headers['X-Requested-With'] = 'XMLHttpRequest' headers['X-CSRFToken'] = self._parent.csrftoken args = '?controller_serial=' + self.serial \ + '&faucet_serial=' + self.faucet.serial req = self._parent.client.get(STATUS_ENDPOINT + args, headers=headers) # token probably expired, then try again if req.status_code == 403: self._parent.login() self.update() elif req.status_code == 200: self.attributes = req.json() else: req.raise_for_status()
python
def _get_cu_and_fu_status(self): """Submit GET request to update information.""" # adjust headers headers = HEADERS.copy() headers['Accept'] = '*/*' headers['X-Requested-With'] = 'XMLHttpRequest' headers['X-CSRFToken'] = self._parent.csrftoken args = '?controller_serial=' + self.serial \ + '&faucet_serial=' + self.faucet.serial req = self._parent.client.get(STATUS_ENDPOINT + args, headers=headers) # token probably expired, then try again if req.status_code == 403: self._parent.login() self.update() elif req.status_code == 200: self.attributes = req.json() else: req.raise_for_status()
[ "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_serial='", "+", "self", ".", "serial", "+", "'&faucet_serial='", "+", "self", ".", "faucet", ".", "serial", "req", "=", "self", ".", "_parent", ".", "client", ".", "get", "(", "STATUS_ENDPOINT", "+", "args", ",", "headers", "=", "headers", ")", "# token probably expired, then try again", "if", "req", ".", "status_code", "==", "403", ":", "self", ".", "_parent", ".", "login", "(", ")", "self", ".", "update", "(", ")", "elif", "req", ".", "status_code", "==", "200", ":", "self", ".", "attributes", "=", "req", ".", "json", "(", ")", "else", ":", "req", ".", "raise_for_status", "(", ")" ]
Submit GET request to update information.
[ "Submit", "GET", "request", "to", "update", "information", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/controller.py#L80-L101
13,509
tchellomello/raincloudy
raincloudy/controller.py
RainCloudyController.name
def name(self, value): """Set a new name to controller.""" data = { '_set_controller_name': 'Set Name', 'controller_name': value, } self.post(data, url=SETUP_ENDPOINT, referer=SETUP_ENDPOINT)
python
def name(self, value): """Set a new name to controller.""" data = { '_set_controller_name': 'Set Name', 'controller_name': value, } self.post(data, url=SETUP_ENDPOINT, referer=SETUP_ENDPOINT)
[ "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.
[ "Set", "a", "new", "name", "to", "controller", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/controller.py#L148-L154
13,510
tchellomello/raincloudy
raincloudy/controller.py
RainCloudyController.faucet
def faucet(self): """Show current linked faucet.""" 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] raise AttributeError("There is no faucet assigned.")
python
def faucet(self): """Show current linked faucet.""" 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] raise AttributeError("There is no faucet assigned.")
[ "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", "]", "raise", "AttributeError", "(", "\"There is no faucet assigned.\"", ")" ]
Show current linked faucet.
[ "Show", "current", "linked", "faucet", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/controller.py#L167-L174
13,511
tchellomello/raincloudy
raincloudy/helpers.py
serial_finder
def serial_finder(data): """ Find controller serial and faucet_serial from the setup page. <select id="id_select_controller2" name="select_controller" > <option value='0' selected='selected'>1 - Controller001</option> </select> :param data: text to be parsed :type data: BeautilSoup object :return: a dict with controller_serial and faucet_serial :rtype: dict :raises IndexError: if controller_serial was not found on the 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 controllersElement = data.find_all('select', {'id': 'id_select_controller2'}) faucetsElement = data.find_all('select', {'id': 'id_select_faucet2'}) controllerSerial = controllersElement[0].text.split('-')[1].strip() faucetSerial = faucetsElement[0].text.split('-')[1].strip() # currently only one faucet is supported on the code # we have plans to support it in the future parsed_dict = {} parsed_dict['controller_serial'] = controllerSerial parsed_dict['faucet_serial'] = [faucetSerial] return parsed_dict except (AttributeError, IndexError, ValueError): raise RainCloudyException( 'Could not find any valid controller or faucet')
python
def serial_finder(data): """ Find controller serial and faucet_serial from the setup page. <select id="id_select_controller2" name="select_controller" > <option value='0' selected='selected'>1 - Controller001</option> </select> :param data: text to be parsed :type data: BeautilSoup object :return: a dict with controller_serial and faucet_serial :rtype: dict :raises IndexError: if controller_serial was not found on the 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 controllersElement = data.find_all('select', {'id': 'id_select_controller2'}) faucetsElement = data.find_all('select', {'id': 'id_select_faucet2'}) controllerSerial = controllersElement[0].text.split('-')[1].strip() faucetSerial = faucetsElement[0].text.split('-')[1].strip() # currently only one faucet is supported on the code # we have plans to support it in the future parsed_dict = {} parsed_dict['controller_serial'] = controllerSerial parsed_dict['faucet_serial'] = [faucetSerial] return parsed_dict except (AttributeError, IndexError, ValueError): raise RainCloudyException( 'Could not find any valid controller or faucet')
[ "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", "controllersElement", "=", "data", ".", "find_all", "(", "'select'", ",", "{", "'id'", ":", "'id_select_controller2'", "}", ")", "faucetsElement", "=", "data", ".", "find_all", "(", "'select'", ",", "{", "'id'", ":", "'id_select_faucet2'", "}", ")", "controllerSerial", "=", "controllersElement", "[", "0", "]", ".", "text", ".", "split", "(", "'-'", ")", "[", "1", "]", ".", "strip", "(", ")", "faucetSerial", "=", "faucetsElement", "[", "0", "]", ".", "text", ".", "split", "(", "'-'", ")", "[", "1", "]", ".", "strip", "(", ")", "# currently only one faucet is supported on the code", "# we have plans to support it in the future", "parsed_dict", "=", "{", "}", "parsed_dict", "[", "'controller_serial'", "]", "=", "controllerSerial", "parsed_dict", "[", "'faucet_serial'", "]", "=", "[", "faucetSerial", "]", "return", "parsed_dict", "except", "(", "AttributeError", ",", "IndexError", ",", "ValueError", ")", ":", "raise", "RainCloudyException", "(", "'Could not find any valid controller or faucet'", ")" ]
Find controller serial and faucet_serial from the setup page. <select id="id_select_controller2" name="select_controller" > <option value='0' selected='selected'>1 - Controller001</option> </select> :param data: text to be parsed :type data: BeautilSoup object :return: a dict with controller_serial and faucet_serial :rtype: dict :raises IndexError: if controller_serial was not found on the data
[ "Find", "controller", "serial", "and", "faucet_serial", "from", "the", "setup", "page", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/helpers.py#L15-L54
13,512
tchellomello/raincloudy
raincloudy/helpers.py
find_controller_or_faucet_name
def find_controller_or_faucet_name(data, p_type): """ Find on the HTML document the controller name. # expected result <label for="select_controller"> <span class="more_info" id="#styling-type-light" data-hasqtip="26" \ title="Select Control Unit to display." >Control Unit:</span></label><br/> <select class="simpleselect" id="id_select_controller" \ name="select_controller" onchange="submit()" > <option value="0" selected="selected">HERE_IS_CONTROLLER_NAME :param data: BeautifulSoup object :param p_type: parameter type. (controller or faucet) :return: controller or valve name :rtype: string. :raises TypeError: if data is not a BeautifulSoup object :raises IndexError: return None because controller name was not found """ 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 be controller or faucet") try: search_field = 'id_select_{0}'.format(p_type) child = data.find('select', {'id': search_field}) return child.get_text().strip() except AttributeError: return None
python
def find_controller_or_faucet_name(data, p_type): """ Find on the HTML document the controller name. # expected result <label for="select_controller"> <span class="more_info" id="#styling-type-light" data-hasqtip="26" \ title="Select Control Unit to display." >Control Unit:</span></label><br/> <select class="simpleselect" id="id_select_controller" \ name="select_controller" onchange="submit()" > <option value="0" selected="selected">HERE_IS_CONTROLLER_NAME :param data: BeautifulSoup object :param p_type: parameter type. (controller or faucet) :return: controller or valve name :rtype: string. :raises TypeError: if data is not a BeautifulSoup object :raises IndexError: return None because controller name was not found """ 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 be controller or faucet") try: search_field = 'id_select_{0}'.format(p_type) child = data.find('select', {'id': search_field}) return child.get_text().strip() except AttributeError: return None
[ "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 be controller or faucet\"", ")", "try", ":", "search_field", "=", "'id_select_{0}'", ".", "format", "(", "p_type", ")", "child", "=", "data", ".", "find", "(", "'select'", ",", "{", "'id'", ":", "search_field", "}", ")", "return", "child", ".", "get_text", "(", ")", ".", "strip", "(", ")", "except", "AttributeError", ":", "return", "None" ]
Find on the HTML document the controller name. # expected result <label for="select_controller"> <span class="more_info" id="#styling-type-light" data-hasqtip="26" \ title="Select Control Unit to display." >Control Unit:</span></label><br/> <select class="simpleselect" id="id_select_controller" \ name="select_controller" onchange="submit()" > <option value="0" selected="selected">HERE_IS_CONTROLLER_NAME :param data: BeautifulSoup object :param p_type: parameter type. (controller or faucet) :return: controller or valve name :rtype: string. :raises TypeError: if data is not a BeautifulSoup object :raises IndexError: return None because controller name was not found
[ "Find", "on", "the", "HTML", "document", "the", "controller", "name", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/helpers.py#L93-L123
13,513
tchellomello/raincloudy
raincloudy/helpers.py
find_zone_name
def find_zone_name(data, zone_id): """ Find on the HTML document the zone name. # expected result <span class="more_info" \ title="Zone can be renamed on Setup tab">1 - zone1</span>, :param data: BeautifulSoup object :param zone: zone id :return: zone name :rtype: string :raises TypeError: if data is not a BeautifulSoup object :raises IndexError: return None because controller name was not found """ 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_all('span', {'class': 'more_info'}) for row in rows: if row.get_text().startswith(str(zone_id)): return row.get_text()[4:].strip() return None
python
def find_zone_name(data, zone_id): """ Find on the HTML document the zone name. # expected result <span class="more_info" \ title="Zone can be renamed on Setup tab">1 - zone1</span>, :param data: BeautifulSoup object :param zone: zone id :return: zone name :rtype: string :raises TypeError: if data is not a BeautifulSoup object :raises IndexError: return None because controller name was not found """ 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_all('span', {'class': 'more_info'}) for row in rows: if row.get_text().startswith(str(zone_id)): return row.get_text()[4:].strip() return None
[ "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_all", "(", "'span'", ",", "{", "'class'", ":", "'more_info'", "}", ")", "for", "row", "in", "rows", ":", "if", "row", ".", "get_text", "(", ")", ".", "startswith", "(", "str", "(", "zone_id", ")", ")", ":", "return", "row", ".", "get_text", "(", ")", "[", "4", ":", "]", ".", "strip", "(", ")", "return", "None" ]
Find on the HTML document the zone name. # expected result <span class="more_info" \ title="Zone can be renamed on Setup tab">1 - zone1</span>, :param data: BeautifulSoup object :param zone: zone id :return: zone name :rtype: string :raises TypeError: if data is not a BeautifulSoup object :raises IndexError: return None because controller name was not found
[ "Find", "on", "the", "HTML", "document", "the", "zone", "name", "." ]
1847fa913e5ba79645d51bf23637860d68c67dbf
https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/helpers.py#L126-L150
13,514
django-getpaid/django-getpaid
example/orders/listeners.py
new_payment_query_listener
def new_payment_query_listener(sender, order=None, payment=None, **kwargs): """ Here we fill only two obligatory fields of payment, and leave signal handler """ payment.amount = order.total payment.currency = order.currency logger.debug("new_payment_query_listener, amount=%s, currency=%s", payment.amount, payment.currency)
python
def new_payment_query_listener(sender, order=None, payment=None, **kwargs): """ Here we fill only two obligatory fields of payment, and leave signal handler """ payment.amount = order.total payment.currency = order.currency logger.debug("new_payment_query_listener, amount=%s, currency=%s", payment.amount, payment.currency)
[ "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", ")" ]
Here we fill only two obligatory fields of payment, and leave signal handler
[ "Here", "we", "fill", "only", "two", "obligatory", "fields", "of", "payment", "and", "leave", "signal", "handler" ]
f32badcd0ebc28d24adceb4f649c0c2b84c03987
https://github.com/django-getpaid/django-getpaid/blob/f32badcd0ebc28d24adceb4f649c0c2b84c03987/example/orders/listeners.py#L6-L14
13,515
django-getpaid/django-getpaid
example/orders/listeners.py
payment_status_changed_listener
def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs): """ Here we will actually do something, when payment is accepted. E.g. lets change an order status. """ logger.debug("payment_status_changed_listener, old=%s, new=%s", old_status, new_status) if old_status != 'paid' and new_status == 'paid': # Ensures that we process order only one instance.order.status = 'P' instance.order.save()
python
def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs): """ Here we will actually do something, when payment is accepted. E.g. lets change an order status. """ logger.debug("payment_status_changed_listener, old=%s, new=%s", old_status, new_status) if old_status != 'paid' and new_status == 'paid': # Ensures that we process order only one instance.order.status = 'P' instance.order.save()
[ "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 that we process order only one", "instance", ".", "order", ".", "status", "=", "'P'", "instance", ".", "order", ".", "save", "(", ")" ]
Here we will actually do something, when payment is accepted. E.g. lets change an order status.
[ "Here", "we", "will", "actually", "do", "something", "when", "payment", "is", "accepted", ".", "E", ".", "g", ".", "lets", "change", "an", "order", "status", "." ]
f32badcd0ebc28d24adceb4f649c0c2b84c03987
https://github.com/django-getpaid/django-getpaid/blob/f32badcd0ebc28d24adceb4f649c0c2b84c03987/example/orders/listeners.py#L17-L27
13,516
django-getpaid/django-getpaid
getpaid/models.py
register_to_payment
def register_to_payment(order_class, **kwargs): """ A function for registering unaware order class to ``getpaid``. This will generate a ``Payment`` model class that will store payments with ForeignKey to original order class This also will build a model class for every enabled backend. """ global Payment global Order class Payment(PaymentFactory.construct(order=order_class, **kwargs)): objects = PaymentManager() class Meta: ordering = ('-created_on',) verbose_name = _("Payment") verbose_name_plural = _("Payments") Order = order_class # Now build models for backends backend_models_modules = import_backend_modules('models') for backend_name, models_module in backend_models_modules.items(): for model in models_module.build_models(Payment): apps.register_model(backend_name, model) return Payment
python
def register_to_payment(order_class, **kwargs): """ A function for registering unaware order class to ``getpaid``. This will generate a ``Payment`` model class that will store payments with ForeignKey to original order class This also will build a model class for every enabled backend. """ global Payment global Order class Payment(PaymentFactory.construct(order=order_class, **kwargs)): objects = PaymentManager() class Meta: ordering = ('-created_on',) verbose_name = _("Payment") verbose_name_plural = _("Payments") Order = order_class # Now build models for backends backend_models_modules = import_backend_modules('models') for backend_name, models_module in backend_models_modules.items(): for model in models_module.build_models(Payment): apps.register_model(backend_name, model) return Payment
[ "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'", ",", ")", "verbose_name", "=", "_", "(", "\"Payment\"", ")", "verbose_name_plural", "=", "_", "(", "\"Payments\"", ")", "Order", "=", "order_class", "# Now build models for backends", "backend_models_modules", "=", "import_backend_modules", "(", "'models'", ")", "for", "backend_name", ",", "models_module", "in", "backend_models_modules", ".", "items", "(", ")", ":", "for", "model", "in", "models_module", ".", "build_models", "(", "Payment", ")", ":", "apps", ".", "register_model", "(", "backend_name", ",", "model", ")", "return", "Payment" ]
A function for registering unaware order class to ``getpaid``. This will generate a ``Payment`` model class that will store payments with ForeignKey to original order class This also will build a model class for every enabled backend.
[ "A", "function", "for", "registering", "unaware", "order", "class", "to", "getpaid", ".", "This", "will", "generate", "a", "Payment", "model", "class", "that", "will", "store", "payments", "with", "ForeignKey", "to", "original", "order", "class" ]
f32badcd0ebc28d24adceb4f649c0c2b84c03987
https://github.com/django-getpaid/django-getpaid/blob/f32badcd0ebc28d24adceb4f649c0c2b84c03987/getpaid/models.py#L128-L155
13,517
django-getpaid/django-getpaid
getpaid/utils.py
get_backend_choices
def get_backend_choices(currency=None): """ Get active backends modules. Backend list can be filtered by supporting given currency. """ choices = [] backends_names = getattr(settings, 'GETPAID_BACKENDS', []) for backend_name in backends_names: backend = import_module(backend_name) if currency: if currency in backend.PaymentProcessor.BACKEND_ACCEPTED_CURRENCY: choices.append( (backend_name, backend.PaymentProcessor.BACKEND_NAME) ) else: choices.append( (backend_name, backend.PaymentProcessor.BACKEND_NAME) ) return choices
python
def get_backend_choices(currency=None): """ Get active backends modules. Backend list can be filtered by supporting given currency. """ choices = [] backends_names = getattr(settings, 'GETPAID_BACKENDS', []) for backend_name in backends_names: backend = import_module(backend_name) if currency: if currency in backend.PaymentProcessor.BACKEND_ACCEPTED_CURRENCY: choices.append( (backend_name, backend.PaymentProcessor.BACKEND_NAME) ) else: choices.append( (backend_name, backend.PaymentProcessor.BACKEND_NAME) ) return choices
[ "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", ".", "PaymentProcessor", ".", "BACKEND_ACCEPTED_CURRENCY", ":", "choices", ".", "append", "(", "(", "backend_name", ",", "backend", ".", "PaymentProcessor", ".", "BACKEND_NAME", ")", ")", "else", ":", "choices", ".", "append", "(", "(", "backend_name", ",", "backend", ".", "PaymentProcessor", ".", "BACKEND_NAME", ")", ")", "return", "choices" ]
Get active backends modules. Backend list can be filtered by supporting given currency.
[ "Get", "active", "backends", "modules", ".", "Backend", "list", "can", "be", "filtered", "by", "supporting", "given", "currency", "." ]
f32badcd0ebc28d24adceb4f649c0c2b84c03987
https://github.com/django-getpaid/django-getpaid/blob/f32badcd0ebc28d24adceb4f649c0c2b84c03987/getpaid/utils.py#L29-L48
13,518
django-getpaid/django-getpaid
getpaid/backends/payu_rest/__init__.py
PaymentProcessor.online
def online(cls, payload, ip, req_sig): """ Receive and analyze request from payment service with information on payment status change. """ 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') key2 = cls.get_backend_setting('key2') if pos_id != cls.get_backend_setting('pos_id'): logger.warning('Received message for different pos: {}'.format(pos_id)) return 'ERROR' req_sig_dict = cls.parse_payu_sig(req_sig) sig = cls.compute_sig(payload, key2, algorithm=req_sig_dict.get('algorithm', 'md5')) if sig != req_sig_dict['signature']: logger.warning('Received message with malformed signature. Payload: {}'.format(payload)) return 'ERROR' try: payment = Payment.objects.get(id=payment_id) except Payment.DoesNotExist: logger.warning('Received message for nonexistent payment: {}.\nPayload: {}'.format(payment_id, payload)) return 'ERROR' status = order_data['status'] if payment.status != 'paid': if status == 'COMPLETED': payment.external_id = order_data['orderId'] payment.amount = Decimal(order_data['totalAmount']) / Decimal(100) payment.amount_paid = payment.amount payment.currenct = order_data['currencyCode'] payment.paid_on = pendulum.parse(params['localReceiptDateTime']).in_tz('utc') payment.description = order_data['description'] payment.change_status('paid') elif status == 'PENDING': payment.change_status('in_progress') elif status in ['CANCELED', 'REJECTED']: payment.change_status('cancelled') return 'OK'
python
def online(cls, payload, ip, req_sig): """ Receive and analyze request from payment service with information on payment status change. """ 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') key2 = cls.get_backend_setting('key2') if pos_id != cls.get_backend_setting('pos_id'): logger.warning('Received message for different pos: {}'.format(pos_id)) return 'ERROR' req_sig_dict = cls.parse_payu_sig(req_sig) sig = cls.compute_sig(payload, key2, algorithm=req_sig_dict.get('algorithm', 'md5')) if sig != req_sig_dict['signature']: logger.warning('Received message with malformed signature. Payload: {}'.format(payload)) return 'ERROR' try: payment = Payment.objects.get(id=payment_id) except Payment.DoesNotExist: logger.warning('Received message for nonexistent payment: {}.\nPayload: {}'.format(payment_id, payload)) return 'ERROR' status = order_data['status'] if payment.status != 'paid': if status == 'COMPLETED': payment.external_id = order_data['orderId'] payment.amount = Decimal(order_data['totalAmount']) / Decimal(100) payment.amount_paid = payment.amount payment.currenct = order_data['currencyCode'] payment.paid_on = pendulum.parse(params['localReceiptDateTime']).in_tz('utc') payment.description = order_data['description'] payment.change_status('paid') elif status == 'PENDING': payment.change_status('in_progress') elif status in ['CANCELED', 'REJECTED']: payment.change_status('cancelled') return 'OK'
[ "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'", ")", "key2", "=", "cls", ".", "get_backend_setting", "(", "'key2'", ")", "if", "pos_id", "!=", "cls", ".", "get_backend_setting", "(", "'pos_id'", ")", ":", "logger", ".", "warning", "(", "'Received message for different pos: {}'", ".", "format", "(", "pos_id", ")", ")", "return", "'ERROR'", "req_sig_dict", "=", "cls", ".", "parse_payu_sig", "(", "req_sig", ")", "sig", "=", "cls", ".", "compute_sig", "(", "payload", ",", "key2", ",", "algorithm", "=", "req_sig_dict", ".", "get", "(", "'algorithm'", ",", "'md5'", ")", ")", "if", "sig", "!=", "req_sig_dict", "[", "'signature'", "]", ":", "logger", ".", "warning", "(", "'Received message with malformed signature. Payload: {}'", ".", "format", "(", "payload", ")", ")", "return", "'ERROR'", "try", ":", "payment", "=", "Payment", ".", "objects", ".", "get", "(", "id", "=", "payment_id", ")", "except", "Payment", ".", "DoesNotExist", ":", "logger", ".", "warning", "(", "'Received message for nonexistent payment: {}.\\nPayload: {}'", ".", "format", "(", "payment_id", ",", "payload", ")", ")", "return", "'ERROR'", "status", "=", "order_data", "[", "'status'", "]", "if", "payment", ".", "status", "!=", "'paid'", ":", "if", "status", "==", "'COMPLETED'", ":", "payment", ".", "external_id", "=", "order_data", "[", "'orderId'", "]", "payment", ".", "amount", "=", "Decimal", "(", "order_data", "[", "'totalAmount'", "]", ")", "/", "Decimal", "(", "100", ")", "payment", ".", "amount_paid", "=", "payment", ".", "amount", "payment", ".", "currenct", "=", "order_data", "[", "'currencyCode'", "]", "payment", ".", "paid_on", "=", "pendulum", ".", "parse", "(", "params", "[", "'localReceiptDateTime'", "]", ")", ".", "in_tz", "(", "'utc'", ")", "payment", ".", "description", "=", "order_data", "[", "'description'", "]", "payment", ".", "change_status", "(", "'paid'", ")", "elif", "status", "==", "'PENDING'", ":", "payment", ".", "change_status", "(", "'in_progress'", ")", "elif", "status", "in", "[", "'CANCELED'", ",", "'REJECTED'", "]", ":", "payment", ".", "change_status", "(", "'cancelled'", ")", "return", "'OK'" ]
Receive and analyze request from payment service with information on payment status change.
[ "Receive", "and", "analyze", "request", "from", "payment", "service", "with", "information", "on", "payment", "status", "change", "." ]
f32badcd0ebc28d24adceb4f649c0c2b84c03987
https://github.com/django-getpaid/django-getpaid/blob/f32badcd0ebc28d24adceb4f649c0c2b84c03987/getpaid/backends/payu_rest/__init__.py#L87-L132
13,519
django-getpaid/django-getpaid
getpaid/backends/__init__.py
PaymentProcessorBase.get_order_description
def get_order_description(self, payment, order): """ Renders order description using django template provided in ``settings.GETPAID_ORDER_DESCRIPTION`` or if not provided return unicode representation of ``Order object``. """ template = getattr(settings, 'GETPAID_ORDER_DESCRIPTION', None) if template: return Template(template).render(Context({"payment": payment, "order": order})) else: return six.text_type(order)
python
def get_order_description(self, payment, order): """ Renders order description using django template provided in ``settings.GETPAID_ORDER_DESCRIPTION`` or if not provided return unicode representation of ``Order object``. """ template = getattr(settings, 'GETPAID_ORDER_DESCRIPTION', None) if template: return Template(template).render(Context({"payment": payment, "order": order})) else: return six.text_type(order)
[ "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", "six", ".", "text_type", "(", "order", ")" ]
Renders order description using django template provided in ``settings.GETPAID_ORDER_DESCRIPTION`` or if not provided return unicode representation of ``Order object``.
[ "Renders", "order", "description", "using", "django", "template", "provided", "in", "settings", ".", "GETPAID_ORDER_DESCRIPTION", "or", "if", "not", "provided", "return", "unicode", "representation", "of", "Order", "object", "." ]
f32badcd0ebc28d24adceb4f649c0c2b84c03987
https://github.com/django-getpaid/django-getpaid/blob/f32badcd0ebc28d24adceb4f649c0c2b84c03987/getpaid/backends/__init__.py#L54-L63
13,520
django-getpaid/django-getpaid
getpaid/backends/__init__.py
PaymentProcessorBase.get_backend_setting
def get_backend_setting(cls, name, default=None): """ Reads ``name`` setting from backend settings dictionary. If `default` value is omitted, raises ``ImproperlyConfigured`` when setting ``name`` is not available. """ backend_settings = get_backend_settings(cls.BACKEND) if default is not None: return backend_settings.get(name, default) else: try: return backend_settings[name] except KeyError: raise ImproperlyConfigured("getpaid '%s' requires backend '%s' setting" % (cls.BACKEND, name))
python
def get_backend_setting(cls, name, default=None): """ Reads ``name`` setting from backend settings dictionary. If `default` value is omitted, raises ``ImproperlyConfigured`` when setting ``name`` is not available. """ backend_settings = get_backend_settings(cls.BACKEND) if default is not None: return backend_settings.get(name, default) else: try: return backend_settings[name] except KeyError: raise ImproperlyConfigured("getpaid '%s' requires backend '%s' setting" % (cls.BACKEND, name))
[ "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_settings", "[", "name", "]", "except", "KeyError", ":", "raise", "ImproperlyConfigured", "(", "\"getpaid '%s' requires backend '%s' setting\"", "%", "(", "cls", ".", "BACKEND", ",", "name", ")", ")" ]
Reads ``name`` setting from backend settings dictionary. If `default` value is omitted, raises ``ImproperlyConfigured`` when setting ``name`` is not available.
[ "Reads", "name", "setting", "from", "backend", "settings", "dictionary", "." ]
f32badcd0ebc28d24adceb4f649c0c2b84c03987
https://github.com/django-getpaid/django-getpaid/blob/f32badcd0ebc28d24adceb4f649c0c2b84c03987/getpaid/backends/__init__.py#L83-L97
13,521
django-getpaid/django-getpaid
getpaid/backends/dotpay/__init__.py
PaymentProcessor.get_gateway_url
def get_gateway_url(self, request): """ Routes a payment to Gateway, should return URL for redirection. """ params = { 'id': self.get_backend_setting('id'), 'description': self.get_order_description(self.payment, self.payment.order), 'amount': self.payment.amount, 'currency': self.payment.currency, 'type': 0, # 0 = show "return" button after finished payment 'control': self.payment.pk, 'URL': self.get_URL(self.payment.pk), 'URLC': self.get_URLC(), 'api_version': 'dev', } user_data = { 'email': None, 'lang': None, } signals.user_data_query.send(sender=None, order=self.payment.order, user_data=user_data) if user_data['email']: params['email'] = user_data['email'] if user_data['lang'] and user_data['lang'].lower() in self._ACCEPTED_LANGS: params['lang'] = user_data['lang'].lower() elif self.get_backend_setting('lang', False ) and self.get_backend_setting('lang').lower() in self._ACCEPTED_LANGS: params['lang'] = self.get_backend_setting('lang').lower() if self.get_backend_setting('onlinetransfer', False): params['onlinetransfer'] = 1 if self.get_backend_setting('p_email', False): params['p_email'] = self.get_backend_setting('p_email') if self.get_backend_setting('p_info', False): params['p_info'] = self.get_backend_setting('p_info') if self.get_backend_setting('tax', False): params['tax'] = 1 gateway_url = self.get_backend_setting('gateway_url', self._GATEWAY_URL) if self.get_backend_setting('method', 'get').lower() == 'post': return gateway_url, 'POST', params elif self.get_backend_setting('method', 'get').lower() == 'get': for key in params.keys(): params[key] = six.text_type(params[key]).encode('utf-8') return gateway_url + '?' + urlencode(params), "GET", {} else: raise ImproperlyConfigured('Dotpay payment backend accepts only GET or POST')
python
def get_gateway_url(self, request): """ Routes a payment to Gateway, should return URL for redirection. """ params = { 'id': self.get_backend_setting('id'), 'description': self.get_order_description(self.payment, self.payment.order), 'amount': self.payment.amount, 'currency': self.payment.currency, 'type': 0, # 0 = show "return" button after finished payment 'control': self.payment.pk, 'URL': self.get_URL(self.payment.pk), 'URLC': self.get_URLC(), 'api_version': 'dev', } user_data = { 'email': None, 'lang': None, } signals.user_data_query.send(sender=None, order=self.payment.order, user_data=user_data) if user_data['email']: params['email'] = user_data['email'] if user_data['lang'] and user_data['lang'].lower() in self._ACCEPTED_LANGS: params['lang'] = user_data['lang'].lower() elif self.get_backend_setting('lang', False ) and self.get_backend_setting('lang').lower() in self._ACCEPTED_LANGS: params['lang'] = self.get_backend_setting('lang').lower() if self.get_backend_setting('onlinetransfer', False): params['onlinetransfer'] = 1 if self.get_backend_setting('p_email', False): params['p_email'] = self.get_backend_setting('p_email') if self.get_backend_setting('p_info', False): params['p_info'] = self.get_backend_setting('p_info') if self.get_backend_setting('tax', False): params['tax'] = 1 gateway_url = self.get_backend_setting('gateway_url', self._GATEWAY_URL) if self.get_backend_setting('method', 'get').lower() == 'post': return gateway_url, 'POST', params elif self.get_backend_setting('method', 'get').lower() == 'get': for key in params.keys(): params[key] = six.text_type(params[key]).encode('utf-8') return gateway_url + '?' + urlencode(params), "GET", {} else: raise ImproperlyConfigured('Dotpay payment backend accepts only GET or POST')
[ "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", ".", "payment", ".", "currency", ",", "'type'", ":", "0", ",", "# 0 = show \"return\" button after finished payment", "'control'", ":", "self", ".", "payment", ".", "pk", ",", "'URL'", ":", "self", ".", "get_URL", "(", "self", ".", "payment", ".", "pk", ")", ",", "'URLC'", ":", "self", ".", "get_URLC", "(", ")", ",", "'api_version'", ":", "'dev'", ",", "}", "user_data", "=", "{", "'email'", ":", "None", ",", "'lang'", ":", "None", ",", "}", "signals", ".", "user_data_query", ".", "send", "(", "sender", "=", "None", ",", "order", "=", "self", ".", "payment", ".", "order", ",", "user_data", "=", "user_data", ")", "if", "user_data", "[", "'email'", "]", ":", "params", "[", "'email'", "]", "=", "user_data", "[", "'email'", "]", "if", "user_data", "[", "'lang'", "]", "and", "user_data", "[", "'lang'", "]", ".", "lower", "(", ")", "in", "self", ".", "_ACCEPTED_LANGS", ":", "params", "[", "'lang'", "]", "=", "user_data", "[", "'lang'", "]", ".", "lower", "(", ")", "elif", "self", ".", "get_backend_setting", "(", "'lang'", ",", "False", ")", "and", "self", ".", "get_backend_setting", "(", "'lang'", ")", ".", "lower", "(", ")", "in", "self", ".", "_ACCEPTED_LANGS", ":", "params", "[", "'lang'", "]", "=", "self", ".", "get_backend_setting", "(", "'lang'", ")", ".", "lower", "(", ")", "if", "self", ".", "get_backend_setting", "(", "'onlinetransfer'", ",", "False", ")", ":", "params", "[", "'onlinetransfer'", "]", "=", "1", "if", "self", ".", "get_backend_setting", "(", "'p_email'", ",", "False", ")", ":", "params", "[", "'p_email'", "]", "=", "self", ".", "get_backend_setting", "(", "'p_email'", ")", "if", "self", ".", "get_backend_setting", "(", "'p_info'", ",", "False", ")", ":", "params", "[", "'p_info'", "]", "=", "self", ".", "get_backend_setting", "(", "'p_info'", ")", "if", "self", ".", "get_backend_setting", "(", "'tax'", ",", "False", ")", ":", "params", "[", "'tax'", "]", "=", "1", "gateway_url", "=", "self", ".", "get_backend_setting", "(", "'gateway_url'", ",", "self", ".", "_GATEWAY_URL", ")", "if", "self", ".", "get_backend_setting", "(", "'method'", ",", "'get'", ")", ".", "lower", "(", ")", "==", "'post'", ":", "return", "gateway_url", ",", "'POST'", ",", "params", "elif", "self", ".", "get_backend_setting", "(", "'method'", ",", "'get'", ")", ".", "lower", "(", ")", "==", "'get'", ":", "for", "key", "in", "params", ".", "keys", "(", ")", ":", "params", "[", "key", "]", "=", "six", ".", "text_type", "(", "params", "[", "key", "]", ")", ".", "encode", "(", "'utf-8'", ")", "return", "gateway_url", "+", "'?'", "+", "urlencode", "(", "params", ")", ",", "\"GET\"", ",", "{", "}", "else", ":", "raise", "ImproperlyConfigured", "(", "'Dotpay payment backend accepts only GET or POST'", ")" ]
Routes a payment to Gateway, should return URL for redirection.
[ "Routes", "a", "payment", "to", "Gateway", "should", "return", "URL", "for", "redirection", "." ]
f32badcd0ebc28d24adceb4f649c0c2b84c03987
https://github.com/django-getpaid/django-getpaid/blob/f32badcd0ebc28d24adceb4f649c0c2b84c03987/getpaid/backends/dotpay/__init__.py#L114-L163
13,522
hubo1016/aiogrpc
aiogrpc/channel.py
channel_ready_future
def channel_ready_future(channel): """Creates a Future that tracks when a Channel is ready. Cancelling the Future does not affect the channel's state machine. It merely decouples the Future from channel state machine. Args: channel: A Channel object. Returns: A Future object that matures when the channel connectivity is ChannelConnectivity.READY. """ 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_result)) channel.subscribe(_set_result, try_to_connect=True) return fut
python
def channel_ready_future(channel): """Creates a Future that tracks when a Channel is ready. Cancelling the Future does not affect the channel's state machine. It merely decouples the Future from channel state machine. Args: channel: A Channel object. Returns: A Future object that matures when the channel connectivity is ChannelConnectivity.READY. """ 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_result)) channel.subscribe(_set_result, try_to_connect=True) return fut
[ "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_result", ")", ")", "channel", ".", "subscribe", "(", "_set_result", ",", "try_to_connect", "=", "True", ")", "return", "fut" ]
Creates a Future that tracks when a Channel is ready. Cancelling the Future does not affect the channel's state machine. It merely decouples the Future from channel state machine. Args: channel: A Channel object. Returns: A Future object that matures when the channel connectivity is ChannelConnectivity.READY.
[ "Creates", "a", "Future", "that", "tracks", "when", "a", "Channel", "is", "ready", "." ]
5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b
https://github.com/hubo1016/aiogrpc/blob/5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b/aiogrpc/channel.py#L395-L414
13,523
hubo1016/aiogrpc
aiogrpc/channel.py
insecure_channel
def insecure_channel(target, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False): """Creates an insecure Channel to a server. Args: target: The server address options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object. """ return Channel(_grpc.insecure_channel(target, options), loop, executor, standalone_pool_for_streaming)
python
def insecure_channel(target, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False): """Creates an insecure Channel to a server. Args: target: The server address options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object. """ return Channel(_grpc.insecure_channel(target, options), loop, executor, standalone_pool_for_streaming)
[ "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. Args: target: The server address options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object.
[ "Creates", "an", "insecure", "Channel", "to", "a", "server", "." ]
5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b
https://github.com/hubo1016/aiogrpc/blob/5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b/aiogrpc/channel.py#L417-L429
13,524
hubo1016/aiogrpc
aiogrpc/channel.py
secure_channel
def secure_channel(target, credentials, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False): """Creates a secure Channel to a server. Args: target: The server address. credentials: A ChannelCredentials instance. options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object. """ return Channel(_grpc.secure_channel(target, credentials, options), loop, executor, standalone_pool_for_streaming)
python
def secure_channel(target, credentials, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False): """Creates a secure Channel to a server. Args: target: The server address. credentials: A ChannelCredentials instance. options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object. """ return Channel(_grpc.secure_channel(target, credentials, options), loop, executor, standalone_pool_for_streaming)
[ "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_streaming", ")" ]
Creates a secure Channel to a server. Args: target: The server address. credentials: A ChannelCredentials instance. options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object.
[ "Creates", "a", "secure", "Channel", "to", "a", "server", "." ]
5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b
https://github.com/hubo1016/aiogrpc/blob/5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b/aiogrpc/channel.py#L432-L446
13,525
hubo1016/aiogrpc
aiogrpc/channel.py
_UnaryUnaryMultiCallable.future
def future(self, request, timeout=None, metadata=None, credentials=None): """Asynchronously invokes the underlying RPC. Args: request: The request value for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. metadata: Optional :term:`metadata` to be transmitted to the service-side of the RPC. credentials: An optional CallCredentials for the RPC. Returns: An object that is both a Call for the RPC and a Future. In the event of RPC completion, the return Call-Future's result value will be the response message of the RPC. Should the event terminate with non-OK status, the returned Call-Future's exception value will be an RpcError. """ return _utils.wrap_future_call(self._inner.future(request, timeout, metadata, credentials), self._loop, self._executor)
python
def future(self, request, timeout=None, metadata=None, credentials=None): """Asynchronously invokes the underlying RPC. Args: request: The request value for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. metadata: Optional :term:`metadata` to be transmitted to the service-side of the RPC. credentials: An optional CallCredentials for the RPC. Returns: An object that is both a Call for the RPC and a Future. In the event of RPC completion, the return Call-Future's result value will be the response message of the RPC. Should the event terminate with non-OK status, the returned Call-Future's exception value will be an RpcError. """ return _utils.wrap_future_call(self._inner.future(request, timeout, metadata, credentials), self._loop, self._executor)
[ "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. Args: request: The request value for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. metadata: Optional :term:`metadata` to be transmitted to the service-side of the RPC. credentials: An optional CallCredentials for the RPC. Returns: An object that is both a Call for the RPC and a Future. In the event of RPC completion, the return Call-Future's result value will be the response message of the RPC. Should the event terminate with non-OK status, the returned Call-Future's exception value will be an RpcError.
[ "Asynchronously", "invokes", "the", "underlying", "RPC", "." ]
5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b
https://github.com/hubo1016/aiogrpc/blob/5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b/aiogrpc/channel.py#L72-L89
13,526
hubo1016/aiogrpc
aiogrpc/channel.py
_StreamUnaryMultiCallable.with_call
async def with_call(self, request_iterator, timeout=None, metadata=None, credentials=None): """Synchronously invokes the underlying RPC on the client. Args: request_iterator: An ASYNC iterator that yields request values for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. If None, the timeout is considered infinite. metadata: Optional :term:`metadata` to be transmitted to the service-side of the RPC. credentials: An optional CallCredentials for the RPC. Returns: The response value for the RPC and a Call object for the RPC. Raises: RpcError: Indicating that the RPC terminated with non-OK status. The raised RpcError will also be a Call for the RPC affording the RPC's metadata, status code, and details. """ fut = self.future(request_iterator, timeout, metadata, credentials) try: result = await fut return (result, fut) finally: if not fut.done(): fut.cancel()
python
async def with_call(self, request_iterator, timeout=None, metadata=None, credentials=None): """Synchronously invokes the underlying RPC on the client. Args: request_iterator: An ASYNC iterator that yields request values for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. If None, the timeout is considered infinite. metadata: Optional :term:`metadata` to be transmitted to the service-side of the RPC. credentials: An optional CallCredentials for the RPC. Returns: The response value for the RPC and a Call object for the RPC. Raises: RpcError: Indicating that the RPC terminated with non-OK status. The raised RpcError will also be a Call for the RPC affording the RPC's metadata, status code, and details. """ fut = self.future(request_iterator, timeout, metadata, credentials) try: result = await fut return (result, fut) finally: if not fut.done(): fut.cancel()
[ "async", "def", "with_call", "(", "self", ",", "request_iterator", ",", "timeout", "=", "None", ",", "metadata", "=", "None", ",", "credentials", "=", "None", ")", ":", "fut", "=", "self", ".", "future", "(", "request_iterator", ",", "timeout", ",", "metadata", ",", "credentials", ")", "try", ":", "result", "=", "await", "fut", "return", "(", "result", ",", "fut", ")", "finally", ":", "if", "not", "fut", ".", "done", "(", ")", ":", "fut", ".", "cancel", "(", ")" ]
Synchronously invokes the underlying RPC on the client. Args: request_iterator: An ASYNC iterator that yields request values for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. If None, the timeout is considered infinite. metadata: Optional :term:`metadata` to be transmitted to the service-side of the RPC. credentials: An optional CallCredentials for the RPC. Returns: The response value for the RPC and a Call object for the RPC. Raises: RpcError: Indicating that the RPC terminated with non-OK status. The raised RpcError will also be a Call for the RPC affording the RPC's metadata, status code, and details.
[ "Synchronously", "invokes", "the", "underlying", "RPC", "on", "the", "client", "." ]
5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b
https://github.com/hubo1016/aiogrpc/blob/5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b/aiogrpc/channel.py#L177-L206
13,527
hubo1016/aiogrpc
aiogrpc/channel.py
_StreamUnaryMultiCallable.future
def future(self, request_iterator, timeout=None, metadata=None, credentials=None): """Asynchronously invokes the underlying RPC on the client. Args: request_iterator: An ASYNC iterator that yields request values for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. If None, the timeout is considered infinite. metadata: Optional :term:`metadata` to be transmitted to the service-side of the RPC. credentials: An optional CallCredentials for the RPC. Returns: An object that is both a Call for the RPC and a Future. In the event of RPC completion, the return Call-Future's result value will be the response message of the RPC. Should the event terminate with non-OK status, the returned Call-Future's exception value will be an RpcError. """ return _utils.wrap_future_call( self._inner.future( _utils.WrappedAsyncIterator(request_iterator, self._loop), timeout, metadata, credentials ), self._loop, self._executor)
python
def future(self, request_iterator, timeout=None, metadata=None, credentials=None): """Asynchronously invokes the underlying RPC on the client. Args: request_iterator: An ASYNC iterator that yields request values for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. If None, the timeout is considered infinite. metadata: Optional :term:`metadata` to be transmitted to the service-side of the RPC. credentials: An optional CallCredentials for the RPC. Returns: An object that is both a Call for the RPC and a Future. In the event of RPC completion, the return Call-Future's result value will be the response message of the RPC. Should the event terminate with non-OK status, the returned Call-Future's exception value will be an RpcError. """ return _utils.wrap_future_call( self._inner.future( _utils.WrappedAsyncIterator(request_iterator, self._loop), timeout, metadata, credentials ), self._loop, self._executor)
[ "def", "future", "(", "self", ",", "request_iterator", ",", "timeout", "=", "None", ",", "metadata", "=", "None", ",", "credentials", "=", "None", ")", ":", "return", "_utils", ".", "wrap_future_call", "(", "self", ".", "_inner", ".", "future", "(", "_utils", ".", "WrappedAsyncIterator", "(", "request_iterator", ",", "self", ".", "_loop", ")", ",", "timeout", ",", "metadata", ",", "credentials", ")", ",", "self", ".", "_loop", ",", "self", ".", "_executor", ")" ]
Asynchronously invokes the underlying RPC on the client. Args: request_iterator: An ASYNC iterator that yields request values for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. If None, the timeout is considered infinite. metadata: Optional :term:`metadata` to be transmitted to the service-side of the RPC. credentials: An optional CallCredentials for the RPC. Returns: An object that is both a Call for the RPC and a Future. In the event of RPC completion, the return Call-Future's result value will be the response message of the RPC. Should the event terminate with non-OK status, the returned Call-Future's exception value will be an RpcError.
[ "Asynchronously", "invokes", "the", "underlying", "RPC", "on", "the", "client", "." ]
5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b
https://github.com/hubo1016/aiogrpc/blob/5bc98bfbe9f2e11dd0eab8e93b8aeefbcc2ccd4b/aiogrpc/channel.py#L208-L237
13,528
Cymmetria/honeycomb
honeycomb/utils/config_utils.py
config_field_type
def config_field_type(field, cls): """Validate a config field against a type. Similar functionality to :func:`validate_field_matches_type` but returns :obj:`honeycomb.defs.ConfigField` """ return defs.ConfigField(lambda _: isinstance(_, cls), lambda: CONFIG_FIELD_TYPE_ERROR.format(field, cls.__name__))
python
def config_field_type(field, cls): """Validate a config field against a type. Similar functionality to :func:`validate_field_matches_type` but returns :obj:`honeycomb.defs.ConfigField` """ return defs.ConfigField(lambda _: isinstance(_, cls), lambda: CONFIG_FIELD_TYPE_ERROR.format(field, cls.__name__))
[ "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. Similar functionality to :func:`validate_field_matches_type` but returns :obj:`honeycomb.defs.ConfigField`
[ "Validate", "a", "config", "field", "against", "a", "type", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L21-L27
13,529
Cymmetria/honeycomb
honeycomb/utils/config_utils.py
get_config_parameters
def get_config_parameters(plugin_path): """Return the parameters section from config.json.""" 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, [])
python
def get_config_parameters(plugin_path): """Return the parameters section from config.json.""" 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, [])
[ "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.
[ "Return", "the", "parameters", "section", "from", "config", ".", "json", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L41-L46
13,530
Cymmetria/honeycomb
honeycomb/utils/config_utils.py
validate_config_parameters
def validate_config_parameters(config_json, allowed_keys, allowed_types): """Validate parameters in config file.""" custom_fields = config_json.get(defs.PARAMETERS, []) for field in custom_fields: validate_field(field, allowed_keys, allowed_types) default = field.get(defs.DEFAULT) field_type = field.get(defs.TYPE) if default: validate_field_matches_type(field[defs.VALUE], default, field_type)
python
def validate_config_parameters(config_json, allowed_keys, allowed_types): """Validate parameters in config file.""" custom_fields = config_json.get(defs.PARAMETERS, []) for field in custom_fields: validate_field(field, allowed_keys, allowed_types) default = field.get(defs.DEFAULT) field_type = field.get(defs.TYPE) if default: validate_field_matches_type(field[defs.VALUE], default, field_type)
[ "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", ")", "field_type", "=", "field", ".", "get", "(", "defs", ".", "TYPE", ")", "if", "default", ":", "validate_field_matches_type", "(", "field", "[", "defs", ".", "VALUE", "]", ",", "default", ",", "field_type", ")" ]
Validate parameters in config file.
[ "Validate", "parameters", "in", "config", "file", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L49-L57
13,531
Cymmetria/honeycomb
honeycomb/utils/config_utils.py
validate_field_matches_type
def validate_field_matches_type(field, value, field_type, select_items=None, _min=None, _max=None): """Validate a config field against a specific type.""" 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)) or \ (field_type == defs.BOOLEAN_TYPE and not isinstance(value, bool)) or \ (field_type == defs.INTEGER_TYPE and not isinstance(value, int)): raise exceptions.ConfigFieldTypeMismatch(field, value, field_type) if field_type == defs.INTEGER_TYPE: if _min and value < _min: raise exceptions.ConfigFieldTypeMismatch(field, value, "must be higher than {}".format(_min)) if _max and value > _max: raise exceptions.ConfigFieldTypeMismatch(field, value, "must be lower than {}".format(_max)) if field_type == defs.SELECT_TYPE: from honeycomb.utils.plugin_utils import get_select_items items = get_select_items(select_items) if value not in items: raise exceptions.ConfigFieldTypeMismatch(field, value, "one of: {}".format(", ".join(items)))
python
def validate_field_matches_type(field, value, field_type, select_items=None, _min=None, _max=None): """Validate a config field against a specific type.""" 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)) or \ (field_type == defs.BOOLEAN_TYPE and not isinstance(value, bool)) or \ (field_type == defs.INTEGER_TYPE and not isinstance(value, int)): raise exceptions.ConfigFieldTypeMismatch(field, value, field_type) if field_type == defs.INTEGER_TYPE: if _min and value < _min: raise exceptions.ConfigFieldTypeMismatch(field, value, "must be higher than {}".format(_min)) if _max and value > _max: raise exceptions.ConfigFieldTypeMismatch(field, value, "must be lower than {}".format(_max)) if field_type == defs.SELECT_TYPE: from honeycomb.utils.plugin_utils import get_select_items items = get_select_items(select_items) if value not in items: raise exceptions.ConfigFieldTypeMismatch(field, value, "one of: {}".format(", ".join(items)))
[ "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", ")", ")", "or", "(", "field_type", "==", "defs", ".", "BOOLEAN_TYPE", "and", "not", "isinstance", "(", "value", ",", "bool", ")", ")", "or", "(", "field_type", "==", "defs", ".", "INTEGER_TYPE", "and", "not", "isinstance", "(", "value", ",", "int", ")", ")", ":", "raise", "exceptions", ".", "ConfigFieldTypeMismatch", "(", "field", ",", "value", ",", "field_type", ")", "if", "field_type", "==", "defs", ".", "INTEGER_TYPE", ":", "if", "_min", "and", "value", "<", "_min", ":", "raise", "exceptions", ".", "ConfigFieldTypeMismatch", "(", "field", ",", "value", ",", "\"must be higher than {}\"", ".", "format", "(", "_min", ")", ")", "if", "_max", "and", "value", ">", "_max", ":", "raise", "exceptions", ".", "ConfigFieldTypeMismatch", "(", "field", ",", "value", ",", "\"must be lower than {}\"", ".", "format", "(", "_max", ")", ")", "if", "field_type", "==", "defs", ".", "SELECT_TYPE", ":", "from", "honeycomb", ".", "utils", ".", "plugin_utils", "import", "get_select_items", "items", "=", "get_select_items", "(", "select_items", ")", "if", "value", "not", "in", "items", ":", "raise", "exceptions", ".", "ConfigFieldTypeMismatch", "(", "field", ",", "value", ",", "\"one of: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "items", ")", ")", ")" ]
Validate a config field against a specific type.
[ "Validate", "a", "config", "field", "against", "a", "specific", "type", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L60-L78
13,532
Cymmetria/honeycomb
honeycomb/utils/config_utils.py
get_truetype
def get_truetype(value): """Convert a string to a pythonized parameter.""" 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)
python
def get_truetype(value): """Convert a string to a pythonized parameter.""" 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)
[ "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.
[ "Convert", "a", "string", "to", "a", "pythonized", "parameter", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L81-L89
13,533
Cymmetria/honeycomb
honeycomb/utils/config_utils.py
validate_field
def validate_field(field, allowed_keys, allowed_types): """Validate field is allowed and valid.""" 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: raise exceptions.ParametersFieldError(value, key) if key == defs.VALUE: if not is_valid_field_name(value): raise exceptions.ParametersFieldError(value, "field name")
python
def validate_field(field, allowed_keys, allowed_types): """Validate field is allowed and valid.""" 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: raise exceptions.ParametersFieldError(value, key) if key == defs.VALUE: if not is_valid_field_name(value): raise exceptions.ParametersFieldError(value, "field name")
[ "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", ":", "raise", "exceptions", ".", "ParametersFieldError", "(", "value", ",", "key", ")", "if", "key", "==", "defs", ".", "VALUE", ":", "if", "not", "is_valid_field_name", "(", "value", ")", ":", "raise", "exceptions", ".", "ParametersFieldError", "(", "value", ",", "\"field name\"", ")" ]
Validate field is allowed and valid.
[ "Validate", "field", "is", "allowed", "and", "valid", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L92-L102
13,534
Cymmetria/honeycomb
honeycomb/utils/config_utils.py
is_valid_field_name
def is_valid_field_name(value): """Ensure field name is valid.""" 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
python
def is_valid_field_name(value): """Ensure field name is valid.""" 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
[ "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.
[ "Ensure", "field", "name", "is", "valid", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L105-L111
13,535
Cymmetria/honeycomb
honeycomb/utils/config_utils.py
process_config
def process_config(ctx, configfile): """Process a yaml config with instructions. This is a heavy method that loads lots of content, so we only run the imports if its called. """ 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.commands.integration.install import install as integration_install from honeycomb.commands.integration.configure import configure as integration_configure VERSION = "version" SERVICES = defs.SERVICES INTEGRATIONS = defs.INTEGRATIONS required_top_keys = [VERSION, SERVICES] supported_versions = [1] def validate_yml(config): for key in required_top_keys: if key not in config: raise exceptions.ConfigFieldMissing(key) version = config.get(VERSION) if version not in supported_versions: raise exceptions.ConfigFieldTypeMismatch(VERSION, version, "one of: {}".format(repr(supported_versions))) def install_plugins(services, integrations): for cmd, kwargs in [(service_install, {SERVICES: services}), (integration_install, {INTEGRATIONS: integrations})]: try: ctx.invoke(cmd, **kwargs) except SystemExit: # If a plugin is already installed honeycomb will exit abnormally pass def parameters_to_string(parameters_dict): return ["{}={}".format(k, v) for k, v in parameters_dict.items()] def configure_integrations(integrations): for integration in integrations: args_list = parameters_to_string(config[INTEGRATIONS][integration].get(defs.PARAMETERS, dict())) ctx.invoke(integration_configure, integration=integration, args=args_list) def run_services(services, integrations): # TODO: Enable support with multiple services as daemon, and run service.logs afterwards # tricky part is that services launched as daemon are exited with os._exit(0) so you # can't catch it. for service in services: args_list = parameters_to_string(config[SERVICES][service].get(defs.PARAMETERS, dict())) ctx.invoke(service_run, service=service, integration=integrations, args=args_list) # TODO: Silence normal stdout and follow honeycomb.debug.json instead # This would make monitoring containers and collecting logs easier with open(configfile, "rb") as fh: config = yaml.load(fh.read()) validate_yml(config) services = config.get(SERVICES).keys() integrations = config.get(INTEGRATIONS).keys() if config.get(INTEGRATIONS) else [] install_plugins(services, integrations) configure_integrations(integrations) run_services(services, integrations)
python
def process_config(ctx, configfile): """Process a yaml config with instructions. This is a heavy method that loads lots of content, so we only run the imports if its called. """ 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.commands.integration.install import install as integration_install from honeycomb.commands.integration.configure import configure as integration_configure VERSION = "version" SERVICES = defs.SERVICES INTEGRATIONS = defs.INTEGRATIONS required_top_keys = [VERSION, SERVICES] supported_versions = [1] def validate_yml(config): for key in required_top_keys: if key not in config: raise exceptions.ConfigFieldMissing(key) version = config.get(VERSION) if version not in supported_versions: raise exceptions.ConfigFieldTypeMismatch(VERSION, version, "one of: {}".format(repr(supported_versions))) def install_plugins(services, integrations): for cmd, kwargs in [(service_install, {SERVICES: services}), (integration_install, {INTEGRATIONS: integrations})]: try: ctx.invoke(cmd, **kwargs) except SystemExit: # If a plugin is already installed honeycomb will exit abnormally pass def parameters_to_string(parameters_dict): return ["{}={}".format(k, v) for k, v in parameters_dict.items()] def configure_integrations(integrations): for integration in integrations: args_list = parameters_to_string(config[INTEGRATIONS][integration].get(defs.PARAMETERS, dict())) ctx.invoke(integration_configure, integration=integration, args=args_list) def run_services(services, integrations): # TODO: Enable support with multiple services as daemon, and run service.logs afterwards # tricky part is that services launched as daemon are exited with os._exit(0) so you # can't catch it. for service in services: args_list = parameters_to_string(config[SERVICES][service].get(defs.PARAMETERS, dict())) ctx.invoke(service_run, service=service, integration=integrations, args=args_list) # TODO: Silence normal stdout and follow honeycomb.debug.json instead # This would make monitoring containers and collecting logs easier with open(configfile, "rb") as fh: config = yaml.load(fh.read()) validate_yml(config) services = config.get(SERVICES).keys() integrations = config.get(INTEGRATIONS).keys() if config.get(INTEGRATIONS) else [] install_plugins(services, integrations) configure_integrations(integrations) run_services(services, integrations)
[ "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", ".", "commands", ".", "integration", ".", "install", "import", "install", "as", "integration_install", "from", "honeycomb", ".", "commands", ".", "integration", ".", "configure", "import", "configure", "as", "integration_configure", "VERSION", "=", "\"version\"", "SERVICES", "=", "defs", ".", "SERVICES", "INTEGRATIONS", "=", "defs", ".", "INTEGRATIONS", "required_top_keys", "=", "[", "VERSION", ",", "SERVICES", "]", "supported_versions", "=", "[", "1", "]", "def", "validate_yml", "(", "config", ")", ":", "for", "key", "in", "required_top_keys", ":", "if", "key", "not", "in", "config", ":", "raise", "exceptions", ".", "ConfigFieldMissing", "(", "key", ")", "version", "=", "config", ".", "get", "(", "VERSION", ")", "if", "version", "not", "in", "supported_versions", ":", "raise", "exceptions", ".", "ConfigFieldTypeMismatch", "(", "VERSION", ",", "version", ",", "\"one of: {}\"", ".", "format", "(", "repr", "(", "supported_versions", ")", ")", ")", "def", "install_plugins", "(", "services", ",", "integrations", ")", ":", "for", "cmd", ",", "kwargs", "in", "[", "(", "service_install", ",", "{", "SERVICES", ":", "services", "}", ")", ",", "(", "integration_install", ",", "{", "INTEGRATIONS", ":", "integrations", "}", ")", "]", ":", "try", ":", "ctx", ".", "invoke", "(", "cmd", ",", "*", "*", "kwargs", ")", "except", "SystemExit", ":", "# If a plugin is already installed honeycomb will exit abnormally", "pass", "def", "parameters_to_string", "(", "parameters_dict", ")", ":", "return", "[", "\"{}={}\"", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "parameters_dict", ".", "items", "(", ")", "]", "def", "configure_integrations", "(", "integrations", ")", ":", "for", "integration", "in", "integrations", ":", "args_list", "=", "parameters_to_string", "(", "config", "[", "INTEGRATIONS", "]", "[", "integration", "]", ".", "get", "(", "defs", ".", "PARAMETERS", ",", "dict", "(", ")", ")", ")", "ctx", ".", "invoke", "(", "integration_configure", ",", "integration", "=", "integration", ",", "args", "=", "args_list", ")", "def", "run_services", "(", "services", ",", "integrations", ")", ":", "# TODO: Enable support with multiple services as daemon, and run service.logs afterwards", "# tricky part is that services launched as daemon are exited with os._exit(0) so you", "# can't catch it.", "for", "service", "in", "services", ":", "args_list", "=", "parameters_to_string", "(", "config", "[", "SERVICES", "]", "[", "service", "]", ".", "get", "(", "defs", ".", "PARAMETERS", ",", "dict", "(", ")", ")", ")", "ctx", ".", "invoke", "(", "service_run", ",", "service", "=", "service", ",", "integration", "=", "integrations", ",", "args", "=", "args_list", ")", "# TODO: Silence normal stdout and follow honeycomb.debug.json instead", "# This would make monitoring containers and collecting logs easier", "with", "open", "(", "configfile", ",", "\"rb\"", ")", "as", "fh", ":", "config", "=", "yaml", ".", "load", "(", "fh", ".", "read", "(", ")", ")", "validate_yml", "(", "config", ")", "services", "=", "config", ".", "get", "(", "SERVICES", ")", ".", "keys", "(", ")", "integrations", "=", "config", ".", "get", "(", "INTEGRATIONS", ")", ".", "keys", "(", ")", "if", "config", ".", "get", "(", "INTEGRATIONS", ")", "else", "[", "]", "install_plugins", "(", "services", ",", "integrations", ")", "configure_integrations", "(", "integrations", ")", "run_services", "(", "services", ",", "integrations", ")" ]
Process a yaml config with instructions. This is a heavy method that loads lots of content, so we only run the imports if its called.
[ "Process", "a", "yaml", "config", "with", "instructions", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L114-L178
13,536
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
get_plugin_path
def get_plugin_path(home, plugin_type, plugin_name, editable=False): """Return path to plugin. :param home: Path to honeycomb home :param plugin_type: Type of plugin (:obj:`honeycomb.defs.SERVICES` pr :obj:`honeycomb.defs.INTEGRATIONS`) :param plugin_name: Name of plugin :param editable: Use plugin_name as direct path instead of loading from honeycomb home folder """ if editable: plugin_path = plugin_name else: plugin_path = os.path.join(home, plugin_type, plugin_name) return os.path.realpath(plugin_path)
python
def get_plugin_path(home, plugin_type, plugin_name, editable=False): """Return path to plugin. :param home: Path to honeycomb home :param plugin_type: Type of plugin (:obj:`honeycomb.defs.SERVICES` pr :obj:`honeycomb.defs.INTEGRATIONS`) :param plugin_name: Name of plugin :param editable: Use plugin_name as direct path instead of loading from honeycomb home folder """ if editable: plugin_path = plugin_name else: plugin_path = os.path.join(home, plugin_type, plugin_name) return os.path.realpath(plugin_path)
[ "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. :param home: Path to honeycomb home :param plugin_type: Type of plugin (:obj:`honeycomb.defs.SERVICES` pr :obj:`honeycomb.defs.INTEGRATIONS`) :param plugin_name: Name of plugin :param editable: Use plugin_name as direct path instead of loading from honeycomb home folder
[ "Return", "path", "to", "plugin", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L44-L57
13,537
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
install_plugin
def install_plugin(pkgpath, plugin_type, install_path, register_func): """Install specified plugin. :param pkgpath: Name of plugin to be downloaded from online repo or path to plugin folder or zip file. :param install_path: Path where plugin will be installed. :param register_func: Method used to register and validate plugin. """ 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): logger.debug("%s exists in filesystem", pkgpath) if os.path.isdir(pkgpath): pip_status = install_dir(pkgpath, install_path, register_func) else: # pkgpath is file pip_status = install_from_zip(pkgpath, install_path, register_func) else: logger.debug("cannot find %s locally, checking github repo", pkgpath) click.secho("Collecting {}..".format(pkgpath)) pip_status = install_from_repo(pkgpath, plugin_type, install_path, register_func) if pip_status == 0: click.secho("[+] Great success!") else: # TODO: rephrase click.secho("[-] Service installed but something was odd with dependency install, please review debug logs")
python
def install_plugin(pkgpath, plugin_type, install_path, register_func): """Install specified plugin. :param pkgpath: Name of plugin to be downloaded from online repo or path to plugin folder or zip file. :param install_path: Path where plugin will be installed. :param register_func: Method used to register and validate plugin. """ 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): logger.debug("%s exists in filesystem", pkgpath) if os.path.isdir(pkgpath): pip_status = install_dir(pkgpath, install_path, register_func) else: # pkgpath is file pip_status = install_from_zip(pkgpath, install_path, register_func) else: logger.debug("cannot find %s locally, checking github repo", pkgpath) click.secho("Collecting {}..".format(pkgpath)) pip_status = install_from_repo(pkgpath, plugin_type, install_path, register_func) if pip_status == 0: click.secho("[+] Great success!") else: # TODO: rephrase click.secho("[-] Service installed but something was odd with dependency install, please review debug logs")
[ "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", ")", ":", "logger", ".", "debug", "(", "\"%s exists in filesystem\"", ",", "pkgpath", ")", "if", "os", ".", "path", ".", "isdir", "(", "pkgpath", ")", ":", "pip_status", "=", "install_dir", "(", "pkgpath", ",", "install_path", ",", "register_func", ")", "else", ":", "# pkgpath is file", "pip_status", "=", "install_from_zip", "(", "pkgpath", ",", "install_path", ",", "register_func", ")", "else", ":", "logger", ".", "debug", "(", "\"cannot find %s locally, checking github repo\"", ",", "pkgpath", ")", "click", ".", "secho", "(", "\"Collecting {}..\"", ".", "format", "(", "pkgpath", ")", ")", "pip_status", "=", "install_from_repo", "(", "pkgpath", ",", "plugin_type", ",", "install_path", ",", "register_func", ")", "if", "pip_status", "==", "0", ":", "click", ".", "secho", "(", "\"[+] Great success!\"", ")", "else", ":", "# TODO: rephrase", "click", ".", "secho", "(", "\"[-] Service installed but something was odd with dependency install, please review debug logs\"", ")" ]
Install specified plugin. :param pkgpath: Name of plugin to be downloaded from online repo or path to plugin folder or zip file. :param install_path: Path where plugin will be installed. :param register_func: Method used to register and validate plugin.
[ "Install", "specified", "plugin", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L60-L86
13,538
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
install_deps
def install_deps(pkgpath): """Install plugin dependencies using pip. We import pip here to reduce load time for when its not needed. """ 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), "--ignore-installed", "-r", os.path.join(pkgpath, "requirements.txt")] logger.debug("running pip %s", pipargs) return subprocess.check_call([sys.executable, "-m", "pip"] + pipargs) return 0
python
def install_deps(pkgpath): """Install plugin dependencies using pip. We import pip here to reduce load time for when its not needed. """ 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), "--ignore-installed", "-r", os.path.join(pkgpath, "requirements.txt")] logger.debug("running pip %s", pipargs) return subprocess.check_call([sys.executable, "-m", "pip"] + pipargs) return 0
[ "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", ")", ",", "\"--ignore-installed\"", ",", "\"-r\"", ",", "os", ".", "path", ".", "join", "(", "pkgpath", ",", "\"requirements.txt\"", ")", "]", "logger", ".", "debug", "(", "\"running pip %s\"", ",", "pipargs", ")", "return", "subprocess", ".", "check_call", "(", "[", "sys", ".", "executable", ",", "\"-m\"", ",", "\"pip\"", "]", "+", "pipargs", ")", "return", "0" ]
Install plugin dependencies using pip. We import pip here to reduce load time for when its not needed.
[ "Install", "plugin", "dependencies", "using", "pip", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L89-L101
13,539
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
copy_file
def copy_file(src, dst): """Copy a single file. :param src: Source name :param dst: Destination name """ 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: try: os.close(fin) except Exception as exc: logger.debug("Failed to close file handle when copying: {}".format(exc)) try: os.close(fout) except Exception as exc: logger.debug("Failed to close file handle when copying: {}".format(exc))
python
def copy_file(src, dst): """Copy a single file. :param src: Source name :param dst: Destination name """ 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: try: os.close(fin) except Exception as exc: logger.debug("Failed to close file handle when copying: {}".format(exc)) try: os.close(fout) except Exception as exc: logger.debug("Failed to close file handle when copying: {}".format(exc))
[ "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", ":", "try", ":", "os", ".", "close", "(", "fin", ")", "except", "Exception", "as", "exc", ":", "logger", ".", "debug", "(", "\"Failed to close file handle when copying: {}\"", ".", "format", "(", "exc", ")", ")", "try", ":", "os", ".", "close", "(", "fout", ")", "except", "Exception", "as", "exc", ":", "logger", ".", "debug", "(", "\"Failed to close file handle when copying: {}\"", ".", "format", "(", "exc", ")", ")" ]
Copy a single file. :param src: Source name :param dst: Destination name
[ "Copy", "a", "single", "file", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L104-L124
13,540
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
copy_tree
def copy_tree(src, dst, symlinks=False, ignore=[]): """Copy a full directory structure. :param src: Source path :param dst: Destination path :param symlinks: Copy symlinks :param ignore: Subdirs/filenames to 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) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copy_tree(srcname, dstname, symlinks, ignore) else: copy_file(srcname, dstname) except (IOError, os.error) as exc: errors.append((srcname, dstname, str(exc))) except CTError as exc: errors.extend(exc.errors) if errors: raise CTError(errors)
python
def copy_tree(src, dst, symlinks=False, ignore=[]): """Copy a full directory structure. :param src: Source path :param dst: Destination path :param symlinks: Copy symlinks :param ignore: Subdirs/filenames to 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) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copy_tree(srcname, dstname, symlinks, ignore) else: copy_file(srcname, dstname) except (IOError, os.error) as exc: errors.append((srcname, dstname, str(exc))) except CTError as exc: errors.extend(exc.errors) if errors: raise CTError(errors)
[ "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", ")", "dstname", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "name", ")", "try", ":", "if", "symlinks", "and", "os", ".", "path", ".", "islink", "(", "srcname", ")", ":", "linkto", "=", "os", ".", "readlink", "(", "srcname", ")", "os", ".", "symlink", "(", "linkto", ",", "dstname", ")", "elif", "os", ".", "path", ".", "isdir", "(", "srcname", ")", ":", "copy_tree", "(", "srcname", ",", "dstname", ",", "symlinks", ",", "ignore", ")", "else", ":", "copy_file", "(", "srcname", ",", "dstname", ")", "except", "(", "IOError", ",", "os", ".", "error", ")", "as", "exc", ":", "errors", ".", "append", "(", "(", "srcname", ",", "dstname", ",", "str", "(", "exc", ")", ")", ")", "except", "CTError", "as", "exc", ":", "errors", ".", "extend", "(", "exc", ".", "errors", ")", "if", "errors", ":", "raise", "CTError", "(", "errors", ")" ]
Copy a full directory structure. :param src: Source path :param dst: Destination path :param symlinks: Copy symlinks :param ignore: Subdirs/filenames to ignore
[ "Copy", "a", "full", "directory", "structure", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L130-L161
13,541
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
install_dir
def install_dir(pkgpath, install_path, register_func, delete_after_install=False): """Install plugin from specified directory. install_path and register_func are same as :func:`install_plugin`. :param delete_after_install: Delete pkgpath after install (used in :func:`install_from_zip`). """ 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: copy_tree(pkgpath, os.path.join(install_path, plugin.name)) if delete_after_install: logger.debug("deleting %s", pkgpath) shutil.rmtree(pkgpath) pkgpath = os.path.join(install_path, plugin.name) except (OSError, CTError) as exc: # TODO: handle package name exists (upgrade? overwrite?) logger.debug(str(exc), exc_info=True) raise exceptions.PluginAlreadyInstalled(plugin.name) return install_deps(pkgpath)
python
def install_dir(pkgpath, install_path, register_func, delete_after_install=False): """Install plugin from specified directory. install_path and register_func are same as :func:`install_plugin`. :param delete_after_install: Delete pkgpath after install (used in :func:`install_from_zip`). """ 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: copy_tree(pkgpath, os.path.join(install_path, plugin.name)) if delete_after_install: logger.debug("deleting %s", pkgpath) shutil.rmtree(pkgpath) pkgpath = os.path.join(install_path, plugin.name) except (OSError, CTError) as exc: # TODO: handle package name exists (upgrade? overwrite?) logger.debug(str(exc), exc_info=True) raise exceptions.PluginAlreadyInstalled(plugin.name) return install_deps(pkgpath)
[ "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", ":", "copy_tree", "(", "pkgpath", ",", "os", ".", "path", ".", "join", "(", "install_path", ",", "plugin", ".", "name", ")", ")", "if", "delete_after_install", ":", "logger", ".", "debug", "(", "\"deleting %s\"", ",", "pkgpath", ")", "shutil", ".", "rmtree", "(", "pkgpath", ")", "pkgpath", "=", "os", ".", "path", ".", "join", "(", "install_path", ",", "plugin", ".", "name", ")", "except", "(", "OSError", ",", "CTError", ")", "as", "exc", ":", "# TODO: handle package name exists (upgrade? overwrite?)", "logger", ".", "debug", "(", "str", "(", "exc", ")", ",", "exc_info", "=", "True", ")", "raise", "exceptions", ".", "PluginAlreadyInstalled", "(", "plugin", ".", "name", ")", "return", "install_deps", "(", "pkgpath", ")" ]
Install plugin from specified directory. install_path and register_func are same as :func:`install_plugin`. :param delete_after_install: Delete pkgpath after install (used in :func:`install_from_zip`).
[ "Install", "plugin", "from", "specified", "directory", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L164-L184
13,542
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
install_from_zip
def install_from_zip(pkgpath, install_path, register_func, delete_after_install=False): """Install plugin from zipfile.""" logger.debug("%s is a file, attempting to load zip", pkgpath) pkgtempdir = tempfile.mkdtemp(prefix="honeycomb_") try: with zipfile.ZipFile(pkgpath) as pkgzip: pkgzip.extractall(pkgtempdir) except zipfile.BadZipfile as exc: logger.debug(str(exc)) raise click.ClickException(str(exc)) if delete_after_install: logger.debug("deleting %s", pkgpath) os.remove(pkgpath) logger.debug("installing from unzipped folder %s", pkgtempdir) return install_dir(pkgtempdir, install_path, register_func, delete_after_install=True)
python
def install_from_zip(pkgpath, install_path, register_func, delete_after_install=False): """Install plugin from zipfile.""" logger.debug("%s is a file, attempting to load zip", pkgpath) pkgtempdir = tempfile.mkdtemp(prefix="honeycomb_") try: with zipfile.ZipFile(pkgpath) as pkgzip: pkgzip.extractall(pkgtempdir) except zipfile.BadZipfile as exc: logger.debug(str(exc)) raise click.ClickException(str(exc)) if delete_after_install: logger.debug("deleting %s", pkgpath) os.remove(pkgpath) logger.debug("installing from unzipped folder %s", pkgtempdir) return install_dir(pkgtempdir, install_path, register_func, delete_after_install=True)
[ "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", ":", "pkgzip", ".", "extractall", "(", "pkgtempdir", ")", "except", "zipfile", ".", "BadZipfile", "as", "exc", ":", "logger", ".", "debug", "(", "str", "(", "exc", ")", ")", "raise", "click", ".", "ClickException", "(", "str", "(", "exc", ")", ")", "if", "delete_after_install", ":", "logger", ".", "debug", "(", "\"deleting %s\"", ",", "pkgpath", ")", "os", ".", "remove", "(", "pkgpath", ")", "logger", ".", "debug", "(", "\"installing from unzipped folder %s\"", ",", "pkgtempdir", ")", "return", "install_dir", "(", "pkgtempdir", ",", "install_path", ",", "register_func", ",", "delete_after_install", "=", "True", ")" ]
Install plugin from zipfile.
[ "Install", "plugin", "from", "zipfile", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L187-L201
13,543
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
install_from_repo
def install_from_repo(pkgname, plugin_type, install_path, register_func): """Install plugin from online repo.""" rsession = requests.Session() rsession.mount("https://", HTTPAdapter(max_retries=3)) logger.debug("trying to install %s from online repo", pkgname) pkgurl = "{}/{}s/{}.zip".format(defs.GITHUB_RAW, plugin_type, pkgname) try: logger.debug("Requesting HTTP HEAD: %s", pkgurl) r = rsession.head(pkgurl) r.raise_for_status() total_size = int(r.headers.get("content-length", 0)) pkgsize = _sizeof_fmt(total_size) with click.progressbar(length=total_size, label="Downloading {} {} ({}).." .format(plugin_type, pkgname, pkgsize)) as bar: r = rsession.get(pkgurl, stream=True) with tempfile.NamedTemporaryFile(delete=False) as f: downloaded_bytes = 0 for chunk in r.iter_content(chunk_size=1): # TODO: Consider increasing to reduce cycles if chunk: f.write(chunk) downloaded_bytes += len(chunk) bar.update(downloaded_bytes) return install_from_zip(f.name, install_path, register_func, delete_after_install=True) except requests.exceptions.HTTPError as exc: logger.debug(str(exc)) raise exceptions.PluginNotFoundInOnlineRepo(pkgname) except requests.exceptions.ConnectionError as exc: logger.debug(str(exc)) raise exceptions.PluginRepoConnectionError()
python
def install_from_repo(pkgname, plugin_type, install_path, register_func): """Install plugin from online repo.""" rsession = requests.Session() rsession.mount("https://", HTTPAdapter(max_retries=3)) logger.debug("trying to install %s from online repo", pkgname) pkgurl = "{}/{}s/{}.zip".format(defs.GITHUB_RAW, plugin_type, pkgname) try: logger.debug("Requesting HTTP HEAD: %s", pkgurl) r = rsession.head(pkgurl) r.raise_for_status() total_size = int(r.headers.get("content-length", 0)) pkgsize = _sizeof_fmt(total_size) with click.progressbar(length=total_size, label="Downloading {} {} ({}).." .format(plugin_type, pkgname, pkgsize)) as bar: r = rsession.get(pkgurl, stream=True) with tempfile.NamedTemporaryFile(delete=False) as f: downloaded_bytes = 0 for chunk in r.iter_content(chunk_size=1): # TODO: Consider increasing to reduce cycles if chunk: f.write(chunk) downloaded_bytes += len(chunk) bar.update(downloaded_bytes) return install_from_zip(f.name, install_path, register_func, delete_after_install=True) except requests.exceptions.HTTPError as exc: logger.debug(str(exc)) raise exceptions.PluginNotFoundInOnlineRepo(pkgname) except requests.exceptions.ConnectionError as exc: logger.debug(str(exc)) raise exceptions.PluginRepoConnectionError()
[ "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", "(", "defs", ".", "GITHUB_RAW", ",", "plugin_type", ",", "pkgname", ")", "try", ":", "logger", ".", "debug", "(", "\"Requesting HTTP HEAD: %s\"", ",", "pkgurl", ")", "r", "=", "rsession", ".", "head", "(", "pkgurl", ")", "r", ".", "raise_for_status", "(", ")", "total_size", "=", "int", "(", "r", ".", "headers", ".", "get", "(", "\"content-length\"", ",", "0", ")", ")", "pkgsize", "=", "_sizeof_fmt", "(", "total_size", ")", "with", "click", ".", "progressbar", "(", "length", "=", "total_size", ",", "label", "=", "\"Downloading {} {} ({})..\"", ".", "format", "(", "plugin_type", ",", "pkgname", ",", "pkgsize", ")", ")", "as", "bar", ":", "r", "=", "rsession", ".", "get", "(", "pkgurl", ",", "stream", "=", "True", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "as", "f", ":", "downloaded_bytes", "=", "0", "for", "chunk", "in", "r", ".", "iter_content", "(", "chunk_size", "=", "1", ")", ":", "# TODO: Consider increasing to reduce cycles", "if", "chunk", ":", "f", ".", "write", "(", "chunk", ")", "downloaded_bytes", "+=", "len", "(", "chunk", ")", "bar", ".", "update", "(", "downloaded_bytes", ")", "return", "install_from_zip", "(", "f", ".", "name", ",", "install_path", ",", "register_func", ",", "delete_after_install", "=", "True", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "exc", ":", "logger", ".", "debug", "(", "str", "(", "exc", ")", ")", "raise", "exceptions", ".", "PluginNotFoundInOnlineRepo", "(", "pkgname", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "exc", ":", "logger", ".", "debug", "(", "str", "(", "exc", ")", ")", "raise", "exceptions", ".", "PluginRepoConnectionError", "(", ")" ]
Install plugin from online repo.
[ "Install", "plugin", "from", "online", "repo", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L204-L233
13,544
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
uninstall_plugin
def uninstall_plugin(pkgpath, force): """Uninstall a plugin. :param pkgpath: Path to package to uninstall (delete) :param force: Force uninstall without asking """ 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) try: shutil.rmtree(pkgpath) logger.debug("successfully uninstalled {}".format(pkgname)) click.secho("[*] Uninstalled {}".format(pkgname)) except OSError as exc: logger.exception(str(exc)) else: click.secho("[-] doh! I cannot seem to find `{}`, are you sure it's installed?".format(pkgname))
python
def uninstall_plugin(pkgpath, force): """Uninstall a plugin. :param pkgpath: Path to package to uninstall (delete) :param force: Force uninstall without asking """ 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) try: shutil.rmtree(pkgpath) logger.debug("successfully uninstalled {}".format(pkgname)) click.secho("[*] Uninstalled {}".format(pkgname)) except OSError as exc: logger.exception(str(exc)) else: click.secho("[-] doh! I cannot seem to find `{}`, are you sure it's installed?".format(pkgname))
[ "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", ")", "try", ":", "shutil", ".", "rmtree", "(", "pkgpath", ")", "logger", ".", "debug", "(", "\"successfully uninstalled {}\"", ".", "format", "(", "pkgname", ")", ")", "click", ".", "secho", "(", "\"[*] Uninstalled {}\"", ".", "format", "(", "pkgname", ")", ")", "except", "OSError", "as", "exc", ":", "logger", ".", "exception", "(", "str", "(", "exc", ")", ")", "else", ":", "click", ".", "secho", "(", "\"[-] doh! I cannot seem to find `{}`, are you sure it's installed?\"", ".", "format", "(", "pkgname", ")", ")" ]
Uninstall a plugin. :param pkgpath: Path to package to uninstall (delete) :param force: Force uninstall without asking
[ "Uninstall", "a", "plugin", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L246-L264
13,545
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
list_remote_plugins
def list_remote_plugins(installed_plugins, plugin_type): """List remote plugins from online repo.""" 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/{1}s.txt".format(defs.GITHUB_RAW, plugin_type)) logger.debug("fetching %ss from remote repo", plugin_type) plugins = [_ for _ in r.text.splitlines() if _ not in installed_plugins] click.secho(" ".join(plugins)) except requests.exceptions.ConnectionError as exc: logger.debug(str(exc), exc_info=True) raise click.ClickException("Unable to fetch {} information from online repository".format(plugin_type))
python
def list_remote_plugins(installed_plugins, plugin_type): """List remote plugins from online repo.""" 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/{1}s.txt".format(defs.GITHUB_RAW, plugin_type)) logger.debug("fetching %ss from remote repo", plugin_type) plugins = [_ for _ in r.text.splitlines() if _ not in installed_plugins] click.secho(" ".join(plugins)) except requests.exceptions.ConnectionError as exc: logger.debug(str(exc), exc_info=True) raise click.ClickException("Unable to fetch {} information from online repository".format(plugin_type))
[ "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/{1}s.txt\"", ".", "format", "(", "defs", ".", "GITHUB_RAW", ",", "plugin_type", ")", ")", "logger", ".", "debug", "(", "\"fetching %ss from remote repo\"", ",", "plugin_type", ")", "plugins", "=", "[", "_", "for", "_", "in", "r", ".", "text", ".", "splitlines", "(", ")", "if", "_", "not", "in", "installed_plugins", "]", "click", ".", "secho", "(", "\" \"", ".", "join", "(", "plugins", ")", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "exc", ":", "logger", ".", "debug", "(", "str", "(", "exc", ")", ",", "exc_info", "=", "True", ")", "raise", "click", ".", "ClickException", "(", "\"Unable to fetch {} information from online repository\"", ".", "format", "(", "plugin_type", ")", ")" ]
List remote plugins from online repo.
[ "List", "remote", "plugins", "from", "online", "repo", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L267-L281
13,546
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
list_local_plugins
def list_local_plugins(plugin_type, plugins_path, plugin_details): """List local plugins with 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_plugins: click.secho("[*] You do not have any {0}s installed, " "try installing one with `honeycomb {0} install`".format(plugin_type)) return installed_plugins
python
def list_local_plugins(plugin_type, plugins_path, plugin_details): """List local plugins with 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_plugins: click.secho("[*] You do not have any {0}s installed, " "try installing one with `honeycomb {0} install`".format(plugin_type)) return installed_plugins
[ "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_plugins", ":", "click", ".", "secho", "(", "\"[*] You do not have any {0}s installed, \"", "\"try installing one with `honeycomb {0} install`\"", ".", "format", "(", "plugin_type", ")", ")", "return", "installed_plugins" ]
List local plugins with details.
[ "List", "local", "plugins", "with", "details", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L284-L296
13,547
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
parse_plugin_args
def parse_plugin_args(command_args, config_args): """Parse command line arguments based on the plugin's parameters config. :param command_args: Command line arguments as provided by the user in `key=value` format. :param config_args: Plugin parameters parsed from config.json. :returns: Validated dictionary of parameters that will be passed to plugin class """ 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)) parsed_args[kv[0]] = config_utils.get_truetype(kv[1]) for arg in config_args: value = arg[defs.VALUE] value_type = arg[defs.TYPE] if value in parsed_args: # will raise if invalid config_utils.validate_field_matches_type(value, parsed_args[value], value_type, arg.get(defs.ITEMS), arg.get(defs.MIN), arg.get(defs.MAX)) elif defs.DEFAULT in arg: # Has a default field # return default values for unset parameters parsed_args[value] = arg[defs.DEFAULT] elif arg[defs.REQUIRED]: # requires field is true """parameter was not supplied by user, but it's required and has no default value""" raise exceptions.RequiredFieldMissing(value) return parsed_args
python
def parse_plugin_args(command_args, config_args): """Parse command line arguments based on the plugin's parameters config. :param command_args: Command line arguments as provided by the user in `key=value` format. :param config_args: Plugin parameters parsed from config.json. :returns: Validated dictionary of parameters that will be passed to plugin class """ 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)) parsed_args[kv[0]] = config_utils.get_truetype(kv[1]) for arg in config_args: value = arg[defs.VALUE] value_type = arg[defs.TYPE] if value in parsed_args: # will raise if invalid config_utils.validate_field_matches_type(value, parsed_args[value], value_type, arg.get(defs.ITEMS), arg.get(defs.MIN), arg.get(defs.MAX)) elif defs.DEFAULT in arg: # Has a default field # return default values for unset parameters parsed_args[value] = arg[defs.DEFAULT] elif arg[defs.REQUIRED]: # requires field is true """parameter was not supplied by user, but it's required and has no default value""" raise exceptions.RequiredFieldMissing(value) return parsed_args
[ "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", ")", ")", "parsed_args", "[", "kv", "[", "0", "]", "]", "=", "config_utils", ".", "get_truetype", "(", "kv", "[", "1", "]", ")", "for", "arg", "in", "config_args", ":", "value", "=", "arg", "[", "defs", ".", "VALUE", "]", "value_type", "=", "arg", "[", "defs", ".", "TYPE", "]", "if", "value", "in", "parsed_args", ":", "# will raise if invalid", "config_utils", ".", "validate_field_matches_type", "(", "value", ",", "parsed_args", "[", "value", "]", ",", "value_type", ",", "arg", ".", "get", "(", "defs", ".", "ITEMS", ")", ",", "arg", ".", "get", "(", "defs", ".", "MIN", ")", ",", "arg", ".", "get", "(", "defs", ".", "MAX", ")", ")", "elif", "defs", ".", "DEFAULT", "in", "arg", ":", "# Has a default field", "# return default values for unset parameters", "parsed_args", "[", "value", "]", "=", "arg", "[", "defs", ".", "DEFAULT", "]", "elif", "arg", "[", "defs", ".", "REQUIRED", "]", ":", "# requires field is true", "\"\"\"parameter was not supplied by user, but it's required and has no default value\"\"\"", "raise", "exceptions", ".", "RequiredFieldMissing", "(", "value", ")", "return", "parsed_args" ]
Parse command line arguments based on the plugin's parameters config. :param command_args: Command line arguments as provided by the user in `key=value` format. :param config_args: Plugin parameters parsed from config.json. :returns: Validated dictionary of parameters that will be passed to plugin class
[ "Parse", "command", "line", "arguments", "based", "on", "the", "plugin", "s", "parameters", "config", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L299-L327
13,548
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
get_select_items
def get_select_items(items): """Return list of possible select 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.ParametersFieldError(item, "a dictionary with {} and {}" .format(defs.LABEL, defs.VALUE)) return option_items
python
def get_select_items(items): """Return list of possible select 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.ParametersFieldError(item, "a dictionary with {} and {}" .format(defs.LABEL, defs.VALUE)) return option_items
[ "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", ".", "ParametersFieldError", "(", "item", ",", "\"a dictionary with {} and {}\"", ".", "format", "(", "defs", ".", "LABEL", ",", "defs", ".", "VALUE", ")", ")", "return", "option_items" ]
Return list of possible select items.
[ "Return", "list", "of", "possible", "select", "items", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L330-L339
13,549
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
print_plugin_args
def print_plugin_args(plugin_path): """Print plugin parameters table.""" 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(), defs.REQUIRED.upper(), defs.DESCRIPTION.upper()) click.secho(title) click.secho("-" * len(title)) for arg in args: help_text = " ({})".format(arg[defs.HELP_TEXT]) if defs.HELP_TEXT in arg else "" options = _parse_select_options(arg) description = arg[defs.LABEL] + options + help_text click.secho(args_format.format(arg[defs.VALUE], arg[defs.TYPE], str(arg.get(defs.DEFAULT, None)), str(arg.get(defs.REQUIRED, False)), description))
python
def print_plugin_args(plugin_path): """Print plugin parameters table.""" 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(), defs.REQUIRED.upper(), defs.DESCRIPTION.upper()) click.secho(title) click.secho("-" * len(title)) for arg in args: help_text = " ({})".format(arg[defs.HELP_TEXT]) if defs.HELP_TEXT in arg else "" options = _parse_select_options(arg) description = arg[defs.LABEL] + options + help_text click.secho(args_format.format(arg[defs.VALUE], arg[defs.TYPE], str(arg.get(defs.DEFAULT, None)), str(arg.get(defs.REQUIRED, False)), description))
[ "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", "(", ")", ",", "defs", ".", "REQUIRED", ".", "upper", "(", ")", ",", "defs", ".", "DESCRIPTION", ".", "upper", "(", ")", ")", "click", ".", "secho", "(", "title", ")", "click", ".", "secho", "(", "\"-\"", "*", "len", "(", "title", ")", ")", "for", "arg", "in", "args", ":", "help_text", "=", "\" ({})\"", ".", "format", "(", "arg", "[", "defs", ".", "HELP_TEXT", "]", ")", "if", "defs", ".", "HELP_TEXT", "in", "arg", "else", "\"\"", "options", "=", "_parse_select_options", "(", "arg", ")", "description", "=", "arg", "[", "defs", ".", "LABEL", "]", "+", "options", "+", "help_text", "click", ".", "secho", "(", "args_format", ".", "format", "(", "arg", "[", "defs", ".", "VALUE", "]", ",", "arg", "[", "defs", ".", "TYPE", "]", ",", "str", "(", "arg", ".", "get", "(", "defs", ".", "DEFAULT", ",", "None", ")", ")", ",", "str", "(", "arg", ".", "get", "(", "defs", ".", "REQUIRED", ",", "False", ")", ")", ",", "description", ")", ")" ]
Print plugin parameters table.
[ "Print", "plugin", "parameters", "table", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L354-L367
13,550
Cymmetria/honeycomb
honeycomb/integrationmanager/tasks.py
configure_integration
def configure_integration(path): """Configure and enable an integration.""" 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(str(exc), exc_info=True) raise click.ClickException("Cannot load {} integration args, please configure it first." .format(os.path.basename(path))) click.secho("[*] Adding integration {}".format(integration.name)) logger.debug("Adding integration %s", integration.name, extra={"integration": integration.name, "args": integration_args}) configured_integration = ConfiguredIntegration(name=integration.name, integration=integration, path=path) configured_integration.data = integration_args configured_integration.integration.module = get_integration_module(path).IntegrationActionsClass(integration_args) configured_integrations.append(configured_integration)
python
def configure_integration(path): """Configure and enable an integration.""" 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(str(exc), exc_info=True) raise click.ClickException("Cannot load {} integration args, please configure it first." .format(os.path.basename(path))) click.secho("[*] Adding integration {}".format(integration.name)) logger.debug("Adding integration %s", integration.name, extra={"integration": integration.name, "args": integration_args}) configured_integration = ConfiguredIntegration(name=integration.name, integration=integration, path=path) configured_integration.data = integration_args configured_integration.integration.module = get_integration_module(path).IntegrationActionsClass(integration_args) configured_integrations.append(configured_integration)
[ "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", "(", "str", "(", "exc", ")", ",", "exc_info", "=", "True", ")", "raise", "click", ".", "ClickException", "(", "\"Cannot load {} integration args, please configure it first.\"", ".", "format", "(", "os", ".", "path", ".", "basename", "(", "path", ")", ")", ")", "click", ".", "secho", "(", "\"[*] Adding integration {}\"", ".", "format", "(", "integration", ".", "name", ")", ")", "logger", ".", "debug", "(", "\"Adding integration %s\"", ",", "integration", ".", "name", ",", "extra", "=", "{", "\"integration\"", ":", "integration", ".", "name", ",", "\"args\"", ":", "integration_args", "}", ")", "configured_integration", "=", "ConfiguredIntegration", "(", "name", "=", "integration", ".", "name", ",", "integration", "=", "integration", ",", "path", "=", "path", ")", "configured_integration", ".", "data", "=", "integration_args", "configured_integration", ".", "integration", ".", "module", "=", "get_integration_module", "(", "path", ")", ".", "IntegrationActionsClass", "(", "integration_args", ")", "configured_integrations", ".", "append", "(", "configured_integration", ")" ]
Configure and enable an integration.
[ "Configure", "and", "enable", "an", "integration", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L39-L58
13,551
Cymmetria/honeycomb
honeycomb/integrationmanager/tasks.py
send_alert_to_subscribed_integrations
def send_alert_to_subscribed_integrations(alert): """Send Alert to relevant integrations.""" 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=(alert, configured_integration)).start()
python
def send_alert_to_subscribed_integrations(alert): """Send Alert to relevant integrations.""" 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=(alert, configured_integration)).start()
[ "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", "=", "(", "alert", ",", "configured_integration", ")", ")", ".", "start", "(", ")" ]
Send Alert to relevant integrations.
[ "Send", "Alert", "to", "relevant", "integrations", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L61-L66
13,552
Cymmetria/honeycomb
honeycomb/integrationmanager/tasks.py
get_valid_configured_integrations
def get_valid_configured_integrations(alert): """Return a list of integrations for alert filtered by alert_type. :returns: A list of relevant integrations """ 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_integrations = [ _ for _ in configured_integrations if _.integration.integration_type == IntegrationTypes.EVENT_OUTPUT.name and (not _.integration.supported_event_types or alert.alert_type in _.integration.supported_event_types) ] return valid_configured_integrations
python
def get_valid_configured_integrations(alert): """Return a list of integrations for alert filtered by alert_type. :returns: A list of relevant integrations """ 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_integrations = [ _ for _ in configured_integrations if _.integration.integration_type == IntegrationTypes.EVENT_OUTPUT.name and (not _.integration.supported_event_types or alert.alert_type in _.integration.supported_event_types) ] return valid_configured_integrations
[ "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_integrations", "=", "[", "_", "for", "_", "in", "configured_integrations", "if", "_", ".", "integration", ".", "integration_type", "==", "IntegrationTypes", ".", "EVENT_OUTPUT", ".", "name", "and", "(", "not", "_", ".", "integration", ".", "supported_event_types", "or", "alert", ".", "alert_type", "in", "_", ".", "integration", ".", "supported_event_types", ")", "]", "return", "valid_configured_integrations" ]
Return a list of integrations for alert filtered by alert_type. :returns: A list of relevant integrations
[ "Return", "a", "list", "of", "integrations", "for", "alert", "filtered", "by", "alert_type", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L74-L89
13,553
Cymmetria/honeycomb
honeycomb/integrationmanager/tasks.py
create_integration_alert_and_call_send
def create_integration_alert_and_call_send(alert, configured_integration): """Create an IntegrationAlert object and send it to Integration.""" integration_alert = IntegrationAlert( alert=alert, configured_integration=configured_integration, status=IntegrationAlertStatuses.PENDING.name, retries=configured_integration.integration.max_send_retries ) send_alert_to_configured_integration(integration_alert)
python
def create_integration_alert_and_call_send(alert, configured_integration): """Create an IntegrationAlert object and send it to Integration.""" integration_alert = IntegrationAlert( alert=alert, configured_integration=configured_integration, status=IntegrationAlertStatuses.PENDING.name, retries=configured_integration.integration.max_send_retries ) send_alert_to_configured_integration(integration_alert)
[ "def", "create_integration_alert_and_call_send", "(", "alert", ",", "configured_integration", ")", ":", "integration_alert", "=", "IntegrationAlert", "(", "alert", "=", "alert", ",", "configured_integration", "=", "configured_integration", ",", "status", "=", "IntegrationAlertStatuses", ".", "PENDING", ".", "name", ",", "retries", "=", "configured_integration", ".", "integration", ".", "max_send_retries", ")", "send_alert_to_configured_integration", "(", "integration_alert", ")" ]
Create an IntegrationAlert object and send it to Integration.
[ "Create", "an", "IntegrationAlert", "object", "and", "send", "it", "to", "Integration", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L92-L101
13,554
Cymmetria/honeycomb
honeycomb/integrationmanager/tasks.py
send_alert_to_configured_integration
def send_alert_to_configured_integration(integration_alert): """Send IntegrationAlert to configured integration.""" try: alert = integration_alert.alert configured_integration = integration_alert.configured_integration integration = configured_integration.integration integration_actions_instance = configured_integration.integration.module alert_fields = dict() if integration.required_fields: if not all([hasattr(alert, _) for _ in integration.required_fields]): logger.debug("Alert does not have all required_fields (%s) for integration %s, skipping", integration.required_fields, integration.name) return exclude_fields = ["alert_type", "service_type"] alert_fields = {} for field in alert.__slots__: if hasattr(alert, field) and field not in exclude_fields: alert_fields[field] = getattr(alert, field) logger.debug("Sending alert %s to %s", alert_fields, integration.name) output_data, output_file_content = integration_actions_instance.send_event(alert_fields) if integration.polling_enabled: integration_alert.status = IntegrationAlertStatuses.POLLING.name polling_integration_alerts.append(integration_alert) else: integration_alert.status = IntegrationAlertStatuses.DONE.name integration_alert.send_time = get_current_datetime_utc() integration_alert.output_data = json.dumps(output_data) # TODO: do something with successfully handled alerts? They are all written to debug log file except exceptions.IntegrationMissingRequiredFieldError as exc: logger.exception("Send response formatting for integration alert %s failed. Missing required fields", integration_alert, exc.message) integration_alert.status = IntegrationAlertStatuses.ERROR_MISSING_SEND_FIELDS.name except exceptions.IntegrationOutputFormatError: logger.exception("Send response formatting for integration alert %s failed", integration_alert) integration_alert.status = IntegrationAlertStatuses.ERROR_SENDING_FORMATTING.name except exceptions.IntegrationSendEventError as exc: integration_send_retries = integration_alert.retries if integration_alert.retries <= MAX_SEND_RETRIES \ else MAX_SEND_RETRIES # making sure we do not exceed celery max retries send_retries_left = integration_send_retries - 1 integration_alert.retries = send_retries_left logger.error("Sending integration alert %s failed. Message: %s. Retries left: %s", integration_alert, exc.message, send_retries_left) if send_retries_left == 0: integration_alert.status = IntegrationAlertStatuses.ERROR_SENDING.name if send_retries_left > 0: sleep(SEND_ALERT_DATA_INTERVAL) send_alert_to_configured_integration(integration_alert)
python
def send_alert_to_configured_integration(integration_alert): """Send IntegrationAlert to configured integration.""" try: alert = integration_alert.alert configured_integration = integration_alert.configured_integration integration = configured_integration.integration integration_actions_instance = configured_integration.integration.module alert_fields = dict() if integration.required_fields: if not all([hasattr(alert, _) for _ in integration.required_fields]): logger.debug("Alert does not have all required_fields (%s) for integration %s, skipping", integration.required_fields, integration.name) return exclude_fields = ["alert_type", "service_type"] alert_fields = {} for field in alert.__slots__: if hasattr(alert, field) and field not in exclude_fields: alert_fields[field] = getattr(alert, field) logger.debug("Sending alert %s to %s", alert_fields, integration.name) output_data, output_file_content = integration_actions_instance.send_event(alert_fields) if integration.polling_enabled: integration_alert.status = IntegrationAlertStatuses.POLLING.name polling_integration_alerts.append(integration_alert) else: integration_alert.status = IntegrationAlertStatuses.DONE.name integration_alert.send_time = get_current_datetime_utc() integration_alert.output_data = json.dumps(output_data) # TODO: do something with successfully handled alerts? They are all written to debug log file except exceptions.IntegrationMissingRequiredFieldError as exc: logger.exception("Send response formatting for integration alert %s failed. Missing required fields", integration_alert, exc.message) integration_alert.status = IntegrationAlertStatuses.ERROR_MISSING_SEND_FIELDS.name except exceptions.IntegrationOutputFormatError: logger.exception("Send response formatting for integration alert %s failed", integration_alert) integration_alert.status = IntegrationAlertStatuses.ERROR_SENDING_FORMATTING.name except exceptions.IntegrationSendEventError as exc: integration_send_retries = integration_alert.retries if integration_alert.retries <= MAX_SEND_RETRIES \ else MAX_SEND_RETRIES # making sure we do not exceed celery max retries send_retries_left = integration_send_retries - 1 integration_alert.retries = send_retries_left logger.error("Sending integration alert %s failed. Message: %s. Retries left: %s", integration_alert, exc.message, send_retries_left) if send_retries_left == 0: integration_alert.status = IntegrationAlertStatuses.ERROR_SENDING.name if send_retries_left > 0: sleep(SEND_ALERT_DATA_INTERVAL) send_alert_to_configured_integration(integration_alert)
[ "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_instance", "=", "configured_integration", ".", "integration", ".", "module", "alert_fields", "=", "dict", "(", ")", "if", "integration", ".", "required_fields", ":", "if", "not", "all", "(", "[", "hasattr", "(", "alert", ",", "_", ")", "for", "_", "in", "integration", ".", "required_fields", "]", ")", ":", "logger", ".", "debug", "(", "\"Alert does not have all required_fields (%s) for integration %s, skipping\"", ",", "integration", ".", "required_fields", ",", "integration", ".", "name", ")", "return", "exclude_fields", "=", "[", "\"alert_type\"", ",", "\"service_type\"", "]", "alert_fields", "=", "{", "}", "for", "field", "in", "alert", ".", "__slots__", ":", "if", "hasattr", "(", "alert", ",", "field", ")", "and", "field", "not", "in", "exclude_fields", ":", "alert_fields", "[", "field", "]", "=", "getattr", "(", "alert", ",", "field", ")", "logger", ".", "debug", "(", "\"Sending alert %s to %s\"", ",", "alert_fields", ",", "integration", ".", "name", ")", "output_data", ",", "output_file_content", "=", "integration_actions_instance", ".", "send_event", "(", "alert_fields", ")", "if", "integration", ".", "polling_enabled", ":", "integration_alert", ".", "status", "=", "IntegrationAlertStatuses", ".", "POLLING", ".", "name", "polling_integration_alerts", ".", "append", "(", "integration_alert", ")", "else", ":", "integration_alert", ".", "status", "=", "IntegrationAlertStatuses", ".", "DONE", ".", "name", "integration_alert", ".", "send_time", "=", "get_current_datetime_utc", "(", ")", "integration_alert", ".", "output_data", "=", "json", ".", "dumps", "(", "output_data", ")", "# TODO: do something with successfully handled alerts? They are all written to debug log file", "except", "exceptions", ".", "IntegrationMissingRequiredFieldError", "as", "exc", ":", "logger", ".", "exception", "(", "\"Send response formatting for integration alert %s failed. Missing required fields\"", ",", "integration_alert", ",", "exc", ".", "message", ")", "integration_alert", ".", "status", "=", "IntegrationAlertStatuses", ".", "ERROR_MISSING_SEND_FIELDS", ".", "name", "except", "exceptions", ".", "IntegrationOutputFormatError", ":", "logger", ".", "exception", "(", "\"Send response formatting for integration alert %s failed\"", ",", "integration_alert", ")", "integration_alert", ".", "status", "=", "IntegrationAlertStatuses", ".", "ERROR_SENDING_FORMATTING", ".", "name", "except", "exceptions", ".", "IntegrationSendEventError", "as", "exc", ":", "integration_send_retries", "=", "integration_alert", ".", "retries", "if", "integration_alert", ".", "retries", "<=", "MAX_SEND_RETRIES", "else", "MAX_SEND_RETRIES", "# making sure we do not exceed celery max retries", "send_retries_left", "=", "integration_send_retries", "-", "1", "integration_alert", ".", "retries", "=", "send_retries_left", "logger", ".", "error", "(", "\"Sending integration alert %s failed. Message: %s. Retries left: %s\"", ",", "integration_alert", ",", "exc", ".", "message", ",", "send_retries_left", ")", "if", "send_retries_left", "==", "0", ":", "integration_alert", ".", "status", "=", "IntegrationAlertStatuses", ".", "ERROR_SENDING", ".", "name", "if", "send_retries_left", ">", "0", ":", "sleep", "(", "SEND_ALERT_DATA_INTERVAL", ")", "send_alert_to_configured_integration", "(", "integration_alert", ")" ]
Send IntegrationAlert to configured integration.
[ "Send", "IntegrationAlert", "to", "configured", "integration", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L104-L167
13,555
Cymmetria/honeycomb
honeycomb/integrationmanager/tasks.py
poll_integration_alert_data
def poll_integration_alert_data(integration_alert): """Poll for updates on waiting IntegrationAlerts.""" logger.info("Polling information for integration alert %s", integration_alert) try: configured_integration = integration_alert.configured_integration integration_actions_instance = configured_integration.integration.module output_data, output_file_content = integration_actions_instance.poll_for_updates( json.loads(integration_alert.output_data) ) integration_alert.status = IntegrationAlertStatuses.DONE.name integration_alert.output_data = json.dumps(output_data) polling_integration_alerts.remove(integration_alert) except exceptions.IntegrationNoMethodImplementationError: logger.error("No poll_for_updates function found for integration alert %s", integration_alert) integration_alert.status = IntegrationAlertStatuses.ERROR_POLLING.name except exceptions.IntegrationPollEventError: # This does not always indicate an error, this is also raised when need to try again later logger.debug("Polling for integration alert %s failed", integration_alert) except exceptions.IntegrationOutputFormatError: logger.error("Integration alert %s formatting error", integration_alert) integration_alert.status = IntegrationAlertStatuses.ERROR_POLLING_FORMATTING.name except Exception: logger.exception("Error polling integration alert %s", integration_alert) integration_alert.status = IntegrationAlertStatuses.ERROR_POLLING.name
python
def poll_integration_alert_data(integration_alert): """Poll for updates on waiting IntegrationAlerts.""" logger.info("Polling information for integration alert %s", integration_alert) try: configured_integration = integration_alert.configured_integration integration_actions_instance = configured_integration.integration.module output_data, output_file_content = integration_actions_instance.poll_for_updates( json.loads(integration_alert.output_data) ) integration_alert.status = IntegrationAlertStatuses.DONE.name integration_alert.output_data = json.dumps(output_data) polling_integration_alerts.remove(integration_alert) except exceptions.IntegrationNoMethodImplementationError: logger.error("No poll_for_updates function found for integration alert %s", integration_alert) integration_alert.status = IntegrationAlertStatuses.ERROR_POLLING.name except exceptions.IntegrationPollEventError: # This does not always indicate an error, this is also raised when need to try again later logger.debug("Polling for integration alert %s failed", integration_alert) except exceptions.IntegrationOutputFormatError: logger.error("Integration alert %s formatting error", integration_alert) integration_alert.status = IntegrationAlertStatuses.ERROR_POLLING_FORMATTING.name except Exception: logger.exception("Error polling integration alert %s", integration_alert) integration_alert.status = IntegrationAlertStatuses.ERROR_POLLING.name
[ "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_integration", ".", "integration", ".", "module", "output_data", ",", "output_file_content", "=", "integration_actions_instance", ".", "poll_for_updates", "(", "json", ".", "loads", "(", "integration_alert", ".", "output_data", ")", ")", "integration_alert", ".", "status", "=", "IntegrationAlertStatuses", ".", "DONE", ".", "name", "integration_alert", ".", "output_data", "=", "json", ".", "dumps", "(", "output_data", ")", "polling_integration_alerts", ".", "remove", "(", "integration_alert", ")", "except", "exceptions", ".", "IntegrationNoMethodImplementationError", ":", "logger", ".", "error", "(", "\"No poll_for_updates function found for integration alert %s\"", ",", "integration_alert", ")", "integration_alert", ".", "status", "=", "IntegrationAlertStatuses", ".", "ERROR_POLLING", ".", "name", "except", "exceptions", ".", "IntegrationPollEventError", ":", "# This does not always indicate an error, this is also raised when need to try again later", "logger", ".", "debug", "(", "\"Polling for integration alert %s failed\"", ",", "integration_alert", ")", "except", "exceptions", ".", "IntegrationOutputFormatError", ":", "logger", ".", "error", "(", "\"Integration alert %s formatting error\"", ",", "integration_alert", ")", "integration_alert", ".", "status", "=", "IntegrationAlertStatuses", ".", "ERROR_POLLING_FORMATTING", ".", "name", "except", "Exception", ":", "logger", ".", "exception", "(", "\"Error polling integration alert %s\"", ",", "integration_alert", ")", "integration_alert", ".", "status", "=", "IntegrationAlertStatuses", ".", "ERROR_POLLING", ".", "name" ]
Poll for updates on waiting IntegrationAlerts.
[ "Poll", "for", "updates", "on", "waiting", "IntegrationAlerts", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L191-L223
13,556
Cymmetria/honeycomb
honeycomb/utils/wait.py
wait_until
def wait_until(func, check_return_value=True, total_timeout=60, interval=0.5, exc_list=None, error_message="", *args, **kwargs): """Run a command in a loop until desired result or timeout occurs. :param func: Function to call and wait for :param bool check_return_value: Examine return value :param int total_timeout: Wait timeout, :param float interval: Sleep interval between retries :param list exc_list: Acceptable exception list :param str error_message: Default error messages :param args: args to pass to func :param kwargs: lwargs to pass to fun """ start_function = time.time() while time.time() - start_function < total_timeout: try: logger.debug("executing {} with args {} {}".format(func, args, kwargs)) return_value = func(*args, **kwargs) if not check_return_value or (check_return_value and return_value): return return_value except Exception as exc: if exc_list and any([isinstance(exc, x) for x in exc_list]): pass else: raise time.sleep(interval) raise TimeoutException(error_message)
python
def wait_until(func, check_return_value=True, total_timeout=60, interval=0.5, exc_list=None, error_message="", *args, **kwargs): """Run a command in a loop until desired result or timeout occurs. :param func: Function to call and wait for :param bool check_return_value: Examine return value :param int total_timeout: Wait timeout, :param float interval: Sleep interval between retries :param list exc_list: Acceptable exception list :param str error_message: Default error messages :param args: args to pass to func :param kwargs: lwargs to pass to fun """ start_function = time.time() while time.time() - start_function < total_timeout: try: logger.debug("executing {} with args {} {}".format(func, args, kwargs)) return_value = func(*args, **kwargs) if not check_return_value or (check_return_value and return_value): return return_value except Exception as exc: if exc_list and any([isinstance(exc, x) for x in exc_list]): pass else: raise time.sleep(interval) raise TimeoutException(error_message)
[ "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", "(", ")", "while", "time", ".", "time", "(", ")", "-", "start_function", "<", "total_timeout", ":", "try", ":", "logger", ".", "debug", "(", "\"executing {} with args {} {}\"", ".", "format", "(", "func", ",", "args", ",", "kwargs", ")", ")", "return_value", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "check_return_value", "or", "(", "check_return_value", "and", "return_value", ")", ":", "return", "return_value", "except", "Exception", "as", "exc", ":", "if", "exc_list", "and", "any", "(", "[", "isinstance", "(", "exc", ",", "x", ")", "for", "x", "in", "exc_list", "]", ")", ":", "pass", "else", ":", "raise", "time", ".", "sleep", "(", "interval", ")", "raise", "TimeoutException", "(", "error_message", ")" ]
Run a command in a loop until desired result or timeout occurs. :param func: Function to call and wait for :param bool check_return_value: Examine return value :param int total_timeout: Wait timeout, :param float interval: Sleep interval between retries :param list exc_list: Acceptable exception list :param str error_message: Default error messages :param args: args to pass to func :param kwargs: lwargs to pass to fun
[ "Run", "a", "command", "in", "a", "loop", "until", "desired", "result", "or", "timeout", "occurs", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/wait.py#L19-L55
13,557
Cymmetria/honeycomb
honeycomb/utils/wait.py
search_json_log
def search_json_log(filepath, key, value): """Search json log file for a key=value pair. :param filepath: Valid path to a json file :param key: key to match :param value: value to match :returns: First matching line in json log file, parsed by :py:func:`json.loads` """ 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 except IOError: pass return False
python
def search_json_log(filepath, key, value): """Search json log file for a key=value pair. :param filepath: Valid path to a json file :param key: key to match :param value: value to match :returns: First matching line in json log file, parsed by :py:func:`json.loads` """ 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 except IOError: pass return False
[ "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", "except", "IOError", ":", "pass", "return", "False" ]
Search json log file for a key=value pair. :param filepath: Valid path to a json file :param key: key to match :param value: value to match :returns: First matching line in json log file, parsed by :py:func:`json.loads`
[ "Search", "json", "log", "file", "for", "a", "key", "=", "value", "pair", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/wait.py#L58-L74
13,558
Cymmetria/honeycomb
honeycomb/commands/__init__.py
MyGroup.list_commands
def list_commands(self, ctx): """List commands from folder.""" 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
python
def list_commands(self, ctx): """List commands from folder.""" 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
[ "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.
[ "List", "commands", "from", "folder", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/__init__.py#L27-L34
13,559
Cymmetria/honeycomb
honeycomb/commands/__init__.py
MyGroup.get_command
def get_command(self, ctx, name): """Fetch command from folder.""" plugin = os.path.basename(self.folder) try: command = importlib.import_module("honeycomb.commands.{}.{}".format(plugin, name)) except ImportError: raise click.UsageError("No such command {} {}\n\n{}".format(plugin, name, self.get_help(ctx))) return getattr(command, name)
python
def get_command(self, ctx, name): """Fetch command from folder.""" plugin = os.path.basename(self.folder) try: command = importlib.import_module("honeycomb.commands.{}.{}".format(plugin, name)) except ImportError: raise click.UsageError("No such command {} {}\n\n{}".format(plugin, name, self.get_help(ctx))) return getattr(command, name)
[ "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 command {} {}\\n\\n{}\"", ".", "format", "(", "plugin", ",", "name", ",", "self", ".", "get_help", "(", "ctx", ")", ")", ")", "return", "getattr", "(", "command", ",", "name", ")" ]
Fetch command from folder.
[ "Fetch", "command", "from", "folder", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/__init__.py#L36-L43
13,560
Cymmetria/honeycomb
honeycomb/cli.py
cli
def cli(ctx, home, iamroot, config, verbose): """Honeycomb is a honeypot framework.""" _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, extra={"command": ctx.command.name, "params": ctx.params}) try: is_admin = os.getuid() == 0 except AttributeError: is_admin = ctypes.windll.shell32.IsUserAnAdmin() if is_admin: if not iamroot: raise click.ClickException("Honeycomb should not run as a privileged user, if you are just " "trying to bind to a low port try running `setcap 'cap_net_bind_service=+ep' " "$(which honeycomb)` instead. If you insist, use --iamroot") logger.warn("running as root!") ctx.obj["HOME"] = home logger.debug("ctx: {}".format(ctx.obj)) if config: return process_config(ctx, config)
python
def cli(ctx, home, iamroot, config, verbose): """Honeycomb is a honeypot framework.""" _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, extra={"command": ctx.command.name, "params": ctx.params}) try: is_admin = os.getuid() == 0 except AttributeError: is_admin = ctypes.windll.shell32.IsUserAnAdmin() if is_admin: if not iamroot: raise click.ClickException("Honeycomb should not run as a privileged user, if you are just " "trying to bind to a low port try running `setcap 'cap_net_bind_service=+ep' " "$(which honeycomb)` instead. If you insist, use --iamroot") logger.warn("running as root!") ctx.obj["HOME"] = home logger.debug("ctx: {}".format(ctx.obj)) if config: return process_config(ctx, config)
[ "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", ",", "extra", "=", "{", "\"command\"", ":", "ctx", ".", "command", ".", "name", ",", "\"params\"", ":", "ctx", ".", "params", "}", ")", "try", ":", "is_admin", "=", "os", ".", "getuid", "(", ")", "==", "0", "except", "AttributeError", ":", "is_admin", "=", "ctypes", ".", "windll", ".", "shell32", ".", "IsUserAnAdmin", "(", ")", "if", "is_admin", ":", "if", "not", "iamroot", ":", "raise", "click", ".", "ClickException", "(", "\"Honeycomb should not run as a privileged user, if you are just \"", "\"trying to bind to a low port try running `setcap 'cap_net_bind_service=+ep' \"", "\"$(which honeycomb)` instead. If you insist, use --iamroot\"", ")", "logger", ".", "warn", "(", "\"running as root!\"", ")", "ctx", ".", "obj", "[", "\"HOME\"", "]", "=", "home", "logger", ".", "debug", "(", "\"ctx: {}\"", ".", "format", "(", "ctx", ".", "obj", ")", ")", "if", "config", ":", "return", "process_config", "(", "ctx", ",", "config", ")" ]
Honeycomb is a honeypot framework.
[ "Honeycomb", "is", "a", "honeypot", "framework", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/cli.py#L40-L66
13,561
Cymmetria/honeycomb
honeycomb/cli.py
setup_logging
def setup_logging(home, verbose): """Configure logging for honeycomb.""" logging.setLoggerClass(MyLogger) logging.config.dictConfig({ "version": 1, "disable_existing_loggers": False, "formatters": { "console": { "format": "%(levelname)-8s [%(asctime)s %(name)s] %(filename)s:%(lineno)s %(funcName)s: %(message)s", }, "json": { "()": jsonlogger.JsonFormatter, "format": "%(levelname)s %(asctime)s %(name)s %(filename)s %(lineno)s %(funcName)s %(message)s", }, }, "handlers": { "default": { "level": "DEBUG" if verbose else "INFO", "class": "logging.StreamHandler", "formatter": "console", }, "file": { "level": "DEBUG", "class": "logging.handlers.WatchedFileHandler", "filename": os.path.join(home, DEBUG_LOG_FILE), "formatter": "json", }, }, "loggers": { "": { "handlers": ["default", "file"], "level": "DEBUG", "propagate": True, }, } })
python
def setup_logging(home, verbose): """Configure logging for honeycomb.""" logging.setLoggerClass(MyLogger) logging.config.dictConfig({ "version": 1, "disable_existing_loggers": False, "formatters": { "console": { "format": "%(levelname)-8s [%(asctime)s %(name)s] %(filename)s:%(lineno)s %(funcName)s: %(message)s", }, "json": { "()": jsonlogger.JsonFormatter, "format": "%(levelname)s %(asctime)s %(name)s %(filename)s %(lineno)s %(funcName)s %(message)s", }, }, "handlers": { "default": { "level": "DEBUG" if verbose else "INFO", "class": "logging.StreamHandler", "formatter": "console", }, "file": { "level": "DEBUG", "class": "logging.handlers.WatchedFileHandler", "filename": os.path.join(home, DEBUG_LOG_FILE), "formatter": "json", }, }, "loggers": { "": { "handlers": ["default", "file"], "level": "DEBUG", "propagate": True, }, } })
[ "def", "setup_logging", "(", "home", ",", "verbose", ")", ":", "logging", ".", "setLoggerClass", "(", "MyLogger", ")", "logging", ".", "config", ".", "dictConfig", "(", "{", "\"version\"", ":", "1", ",", "\"disable_existing_loggers\"", ":", "False", ",", "\"formatters\"", ":", "{", "\"console\"", ":", "{", "\"format\"", ":", "\"%(levelname)-8s [%(asctime)s %(name)s] %(filename)s:%(lineno)s %(funcName)s: %(message)s\"", ",", "}", ",", "\"json\"", ":", "{", "\"()\"", ":", "jsonlogger", ".", "JsonFormatter", ",", "\"format\"", ":", "\"%(levelname)s %(asctime)s %(name)s %(filename)s %(lineno)s %(funcName)s %(message)s\"", ",", "}", ",", "}", ",", "\"handlers\"", ":", "{", "\"default\"", ":", "{", "\"level\"", ":", "\"DEBUG\"", "if", "verbose", "else", "\"INFO\"", ",", "\"class\"", ":", "\"logging.StreamHandler\"", ",", "\"formatter\"", ":", "\"console\"", ",", "}", ",", "\"file\"", ":", "{", "\"level\"", ":", "\"DEBUG\"", ",", "\"class\"", ":", "\"logging.handlers.WatchedFileHandler\"", ",", "\"filename\"", ":", "os", ".", "path", ".", "join", "(", "home", ",", "DEBUG_LOG_FILE", ")", ",", "\"formatter\"", ":", "\"json\"", ",", "}", ",", "}", ",", "\"loggers\"", ":", "{", "\"\"", ":", "{", "\"handlers\"", ":", "[", "\"default\"", ",", "\"file\"", "]", ",", "\"level\"", ":", "\"DEBUG\"", ",", "\"propagate\"", ":", "True", ",", "}", ",", "}", "}", ")" ]
Configure logging for honeycomb.
[ "Configure", "logging", "for", "honeycomb", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/cli.py#L91-L126
13,562
Cymmetria/honeycomb
honeycomb/cli.py
MyLogger.makeRecord
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): """Override default logger to allow overriding of internal attributes.""" # See below commented section for a simple example of what the docstring refers to if six.PY2: rv = logging.LogRecord(name, level, fn, lno, msg, args, exc_info, func) else: rv = logging.LogRecord(name, level, fn, lno, msg, args, exc_info, func, sinfo) if extra is None: extra = dict() extra.update({"pid": os.getpid(), "uid": os.getuid(), "gid": os.getgid(), "ppid": os.getppid()}) for key in extra: # if (key in ["message", "asctime"]) or (key in rv.__dict__): # raise KeyError("Attempt to overwrite %r in LogRecord" % key) rv.__dict__[key] = extra[key] return rv
python
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): """Override default logger to allow overriding of internal attributes.""" # See below commented section for a simple example of what the docstring refers to if six.PY2: rv = logging.LogRecord(name, level, fn, lno, msg, args, exc_info, func) else: rv = logging.LogRecord(name, level, fn, lno, msg, args, exc_info, func, sinfo) if extra is None: extra = dict() extra.update({"pid": os.getpid(), "uid": os.getuid(), "gid": os.getgid(), "ppid": os.getppid()}) for key in extra: # if (key in ["message", "asctime"]) or (key in rv.__dict__): # raise KeyError("Attempt to overwrite %r in LogRecord" % key) rv.__dict__[key] = extra[key] return rv
[ "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", ",", "msg", ",", "args", ",", "exc_info", ",", "func", ")", "else", ":", "rv", "=", "logging", ".", "LogRecord", "(", "name", ",", "level", ",", "fn", ",", "lno", ",", "msg", ",", "args", ",", "exc_info", ",", "func", ",", "sinfo", ")", "if", "extra", "is", "None", ":", "extra", "=", "dict", "(", ")", "extra", ".", "update", "(", "{", "\"pid\"", ":", "os", ".", "getpid", "(", ")", ",", "\"uid\"", ":", "os", ".", "getuid", "(", ")", ",", "\"gid\"", ":", "os", ".", "getgid", "(", ")", ",", "\"ppid\"", ":", "os", ".", "getppid", "(", ")", "}", ")", "for", "key", "in", "extra", ":", "# if (key in [\"message\", \"asctime\"]) or (key in rv.__dict__):", "# raise KeyError(\"Attempt to overwrite %r in LogRecord\" % key)", "rv", ".", "__dict__", "[", "key", "]", "=", "extra", "[", "key", "]", "return", "rv" ]
Override default logger to allow overriding of internal attributes.
[ "Override", "default", "logger", "to", "allow", "overriding", "of", "internal", "attributes", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/cli.py#L72-L88
13,563
Cymmetria/honeycomb
honeycomb/commands/service/stop.py
stop
def stop(ctx, service, editable): """Stop a running service daemon.""" 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, SERVICES, service, editable) logger.debug("loading {}".format(service)) service = register_service(service_path) try: with open(os.path.join(service_path, ARGS_JSON)) as f: service_args = json.loads(f.read()) except IOError as exc: logger.debug(str(exc), exc_info=True) raise click.ClickException("Cannot load service args, are you sure server is running?") # get our service class instance service_module = get_service_module(service_path) service_obj = service_module.service_class(alert_types=service.alert_types, service_args=service_args) # prepare runner runner = myRunner(service_obj, pidfile=service_path + ".pid", stdout=open(os.path.join(service_path, "stdout.log"), "ab"), stderr=open(os.path.join(service_path, "stderr.log"), "ab")) click.secho("[*] Stopping {}".format(service.name)) try: runner._stop() except daemon.runner.DaemonRunnerStopFailureError as exc: logger.debug(str(exc), exc_info=True) raise click.ClickException("Unable to stop service, are you sure it is running?")
python
def stop(ctx, service, editable): """Stop a running service daemon.""" 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, SERVICES, service, editable) logger.debug("loading {}".format(service)) service = register_service(service_path) try: with open(os.path.join(service_path, ARGS_JSON)) as f: service_args = json.loads(f.read()) except IOError as exc: logger.debug(str(exc), exc_info=True) raise click.ClickException("Cannot load service args, are you sure server is running?") # get our service class instance service_module = get_service_module(service_path) service_obj = service_module.service_class(alert_types=service.alert_types, service_args=service_args) # prepare runner runner = myRunner(service_obj, pidfile=service_path + ".pid", stdout=open(os.path.join(service_path, "stdout.log"), "ab"), stderr=open(os.path.join(service_path, "stderr.log"), "ab")) click.secho("[*] Stopping {}".format(service.name)) try: runner._stop() except daemon.runner.DaemonRunnerStopFailureError as exc: logger.debug(str(exc), exc_info=True) raise click.ClickException("Unable to stop service, are you sure it is running?")
[ "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", ",", "SERVICES", ",", "service", ",", "editable", ")", "logger", ".", "debug", "(", "\"loading {}\"", ".", "format", "(", "service", ")", ")", "service", "=", "register_service", "(", "service_path", ")", "try", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "service_path", ",", "ARGS_JSON", ")", ")", "as", "f", ":", "service_args", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "except", "IOError", "as", "exc", ":", "logger", ".", "debug", "(", "str", "(", "exc", ")", ",", "exc_info", "=", "True", ")", "raise", "click", ".", "ClickException", "(", "\"Cannot load service args, are you sure server is running?\"", ")", "# get our service class instance", "service_module", "=", "get_service_module", "(", "service_path", ")", "service_obj", "=", "service_module", ".", "service_class", "(", "alert_types", "=", "service", ".", "alert_types", ",", "service_args", "=", "service_args", ")", "# prepare runner", "runner", "=", "myRunner", "(", "service_obj", ",", "pidfile", "=", "service_path", "+", "\".pid\"", ",", "stdout", "=", "open", "(", "os", ".", "path", ".", "join", "(", "service_path", ",", "\"stdout.log\"", ")", ",", "\"ab\"", ")", ",", "stderr", "=", "open", "(", "os", ".", "path", ".", "join", "(", "service_path", ",", "\"stderr.log\"", ")", ",", "\"ab\"", ")", ")", "click", ".", "secho", "(", "\"[*] Stopping {}\"", ".", "format", "(", "service", ".", "name", ")", ")", "try", ":", "runner", ".", "_stop", "(", ")", "except", "daemon", ".", "runner", ".", "DaemonRunnerStopFailureError", "as", "exc", ":", "logger", ".", "debug", "(", "str", "(", "exc", ")", ",", "exc_info", "=", "True", ")", "raise", "click", ".", "ClickException", "(", "\"Unable to stop service, are you sure it is running?\"", ")" ]
Stop a running service daemon.
[ "Stop", "a", "running", "service", "daemon", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/service/stop.py#L24-L57
13,564
Cymmetria/honeycomb
honeycomb/commands/service/logs.py
logs
def logs(ctx, services, num, follow): """Show logs of daemonized service.""" 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) tail_threads = [] for service in services: logpath = os.path.join(services_path, service, LOGS_DIR, STDOUTLOG) if os.path.exists(logpath): logger.debug("tailing %s", logpath) # TODO: Print log lines from multiple services sorted by timestamp t = threading.Thread(target=Tailer, kwargs={"name": service, "nlines": num, "filepath": logpath, "follow": follow}) t.daemon = True t.start() tail_threads.append(t) if tail_threads: while tail_threads[0].isAlive(): tail_threads[0].join(0.1)
python
def logs(ctx, services, num, follow): """Show logs of daemonized service.""" 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) tail_threads = [] for service in services: logpath = os.path.join(services_path, service, LOGS_DIR, STDOUTLOG) if os.path.exists(logpath): logger.debug("tailing %s", logpath) # TODO: Print log lines from multiple services sorted by timestamp t = threading.Thread(target=Tailer, kwargs={"name": service, "nlines": num, "filepath": logpath, "follow": follow}) t.daemon = True t.start() tail_threads.append(t) if tail_threads: while tail_threads[0].isAlive(): tail_threads[0].join(0.1)
[ "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", ")", "tail_threads", "=", "[", "]", "for", "service", "in", "services", ":", "logpath", "=", "os", ".", "path", ".", "join", "(", "services_path", ",", "service", ",", "LOGS_DIR", ",", "STDOUTLOG", ")", "if", "os", ".", "path", ".", "exists", "(", "logpath", ")", ":", "logger", ".", "debug", "(", "\"tailing %s\"", ",", "logpath", ")", "# TODO: Print log lines from multiple services sorted by timestamp", "t", "=", "threading", ".", "Thread", "(", "target", "=", "Tailer", ",", "kwargs", "=", "{", "\"name\"", ":", "service", ",", "\"nlines\"", ":", "num", ",", "\"filepath\"", ":", "logpath", ",", "\"follow\"", ":", "follow", "}", ")", "t", ".", "daemon", "=", "True", "t", ".", "start", "(", ")", "tail_threads", ".", "append", "(", "t", ")", "if", "tail_threads", ":", "while", "tail_threads", "[", "0", "]", ".", "isAlive", "(", ")", ":", "tail_threads", "[", "0", "]", ".", "join", "(", "0.1", ")" ]
Show logs of daemonized service.
[ "Show", "logs", "of", "daemonized", "service", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/service/logs.py#L22-L46
13,565
Cymmetria/honeycomb
honeycomb/integrationmanager/registration.py
get_integration_module
def get_integration_module(integration_path): """Add custom paths to sys and import integration module. :param integration_path: Path to integration folder """ # 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.path.join(integration_path, DEPS_DIR), # to import integration deps ] for path in paths: path = os.path.realpath(path) logger.debug("adding %s to path", path) sys.path.insert(0, path) # get our integration class instance integration_name = os.path.basename(integration_path) logger.debug("importing %s", ".".join([integration_name, INTEGRATION])) return importlib.import_module(".".join([integration_name, INTEGRATION]))
python
def get_integration_module(integration_path): """Add custom paths to sys and import integration module. :param integration_path: Path to integration folder """ # 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.path.join(integration_path, DEPS_DIR), # to import integration deps ] for path in paths: path = os.path.realpath(path) logger.debug("adding %s to path", path) sys.path.insert(0, path) # get our integration class instance integration_name = os.path.basename(integration_path) logger.debug("importing %s", ".".join([integration_name, INTEGRATION])) return importlib.import_module(".".join([integration_name, INTEGRATION]))
[ "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", ".", "path", ".", "join", "(", "integration_path", ",", "DEPS_DIR", ")", ",", "# to import integration deps", "]", "for", "path", "in", "paths", ":", "path", "=", "os", ".", "path", ".", "realpath", "(", "path", ")", "logger", ".", "debug", "(", "\"adding %s to path\"", ",", "path", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "path", ")", "# get our integration class instance", "integration_name", "=", "os", ".", "path", ".", "basename", "(", "integration_path", ")", "logger", ".", "debug", "(", "\"importing %s\"", ",", "\".\"", ".", "join", "(", "[", "integration_name", ",", "INTEGRATION", "]", ")", ")", "return", "importlib", ".", "import_module", "(", "\".\"", ".", "join", "(", "[", "integration_name", ",", "INTEGRATION", "]", ")", ")" ]
Add custom paths to sys and import integration module. :param integration_path: Path to integration folder
[ "Add", "custom", "paths", "to", "sys", "and", "import", "integration", "module", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/registration.py#L25-L45
13,566
Cymmetria/honeycomb
honeycomb/integrationmanager/registration.py
register_integration
def register_integration(package_folder): """Register a honeycomb integration. :param package_folder: Path to folder with integration to load :returns: Validated integration object :rtype: :func:`honeycomb.utils.defs.Integration` """ 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)) json_config_path = os.path.join(package_folder, CONFIG_FILE_NAME) if not os.path.exists(json_config_path): raise ConfigFileNotFound(json_config_path) with open(json_config_path, "r") as f: config_json = json.load(f) # Validate integration and alert config validate_config(config_json, defs.INTEGRATION_VALIDATE_CONFIG_FIELDS) validate_config_parameters(config_json, defs.INTEGRATION_PARAMETERS_ALLOWED_KEYS, defs.INTEGRATION_PARAMETERS_ALLOWED_TYPES) integration_type = _create_integration_object(config_json) return integration_type
python
def register_integration(package_folder): """Register a honeycomb integration. :param package_folder: Path to folder with integration to load :returns: Validated integration object :rtype: :func:`honeycomb.utils.defs.Integration` """ 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)) json_config_path = os.path.join(package_folder, CONFIG_FILE_NAME) if not os.path.exists(json_config_path): raise ConfigFileNotFound(json_config_path) with open(json_config_path, "r") as f: config_json = json.load(f) # Validate integration and alert config validate_config(config_json, defs.INTEGRATION_VALIDATE_CONFIG_FIELDS) validate_config_parameters(config_json, defs.INTEGRATION_PARAMETERS_ALLOWED_KEYS, defs.INTEGRATION_PARAMETERS_ALLOWED_TYPES) integration_type = _create_integration_object(config_json) return integration_type
[ "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", ")", ")", "json_config_path", "=", "os", ".", "path", ".", "join", "(", "package_folder", ",", "CONFIG_FILE_NAME", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "json_config_path", ")", ":", "raise", "ConfigFileNotFound", "(", "json_config_path", ")", "with", "open", "(", "json_config_path", ",", "\"r\"", ")", "as", "f", ":", "config_json", "=", "json", ".", "load", "(", "f", ")", "# Validate integration and alert config", "validate_config", "(", "config_json", ",", "defs", ".", "INTEGRATION_VALIDATE_CONFIG_FIELDS", ")", "validate_config_parameters", "(", "config_json", ",", "defs", ".", "INTEGRATION_PARAMETERS_ALLOWED_KEYS", ",", "defs", ".", "INTEGRATION_PARAMETERS_ALLOWED_TYPES", ")", "integration_type", "=", "_create_integration_object", "(", "config_json", ")", "return", "integration_type" ]
Register a honeycomb integration. :param package_folder: Path to folder with integration to load :returns: Validated integration object :rtype: :func:`honeycomb.utils.defs.Integration`
[ "Register", "a", "honeycomb", "integration", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/registration.py#L48-L75
13,567
Cymmetria/honeycomb
honeycomb/commands/integration/list.py
list
def list(ctx, remote): """List integrations.""" 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 = os.path.join(home, INTEGRATIONS) plugin_type = "integration" def get_integration_details(integration_name): logger.debug("loading {}".format(integration_name)) integration = register_integration(os.path.join(integrations_path, integration_name)) supported_event_types = integration.supported_event_types if not supported_event_types: supported_event_types = "All" return "{:s} ({:s}) [Supported event types: {}]".format(integration.name, integration.description, supported_event_types) installed_integrations = list_local_plugins(plugin_type, integrations_path, get_integration_details) if remote: list_remote_plugins(installed_integrations, plugin_type) else: click.secho("\n[*] Try running `honeycomb integrations list -r` " "to see integrations available from our repository")
python
def list(ctx, remote): """List integrations.""" 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 = os.path.join(home, INTEGRATIONS) plugin_type = "integration" def get_integration_details(integration_name): logger.debug("loading {}".format(integration_name)) integration = register_integration(os.path.join(integrations_path, integration_name)) supported_event_types = integration.supported_event_types if not supported_event_types: supported_event_types = "All" return "{:s} ({:s}) [Supported event types: {}]".format(integration.name, integration.description, supported_event_types) installed_integrations = list_local_plugins(plugin_type, integrations_path, get_integration_details) if remote: list_remote_plugins(installed_integrations, plugin_type) else: click.secho("\n[*] Try running `honeycomb integrations list -r` " "to see integrations available from our repository")
[ "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", "=", "os", ".", "path", ".", "join", "(", "home", ",", "INTEGRATIONS", ")", "plugin_type", "=", "\"integration\"", "def", "get_integration_details", "(", "integration_name", ")", ":", "logger", ".", "debug", "(", "\"loading {}\"", ".", "format", "(", "integration_name", ")", ")", "integration", "=", "register_integration", "(", "os", ".", "path", ".", "join", "(", "integrations_path", ",", "integration_name", ")", ")", "supported_event_types", "=", "integration", ".", "supported_event_types", "if", "not", "supported_event_types", ":", "supported_event_types", "=", "\"All\"", "return", "\"{:s} ({:s}) [Supported event types: {}]\"", ".", "format", "(", "integration", ".", "name", ",", "integration", ".", "description", ",", "supported_event_types", ")", "installed_integrations", "=", "list_local_plugins", "(", "plugin_type", ",", "integrations_path", ",", "get_integration_details", ")", "if", "remote", ":", "list_remote_plugins", "(", "installed_integrations", ",", "plugin_type", ")", "else", ":", "click", ".", "secho", "(", "\"\\n[*] Try running `honeycomb integrations list -r` \"", "\"to see integrations available from our repository\"", ")" ]
List integrations.
[ "List", "integrations", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/integration/list.py#L20-L46
13,568
Cymmetria/honeycomb
honeycomb/commands/service/run.py
run
def run(ctx, service, args, show_args, daemon, editable, integration): """Load and run a specific service.""" 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 command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) logger.debug("loading {} ({})".format(service, service_path)) service = register_service(service_path) if show_args: return plugin_utils.print_plugin_args(service_path) # get our service class instance service_module = get_service_module(service_path) service_args = plugin_utils.parse_plugin_args(args, config_utils.get_config_parameters(service_path)) service_obj = service_module.service_class(alert_types=service.alert_types, service_args=service_args) if not os.path.exists(service_log_path): os.mkdir(service_log_path) # prepare runner if daemon: runner = myRunner(service_obj, pidfile=service_path + ".pid", stdout=open(os.path.join(service_log_path, STDOUTLOG), "ab"), stderr=open(os.path.join(service_log_path, STDERRLOG), "ab")) files_preserve = [] for handler in logging.getLogger().handlers: if hasattr(handler, "stream"): if hasattr(handler.stream, "fileno"): files_preserve.append(handler.stream.fileno()) if hasattr(handler, "socket"): files_preserve.append(handler.socket.fileno()) runner.daemon_context.files_preserve = files_preserve runner.daemon_context.signal_map.update({ signal.SIGTERM: service_obj._on_server_shutdown, signal.SIGINT: service_obj._on_server_shutdown, }) logger.debug("daemon_context", extra={"daemon_context": vars(runner.daemon_context)}) for integration_name in integration: integration_path = plugin_utils.get_plugin_path(home, INTEGRATIONS, integration_name, editable) configure_integration(integration_path) click.secho("[+] Launching {} {}".format(service.name, "in daemon mode" if daemon else "")) try: # save service_args for external reference (see test) with open(os.path.join(service_path, ARGS_JSON), "w") as f: f.write(json.dumps(service_args)) runner._start() if daemon else service_obj.run() except KeyboardInterrupt: service_obj._on_server_shutdown() click.secho("[*] {} has stopped".format(service.name))
python
def run(ctx, service, args, show_args, daemon, editable, integration): """Load and run a specific service.""" 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 command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) logger.debug("loading {} ({})".format(service, service_path)) service = register_service(service_path) if show_args: return plugin_utils.print_plugin_args(service_path) # get our service class instance service_module = get_service_module(service_path) service_args = plugin_utils.parse_plugin_args(args, config_utils.get_config_parameters(service_path)) service_obj = service_module.service_class(alert_types=service.alert_types, service_args=service_args) if not os.path.exists(service_log_path): os.mkdir(service_log_path) # prepare runner if daemon: runner = myRunner(service_obj, pidfile=service_path + ".pid", stdout=open(os.path.join(service_log_path, STDOUTLOG), "ab"), stderr=open(os.path.join(service_log_path, STDERRLOG), "ab")) files_preserve = [] for handler in logging.getLogger().handlers: if hasattr(handler, "stream"): if hasattr(handler.stream, "fileno"): files_preserve.append(handler.stream.fileno()) if hasattr(handler, "socket"): files_preserve.append(handler.socket.fileno()) runner.daemon_context.files_preserve = files_preserve runner.daemon_context.signal_map.update({ signal.SIGTERM: service_obj._on_server_shutdown, signal.SIGINT: service_obj._on_server_shutdown, }) logger.debug("daemon_context", extra={"daemon_context": vars(runner.daemon_context)}) for integration_name in integration: integration_path = plugin_utils.get_plugin_path(home, INTEGRATIONS, integration_name, editable) configure_integration(integration_path) click.secho("[+] Launching {} {}".format(service.name, "in daemon mode" if daemon else "")) try: # save service_args for external reference (see test) with open(os.path.join(service_path, ARGS_JSON), "w") as f: f.write(json.dumps(service_args)) runner._start() if daemon else service_obj.run() except KeyboardInterrupt: service_obj._on_server_shutdown() click.secho("[*] {} has stopped".format(service.name))
[ "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 command %s (%s)\"", ",", "ctx", ".", "command", ".", "name", ",", "ctx", ".", "params", ",", "extra", "=", "{", "\"command\"", ":", "ctx", ".", "command", ".", "name", ",", "\"params\"", ":", "ctx", ".", "params", "}", ")", "logger", ".", "debug", "(", "\"loading {} ({})\"", ".", "format", "(", "service", ",", "service_path", ")", ")", "service", "=", "register_service", "(", "service_path", ")", "if", "show_args", ":", "return", "plugin_utils", ".", "print_plugin_args", "(", "service_path", ")", "# get our service class instance", "service_module", "=", "get_service_module", "(", "service_path", ")", "service_args", "=", "plugin_utils", ".", "parse_plugin_args", "(", "args", ",", "config_utils", ".", "get_config_parameters", "(", "service_path", ")", ")", "service_obj", "=", "service_module", ".", "service_class", "(", "alert_types", "=", "service", ".", "alert_types", ",", "service_args", "=", "service_args", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "service_log_path", ")", ":", "os", ".", "mkdir", "(", "service_log_path", ")", "# prepare runner", "if", "daemon", ":", "runner", "=", "myRunner", "(", "service_obj", ",", "pidfile", "=", "service_path", "+", "\".pid\"", ",", "stdout", "=", "open", "(", "os", ".", "path", ".", "join", "(", "service_log_path", ",", "STDOUTLOG", ")", ",", "\"ab\"", ")", ",", "stderr", "=", "open", "(", "os", ".", "path", ".", "join", "(", "service_log_path", ",", "STDERRLOG", ")", ",", "\"ab\"", ")", ")", "files_preserve", "=", "[", "]", "for", "handler", "in", "logging", ".", "getLogger", "(", ")", ".", "handlers", ":", "if", "hasattr", "(", "handler", ",", "\"stream\"", ")", ":", "if", "hasattr", "(", "handler", ".", "stream", ",", "\"fileno\"", ")", ":", "files_preserve", ".", "append", "(", "handler", ".", "stream", ".", "fileno", "(", ")", ")", "if", "hasattr", "(", "handler", ",", "\"socket\"", ")", ":", "files_preserve", ".", "append", "(", "handler", ".", "socket", ".", "fileno", "(", ")", ")", "runner", ".", "daemon_context", ".", "files_preserve", "=", "files_preserve", "runner", ".", "daemon_context", ".", "signal_map", ".", "update", "(", "{", "signal", ".", "SIGTERM", ":", "service_obj", ".", "_on_server_shutdown", ",", "signal", ".", "SIGINT", ":", "service_obj", ".", "_on_server_shutdown", ",", "}", ")", "logger", ".", "debug", "(", "\"daemon_context\"", ",", "extra", "=", "{", "\"daemon_context\"", ":", "vars", "(", "runner", ".", "daemon_context", ")", "}", ")", "for", "integration_name", "in", "integration", ":", "integration_path", "=", "plugin_utils", ".", "get_plugin_path", "(", "home", ",", "INTEGRATIONS", ",", "integration_name", ",", "editable", ")", "configure_integration", "(", "integration_path", ")", "click", ".", "secho", "(", "\"[+] Launching {} {}\"", ".", "format", "(", "service", ".", "name", ",", "\"in daemon mode\"", "if", "daemon", "else", "\"\"", ")", ")", "try", ":", "# save service_args for external reference (see test)", "with", "open", "(", "os", ".", "path", ".", "join", "(", "service_path", ",", "ARGS_JSON", ")", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "service_args", ")", ")", "runner", ".", "_start", "(", ")", "if", "daemon", "else", "service_obj", ".", "run", "(", ")", "except", "KeyboardInterrupt", ":", "service_obj", ".", "_on_server_shutdown", "(", ")", "click", ".", "secho", "(", "\"[*] {} has stopped\"", ".", "format", "(", "service", ".", "name", ")", ")" ]
Load and run a specific service.
[ "Load", "and", "run", "a", "specific", "service", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/service/run.py#L30-L88
13,569
Cymmetria/honeycomb
honeycomb/servicemanager/base_service.py
DockerService.read_lines
def read_lines(self, file_path, empty_lines=False, signal_ready=True): """Fetch lines from file. In case the file handler changes (logrotate), reopen the file. :param file_path: Path to file :param empty_lines: Return empty lines :param signal_ready: Report signal ready on start """ 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_alive(): line = six.text_type(file_handler.readline(), "utf-8") if line: yield line continue elif empty_lines: yield line time.sleep(0.1) if file_id != self._get_file_id(os.stat(file_path)) and os.path.isfile(file_path): file_handler, file_id = self._get_file(file_path)
python
def read_lines(self, file_path, empty_lines=False, signal_ready=True): """Fetch lines from file. In case the file handler changes (logrotate), reopen the file. :param file_path: Path to file :param empty_lines: Return empty lines :param signal_ready: Report signal ready on start """ 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_alive(): line = six.text_type(file_handler.readline(), "utf-8") if line: yield line continue elif empty_lines: yield line time.sleep(0.1) if file_id != self._get_file_id(os.stat(file_path)) and os.path.isfile(file_path): file_handler, file_id = self._get_file(file_path)
[ "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_alive", "(", ")", ":", "line", "=", "six", ".", "text_type", "(", "file_handler", ".", "readline", "(", ")", ",", "\"utf-8\"", ")", "if", "line", ":", "yield", "line", "continue", "elif", "empty_lines", ":", "yield", "line", "time", ".", "sleep", "(", "0.1", ")", "if", "file_id", "!=", "self", ".", "_get_file_id", "(", "os", ".", "stat", "(", "file_path", ")", ")", "and", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "file_handler", ",", "file_id", "=", "self", ".", "_get_file", "(", "file_path", ")" ]
Fetch lines from file. In case the file handler changes (logrotate), reopen the file. :param file_path: Path to file :param empty_lines: Return empty lines :param signal_ready: Report signal ready on start
[ "Fetch", "lines", "from", "file", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/base_service.py#L171-L197
13,570
Cymmetria/honeycomb
honeycomb/servicemanager/base_service.py
DockerService.on_server_start
def on_server_start(self): """Service run loop function. Run the desired docker container with parameters and start parsing the monitored file for alerts. """ 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 = self.parse_line(log_line) if alert_dict: self.add_alert_to_queue(alert_dict) except Exception: self.logger.exception(None)
python
def on_server_start(self): """Service run loop function. Run the desired docker container with parameters and start parsing the monitored file for alerts. """ 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 = self.parse_line(log_line) if alert_dict: self.add_alert_to_queue(alert_dict) except Exception: self.logger.exception(None)
[ "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", "=", "self", ".", "parse_line", "(", "log_line", ")", "if", "alert_dict", ":", "self", ".", "add_alert_to_queue", "(", "alert_dict", ")", "except", "Exception", ":", "self", ".", "logger", ".", "exception", "(", "None", ")" ]
Service run loop function. Run the desired docker container with parameters and start parsing the monitored file for alerts.
[ "Service", "run", "loop", "function", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/base_service.py#L212-L226
13,571
Cymmetria/honeycomb
honeycomb/servicemanager/base_service.py
DockerService.on_server_shutdown
def on_server_shutdown(self): """Stop the container before shutting down.""" if not self._container: return self._container.stop() self._container.remove(v=True, force=True)
python
def on_server_shutdown(self): """Stop the container before shutting down.""" if not self._container: return self._container.stop() self._container.remove(v=True, force=True)
[ "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.
[ "Stop", "the", "container", "before", "shutting", "down", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/base_service.py#L228-L233
13,572
Cymmetria/honeycomb
honeycomb/commands/integration/uninstall.py
uninstall
def uninstall(ctx, yes, integrations): """Uninstall a integration.""" 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: integration_path = plugin_utils.get_plugin_path(home, INTEGRATIONS, integration) plugin_utils.uninstall_plugin(integration_path, yes)
python
def uninstall(ctx, yes, integrations): """Uninstall a integration.""" 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: integration_path = plugin_utils.get_plugin_path(home, INTEGRATIONS, integration) plugin_utils.uninstall_plugin(integration_path, yes)
[ "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", ":", "integration_path", "=", "plugin_utils", ".", "get_plugin_path", "(", "home", ",", "INTEGRATIONS", ",", "integration", ")", "plugin_utils", ".", "uninstall_plugin", "(", "integration_path", ",", "yes", ")" ]
Uninstall a integration.
[ "Uninstall", "a", "integration", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/integration/uninstall.py#L18-L27
13,573
Cymmetria/honeycomb
honeycomb/commands/service/install.py
install
def install(ctx, services, delete_after_install=False): """Install a honeypot service from the online library, local path or zipfile.""" 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) installed_all_plugins = True for service in services: try: plugin_utils.install_plugin(service, SERVICE, services_path, register_service) except exceptions.PluginAlreadyInstalled as exc: click.echo(exc) installed_all_plugins = False if not installed_all_plugins: raise ctx.exit(errno.EEXIST)
python
def install(ctx, services, delete_after_install=False): """Install a honeypot service from the online library, local path or zipfile.""" 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) installed_all_plugins = True for service in services: try: plugin_utils.install_plugin(service, SERVICE, services_path, register_service) except exceptions.PluginAlreadyInstalled as exc: click.echo(exc) installed_all_plugins = False if not installed_all_plugins: raise ctx.exit(errno.EEXIST)
[ "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", "(", "home", ",", "SERVICES", ")", "installed_all_plugins", "=", "True", "for", "service", "in", "services", ":", "try", ":", "plugin_utils", ".", "install_plugin", "(", "service", ",", "SERVICE", ",", "services_path", ",", "register_service", ")", "except", "exceptions", ".", "PluginAlreadyInstalled", "as", "exc", ":", "click", ".", "echo", "(", "exc", ")", "installed_all_plugins", "=", "False", "if", "not", "installed_all_plugins", ":", "raise", "ctx", ".", "exit", "(", "errno", ".", "EEXIST", ")" ]
Install a honeypot service from the online library, local path or zipfile.
[ "Install", "a", "honeypot", "service", "from", "the", "online", "library", "local", "path", "or", "zipfile", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/service/install.py#L21-L38
13,574
Cymmetria/honeycomb
honeycomb/commands/service/uninstall.py
uninstall
def uninstall(ctx, yes, services): """Uninstall a service.""" 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 = plugin_utils.get_plugin_path(home, SERVICES, service) plugin_utils.uninstall_plugin(service_path, yes)
python
def uninstall(ctx, yes, services): """Uninstall a service.""" 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 = plugin_utils.get_plugin_path(home, SERVICES, service) plugin_utils.uninstall_plugin(service_path, yes)
[ "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", "=", "plugin_utils", ".", "get_plugin_path", "(", "home", ",", "SERVICES", ",", "service", ")", "plugin_utils", ".", "uninstall_plugin", "(", "service_path", ",", "yes", ")" ]
Uninstall a service.
[ "Uninstall", "a", "service", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/service/uninstall.py#L18-L27
13,575
Cymmetria/honeycomb
honeycomb/servicemanager/registration.py
get_service_module
def get_service_module(service_path): """Add custom paths to sys and import service module. :param service_path: Path to service folder """ # 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 os.path.realpath(os.path.join(service_path)), # service's folder for local imports os.path.realpath(os.path.join(service_path, DEPS_DIR)), # deps dir ] for path in paths: path = os.path.realpath(path) logger.debug("adding %s to path", path) sys.path.insert(0, path) # get our service class instance service_name = os.path.basename(service_path) module = ".".join([service_name, service_name + "_service"]) logger.debug("importing %s", module) return importlib.import_module(module)
python
def get_service_module(service_path): """Add custom paths to sys and import service module. :param service_path: Path to service folder """ # 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 os.path.realpath(os.path.join(service_path)), # service's folder for local imports os.path.realpath(os.path.join(service_path, DEPS_DIR)), # deps dir ] for path in paths: path = os.path.realpath(path) logger.debug("adding %s to path", path) sys.path.insert(0, path) # get our service class instance service_name = os.path.basename(service_path) module = ".".join([service_name, service_name + "_service"]) logger.debug("importing %s", module) return importlib.import_module(module)
[ "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", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "service_path", ")", ")", ",", "# service's folder for local imports", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "service_path", ",", "DEPS_DIR", ")", ")", ",", "# deps dir", "]", "for", "path", "in", "paths", ":", "path", "=", "os", ".", "path", ".", "realpath", "(", "path", ")", "logger", ".", "debug", "(", "\"adding %s to path\"", ",", "path", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "path", ")", "# get our service class instance", "service_name", "=", "os", ".", "path", ".", "basename", "(", "service_path", ")", "module", "=", "\".\"", ".", "join", "(", "[", "service_name", ",", "service_name", "+", "\"_service\"", "]", ")", "logger", ".", "debug", "(", "\"importing %s\"", ",", "module", ")", "return", "importlib", ".", "import_module", "(", "module", ")" ]
Add custom paths to sys and import service module. :param service_path: Path to service folder
[ "Add", "custom", "paths", "to", "sys", "and", "import", "service", "module", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/registration.py#L26-L48
13,576
Cymmetria/honeycomb
honeycomb/servicemanager/registration.py
register_service
def register_service(package_folder): """Register a honeycomb service. :param package_folder: Path to folder with service to load :returns: Validated service object :rtype: :func:`honeycomb.utils.defs.ServiceType` """ 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_config_path = os.path.join(package_folder, CONFIG_FILE_NAME) if not os.path.exists(json_config_path): raise ConfigFileNotFound(json_config_path) with open(json_config_path, "r") as f: config_json = json.load(f) # Validate service and alert config config_utils.validate_config(config_json, defs.SERVICE_ALERT_VALIDATE_FIELDS) config_utils.validate_config(config_json.get(defs.SERVICE_CONFIG_SECTION_KEY, {}), defs.SERVICE_CONFIG_VALIDATE_FIELDS) _validate_supported_platform(config_json) _validate_alert_configs(config_json) config_utils.validate_config_parameters(config_json, defs.SERVICE_ALLOWED_PARAMTER_KEYS, defs.SERVICE_ALLOWED_PARAMTER_TYPES) service_type = _create_service_object(config_json) service_type.alert_types = _create_alert_types(config_json, service_type) return service_type
python
def register_service(package_folder): """Register a honeycomb service. :param package_folder: Path to folder with service to load :returns: Validated service object :rtype: :func:`honeycomb.utils.defs.ServiceType` """ 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_config_path = os.path.join(package_folder, CONFIG_FILE_NAME) if not os.path.exists(json_config_path): raise ConfigFileNotFound(json_config_path) with open(json_config_path, "r") as f: config_json = json.load(f) # Validate service and alert config config_utils.validate_config(config_json, defs.SERVICE_ALERT_VALIDATE_FIELDS) config_utils.validate_config(config_json.get(defs.SERVICE_CONFIG_SECTION_KEY, {}), defs.SERVICE_CONFIG_VALIDATE_FIELDS) _validate_supported_platform(config_json) _validate_alert_configs(config_json) config_utils.validate_config_parameters(config_json, defs.SERVICE_ALLOWED_PARAMTER_KEYS, defs.SERVICE_ALLOWED_PARAMTER_TYPES) service_type = _create_service_object(config_json) service_type.alert_types = _create_alert_types(config_json, service_type) return service_type
[ "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_config_path", "=", "os", ".", "path", ".", "join", "(", "package_folder", ",", "CONFIG_FILE_NAME", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "json_config_path", ")", ":", "raise", "ConfigFileNotFound", "(", "json_config_path", ")", "with", "open", "(", "json_config_path", ",", "\"r\"", ")", "as", "f", ":", "config_json", "=", "json", ".", "load", "(", "f", ")", "# Validate service and alert config", "config_utils", ".", "validate_config", "(", "config_json", ",", "defs", ".", "SERVICE_ALERT_VALIDATE_FIELDS", ")", "config_utils", ".", "validate_config", "(", "config_json", ".", "get", "(", "defs", ".", "SERVICE_CONFIG_SECTION_KEY", ",", "{", "}", ")", ",", "defs", ".", "SERVICE_CONFIG_VALIDATE_FIELDS", ")", "_validate_supported_platform", "(", "config_json", ")", "_validate_alert_configs", "(", "config_json", ")", "config_utils", ".", "validate_config_parameters", "(", "config_json", ",", "defs", ".", "SERVICE_ALLOWED_PARAMTER_KEYS", ",", "defs", ".", "SERVICE_ALLOWED_PARAMTER_TYPES", ")", "service_type", "=", "_create_service_object", "(", "config_json", ")", "service_type", ".", "alert_types", "=", "_create_alert_types", "(", "config_json", ",", "service_type", ")", "return", "service_type" ]
Register a honeycomb service. :param package_folder: Path to folder with service to load :returns: Validated service object :rtype: :func:`honeycomb.utils.defs.ServiceType`
[ "Register", "a", "honeycomb", "service", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/registration.py#L51-L84
13,577
Cymmetria/honeycomb
honeycomb/commands/integration/install.py
install
def install(ctx, integrations, delete_after_install=False): """Install a honeycomb integration from the online library, local path or zipfile.""" logger.debug("running command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) home = ctx.obj["HOME"] integrations_path = os.path.join(home, INTEGRATIONS) installed_all_plugins = True for integration in integrations: try: plugin_utils.install_plugin(integration, INTEGRATION, integrations_path, register_integration) except exceptions.PluginAlreadyInstalled as exc: click.echo(exc) installed_all_plugins = False if not installed_all_plugins: raise ctx.exit(errno.EEXIST)
python
def install(ctx, integrations, delete_after_install=False): """Install a honeycomb integration from the online library, local path or zipfile.""" logger.debug("running command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) home = ctx.obj["HOME"] integrations_path = os.path.join(home, INTEGRATIONS) installed_all_plugins = True for integration in integrations: try: plugin_utils.install_plugin(integration, INTEGRATION, integrations_path, register_integration) except exceptions.PluginAlreadyInstalled as exc: click.echo(exc) installed_all_plugins = False if not installed_all_plugins: raise ctx.exit(errno.EEXIST)
[ "def", "install", "(", "ctx", ",", "integrations", ",", "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\"", "]", "integrations_path", "=", "os", ".", "path", ".", "join", "(", "home", ",", "INTEGRATIONS", ")", "installed_all_plugins", "=", "True", "for", "integration", "in", "integrations", ":", "try", ":", "plugin_utils", ".", "install_plugin", "(", "integration", ",", "INTEGRATION", ",", "integrations_path", ",", "register_integration", ")", "except", "exceptions", ".", "PluginAlreadyInstalled", "as", "exc", ":", "click", ".", "echo", "(", "exc", ")", "installed_all_plugins", "=", "False", "if", "not", "installed_all_plugins", ":", "raise", "ctx", ".", "exit", "(", "errno", ".", "EEXIST", ")" ]
Install a honeycomb integration from the online library, local path or zipfile.
[ "Install", "a", "honeycomb", "integration", "from", "the", "online", "library", "local", "path", "or", "zipfile", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/integration/install.py#L21-L38
13,578
Cymmetria/honeycomb
honeycomb/commands/integration/configure.py
configure
def configure(ctx, integration, args, show_args, editable): """Configure an integration with default parameters. You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required. """ home = ctx.obj["HOME"] integration_path = plugin_utils.get_plugin_path(home, defs.INTEGRATIONS, integration, editable) logger.debug("running command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) logger.debug("loading {} ({})".format(integration, integration_path)) integration = register_integration(integration_path) if show_args: return plugin_utils.print_plugin_args(integration_path) # get our integration class instance integration_args = plugin_utils.parse_plugin_args(args, config_utils.get_config_parameters(integration_path)) args_file = os.path.join(integration_path, defs.ARGS_JSON) with open(args_file, "w") as f: data = json.dumps(integration_args) logger.debug("writing %s to %s", data, args_file) f.write(json.dumps(integration_args)) click.secho("[*] {0} has been configured, make sure to test it with `honeycomb integration test {0}`" .format(integration.name))
python
def configure(ctx, integration, args, show_args, editable): """Configure an integration with default parameters. You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required. """ home = ctx.obj["HOME"] integration_path = plugin_utils.get_plugin_path(home, defs.INTEGRATIONS, integration, editable) logger.debug("running command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) logger.debug("loading {} ({})".format(integration, integration_path)) integration = register_integration(integration_path) if show_args: return plugin_utils.print_plugin_args(integration_path) # get our integration class instance integration_args = plugin_utils.parse_plugin_args(args, config_utils.get_config_parameters(integration_path)) args_file = os.path.join(integration_path, defs.ARGS_JSON) with open(args_file, "w") as f: data = json.dumps(integration_args) logger.debug("writing %s to %s", data, args_file) f.write(json.dumps(integration_args)) click.secho("[*] {0} has been configured, make sure to test it with `honeycomb integration test {0}`" .format(integration.name))
[ "def", "configure", "(", "ctx", ",", "integration", ",", "args", ",", "show_args", ",", "editable", ")", ":", "home", "=", "ctx", ".", "obj", "[", "\"HOME\"", "]", "integration_path", "=", "plugin_utils", ".", "get_plugin_path", "(", "home", ",", "defs", ".", "INTEGRATIONS", ",", "integration", ",", "editable", ")", "logger", ".", "debug", "(", "\"running command %s (%s)\"", ",", "ctx", ".", "command", ".", "name", ",", "ctx", ".", "params", ",", "extra", "=", "{", "\"command\"", ":", "ctx", ".", "command", ".", "name", ",", "\"params\"", ":", "ctx", ".", "params", "}", ")", "logger", ".", "debug", "(", "\"loading {} ({})\"", ".", "format", "(", "integration", ",", "integration_path", ")", ")", "integration", "=", "register_integration", "(", "integration_path", ")", "if", "show_args", ":", "return", "plugin_utils", ".", "print_plugin_args", "(", "integration_path", ")", "# get our integration class instance", "integration_args", "=", "plugin_utils", ".", "parse_plugin_args", "(", "args", ",", "config_utils", ".", "get_config_parameters", "(", "integration_path", ")", ")", "args_file", "=", "os", ".", "path", ".", "join", "(", "integration_path", ",", "defs", ".", "ARGS_JSON", ")", "with", "open", "(", "args_file", ",", "\"w\"", ")", "as", "f", ":", "data", "=", "json", ".", "dumps", "(", "integration_args", ")", "logger", ".", "debug", "(", "\"writing %s to %s\"", ",", "data", ",", "args_file", ")", "f", ".", "write", "(", "json", ".", "dumps", "(", "integration_args", ")", ")", "click", ".", "secho", "(", "\"[*] {0} has been configured, make sure to test it with `honeycomb integration test {0}`\"", ".", "format", "(", "integration", ".", "name", ")", ")" ]
Configure an integration with default parameters. You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required.
[ "Configure", "an", "integration", "with", "default", "parameters", "." ]
33ea91b5cf675000e4e85dd02efe580ea6e95c86
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/integration/configure.py#L24-L51
13,579
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.get_match_history
def get_match_history(self, account_id=None, **kwargs): """Returns a dictionary containing a list of the most recent Dota matches :param account_id: (int, optional) :param hero_id: (int, optional) :param game_mode: (int, optional) see ``ref/modes.json`` :param skill: (int, optional) see ``ref/skill.json`` :param min_players: (int, optional) only return matches with minimum amount of players :param league_id: (int, optional) for ids use ``get_league_listing()`` :param start_at_match_id: (int, optional) start at matches equal to or older than this match id :param matches_requested: (int, optional) defaults to ``100`` :param tournament_games_only: (str, optional) limit results to tournament matches only :return: dictionary of matches, see :doc:`responses </responses>` """ if 'account_id' not in kwargs: kwargs['account_id'] = account_id url = self.__build_url(urls.GET_MATCH_HISTORY, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
python
def get_match_history(self, account_id=None, **kwargs): """Returns a dictionary containing a list of the most recent Dota matches :param account_id: (int, optional) :param hero_id: (int, optional) :param game_mode: (int, optional) see ``ref/modes.json`` :param skill: (int, optional) see ``ref/skill.json`` :param min_players: (int, optional) only return matches with minimum amount of players :param league_id: (int, optional) for ids use ``get_league_listing()`` :param start_at_match_id: (int, optional) start at matches equal to or older than this match id :param matches_requested: (int, optional) defaults to ``100`` :param tournament_games_only: (str, optional) limit results to tournament matches only :return: dictionary of matches, see :doc:`responses </responses>` """ if 'account_id' not in kwargs: kwargs['account_id'] = account_id url = self.__build_url(urls.GET_MATCH_HISTORY, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
[ "def", "get_match_history", "(", "self", ",", "account_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'account_id'", "not", "in", "kwargs", ":", "kwargs", "[", "'account_id'", "]", "=", "account_id", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_MATCH_HISTORY", ",", "*", "*", "kwargs", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Returns a dictionary containing a list of the most recent Dota matches :param account_id: (int, optional) :param hero_id: (int, optional) :param game_mode: (int, optional) see ``ref/modes.json`` :param skill: (int, optional) see ``ref/skill.json`` :param min_players: (int, optional) only return matches with minimum amount of players :param league_id: (int, optional) for ids use ``get_league_listing()`` :param start_at_match_id: (int, optional) start at matches equal to or older than this match id :param matches_requested: (int, optional) defaults to ``100`` :param tournament_games_only: (str, optional) limit results to tournament matches only :return: dictionary of matches, see :doc:`responses </responses>`
[ "Returns", "a", "dictionary", "containing", "a", "list", "of", "the", "most", "recent", "Dota", "matches" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L66-L90
13,580
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.get_match_history_by_seq_num
def get_match_history_by_seq_num(self, start_at_match_seq_num=None, **kwargs): """Returns a dictionary containing a list of Dota matches in the order they were recorded :param start_at_match_seq_num: (int, optional) start at matches equal to or older than this match id :param matches_requested: (int, optional) defaults to ``100`` :return: dictionary of matches, see :doc:`responses </responses>` """ if 'start_at_match_seq_num' not in kwargs: kwargs['start_at_match_seq_num'] = start_at_match_seq_num url = self.__build_url(urls.GET_MATCH_HISTORY_BY_SEQ_NUM, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
python
def get_match_history_by_seq_num(self, start_at_match_seq_num=None, **kwargs): """Returns a dictionary containing a list of Dota matches in the order they were recorded :param start_at_match_seq_num: (int, optional) start at matches equal to or older than this match id :param matches_requested: (int, optional) defaults to ``100`` :return: dictionary of matches, see :doc:`responses </responses>` """ if 'start_at_match_seq_num' not in kwargs: kwargs['start_at_match_seq_num'] = start_at_match_seq_num url = self.__build_url(urls.GET_MATCH_HISTORY_BY_SEQ_NUM, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
[ "def", "get_match_history_by_seq_num", "(", "self", ",", "start_at_match_seq_num", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'start_at_match_seq_num'", "not", "in", "kwargs", ":", "kwargs", "[", "'start_at_match_seq_num'", "]", "=", "start_at_match_seq_num", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_MATCH_HISTORY_BY_SEQ_NUM", ",", "*", "*", "kwargs", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Returns a dictionary containing a list of Dota matches in the order they were recorded :param start_at_match_seq_num: (int, optional) start at matches equal to or older than this match id :param matches_requested: (int, optional) defaults to ``100`` :return: dictionary of matches, see :doc:`responses </responses>`
[ "Returns", "a", "dictionary", "containing", "a", "list", "of", "Dota", "matches", "in", "the", "order", "they", "were", "recorded" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L92-L107
13,581
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.get_match_details
def get_match_details(self, match_id=None, **kwargs): """Returns a dictionary containing the details for a Dota 2 match :param match_id: (int, optional) :return: dictionary of matches, see :doc:`responses </responses>` """ if 'match_id' not in kwargs: kwargs['match_id'] = match_id url = self.__build_url(urls.GET_MATCH_DETAILS, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
python
def get_match_details(self, match_id=None, **kwargs): """Returns a dictionary containing the details for a Dota 2 match :param match_id: (int, optional) :return: dictionary of matches, see :doc:`responses </responses>` """ if 'match_id' not in kwargs: kwargs['match_id'] = match_id url = self.__build_url(urls.GET_MATCH_DETAILS, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
[ "def", "get_match_details", "(", "self", ",", "match_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'match_id'", "not", "in", "kwargs", ":", "kwargs", "[", "'match_id'", "]", "=", "match_id", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_MATCH_DETAILS", ",", "*", "*", "kwargs", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Returns a dictionary containing the details for a Dota 2 match :param match_id: (int, optional) :return: dictionary of matches, see :doc:`responses </responses>`
[ "Returns", "a", "dictionary", "containing", "the", "details", "for", "a", "Dota", "2", "match" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L109-L122
13,582
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.get_league_listing
def get_league_listing(self): """Returns a dictionary containing a list of all ticketed leagues :return: dictionary of ticketed leagues, see :doc:`responses </responses>` """ url = self.__build_url(urls.GET_LEAGUE_LISTING) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
python
def get_league_listing(self): """Returns a dictionary containing a list of all ticketed leagues :return: dictionary of ticketed leagues, see :doc:`responses </responses>` """ url = self.__build_url(urls.GET_LEAGUE_LISTING) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
[ "def", "get_league_listing", "(", "self", ")", ":", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_LEAGUE_LISTING", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Returns a dictionary containing a list of all ticketed leagues :return: dictionary of ticketed leagues, see :doc:`responses </responses>`
[ "Returns", "a", "dictionary", "containing", "a", "list", "of", "all", "ticketed", "leagues" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L124-L134
13,583
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.get_live_league_games
def get_live_league_games(self): """Returns a dictionary containing a list of ticked games in progress :return: dictionary of live games, see :doc:`responses </responses>` """ url = self.__build_url(urls.GET_LIVE_LEAGUE_GAMES) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
python
def get_live_league_games(self): """Returns a dictionary containing a list of ticked games in progress :return: dictionary of live games, see :doc:`responses </responses>` """ url = self.__build_url(urls.GET_LIVE_LEAGUE_GAMES) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
[ "def", "get_live_league_games", "(", "self", ")", ":", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_LIVE_LEAGUE_GAMES", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Returns a dictionary containing a list of ticked games in progress :return: dictionary of live games, see :doc:`responses </responses>`
[ "Returns", "a", "dictionary", "containing", "a", "list", "of", "ticked", "games", "in", "progress" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L136-L146
13,584
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.get_team_info_by_team_id
def get_team_info_by_team_id(self, start_at_team_id=None, **kwargs): """Returns a dictionary containing a in-game teams :param start_at_team_id: (int, optional) :param teams_requested: (int, optional) :return: dictionary of teams, see :doc:`responses </responses>` """ if 'start_at_team_id' not in kwargs: kwargs['start_at_team_id'] = start_at_team_id url = self.__build_url(urls.GET_TEAM_INFO_BY_TEAM_ID, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
python
def get_team_info_by_team_id(self, start_at_team_id=None, **kwargs): """Returns a dictionary containing a in-game teams :param start_at_team_id: (int, optional) :param teams_requested: (int, optional) :return: dictionary of teams, see :doc:`responses </responses>` """ if 'start_at_team_id' not in kwargs: kwargs['start_at_team_id'] = start_at_team_id url = self.__build_url(urls.GET_TEAM_INFO_BY_TEAM_ID, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
[ "def", "get_team_info_by_team_id", "(", "self", ",", "start_at_team_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'start_at_team_id'", "not", "in", "kwargs", ":", "kwargs", "[", "'start_at_team_id'", "]", "=", "start_at_team_id", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_TEAM_INFO_BY_TEAM_ID", ",", "*", "*", "kwargs", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Returns a dictionary containing a in-game teams :param start_at_team_id: (int, optional) :param teams_requested: (int, optional) :return: dictionary of teams, see :doc:`responses </responses>`
[ "Returns", "a", "dictionary", "containing", "a", "in", "-", "game", "teams" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L148-L162
13,585
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.get_player_summaries
def get_player_summaries(self, steamids=None, **kwargs): """Returns a dictionary containing a player summaries :param steamids: (list) list of ``32-bit`` or ``64-bit`` steam ids, notice that api will convert if ``32-bit`` are given :return: dictionary of player summaries, see :doc:`responses </responses>` """ if not isinstance(steamids, collections.Iterable): steamids = [steamids] base64_ids = list(map(convert_to_64_bit, filter(lambda x: x is not None, steamids))) if 'steamids' not in kwargs: kwargs['steamids'] = base64_ids url = self.__build_url(urls.GET_PLAYER_SUMMARIES, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
python
def get_player_summaries(self, steamids=None, **kwargs): """Returns a dictionary containing a player summaries :param steamids: (list) list of ``32-bit`` or ``64-bit`` steam ids, notice that api will convert if ``32-bit`` are given :return: dictionary of player summaries, see :doc:`responses </responses>` """ if not isinstance(steamids, collections.Iterable): steamids = [steamids] base64_ids = list(map(convert_to_64_bit, filter(lambda x: x is not None, steamids))) if 'steamids' not in kwargs: kwargs['steamids'] = base64_ids url = self.__build_url(urls.GET_PLAYER_SUMMARIES, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
[ "def", "get_player_summaries", "(", "self", ",", "steamids", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "steamids", ",", "collections", ".", "Iterable", ")", ":", "steamids", "=", "[", "steamids", "]", "base64_ids", "=", "list", "(", "map", "(", "convert_to_64_bit", ",", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "steamids", ")", ")", ")", "if", "'steamids'", "not", "in", "kwargs", ":", "kwargs", "[", "'steamids'", "]", "=", "base64_ids", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_PLAYER_SUMMARIES", ",", "*", "*", "kwargs", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Returns a dictionary containing a player summaries :param steamids: (list) list of ``32-bit`` or ``64-bit`` steam ids, notice that api will convert if ``32-bit`` are given :return: dictionary of player summaries, see :doc:`responses </responses>`
[ "Returns", "a", "dictionary", "containing", "a", "player", "summaries" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L164-L183
13,586
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.get_heroes
def get_heroes(self, **kwargs): """Returns a dictionary of in-game heroes, used to parse ids into localised names :return: dictionary of heroes, see :doc:`responses </responses>` """ url = self.__build_url(urls.GET_HEROES, language=self.language, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
python
def get_heroes(self, **kwargs): """Returns a dictionary of in-game heroes, used to parse ids into localised names :return: dictionary of heroes, see :doc:`responses </responses>` """ url = self.__build_url(urls.GET_HEROES, language=self.language, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
[ "def", "get_heroes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_HEROES", ",", "language", "=", "self", ".", "language", ",", "*", "*", "kwargs", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Returns a dictionary of in-game heroes, used to parse ids into localised names :return: dictionary of heroes, see :doc:`responses </responses>`
[ "Returns", "a", "dictionary", "of", "in", "-", "game", "heroes", "used", "to", "parse", "ids", "into", "localised", "names" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L185-L195
13,587
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.get_tournament_prize_pool
def get_tournament_prize_pool(self, leagueid=None, **kwargs): """Returns a dictionary that includes community funded tournament prize pools :param leagueid: (int, optional) :return: dictionary of prize pools, see :doc:`responses </responses>` """ if 'leagueid' not in kwargs: kwargs['leagueid'] = leagueid url = self.__build_url(urls.GET_TOURNAMENT_PRIZE_POOL, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
python
def get_tournament_prize_pool(self, leagueid=None, **kwargs): """Returns a dictionary that includes community funded tournament prize pools :param leagueid: (int, optional) :return: dictionary of prize pools, see :doc:`responses </responses>` """ if 'leagueid' not in kwargs: kwargs['leagueid'] = leagueid url = self.__build_url(urls.GET_TOURNAMENT_PRIZE_POOL, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
[ "def", "get_tournament_prize_pool", "(", "self", ",", "leagueid", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'leagueid'", "not", "in", "kwargs", ":", "kwargs", "[", "'leagueid'", "]", "=", "leagueid", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_TOURNAMENT_PRIZE_POOL", ",", "*", "*", "kwargs", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Returns a dictionary that includes community funded tournament prize pools :param leagueid: (int, optional) :return: dictionary of prize pools, see :doc:`responses </responses>`
[ "Returns", "a", "dictionary", "that", "includes", "community", "funded", "tournament", "prize", "pools" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L209-L222
13,588
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.get_top_live_games
def get_top_live_games(self, partner='', **kwargs): """Returns a dictionary that includes top MMR live games :param partner: (int, optional) :return: dictionary of prize pools, see :doc:`responses </responses>` """ if 'partner' not in kwargs: kwargs['partner'] = partner url = self.__build_url(urls.GET_TOP_LIVE_GAME, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
python
def get_top_live_games(self, partner='', **kwargs): """Returns a dictionary that includes top MMR live games :param partner: (int, optional) :return: dictionary of prize pools, see :doc:`responses </responses>` """ if 'partner' not in kwargs: kwargs['partner'] = partner url = self.__build_url(urls.GET_TOP_LIVE_GAME, **kwargs) req = self.executor(url) if self.logger: self.logger.info('URL: {0}'.format(url)) if not self.__check_http_err(req.status_code): return response.build(req, url, self.raw_mode)
[ "def", "get_top_live_games", "(", "self", ",", "partner", "=", "''", ",", "*", "*", "kwargs", ")", ":", "if", "'partner'", "not", "in", "kwargs", ":", "kwargs", "[", "'partner'", "]", "=", "partner", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_TOP_LIVE_GAME", ",", "*", "*", "kwargs", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Returns a dictionary that includes top MMR live games :param partner: (int, optional) :return: dictionary of prize pools, see :doc:`responses </responses>`
[ "Returns", "a", "dictionary", "that", "includes", "top", "MMR", "live", "games" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L224-L237
13,589
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.__build_url
def __build_url(self, api_call, **kwargs): """Builds the api query""" kwargs['key'] = self.api_key if 'language' not in kwargs: kwargs['language'] = self.language if 'format' not in kwargs: kwargs['format'] = self.__format api_query = urlencode(kwargs) return "{0}{1}?{2}".format(urls.BASE_URL, api_call, api_query)
python
def __build_url(self, api_call, **kwargs): """Builds the api query""" kwargs['key'] = self.api_key if 'language' not in kwargs: kwargs['language'] = self.language if 'format' not in kwargs: kwargs['format'] = self.__format api_query = urlencode(kwargs) return "{0}{1}?{2}".format(urls.BASE_URL, api_call, api_query)
[ "def", "__build_url", "(", "self", ",", "api_call", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'key'", "]", "=", "self", ".", "api_key", "if", "'language'", "not", "in", "kwargs", ":", "kwargs", "[", "'language'", "]", "=", "self", ".", "language", "if", "'format'", "not", "in", "kwargs", ":", "kwargs", "[", "'format'", "]", "=", "self", ".", "__format", "api_query", "=", "urlencode", "(", "kwargs", ")", "return", "\"{0}{1}?{2}\"", ".", "format", "(", "urls", ".", "BASE_URL", ",", "api_call", ",", "api_query", ")" ]
Builds the api query
[ "Builds", "the", "api", "query" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L251-L262
13,590
joshuaduffy/dota2api
dota2api/__init__.py
Initialise.__check_http_err
def __check_http_err(self, status_code): """Raises an exception if we get a http error""" if status_code == 403: raise exceptions.APIAuthenticationError(self.api_key) elif status_code == 503: raise exceptions.APITimeoutError() else: return False
python
def __check_http_err(self, status_code): """Raises an exception if we get a http error""" if status_code == 403: raise exceptions.APIAuthenticationError(self.api_key) elif status_code == 503: raise exceptions.APITimeoutError() else: return False
[ "def", "__check_http_err", "(", "self", ",", "status_code", ")", ":", "if", "status_code", "==", "403", ":", "raise", "exceptions", ".", "APIAuthenticationError", "(", "self", ".", "api_key", ")", "elif", "status_code", "==", "503", ":", "raise", "exceptions", ".", "APITimeoutError", "(", ")", "else", ":", "return", "False" ]
Raises an exception if we get a http error
[ "Raises", "an", "exception", "if", "we", "get", "a", "http", "error" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L264-L271
13,591
joshuaduffy/dota2api
dota2api/src/parse.py
item_id
def item_id(response): """ Parse the item ids, will be available as ``item_0_name``, ``item_1_name``, ``item_2_name`` and so on """ dict_keys = ['item_0', 'item_1', 'item_2', 'item_3', 'item_4', 'item_5'] new_keys = ['item_0_name', 'item_1_name', 'item_2_name', 'item_3_name', 'item_4_name', 'item_5_name'] for player in response['players']: for key, new_key in zip(dict_keys, new_keys): for item in items['items']: if item['id'] == player[key]: player[new_key] = item['localized_name'] return response
python
def item_id(response): """ Parse the item ids, will be available as ``item_0_name``, ``item_1_name``, ``item_2_name`` and so on """ dict_keys = ['item_0', 'item_1', 'item_2', 'item_3', 'item_4', 'item_5'] new_keys = ['item_0_name', 'item_1_name', 'item_2_name', 'item_3_name', 'item_4_name', 'item_5_name'] for player in response['players']: for key, new_key in zip(dict_keys, new_keys): for item in items['items']: if item['id'] == player[key]: player[new_key] = item['localized_name'] return response
[ "def", "item_id", "(", "response", ")", ":", "dict_keys", "=", "[", "'item_0'", ",", "'item_1'", ",", "'item_2'", ",", "'item_3'", ",", "'item_4'", ",", "'item_5'", "]", "new_keys", "=", "[", "'item_0_name'", ",", "'item_1_name'", ",", "'item_2_name'", ",", "'item_3_name'", ",", "'item_4_name'", ",", "'item_5_name'", "]", "for", "player", "in", "response", "[", "'players'", "]", ":", "for", "key", ",", "new_key", "in", "zip", "(", "dict_keys", ",", "new_keys", ")", ":", "for", "item", "in", "items", "[", "'items'", "]", ":", "if", "item", "[", "'id'", "]", "==", "player", "[", "key", "]", ":", "player", "[", "new_key", "]", "=", "item", "[", "'localized_name'", "]", "return", "response" ]
Parse the item ids, will be available as ``item_0_name``, ``item_1_name``, ``item_2_name`` and so on
[ "Parse", "the", "item", "ids", "will", "be", "available", "as", "item_0_name", "item_1_name", "item_2_name", "and", "so", "on" ]
03c9e1c609ec36728805bbd3ada0a53ec8f51e86
https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/src/parse.py#L40-L56
13,592
bitlabstudio/django-review
review/templatetags/review_tags.py
get_reviews
def get_reviews(obj): """Simply returns the reviews for an object.""" ctype = ContentType.objects.get_for_model(obj) return models.Review.objects.filter(content_type=ctype, object_id=obj.id)
python
def get_reviews(obj): """Simply returns the reviews for an object.""" ctype = ContentType.objects.get_for_model(obj) return models.Review.objects.filter(content_type=ctype, object_id=obj.id)
[ "def", "get_reviews", "(", "obj", ")", ":", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "return", "models", ".", "Review", ".", "objects", ".", "filter", "(", "content_type", "=", "ctype", ",", "object_id", "=", "obj", ".", "id", ")" ]
Simply returns the reviews for an object.
[ "Simply", "returns", "the", "reviews", "for", "an", "object", "." ]
70d4b5c8d52d9a5615e5d0f5c7f147e15573c566
https://github.com/bitlabstudio/django-review/blob/70d4b5c8d52d9a5615e5d0f5c7f147e15573c566/review/templatetags/review_tags.py#L12-L15
13,593
bitlabstudio/django-review
review/templatetags/review_tags.py
get_review_average
def get_review_average(obj): """Returns the review average for an object.""" total = 0 reviews = get_reviews(obj) if not reviews: return False for review in reviews: average = review.get_average_rating() if average: total += review.get_average_rating() if total > 0: return total / reviews.count() return False
python
def get_review_average(obj): """Returns the review average for an object.""" total = 0 reviews = get_reviews(obj) if not reviews: return False for review in reviews: average = review.get_average_rating() if average: total += review.get_average_rating() if total > 0: return total / reviews.count() return False
[ "def", "get_review_average", "(", "obj", ")", ":", "total", "=", "0", "reviews", "=", "get_reviews", "(", "obj", ")", "if", "not", "reviews", ":", "return", "False", "for", "review", "in", "reviews", ":", "average", "=", "review", ".", "get_average_rating", "(", ")", "if", "average", ":", "total", "+=", "review", ".", "get_average_rating", "(", ")", "if", "total", ">", "0", ":", "return", "total", "/", "reviews", ".", "count", "(", ")", "return", "False" ]
Returns the review average for an object.
[ "Returns", "the", "review", "average", "for", "an", "object", "." ]
70d4b5c8d52d9a5615e5d0f5c7f147e15573c566
https://github.com/bitlabstudio/django-review/blob/70d4b5c8d52d9a5615e5d0f5c7f147e15573c566/review/templatetags/review_tags.py#L19-L31
13,594
bitlabstudio/django-review
review/templatetags/review_tags.py
render_category_averages
def render_category_averages(obj, normalize_to=100): """Renders all the sub-averages for each category.""" context = {'reviewed_item': obj} ctype = ContentType.objects.get_for_model(obj) reviews = models.Review.objects.filter( content_type=ctype, object_id=obj.id) category_averages = {} for review in reviews: review_category_averages = review.get_category_averages(normalize_to) if review_category_averages: for category, average in review_category_averages.items(): if category not in category_averages: category_averages[category] = review_category_averages[ category] else: category_averages[category] += review_category_averages[ category] if reviews and category_averages: for category, average in category_averages.items(): category_averages[category] = \ category_averages[category] / models.Rating.objects.filter( category=category, value__isnull=False, review__content_type=ctype, review__object_id=obj.id).exclude(value='').count() else: category_averages = {} for category in models.RatingCategory.objects.filter( counts_for_average=True): category_averages[category] = 0.0 context.update({'category_averages': category_averages}) return context
python
def render_category_averages(obj, normalize_to=100): """Renders all the sub-averages for each category.""" context = {'reviewed_item': obj} ctype = ContentType.objects.get_for_model(obj) reviews = models.Review.objects.filter( content_type=ctype, object_id=obj.id) category_averages = {} for review in reviews: review_category_averages = review.get_category_averages(normalize_to) if review_category_averages: for category, average in review_category_averages.items(): if category not in category_averages: category_averages[category] = review_category_averages[ category] else: category_averages[category] += review_category_averages[ category] if reviews and category_averages: for category, average in category_averages.items(): category_averages[category] = \ category_averages[category] / models.Rating.objects.filter( category=category, value__isnull=False, review__content_type=ctype, review__object_id=obj.id).exclude(value='').count() else: category_averages = {} for category in models.RatingCategory.objects.filter( counts_for_average=True): category_averages[category] = 0.0 context.update({'category_averages': category_averages}) return context
[ "def", "render_category_averages", "(", "obj", ",", "normalize_to", "=", "100", ")", ":", "context", "=", "{", "'reviewed_item'", ":", "obj", "}", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "reviews", "=", "models", ".", "Review", ".", "objects", ".", "filter", "(", "content_type", "=", "ctype", ",", "object_id", "=", "obj", ".", "id", ")", "category_averages", "=", "{", "}", "for", "review", "in", "reviews", ":", "review_category_averages", "=", "review", ".", "get_category_averages", "(", "normalize_to", ")", "if", "review_category_averages", ":", "for", "category", ",", "average", "in", "review_category_averages", ".", "items", "(", ")", ":", "if", "category", "not", "in", "category_averages", ":", "category_averages", "[", "category", "]", "=", "review_category_averages", "[", "category", "]", "else", ":", "category_averages", "[", "category", "]", "+=", "review_category_averages", "[", "category", "]", "if", "reviews", "and", "category_averages", ":", "for", "category", ",", "average", "in", "category_averages", ".", "items", "(", ")", ":", "category_averages", "[", "category", "]", "=", "category_averages", "[", "category", "]", "/", "models", ".", "Rating", ".", "objects", ".", "filter", "(", "category", "=", "category", ",", "value__isnull", "=", "False", ",", "review__content_type", "=", "ctype", ",", "review__object_id", "=", "obj", ".", "id", ")", ".", "exclude", "(", "value", "=", "''", ")", ".", "count", "(", ")", "else", ":", "category_averages", "=", "{", "}", "for", "category", "in", "models", ".", "RatingCategory", ".", "objects", ".", "filter", "(", "counts_for_average", "=", "True", ")", ":", "category_averages", "[", "category", "]", "=", "0.0", "context", ".", "update", "(", "{", "'category_averages'", ":", "category_averages", "}", ")", "return", "context" ]
Renders all the sub-averages for each category.
[ "Renders", "all", "the", "sub", "-", "averages", "for", "each", "category", "." ]
70d4b5c8d52d9a5615e5d0f5c7f147e15573c566
https://github.com/bitlabstudio/django-review/blob/70d4b5c8d52d9a5615e5d0f5c7f147e15573c566/review/templatetags/review_tags.py#L41-L71
13,595
bitlabstudio/django-review
review/templatetags/review_tags.py
total_review_average
def total_review_average(obj, normalize_to=100): """Returns the average for all reviews of the given object.""" ctype = ContentType.objects.get_for_model(obj) total_average = 0 reviews = models.Review.objects.filter( content_type=ctype, object_id=obj.id) for review in reviews: total_average += review.get_average_rating(normalize_to) if reviews: total_average /= reviews.count() return total_average
python
def total_review_average(obj, normalize_to=100): """Returns the average for all reviews of the given object.""" ctype = ContentType.objects.get_for_model(obj) total_average = 0 reviews = models.Review.objects.filter( content_type=ctype, object_id=obj.id) for review in reviews: total_average += review.get_average_rating(normalize_to) if reviews: total_average /= reviews.count() return total_average
[ "def", "total_review_average", "(", "obj", ",", "normalize_to", "=", "100", ")", ":", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "total_average", "=", "0", "reviews", "=", "models", ".", "Review", ".", "objects", ".", "filter", "(", "content_type", "=", "ctype", ",", "object_id", "=", "obj", ".", "id", ")", "for", "review", "in", "reviews", ":", "total_average", "+=", "review", ".", "get_average_rating", "(", "normalize_to", ")", "if", "reviews", ":", "total_average", "/=", "reviews", ".", "count", "(", ")", "return", "total_average" ]
Returns the average for all reviews of the given object.
[ "Returns", "the", "average", "for", "all", "reviews", "of", "the", "given", "object", "." ]
70d4b5c8d52d9a5615e5d0f5c7f147e15573c566
https://github.com/bitlabstudio/django-review/blob/70d4b5c8d52d9a5615e5d0f5c7f147e15573c566/review/templatetags/review_tags.py#L75-L85
13,596
bitlabstudio/django-review
review/templatetags/review_tags.py
user_has_reviewed
def user_has_reviewed(obj, user): """Returns True if the user has already reviewed the object.""" ctype = ContentType.objects.get_for_model(obj) try: models.Review.objects.get(user=user, content_type=ctype, object_id=obj.id) except models.Review.DoesNotExist: return False return True
python
def user_has_reviewed(obj, user): """Returns True if the user has already reviewed the object.""" ctype = ContentType.objects.get_for_model(obj) try: models.Review.objects.get(user=user, content_type=ctype, object_id=obj.id) except models.Review.DoesNotExist: return False return True
[ "def", "user_has_reviewed", "(", "obj", ",", "user", ")", ":", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "try", ":", "models", ".", "Review", ".", "objects", ".", "get", "(", "user", "=", "user", ",", "content_type", "=", "ctype", ",", "object_id", "=", "obj", ".", "id", ")", "except", "models", ".", "Review", ".", "DoesNotExist", ":", "return", "False", "return", "True" ]
Returns True if the user has already reviewed the object.
[ "Returns", "True", "if", "the", "user", "has", "already", "reviewed", "the", "object", "." ]
70d4b5c8d52d9a5615e5d0f5c7f147e15573c566
https://github.com/bitlabstudio/django-review/blob/70d4b5c8d52d9a5615e5d0f5c7f147e15573c566/review/templatetags/review_tags.py#L89-L97
13,597
ahawker/ulid
ulid/base32.py
str_to_bytes
def str_to_bytes(value: str, expected_length: int) -> bytes: """ Convert the given string to bytes and validate it is within the Base32 character set. :param value: String to convert to bytes :type value: :class:`~str` :param expected_length: Expected length of the input string :type expected_length: :class:`~int` :return: Value converted to bytes. :rtype: :class:`~bytes` """ length = len(value) if length != expected_length: raise ValueError('Expects {} characters for decoding; got {}'.format(expected_length, length)) try: encoded = value.encode('ascii') except UnicodeEncodeError as ex: raise ValueError('Expects value that can be encoded in ASCII charset: {}'.format(ex)) decoding = DECODING # Confirm all bytes are valid Base32 decode characters. # Note: ASCII encoding handles the out of range checking for us. for byte in encoded: if decoding[byte] > 31: raise ValueError('Non-base32 character found: "{}"'.format(chr(byte))) return encoded
python
def str_to_bytes(value: str, expected_length: int) -> bytes: """ Convert the given string to bytes and validate it is within the Base32 character set. :param value: String to convert to bytes :type value: :class:`~str` :param expected_length: Expected length of the input string :type expected_length: :class:`~int` :return: Value converted to bytes. :rtype: :class:`~bytes` """ length = len(value) if length != expected_length: raise ValueError('Expects {} characters for decoding; got {}'.format(expected_length, length)) try: encoded = value.encode('ascii') except UnicodeEncodeError as ex: raise ValueError('Expects value that can be encoded in ASCII charset: {}'.format(ex)) decoding = DECODING # Confirm all bytes are valid Base32 decode characters. # Note: ASCII encoding handles the out of range checking for us. for byte in encoded: if decoding[byte] > 31: raise ValueError('Non-base32 character found: "{}"'.format(chr(byte))) return encoded
[ "def", "str_to_bytes", "(", "value", ":", "str", ",", "expected_length", ":", "int", ")", "->", "bytes", ":", "length", "=", "len", "(", "value", ")", "if", "length", "!=", "expected_length", ":", "raise", "ValueError", "(", "'Expects {} characters for decoding; got {}'", ".", "format", "(", "expected_length", ",", "length", ")", ")", "try", ":", "encoded", "=", "value", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeEncodeError", "as", "ex", ":", "raise", "ValueError", "(", "'Expects value that can be encoded in ASCII charset: {}'", ".", "format", "(", "ex", ")", ")", "decoding", "=", "DECODING", "# Confirm all bytes are valid Base32 decode characters.", "# Note: ASCII encoding handles the out of range checking for us.", "for", "byte", "in", "encoded", ":", "if", "decoding", "[", "byte", "]", ">", "31", ":", "raise", "ValueError", "(", "'Non-base32 character found: \"{}\"'", ".", "format", "(", "chr", "(", "byte", ")", ")", ")", "return", "encoded" ]
Convert the given string to bytes and validate it is within the Base32 character set. :param value: String to convert to bytes :type value: :class:`~str` :param expected_length: Expected length of the input string :type expected_length: :class:`~int` :return: Value converted to bytes. :rtype: :class:`~bytes`
[ "Convert", "the", "given", "string", "to", "bytes", "and", "validate", "it", "is", "within", "the", "Base32", "character", "set", "." ]
f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f
https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L340-L368
13,598
noxdafox/pebble
setup.py
package_version
def package_version(): """Get the package version via Git Tag.""" version_path = os.path.join(os.path.dirname(__file__), 'version.py') version = read_version(version_path) write_version(version_path, version) return version
python
def package_version(): """Get the package version via Git Tag.""" version_path = os.path.join(os.path.dirname(__file__), 'version.py') version = read_version(version_path) write_version(version_path, version) return version
[ "def", "package_version", "(", ")", ":", "version_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'version.py'", ")", "version", "=", "read_version", "(", "version_path", ")", "write_version", "(", "version_path", ",", "version", ")", "return", "version" ]
Get the package version via Git Tag.
[ "Get", "the", "package", "version", "via", "Git", "Tag", "." ]
d8f3d989655715754f0a65d7419cfa584491f614
https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/setup.py#L10-L17
13,599
noxdafox/pebble
pebble/decorators.py
synchronized
def synchronized(*args): """A synchronized function prevents two or more callers to interleave its execution preventing race conditions. The synchronized decorator accepts as optional parameter a Lock, RLock or Semaphore object which will be employed to ensure the function's atomicity. If no synchronization object is given, a single threading.Lock will be used. This implies that between different decorated function only one at a time will be executed. """ if callable(args[0]): return decorate_synchronized(args[0], _synchronized_lock) else: def wrap(function): return decorate_synchronized(function, args[0]) return wrap
python
def synchronized(*args): """A synchronized function prevents two or more callers to interleave its execution preventing race conditions. The synchronized decorator accepts as optional parameter a Lock, RLock or Semaphore object which will be employed to ensure the function's atomicity. If no synchronization object is given, a single threading.Lock will be used. This implies that between different decorated function only one at a time will be executed. """ if callable(args[0]): return decorate_synchronized(args[0], _synchronized_lock) else: def wrap(function): return decorate_synchronized(function, args[0]) return wrap
[ "def", "synchronized", "(", "*", "args", ")", ":", "if", "callable", "(", "args", "[", "0", "]", ")", ":", "return", "decorate_synchronized", "(", "args", "[", "0", "]", ",", "_synchronized_lock", ")", "else", ":", "def", "wrap", "(", "function", ")", ":", "return", "decorate_synchronized", "(", "function", ",", "args", "[", "0", "]", ")", "return", "wrap" ]
A synchronized function prevents two or more callers to interleave its execution preventing race conditions. The synchronized decorator accepts as optional parameter a Lock, RLock or Semaphore object which will be employed to ensure the function's atomicity. If no synchronization object is given, a single threading.Lock will be used. This implies that between different decorated function only one at a time will be executed.
[ "A", "synchronized", "function", "prevents", "two", "or", "more", "callers", "to", "interleave", "its", "execution", "preventing", "race", "conditions", "." ]
d8f3d989655715754f0a65d7419cfa584491f614
https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/decorators.py#L26-L44