fengmiguoji commited on
Commit
84df80c
·
verified ·
1 Parent(s): f7f8f95

Upload api\configs\remote_settings_sources\apollo\client.py with huggingface_hub

Browse files
api//configs//remote_settings_sources//apollo//client.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import json
3
+ import logging
4
+ import os
5
+ import threading
6
+ import time
7
+ from collections.abc import Mapping
8
+ from pathlib import Path
9
+
10
+ from .python_3x import http_request, makedirs_wrapper
11
+ from .utils import (
12
+ CONFIGURATIONS,
13
+ NAMESPACE_NAME,
14
+ NOTIFICATION_ID,
15
+ get_value_from_dict,
16
+ init_ip,
17
+ no_key_cache_key,
18
+ signature,
19
+ url_encode_wrapper,
20
+ )
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class ApolloClient:
26
+ def __init__(
27
+ self,
28
+ config_url,
29
+ app_id,
30
+ cluster="default",
31
+ secret="",
32
+ start_hot_update=True,
33
+ change_listener=None,
34
+ _notification_map=None,
35
+ ):
36
+ # Core routing parameters
37
+ self.config_url = config_url
38
+ self.cluster = cluster
39
+ self.app_id = app_id
40
+
41
+ # Non-core parameters
42
+ self.ip = init_ip()
43
+ self.secret = secret
44
+
45
+ # Check the parameter variables
46
+
47
+ # Private control variables
48
+ self._cycle_time = 5
49
+ self._stopping = False
50
+ self._cache = {}
51
+ self._no_key = {}
52
+ self._hash = {}
53
+ self._pull_timeout = 75
54
+ self._cache_file_path = os.path.expanduser("~") + "/.dify/config/remote-settings/apollo/cache/"
55
+ self._long_poll_thread = None
56
+ self._change_listener = change_listener # "add" "delete" "update"
57
+ if _notification_map is None:
58
+ _notification_map = {"application": -1}
59
+ self._notification_map = _notification_map
60
+ self.last_release_key = None
61
+ # Private startup method
62
+ self._path_checker()
63
+ if start_hot_update:
64
+ self._start_hot_update()
65
+
66
+ # start the heartbeat thread
67
+ heartbeat = threading.Thread(target=self._heart_beat)
68
+ heartbeat.daemon = True
69
+ heartbeat.start()
70
+
71
+ def get_json_from_net(self, namespace="application"):
72
+ url = "{}/configs/{}/{}/{}?releaseKey={}&ip={}".format(
73
+ self.config_url, self.app_id, self.cluster, namespace, "", self.ip
74
+ )
75
+ try:
76
+ code, body = http_request(url, timeout=3, headers=self._sign_headers(url))
77
+ if code == 200:
78
+ if not body:
79
+ logger.error(f"get_json_from_net load configs failed, body is {body}")
80
+ return None
81
+ data = json.loads(body)
82
+ data = data["configurations"]
83
+ return_data = {CONFIGURATIONS: data}
84
+ return return_data
85
+ else:
86
+ return None
87
+ except Exception:
88
+ logger.exception("an error occurred in get_json_from_net")
89
+ return None
90
+
91
+ def get_value(self, key, default_val=None, namespace="application"):
92
+ try:
93
+ # read memory configuration
94
+ namespace_cache = self._cache.get(namespace)
95
+ val = get_value_from_dict(namespace_cache, key)
96
+ if val is not None:
97
+ return val
98
+
99
+ no_key = no_key_cache_key(namespace, key)
100
+ if no_key in self._no_key:
101
+ return default_val
102
+
103
+ # read the network configuration
104
+ namespace_data = self.get_json_from_net(namespace)
105
+ val = get_value_from_dict(namespace_data, key)
106
+ if val is not None:
107
+ self._update_cache_and_file(namespace_data, namespace)
108
+ return val
109
+
110
+ # read the file configuration
111
+ namespace_cache = self._get_local_cache(namespace)
112
+ val = get_value_from_dict(namespace_cache, key)
113
+ if val is not None:
114
+ self._update_cache_and_file(namespace_cache, namespace)
115
+ return val
116
+
117
+ # If all of them are not obtained, the default value is returned
118
+ # and the local cache is set to None
119
+ self._set_local_cache_none(namespace, key)
120
+ return default_val
121
+ except Exception:
122
+ logger.exception("get_value has error, [key is %s], [namespace is %s]", key, namespace)
123
+ return default_val
124
+
125
+ # Set the key of a namespace to none, and do not set default val
126
+ # to ensure the real-time correctness of the function call.
127
+ # If the user does not have the same default val twice
128
+ # and the default val is used here, there may be a problem.
129
+ def _set_local_cache_none(self, namespace, key):
130
+ no_key = no_key_cache_key(namespace, key)
131
+ self._no_key[no_key] = key
132
+
133
+ def _start_hot_update(self):
134
+ self._long_poll_thread = threading.Thread(target=self._listener)
135
+ # When the asynchronous thread is started, the daemon thread will automatically exit
136
+ # when the main thread is launched.
137
+ self._long_poll_thread.daemon = True
138
+ self._long_poll_thread.start()
139
+
140
+ def stop(self):
141
+ self._stopping = True
142
+ logger.info("Stopping listener...")
143
+
144
+ # Call the set callback function, and if it is abnormal, try it out
145
+ def _call_listener(self, namespace, old_kv, new_kv):
146
+ if self._change_listener is None:
147
+ return
148
+ if old_kv is None:
149
+ old_kv = {}
150
+ if new_kv is None:
151
+ new_kv = {}
152
+ try:
153
+ for key in old_kv:
154
+ new_value = new_kv.get(key)
155
+ old_value = old_kv.get(key)
156
+ if new_value is None:
157
+ # If newValue is empty, it means key, and the value is deleted.
158
+ self._change_listener("delete", namespace, key, old_value)
159
+ continue
160
+ if new_value != old_value:
161
+ self._change_listener("update", namespace, key, new_value)
162
+ continue
163
+ for key in new_kv:
164
+ new_value = new_kv.get(key)
165
+ old_value = old_kv.get(key)
166
+ if old_value is None:
167
+ self._change_listener("add", namespace, key, new_value)
168
+ except BaseException as e:
169
+ logger.warning(str(e))
170
+
171
+ def _path_checker(self):
172
+ if not os.path.isdir(self._cache_file_path):
173
+ makedirs_wrapper(self._cache_file_path)
174
+
175
+ # update the local cache and file cache
176
+ def _update_cache_and_file(self, namespace_data, namespace="application"):
177
+ # update the local cache
178
+ self._cache[namespace] = namespace_data
179
+ # update the file cache
180
+ new_string = json.dumps(namespace_data)
181
+ new_hash = hashlib.md5(new_string.encode("utf-8")).hexdigest()
182
+ if self._hash.get(namespace) == new_hash:
183
+ pass
184
+ else:
185
+ file_path = Path(self._cache_file_path) / f"{self.app_id}_configuration_{namespace}.txt"
186
+ file_path.write_text(new_string)
187
+ self._hash[namespace] = new_hash
188
+
189
+ # get the configuration from the local file
190
+ def _get_local_cache(self, namespace="application"):
191
+ cache_file_path = os.path.join(self._cache_file_path, f"{self.app_id}_configuration_{namespace}.txt")
192
+ if os.path.isfile(cache_file_path):
193
+ with open(cache_file_path) as f:
194
+ result = json.loads(f.readline())
195
+ return result
196
+ return {}
197
+
198
+ def _long_poll(self):
199
+ notifications = []
200
+ for key in self._cache:
201
+ namespace_data = self._cache[key]
202
+ notification_id = -1
203
+ if NOTIFICATION_ID in namespace_data:
204
+ notification_id = self._cache[key][NOTIFICATION_ID]
205
+ notifications.append({NAMESPACE_NAME: key, NOTIFICATION_ID: notification_id})
206
+ try:
207
+ # if the length is 0 it is returned directly
208
+ if len(notifications) == 0:
209
+ return
210
+ url = "{}/notifications/v2".format(self.config_url)
211
+ params = {
212
+ "appId": self.app_id,
213
+ "cluster": self.cluster,
214
+ "notifications": json.dumps(notifications, ensure_ascii=False),
215
+ }
216
+ param_str = url_encode_wrapper(params)
217
+ url = url + "?" + param_str
218
+ code, body = http_request(url, self._pull_timeout, headers=self._sign_headers(url))
219
+ http_code = code
220
+ if http_code == 304:
221
+ logger.debug("No change, loop...")
222
+ return
223
+ if http_code == 200:
224
+ if not body:
225
+ logger.error(f"_long_poll load configs failed,body is {body}")
226
+ return
227
+ data = json.loads(body)
228
+ for entry in data:
229
+ namespace = entry[NAMESPACE_NAME]
230
+ n_id = entry[NOTIFICATION_ID]
231
+ logger.info("%s has changes: notificationId=%d", namespace, n_id)
232
+ self._get_net_and_set_local(namespace, n_id, call_change=True)
233
+ return
234
+ else:
235
+ logger.warning("Sleep...")
236
+ except Exception as e:
237
+ logger.warning(str(e))
238
+
239
+ def _get_net_and_set_local(self, namespace, n_id, call_change=False):
240
+ namespace_data = self.get_json_from_net(namespace)
241
+ if not namespace_data:
242
+ return
243
+ namespace_data[NOTIFICATION_ID] = n_id
244
+ old_namespace = self._cache.get(namespace)
245
+ self._update_cache_and_file(namespace_data, namespace)
246
+ if self._change_listener is not None and call_change and old_namespace:
247
+ old_kv = old_namespace.get(CONFIGURATIONS)
248
+ new_kv = namespace_data.get(CONFIGURATIONS)
249
+ self._call_listener(namespace, old_kv, new_kv)
250
+
251
+ def _listener(self):
252
+ logger.info("start long_poll")
253
+ while not self._stopping:
254
+ self._long_poll()
255
+ time.sleep(self._cycle_time)
256
+ logger.info("stopped, long_poll")
257
+
258
+ # add the need for endorsement to the header
259
+ def _sign_headers(self, url: str) -> Mapping[str, str]:
260
+ headers: dict[str, str] = {}
261
+ if self.secret == "":
262
+ return headers
263
+ uri = url[len(self.config_url) : len(url)]
264
+ time_unix_now = str(int(round(time.time() * 1000)))
265
+ headers["Authorization"] = "Apollo " + self.app_id + ":" + signature(time_unix_now, uri, self.secret)
266
+ headers["Timestamp"] = time_unix_now
267
+ return headers
268
+
269
+ def _heart_beat(self):
270
+ while not self._stopping:
271
+ for namespace in self._notification_map:
272
+ self._do_heart_beat(namespace)
273
+ time.sleep(60 * 10) # 10分钟
274
+
275
+ def _do_heart_beat(self, namespace):
276
+ url = "{}/configs/{}/{}/{}?ip={}".format(self.config_url, self.app_id, self.cluster, namespace, self.ip)
277
+ try:
278
+ code, body = http_request(url, timeout=3, headers=self._sign_headers(url))
279
+ if code == 200:
280
+ if not body:
281
+ logger.error(f"_do_heart_beat load configs failed,body is {body}")
282
+ return None
283
+ data = json.loads(body)
284
+ if self.last_release_key == data["releaseKey"]:
285
+ return None
286
+ self.last_release_key = data["releaseKey"]
287
+ data = data["configurations"]
288
+ self._update_cache_and_file(data, namespace)
289
+ else:
290
+ return None
291
+ except Exception:
292
+ logger.exception("an error occurred in _do_heart_beat")
293
+ return None
294
+
295
+ def get_all_dicts(self, namespace):
296
+ namespace_data = self._cache.get(namespace)
297
+ if namespace_data is None:
298
+ net_namespace_data = self.get_json_from_net(namespace)
299
+ if not net_namespace_data:
300
+ return namespace_data
301
+ namespace_data = net_namespace_data.get(CONFIGURATIONS)
302
+ if namespace_data:
303
+ self._update_cache_and_file(namespace_data, namespace)
304
+ return namespace_data