python-eigen-ingenuity 0.5.19b1__py3-none-any.whl → 0.5.20__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- eigeningenuity/events.py +95 -58
- eigeningenuity/util.py +270 -129
- {python_eigen_ingenuity-0.5.19b1.dist-info → python_eigen_ingenuity-0.5.20.dist-info}/METADATA +1 -1
- {python_eigen_ingenuity-0.5.19b1.dist-info → python_eigen_ingenuity-0.5.20.dist-info}/RECORD +8 -7
- regressiontests/eigeningenuity/historian/test_deprecation_warning.py +63 -0
- {python_eigen_ingenuity-0.5.19b1.dist-info → python_eigen_ingenuity-0.5.20.dist-info}/WHEEL +0 -0
- {python_eigen_ingenuity-0.5.19b1.dist-info → python_eigen_ingenuity-0.5.20.dist-info}/entry_points.txt +0 -0
- {python_eigen_ingenuity-0.5.19b1.dist-info → python_eigen_ingenuity-0.5.20.dist-info}/top_level.txt +0 -0
eigeningenuity/events.py
CHANGED
|
@@ -1,40 +1,55 @@
|
|
|
1
1
|
import requests
|
|
2
2
|
from datetime import datetime
|
|
3
3
|
from eigeningenuity.core import get_default_server, EigenServer
|
|
4
|
-
from eigeningenuity.util import
|
|
4
|
+
from eigeningenuity.util import (
|
|
5
|
+
force_list,
|
|
6
|
+
get_eigenserver,
|
|
7
|
+
parseEvents,
|
|
8
|
+
_do_chunked_eigen_post_request,
|
|
9
|
+
_do_eigen_post_request,
|
|
10
|
+
validate_eventlog_query,
|
|
11
|
+
)
|
|
5
12
|
|
|
6
13
|
from typing import Union
|
|
7
14
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
"""
|
|
11
|
-
|
|
15
|
+
|
|
16
|
+
class EventLog(object):
|
|
17
|
+
"""An elasticsearch instance which talks the Eigen elastic endpoint."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, baseurl: str, default_eventlog: str, auth: bool):
|
|
12
20
|
"""This is a constructor. It takes in a URL like http://infra:8080/ei-applet/search/"""
|
|
13
21
|
self.baseurl = baseurl
|
|
14
22
|
self.eigenserver = get_eigenserver(baseurl)
|
|
15
23
|
self.auth = auth
|
|
24
|
+
self.default_eventlog = default_eventlog
|
|
16
25
|
|
|
17
26
|
def _testConnection(self):
|
|
18
27
|
"""Preflight Request to verify connection to ingenuity"""
|
|
19
28
|
try:
|
|
20
29
|
status = requests.get(self.baseurl, verify=False).status_code
|
|
21
|
-
except
|
|
22
|
-
raise ConnectionError
|
|
23
|
-
|
|
24
|
-
|
|
30
|
+
except ConnectionError:
|
|
31
|
+
raise ConnectionError(
|
|
32
|
+
"Failed to connect to ingenuity instance at "
|
|
33
|
+
+ self.eigenserver
|
|
34
|
+
+ ". Please check the url is correct and the instance is up."
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
def _doJsonWriteRequest(self, relative_url: str, data: dict, label: str):
|
|
25
38
|
url = self.baseurl + relative_url
|
|
26
|
-
return _do_chunked_eigen_post_request(url,data,label,self.auth)
|
|
39
|
+
return _do_chunked_eigen_post_request(url, data, label, self.auth)
|
|
27
40
|
|
|
28
41
|
def _doJsonReadRequest(self, relative_url: str, data: dict):
|
|
29
42
|
url = self.baseurl + relative_url
|
|
30
|
-
response = _do_eigen_post_request(url,data,self.auth)
|
|
31
|
-
|
|
43
|
+
response = _do_eigen_post_request(url, data, self.auth)
|
|
44
|
+
|
|
32
45
|
if response["success"] is not True:
|
|
33
46
|
raise ValueError("Query failed: " + str(response["errors"]))
|
|
34
47
|
|
|
35
48
|
return response["response"]
|
|
36
49
|
|
|
37
|
-
def getEvents(
|
|
50
|
+
def getEvents(
|
|
51
|
+
self, query: dict, eventlog: str = "default", size: int = 1000, page: int = 0
|
|
52
|
+
) -> list:
|
|
38
53
|
"""
|
|
39
54
|
Execute a raw query against the ingenuity eventlog
|
|
40
55
|
|
|
@@ -53,25 +68,35 @@ class EventLog (object):
|
|
|
53
68
|
|
|
54
69
|
Returns:
|
|
55
70
|
The response from ingenuity, typically a list of dictionaries
|
|
56
|
-
|
|
71
|
+
|
|
57
72
|
Raises:
|
|
58
73
|
ValueError: If required fields are missing or invalid
|
|
59
74
|
"""
|
|
75
|
+
|
|
76
|
+
if eventlog == "default":
|
|
77
|
+
eventlog = self.default_eventlog
|
|
78
|
+
|
|
60
79
|
# Validate the query structure and required fields
|
|
61
80
|
validate_eventlog_query(query)
|
|
62
|
-
|
|
63
|
-
relative_url = "/list/eventlog"
|
|
64
|
-
body = {
|
|
65
|
-
|
|
66
|
-
"size": size,
|
|
67
|
-
"page": page
|
|
68
|
-
}
|
|
69
|
-
|
|
81
|
+
|
|
82
|
+
relative_url = f"/list/{eventlog}"
|
|
83
|
+
body = {"request": query, "size": size, "page": page}
|
|
84
|
+
|
|
70
85
|
response = self._doJsonReadRequest(relative_url, body)
|
|
71
86
|
|
|
72
87
|
return response
|
|
73
88
|
|
|
74
|
-
def getEventsBySource(
|
|
89
|
+
def getEventsBySource(
|
|
90
|
+
self,
|
|
91
|
+
source: Union[str, list],
|
|
92
|
+
eventlog: str = "default",
|
|
93
|
+
exact_match: bool = False,
|
|
94
|
+
start: Union[str, datetime] = "yesterday",
|
|
95
|
+
end: Union[str, datetime] = "now",
|
|
96
|
+
filter: Union[str, None] = None,
|
|
97
|
+
size: int = 1000,
|
|
98
|
+
page: int = 0,
|
|
99
|
+
) -> list:
|
|
75
100
|
"""
|
|
76
101
|
Retrieve events from the ingenuity eventlog filtered by source
|
|
77
102
|
|
|
@@ -86,7 +111,7 @@ class EventLog (object):
|
|
|
86
111
|
|
|
87
112
|
Returns:
|
|
88
113
|
The response from ingenuity, typically a list of dictionaries
|
|
89
|
-
|
|
114
|
+
|
|
90
115
|
Raises:
|
|
91
116
|
ValueError: If the source is not provided
|
|
92
117
|
"""
|
|
@@ -95,37 +120,43 @@ class EventLog (object):
|
|
|
95
120
|
|
|
96
121
|
source = force_list(source)
|
|
97
122
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
"end": end,
|
|
101
|
-
"sources": source
|
|
102
|
-
})
|
|
123
|
+
if eventlog == "default":
|
|
124
|
+
eventlog = self.default_eventlog
|
|
103
125
|
|
|
104
|
-
|
|
126
|
+
validate_eventlog_query({"start": start, "end": end, "sources": source})
|
|
127
|
+
|
|
128
|
+
relative_url = f"/list/{eventlog}"
|
|
105
129
|
body = {
|
|
106
|
-
"request": {
|
|
107
|
-
"start": start,
|
|
108
|
-
"end": end,
|
|
109
|
-
"sources": source
|
|
110
|
-
},
|
|
130
|
+
"request": {"start": start, "end": end, "sources": source},
|
|
111
131
|
"size": size,
|
|
112
|
-
"page": page
|
|
132
|
+
"page": page,
|
|
113
133
|
}
|
|
114
|
-
|
|
134
|
+
|
|
115
135
|
# Only include contentFilter if it's not None
|
|
116
136
|
if filter is not None:
|
|
117
137
|
body["request"]["contentFilter"] = filter
|
|
118
|
-
|
|
138
|
+
|
|
119
139
|
response = self._doJsonReadRequest(relative_url, body)
|
|
120
|
-
|
|
140
|
+
|
|
121
141
|
if exact_match:
|
|
122
142
|
# Filter results to only include exact matches on source
|
|
123
|
-
filtered_events = [
|
|
143
|
+
filtered_events = [
|
|
144
|
+
event for event in response["items"] if event.get("source") in source
|
|
145
|
+
]
|
|
124
146
|
return filtered_events
|
|
125
147
|
|
|
126
148
|
return response
|
|
127
149
|
|
|
128
|
-
def getEventsByType(
|
|
150
|
+
def getEventsByType(
|
|
151
|
+
self,
|
|
152
|
+
event_type: Union[str, list],
|
|
153
|
+
eventlog: str = "default",
|
|
154
|
+
start: Union[str, datetime] = "yesterday",
|
|
155
|
+
end: Union[str, datetime] = "now",
|
|
156
|
+
filter: Union[str, None] = None,
|
|
157
|
+
size: int = 1000,
|
|
158
|
+
page: int = 0,
|
|
159
|
+
) -> list:
|
|
129
160
|
"""
|
|
130
161
|
Retrieve events from the ingenuity eventlog filtered by event type
|
|
131
162
|
|
|
@@ -145,24 +176,19 @@ class EventLog (object):
|
|
|
145
176
|
"""
|
|
146
177
|
if not event_type or not isinstance(event_type, (str, list)):
|
|
147
178
|
raise ValueError("Event type must be a non-empty string or list")
|
|
148
|
-
|
|
179
|
+
|
|
149
180
|
event_type = force_list(event_type)
|
|
150
181
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
})
|
|
182
|
+
if eventlog == "default":
|
|
183
|
+
eventlog = self.default_eventlog
|
|
184
|
+
|
|
185
|
+
validate_eventlog_query({"start": start, "end": end, "types": event_type})
|
|
156
186
|
|
|
157
|
-
relative_url = "/list/eventlog"
|
|
187
|
+
relative_url = f"/list/{eventlog}"
|
|
158
188
|
body = {
|
|
159
|
-
"request": {
|
|
160
|
-
"start": start,
|
|
161
|
-
"end": end,
|
|
162
|
-
"types": event_type
|
|
163
|
-
},
|
|
189
|
+
"request": {"start": start, "end": end, "types": event_type},
|
|
164
190
|
"size": size,
|
|
165
|
-
"page": page
|
|
191
|
+
"page": page,
|
|
166
192
|
}
|
|
167
193
|
|
|
168
194
|
# Only include contentFilter if it's not None
|
|
@@ -184,9 +210,9 @@ class EventLog (object):
|
|
|
184
210
|
A boolean representing the successful push of all events. False if at least one event failed to be created
|
|
185
211
|
"""
|
|
186
212
|
events = parseEvents(events)
|
|
187
|
-
relative_url = "/save
|
|
213
|
+
relative_url = "/save"
|
|
188
214
|
label = "events"
|
|
189
|
-
|
|
215
|
+
|
|
190
216
|
failures = self._doJsonWriteRequest(relative_url, events, label)
|
|
191
217
|
|
|
192
218
|
if failures:
|
|
@@ -195,7 +221,10 @@ class EventLog (object):
|
|
|
195
221
|
else:
|
|
196
222
|
return True
|
|
197
223
|
|
|
198
|
-
|
|
224
|
+
|
|
225
|
+
def get_eventlog(
|
|
226
|
+
eigenserver: EigenServer = None, default_eventlog: Union[str, None] = None
|
|
227
|
+
) -> EventLog:
|
|
199
228
|
"""
|
|
200
229
|
Connect to Assetmodel of eigenserver. If eigenserver is not provided this will default to the EIGENSERVER environmental variable
|
|
201
230
|
|
|
@@ -210,5 +239,13 @@ def get_eventlog(eigenserver: EigenServer = None) -> EventLog:
|
|
|
210
239
|
elif isinstance(eigenserver, str):
|
|
211
240
|
eigenserver = EigenServer(eigenserver)
|
|
212
241
|
|
|
213
|
-
|
|
242
|
+
if default_eventlog is None:
|
|
243
|
+
default_eventlog = "eventlog"
|
|
244
|
+
else:
|
|
245
|
+
default_eventlog = str(default_eventlog)
|
|
214
246
|
|
|
247
|
+
return EventLog(
|
|
248
|
+
eigenserver.getEigenServerUrl() + "events" + "/",
|
|
249
|
+
default_eventlog,
|
|
250
|
+
eigenserver.auth,
|
|
251
|
+
)
|
eigeningenuity/util.py
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import
|
|
1
|
+
import json
|
|
2
|
+
import time
|
|
3
|
+
import requests
|
|
4
|
+
import csv
|
|
5
|
+
import logging
|
|
6
|
+
import warnings
|
|
7
|
+
import re
|
|
2
8
|
from datetime import datetime
|
|
3
9
|
from dateparser import parse
|
|
4
10
|
import pandas as pd
|
|
@@ -13,19 +19,24 @@ import eigeningenuity.settings as settings
|
|
|
13
19
|
from urllib3.exceptions import InsecureRequestWarning
|
|
14
20
|
|
|
15
21
|
# Suppress only the single InsecureRequestWarning from urllib3
|
|
16
|
-
warnings.simplefilter(
|
|
22
|
+
warnings.simplefilter("ignore", InsecureRequestWarning)
|
|
17
23
|
# Suppress only the single InsecureRequestWarning from urllib3
|
|
18
24
|
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
|
|
19
25
|
|
|
20
|
-
def _do_eigen_json_request(requesturl,auth,**params):
|
|
21
26
|
|
|
27
|
+
def _do_eigen_json_request(requesturl, auth, **params):
|
|
22
28
|
headers = {}
|
|
23
29
|
|
|
24
|
-
if
|
|
25
|
-
|
|
30
|
+
if (
|
|
31
|
+
settings._azure_tenant_id_
|
|
32
|
+
and settings._azure_client_id_
|
|
33
|
+
and settings._azure_auth_enabled_
|
|
34
|
+
and auth
|
|
35
|
+
):
|
|
36
|
+
headers = _authenticate_azure_user("/".join(requesturl.split("/")[0:3]))
|
|
26
37
|
|
|
27
38
|
if settings._api_token_value_:
|
|
28
|
-
headers[
|
|
39
|
+
headers["X-Api-Key"] = settings._api_token_value_
|
|
29
40
|
|
|
30
41
|
if params:
|
|
31
42
|
if "?" in requesturl:
|
|
@@ -33,9 +44,9 @@ def _do_eigen_json_request(requesturl,auth,**params):
|
|
|
33
44
|
else:
|
|
34
45
|
sep = "?"
|
|
35
46
|
|
|
36
|
-
for k,v in params.items():
|
|
47
|
+
for k, v in params.items():
|
|
37
48
|
if v is None:
|
|
38
|
-
|
|
49
|
+
pass
|
|
39
50
|
else:
|
|
40
51
|
for e in force_list(v):
|
|
41
52
|
if not isinstance(e, str):
|
|
@@ -51,15 +62,21 @@ def _do_eigen_json_request(requesturl,auth,**params):
|
|
|
51
62
|
data = requests.get(requesturl, headers=headers, verify=False)
|
|
52
63
|
except ConnectionError as e:
|
|
53
64
|
# sys.tracebacklimit = 0
|
|
54
|
-
raise EigenException(
|
|
55
|
-
|
|
65
|
+
raise EigenException(
|
|
66
|
+
"No Response from ingenuity instance at https://"
|
|
67
|
+
+ requesturl.split("/")[2]
|
|
68
|
+
+ ". Please check this is correct url and that the instance is currently running"
|
|
69
|
+
) from None
|
|
56
70
|
|
|
57
71
|
if data.text.startswith("ERROR:"):
|
|
58
72
|
if "UNKNOWN TAG" in data.text:
|
|
59
73
|
raise RemoteServerException(data.text)
|
|
60
74
|
raise RemoteServerException(data.text.split("\n")[1], requesturl)
|
|
61
75
|
elif data.text.startswith("EXCEPT:") and data.status_code != 200:
|
|
62
|
-
raise RemoteServerException(
|
|
76
|
+
raise RemoteServerException(
|
|
77
|
+
data.text.split("\n")[0],
|
|
78
|
+
"API could not parse request, check query syntax is correct",
|
|
79
|
+
)
|
|
63
80
|
else:
|
|
64
81
|
try:
|
|
65
82
|
ret = data.json()
|
|
@@ -67,7 +84,9 @@ def _do_eigen_json_request(requesturl,auth,**params):
|
|
|
67
84
|
ret = data.text
|
|
68
85
|
try:
|
|
69
86
|
if "Sign in to your account" in ret:
|
|
70
|
-
if not settings._azure_auth_enabled_ or not (
|
|
87
|
+
if not settings._azure_auth_enabled_ or not (
|
|
88
|
+
settings._azure_tenant_id_ and settings._azure_client_id_
|
|
89
|
+
):
|
|
71
90
|
msg = "This resource requires authentication with an Azure account. Use set_azure_tenant_id and set_azure_client_id to set the server parameters."
|
|
72
91
|
else:
|
|
73
92
|
msg = "Authentication failed, check the resource you are querying matches the azure parameters set"
|
|
@@ -76,33 +95,50 @@ def _do_eigen_json_request(requesturl,auth,**params):
|
|
|
76
95
|
pass
|
|
77
96
|
return ret
|
|
78
97
|
|
|
79
|
-
|
|
98
|
+
|
|
99
|
+
def _do_eigen_post_request(requesturl, payload, auth):
|
|
80
100
|
headers = {}
|
|
81
|
-
if
|
|
82
|
-
|
|
101
|
+
if (
|
|
102
|
+
settings._azure_tenant_id_
|
|
103
|
+
and settings._azure_client_id_
|
|
104
|
+
and settings._azure_auth_enabled_
|
|
105
|
+
and auth
|
|
106
|
+
):
|
|
107
|
+
headers = _authenticate_azure_user("/".join(requesturl.split("/")[0:3]))
|
|
83
108
|
|
|
84
109
|
if settings._api_token_value_:
|
|
85
|
-
headers[
|
|
110
|
+
headers["X-Api-Key"] = settings._api_token_value_
|
|
86
111
|
|
|
87
|
-
resp = requests.post(requesturl,json=payload, headers=headers, verify=False)
|
|
112
|
+
resp = requests.post(requesturl, json=payload, headers=headers, verify=False)
|
|
88
113
|
|
|
89
114
|
if not str(resp.status_code).startswith("2"):
|
|
90
|
-
logging.warning(
|
|
115
|
+
logging.warning(
|
|
116
|
+
"Request to "
|
|
117
|
+
+ requesturl
|
|
118
|
+
+ " failed with status code "
|
|
119
|
+
+ str(resp.status_code)
|
|
120
|
+
)
|
|
91
121
|
success = False
|
|
92
122
|
errors = resp.text
|
|
93
123
|
else:
|
|
94
124
|
success = True
|
|
95
125
|
errors = None
|
|
96
|
-
|
|
126
|
+
|
|
97
127
|
return {"success": success, "errors": errors, "response": resp.json()}
|
|
98
128
|
|
|
99
|
-
|
|
129
|
+
|
|
130
|
+
def _do_chunked_eigen_post_request(requesturl, data, label, auth):
|
|
100
131
|
headers = {}
|
|
101
|
-
if
|
|
102
|
-
|
|
132
|
+
if (
|
|
133
|
+
settings._azure_tenant_id_
|
|
134
|
+
and settings._azure_client_id_
|
|
135
|
+
and settings._azure_auth_enabled_
|
|
136
|
+
and auth
|
|
137
|
+
):
|
|
138
|
+
headers = _authenticate_azure_user("/".join(requesturl.split("/")[0:3]))
|
|
103
139
|
|
|
104
140
|
if settings._api_token_value_:
|
|
105
|
-
headers[
|
|
141
|
+
headers["X-Api-Key"] = settings._api_token_value_
|
|
106
142
|
|
|
107
143
|
chunks = list(divide_chunks(data, 500))
|
|
108
144
|
failures = []
|
|
@@ -116,29 +152,33 @@ def _do_chunked_eigen_post_request(requesturl,data,label,auth):
|
|
|
116
152
|
return failures
|
|
117
153
|
return False
|
|
118
154
|
|
|
155
|
+
|
|
119
156
|
def is_list(x):
|
|
120
157
|
return type(x) in (list, tuple, set)
|
|
121
158
|
|
|
159
|
+
|
|
122
160
|
def force_list(x):
|
|
123
161
|
if is_list(x):
|
|
124
162
|
return x
|
|
125
163
|
else:
|
|
126
164
|
return [x]
|
|
127
165
|
|
|
166
|
+
|
|
128
167
|
def number_to_string(n):
|
|
129
168
|
if type(n) == float:
|
|
130
|
-
return format(n,
|
|
169
|
+
return format(n, "^12.5f")
|
|
131
170
|
else:
|
|
132
171
|
return n
|
|
133
172
|
|
|
173
|
+
|
|
134
174
|
def time_to_epoch_millis(t):
|
|
135
175
|
if type(t) == datetime:
|
|
136
176
|
epochmillis = t.timestamp()
|
|
137
|
-
elif
|
|
177
|
+
elif type(t) == int or type(t) == float:
|
|
138
178
|
if t > 100000000000:
|
|
139
179
|
epochmillis = int(t)
|
|
140
180
|
else:
|
|
141
|
-
epochmillis = int(t*1000)
|
|
181
|
+
epochmillis = int(t * 1000)
|
|
142
182
|
elif type(t) == str:
|
|
143
183
|
if "ago" in t or "now" in t:
|
|
144
184
|
return t
|
|
@@ -148,53 +188,58 @@ def time_to_epoch_millis(t):
|
|
|
148
188
|
raise EigenException("Unknown time format " + str(type(t)))
|
|
149
189
|
return int(round(epochmillis))
|
|
150
190
|
|
|
191
|
+
|
|
151
192
|
def get_time_tuple(floatingpointepochsecs):
|
|
152
193
|
time_tuple = time.gmtime(floatingpointepochsecs)
|
|
153
194
|
return time_tuple
|
|
154
195
|
|
|
196
|
+
|
|
155
197
|
def get_timestamp_string(t):
|
|
156
|
-
pattern =
|
|
198
|
+
pattern = "%Y-%m-%d %H:%M:%S UTC"
|
|
157
199
|
s = datetime.fromtimestamp(t).strftime(pattern)
|
|
158
200
|
return s
|
|
159
201
|
|
|
202
|
+
|
|
160
203
|
def get_timestamp(t):
|
|
161
204
|
if type(t) == str:
|
|
162
205
|
try:
|
|
163
206
|
epochmillis = parse(t).timestamp()
|
|
164
207
|
except ValueError:
|
|
165
208
|
try:
|
|
166
|
-
pattern =
|
|
209
|
+
pattern = "%Y-%m-%d %H:%M:%S.%f"
|
|
167
210
|
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
168
211
|
except ValueError:
|
|
169
212
|
try:
|
|
170
|
-
pattern =
|
|
213
|
+
pattern = "%Y-%m-%dT%H:%M:%S.%f%z"
|
|
171
214
|
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
172
215
|
except ValueError:
|
|
173
216
|
try:
|
|
174
|
-
pattern =
|
|
217
|
+
pattern = "%Y-%m-%d %H:%M:%S"
|
|
175
218
|
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
176
219
|
except ValueError:
|
|
177
220
|
try:
|
|
178
|
-
pattern =
|
|
221
|
+
pattern = "%Y-%m-%d"
|
|
179
222
|
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
180
223
|
except ValueError:
|
|
181
224
|
try:
|
|
182
225
|
epochmillis = int(t)
|
|
183
226
|
except ValueError:
|
|
184
|
-
raise EigenException(
|
|
227
|
+
raise EigenException(
|
|
228
|
+
"Unknown time format " + str(type(t))
|
|
229
|
+
)
|
|
185
230
|
|
|
186
231
|
else:
|
|
187
|
-
return
|
|
232
|
+
return time_to_epoch_millis(t)
|
|
188
233
|
return int(round(epochmillis))
|
|
189
234
|
|
|
190
235
|
|
|
191
|
-
|
|
192
236
|
def get_datetime(t):
|
|
193
237
|
timestamp = get_timestamp(t)
|
|
194
238
|
return datetime.fromtimestamp(timestamp)
|
|
195
239
|
|
|
240
|
+
|
|
196
241
|
def pythonTimeToServerTime(ts):
|
|
197
|
-
# where ts may be supplied as time tuple, datetime or floating point seconds, and server time is (obviously) millis.
|
|
242
|
+
# where ts may be supplied as time tuple, datetime or floating point seconds, and server time is (obviously) millis.
|
|
198
243
|
if type(ts) == datetime:
|
|
199
244
|
epochmillis = time.mktime(ts.timetuple()) * 1000
|
|
200
245
|
elif type(ts) == tuple:
|
|
@@ -207,11 +252,12 @@ def pythonTimeToServerTime(ts):
|
|
|
207
252
|
|
|
208
253
|
|
|
209
254
|
def serverTimeToPythonTime(ts):
|
|
210
|
-
# where ts is millis and the returned value is consistently whatever we're using internally in the python library (i.e. floating secs)
|
|
255
|
+
# where ts is millis and the returned value is consistently whatever we're using internally in the python library (i.e. floating secs)
|
|
211
256
|
return ts / 1000.0
|
|
212
257
|
|
|
258
|
+
|
|
213
259
|
def pythonTimeToFloatingSecs(ts):
|
|
214
|
-
# where ts may be supplied as time tuple, datetime or floating point seconds
|
|
260
|
+
# where ts may be supplied as time tuple, datetime or floating point seconds
|
|
215
261
|
if type(ts) == datetime:
|
|
216
262
|
return time.mktime(ts.timetuple())
|
|
217
263
|
elif type(ts) == tuple:
|
|
@@ -221,8 +267,9 @@ def pythonTimeToFloatingSecs(ts):
|
|
|
221
267
|
else:
|
|
222
268
|
raise EigenException("Unknown python time format " + str(type(ts)))
|
|
223
269
|
|
|
270
|
+
|
|
224
271
|
def pythonTimeToTuple(ts):
|
|
225
|
-
# where ts may be supplied as time tuple, datetime or floating point seconds
|
|
272
|
+
# where ts may be supplied as time tuple, datetime or floating point seconds
|
|
226
273
|
if type(ts) == datetime:
|
|
227
274
|
return ts.timetuple()
|
|
228
275
|
elif type(ts) == tuple:
|
|
@@ -232,8 +279,9 @@ def pythonTimeToTuple(ts):
|
|
|
232
279
|
else:
|
|
233
280
|
raise EigenException("Unknown python time format " + str(type(ts)))
|
|
234
281
|
|
|
282
|
+
|
|
235
283
|
def pythonTimeToDateTime(ts):
|
|
236
|
-
# where ts may be supplied as time tuple, datetime or floating point seconds
|
|
284
|
+
# where ts may be supplied as time tuple, datetime or floating point seconds
|
|
237
285
|
if type(ts) == datetime:
|
|
238
286
|
return ts
|
|
239
287
|
elif type(ts) == tuple:
|
|
@@ -244,13 +292,15 @@ def pythonTimeToDateTime(ts):
|
|
|
244
292
|
else:
|
|
245
293
|
raise EigenException("Unknown python time format " + str(type(ts)))
|
|
246
294
|
|
|
295
|
+
|
|
247
296
|
def map_java_exception(myExceptionName, params):
|
|
248
297
|
if myExceptionName == "urllib2.HTTPError":
|
|
249
|
-
|
|
250
|
-
# elif: ...
|
|
298
|
+
return RemoteServerException(params)
|
|
299
|
+
# elif: ...
|
|
251
300
|
else:
|
|
252
301
|
return EigenException(myExceptionName)
|
|
253
302
|
|
|
303
|
+
|
|
254
304
|
def parse_duration(timeWindow):
|
|
255
305
|
unit = timeWindow[-1:]
|
|
256
306
|
value = timeWindow[:-1]
|
|
@@ -270,36 +320,40 @@ def parse_duration(timeWindow):
|
|
|
270
320
|
def months():
|
|
271
321
|
return int(value) * 3600 * 24 * 30
|
|
272
322
|
|
|
273
|
-
def years():
|
|
323
|
+
def years():
|
|
324
|
+
int(value) * 3600 * 24 * 365
|
|
274
325
|
|
|
275
|
-
options = {
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
326
|
+
options = {
|
|
327
|
+
"s": seconds,
|
|
328
|
+
"m": minutes,
|
|
329
|
+
"h": hours,
|
|
330
|
+
"d": days,
|
|
331
|
+
"M": months,
|
|
332
|
+
"y": years,
|
|
281
333
|
}
|
|
282
334
|
|
|
283
|
-
duration = options[unit]()*1000
|
|
335
|
+
duration = options[unit]() * 1000
|
|
284
336
|
|
|
285
337
|
return duration
|
|
286
338
|
|
|
287
339
|
|
|
288
340
|
def divide_chunks(l, n):
|
|
289
341
|
for i in range(0, len(l), n):
|
|
290
|
-
yield l[i:i + n]
|
|
342
|
+
yield l[i : i + n]
|
|
343
|
+
|
|
291
344
|
|
|
292
345
|
def cypherRespMap(resp):
|
|
293
346
|
return resp["m"]
|
|
294
347
|
|
|
295
348
|
|
|
296
|
-
def jsonToDf(json,transpose:bool=False):
|
|
349
|
+
def jsonToDf(json, transpose: bool = False):
|
|
297
350
|
p = {}
|
|
298
351
|
keys = json.keys()
|
|
299
|
-
if "unknown" in keys:
|
|
352
|
+
if "unknown" in keys:
|
|
353
|
+
keys.remove("unknown")
|
|
300
354
|
for key in keys:
|
|
301
355
|
if type(json[key]) == list:
|
|
302
|
-
m = list(map(dataMap,json[key]))
|
|
356
|
+
m = list(map(dataMap, json[key]))
|
|
303
357
|
n = dict(ChainMap(*m))
|
|
304
358
|
else:
|
|
305
359
|
n = dataMap(json[key])
|
|
@@ -308,9 +362,10 @@ def jsonToDf(json,transpose:bool=False):
|
|
|
308
362
|
df = pd.DataFrame(p)
|
|
309
363
|
if transpose:
|
|
310
364
|
df = df.T
|
|
311
|
-
return
|
|
365
|
+
return df[::-1]
|
|
312
366
|
except ValueError:
|
|
313
|
-
return
|
|
367
|
+
return pd.Series(p)
|
|
368
|
+
|
|
314
369
|
|
|
315
370
|
def dataMap(j):
|
|
316
371
|
try:
|
|
@@ -319,9 +374,11 @@ def dataMap(j):
|
|
|
319
374
|
h = j
|
|
320
375
|
return h
|
|
321
376
|
|
|
377
|
+
|
|
322
378
|
def flattenList(list):
|
|
323
379
|
return [item for sublist in list for item in sublist]
|
|
324
380
|
|
|
381
|
+
|
|
325
382
|
def flattenDict(nestedDict):
|
|
326
383
|
points = []
|
|
327
384
|
keys = nestedDict.keys()
|
|
@@ -333,15 +390,28 @@ def flattenDict(nestedDict):
|
|
|
333
390
|
points.append(tag)
|
|
334
391
|
return points
|
|
335
392
|
|
|
393
|
+
|
|
336
394
|
def aggMap(x):
|
|
337
395
|
for k in x[1]:
|
|
338
396
|
k["tag"] = x[0]
|
|
339
397
|
return x[1]
|
|
340
398
|
|
|
341
|
-
|
|
342
|
-
|
|
399
|
+
|
|
400
|
+
def aggToDf(x, cols):
|
|
401
|
+
y = flattenList(list(map(aggMap, x.items())))
|
|
343
402
|
if cols is None:
|
|
344
|
-
cols = [
|
|
403
|
+
cols = [
|
|
404
|
+
"tag",
|
|
405
|
+
"start",
|
|
406
|
+
"end",
|
|
407
|
+
"min",
|
|
408
|
+
"max",
|
|
409
|
+
"avg",
|
|
410
|
+
"var",
|
|
411
|
+
"stddev",
|
|
412
|
+
"numgood",
|
|
413
|
+
"numbad",
|
|
414
|
+
]
|
|
345
415
|
else:
|
|
346
416
|
cols = ["tag", "start", "end"] + cols
|
|
347
417
|
df = pd.DataFrame(y)
|
|
@@ -352,31 +422,36 @@ def aggToDf(x,cols):
|
|
|
352
422
|
except ValueError:
|
|
353
423
|
df["start"] = pd.to_datetime(df["start"], format="ISO8601")
|
|
354
424
|
df["end"] = pd.to_datetime(df["end"], format="ISO8601")
|
|
355
|
-
df.sort_values(by=
|
|
356
|
-
return
|
|
425
|
+
df.sort_values(by="start", inplace=True)
|
|
426
|
+
return df
|
|
427
|
+
|
|
357
428
|
|
|
358
429
|
def get_eigenserver(url):
|
|
359
430
|
split_url = urlsplit(url)
|
|
360
431
|
return split_url.scheme + "://" + split_url.netloc
|
|
361
432
|
|
|
362
|
-
|
|
433
|
+
|
|
434
|
+
def constructURL(y, x):
|
|
363
435
|
if "//" not in x["url"]:
|
|
364
436
|
x["url"] = y + x["url"]
|
|
365
437
|
k = {"fileName": x["fileName"], "description": x["description"], "url": x["url"]}
|
|
366
438
|
return k
|
|
367
439
|
|
|
440
|
+
|
|
368
441
|
def parseEvents(events):
|
|
369
442
|
if type(events) == dict or type(events) == list:
|
|
370
443
|
events = events
|
|
371
444
|
elif type(events) == str:
|
|
372
445
|
try:
|
|
373
|
-
with open(events,"r") as f:
|
|
446
|
+
with open(events, "r") as f:
|
|
374
447
|
events = json.loads(f.read())
|
|
375
448
|
except FileNotFoundError:
|
|
376
449
|
try:
|
|
377
450
|
events = json.loads(events)
|
|
378
451
|
except json.decoder.JSONDecodeError:
|
|
379
|
-
raise EigenException(
|
|
452
|
+
raise EigenException(
|
|
453
|
+
"Could not parse input, enter the path to a file, or a json/dict object"
|
|
454
|
+
)
|
|
380
455
|
try:
|
|
381
456
|
events = events["events"]
|
|
382
457
|
except:
|
|
@@ -384,61 +459,105 @@ def parseEvents(events):
|
|
|
384
459
|
events = force_list(events)
|
|
385
460
|
return events
|
|
386
461
|
|
|
462
|
+
|
|
387
463
|
def parse_properties(x):
|
|
388
464
|
return x["graphapi"]["properties"]
|
|
389
465
|
|
|
390
|
-
|
|
466
|
+
|
|
467
|
+
def csvWriter(
|
|
468
|
+
data, historian, filepath, multi_csv, functionName, order=None, headers=False
|
|
469
|
+
):
|
|
391
470
|
if "Agg" in functionName:
|
|
392
|
-
timeField =
|
|
471
|
+
timeField = "start"
|
|
393
472
|
else:
|
|
394
|
-
timeField =
|
|
473
|
+
timeField = "timestamp"
|
|
395
474
|
if multi_csv:
|
|
396
475
|
for item in data:
|
|
397
|
-
sortedDicts=[]
|
|
476
|
+
sortedDicts = []
|
|
398
477
|
for entry in force_list(data[item]):
|
|
399
478
|
if order is not None:
|
|
400
|
-
entry =
|
|
479
|
+
entry = dict(
|
|
480
|
+
sorted(entry.items(), key=lambda item: order.index(item[0]))
|
|
481
|
+
)
|
|
401
482
|
sortedDicts.append(dict(entry.items()))
|
|
402
|
-
sortedList = sorted(sortedDicts, key=lambda d: (d[timeField]))
|
|
483
|
+
sortedList = sorted(sortedDicts, key=lambda d: (d[timeField]))
|
|
403
484
|
keys = sortedList[0].keys()
|
|
404
485
|
if filepath is None:
|
|
405
|
-
filepath =
|
|
486
|
+
filepath = (
|
|
487
|
+
item
|
|
488
|
+
+ "-"
|
|
489
|
+
+ functionName
|
|
490
|
+
+ "-"
|
|
491
|
+
+ str(round(datetime.now().timestamp()))
|
|
492
|
+
+ ".csv"
|
|
493
|
+
)
|
|
406
494
|
elif filepath[-1] == "/":
|
|
407
|
-
filepath +=
|
|
495
|
+
filepath += (
|
|
496
|
+
item
|
|
497
|
+
+ "-"
|
|
498
|
+
+ functionName
|
|
499
|
+
+ "-"
|
|
500
|
+
+ str(round(datetime.now().timestamp()))
|
|
501
|
+
+ ".csv"
|
|
502
|
+
)
|
|
408
503
|
else:
|
|
409
|
-
filepath =
|
|
410
|
-
|
|
411
|
-
|
|
504
|
+
filepath = (
|
|
505
|
+
item
|
|
506
|
+
+ "-"
|
|
507
|
+
+ functionName
|
|
508
|
+
+ "-"
|
|
509
|
+
+ str(round(datetime.now().timestamp()))
|
|
510
|
+
+ ".csv"
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
with open(filepath, "w", newline="") as output_file:
|
|
412
514
|
dict_writer = csv.DictWriter(output_file, keys)
|
|
413
515
|
if headers:
|
|
414
516
|
dict_writer.writeheader()
|
|
415
517
|
dict_writer.writerows(sortedList)
|
|
416
|
-
return True
|
|
518
|
+
return True
|
|
417
519
|
else:
|
|
418
520
|
sortedDicts = []
|
|
419
521
|
points = flattenDict(data)
|
|
420
522
|
for entry in points:
|
|
421
523
|
if order is not None:
|
|
422
|
-
entry = dict(
|
|
524
|
+
entry = dict(
|
|
525
|
+
sorted(entry.items(), key=lambda item: order.index(item[0]))
|
|
526
|
+
)
|
|
423
527
|
sortedDicts.append(entry)
|
|
424
|
-
sortedList = sorted(sortedDicts, key=lambda d: (d[
|
|
528
|
+
sortedList = sorted(sortedDicts, key=lambda d: (d["tag"], d[timeField]))
|
|
425
529
|
keys = sortedList[0].keys()
|
|
426
530
|
if filepath is None:
|
|
427
|
-
filepath =
|
|
531
|
+
filepath = (
|
|
532
|
+
historian
|
|
533
|
+
+ "-"
|
|
534
|
+
+ functionName
|
|
535
|
+
+ "-"
|
|
536
|
+
+ str(round(datetime.now().timestamp()))
|
|
537
|
+
+ ".csv"
|
|
538
|
+
)
|
|
428
539
|
elif filepath[-1] == "/":
|
|
429
|
-
filepath +=
|
|
430
|
-
|
|
431
|
-
|
|
540
|
+
filepath += (
|
|
541
|
+
historian
|
|
542
|
+
+ "-"
|
|
543
|
+
+ functionName
|
|
544
|
+
+ "-"
|
|
545
|
+
+ str(round(datetime.now().timestamp()))
|
|
546
|
+
+ ".csv"
|
|
547
|
+
)
|
|
548
|
+
|
|
549
|
+
with open(filepath, "w", newline="") as output_file:
|
|
432
550
|
dict_writer = csv.DictWriter(output_file, keys)
|
|
433
551
|
if headers:
|
|
434
552
|
dict_writer.writeheader()
|
|
435
553
|
dict_writer.writerows(sortedList)
|
|
436
554
|
return True
|
|
437
|
-
|
|
438
|
-
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def process_datapoint(data_dict, key, datapoint):
|
|
439
558
|
tag_name = key
|
|
440
|
-
timestamp = datapoint[
|
|
441
|
-
value_data = datapoint[
|
|
559
|
+
timestamp = datapoint["timestamp"]
|
|
560
|
+
value_data = datapoint["value"]
|
|
442
561
|
|
|
443
562
|
# Check if timestamp is already a key in the dictionary
|
|
444
563
|
if timestamp not in data_dict:
|
|
@@ -448,7 +567,8 @@ def process_datapoint(data_dict,key,datapoint):
|
|
|
448
567
|
data_dict[timestamp][tag_name] = value_data
|
|
449
568
|
|
|
450
569
|
return data_dict
|
|
451
|
-
|
|
570
|
+
|
|
571
|
+
|
|
452
572
|
# Function to convert timestamp to a consistent format
|
|
453
573
|
def convert_df_timestamp_header(timestamp):
|
|
454
574
|
# Convert to datetime object and then format as string
|
|
@@ -463,38 +583,40 @@ def multi_response_to_df(api_response):
|
|
|
463
583
|
for key, value in api_response.items():
|
|
464
584
|
if "dataPoints" in value.keys():
|
|
465
585
|
for datapoint in value["dataPoints"]:
|
|
466
|
-
data_dict = process_datapoint(data_dict,key,datapoint)
|
|
586
|
+
data_dict = process_datapoint(data_dict, key, datapoint)
|
|
467
587
|
|
|
468
588
|
elif "dataPoint" in value.keys():
|
|
469
589
|
datapoint = value["dataPoint"]
|
|
470
|
-
data_dict = process_datapoint(data_dict,key,datapoint)
|
|
590
|
+
data_dict = process_datapoint(data_dict, key, datapoint)
|
|
471
591
|
|
|
472
592
|
# Create DataFrame
|
|
473
593
|
df = pd.DataFrame(data_dict)
|
|
474
594
|
df.columns = [convert_df_timestamp_header(col) for col in df.columns]
|
|
475
|
-
df = df.T
|
|
595
|
+
df = df.T # Transpose the DataFrame
|
|
476
596
|
|
|
477
597
|
# Convert timestamp index to datetime format
|
|
478
598
|
df.index = pd.to_datetime(df.index)
|
|
479
599
|
|
|
480
600
|
return df
|
|
481
601
|
|
|
602
|
+
|
|
482
603
|
def merge_tags_from_response(response):
|
|
483
604
|
merged_response = {}
|
|
484
605
|
|
|
485
606
|
for key, value in response.items():
|
|
486
607
|
# Extract the header by removing the suffix (e.g., '-0' or '-1')
|
|
487
|
-
header = key.rsplit(
|
|
608
|
+
header = key.rsplit("-", 1)[0]
|
|
488
609
|
|
|
489
610
|
# If the header is not already in the merged_response, initialize it
|
|
490
611
|
if header not in merged_response:
|
|
491
|
-
merged_response[header] = {
|
|
612
|
+
merged_response[header] = {"dataPoints": []}
|
|
492
613
|
|
|
493
614
|
# Append the dataPoint to the list of dataPoints under the header
|
|
494
|
-
merged_response[header][
|
|
615
|
+
merged_response[header]["dataPoints"].append(value["dataPoint"])
|
|
495
616
|
|
|
496
617
|
return merged_response
|
|
497
618
|
|
|
619
|
+
|
|
498
620
|
def update_keys(my_dict, historian):
|
|
499
621
|
# Use dictionary comprehension to update keys
|
|
500
622
|
return {
|
|
@@ -502,17 +624,23 @@ def update_keys(my_dict, historian):
|
|
|
502
624
|
for key, value in my_dict.items()
|
|
503
625
|
}
|
|
504
626
|
|
|
505
|
-
def _do_historian_multi_request(url,body,auth,write_request=False,get_request=False):
|
|
506
627
|
|
|
628
|
+
def _do_historian_multi_request(
|
|
629
|
+
url, body, auth, write_request=False, get_request=False
|
|
630
|
+
):
|
|
507
631
|
headers = {}
|
|
508
632
|
|
|
509
|
-
if
|
|
510
|
-
|
|
633
|
+
if (
|
|
634
|
+
settings._azure_tenant_id_
|
|
635
|
+
and settings._azure_client_id_
|
|
636
|
+
and settings._azure_auth_enabled_
|
|
637
|
+
and auth
|
|
638
|
+
):
|
|
639
|
+
headers = _authenticate_azure_user("/".join(url.split("/")[0:3]))
|
|
511
640
|
|
|
512
641
|
if settings._api_token_value_:
|
|
513
|
-
headers[
|
|
642
|
+
headers["X-Api-Key"] = settings._api_token_value_
|
|
514
643
|
|
|
515
|
-
|
|
516
644
|
if get_request:
|
|
517
645
|
resp = requests.get(url, verify=False, headers=headers).json()
|
|
518
646
|
|
|
@@ -520,13 +648,14 @@ def _do_historian_multi_request(url,body,auth,write_request=False,get_request=Fa
|
|
|
520
648
|
resp = requests.post(url, json=body, verify=False, headers=headers).json()
|
|
521
649
|
|
|
522
650
|
if write_request:
|
|
523
|
-
return resp[
|
|
651
|
+
return resp["message"]
|
|
524
652
|
|
|
525
653
|
return resp
|
|
526
654
|
|
|
655
|
+
|
|
527
656
|
def _reformat_multi_response(original_dict):
|
|
528
657
|
reformatted_dict = {}
|
|
529
|
-
|
|
658
|
+
|
|
530
659
|
for key, value in original_dict.items():
|
|
531
660
|
if type(value) == list:
|
|
532
661
|
reformatted_dict = value
|
|
@@ -536,15 +665,16 @@ def _reformat_multi_response(original_dict):
|
|
|
536
665
|
continue
|
|
537
666
|
else:
|
|
538
667
|
# Extract the list of data points from either 'dataPoints' or 'dataPoint' key
|
|
539
|
-
data_points = value.get(
|
|
668
|
+
data_points = value.get("dataPoints") or value.get("dataPoint") or value
|
|
540
669
|
# Assign the data points list directly to the top-level key
|
|
541
670
|
reformatted_dict[key] = data_points
|
|
542
|
-
|
|
671
|
+
|
|
543
672
|
return reformatted_dict
|
|
544
673
|
|
|
545
|
-
|
|
674
|
+
|
|
675
|
+
def format_output(output, response, tags, timestamps=False):
|
|
546
676
|
if not timestamps:
|
|
547
|
-
items = response[
|
|
677
|
+
items = response["results"]
|
|
548
678
|
else:
|
|
549
679
|
items = response
|
|
550
680
|
|
|
@@ -556,54 +686,63 @@ def format_output(output,response,tags,timestamps=False):
|
|
|
556
686
|
else:
|
|
557
687
|
return _reformat_multi_response(items)
|
|
558
688
|
elif output == "string":
|
|
559
|
-
return json.dumps(items,indent=4)
|
|
689
|
+
return json.dumps(items, indent=4)
|
|
560
690
|
elif output == "df":
|
|
561
691
|
return multi_response_to_df(items)
|
|
562
|
-
|
|
563
|
-
raise EigenException("Unrecognised Output Type. Must be one of ['raw','json','string','df']")
|
|
564
692
|
|
|
693
|
+
raise EigenException(
|
|
694
|
+
"Unrecognised Output Type. Must be one of ['raw','json','string','df']"
|
|
695
|
+
)
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
class EigenException(Exception):
|
|
699
|
+
pass
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
class RemoteServerException(EigenException):
|
|
703
|
+
pass
|
|
565
704
|
|
|
566
|
-
class EigenException (Exception): pass
|
|
567
|
-
class RemoteServerException (EigenException): pass
|
|
568
705
|
|
|
569
706
|
def validate_date_field(date_value, field_name):
|
|
570
707
|
"""
|
|
571
708
|
Validate that a date field is in the correct format
|
|
572
|
-
|
|
709
|
+
|
|
573
710
|
Args:
|
|
574
711
|
date_value: The date value to validate
|
|
575
712
|
field_name: Name of the field for error messages
|
|
576
|
-
|
|
713
|
+
|
|
577
714
|
Raises:
|
|
578
715
|
ValueError: If the date format is invalid
|
|
579
716
|
"""
|
|
580
717
|
if date_value is None:
|
|
581
718
|
raise ValueError(f"Field '{field_name}' is required")
|
|
582
|
-
|
|
719
|
+
|
|
583
720
|
# Check if it's already a datetime object
|
|
584
721
|
if isinstance(date_value, datetime):
|
|
585
722
|
return
|
|
586
|
-
|
|
723
|
+
|
|
587
724
|
# Check if it's a string
|
|
588
725
|
if isinstance(date_value, str):
|
|
589
726
|
# Check for relative time strings
|
|
590
727
|
relative_times = ["now", "today", "yesterday"]
|
|
591
728
|
if date_value.lower() in relative_times:
|
|
592
729
|
return
|
|
593
|
-
|
|
730
|
+
|
|
594
731
|
# Check for ISO format (basic check)
|
|
595
|
-
iso_pattern = re.compile(r
|
|
732
|
+
iso_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}")
|
|
596
733
|
if iso_pattern.match(date_value):
|
|
597
734
|
try:
|
|
598
735
|
# Try to parse as ISO format
|
|
599
|
-
datetime.fromisoformat(date_value.replace(
|
|
736
|
+
datetime.fromisoformat(date_value.replace("Z", "+00:00"))
|
|
600
737
|
return
|
|
601
738
|
except ValueError:
|
|
602
739
|
pass
|
|
603
|
-
|
|
740
|
+
|
|
604
741
|
# If we get here, the string format is not recognized
|
|
605
|
-
raise ValueError(
|
|
606
|
-
|
|
742
|
+
raise ValueError(
|
|
743
|
+
f"Field '{field_name}' must be a datetime object, ISO format string, or relative time ('now', 'today', 'yesterday'). Got: {date_value}"
|
|
744
|
+
)
|
|
745
|
+
|
|
607
746
|
# Check if it's a timestamp (int or float)
|
|
608
747
|
if isinstance(date_value, (int, float)):
|
|
609
748
|
try:
|
|
@@ -611,31 +750,33 @@ def validate_date_field(date_value, field_name):
|
|
|
611
750
|
return
|
|
612
751
|
except (ValueError, OSError):
|
|
613
752
|
raise ValueError(f"Field '{field_name}' timestamp is invalid: {date_value}")
|
|
614
|
-
|
|
753
|
+
|
|
615
754
|
# If we get here, the type is not supported
|
|
616
|
-
raise ValueError(
|
|
755
|
+
raise ValueError(
|
|
756
|
+
f"Field '{field_name}' must be a datetime object, ISO format string, timestamp, or relative time. Got type: {type(date_value)}"
|
|
757
|
+
)
|
|
617
758
|
|
|
618
759
|
|
|
619
760
|
def validate_eventlog_query(query):
|
|
620
761
|
"""
|
|
621
762
|
Validate the eventlog query structure and required fields
|
|
622
|
-
|
|
763
|
+
|
|
623
764
|
Args:
|
|
624
765
|
query: The query dictionary to validate
|
|
625
|
-
|
|
766
|
+
|
|
626
767
|
Raises:
|
|
627
768
|
ValueError: If validation fails
|
|
628
769
|
"""
|
|
629
770
|
if not isinstance(query, dict):
|
|
630
771
|
raise ValueError("Query must be a dictionary")
|
|
631
|
-
|
|
772
|
+
|
|
632
773
|
# Set defaults for missing required fields
|
|
633
|
-
if
|
|
634
|
-
query[
|
|
635
|
-
if
|
|
636
|
-
query[
|
|
637
|
-
|
|
774
|
+
if "start" not in query:
|
|
775
|
+
query["start"] = "yesterday"
|
|
776
|
+
if "end" not in query:
|
|
777
|
+
query["end"] = "now"
|
|
778
|
+
|
|
638
779
|
# Validate the date fields
|
|
639
|
-
required_fields = [
|
|
780
|
+
required_fields = ["start", "end"]
|
|
640
781
|
for field in required_fields:
|
|
641
782
|
validate_date_field(query[field], field)
|
{python_eigen_ingenuity-0.5.19b1.dist-info → python_eigen_ingenuity-0.5.20.dist-info}/RECORD
RENAMED
|
@@ -2,13 +2,13 @@ eigeningenuity/__init__.py,sha256=DwkzJMZccpxj9rZ9zV4CkY2P7zkOGgfBVXaw6MedeTw,18
|
|
|
2
2
|
eigeningenuity/assetmodel.py,sha256=crDvVkzZ6j3TDkKSxhkthttsjzTqdOlKcv2_TgSGy1Q,16789
|
|
3
3
|
eigeningenuity/auth.py,sha256=RjmtLBS6m4YhDZJa7RgB4RYWJDhE4zd-9tKeOz0iNug,7578
|
|
4
4
|
eigeningenuity/elastic.py,sha256=LJYDNTi0MJfryUFq5zkiDTQOXnzOo9GOoA3zoxpZ94s,6652
|
|
5
|
-
eigeningenuity/events.py,sha256=
|
|
5
|
+
eigeningenuity/events.py,sha256=0mJU9OknL5cP2sdABwbpWEc-WLv8GglrQQqoUCJENa0,9468
|
|
6
6
|
eigeningenuity/historian.py,sha256=UCUjSVF6T1RVjydnX-aZWFlcQ5nQqqC7F_fbBnVPDwQ,36341
|
|
7
7
|
eigeningenuity/historianmulti.py,sha256=1zkSMNPZih4rJQqYP8Y6dRAHmo4VvRoHUJo0HHkiawU,27418
|
|
8
8
|
eigeningenuity/settings.py,sha256=sCY7AONBrc0IWSa3D37Scu_JapQoEBfJbRbY7BdDoBM,4212
|
|
9
9
|
eigeningenuity/smartdash.py,sha256=45c52XbdayYUUgc2DS-RZuq59SiTm1cglA1Yq8ObZvk,3033
|
|
10
10
|
eigeningenuity/sql.py,sha256=r9kHjOymZxKY2HpAT3jYSr77oSDyT8UK-DLSaSDk7zI,5063
|
|
11
|
-
eigeningenuity/util.py,sha256=
|
|
11
|
+
eigeningenuity/util.py,sha256=y3P_PH3vfpYK17u00GaRV0lvTiP04olIWcdKockF2Ho,22752
|
|
12
12
|
eigeningenuity/core/__init__.py,sha256=WKu5uGz7wl2JZH7VPCSohpJvAz44EOXuj91int-EHDs,8956
|
|
13
13
|
local-tests/__init__.py,sha256=oe1wRdOprjUbn027t5ybBBo5T9_byi-burZFgv64ND4,149
|
|
14
14
|
local-tests/common.py,sha256=dIMBplH4P4T-BlhODjD5_RLhK2uA18MxEesiIMslsG0,1766
|
|
@@ -68,6 +68,7 @@ regressiontests/eigeningenuity/common.py,sha256=mskb8t99yhcOdGVxSMYKwX3uobWaH-H2
|
|
|
68
68
|
regressiontests/eigeningenuity/common_multi.py,sha256=XB_icW3YBB-Y6ZHA_wESf3DmdzG4yn4V1SoLFt-ziUM,5441
|
|
69
69
|
regressiontests/eigeningenuity/historian/__init__.py,sha256=0GYb2g7kCchhb2Pl9Tsp4VCJeSs9WoyWAyRIbFYV1vs,29
|
|
70
70
|
regressiontests/eigeningenuity/historian/common.py,sha256=9sOgPbz7oCaMu4b1pjzgCU61-jy1IZ6-ddHhzSpRkzA,4231
|
|
71
|
+
regressiontests/eigeningenuity/historian/test_deprecation_warning.py,sha256=rvt5GohWEsubBzokbdDcKLcnDvmMVMC6NUaAqP8Bimc,3316
|
|
71
72
|
regressiontests/eigeningenuity/historian/test_getCurrentDataPoints.py,sha256=kKH5wHWEJF-8b6UCFTzjKgMENfClcxJzgcRP58bzwP4,7100
|
|
72
73
|
regressiontests/eigeningenuity/historian/test_getInterpolatedPoints.py,sha256=k2B_Uor-CiPBtn5vC2C6gDx6vpF_LaDg1kakDIBmMqE,6773
|
|
73
74
|
regressiontests/eigeningenuity/historian/test_getInterpolatedRange.py,sha256=OxwG7u8c6dQySsblwO1gNAwWzLlNfhxZ-Mc2GR9AQ3A,7083
|
|
@@ -86,8 +87,8 @@ regressiontests/eigeningenuity/historian-multi/test_getRawDatapoints.py,sha256=f
|
|
|
86
87
|
regressiontests/eigeningenuity/historian-multi/test_listDataTags.py,sha256=TcceNSjCKoiK5SJcgTH2JXfKLYxIHdQdwZWlkpGnEVM,2006
|
|
87
88
|
regressiontests/eigeningenuity/historian-multi/test_tagManagement.py,sha256=ylInBt453d1RaSih1eTTxGPZmb60UK4vMwI3UW-U1JY,4830
|
|
88
89
|
regressiontests/eigeningenuity/historian-multi/test_writePoints.py,sha256=51tfUSLUqLKcCKJ1EyhjfzoC_4OP6n1oL3zgTSkXu4s,2696
|
|
89
|
-
python_eigen_ingenuity-0.5.
|
|
90
|
-
python_eigen_ingenuity-0.5.
|
|
91
|
-
python_eigen_ingenuity-0.5.
|
|
92
|
-
python_eigen_ingenuity-0.5.
|
|
93
|
-
python_eigen_ingenuity-0.5.
|
|
90
|
+
python_eigen_ingenuity-0.5.20.dist-info/METADATA,sha256=DQz-yg8t-FEr9hXw5swMLV8pY7a7LkP4w9cyyiZQnFc,38419
|
|
91
|
+
python_eigen_ingenuity-0.5.20.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
92
|
+
python_eigen_ingenuity-0.5.20.dist-info/entry_points.txt,sha256=G3LjFQX5xKaN4mqtqCL8uaC-gRbP5T5x9r0gBTJTXXA,70
|
|
93
|
+
python_eigen_ingenuity-0.5.20.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
|
|
94
|
+
python_eigen_ingenuity-0.5.20.dist-info/RECORD,,
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Test to verify that deprecation warnings are properly shown when using the old historian module.
|
|
3
|
+
This ensures users are properly notified about the deprecation.
|
|
4
|
+
"""
|
|
5
|
+
import sys
|
|
6
|
+
import os
|
|
7
|
+
import unittest
|
|
8
|
+
import warnings
|
|
9
|
+
|
|
10
|
+
# Import the common test configuration
|
|
11
|
+
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
|
12
|
+
from common import BaseHistorianTest
|
|
13
|
+
|
|
14
|
+
class TestDeprecationWarning(BaseHistorianTest):
|
|
15
|
+
"""Test class to verify deprecation warnings are working correctly"""
|
|
16
|
+
|
|
17
|
+
def test_historian_deprecation_warning_is_raised(self):
|
|
18
|
+
"""Test that using get_historian raises a deprecation warning"""
|
|
19
|
+
from eigeningenuity import EigenServer, get_historian
|
|
20
|
+
|
|
21
|
+
# Capture warnings to verify the deprecation warning is raised
|
|
22
|
+
with warnings.catch_warnings(record=True) as warning_list:
|
|
23
|
+
# Ensure all warnings are captured
|
|
24
|
+
warnings.simplefilter("always")
|
|
25
|
+
|
|
26
|
+
# This should trigger the deprecation warning
|
|
27
|
+
server = EigenServer("demo-dev.eigen.co")
|
|
28
|
+
_ = get_historian("Demo-influxdb", server) # Create historian to trigger warning
|
|
29
|
+
|
|
30
|
+
# Verify that at least one deprecation warning was raised
|
|
31
|
+
deprecation_warnings = [w for w in warning_list if issubclass(w.category, DeprecationWarning)]
|
|
32
|
+
self.assertGreater(len(deprecation_warnings), 0,
|
|
33
|
+
"Expected deprecation warning was not raised when using get_historian")
|
|
34
|
+
|
|
35
|
+
# Verify the specific deprecation message
|
|
36
|
+
expected_message = "eigeningenuity.historian.get_historian is deprecated"
|
|
37
|
+
found_expected_warning = any(expected_message in str(w.message) for w in deprecation_warnings)
|
|
38
|
+
self.assertTrue(found_expected_warning,
|
|
39
|
+
f"Expected deprecation warning message not found. Got warnings: {[str(w.message) for w in deprecation_warnings]}")
|
|
40
|
+
|
|
41
|
+
def test_historian_multi_does_not_raise_deprecation_warning(self):
|
|
42
|
+
"""Test that using get_historian_multi does NOT raise a deprecation warning"""
|
|
43
|
+
from eigeningenuity.historianmulti import get_historian_multi
|
|
44
|
+
from eigeningenuity import EigenServer
|
|
45
|
+
|
|
46
|
+
# Capture warnings to verify no deprecation warning is raised
|
|
47
|
+
with warnings.catch_warnings(record=True) as warning_list:
|
|
48
|
+
# Ensure all warnings are captured
|
|
49
|
+
warnings.simplefilter("always")
|
|
50
|
+
|
|
51
|
+
# This should NOT trigger a deprecation warning
|
|
52
|
+
server = EigenServer("demo-dev.eigen.co")
|
|
53
|
+
_ = get_historian_multi(server, "Demo-influxdb") # Create historian_multi (should not warn)
|
|
54
|
+
|
|
55
|
+
# Verify that no deprecation warnings were raised for historian
|
|
56
|
+
historian_deprecation_warnings = [w for w in warning_list
|
|
57
|
+
if issubclass(w.category, DeprecationWarning)
|
|
58
|
+
and "historian" in str(w.message).lower()]
|
|
59
|
+
self.assertEqual(len(historian_deprecation_warnings), 0,
|
|
60
|
+
f"Unexpected deprecation warning raised when using get_historian_multi: {[str(w.message) for w in historian_deprecation_warnings]}")
|
|
61
|
+
|
|
62
|
+
if __name__ == '__main__':
|
|
63
|
+
unittest.main()
|
|
File without changes
|
|
File without changes
|
{python_eigen_ingenuity-0.5.19b1.dist-info → python_eigen_ingenuity-0.5.20.dist-info}/top_level.txt
RENAMED
|
File without changes
|