def log(request): ''' takes { url: string, line: string, text: string } returns { } ''' data = json.loads(request.POST['data']) if request.user.is_authenticated(): user = request.user else: user = None url = data.get('url', '').split('/static/')[-1] if 'text' in data: if len(url) > 1000: url = url[:997] + '...' l = models.Log( text=data['text'], line=int(data.get('line', 0)), url=url ) if user: l.user = user l.save() response = json_response() return render_to_json_response(response)
def post(self): data_point = float(self.request.get('logReading')) new_log = models.Log(sensor = self.request.get('sensor'), dateTime = datetime.datetime.strptime(self.request.get('sampleTime'), fmt), reading = data_point) new_log.put() logging.info('Logged a sensor reading') logging.info(self.request.get('sampleTime'))
def ten_minute_warning(): if not config['game_ongoing']: return l = models.Log() l.date = str(datetime.now()) l.game_day = helpers.get_game_day() l.msg = "10 minutes remaining in the day! Get those payments in!!!" l.target_channel_id = config['channels']['progress-announcements'] l.insert() models.save()
def log(self, channel, action, template, period): log = models.Log() log.channel = channel log.action = action log.template = template log.period = period log.ip_addr = func.INET_ATON(self.request.remote_ip) self.db.add(log) try: self.db.commit() except Exception: self.db.rollback()
def on_new_day(): if not config['game_ongoing']: return print("A new day dawns...") print("Moving teams") # Each team tries to move to a new location! progress_log = [] for i in range(1, 4): progress_log.append(team_attempt_move(i)) progress_log.append("\n") # Send coins to players print("Updating player shares") update_shares() print("Paying players") pay_players() # Send daily message to progress-announcements channel with sql.connect('internal.sqlite3') as conn: msg = [] msg.append("A new day has begun! Welcome to day **{}**!\n".format( helpers.get_game_day())) msg.append("Here's what's happened since yesterday:\n") msg.append("```\n") if helpers.get_game_day() == 1: msg.append("The race began! All teams are currently in London\n") else: msg.append("\n".join(progress_log)) msg.append("```\n") # FIXME hardcoded team names... msg.append( "**Argent Boars**, here are your destination options for today:\n") msg.append(next_location_table(1)) msg.append("And for you, **Azure Wolves**:\n") msg.append(next_location_table(2)) msg.append("Finally, **Crimson Stallions**:\n") msg.append(next_location_table(3)) msg.append( "You've all already received your salaries and refunds, so get booking and good luck!" ) c = conn.cursor() log = models.Log() log.date = str(datetime.now()) log.game_day = helpers.get_game_day() log.msg = ''.join(msg) log.target_channel_id = config['channels']['progress-announcements'] # I hate this but it's better than my hackosaurus workaround c.execute( "INSERT INTO Log(date, game_day, msg, sent, target_channel_id) VALUES (?,?,?,?,?)", (log.date, log.game_day, log.msg, log.sent, log.target_channel_id)) conn.commit()
def check_request_ip(self, request): remote_ip = ipv6._unpack_ipv4(request.META['REMOTE_ADDR']) cache_entries = models.Cache.objects.filter(ip=remote_ip) if cache_entries.count() > 0: if sfs_settings.LOG_SPAM: log = models.Log(message="Spam received from %s" % remote_ip) log.save() return render(request, 'stopforumspam/denied.html', { "cache_entries": cache_entries, }, status=403)
def __log_request(request): ''' .method == .META['REQUEST_METHOD'] .encoding == None .path_info == .META['PATH_INFO'] ''' #pprint.pprint(request.META) if not settings.DEBUG: #if True: # 1. sanitize meta = request.META for k in meta.keys(): if k.islower(): del(meta[k]) # 2. save #models.Log(data=json.dumps(meta, indent=1, ensure_ascii=False)).save() models.Log( method=(request.META['REQUEST_METHOD']=='GET'), ip=request.META['REMOTE_ADDR'], path=request.META['PATH_INFO'][:254], agent=request.META.get('HTTP_USER_AGENT', 'noname')[:254], data=json.dumps(meta, indent=1, ensure_ascii=False) ).save()
def update_log(request): serial_add_script = os.path.join(script_path, "run.sh") serial_del_script = os.path.join(script_path, "end.sh") ret_dict = dict() if request.method == "POST": ret_dict["status"] = "FAIL" data = unicode_convert(request.POST.dict()) print "request data: {0}".format(data) save_data(debug_log_path, "request data: {0}".format(json.dumps(data))) opt = re.search(r'ADD|DELETE', data.keys()[0], re.IGNORECASE).group() key_ip = unicode_convert("%s[IP]" % opt) key_port = unicode_convert("%s[Port]" % opt) ip = data[key_ip] port = data[key_port] ret_dict["flag"] = opt filename = "%s_%s.log" % (ip, port) # The filename should be unique log = models.Log(ip=ip, port=port, filename=filename) try: log.full_clean() except ValidationError as e: # ret_dict["error"] = unicode_convert(e.message_dict) ret_dict["error"] = "Input error !" else: filter_res = models.Log.objects.filter(filename=filename) if opt == "ADD": """ # Don't care database !!! if filter_res: ret_dict["error"] = "[%s %s] Already monitored !" %(ip, port) """ serial_cmd = "bash %s serial %s %s %s" % (serial_add_script, ip, port, log_path) elif opt == "DELETE": """ # Don't care database !!! if not filter_res: ret_dict["error"] = "[%s %s] Not being collected !" %(ip, port) """ serial_cmd = "bash %s %s %s" % (serial_del_script, ip, port) else: serial_cmd = "false" # return not 0 if ret_dict.has_key("error"): ret_dict = unicode_convert(ret_dict) print "ret_dict: {0}".format(ret_dict) save_data(debug_log_path, "ret_dict: {0}".format(json.dumps(ret_dict))) return HttpResponse(json.dumps(ret_dict), content_type="application/json") process = "socat - TCP:{0}:{1}".format(ip, port) print "process: {0}".format(process) save_data(debug_log_path, "process: {0}".format(process)) location = judge_ip_location(ip) print "location: {0}".format(location) save_data(debug_log_path, "location: {0}".format(location)) ### Log server is Platform server ### if location == "Beijing": process_exist = check_process_exist(process, flag="local") print "process status: {0}".format(process_exist) save_data(debug_log_path, "process status: {0}".format(process_exist)) if opt == "DELETE": if process_exist == True: ret = run_cmd(serial_cmd) if ret[0] == 0: ret_dict["status"] = "OK" if filter_res: filter_res.delete() else: ret_dict[ "error"] = "[%s %s] Stop logging FAILED !" % ( ip, port) save_data(debug_log_path, ret[-1]) elif process_exist == False: ret_dict["status"] = "OK" if filter_res: filter_res.delete() else: ret_dict["status"] = "Unknown" if filter_res: filter_res.delete() elif opt == "ADD": if process_exist: ret_dict["status"] = "OK" if not filter_res: log.save() else: ping_ret = Remote.ping(ip) if ping_ret: ret = run_cmd(serial_cmd) if ret[0] == 0: ret_dict["status"] = "OK" if not filter_res: log.save() else: ret_dict[ "error"] = "[%s %s] Log collection FAILED !" % ( ip, port) save_data(debug_log_path, ret[-1]) else: ret_dict["error"] = "[%s] Connection FAIL !" % ip ### Log server is other server (Tianjin or Kunshan) ### else: remote_log_path, remote_add_script, remote_del_script = None, None, None server_ip, server_username, server_password = None, None, None if location == "Kunshan": server_ip = KS_server_ip server_username = KS_username server_password = KS_password remote_log_path = KS_log_path remote_add_script = os.path.join(KS_script_path, "run.sh") remote_del_script = os.path.join(KS_script_path, "end.sh") elif location == "Tianjin": server_ip = TJ_server_ip server_username = TJ_username server_password = TJ_password remote_log_path = TJ_log_path remote_add_script = os.path.join(TJ_script_path, "run.sh") remote_del_script = os.path.join(TJ_script_path, "end.sh") if server_ip: ping_server_ret = Remote.ping(server_ip) if ping_server_ret: process_exist = check_process_exist( process, "remote", server_ip, server_username, server_password) print "process status: {0}".format(process_exist) save_data(debug_log_path, "process status: {0}".format(process_exist)) if opt == "DELETE": if process_exist == True: remote_serial_cmd = "bash %s %s %s" % ( remote_del_script, ip, port) ret = Remote.ssh_run_cmd( remote_serial_cmd, server_ip, server_username, server_password) if ret[0] == 0: ret_dict["status"] = "OK" if filter_res: filter_res.delete() else: ret_dict[ "error"] = "[%s %s] Stop logging FAILED !" % ( ip, port) save_data(debug_log_path, ret[-1]) elif process_exist == False: ret_dict["status"] = "OK" if filter_res: filter_res.delete() else: ret_dict["status"] = "Unknown" if filter_res: filter_res.delete() elif opt == "ADD": if process_exist: ret_dict["status"] = "OK" if not filter_res: log.save() else: ping_ret = Remote.ping(ip) if ping_ret: remote_serial_cmd = "bash %s serial %s %s %s" % ( remote_add_script, ip, port, remote_log_path) ret = Remote.ssh_run_cmd( remote_serial_cmd, server_ip, server_username, server_password) if ret[0] == 0: save_data(debug_log_path, str(ret[-1])) ret_dict["status"] = "OK" if not filter_res: log.save() else: ret_dict[ "error"] = "[%s %s] Log collection FAILED !" % ( ip, port) save_data(debug_log_path, ret[-1]) else: ret_dict[ "error"] = "[%s] Connection FAIL !" % ip else: ret_dict[ "error"] = "[%s] Connection FAIL !" % server_ip else: ret_dict["error"] = "[%s] Unknown location !" % ip ret_dict = unicode_convert(ret_dict) print "ret_dict: {0}".format(ret_dict) save_data(debug_log_path, "ret_dict: {0}".format(json.dumps(ret_dict))) return HttpResponse(json.dumps(ret_dict), content_type="application/json") return render_to_response("Equipment/LogServer.html")
def add(self, event_type, event_desc, user=None, user_ip=None): log = models.Log(event_type=event_type, event_desc=event_desc, user=user, user_ip=user_ip) log.save()