elasticsearch-secure-nodes/generate/hamlet.py

raw link view readme
1 #+ copyright (c) 2015-2018 David Betz
2
3 import datetime
4 import sys, os
5 from random import randint
6 from time import time
7 import requests
8 import json
9 import socket
10 import fcntl
11 import struct
12
13 from random import randrange, randint
14
15 with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'hamlet_distinct.t'), 'r') as f:
16 hamlet_all = f.read()
17
18 genData = hamlet_all.split(' ')
19
20 def hamlet(count):
21 return genData[randint(1, len(genData) - 1)] + ('' if count == 1 else ' ' + hamlet(count - 1))
22
23 interface = b'eth0'
24 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
25 address = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', interface[:15]))[20:24])
26
27 endpoint = 'http://{}:9200/librarygen'.format(address)
28
29 print(endpoint)
30
31 def call(verb, endpoint, obj = None):
32 headers = {
33 "Accept": "application/json",
34 }
35 endpoint = endpoint.lower()
36
37 verb = verb.lower()
38
39 jsonData = json.dumps(obj)
40
41 if verb == 'get':
42 response = requests.get(endpoint, headers=headers)
43 elif verb == 'post':
44 response = requests.post(endpoint, headers=headers, data=jsonData)
45 elif verb == 'put':
46 response = requests.put(endpoint, headers=headers, data=jsonData)
47 elif verb == 'delete':
48 response = requests.delete(endpoint, headers=headers)
49
50 return response
51
52 def create_date():
53 return '{}-{:02}-{:02}T{:02}:{:02}:{:02}Z'.format(randint(2006, 2016), randint(1, 12), randint(1, 28), randint(0, 23), randint(0, 59), randint(0, 59))
54
55 call('PUT', endpoint, {
56 "settings": {
57 "index.mapping.single_type": True,
58 "number_of_replicas": 1,
59 "number_of_shards": 6
60 }
61 })
62
63 def run():
64 then = time()
65 count = 0
66 while True:
67 try:
68 item = {
69 "title": hamlet(4),
70 "authors": [hamlet(_) for _ in range(1, randrange(2,4))],
71 "editor": hamlet(1) if randrange(4) == 0 else None,
72 "abstract": hamlet(randrange(100, 400)),
73 "metadata": {
74 "pages": randrange(1,400),
75 "isbn": '9780' + str(randrange(100000000, 999999999)),
76 "genre": hamlet(1),
77 },
78 "created": create_date(),
79 "modified": create_date(),
80 }
81 call('POST', '{}/book'.format(endpoint), item)
82 count = count + 1
83 except KeyboardInterrupt:
84 now = time()
85 print('Stopped ({})'.format(count / (now - then)))
86 sys.exit(0)
87
88
89 if __name__ == '__main__':
90 run()
91