Skip to content

Commit 5d0fdad

Browse files
author
xuwenyihust
committed
Added src/stream_monitor/fake_log_stream.py.
1 parent 749555b commit 5d0fdad

File tree

1 file changed

+184
-0
lines changed

1 file changed

+184
-0
lines changed
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
from src.fake_log_gen import fake_log_gen
2+
import socket
3+
4+
import random
5+
import json
6+
import logging
7+
import argparse
8+
import asyncio
9+
import datetime
10+
import time
11+
from asyncio import coroutine
12+
import numpy
13+
14+
15+
class fake_access_stream(fake_log_gen.fake_access_gen):
16+
17+
def run(self):
18+
#super(fake_access_stream, self).__init__(log, config, mode)
19+
# Create a TCP/IP socket object
20+
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
21+
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
22+
# Get local machine name
23+
host = socket.gethostbyname(socket.gethostname())
24+
print('>>> Host Name:\t%s' % str(host))
25+
# Reserve a hst for your service
26+
port = 5555
27+
server_addr = (host, port)
28+
# Bind the socket with the server address
29+
self.s.bind(server_addr)
30+
print('>>> Listening on port:\t%s' % str(port))
31+
# Calling listen() puts the socket into server mode
32+
self.s.listen(5)
33+
print('>>> Waiting for client connection')
34+
# accept() waits for an incoming connection
35+
# Establish connection with client
36+
self.client, self.addr = self.s.accept()
37+
print('>>> Received request from ' + str(self.addr))
38+
39+
super(fake_access_stream, self).run()
40+
41+
@coroutine
42+
def heartbeat_lines(self):
43+
while True:
44+
t = datetime.datetime.now().strftime('%d/%b/%Y:%H:%M:%S -0700')
45+
data = '- - - [%s] "%s" - -' % (t, self.config["heartbeat"]["message"])
46+
self.log.info(data)
47+
self.client.send((data+'\n').encode())
48+
49+
yield from asyncio.sleep(int(self.config["heartbeat"]["interval"]))
50+
51+
@coroutine
52+
def access_lines(self):
53+
while True:
54+
ip = '.'.join(str(random.randint(0, 255)) for i in range(4))
55+
user_identifier = '-'
56+
user_id = self.user_ids[random.randint(0,len(self.user_ids)-1)]
57+
t = datetime.datetime.now().strftime('%d/%b/%Y:%H:%M:%S -0700')
58+
59+
method = numpy.random.choice(self.methods, p=self.methods_dist)
60+
resource = self.resources[random.randint(0, len(self.resources)-1)]
61+
version = self.versions[random.randint(0, len(self.versions)-1)]
62+
msg = method + " " + resource + " " + version
63+
code = numpy.random.choice(self.codes, p=self.codes_dist)
64+
size = random.randint(1024, 10240)
65+
data = '%s %s %s [%s] "%s" %s %s' % (ip, user_identifier, user_id, t, msg, code, size)
66+
self.log.info(data)
67+
self.client.send((data+'\n').encode())
68+
yield from asyncio.sleep(random.uniform(self.access_min, self.access_max))
69+
70+
71+
class fake_error_stream(fake_log_gen.fake_error_gen):
72+
73+
def run(self):
74+
#super(fake_error_stream, self).__init__(log, config, mode)
75+
# Create a TCP/IP socket object
76+
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
77+
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
78+
# Get local machine name
79+
host = socket.gethostbyname(socket.gethostname())
80+
print('>>> Server Host Name:\t%s' % str(host))
81+
# Reserve a hst for your service
82+
port = 5555
83+
server_addr = (host, port)
84+
# Bind the socket with the server address
85+
self.s.bind(server_addr)
86+
print('>>> Server is listening on port:\t%s' % str(port))
87+
# Calling listen() puts the socket into server mode
88+
self.s.listen(5)
89+
print('>>> Server is waiting for client connection')
90+
# accept() waits for an incoming connection
91+
# Establish connection with client
92+
self.client, self.addr = self.s.accept()
93+
print('>>> Server received request from ' + str(self.addr))
94+
95+
super(fake_error_stream, self).run()
96+
97+
@coroutine
98+
def heartbeat_lines(self):
99+
while True:
100+
data = "[-] [-] " + self.config["heartbeat"]["message"]
101+
self.log.info(data)
102+
self.client.send((data+'\n').encode())
103+
yield from asyncio.sleep(int(self.config["heartbeat"]["interval"]))
104+
105+
@coroutine
106+
def warn_lines(self):
107+
while True:
108+
pid = ''.join(str(random.randint(0, 9)) for i in range(5))
109+
tid = ''.join(str(random.randint(0, 9)) for i in range(10))
110+
ip = '.'.join(str(random.randint(0, 255)) for i in range(4))
111+
# "%a %b %d %H:%M:%S %Y"
112+
now = time.localtime()
113+
asctime = '[' + time.strftime("%a %b %d %H:%M:%S %Y", now) + '] '
114+
level_name = '[ERROR] '
115+
msg = "[pid %s:tid %s] [client %s] %s" % (pid, tid, ip, self.warnings[random.randrange(len(self.warnings))])
116+
data = asctime + level_name + msg
117+
self.log.warning(data)
118+
self.client.send((data+'\n').encode())
119+
yield from asyncio.sleep(random.uniform(self.warn_min, self.warn_max))
120+
121+
@coroutine
122+
def error_lines(self):
123+
while True:
124+
pid = ''.join(str(random.randint(0, 9)) for i in range(5))
125+
tid = ''.join(str(random.randint(0, 9)) for i in range(10))
126+
ip = '.'.join(str(random.randint(0, 255)) for i in range(4))
127+
now = time.localtime()
128+
asctime = '[' + time.strftime("%a %b %d %H:%M:%S %Y", now) + '] '
129+
level_name = '[WARNING] '
130+
msg = "[pid %s:tid %s] [client %s] %s" % (pid, tid, ip, self.errors[random.randrange(len(self.errors))])
131+
data = asctime + level_name + msg
132+
self.log.error(data)
133+
self.client.send((data+'\n').encode())
134+
yield from asyncio.sleep(random.uniform(self.error_min, self.error_max))
135+
136+
def main():
137+
parser = argparse.ArgumentParser()
138+
parser.add_argument("-o", help="fake logfile")
139+
parser.add_argument("-m", help="log mode")
140+
args = parser.parse_args()
141+
142+
# Identify the log format
143+
mode = args.m
144+
if mode not in ['error', 'access']:
145+
print('Argument error.')
146+
147+
# Instantiate the logger
148+
log = logging.getLogger('Gen')
149+
# Set the level
150+
logging.basicConfig(level=logging.INFO)
151+
# Instantiate a file Handler
152+
out = logging.FileHandler(args.o)
153+
# Instantiate a Formatter
154+
# Format the time string
155+
if mode == 'error':
156+
#log_format = logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s", "%a %b %d %H:%M:%S %Y")
157+
log_format = logging.Formatter("%(message)s")
158+
else:
159+
log_format = logging.Formatter("%(message)s")
160+
# Set the Formatter for this Handler to form
161+
out.setFormatter(log_format)
162+
# Add the file Handler 'out' to the logger'log'
163+
log.addHandler(out)
164+
165+
# Load the configure json file to a dict
166+
with open("../../config/fake_log_gen.json") as config_file:
167+
config = json.load(config_file)
168+
169+
# Instantiate a fake log generator
170+
if mode == 'access':
171+
log_streamer = fake_access_stream(log, config, mode)
172+
else:
173+
log_streamer = fake_error_stream(log, config, mode)
174+
175+
log_streamer.run()
176+
177+
178+
if __name__ == "__main__":
179+
main()
180+
181+
182+
183+
184+

0 commit comments

Comments
 (0)