def __init__(self, session): self.session = session self.name = self.__class__.__name__ self.level = "GREEN" pagerduty = utils.get_config("PagerDuty") self.subdomain = pagerduty.get("subdomain") self.apikey = pagerduty.get("apikey")
def run(self): """A network connection.""" while True: try: network_config = utils.get_config(self.network) if network_config.get("api_token", default=None): from pyhole.core.slack import client else: from pyhole.core.irc import client connection = client.Client(self.network) except Exception, exc: LOG.exception(exc) LOG.error("Retrying in %d seconds" % self.reconnect_delay) time.sleep(self.reconnect_delay) continue try: connection.start() except KeyboardInterrupt: sys.exit(0) except Exception, ex: LOG.exception(ex) LOG.error("Retrying in %d seconds" % self.reconnect_delay) time.sleep(self.reconnect_delay) continue
def __init__(self): jira = utils.get_config("Jira") self.auth_server = jira.get("auth_server") self.domain = jira.get("domain") self.username = jira.get("username") self.password = jira.get("password")
def __init__(self, network): super(Process, self).__init__() self.log = logger.get_logger() self.config = utils.get_config() self.network = network self.reconnect_delay = self.config.get("reconnect_delay", type="int")
def Main(): """Main loop.""" config = utils.get_config() log = logger.get_logger() networks = config.get("networks", type="list") log.info("Starting %s..." % version.version_string()) log.info("Connecting to networks: %s" % ", ".join(networks)) procs = [] for network in networks: proc = process.Process(network) proc.start() procs.append(proc) try: if config.get("api_enabled", type="bool"): api.run() while True: time.sleep(1) for proc in procs: if not proc.is_alive(): procs.remove(proc) if not procs: log.info("No longer connected to any networks; shutting down.") sys.exit(0) except KeyboardInterrupt: log.info("Caught KeyboardInterrupt; shutting down.")
def __init__(self, network): pyhole_config = utils.get_config() network_config = utils.get_config(network) self.addressed = False self.client = None self.log = logger.get_logger(str(network)) self.version = version.version_string() self.admins = pyhole_config.get("admins", type="list") self.command_prefix = pyhole_config.get("command_prefix") self.api_token = network_config.get("api_token") self.nick = network_config.get("nick") self.load_plugins()
def history_update(self, source, message): self.irc_history.insert(0, (source, message)) try: lookback = utils.get_config("Regex").get("lookback") except: lookback = 10 if len(self.irc_history) > int(lookback): self.irc_history.pop()
def __init__(self, session): self.session = session self.name = self.__class__.__name__ self.redmine = utils.get_config("Redmine") self.redmine_domain = self.redmine.get("domain") self.redmine_key = self.redmine.get("key") self.redmine_url = "https://%s:password@%s" % ( self.redmine_key, self.redmine_domain)
def __init__(self, session): self.session = session self.name = self.__class__.__name__ self.redmine = utils.get_config("Redmine") self.redmine_domain = self.redmine.get("domain") self.redmine_key = self.redmine.get("key") self.redmine_url = "https://%s:password@%s" % (self.redmine_key, self.redmine_domain)
def distance(self, message, params=None, **kwargs): """Display distances (ex: .dist <nick|loc> [to <nick|loc>]).""" maps_api = utils.get_config("GoogleMaps") try: key = maps_api.get("key") except Exception: message.dispatch("No Google Maps API key set.") return parts = params.split(" to ") if not parts: message.dispatch(self.distance.__doc__) return dest_nick = parts[0].strip() if len(parts) > 1: origin_nick = parts[1].strip() else: origin_nick = message.source.split("!")[0] dest = None origin = None for filename in utils.list_files("Wunderground"): nick = filename.split("!")[0] if nick == dest_nick: dest = utils.read_file("Wunderground", filename) if nick == origin_nick: origin = utils.read_file("Wunderground", filename) if not dest: # They passed in a location dest = dest_nick if not origin: # They passed in a location origin = origin_nick origin = _resolve_pws(origin) dest = _resolve_pws(dest) resp = utils.fetch_url("https://maps.googleapis.com/maps/api" "/directions/json?origin=%s&destination=%s" "&key=%s" % (origin, dest, key)) msg = None if resp.status_code == 200: try: msg = resp.json()["routes"][0]["legs"][0]["distance"]["text"] except IndexError: pass if not msg: msg = "Unable to fetch data from Google Maps." message.dispatch(msg)
def distance(self, message, params=None, **kwargs): """Display distances (ex: .dist <nick|loc> [to <nick|loc>]).""" maps_api = utils.get_config("GoogleMaps") try: key = maps_api.get("key") except Exception: message.dispatch("No Google Maps API key set.") return parts = params.split(" to ") if not parts: message.dispatch(self.distance.__doc__) return dest_nick = parts[0].strip() if len(parts) > 1: origin_nick = parts[1].strip() else: origin_nick = message.source.split("!")[0] dest = None origin = None for filename in utils.list_files("Wunderground"): nick = filename.split("!")[0] if nick == dest_nick: dest = utils.read_file("Wunderground", filename) if nick == origin_nick: origin = utils.read_file("Wunderground", filename) if not dest: # They passed in a location dest = dest_nick if not origin: # They passed in a location origin = origin_nick origin = _resolve_pws(origin) dest = _resolve_pws(dest) resp = request.get("https://maps.googleapis.com/maps/api" "/directions/json?origin=%s&destination=%s" "&key=%s" % (origin, dest, key)) msg = None if resp.status_code == 200: try: msg = resp.json()["routes"][0]["legs"][0]["distance"]["text"] except IndexError: pass if not msg: msg = "Unable to fetch data from Google Maps." message.dispatch(msg)
def run(self): """Run the network connection.""" network_config = utils.get_config(self.network) if network_config.get("api_token", default=None): from pyhole.core.slack import client else: from pyhole.core.irc import client connection = client.Client(self.network) connection.start()
def _resolve_pws(location): """Look up the location of a PWS.""" if location.lower().startswith("pws:"): wunderground = utils.get_config("Wunderground") api_key = wunderground.get("key") w = pywunderground.request(api_key, ["conditions"], location) return w["current_observation"]["display_location"]["zip"] return location
def __init__(self, irc): self.irc = irc self.name = self.__class__.__name__ self.jira = utils.get_config("Jira") self.jira_domain = self.jira.get("domain") self.jira_username = self.jira.get("username") self.jira_password = self.jira.get("password") self.jira = JIRA(self.jira_url, basic_auth=(self.jira_username, self.jira_password))
def __init__(self, network): irclib.SimpleIRCClient.__init__(self) pyhole_config = utils.get_config() network_config = utils.get_config(network) self.log = logger.get_logger(str(network)) self.version = version.version_string() self.source = None self.target = None self.addressed = False self.admins = pyhole_config.get("admins", type="list") self.command_prefix = pyhole_config.get("command_prefix") self.reconnect_delay = pyhole_config.get("reconnect_delay", type="int") self.rejoin_delay = pyhole_config.get("rejoin_delay", type="int") self.server = network_config.get("server") self.password = network_config.get("password", default=None) self.port = network_config.get("port", type="int", default=6667) self.ssl = network_config.get("ssl", type="bool", default=False) self.ipv6 = network_config.get("ipv6", type="bool", default=False) self.bind_to = network_config.get("bind_to", default=None) self.nick = network_config.get("nick") self.username = network_config.get("username", default=None) self.identify_password = network_config.get("identify_password", default=None) self.channels = network_config.get("channels", type="list") self.load_plugins() self.log.info("Connecting to %s:%d as %s" % (self.server, self.port, self.nick)) self.connect(self.server, self.port, self.nick, self.password, username=self.username, connect_factory=connection.Factory( wrapper=ssl.wrap_socket, ipv6=self.ipv6).connect if self.ssl else connection.Factory())
def __init__(self, network): irclib.SimpleIRCClient.__init__(self) logger.setup_logger(str(network)) pyhole_config = utils.get_config() network_config = utils.get_config(network) self.log = logger.get_logger(str(network)) self.version = version.version_string() self.source = None self.target = None self.addressed = False self.admins = pyhole_config.get("admins", type="list") self.command_prefix = pyhole_config.get("command_prefix") self.reconnect_delay = pyhole_config.get("reconnect_delay", type="int") self.rejoin_delay = pyhole_config.get("rejoin_delay", type="int") self.server = network_config.get("server") self.password = network_config.get("password", default=None) self.port = network_config.get("port", type="int", default=6667) self.ssl = network_config.get("ssl", type="bool", default=False) self.ipv6 = network_config.get("ipv6", type="bool", default=False) self.bind_to = network_config.get("bind_to", default=None) self.nick = network_config.get("nick") self.username = network_config.get("username", default=None) self.identify_password = network_config.get("identify_password", default=None) self.channels = network_config.get("channels", type="list") self.load_plugins() self.log.info("Connecting to %s:%d as %s" % (self.server, self.port, self.nick)) self.connect(self.server, self.port, self.nick, self.password, username=self.username, connect_factory=connection.Factory( wrapper=ssl.wrap_socket, ipv6=self.ipv6).connect if self.ssl else connection.Factory())
def _connectToDatabase(self): try: self.config = utils.get_config("MysqlLogger") db_name = self.config.get("db_name") db_user = self.config.get("db_user") db_pass = self.config.get("db_password") db_host = self.config.get("db_host") try: db_type = self.config.get("db_type") except: db_type = "mysql" except Exception: print "Could not load MysqlLogger" #self.disabled = True #DbConnect self.db_engine = create_engine( '' + db_type + '://' + db_user + ':' + db_pass + '@' + db_host + '/' + db_name ) self.db_metadata = MetaData() self.db_chanlog = Table( 'irc_chanlog', self.db_metadata, Column('ID', Integer, primary_key=True), Column('channel', String(14)), Column('sender', String(14), nullable=False), Column('sender_user', String(40)), Column('message', TEXT), Column( 'timestamp', TIMESTAMP, nullable=False, default=func.now() ) ) self.db_chanevs = Table( 'irc_chanevs', self.db_metadata, Column('ID', Integer, primary_key=True), Column('channel', String(14)), Column('sender', String(14), nullable=False), Column('sender_user', String(40)), Column('evtype', String(10)), Column( 'timestamp', TIMESTAMP, nullable=False, default=func.now() ) ) try: self.db_conn = self.db_engine.connect() except OperationalError: print 'Nedalo sa mi pripojit sa do databazy'
def distance(self, message, params=None, **kwargs): """Display distance between users (ex: .dist <nick|location> [to <nick|location>])""" maps_api = utils.get_config("Googlemaps") try: key = maps_api.get("key") except Exception: message.dispatch("No Google Maps API key set") return parts = params.split(' to ') if not parts: message.dispatch(self.distance.__doc__) return dest_nick = parts[0].strip() if len(parts) > 1: origin_nick = parts[1].strip() else: origin_nick = message.source.split('!')[0] dest = None origin = None for filename in utils.list_files('Weather'): nick, ident = filename.split('!') if nick == dest_nick: dest = utils.read_file('Weather', filename) if nick == origin_nick: origin = utils.read_file('Weather', filename) if not dest: # They passed in a location dest = dest_nick if not origin: # They passed in a location origin = origin_nick resp = requests.get('https://maps.googleapis.com/maps/api' '/directions/json?origin=%s&destination=%s' '&key=%s' % (origin, dest, key)) msg = None if resp.status_code == 200: try: msg = resp.json()['routes'][0]['legs'][0]['distance']['text'] except IndexError: pass if not msg: msg = "Unable to fetch data from Google Maps" message.dispatch(msg)
def _notify_new_xsas(self, added_xsa_ids, new_data): xsa_config = utils.get_config("Xsa") try: notify_str = xsa_config.get("notify") except Exception: return channels = notify_str.split(',') for xsa_id in added_xsa_ids: msg = self._make_xsa_message(xsa_id, new_data) for channel in channels: channel = channel.strip() self.irc.notice(channel, msg)
def __init__(self, irc): self.irc = irc self.name = self.__class__.__name__ self.disabled = False try: self.redmine = utils.get_config("Redmine") self.redmine_domain = self.redmine.get("domain") self.redmine_key = self.redmine.get("key") self.redmine_url = "https://%s:password@%s" % (self.redmine_key, self.redmine_domain) except Exception: self.disabled = True
def __init__(self, irc): self.irc = irc self.name = self.__class__.__name__ self.disabled = False try: self.redmine = utils.get_config("Redmine") self.redmine_domain = self.redmine.get("domain") self.redmine_key = self.redmine.get("key") self.redmine_url = "https://%s:password@%s" % ( self.redmine_key, self.redmine_domain) except Exception: self.disabled = True
def _notify_new_xsas(self, added_xsa_ids, new_data): xsa_config = utils.get_config("XSA") try: notify_str = xsa_config.get("notify") except Exception: return channels = notify_str.split(",") for xsa_id in added_xsa_ids: msg = self._make_xsa_message(xsa_id, new_data) for channel in channels: channel = channel.strip() self.irc.notice(channel, msg)
def __init__(self, session): self.session = session self.name = self.__class__.__name__ pagerduty = utils.get_config("PagerDuty") self.api_token = pagerduty.get("api_token") self.endpoint = "https://api.pagerduty.com" self.api_headers = { "Accept": "application/vnd.pagerduty+json;version=2", "Authorization": "Token token=%s" % self.api_token, "Content-Type": "application/json" }
def __init__(self, session): self.session = session self.name = self.__class__.__name__ pagerduty = utils.get_config("PagerDuty") self.subdomain = pagerduty.get("subdomain") self.api_key = pagerduty.get("api_key") self.integration_key = pagerduty.get("integration_key") self.api_headers = { "Authorization": "Token token=%s" % self.api_key, "Content-Type": "application/json" } self.user_cache = None self.reset_current_incident()
def run(): """Run the flask process.""" config = utils.get_config() kwargs = { "host": "0.0.0.0", "threaded": True } ssl_crt = config.get("api_ssl_crt", default="") ssl_key = config.get("api_ssl_key", default="") if os.path.exists(ssl_crt) and os.path.exists(ssl_key): kwargs["ssl_context"] = (ssl_crt, ssl_key) APP.run(**kwargs)
def weather(self, message, params=None, **kwargs): """Display current weather report (ex: .w [set] [<location>])""" wunderground = utils.get_config("Wunderground") api_key = wunderground.get("key") if params: location = params if location.startswith("set "): location = location[4:] utils.write_file(self.name, message.source, location) message.dispatch("Location information saved") else: location = utils.read_file(self.name, message.source) if not location: message.dispatch(self.weather.__doc__) return try: w = pywunderground.request(api_key, ["conditions"], location) except Exception: message.dispatch("Unable to fetch weather data") return if w.get("current_observation"): w = w["current_observation"] city = w["display_location"]["full"] zip_code = w["display_location"]["zip"] temp = w["temperature_string"] humidity = w["relative_humidity"] wind = w["wind_string"] condition = w["weather"] zip_code = "" if zip_code == "00000" else " %s" % zip_code humidity = "N/A%" if len(humidity) > 3 else humidity result = ("%s%s: %s Humidity: %s Wind: %s %s") % (city, zip_code, temp, humidity, wind, condition) message.dispatch(result) else: message.dispatch("Location not found: '%s'" % location)
def wunderground(self, message, params=None, **kwargs): """Display current weather report (ex: .w [set] [<location>]).""" wunderground = utils.get_config("Wunderground") api_key = wunderground.get("key") if params: location = params if location.startswith("set "): location = location[4:] utils.write_file(self.name, message.source, location) message.dispatch("Location information saved.") else: location = utils.read_file(self.name, message.source) if not location: message.dispatch(self.wunderground.__doc__) return try: w = pywunderground.request(api_key, ["conditions"], location) except Exception: message.dispatch("Unable to fetch Wunderground data.") return if "current_observation" in w: w = w["current_observation"] city = w["display_location"]["full"] zip_code = w["display_location"]["zip"] temp = w["temperature_string"] humidity = w["relative_humidity"] wind = w["wind_string"] condition = w["weather"] zip_code = "" if zip_code == "00000" else " %s" % zip_code humidity = "N/A%" if len(humidity) > 3 else humidity result = "%s%s: %s Humidity: %s Wind: %s %s" % (city, zip_code, temp, humidity, wind, condition) message.dispatch(result) else: message.dispatch("Location not found: '%s'" % location)
def __init__(self, irc): self.irc = irc self.name = self.__class__.__name__ self.disabled = False try: self.versionone = utils.get_config("VersionOne") self.versionone_domain = self.versionone.get("domain") self.versionone_key = self.versionone.get("key") self.versionone_username = self.versionone.get("username") self.versionone_password = self.versionone.get("password") self.versionone_url = ("https://%s:%s@%s/%s/VersionOne/" "rest-1.v1") % (self.versionone_username, self.versionone_password, self.versionone_domain, self.versionone_key) except Exception: self.disabled = True
def __init__(self, *args, **kwargs): plugin.Plugin.__init__(self, *args, **kwargs) self.config = utils.get_config("TinyURL")
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Network Process Class""" import multiprocessing import sys import time from pyhole.core import log from pyhole.core import utils LOG = log.get_logger() CONFIG = utils.get_config() class Process(multiprocessing.Process): """A network connection process.""" def __init__(self, network): super(Process, self).__init__() self.network = network self.reconnect_delay = CONFIG.get("reconnect_delay", type="int") def run(self): """A network connection.""" while True: try: network_config = utils.get_config(self.network) if network_config.get("api_token", default=None):
def test_get_config(self): config = utils.get_config() debug = config.get("debug", type="bool") self.assertTrue(debug in [True, False])
request["network"], request["target"], request["message"] ) except KeyError: flask.abort(422) # NOTE(jk0): Disable until auth is implemented. # QUEUE.put(item) return str(item), 200 # END MESSAGE API # # BEGIN PAGERDUTY API # pagerduty = utils.get_config("PagerDuty") api_token = pagerduty.get("api_token") api_endpoint = "https://api.pagerduty.com" api_headers = { "Accept": "application/vnd.pagerduty+json;version=2", "Authorization": "Token token=%s" % api_token, "Content-Type": "application/json" } @APP.route("/pagerduty", methods=["GET"]) def get_services(): """Fetch and return PagerDuty services.""" url = "%s/services?limit=100" % api_endpoint req = request.get(url, headers=api_headers)
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Network Process Class""" import multiprocessing import sys import time from pyhole.core import log from pyhole.core import utils LOG = log.get_logger() CONFIG = utils.get_config() class Process(multiprocessing.Process): """A network connection process.""" def __init__(self, network): super(Process, self).__init__() self.network = network self.reconnect_delay = CONFIG.get("reconnect_delay", type="int") def run(self): """A network connection.""" while True: try: network_config = utils.get_config(self.network) if network_config.get("api_token", default=None):