-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathservice.py
More file actions
187 lines (151 loc) · 5.16 KB
/
service.py
File metadata and controls
187 lines (151 loc) · 5.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import json
import logging
import os
import sys
from logging.config import dictConfig
from client_entity import ClientEntity
from flask import Flask, request
from flask.logging import default_handler
from werkzeug.exceptions import HTTPException
# Import ldclient from parent directory
sys.path.insert(1, os.path.join(sys.path[0], '..'))
default_port = 8000
# logging configuration
dictConfig(
{
'version': 1,
'formatters': {
'default': {
'format': '[%(asctime)s] [%(name)s] %(levelname)s: %(message)s',
}
},
'handlers': {'console': {'class': 'logging.StreamHandler', 'formatter': 'default'}},
'root': {'level': 'INFO', 'handlers': ['console']},
'loggers': {
'ldclient': {
'level': 'INFO', # change to 'DEBUG' to enable SDK debug logging
},
'werkzeug': {'level': 'ERROR'}, # disable irrelevant Flask app logging
},
}
)
app = Flask(__name__)
app.logger.removeHandler(default_handler)
client_counter = 0
clients = {}
global_log = logging.getLogger('testservice')
@app.errorhandler(Exception)
def handle_exception(e):
# pass through HTTP errors
if isinstance(e, HTTPException):
return e
app.logger.exception(e)
return str(e), 500
@app.route('/', methods=['GET'])
def status():
body = {
'capabilities': [
'server-side',
'server-side-polling',
'all-flags-with-reasons',
'all-flags-client-side-only',
'all-flags-details-only-for-tracked-flags',
'big-segments',
'context-type',
'filtering',
'secure-mode-hash',
'tags',
'migrations',
'event-gzip',
'optional-event-gzip',
'event-sampling',
'polling-gzip',
'inline-context-all',
'instance-id',
'anonymous-redaction',
'evaluation-hooks',
'omit-anonymous-contexts',
'client-prereq-events',
'persistent-data-store-redis',
'persistent-data-store-dynamodb',
'persistent-data-store-consul',
'flag-change-listeners',
'flag-value-change-listeners',
]
}
return json.dumps(body), 200, {'Content-type': 'application/json'}
@app.route('/', methods=['DELETE'])
def delete_stop_service():
global_log.info("Test service has told us to exit")
os._exit(0)
@app.route('/', methods=['POST'])
def post_create_client():
global client_counter, clients
options = request.get_json()
client_counter += 1
client_id = str(client_counter)
resource_url = '/clients/%s' % client_id
client = ClientEntity(options['tag'], options['configuration'])
if client.is_initializing() is False and options['configuration'].get('initCanFail', False) is False:
client.close()
return "Failed to initialize", 500
clients[client_id] = client
return '', 201, {'Location': resource_url}
@app.route('/clients/<id>', methods=['POST'])
def post_client_command(id):
global clients
params = request.get_json()
client = clients[id]
if client is None:
return '', 404
command = params.get('command')
sub_params = params.get(command)
response = None
if command == "evaluate":
response = client.evaluate(sub_params)
elif command == "evaluateAll":
response = client.evaluate_all(sub_params)
elif command == "customEvent":
client.track(sub_params)
elif command == "identifyEvent":
client.identify(sub_params)
elif command == "flushEvents":
client.flush()
elif command == "secureModeHash":
response = client.secure_mode_hash(sub_params)
elif command == "contextBuild":
response = client.context_build(sub_params)
elif command == "contextConvert":
response = client.context_convert(sub_params)
elif command == "getBigSegmentStoreStatus":
response = client.get_big_segment_store_status()
elif command == "migrationVariation":
response = client.migration_variation(sub_params)
elif command == "migrationOperation":
response = client.migration_operation(sub_params)
elif command == "registerFlagChangeListener":
client.register_flag_change_listener(sub_params)
elif command == "registerFlagValueChangeListener":
client.register_flag_value_change_listener(sub_params)
elif command == "unregisterListener":
if not client.unregister_listener(sub_params):
return 'no listener with id "%s"' % sub_params['listenerId'], 400
else:
return '', 400
if response is None:
return '', 201
return json.dumps(response), 200
@app.route('/clients/<id>', methods=['DELETE'])
def delete_client(id):
global clients
client = clients[id]
if client is None:
return '', 404
client.close()
return '', 202
if __name__ == "__main__":
port = default_port
if sys.argv[len(sys.argv) - 1] != 'service.py':
port = int(sys.argv[len(sys.argv) - 1])
global_log.info('Listening on port %d', port)
app.run(host='0.0.0.0', port=port)