def __init__(self, access_token=None): self.digital_ocean = access_token self.report = "" config_file = open("config.json", "r") self.backup_data = json.load(config_file) self.alert = Alert(self.backup_data["femail"], self.backup_data["temail"])
def win_animation(self): ship_position = self.main_win.objects[self.p1.stacking_order].x1 distance = self.main_win.max_x - ship_position + 2 self.main_win.auto_refresh = False self.main_win.show(self.p1.thruster) self.p1.thruster.step = 1 speed = 0.25 while distance >= 0: self.main_win.move_relative(self.p1, x=1) self.p1.thruster.update() self.main_win.move_relative(self.p1.thruster, x=1) self.main_win.refresh() time.sleep(speed) speed -= 0.005 if speed < 0.04: speed = 0.04 distance -= 1 self.main_win.auto_refresh = True msg = Alert('!!! CONGRATULATIONS !!!\nTHE GUMMIES HAVE BEEN SAVED') msg.show(self.main_win) time.sleep(3) msg.hide()
def on_save(self, passphrase, repeat_passphrase): # if store.get("mnemonic"): # print ("Mnemonic exists") # print (store.get("mnemonic")) # return if passphrase.text != repeat_passphrase.text or not passphrase.text: Alert(title='Error message', text='Passphrases must match') return if len(passphrase.text) < 8: Alert(title='Error message', text='Passphrases must be at least 8 characters long') return if not self.mnemonic: Alert(title='Error message', text='PLease generate a New mnemonic') return scrypt_key, salt = generate_scrypt_key(passphrase.text) encrypted_mnemonic = aes_encrypt(scrypt_key, self.mnemonic) store.put("mnemonic", value=encrypted_mnemonic.hex(), salt=salt.hex()) print(store.get("mnemonic")) self.go_to_login() return
def DelTargetRequest(self, request, context): try: target_file = File(self._target_file) target_file_content = target_file.open_file() fild_sd = FileSD(target_file_content) alert_file = File(self._alert_file) alert_file_content = alert_file.open_file() alerts = Alert(alert_file_content) fild_sd.del_target(vnf_id=request.vnf_id) target_file.write_to_file(str(fild_sd)) alerts.delete_rule(vnf_id=request.vnf_id) alert_file.write_to_file(str(alerts)) response = service_pb2.MonitorReply(message="", status=1) r = requests.post("http://127.0.0.1:9090/-/reload") print("Target deleted") return response except: traceback.print_exc(file=sys.stdout) response = service_pb2.MonitorReply(message="Unexpected error:", status=1) return response
def _button_Create_clicked(self): saveDir = self.ui.lineEdit_BookPath.text() bookTitle = self.ui.lineEdit_BookTitle.text() author = self.ui.lineEdit_Author.text() publisher = self.ui.lineEdit_Publisher.text() readBy = self.ui.lineEdit_ReadBy.text() if saveDir and bookTitle: logging.debug(saveDir + ":" + bookTitle) self.switch_window.emit({"saveDir": saveDir, "bookTitle": bookTitle, "author": {"type": "Person", "name": author}, "publisher": publisher, "readBy": {"type": "Person", "name": readBy}}) else: self.mask = MaskWidget(self) self.mask.show() self.alert = Alert(self._translate("CreateNewWizard", "You must select one directory and" " keyin the booktitle!"), self._translate("CreateNewWizard", "Warning!")) self.alert.move( self.geometry().x() + self.geometry().width() / 2 - self.alert.geometry().width() / 2, self.geometry().y() + self.geometry().height() / 2 - self.alert.geometry().height() / 2) result = self.alert.exec_() self.mask.close()
def NewTargetRequest(self, request, context): try: target_file = File(self._target_file) target_file_content = target_file.open_file() fild_sd = FileSD(target_file_content) alert_file = File(self._alert_file) alert_file_content = alert_file.open_file() alerts = Alert(alert_file_content) for vdu in request.vdus: fild_sd.add_new_target(vdu, request.vnf_id) alerts.add_new_rule(alerts=vdu.alerts, vnf_id=request.vnf_id, vdu_name=vdu.vdu_name) target_file.write_to_file(str(fild_sd)) alert_file.write_to_file(str(alerts)) # Reload prometheus configuration r = requests.post("http://127.0.0.1:9090/-/reload") print("New target created") response = service_pb2.MonitorReply(message="", status=1) return response except: traceback.print_exc(file=sys.stdout) response = service_pb2.MonitorReply(message="Unexpected error:", status=1) return response
def _check(data, context, check_function): # Ensure checkers registration _load() is_valid = True for checker in _checkers: processed_data = check_function(checker, data, context) if processed_data is not None: data = processed_data else: attack_config = Config.get_attack_config(checker.get_attack_name()) if attack_config is None: continue if attack_config['action'] == 'ids': Alert.add_alert(alert_type=attack_config['report_type'], action_taken='LOGGED', event='Attack %s was found' % checker.get_attack_name()) elif attack_config['action'] == 'ips': Alert.add_alert(alert_type=attack_config['report_type'], action_taken='ABORTED', event='Attack %s was found' % checker.get_attack_name()) is_valid = False return data if is_valid else None
def on_connect(self, obj): try: local_port = self.ent_port.get_text() tunnel = None if self.ent_remote_host.get_text(): tunnel = SSHTunnelForwarder( self.ent_remote_host.get_text(), ssh_username=self.ent_remote_user.get_text(), ssh_pkey=self.file_remote_key.get_filename(), remote_bind_address=('127.0.0.1', int(self.ent_port.get_text()))) tunnel.start() local_port = tunnel.local_bind_port conn = psycopg2.connect(database=self.ent_database.get_text(), user=self.ent_user.get_text(), host=self.ent_host.get_text(), port=local_port, password=self.ent_password.get_text()) QueryWindow(conn, tunnel) WindowManager.remove(self.window) self.window.destroy() except SSHException as e: print e Alert('Unable to create SSH tunnel', self.window) except Exception as e: print e Alert('Unable to connect to server.', self.window)
def testICMP(config): db = Database(config) alert = Alert(db, config) ping = Ping() ping.thread_count = int(config.get('Config', 'config.numthreads')) while True: logger.info("Start test ICMP: %s" % time.ctime()) #Get hots hosts = list(db.getHostsActive()) if hosts: #test hosts tests = list(ping.start(list(hosts))) #Process old alerts with new alerts and send messages alert.procAlerts(tests) else: #Check if exist alerts when database is empty. If exist, clean all. flag, alerts = db.getAlert() if flag: for alert in alerts: flag, result = self.db.delAlert(alert[0]) if not flag: self.logger.info( 'I could not delete alerts %s, error %s' % (str(alert[0]), result)) else: self.logger.info('I could not get alerts: %s' % (alerts)) #Uncomment to sleep a while #time.sleep( 30 ) logger.info("End test ICMP: %s" % time.ctime())
def on_button_remove_tag_clicked(self, widget): selected_row = self.tags.get_selected_row() if selected_row: if selected_row.get_name() == "due": Alert.show_alert("This tag can't be removed") else: self.tags.remove_item(selected_row.get_name()) self.tags.show_all()
def test_action_is_executed_when_rule_matches(self): """""" exchange = {"GOOG": Stock("GOOG")} rule = PriceRule("GOOG", lambda stock: stock.price > 10) action = MagicMock() alert = Alert("sample alert", rule, action) alert.connect(exchange) exchange["GOOG"].update(datetime(2014, 2, 10), 11) action.execute.assert_called_with("sample alert")
def intro(self): self.midpoint_x = round( self.main_win.width * (self.screens - 0.5)/self.screens ) midpoint_y = self.main_win.height // 2 outline = Outline(self.p2) self.main_win.add_object( outline, self.midpoint_x + self.ship_space - 1, midpoint_y - self.p2.height // 2 - 1 ) outline = Outline(self.p1) self.main_win.add_object( outline, self.midpoint_x - self.ship_space - self.p1.width, midpoint_y - self.p1.height // 2 - 1 ) self.main_win.add_object( self.p2, self.midpoint_x + self.ship_space, midpoint_y - self.p2.height // 2 ) self.main_win.add_object( self.p1, 4, midpoint_y - self.p1.height // 2 ) self.main_win.add_object( self.p1.thruster, 2, midpoint_y + 1 ) self.main_win.display(0, 7) self.main_win.auto_refresh = False position = self.p1.scene.objects[self.p1.stacking_order] distance = self.midpoint_x - self.ship_space - position.x2 speed = 0.04 while distance > 0: self.main_win.move_relative(self.p1, x=1) self.main_win.move_relative(self.p1.thruster, x=1) self.p1.thruster.update() self.main_win.pan(x=1) self.main_win.refresh() time.sleep(speed) if distance == 40: self.main_win.hide(self.p1.thruster) if distance < 40: speed += 0.005 distance -= 1 msg = Alert('!!! WARNING !!!\nENEMY WEAPONS LOCKED') msg.show(self.main_win) self.main_win.refresh() time.sleep(3) msg.hide() self.main_win.refresh()
def on_button_add_clicked(self, widget): addTodoDialog = AddTodoDialog(_('Add task')) if addTodoDialog.run() == Gtk.ResponseType.ACCEPT: todo = addTodoDialog.get_task() if not todo: Alert.show_alert(_('Fill your task'), _('You must specify a text for the task')) else: self.todos.add_item(todo) addTodoDialog.destroy()
def test_action_is_executed_when_rule2_matches(self): """""" exchange = {"GOOG": Stock("GOOG")} rule = MagicMock(spec=PriceRule) rule.matches.return_value = True rule.depends_on.return_value = {"GOOG"} action = MagicMock() alert = Alert("sample alert", rule, action) alert.connect(exchange) exchange["GOOG"].update(datetime(2014, 2, 10), 11) action.execute.assert_called_with("sample alert")
def temp_alert(self, data): """ Method that instantiates Alert object and calls its method for sending alert email to a specified address. :param data: Data about the state of the instrument :type data: dict :return: :rtype: NoneType """ alert = Alert(self.settings["receiver"], self.settings["sender"], self.settings["username"], self.settings["password"]) sleep(5) alert.send_msg(*alert.format_temperature_alert_msg(data))
def on_time_button_clicked(self, widget): if self.switch.get_active(): Alert.show_alert(_('Your task is completed'), _('Mark as uncompleted and continue')) else: self.stop_siblings_if_started() self.track_time() widget.set_image( Gtk.Image.new_from_icon_name(self.get_started_at_icon(), Gtk.IconSize.BUTTON)) self.set_todo(self.todo) self.get_toplevel().indicator.set_icon_tracktime( self.get_started_at())
def __init__(self, vendor_name, logger): self.logger = logger self.vendor_name = vendor_name self.items_json_path = os.path.dirname(__file__) + '/../vendors/' + vendor_name.lower().replace(' ', '_') + '/items.json' self.alert = Alert(logger) self.session = FuturesSession() if os.path.isfile(self.items_json_path): with open(self.items_json_path, 'r') as file: json_data = json.load(file) self.items_to_check = json_data['items'] self.stores_to_check = json_data['stores'] else: raise IOError('File not found \'{}\''.format(self.items_json_path))
def _openAlertWindow(self, str_Msg, str_Title): self.mask = MaskWidget(self) self.mask.show() self.alert = Alert(str_Msg, str_Title) self.alert.move( self.geometry().x() + self.geometry().width() / 2 - self.alert.geometry().width() / 2, self.geometry().y() + self.geometry().height() / 2 - self.alert.geometry().height() / 2) result = self.alert.exec_() self.mask.close() return result
def __get_pull_requests(self, repository_name, feature_name=None, only_active=False): if repository_name not in self.settings['repo_id']: Alert.show("Couldn't find this repository on your TFS") return [] auth = self.__get_auth() baseUrl = self.settings['url'] repo_id = self.settings['repo_id'][repository_name] feature_filter = '&sourceRefName=refs/heads/' + feature_name if feature_name else "" pull_requests = requests.get(baseUrl + '/_apis/git/repositories/' + repo_id + '/pullRequests?api-version=2.0&status=active' + feature_filter, auth=auth).json()['value'] if not only_active: pull_requests = pull_requests + requests.get(baseUrl + '/_apis/git/repositories/' + repo_id + '/pullRequests?api-version=2.0&status=completed' + feature_filter, auth=auth).json()['value'] pull_requests = pull_requests + requests.get(baseUrl + '/_apis/git/repositories/' + repo_id + '/pullRequests?api-version=2.0&status=abandoned' + feature_filter, auth=auth).json()['value'] return pull_requests
def handle_position(message): """Receive position data from the IB/Risk websocket connection, store the new positions, check for alerts, and send to the right user on the frontend""" logger.info(message) token, data, user = parse_message(message) if user: alerts = Alert.objects(user=user) original_number_alerts = alerts.count() positions = Position.create_positions(user, data) position_data_formatted = marshal(list(positions), position_schema) #logger.info([user, 'EMIT to', user.websocket_session_id]) emit('frontend_position', position_data_formatted, room=user.websocket_session_id) for alert in alerts: alert_event = alert.check() if alert_event: alerts = Alert.objects(user=user) alert_events = AlertEvent.objects(user=user) alert_data_formatted = marshal(list(alerts), alert_schema) alert_events_data_formatted = marshal(list(alert_events), alert_event_schema) alert_event_data_formatted = marshal(alert_event, alert_event_schema) emit('frontend_alerts', alert_data_formatted, room=user.websocket_session_id) emit('frontend_alert_events', alert_events_data_formatted, room=user.websocket_session_id) emit('frontend_alert_event', alert_event_data_formatted, room=user.websocket_session_id) alerts = Alert.objects(user=user) alert_data_formatted = marshal(list(alerts), alert_schema) if alerts.count() != original_number_alerts: emit('frontend_alerts', alert_data_formatted, room=user.websocket_session_id) return { "status": "success", "position": data, "token": token, }
def run(self): try: self._init_menu() self.music = Music(self.core, self.config['default_tracks'], self.config['default_preset']) self.display = DisplayWithPowerSaving( self.config['display_min_brightness'], self.config['display_max_brightness'], self.config['display_off_time_from'], self.config['display_off_time_to']) self.gpio = Gpio( self.config['buttons_enabled'], self.play_stop_music, self._on_menu_click, self._on_menu_click_left, self._on_menu_click_right, self.config['light_sensor_enabled'], self._on_light_sensor, self.config['relay_enabled']) self.ir_sender = IrSender(self.config['ir_remote'], self.gpio.switch_relay) self.ir_receiver = IrReceiver( self.config['ir_receiver_enabled'], self.play_stop_music, self._on_menu_click, self._on_menu_click_left, self._on_menu_click_right, self.music.decrease_volume, self.music.increase_volume, self.run_alert, self._on_change_preset) self.timer_on = TimerOn(self.play_music) self.timer_off = TimerOff(self.stop_music) self.alert = Alert(self.music, self.ir_sender, self.config['alert_files']) self.timer_alert = TimerAlert(self.run_alert) self.time = Time() self.date = Date([self.timer_on, self.timer_off, self.timer_alert]) self.menu = Menu(self.display, self.MENU, [ self.time, self.date, self.timer_on, self.timer_off, self.timer_alert ]) while True: self.menu.run() if (self.stopped()): break else: sleep(1) except Exception as inst: logging.error(inst) finally: self.ir_sender.stop() self.ir_receiver.stop() self.display.shutdown() self.gpio.cleanup()
def test_alert(stats_good, stats_bad): a = Alert(stats_good, 1, 'test') a.do_work() assert (a.flag_alert is False) b = Alert(stats_bad, 1, 'test') b.do_work() assert (b.flag_alert is True)
def get_attack_config(attack_name): config_json = Config.get_config() if not config_json.get(Setting.SYSTEM_MODE): Alert.add_alert( alert_type='ERROR', event='Could not find \'system_mode\' on config.json') return None elif config_json[Setting.SYSTEM_MODE] == 'no_action': return None elif config_json[Setting.SYSTEM_MODE] != 'per_attack': return { 'action': config_json['system_mode'], 'report_type': 'WARN' } elif not config_json.get('attack_types'): Alert.add_alert( alert_type='ERROR', event='Could not find \'attack_types\' on config.json') return None else: for attack_type in config_json['attack_types']: if attack_type.get('name') == attack_name: if not attack_type.get('per_attack_action'): Alert.add_alert( alert_type='ERROR', event= 'No \'per_attack_action\' found for \'%s\' on config.json' % attack_name) elif not attack_type.get('report_type'): Alert.add_alert( alert_type='ERROR', event= 'No \'report_type\' found for \'%s\' on config.json' % attack_name) elif attack_type['per_attack_action'] == 'no_action': return None else: return { 'action': attack_type['per_attack_action'], 'report_type': attack_type['report_type'] } Alert.add_alert( alert_type='ERROR', event='Could not find attack \'%s\' on config.json' % attack_name) return None
def clear_history(self, widget): widget.set_sensitive(False) result = Alert.show_alert("Are you sure?", "You will remove all history", True) if result == Gtk.ResponseType.OK: todotxtio.to_file(self.todo_histoy, []) widget.set_sensitive(True)
def get_alerts(self): ''' Public method that parses ''' emptyfeed = "There are no active watches, warnings or advisories" alerts = [] if emptyfeed in str(self._raw_cap): pass else: main_dom = minidom.parseString(self._raw_cap) xml_entries = main_dom.getElementsByTagName('entry') # title is currently first so we can detect an empty cap feed for dom in xml_entries: #parse the entry to a temp 'entry' dict entry = self._parse_entry(dom) # perform some cleanup before creating an object #entry['locations'] = self.build_locations(entry) # FIXME: remove? entry['target_areas'] = self.build_target_areas(entry) alert = Alert(entry) alerts.append(alert) del entry del alert return alerts
def create_task(self, task_name): doc_name = input(Alert().messages['document_name']) path = self.path(doc_name) if path.exists(): _id = self.generate_task_id(doc_name) read_text = self.is_there_content( path.read_text() ) new_content = f'{read_text}{_id} - {task_name} - {datetime.datetime.now()}' path.write_text(new_content) print(Alert().messages['task_created']) else: create_document = input(Alert().messages['do_you_wanna_create_it']) if create_document.upper() == 'Y' or len(create_document) == 0: self.create_document(doc_name).write_text(f'{1} - {task_name} - {datetime.datetime.now()}') print(Alert().messages['task_created'])
def _parse_config(self, xml_config): logging.info('Hawkeye: Parsing config') clients = [] parsed = xmltodict.parse(xml_config) clients_config = parsed['root']['client'] for client in clients_config: ip_address = client['@ip'] port = int(client['@port']) username = client['@username'] password = client['@password'] email = client['@mail'] alerts = [] alerts_db_array = [] for alert_config in client['alert']: alerts.append(Alert(alert_config['@type'], alert_config['@limit'])) alerts_db_array.append([alert_config['@type'], alert_config['@limit']]) client_instance = self.db_driver.retrieve('hawkeye_db', 'clients', 'ip_address', ip_address) print('client_instance', client_instance) if client_instance is None: data = { 'ip_address': ip_address, 'port': port, 'username': username, 'password': password, 'email': email, 'alerts': alerts_db_array } clients.append(Client(ip_address, port, username, password, email, alerts)) return clients
def refresh_data(self): self.store.clear() query = 'SELECT * FROM %s' % self.table if self.where: query += ' WHERE %s' % self.where if self.order: query += ' ORDER BY %s %s' % (self.order, self.order_direction) query += ' LIMIT %s OFFSET %s' % (self.row_size, self.page * self.row_size) try: cursor = self.conn.cursor() cursor.execute(query) self.conn.commit() for row in cursor.fetchall(): data = [] for i, val in enumerate(row): if self.columns[i](val) == 'None': data.append(None) else: data.append(self.columns[i](val)) self.store.append(data) except DatabaseError as e: Alert(e.message, self.data_tree.get_toplevel()) self.conn.rollback() self.data_tree.show_all()
def test_send_email_mock(self): self.mon.mailer = Mock() self.mon.mailer.send.return_value = {} self.assertTrue(self.mon.send_email(Alert("test", "msg"))) # assert ensure_wifi_mock.called assert self.mon.mailer.login.called assert self.mon.mailer.send.called assert self.mon.mailer.close.called
def test_send_email_mock_failed_send_false(self): self.mon.ensure_wifi = Mock() self.mon.mailer = Mock() self.mon.mailer.send.return_value = False self.assertFalse(self.mon.send_email(Alert("test1", "msg1"))) assert self.mon.mailer.login.called assert self.mon.mailer.send.called assert self.mon.mailer.close.called
def test_send_email_mock_failed_login(self): self.mon.ensure_wifi = Mock() self.mon.mailer = Mock() self.mon.mailer.login.side_effect = socket.gaierror self.assertFalse(self.mon.send_email(Alert("test1", "msg1"))) assert self.mon.mailer.login.called assert self.mon.mailer.login.not_called assert self.mon.mailer.close.called
def on_text_edit(self, widget, row, text, column_num): if self.data_tree.get_column(0).get_title() != 'id': Alert( 'Unable to update because we can\'t handle a missing ID column. TODO fix this' ) self.store[row][column_num] = text column = self.data_tree.get_column(column_num) column_name = column.get_title().replace('__', '_') try: cursor = self.conn.cursor() cursor.execute('UPDATE %s SET %s=\'%s\' WHERE id=%s' % (self.table, column_name, text, self.store[row][0])) self.conn.commit() except DatabaseError as e: Alert(e.message, self.data_tree.get_toplevel()) self.conn.rollback()
async def create_alert(user): ''' Creates a scheduled alert from user input ''' alert = Alert(user["name"], user["alert"][0], user["alert"][1], user["alert"][2], user["alert"][3]) db["Alerts"].append(alert)
def read_document(self, doc_name): path = self.path(doc_name) if not path.exists(): print(Alert().messages['document_does_not_exist']) return False else: print(path.read_text()) return True
def handle_noargs(self, **options): alert = Alert() some_time_ago = datetime.datetime.now() - time.timedelta(minutes=15) yesterday = datetime.datetime.now() - time.timedelta(days=1, minutes=15) warnings = [] for a in Account.objects.all(): if a.last_ping < some_time_ago: warnings.append('Account %s is not sending updates.' % str(a)) for pair in Pair.objects.filter(is_active=True): if Bar.objects.filter(pair__id=pair.id, broker_account__id=a.id).count() > 0: last_bar = Bar.objects.filter(pair__id=pair.id, broker_account__id=a.id).order('created_at')[-1] if last_bar.created_at < yesterday: warnings.append('Expected new %s bar from %s by now.' % (str(pair.name), str(a))) if len(warnings) > 0: alert.warning("\n".join(warnings))
def send_alerts(): sent = [] with ConnectionContext(safe=False): for alert in Alert.alerts_to_send(): try: send_email(**alert.email_data) alert.update_sent() sent.append(alert.email) except ConnectionError: pass return jsonify({'emails_sent': sent})
def start (self): """Creates the socket and starts the threads""" try: self.piglow = PiGlow () except IOError as e: if e[0] == errno.EACCES: print >> sys.stderr, "Permission denied, try running as root" else: print >> sys.stderr, "Unknown error accessing the PiGlow" sys.exit (1) self.piglow.all (0) self.clock = Clock (self.piglow) self.alert = Alert (self.piglow) self.in_progress = In_Progress (self.piglow) address = (self.cfg.HOST, self.cfg.PORT) serversock = socket (AF_INET, SOCK_STREAM) serversock.setsockopt (SOL_SOCKET, SO_REUSEADDR, 1) serversock.bind (address) serversock.listen (5) self.check_jobs_thread = Thread (None, self.check_jobs, None, ()) self.socket_manager_thread = Thread (None, self.socket_manager, None, (serversock, )) self.start_threads () while self.running == True: sleep (1) self.stop ()
def show(message): Alert.show(message) click.confirm("Do you want to continue?", abort=True)
class Backup: def __init__(self, access_token=None): self.digital_ocean = access_token self.report = "" config_file = open("config.json", "r") self.backup_data = json.load(config_file) self.alert = Alert(self.backup_data["femail"], self.backup_data["temail"]) def print_snapshots(self, droplet=None): if droplet is None: return None self.report += "[Snapshots for:] " + droplet.name + "\n" for snap in droplet.get_snapshots(): self.report += str(snap) + "\n" def snapshot(self, droplet=None): if droplet is None: return None try: # if the droplet is active we must power of the droplet and then # make the snapshot and then power on again if droplet.status == "active": try: self.report += "[Power off:] " + droplet.name + "\n" # attempt grateful shutdown droplet.shutdown() # now we must refresh the droplet state droplet = self.digital_ocean.droplet.get(droplet.id) timeout = 0 while droplet.status != "off" and timeout < 20: # try to see if is power off droplet = self.digital_ocean.droplet.get(droplet.id) # wait 1 sec time.sleep(1) # now power off droplet.power_off() time.sleep(20) # now we must refresh the droplet state droplet = self.digital_ocean.droplet.get(droplet.id) except pyocean.exceptions.DOException as e: if e.code is not 422: self.report += ('ERROR: %s' % e) self.report += "[Create snapshot for:] " + droplet.name + "\n" droplet.create_snapshot(droplet.name + str(datetime.datetime.now().day) + str(datetime.datetime.now().month) + str(datetime.datetime.now().year)) # now we must refresh the droplet state droplet = self.digital_ocean.droplet.get(droplet.id) # print all the snapshots taken so far self.print_snapshots(droplet) time.sleep(20) except pyocean.exceptions.DOException as e: self.report += ('ERROR: %s' % e) @staticmethod def need_to_backup(droplet=None): if droplet is None: return False # get a list of snapshots snaps = [snap for snap in droplet.get_snapshots()] # if the last one snapshot has a today date, it don't need to be backup if len(snaps) == 0: return True return snaps[-1].name != (droplet.name + str(datetime.datetime.now().day) + str(datetime.datetime.now().month) + str(datetime.datetime.now().year)) def clean_snapshots(self, droplet=None): if droplet is None: return None snaps = [snap for snap in droplet.get_snapshots()] if len(snaps) <= self.backup_data["max_snaps"]: self.report += "[No need to clean snaps for:] " + droplet.name + "\n" else: while len(snaps) > self.backup_data["max_snaps"]: self.report += "[TASK: Destroying snap:] " + snaps[0].name + "\n" snaps[0].destroy() self.report += "[DONE: left:] " + str(len(snaps) - (self.backup_data["max_snaps"] + 1)) + "\n" # refresh the list snaps = [snap for snap in droplet.get_snapshots()] return self.report def run(self): try: for account in self.backup_data["accountsList"]: self.digital_ocean = pyocean.DigitalOcean(account) for droplet in self.digital_ocean.droplet.all(): # refresh the state of the digital ocean droplet droplet = self.digital_ocean.droplet.get(droplet.id) # if need to be backup the droplet must be made a snapshot to the droplet if self.need_to_backup(droplet): self.snapshot(droplet) self.clean_snapshots(droplet) else: self.report += "[Snapshot already taken for:] " + droplet.name + "\n" # see if apache is running host = droplet.networks['v4'][0]['ip_address'] port = 80 try: socket.socket().connect((host, port)) except socket.error: self.alert.send_alert_droplet_down(droplet) self.report += "\n" # make all droplets active, they must be active for droplet in self.digital_ocean.droplet.all(): # refresh the state of the digital ocean droplet droplet = self.digital_ocean.droplet.get(droplet.id) if droplet.status == "off": try: droplet.power_on() except pyocean.exceptions.DOException as e: if e.code is 422: continue else: self.report += ('ERROR: %s' % e) except pyocean.exceptions.DOException as e: self.report += ('ERROR: %s' % e) self.alert.send_report(self.report)
def lose_animation(self): msg = Alert('YOUR SHIP HAS BEEN DESTROYED') msg.show(self.main_win) time.sleep(5) msg.hide()
class PiGlow_Status_Server: def __init__ (self): self.cfg = PiGlow_Status_Config () self.commands = PiGlow_Status_Commands () self.idle_job = self.commands.CLOCK self.jobs = [] self.running = None self.locked_thread = None self.check_jobs_thread = None self.socket_manager_thread = None self.piglow = None self.clock = None self.alert = None self.in_progress = None self.job_interval = 0.1 self.quiet_time = False def start (self): """Creates the socket and starts the threads""" try: self.piglow = PiGlow () except IOError as e: if e[0] == errno.EACCES: print >> sys.stderr, "Permission denied, try running as root" else: print >> sys.stderr, "Unknown error accessing the PiGlow" sys.exit (1) self.piglow.all (0) self.clock = Clock (self.piglow) self.alert = Alert (self.piglow) self.in_progress = In_Progress (self.piglow) address = (self.cfg.HOST, self.cfg.PORT) serversock = socket (AF_INET, SOCK_STREAM) serversock.setsockopt (SOL_SOCKET, SO_REUSEADDR, 1) serversock.bind (address) serversock.listen (5) self.check_jobs_thread = Thread (None, self.check_jobs, None, ()) self.socket_manager_thread = Thread (None, self.socket_manager, None, (serversock, )) self.start_threads () while self.running == True: sleep (1) self.stop () def stop (self): """Closes the threads and returns""" self.stop_threads () self.piglow.all (0) def start_threads (self): """Starts the threads""" self.running = True self.check_jobs_thread.start () self.socket_manager_thread.start () def stop_threads (self): """Stops the threads""" self.running = False self.unlock () try: self.check_jobs_thread.join () except (KeyboardInterrupt, SystemExit): pass try: self.socket_manager_thread.join () except (KeyboardInterrupt, SystemExit): pass def check_jobs (self): """Performs the actions in the job list""" while self.running == True: if self.quit_requested (): self.running = False break if self.entering_quiet_time () == True: self.unlock () self.piglow.all (0) if self.in_quiet_time () == False: if self.locked_thread is None: # No currently locking jobs, we can process the next job in the list as # normal or run the idle task if none are scheduled self.run_jobs () else: # A locking job is currently running, screen the job list for tasks # relating to it. self.check_locked_jobs () sleep (self.job_interval) def quit_requested (self): """Returns true if the quit command is in the job list""" for job in self.jobs: if job[0] == self.commands.QUIT: return True return False def check_locked_jobs (self): """Goes through the job list searching for tasks relating to the current locked job""" jobs = self.jobs self.jobs = [] for job in jobs: if job[0] == self.commands.CYCLE: try: self.in_progress.set_speed (job[1]) except IndexError: pass elif job[0] == self.commands.UNLOCK: self.unlock () elif job[0] == self.commands.OFF: self.unlock () self.jobs.append (job) else: self.jobs.append (job) def run_jobs (self): """First the first job in the list or the current idle job""" if len (self.jobs) > 0: job = self.jobs[:1].pop () self.jobs = self.jobs[1:] self.handle_job (job) else: if self.idle_job is not None: self.run_idle_job () else: self.piglow.all (0) def run_idle_job (self): """Runs the current idle job""" if self.idle_job == self.commands.CLOCK: self.clock.run () def handle_job (self, job): """Performs the given job""" command = job[:1].pop () args = job[1:] if command == self.commands.QUIT: self.running = False elif command == self.commands.CYCLE: self.locked_thread = self.in_progress if len (args) > 0: self.in_progress.set_speed (args[0]) self.in_progress.start () elif command == self.commands.ALERT: self.alert.show (*args) elif command == self.commands.OFF: self.idle_job = None elif command == self.commands.CLOCK: self.idle_job = self.commands.CLOCK def unlock (self): """Stops the currently locking thread""" if self.locked_thread is None: return self.locked_thread.stop () self.locked_thread = None def socket_manager (self, serversock): """Creates handlers for new data given to this process via the socket""" rlist = [serversock] wlist = [] xlist = [] while self.running == True: readable, writable, errored = select.select (rlist, wlist, xlist, self.cfg.TIMEOUT) for s in readable: if s is serversock: clientsock, addr = serversock.accept () self.socket_buffer_handler (clientsock) def socket_buffer_handler (self, clientsock): """Handles data in the socket buffer""" data = clientsock.recv (self.cfg.BUFF).rstrip () command = data.split (" ") if command == self.commands.CLOSE: clientsock.close () else: self.add_job (command) def add_job (self, job): """Adds a job to the list""" if self.cfg.quiet_time () == False or job == self.command.QUIT: self.jobs.append (job) def entering_quiet_time (self): """Returns true if we're entering quiet time""" return self.quiet_time == False and self.cfg.quiet_time () == True def in_quiet_time (self): """Returns true if we're in quiet time""" self.quiet_time = self.cfg.quiet_time () return self.quiet_time