291 Commits

Author SHA1 Message Date
stephb9959
64ba6f4d67 https://telecominfraproject.atlassian.net/browse/WIFI-12868
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-09-01 09:24:19 -07:00
stephb9959
3d83d6a80e https://telecominfraproject.atlassian.net/browse/WIFI-12868
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-09-01 09:19:19 -07:00
stephb9959
43cae660de https://telecominfraproject.atlassian.net/browse/WIFI-12868
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-08-03 22:29:28 -07:00
stephb9959
d71be33cc3 https://telecominfraproject.atlassian.net/browse/WIFI-12868
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-08-03 11:07:01 -07:00
stephb9959
965ea73a13 https://telecominfraproject.atlassian.net/browse/WIFI-12868
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-08-03 10:56:44 -07:00
Jaspreet Sachdev
faa678d4e7 Fixed the $#
Signed-off-by: Jaspreet Sachdev <jaspreetsachdev@meta.com>
2023-06-13 17:50:19 -04:00
stephb9959
3c2503bc79 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-30 22:44:15 -07:00
stephb9959
e8d11c8631 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-30 22:42:10 -07:00
stephb9959
c0eda00485 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-30 08:39:10 -07:00
stephb9959
43ee46ea8a https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-30 08:32:05 -07:00
stephb9959
9584e1833c https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-30 08:16:13 -07:00
stephb9959
ba0ae691bf https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-30 08:01:01 -07:00
stephb9959
9dc9d11bce https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-30 07:52:39 -07:00
stephb9959
c9f692a067 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 22:48:03 -07:00
stephb9959
b8f7e8528e https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 22:38:08 -07:00
stephb9959
3cf1013fcb https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 22:30:47 -07:00
stephb9959
69772aaef2 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 22:20:02 -07:00
stephb9959
9382999719 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 22:12:30 -07:00
stephb9959
06e69405c0 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 22:08:13 -07:00
stephb9959
bcaee74193 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 22:01:25 -07:00
stephb9959
260543096d https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 21:44:35 -07:00
stephb9959
c11de3598f https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 21:22:03 -07:00
stephb9959
1173e5b088 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 14:45:22 -07:00
stephb9959
be893a0b08 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 08:31:05 -07:00
stephb9959
eeec24cd11 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-29 08:14:04 -07:00
stephb9959
bf8d73c947 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-26 14:28:50 -07:00
stephb9959
06fffea197 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-26 14:19:58 -07:00
stephb9959
39f012a429 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-26 14:02:13 -07:00
stephb9959
4a1e4d9cba https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 23:52:40 -07:00
stephb9959
b8d5f9e2b4 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 23:43:51 -07:00
stephb9959
033f67fac4 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 23:29:41 -07:00
stephb9959
9c75e989b5 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 23:19:41 -07:00
stephb9959
0d5c42fe9f https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 23:12:32 -07:00
stephb9959
adfbd2d52b https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 22:47:42 -07:00
stephb9959
93aa2e300f https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 13:33:48 -07:00
stephb9959
218da6d7d5 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 13:29:42 -07:00
stephb9959
f0fea163e4 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 13:14:22 -07:00
stephb9959
dc90ad1698 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 13:03:35 -07:00
stephb9959
d13526606d https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 11:09:57 -07:00
stephb9959
45126be0dc https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 08:27:45 -07:00
stephb9959
cf0677910f https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 08:18:52 -07:00
stephb9959
475522d5dc https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-25 08:04:15 -07:00
stephb9959
7be435a27b https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-24 15:47:48 -07:00
stephb9959
487a038903 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-24 09:46:15 -07:00
stephb9959
e4fd1c4f7e https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-24 09:42:21 -07:00
stephb9959
3c529dbba0 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-05-24 09:06:42 -07:00
stephb9959
94636ea1dc https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-24 08:56:47 -07:00
stephb9959
b4b2b08336 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-05-24 07:29:07 -07:00
stephb9959
fda78a1d8b https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-24 07:27:59 -07:00
stephb9959
f4e7c212fa Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-05-22 10:51:05 -07:00
stephb9959
77c46ad267 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-22 10:50:42 -07:00
stephb9959
8b67aa61c0 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-05-22 10:46:08 -07:00
stephb9959
f2fdf68130 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-22 10:45:11 -07:00
stephb9959
9edba2c9c7 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-05-22 10:31:01 -07:00
stephb9959
e427b4cd25 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-22 10:30:53 -07:00
stephb9959
81c872151b Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-05-22 10:25:38 -07:00
stephb9959
18257c8247 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-05-22 10:25:14 -07:00
stephb9959
a51746f396 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	build
2023-04-19 13:44:45 -07:00
stephb9959
0057483346 https://telecominfraproject.atlassian.net/browse/WIFI-12525
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-19 13:44:12 -07:00
stephb9959
3163684eac Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-19 08:58:50 -07:00
Stephane Bourque
1033985339 Merge pull request #29 from Telecominfraproject/WIFI-12378
https://telecominfraproject.atlassian.net/browse/WIFI-12378
2023-04-19 08:44:10 -07:00
stephb9959
e07d472142 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-19 08:39:43 -07:00
stephb9959
9af3ffe38f https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-19 08:37:49 -07:00
stephb9959
4ccc990ac4 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-19 08:15:07 -07:00
stephb9959
8e0a21fd9a Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 23:23:48 -07:00
stephb9959
cd2715da65 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 23:23:21 -07:00
stephb9959
26f49c254f Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 23:15:40 -07:00
stephb9959
be47fe6d57 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 23:15:15 -07:00
stephb9959
d9ecc1aac7 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 23:09:06 -07:00
stephb9959
ca5520a395 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 23:08:50 -07:00
stephb9959
b7ba377a0c Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 22:58:50 -07:00
stephb9959
7ba8d765c4 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 22:58:42 -07:00
stephb9959
91e27fe0c4 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 22:40:02 -07:00
stephb9959
8ec49a9846 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 22:39:51 -07:00
stephb9959
28f4ea5145 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 22:15:44 -07:00
stephb9959
f453a952db https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 22:15:37 -07:00
stephb9959
e98c8f2340 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 22:06:12 -07:00
stephb9959
0a120c2693 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 22:06:05 -07:00
stephb9959
132bbfc597 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 22:04:47 -07:00
stephb9959
f050470ed3 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 22:04:34 -07:00
stephb9959
03e0031429 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 21:57:23 -07:00
stephb9959
78980f5cd7 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 21:57:16 -07:00
stephb9959
a2d44f3d64 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 21:56:08 -07:00
stephb9959
bf06e7ebe8 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 21:55:50 -07:00
stephb9959
1de06904c6 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 21:32:53 -07:00
stephb9959
26fb93dc6f https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 21:32:46 -07:00
stephb9959
8b570d8d62 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 21:25:53 -07:00
stephb9959
ed910d50d4 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 21:25:08 -07:00
stephb9959
d0106a9687 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 16:41:00 -07:00
stephb9959
de4800a896 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 16:40:42 -07:00
stephb9959
3bbe5e2d1b Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 15:05:54 -07:00
stephb9959
a4e1997361 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 15:05:33 -07:00
stephb9959
eff23f22d9 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 14:31:01 -07:00
stephb9959
ecdef5912e https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 14:30:41 -07:00
stephb9959
5bc6232a89 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 14:12:58 -07:00
stephb9959
e258772ea4 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 14:12:39 -07:00
stephb9959
aefd6ccf37 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 14:07:41 -07:00
stephb9959
6be8168a5a https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 14:07:29 -07:00
stephb9959
eafe534aad Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 14:04:15 -07:00
stephb9959
7cfea54f0f https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 14:03:59 -07:00
stephb9959
50b8113d18 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 13:59:50 -07:00
stephb9959
12ec99008d https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 13:59:09 -07:00
stephb9959
050ad3c3d3 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 13:49:15 -07:00
stephb9959
cf3a2ef64a https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 13:48:49 -07:00
stephb9959
384a21fef3 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 13:41:02 -07:00
stephb9959
6c8fa9dba7 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 12:50:38 -07:00
stephb9959
788363d85b https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 12:50:05 -07:00
stephb9959
d719d9b9ce Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 12:35:25 -07:00
stephb9959
d823500629 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 12:35:05 -07:00
stephb9959
6f52e8bf85 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 12:25:41 -07:00
stephb9959
8f9cf5d8e2 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 12:25:32 -07:00
stephb9959
259d2722dc Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 12:19:41 -07:00
stephb9959
979888c9dc https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 12:19:13 -07:00
stephb9959
eedfce997d Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 12:16:29 -07:00
stephb9959
bbaff51002 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 12:16:11 -07:00
stephb9959
0dbe8e2c81 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 12:08:26 -07:00
stephb9959
e967f6b28b https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 12:08:13 -07:00
stephb9959
1899728e21 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 11:40:34 -07:00
stephb9959
c6edb6be43 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 11:40:27 -07:00
stephb9959
28e6362b32 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 11:07:18 -07:00
stephb9959
866dc044f9 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 11:06:55 -07:00
stephb9959
7bd9fe147f Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 10:55:29 -07:00
stephb9959
e6551b7f84 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 10:53:55 -07:00
stephb9959
c8002c55ea Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 10:46:39 -07:00
stephb9959
efc7b9e915 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 10:45:54 -07:00
stephb9959
f978ff0f06 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-18 07:47:41 -07:00
stephb9959
0ddcf18c2c https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-18 07:45:07 -07:00
stephb9959
1d61ee6539 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-17 11:00:15 -07:00
stephb9959
aec865aac4 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 10:59:47 -07:00
stephb9959
acdce83ef9 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-17 10:12:52 -07:00
stephb9959
b3ab806a67 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 10:06:47 -07:00
stephb9959
088ab3bdad https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 10:05:44 -07:00
stephb9959
c3741f177e https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 09:52:57 -07:00
stephb9959
5a4807b6fa https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 09:52:37 -07:00
stephb9959
f44d135acf Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-17 09:45:10 -07:00
stephb9959
f551eed6f5 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 09:44:27 -07:00
stephb9959
f199cbdaec Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-17 09:26:34 -07:00
stephb9959
bc3c56a737 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 09:25:25 -07:00
stephb9959
2cfb573c67 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 09:19:13 -07:00
stephb9959
0eef450565 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-17 08:46:28 -07:00
stephb9959
4b9455e7fc https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 08:46:16 -07:00
stephb9959
1c4bd5835c Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-17 08:41:33 -07:00
stephb9959
9c97b043fd https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 08:40:56 -07:00
stephb9959
2129861184 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-17 08:27:26 -07:00
stephb9959
91f3bd66cd https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-17 08:27:00 -07:00
stephb9959
dbf8fd4a9d Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 23:24:21 -07:00
stephb9959
bf8fd955d4 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 23:23:56 -07:00
stephb9959
3b8efb40ef Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 23:17:12 -07:00
stephb9959
fcddf2f980 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 23:16:57 -07:00
stephb9959
bb23cb22ad Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 23:10:22 -07:00
stephb9959
eca5584f67 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 23:10:07 -07:00
stephb9959
716cf134f1 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 22:24:31 -07:00
stephb9959
5f1b31c149 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 22:24:19 -07:00
stephb9959
0b8d7fdc5c Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 22:09:34 -07:00
stephb9959
78530fbcf8 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 22:09:20 -07:00
stephb9959
01d099c586 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 21:37:30 -07:00
stephb9959
a7d81c9f85 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 21:37:09 -07:00
stephb9959
21df075a8a Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 21:29:24 -07:00
stephb9959
22cc9776d7 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 21:29:11 -07:00
stephb9959
6f710c0344 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 21:27:48 -07:00
stephb9959
7bacf4e259 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 21:27:39 -07:00
stephb9959
7eb9e0c6cd Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 21:19:16 -07:00
stephb9959
65e06089c3 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 21:18:47 -07:00
stephb9959
ffaf5428d1 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 11:17:13 -07:00
stephb9959
b32da1bc5d https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 11:17:04 -07:00
stephb9959
ae508dcfd6 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 11:14:53 -07:00
stephb9959
3fea5e3864 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 11:14:37 -07:00
stephb9959
8fe56ded3a Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 10:09:40 -07:00
stephb9959
dcced2d9ff https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 10:09:29 -07:00
stephb9959
1f2c3f609c Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 10:02:58 -07:00
stephb9959
19d0ece5d7 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 10:02:46 -07:00
stephb9959
051612334d Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 09:54:33 -07:00
stephb9959
1da80ff7b9 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 09:54:18 -07:00
stephb9959
52225e355b Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 09:42:24 -07:00
stephb9959
c2650d4d41 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 09:42:17 -07:00
stephb9959
a17a5ec74b Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 09:07:10 -07:00
stephb9959
d10925c108 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 09:06:16 -07:00
stephb9959
856f868af9 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 08:44:43 -07:00
stephb9959
2fe4991c4b https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 08:44:20 -07:00
stephb9959
d7dc336fa9 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-16 08:34:01 -07:00
stephb9959
d24d6d3b55 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-16 08:32:37 -07:00
stephb9959
cf50a7125a Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 23:39:53 -07:00
stephb9959
21d31c0681 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 23:38:53 -07:00
stephb9959
0164794f50 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 23:34:42 -07:00
stephb9959
fd26554af0 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 23:33:56 -07:00
stephb9959
389743a6d0 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 23:28:01 -07:00
stephb9959
5087e77708 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 23:27:42 -07:00
stephb9959
75a491d2dd Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 23:23:46 -07:00
stephb9959
0b1c1fdf69 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 23:23:36 -07:00
stephb9959
3cd669f4a3 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 23:05:45 -07:00
stephb9959
9529c4499f https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 23:05:36 -07:00
stephb9959
61b5f9bf3a Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 22:55:53 -07:00
stephb9959
63b18bc78e https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 22:55:44 -07:00
stephb9959
656b32f1db Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 22:37:01 -07:00
stephb9959
440f437502 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 22:36:12 -07:00
stephb9959
55871aa07e Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 22:23:10 -07:00
stephb9959
2be2b55aa7 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 22:22:59 -07:00
stephb9959
ea8bdb1f65 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 22:07:45 -07:00
stephb9959
e3f2e7e102 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 22:07:36 -07:00
stephb9959
b266e5f450 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 22:00:36 -07:00
stephb9959
6191872277 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 22:00:24 -07:00
stephb9959
96e89ba0dd Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 21:54:00 -07:00
stephb9959
43fca22c43 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 21:53:49 -07:00
stephb9959
cbc7c8c564 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 21:47:45 -07:00
stephb9959
aef29b320c https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 21:47:36 -07:00
stephb9959
a8963de508 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 21:39:31 -07:00
stephb9959
2a918f4574 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 21:39:22 -07:00
stephb9959
bf10713b7f Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 21:37:57 -07:00
stephb9959
80fb6ac69f Merge remote-tracking branch 'origin/WIFI-12378' into WIFI-12378
# Conflicts:
#	src/SimulationRunner.cpp
2023-04-15 21:35:15 -07:00
stephb9959
a7e36e4c3c https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 21:34:55 -07:00
stephb9959
9a0156dea9 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 21:27:45 -07:00
stephb9959
3a4f5391f3 Do Not Track
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 21:27:09 -07:00
stephb9959
47092ac303 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 20:55:26 -07:00
stephb9959
4b4ced0429 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 20:52:05 -07:00
stephb9959
d7d487856d Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 07:00:02 -07:00
stephb9959
204ca3b217 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 06:59:42 -07:00
stephb9959
364797e945 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 06:58:36 -07:00
stephb9959
00f4be21ff Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-15 06:56:11 -07:00
stephb9959
f5320371f5 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-15 06:55:48 -07:00
stephb9959
2f57241432 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 10:14:50 -07:00
stephb9959
1a4c696e1a https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 10:14:43 -07:00
stephb9959
7035049b7d Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 10:11:15 -07:00
stephb9959
3a214b09a0 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 10:11:06 -07:00
stephb9959
d28056a43c Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 10:05:56 -07:00
stephb9959
705b315578 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 10:05:49 -07:00
stephb9959
d9c8274bee Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:59:58 -07:00
stephb9959
a8495445e9 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:59:50 -07:00
stephb9959
9ff09e8a13 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:57:35 -07:00
stephb9959
16a038e660 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:57:27 -07:00
stephb9959
987abb64ab Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:54:37 -07:00
stephb9959
f2ff13a53e https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:54:30 -07:00
stephb9959
265cd1ed5c Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:49:56 -07:00
stephb9959
a7d961d88e https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:49:48 -07:00
stephb9959
dcad05dd85 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:43:06 -07:00
stephb9959
df3fa0645d https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:42:57 -07:00
stephb9959
0499fb51dc Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:41:45 -07:00
stephb9959
fa78d25b3b https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:41:36 -07:00
stephb9959
10a55031e4 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:39:29 -07:00
stephb9959
f08f496581 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:39:19 -07:00
stephb9959
fe23a777d0 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:36:37 -07:00
stephb9959
191a206bfc https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:36:16 -07:00
stephb9959
1f0fa3ae6c Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:31:03 -07:00
stephb9959
9753b35b2a https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:30:53 -07:00
stephb9959
7ae8498b18 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:29:30 -07:00
stephb9959
f1665a20ac https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:29:07 -07:00
stephb9959
5afac8092e Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 09:19:39 -07:00
stephb9959
b209333793 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 09:12:13 -07:00
stephb9959
2615d0113a Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 08:58:46 -07:00
stephb9959
d0be28148f https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 08:58:28 -07:00
stephb9959
641ab1ad50 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-14 08:55:06 -07:00
stephb9959
f4557e3157 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 08:54:28 -07:00
stephb9959
fa826030e0 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 08:10:26 -07:00
stephb9959
3602772df6 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-14 07:39:30 -07:00
stephb9959
8300d387f4 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-13 16:56:45 -07:00
stephb9959
a18ce9e8f4 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-13 16:56:28 -07:00
stephb9959
44efafa206 Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-13 16:34:15 -07:00
stephb9959
49fe5f9108 https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-13 16:34:03 -07:00
stephb9959
82e8f3373c Merge branch 'WIFI-12378' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-04-13 16:31:45 -07:00
stephb9959
dc26332dbe https://telecominfraproject.atlassian.net/browse/WIFI-12378
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-04-13 16:30:36 -07:00
stephb9959
b02ad2834e https://telecominfraproject.atlassian.net/browse/WIFI-12068
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-03-13 12:02:26 -07:00
stephb9959
f69b6b10a2 https://telecominfraproject.atlassian.net/browse/WIFI-12068
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-03-13 10:51:49 -07:00
stephb9959
565ee836fa https://telecominfraproject.atlassian.net/browse/WIFI-12068
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-03-02 13:09:46 -08:00
stephb9959
2e59557b3e Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-03-02 13:01:25 -08:00
stephb9959
9311af7992 https://telecominfraproject.atlassian.net/browse/WIFI-12068
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-03-02 13:00:26 -08:00
stephb9959
7a5b4a021c https://telecominfraproject.atlassian.net/browse/WIFI-12068
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-02-21 13:44:19 -08:00
stephb9959
08e69b1d5b https://telecominfraproject.atlassian.net/browse/WIFI-12068
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-02-15 08:34:47 -08:00
stephb9959
76153ea83e https://telecominfraproject.atlassian.net/browse/WIFI-12068
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-02-15 08:34:36 -08:00
stephb9959
76549c52f4 https://telecominfraproject.atlassian.net/browse/WIFI-12068
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-01-10 21:54:55 -08:00
stephb9959
e39e58b09b Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2023-01-08 11:54:31 -08:00
stephb9959
24bce3f7fb Merge remote-tracking branch 'origin/main'
# Conflicts:
#	build
2023-01-08 11:06:56 -08:00
stephb9959
f708ae6256 https://telecominfraproject.atlassian.net/browse/WIFI-12068
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2023-01-08 11:06:47 -08:00
stephb9959
0118650be6 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-12-20 11:27:02 -08:00
stephb9959
85858d40b9 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-12-14 12:25:34 -08:00
stephb9959
1e77c7a746 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-11-27 22:03:48 -08:00
stephb9959
2493511ad6 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-11-18 20:05:39 -08:00
stephb9959
1310865a70 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-11-17 21:42:23 -08:00
stephb9959
9d77130c5d Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-11-17 11:48:29 -08:00
stephb9959
b0a59f97e5 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-11-16 10:43:01 -08:00
stephb9959
d4e8b468e9 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-11-07 15:55:25 -08:00
stephb9959
6cf96051bc Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-11-03 10:17:40 -07:00
stephb9959
e0bae5e975 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-10-30 23:40:25 -07:00
stephb9959
4ed5cda4d0 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-10-27 09:46:55 -07:00
stephb9959
6059927eea Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-10-27 09:38:56 -07:00
stephb9959
90738bcc29 Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-10-04 08:36:01 -07:00
stephb9959
f36ede98dc Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-09-30 20:33:30 -07:00
stephb9959
54079e014a Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-09-30 15:16:03 -07:00
stephb9959
39abb170dd Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-09-30 15:07:01 -07:00
stephb9959
bccbbf685d Merge branch 'main' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-09-14 15:44:12 -07:00
stephb9959
7fc9273484 Merge branch 'WIFI-10713' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-09-14 15:40:43 -07:00
stephb9959
43f3dff19b Merge branch 'WIFI-10713' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-09-14 15:22:14 -07:00
stephb9959
9d21987fd1 Merge branch 'WIFI-10713' of https://github.com/telecominfraproject/wlan-cloud-owls into main 2022-09-14 15:14:31 -07:00
138 changed files with 20363 additions and 15342 deletions

178
.clang-format Normal file
View File

@@ -0,0 +1,178 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveMacros: None
AlignConsecutiveAssignments: None
AlignConsecutiveBitFields: None
AlignConsecutiveDeclarations: None
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortEnumsOnASingleLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
AttributeMacros:
- __capability
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: true
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 100
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseLabels: false
IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentExternBlock: AfterExternBlock
IndentRequires: false
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertTrailingCommas: None
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
LambdaBodyIndentation: Signature
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: All
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PenaltyIndentedWhitespace: 0
PointerAlignment: Right
PPIndentWidth: -1
ReferenceAlignment: Pointer
ReflowComments: true
ShortNamespaceLines: 1
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceAroundPointerQualifiers: Default
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
BitFieldColonSpacing: Both
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 4
UseCRLF: false
UseTab: Always
WhitespaceSensitiveMacros:
- STRINGIZE
- PP_STRINGIZE
- BOOST_PP_STRINGIZE
- NS_SWIFT_NAME
- CF_SWIFT_NAME
...

2
.gitignore vendored
View File

@@ -37,6 +37,7 @@ git_rsa
/cmake-build/
/cmake-build-debug/
/data/
/owls.properties.good
# Helm
*.swp
@@ -45,3 +46,4 @@ helm/charts/*
# Logs
test_scripts/curl/*.json
/src/ow_version.h

2
.idea/.name generated
View File

@@ -1 +1 @@
ucentral_clnt
owls

4
.idea/modules.xml generated
View File

@@ -2,7 +2,7 @@
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ucentral-clnt.iml" filepath="$PROJECT_DIR$/.idea/ucentral-clnt.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/owls.iml" filepath="$PROJECT_DIR$/.idea/owls.iml" />
</modules>
</component>
</project>
</project>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module classpath="CMake" type="CPP_MODULE" version="4" />

View File

@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.13)
project(owls VERSION 2.8.1)
project(owls VERSION 2.10.0)
# cmake .. -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl@1.1 -DMYSQL_ROOT_DIR=/usr/local/opt/mysql-client
@@ -46,13 +46,14 @@ find_package(ZLIB REQUIRED)
find_package(fmt REQUIRED)
find_package(CppKafka REQUIRED)
find_package(nlohmann_json REQUIRED)
find_package(nlohmann_json_schema_validator REQUIRED)
find_package(Poco REQUIRED COMPONENTS Crypto Net Util JWT NetSSL Data DataSQLite DataPostgreSQL DataMySQL)
include_directories(/usr/local/include /usr/local/opt/openssl/include src include/kafka /usr/local/opt/mysql-client/include)
configure_file(src/ow_version.h.in ${PROJECT_SOURCE_DIR}/src/ow_version.h @ONLY)
add_definitions(-DPOCO_LOG_DEBUG="1")
add_compile_options(-Wall -Wextra)
if(ASAN)
add_compile_options(-fsanitize=address)
@@ -107,6 +108,7 @@ add_executable( owls
src/framework/RESTAPI_PartHandler.h
src/framework/MicroService.cpp
src/framework/MicroServiceExtra.h
src/framework/default_device_types.h
src/RESTObjects/RESTAPI_SecurityObjects.h src/RESTObjects/RESTAPI_SecurityObjects.cpp
src/RESTObjects/RESTAPI_GWobjects.h src/RESTObjects/RESTAPI_GWobjects.cpp
src/RESTObjects/RESTAPI_FMSObjects.h src/RESTObjects/RESTAPI_FMSObjects.cpp
@@ -114,18 +116,17 @@ add_executable( owls
src/RESTObjects/RESTAPI_OWLSobjects.cpp src/RESTObjects/RESTAPI_OWLSobjects.h
src/RESTObjects/RESTAPI_ProvObjects.cpp src/RESTObjects/RESTAPI_ProvObjects.h
src/RESTObjects/RESTAPI_AnalyticsObjects.cpp src/RESTObjects/RESTAPI_AnalyticsObjects.h
src/RESTAPI/RESTAPI_routers.cpp
src/Daemon.cpp src/Daemon.h
src/Dashboard.cpp src/Dashboard.h
src/uCentralClient.cpp
src/uCentralClient.h
src/Simulator.cpp src/Simulator.h
src/uCentralEvent.cpp src/uCentralEvent.h
src/uCentralEventTypes.h
src/OWLSclient.cpp
src/OWLSclient.h
src/SimulationRunner.cpp src/SimulationRunner.h
# src/OWLSevent.cpp src/OWLSevent.h
src/OWLSdefinitions.h
src/SimStats.h
src/RESTAPI/RESTAPI_deviceDashboardHandler.cpp src/RESTAPI/RESTAPI_deviceDashboardHandler.h
src/StorageService.cpp src/StorageService.h src/storage/storage_simulations.cpp src/storage/storage_simulations.h src/storage/storage_results.cpp src/storage/storage_results.h src/RESTAPI/RESTAPI_simulation_handler.cpp src/RESTAPI/RESTAPI_simulation_handler.h src/RESTAPI/RESTAPI_results_handler.cpp src/RESTAPI/RESTAPI_results_handler.h src/RESTAPI/RESTAPI_status_handler.cpp src/RESTAPI/RESTAPI_status_handler.h src/RESTAPI/RESTAPI_operation_handler.cpp src/RESTAPI/RESTAPI_operation_handler.h src/Simulation.cpp src/Simulation.h src/UI_Owls_WebSocketNotifications.cpp src/UI_Owls_WebSocketNotifications.h)
src/StorageService.cpp src/StorageService.h src/storage/storage_simulations.cpp src/storage/storage_simulations.h src/storage/storage_results.cpp src/storage/storage_results.h src/RESTAPI/RESTAPI_simulation_handler.cpp src/RESTAPI/RESTAPI_simulation_handler.h src/RESTAPI/RESTAPI_results_handler.cpp src/RESTAPI/RESTAPI_results_handler.h src/RESTAPI/RESTAPI_status_handler.cpp src/RESTAPI/RESTAPI_status_handler.h src/RESTAPI/RESTAPI_operation_handler.cpp src/RESTAPI/RESTAPI_operation_handler.h src/SimulationCoordinator.cpp src/SimulationCoordinator.h src/UI_Owls_WebSocketNotifications.cpp src/UI_Owls_WebSocketNotifications.h src/OWLS_utils.h src/MockElements.h src/libs/ctpl_stl.h src/libs/Cron.h src/libs/InterruptableSleep.h src/libs/Scheduler.h src/OWLS_EstablishConnection.cpp src/OWLS_Reconnect.cpp src/OWLS_Connect.cpp src/OWLSclientEvents.h src/OWLS_State.cpp src/OWLS_HealthCheck.cpp src/OWLS_Log.cpp src/OWLS_Update.cpp src/OWLS_WSPing.cpp src/OWLS_KeepAlive.cpp src/OWLS_Disconnect.cpp src/OWLS_PendingConfig.cpp src/OWLS_CrashLog.cpp src/CensusReport.h)
target_link_libraries(owls PRIVATE
${Poco_LIBRARIES}
@@ -133,5 +134,4 @@ target_link_libraries(owls PRIVATE
${MySQL_LIBRARIES}
${ZLIB_LIBRARIES}
fmt::fmt
CppKafka::cppkafka
nlohmann_json_schema_validator)
CppKafka::cppkafka)

View File

@@ -1,7 +1,7 @@
ARG DEBIAN_VERSION=11.4-slim
ARG POCO_VERSION=poco-tip-v2
ARG CPPKAFKA_VERSION=tip-v1
ARG JSON_VALIDATOR_VERSION=2.1.0
ARG VALIJASON_VERSION=tip-v1
FROM debian:$DEBIAN_VERSION AS build-base
@@ -39,19 +39,19 @@ RUN cmake ..
RUN cmake --build . --config Release -j8
RUN cmake --build . --target install
FROM build-base AS json-schema-validator-build
FROM build-base AS valijson-build
ARG JSON_VALIDATOR_VERSION
ARG VALIJASON_VERSION
ADD https://api.github.com/repos/pboettch/json-schema-validator/git/refs/tags/${JSON_VALIDATOR_VERSION} version.json
RUN git clone https://github.com/pboettch/json-schema-validator --branch ${JSON_VALIDATOR_VERSION} /json-schema-validator
ADD https://api.github.com/repos/AriliaWireless/valijson/git/refs/tags/${VALIJASON_VERSION} version.json
RUN git clone https://github.com/AriliaWireless/valijson --branch ${VALIJASON_VERSION} /valijson
WORKDIR /json-schema-validator
WORKDIR /valijson
RUN mkdir cmake-build
WORKDIR cmake-build
RUN cmake ..
RUN make
RUN make install
RUN cmake --build . --config Release -j8
RUN cmake --build . --target install
FROM build-base AS owls-build
@@ -64,8 +64,7 @@ COPY --from=poco-build /usr/local/include /usr/local/include
COPY --from=poco-build /usr/local/lib /usr/local/lib
COPY --from=cppkafka-build /usr/local/include /usr/local/include
COPY --from=cppkafka-build /usr/local/lib /usr/local/lib
COPY --from=json-schema-validator-build /usr/local/include /usr/local/include
COPY --from=json-schema-validator-build /usr/local/lib /usr/local/lib
COPY --from=valijson-build /usr/local/include /usr/local/include
WORKDIR /owls
RUN mkdir cmake-build

2
build
View File

@@ -1 +1 @@
18
13

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,7 @@ openapi: 3.0.1
info:
title: OpenWifi Load Simulator
description: An application to test load on an OpenWifi system.
version: 2.5.0
version: 2.10.0
license:
name: BSD3
url: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
@@ -146,12 +146,6 @@ components:
- $ref: '#/components/schemas/StringList'
- $ref: '#/components/schemas/TagValuePairList'
SystemCommandResults:
type: object
oneOf:
- $ref: '#/components/schemas/StringList'
- $ref: '#/components/schemas/TagValuePairList'
SystemInfoResults:
type: object
properties:
@@ -180,6 +174,33 @@ components:
type: integer
format: int64
SystemResources:
type: object
properties:
numberOfFileDescriptors:
type: integer
format: int64
currRealMem:
type: integer
format: int64
peakRealMem:
type: integer
format: int64
currVirtMem:
type: integer
format: int64
peakVirtMem:
type: integer
format: int64
SystemCommandResults:
type: object
oneOf:
- $ref: '#/components/schemas/SystemResources'
- $ref: '#/components/schemas/SystemInfoResults'
- $ref: '#/components/schemas/StringList'
- $ref: '#/components/schemas/TagValuePairList'
SystemCommandSetLogLevel:
type: object
properties:
@@ -279,7 +300,7 @@ components:
maxLength: 6
devices:
type: integer
minimum: 1
minimum: 5
default: 10
maximum: 50000
healthCheckInterval:
@@ -300,7 +321,7 @@ components:
maxAssociations:
type: integer
minimum: 0
maximum: 32
maximum: 64
default: 8
minClients:
type: integer
@@ -310,7 +331,7 @@ components:
maxClients:
type: integer
minimum: 0
maximum: 32
maximum: 16
default: 4
simulationLength:
type: integer
@@ -403,21 +424,57 @@ components:
$ref: '#/components/schemas/SimulationStatus'
paths:
/simulation:
/simulation/{id}:
get:
tags:
- Simulations
operationId: getSimulations
parameters:
- in: path
name: id
description: The UUID of the specific simulation ID
schema:
type: string
format: uuid
required: true
example: Set this to the ID of the running simulation. To get the list of running simulations, set this to '*'
- in: query
name: offset
schema:
type: integer
format: int64
- in: query
name: limit
schema:
type: integer
format: int64
responses:
200:
$ref: '#/components/schemas/SimulationDetailsList'
description: A single or list of simulation definitions
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/SimulationDetailsList'
- $ref: '#/components/schemas/SimulationDetails'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
post:
tags:
- Simulations
operationId: createSimulation
parameters:
- in: path
name: id
description: The UUID of the specific simulation ID. Must be set to 0 for a POST
schema:
type: string
format: uuid
required: true
example: must be set to 0 to create a new simulation
requestBody:
description: Simulation details
content:
@@ -429,17 +486,21 @@ paths:
$ref: '#/components/schemas/SimulationDetails'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
put:
tags:
- Simulations
operationId: modifySimulation
parameters:
- in: query
- in: path
name: id
description: The UUID of the specific simulation ID
schema:
type: string
format: uuid
required: true
requestBody:
description: Simulation details
content:
@@ -451,79 +512,128 @@ paths:
$ref: '#/components/schemas/SimulationDetails'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
delete:
tags:
- Simulations
operationId: deleteSimulation
parameters:
- in: query
- in: path
name: id
schema:
type: string
format: uuid
required: true
responses:
200:
$ref: '#/components/responses/Success'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
/results:
/results/{id}:
get:
tags:
- Results
operationId: getSimulationResults
parameters:
- in: path
name: id
description: The UUID of the Simulation Definition
schema:
type: string
format: uuid
required: true
- in: query
name: offset
schema:
type: integer
format: int64
- in: query
name: limit
schema:
type: integer
format: int64
responses:
200:
$ref: '#/components/schemas/SimulationStatusList'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
delete:
tags:
- Results
operationId: deleteSimulationResults
parameters:
- in: query
- in: path
name: id
description: The UUID of the results to remove.
schema:
type: string
format: uuid
required: true
example: Set this to the ID of the running simulation. To get the list of running simulations, set this to '*'
responses:
200:
$ref: '#/components/responses/Success'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
/status:
/status/{id}:
get:
tags:
- Status
operationId: getStatusOfRunningSimulation
parameters:
- in: path
name: id
schema:
type: string
required: true
example: Set this to the ID of the running simulation. To get the list of running simulations, set this to '*'
responses:
200:
$ref: '#/components/schemas/SimulationStatus'
description: Successfully retrieved status list
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/SimulationStatus'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
/operation:
/operation/{id}:
post:
tags:
- Operations
operationId: createARunningSimulation
parameters:
- in: query
- in: path
name: id
description: The UUID of the specific simulation definition. Set this to 0 when creating a new running simulation
schema:
type: string
format: uuid
- in: query
name: simulationId
schema:
type: string
format: uuid
required: true
- in: query
name: operation
schema:
@@ -532,12 +642,21 @@ paths:
- start
- stop
- cancel
required: true
- in: query
name: runningId
description: Must be specified when stop or cancel re used.
schema:
type: string
format: uuid
responses:
200:
$ref: '#/components/schemas/SimulationStatus'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
@@ -588,16 +707,12 @@ paths:
type: string
enum:
- info
- extraConfiguration
- resources
required: true
responses:
200:
description: Successful command execution
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/SystemInfoResults'
$ref: '#/components/schemas/SystemCommandResults'
403:
$ref: '#/components/responses/Unauthorized'
404:

3170
sample_data/state-2-9.json Normal file

File diff suppressed because it is too large Load Diff

66
src/CensusReport.h Normal file
View File

@@ -0,0 +1,66 @@
//
// Created by stephane bourque on 2023-04-13.
//
#pragma once
#include <cstdint>
namespace OpenWifi {
struct CensusReport {
std::uint64_t
ev_none,
ev_reconnect,
ev_connect,
ev_state,
ev_healthcheck,
ev_log,
ev_crashlog,
ev_configpendingchange,
ev_keepalive,
ev_reboot,
ev_disconnect,
ev_wsping,
ev_update,
ev_configure,
ev_firmwareupgrade,
ev_factory,
ev_leds,
ev_trace,
ev_perform,
ev_establish_connection,
protocol_tx,
protocol_rx,
client_tx,
client_rx
;
void Reset() {
ev_none =
ev_reconnect =
ev_connect =
ev_state =
ev_healthcheck =
ev_log =
ev_crashlog =
ev_configpendingchange =
ev_keepalive =
ev_reboot =
ev_disconnect =
ev_wsping =
ev_update =
ev_configure =
ev_firmwareupgrade =
ev_factory =
ev_leds =
ev_trace =
ev_perform =
protocol_tx =
protocol_rx =
client_tx =
client_rx =
ev_establish_connection = 0;
}
};
}

View File

@@ -6,64 +6,57 @@
// Arilia Wireless Inc.
//
#include "Daemon.h"
#include "Simulation.h"
#include "StorageService.h"
#include "SimStats.h"
#include <Poco/Net/SSLManager.h>
#include <framework/UI_WebSocketClientServer.h>
#include "Poco/Net/SSLManager.h"
#include "Daemon.h"
#include "SimStats.h"
#include "SimulationCoordinator.h"
#include "StorageService.h"
#include "UI_Owls_WebSocketNotifications.h"
#include "framework/UI_WebSocketClientServer.h"
namespace OpenWifi {
class Daemon *Daemon::instance_ = nullptr;
class Daemon *Daemon::instance() {
if (instance_ == nullptr) {
instance_ = new Daemon(vDAEMON_PROPERTIES_FILENAME,
vDAEMON_ROOT_ENV_VAR,
vDAEMON_CONFIG_ENV_VAR,
vDAEMON_APP_NAME,
vDAEMON_BUS_TIMER,
SubSystemVec{
SimStats(),
StorageService(),
SimulationCoordinator(),
UI_WebSocketClientServer()
});
instance_ =
new Daemon(vDAEMON_PROPERTIES_FILENAME, vDAEMON_ROOT_ENV_VAR,
vDAEMON_CONFIG_ENV_VAR, vDAEMON_APP_NAME, vDAEMON_BUS_TIMER,
SubSystemVec{SimStats(), StorageService(), SimulationCoordinator(),
UI_WebSocketClientServer()});
}
return instance_;
}
void Daemon::PostInitialization([[maybe_unused]] Poco::Util::Application &self) {
}
void Daemon::PostInitialization([[maybe_unused]] Poco::Util::Application &self) {}
void DaemonPostInitialization(Poco::Util::Application &self) {
Daemon()->PostInitialization(self);
OWLSNotifications::Register();
}
}
void DaemonPostInitialization(Poco::Util::Application &self) {
Daemon()->PostInitialization(self);
OWLSNotifications::Register();
}
} // namespace OpenWifi
int main(int argc, char **argv) {
int ExitCode;
try {
Poco::Net::SSLManager::instance().initializeServer(nullptr, nullptr, nullptr);
auto App = OpenWifi::Daemon::instance();
ExitCode = App->run(argc, argv);
Poco::Net::SSLManager::instance().shutdown();
} catch (Poco::Exception &exc) {
ExitCode = Poco::Util::Application::EXIT_SOFTWARE;
std::cout << exc.displayText() << std::endl;
} catch (std::exception &exc) {
ExitCode = Poco::Util::Application::EXIT_TEMPFAIL;
std::cout << exc.what() << std::endl;
} catch (...) {
ExitCode = Poco::Util::Application::EXIT_TEMPFAIL;
std::cout << "Exception on closure" << std::endl;
}
int ExitCode;
try {
Poco::Net::SSLManager::instance().initializeServer(nullptr, nullptr, nullptr);
auto App = OpenWifi::Daemon::instance();
ExitCode = App->run(argc, argv);
Poco::Net::SSLManager::instance().shutdown();
} catch (Poco::Exception &exc) {
ExitCode = Poco::Util::Application::EXIT_SOFTWARE;
std::cout << exc.displayText() << std::endl;
} catch (std::exception &exc) {
ExitCode = Poco::Util::Application::EXIT_TEMPFAIL;
std::cout << exc.what() << std::endl;
} catch (...) {
ExitCode = Poco::Util::Application::EXIT_TEMPFAIL;
std::cout << "Exception on closure" << std::endl;
}
std::cout << "Exitcode: " << ExitCode << std::endl;
return ExitCode;
std::cout << "Exitcode: " << ExitCode << std::endl;
return ExitCode;
}
// end of namespace

View File

@@ -8,36 +8,35 @@
#pragma once
#include <framework/MicroService.h>
#include <framework/MicroServiceNames.h>
#include "Dashboard.h"
#include "framework/MicroService.h"
#include "framework/MicroServiceNames.h"
namespace OpenWifi {
[[maybe_unused]] static const char * vDAEMON_PROPERTIES_FILENAME = "owls.properties";
[[maybe_unused]] static const char * vDAEMON_ROOT_ENV_VAR = "OWLS_ROOT";
[[maybe_unused]] static const char * vDAEMON_CONFIG_ENV_VAR = "OWLS_CONFIG";
[[maybe_unused]] static const char * vDAEMON_APP_NAME = uSERVICE_OWLS.c_str();
[[maybe_unused]] static const uint64_t vDAEMON_BUS_TIMER = 10000;
[[maybe_unused]] static const char *vDAEMON_PROPERTIES_FILENAME = "owls.properties";
[[maybe_unused]] static const char *vDAEMON_ROOT_ENV_VAR = "OWLS_ROOT";
[[maybe_unused]] static const char *vDAEMON_CONFIG_ENV_VAR = "OWLS_CONFIG";
[[maybe_unused]] static const char *vDAEMON_APP_NAME = uSERVICE_OWLS.c_str();
[[maybe_unused]] static const uint64_t vDAEMON_BUS_TIMER = 10000;
class Daemon : public MicroService {
public:
explicit Daemon(const std::string & PropFile,
const std::string & RootEnv,
const std::string & ConfigEnv,
const std::string & AppName,
uint64_t BusTimer,
const SubSystemVec & SubSystems) :
MicroService( PropFile, RootEnv, ConfigEnv, AppName, BusTimer, SubSystems) {};
class Daemon : public MicroService {
public:
explicit Daemon(const std::string &PropFile, const std::string &RootEnv,
const std::string &ConfigEnv, const std::string &AppName, uint64_t BusTimer,
const SubSystemVec &SubSystems)
: MicroService(PropFile, RootEnv, ConfigEnv, AppName, BusTimer, SubSystems){};
void PostInitialization(Poco::Util::Application &self);
static Daemon *instance();
inline OWLSDashboard & GetDashboard() { return DB_; }
private:
static Daemon *instance_;
OWLSDashboard DB_{};
};
void PostInitialization(Poco::Util::Application &self);
static Daemon *instance();
inline OWLSDashboard &GetDashboard() { return DB_; }
inline Daemon * Daemon() { return Daemon::instance(); }
void DaemonPostInitialization(Poco::Util::Application &self);
}
private:
static Daemon *instance_;
OWLSDashboard DB_{};
};
inline Daemon *Daemon() { return Daemon::instance(); }
void DaemonPostInitialization(Poco::Util::Application &self);
} // namespace OpenWifi

View File

@@ -2,16 +2,16 @@
// Created by stephane bourque on 2021-07-21.
//
#include "Dashboard.h"
#include "framework/utils.h"
#include <framework/utils.h>
#include <Dashboard.h>
namespace OpenWifi {
void OWLSDashboard::Create() {
void OWLSDashboard::Create() {
uint64_t Now = Utils::Now();
if(LastRun_==0 || (Now-LastRun_)>120) {
if (LastRun_ == 0 || (Now - LastRun_) > 120) {
DB_.reset();
LastRun_ = Now;
}
}
}
} // namespace OpenWifi

View File

@@ -2,22 +2,21 @@
// Created by stephane bourque on 2021-07-21.
//
#ifndef UCENTRALGW_DASHBOARD_H
#define UCENTRALGW_DASHBOARD_H
#pragma once
#include "framework/OpenWifiTypes.h"
#include "RESTObjects/RESTAPI_OWLSobjects.h"
#include <framework/OpenWifiTypes.h>
#include <RESTObjects/RESTAPI_OWLSobjects.h>
namespace OpenWifi {
class OWLSDashboard {
public:
void Create();
const OWLSObjects::Dashboard & Report() const { return DB_;}
private:
OWLSObjects::Dashboard DB_;
uint64_t LastRun_=0;
inline void Reset() { DB_.reset(); }
};
}
void Create();
const OWLSObjects::Dashboard &Report() const { return DB_; }
private:
OWLSObjects::Dashboard DB_;
uint64_t LastRun_ = 0;
inline void Reset() { DB_.reset(); }
};
} // namespace OpenWifi
#endif // UCENTRALGW_DASHBOARD_H

313
src/MockElements.h Normal file
View File

@@ -0,0 +1,313 @@
//
// Created by stephane bourque on 2023-04-12.
//
#pragma once
#include <framework/MicroServiceFuncs.h>
#include "OWLS_utils.h"
namespace OpenWifi {
struct MockElement {
explicit MockElement(std::uint64_t S) : size(S) {
}
virtual void next() { last_update = Utils::Now(); };
virtual void reset() = 0;
virtual void to_json(Poco::JSON::Object &json ) const = 0;
virtual ~MockElement() = default;
void SetSize(std::uint64_t S) { size = S; }
std::uint64_t last_update = Utils::Now();
std::uint64_t size = 0;
};
struct MockMemory : public MockElement {
std::uint64_t total=973131776, free=0, cached=0, buffered=0;
explicit MockMemory(std::uint64_t S) : MockElement(S) {
}
void next() final {
MockElement::next();
if(size==0)
size=7;
free = total - (size * (128000 + OWLSutils::local_random(25000,75000))) - 150000000 ;
cached = OWLSutils::local_random(25000000,100000000);
buffered = OWLSutils::local_random(25000000,100000000);
}
void reset() final {
}
void to_json(Poco::JSON::Object &json ) const final {
Poco::JSON::Object Memory;
Memory.set("buffered", buffered);
Memory.set("cached", cached);
Memory.set("free", free);
Memory.set("total", total);
json.set("memory", Memory);
}
};
struct MockCPULoad : public MockElement {
std::double_t load_1=0.0, load_5=0.0, load_15=0.0;
explicit MockCPULoad(std::uint64_t S) : MockElement(S) {
}
void next() final {
MockElement::next();
load_15 = load_5;
load_5 = load_1;
if(size==0)
size=7;
load_1 = (std::double_t) OWLSutils::local_random(10*size,100*size) / (std::double_t) (75 * size);
}
void reset() final {
load_1 = load_5 = load_15 = 0.0;
}
void to_json(Poco::JSON::Object &json) const final {
auto LoadArray = std::vector<std::double_t> { load_1, load_5, load_15};
Poco::JSON::Object ObjArr;
json.set("load", LoadArray);
}
};
struct MockLanClient : public MockElement {
std::vector<std::string> ipv6_addresses, ipv4_addresses, ports;
std::string mac;
explicit MockLanClient() : MockElement(1) {
}
void next() final {
MockElement::next();
}
void reset() final {
}
void to_json(Poco::JSON::Object &json) const final {
json.set("ipv4_addresses", ipv4_addresses);
json.set("ipv6_addresses", ipv6_addresses);
json.set("ports", ports);
json.set("mac", mac);
}
};
typedef std::vector<MockLanClient> MockLanClients;
struct MockAssociation : public MockElement {
std::string station;
std::string bssid;
std::string ipaddr_v4;
std::string ipaddr_v6;
uint64_t tx_bytes = 0, rx_bytes = 0, rx_duration = 0, rx_packets = 0, connected = 0,
inactive = 0, tx_duration = 0, tx_failed = 0, tx_packets = 0, tx_retries = 0;
int64_t ack_signal = 0, ack_signal_avg = OWLSutils::local_random(-65, -75),
rssi = OWLSutils::local_random(-40, -90);
MockAssociation() : MockElement(1) {
}
void to_json(Poco::JSON::Object &json) const final {
json.set("ack_signal", ack_signal);
json.set("ack_signal_avg", ack_signal_avg);
json.set("bssid", bssid);
json.set("station", station);
json.set("connected", connected);
json.set("inactive", inactive);
json.set("ipaddr_v4", ipaddr_v4);
json.set("rssi", rssi);
json.set("rx_bytes", rx_bytes);
json.set("rx_duration", rx_duration);
json.set("rx_packets", rx_packets);
json.set("tx_packets", tx_packets);
json.set("tx_retries", tx_retries);
Poco::JSON::Object rx_rate;
rx_rate.set("bitrate", 200000);
rx_rate.set("chwidth", 40);
rx_rate.set("mcs", 9);
rx_rate.set("nss", 9);
rx_rate.set("sgi", true);
rx_rate.set("vht", true);
json.set("rx_rate", rx_rate);
json.set("tx_bytes", tx_bytes);
json.set("tx_duration", tx_duration);
json.set("tx_failed", tx_failed);
json.set("tx_packets", tx_packets);
json.set("tx_retries", tx_retries);
Poco::JSON::Object tx_rate;
tx_rate.set("bitrate", 200000);
tx_rate.set("chwidth", 40);
tx_rate.set("mcs", 9);
tx_rate.set("sgi", true);
tx_rate.set("ht", true);
json.set("tx_rate", tx_rate);
}
void next() final {
MockElement::next();
ack_signal = ack_signal_avg + OWLSutils::local_random(-5, 5);
connected += OWLSutils::local_random(100, 500);
inactive += OWLSutils::local_random(100, 500);
rssi += OWLSutils::local_random(-2, 2);
auto new_rx_packets = OWLSutils::local_random(200, 2000);
rx_packets += new_rx_packets;
rx_bytes += new_rx_packets * OWLSutils::local_random(500, 1000);
rx_duration += OWLSutils::local_random(400, 1750);
auto new_tx_packets = OWLSutils::local_random(100, 300);
tx_packets += new_tx_packets;
tx_bytes += new_tx_packets * OWLSutils::local_random(500, 1000);
tx_duration += OWLSutils::local_random(400, 1750);
tx_failed += OWLSutils::local_random(3) * OWLSutils::local_random(800, 1200);
tx_retries += OWLSutils::local_random(3);
}
void reset() final {
ack_signal = ack_signal_avg;
connected = 0;
inactive = 0;
rx_packets = 0;
rx_bytes = 0;
rx_duration = 0;
tx_packets = 0;
tx_bytes = 0;
tx_duration = 0;
tx_failed = 0;
tx_retries = 0;
}
};
typedef std::vector<MockAssociation> MockAssociations;
struct MockRadio : public MockElement {
std::uint64_t active_ms = 0,
busy_ms = 0,
channel = 0,
channel_width = 40,
receive_ms = 0,
transmit_ms = 0,
tx_power = 23;
std::int64_t noise = -100,
temperature = 40;
std::string phy;
uint64_t index = 0;
radio_bands radioBands = radio_bands::band_2g;
std::vector<std::uint64_t> channels;
std::vector<std::uint64_t> frequency;
std::vector<std::string> band;
explicit MockRadio() : MockElement(1) {
}
void to_json(Poco::JSON::Object &json) const final {
json.set("active_ms", active_ms);
json.set("busy_ms", busy_ms);
json.set("receive_ms", receive_ms);
json.set("transmit_ms", transmit_ms);
json.set("noise", noise);
json.set("temperature", temperature);
json.set("channel", channel);
json.set("channel_width", channel_width);
json.set("tx_power", tx_power);
json.set("phy", phy);
json.set("channels", channels);
json.set("frequency", frequency);
json.set("band", band);
}
void next() final {
MockElement::next();
temperature = 50 + OWLSutils::local_random(-7, 7);
noise = -95 + OWLSutils::local_random(-3, 3);
active_ms += OWLSutils::local_random(100, 2000);
busy_ms += OWLSutils::local_random(200, 3000);
receive_ms += OWLSutils::local_random(500, 1500);
transmit_ms += OWLSutils::local_random(250, 100);
}
void reset() final {
active_ms = 0;
busy_ms = 0;
receive_ms = 0;
transmit_ms = 0;
}
};
struct MockCounters : public MockElement {
std::uint64_t collisions = 0, multicast = 0, rx_bytes = 0, rx_dropped = 0, rx_errors = 0,
rx_packets = 0, tx_bytes = 0, tx_dropped = 0, tx_errors = 0, tx_packets = 0;
MockCounters() : MockElement(1) {
}
void to_json(Poco::JSON::Object &json) const final {
json.set("collisions", collisions);
json.set("multicast", multicast);
json.set("rx_bytes", rx_bytes);
json.set("rx_dropped", rx_dropped);
json.set("rx_errors", rx_errors);
json.set("rx_packets", rx_packets);
json.set("tx_bytes", tx_bytes);
json.set("tx_dropped", tx_dropped);
json.set("tx_errors", tx_errors);
json.set("tx_packets", tx_packets);
}
void next() final {
MockElement::next();
multicast += OWLSutils::local_random(10, 100);
collisions += OWLSutils::local_random(1);
rx_dropped += OWLSutils::local_random(2);
rx_errors += OWLSutils::local_random(3);
auto new_rx_packets = OWLSutils::local_random(300, 2000);
rx_packets += new_rx_packets;
rx_bytes += new_rx_packets * OWLSutils::local_random(900, 1400);
tx_dropped += OWLSutils::local_random(2);
tx_errors += OWLSutils::local_random(3);
auto new_tx_packets = OWLSutils::local_random(300, 2000);
tx_packets += new_tx_packets;
tx_bytes += new_tx_packets * OWLSutils::local_random(900, 1400);
}
void reset() final {
multicast = 0;
collisions = 0;
rx_dropped = 0;
rx_errors = 0;
rx_packets = 0;
rx_bytes = 0;
tx_dropped = 0;
tx_errors = 0;
tx_packets = 0;
tx_bytes = 0;
}
};
}

63
src/OWLS_Connect.cpp Normal file
View File

@@ -0,0 +1,63 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <fmt/format.h>
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimulationCoordinator.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
namespace OpenWifi::OWLSClientEvents {
/*
void Connect(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
if(!Runner->Running()) {
return;
}
std::lock_guard ClientGuard(Client->Mutex_);
if(Client->Valid_) {
try {
Runner->Report().ev_connect++;
Poco::JSON::Object ConnectMessage, Params, TmpCapabilities, Capabilities, MacAddr;
auto LabelMac = Utils::SerialNumberToInt(Client->SerialNumber_);
Params.set("serial", Client->SerialNumber_);
Params.set("uuid", Client->UUID_);
Params.set("firmware", Client->Firmware_);
MacAddr.set("wan", Client->SerialNumber_);
MacAddr.set("lan", Utils::SerialToMAC(Utils::IntToSerialNumber(LabelMac + 1)));
TmpCapabilities = *SimulationCoordinator()->GetSimCapabilitiesPtr();
TmpCapabilities.set("label_macaddr", Client->SerialNumber_);
TmpCapabilities.set("macaddr", MacAddr);
Params.set("capabilities", TmpCapabilities);
OWLSutils::MakeHeader(ConnectMessage,"connect",Params);
if (Client->SendObject(ConnectMessage)) {
Client->Reset();
Runner->Scheduler().in(std::chrono::seconds(Client->StatisticsInterval_),
OWLSClientEvents::State, Client, Runner);
Runner->Scheduler().in(std::chrono::seconds(Client->HealthInterval_),
OWLSClientEvents::HealthCheck, Client, Runner);
Runner->Scheduler().in(std::chrono::seconds(MicroServiceRandom(120, 200)),
OWLSClientEvents::Log, Client, Runner, 1, "Device started");
Runner->Scheduler().in(std::chrono::seconds(60 * 4),
OWLSClientEvents::WSPing, Client, Runner);
Runner->Scheduler().in(std::chrono::seconds(30),
OWLSClientEvents::Update, Client, Runner);
Client->Logger_.information(fmt::format("connect({}): completed.", Client->SerialNumber_));
return;
}
} catch (const Poco::Exception &E) {
Client->Logger().log(E);
}
OWLSClientEvents::Disconnect(ClientGuard,Client, Runner, "Error occurred during connection", true);
}
}
*/
}

23
src/OWLS_CrashLog.cpp Normal file
View File

@@ -0,0 +1,23 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
namespace OpenWifi::OWLSClientEvents {
void CrashLog([[
maybe_unused]] std::lock_guard<std::mutex> &ClientGuard, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
if(!Runner->Running()) {
return;
}
if(Client->Valid_) {
Runner->Report().ev_crashlog++;
}
}
}

43
src/OWLS_Disconnect.cpp Normal file
View File

@@ -0,0 +1,43 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <fmt/format.h>
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
#include "OWLS_utils.h"
namespace OpenWifi::OWLSClientEvents {
void Disconnect(const char *context, std::lock_guard<std::mutex> &ClientGuard, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner,
const std::string &Reason, bool Reconnect) {
if(!Runner->Running()) {
return;
}
try {
if (Client->Valid_) {
Client->Disconnect(context, ClientGuard);
poco_debug(Client->Logger(),
fmt::format("Disconnecting({}): Reason: {}", Client->SerialNumber_, Reason));
if (Reconnect) {
poco_debug(Client->Logger_, fmt::format( "Reconnecting({}): {}", context, Client->SerialNumber_ ));
Runner->Scheduler().in(std::chrono::seconds(Client->Backoff()),
OWLSClientEvents::EstablishConnection, Client, Runner);
} else {
// DEBUG_LINE("not reconnecting");
}
}
} catch (const Poco::Exception &E) {
poco_warning(Client->Logger_,fmt::format("Disconnect({}): exception {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
poco_warning(Client->Logger_,fmt::format("Disconnect({}): std::exception {}", Client->SerialNumber_, E.what()));
}
}
}

View File

@@ -0,0 +1,153 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <fmt/format.h>
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimulationCoordinator.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
namespace OpenWifi::OWLSClientEvents {
void EstablishConnection( const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
if(!Runner->Running()) {
return;
}
Poco::URI uri(Runner->Details().gateway);
Poco::Net::Context::Params P;
Runner->Report().ev_establish_connection++;
P.verificationMode = Poco::Net::Context::VERIFY_STRICT;
P.verificationDepth = 9;
P.caLocation = SimulationCoordinator()->GetCasLocation();
P.loadDefaultCAs = false;
P.certificateFile = SimulationCoordinator()->GetCertFileName();
P.privateKeyFile = SimulationCoordinator()->GetKeyFileName();
P.cipherList = "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH";
P.dhUse2048Bits = true;
auto Context = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, P);
Poco::Crypto::X509Certificate Cert(SimulationCoordinator()->GetCertFileName());
Poco::Crypto::X509Certificate Root(SimulationCoordinator()->GetRootCAFileName());
Context->useCertificate(Cert);
Context->addChainCertificate(Root);
Context->addCertificateAuthority(Root);
if (SimulationCoordinator()->GetLevel() == Poco::Net::Context::VERIFY_STRICT) {
}
Poco::Crypto::RSAKey Key("", SimulationCoordinator()->GetKeyFileName(), "");
Context->usePrivateKey(Key);
SSL_CTX *SSLCtx = Context->sslContext();
if (!SSL_CTX_check_private_key(SSLCtx)) {
poco_error(Client->Logger_,fmt::format("Wrong Certificate: {} for {}",SimulationCoordinator()->GetCertFileName() ,
SimulationCoordinator()->GetKeyFileName()));
}
if (SimulationCoordinator()->GetLevel() == Poco::Net::Context::VERIFY_STRICT) {
}
Poco::Net::HTTPSClientSession Session(uri.getHost(), uri.getPort(), Context);
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET, "/?encoding=text",
Poco::Net::HTTPMessage::HTTP_1_1);
Request.set("origin", "http://www.websocket.org");
Poco::Net::HTTPResponse Response;
std::lock_guard ClientGuard(Client->Mutex_);
Client->Logger_.information(fmt::format("Connecting({}): host={} port={}", Client->SerialNumber_,
uri.getHost(), uri.getPort()));
try {
Client->WS_ = std::make_unique<Poco::Net::WebSocket>(Session, Request, Response);
(*Client->WS_).setReceiveTimeout(Poco::Timespan(1200,0));
(*Client->WS_).setSendTimeout(Poco::Timespan(1200,0));
(*Client->WS_).setKeepAlive(true);
(*Client->WS_).setNoDelay(true);
(*Client->WS_).setBlocking(false);
(*Client->WS_).setMaxPayloadSize(128000);
if(Connect(ClientGuard, Client, Runner)) {
Client->fd_ = Client->WS_->impl()->sockfd();
Runner->AddClientFd(Client->fd_, Client);
Client->Reactor_.addEventHandler(
*Client->WS_, Poco::NObserver<SimulationRunner, Poco::Net::ReadableNotification>(
*Runner, &SimulationRunner::OnSocketReadable));
Client->Reactor_.addEventHandler(
*Client->WS_, Poco::NObserver<SimulationRunner, Poco::Net::ErrorNotification>(
*Runner, &SimulationRunner::OnSocketError));
Client->Reactor_.addEventHandler(
*Client->WS_, Poco::NObserver<SimulationRunner, Poco::Net::ShutdownNotification>(
*Runner, &SimulationRunner::OnSocketShutdown));
Client->Connected_ = true;
Client->Logger_.information(fmt::format("connecting({}): connected.", Client->SerialNumber_));
return;
}
} catch (const Poco::Exception &E) {
Client->Logger_.warning(
fmt::format("Connecting({}): exception. {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
Client->Logger_.warning(
fmt::format("Connecting({}): std::exception. {}", Client->SerialNumber_, E.what()));
} catch (...) {
Client->Logger_.warning(fmt::format("Connecting({}): unknown exception. {}", Client->SerialNumber_));
}
Runner->Scheduler().in(std::chrono::seconds(Client->Backoff()), Reconnect, Client, Runner);
}
bool Connect([[
maybe_unused]] std::lock_guard<std::mutex> & ClientGuard, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
try {
Runner->Report().ev_connect++;
Poco::JSON::Object::Ptr ConnectMessage{new Poco::JSON::Object}, Params{new Poco::JSON::Object},
TmpCapabilities{new Poco::JSON::Object}, Capabilities{new Poco::JSON::Object}, MacAddr{new Poco::JSON::Object};
auto LabelMac = Utils::SerialNumberToInt(Client->SerialNumber_);
Params->set("serial", Client->SerialNumber_);
Params->set("uuid", Client->UUID_);
Params->set("firmware", Client->Firmware_);
MacAddr->set("wan", Client->SerialNumber_);
MacAddr->set("lan", Utils::SerialToMAC(Utils::IntToSerialNumber(LabelMac + 1)));
TmpCapabilities = SimulationCoordinator()->GetSimCapabilitiesPtr();
TmpCapabilities->set("label_macaddr", Client->SerialNumber_);
TmpCapabilities->set("macaddr", MacAddr);
Params->set("capabilities", TmpCapabilities);
OWLSutils::MakeHeader(ConnectMessage,"connect",Params);
if (Client->SendObject(__func__, ConnectMessage)) {
Client->Reset();
Runner->Scheduler().in(std::chrono::seconds(Client->StatisticsInterval_ + MicroServiceRandom(5, 15)),
OWLSClientEvents::State, Client, Runner);
Runner->Scheduler().in(std::chrono::seconds(Client->HealthInterval_ + MicroServiceRandom(5, 15)),
OWLSClientEvents::HealthCheck, Client, Runner);
Runner->Scheduler().in(std::chrono::seconds(MicroServiceRandom(120, 200)),
OWLSClientEvents::Log, Client, Runner, 1, "Device started");
Runner->Scheduler().in(std::chrono::seconds(60 * 4 + MicroServiceRandom(5, 15) ),
OWLSClientEvents::WSPing, Client, Runner);
/* Runner->Scheduler().in(std::chrono::seconds(30),
OWLSClientEvents::Update, Client, Runner);
*/
Client->Logger_.information(fmt::format("connect({}): completed.", Client->SerialNumber_));
Client->Backoff_=0;
SimStats()->Connect(Runner->Id());
return true;
}
} catch (const Poco::Exception &E) {
Client->Logger().log(E);
}
return false;
}
}

46
src/OWLS_HealthCheck.cpp Normal file
View File

@@ -0,0 +1,46 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
namespace OpenWifi::OWLSClientEvents {
void HealthCheck(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
if(!Runner->Running()) {
return;
}
std::lock_guard ClientGuard(Client->Mutex_);
if(Client->Valid_ && Client->Connected_) {
Runner->Report().ev_healthcheck++;
try {
Poco::JSON::Object::Ptr Message{new Poco::JSON::Object}, Params{new Poco::JSON::Object}, Data{new Poco::JSON::Object}, Memory{new Poco::JSON::Object};
Memory->set("memory", 23);
Data->set("data", Memory);
Params->set(uCentralProtocol::SERIAL, Client->SerialNumber_);
Params->set(uCentralProtocol::UUID, Client->UUID_);
Params->set(uCentralProtocol::SANITY, 100);
Params->set(uCentralProtocol::DATA, Data);
OWLSutils::MakeHeader(Message, uCentralProtocol::HEALTHCHECK, Params);
if (Client->SendObject(__func__, Message)) {
Runner->Scheduler().in(std::chrono::seconds(Client->HealthInterval_),
OWLSClientEvents::HealthCheck, Client, Runner);
return;
}
} catch (const Poco::Exception &E) {
poco_warning(Client->Logger_,fmt::format("HealthCheck({}): exception {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
poco_warning(Client->Logger_,fmt::format("HealthCheck({}): std::exception {}", Client->SerialNumber_, E.what()));
}
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Runner, "Error while sending HealthCheck", true);
}
}
}

42
src/OWLS_KeepAlive.cpp Normal file
View File

@@ -0,0 +1,42 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
namespace OpenWifi::OWLSClientEvents {
void KeepAlive(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
if(!Runner->Running()) {
return;
}
std::lock_guard ClientGuard(Client->Mutex_);
if(Client->Valid_ && Client->Connected_) {
Runner->Report().ev_keepalive++;
try {
Poco::JSON::Object::Ptr Message{new Poco::JSON::Object},
Params{new Poco::JSON::Object};
Params->set("serial", Client->SerialNumber_);
Params->set("uuid", Client->UUID_);
OWLSutils::MakeHeader(Message,"ping",Params);
if (Client->SendObject(__func__, Message)) {
Runner->Scheduler().in(std::chrono::seconds(Runner->Details().keepAlive),
OWLSClientEvents::KeepAlive, Client, Runner);
return;
}
} catch (const Poco::Exception &E) {
poco_warning(Client->Logger_,fmt::format("KeepAlive({}): exception {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
poco_warning(Client->Logger_,fmt::format("KeepAlive({}): std::exception {}", Client->SerialNumber_, E.what()));
}
OWLSClientEvents::Disconnect(__func__, ClientGuard,Client, Runner, "Error while sending keepalive", true);
}
}
}

41
src/OWLS_Log.cpp Normal file
View File

@@ -0,0 +1,41 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
namespace OpenWifi::OWLSClientEvents {
void Log(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner, std::uint64_t Severity, const std::string & LogLine) {
if(!Runner->Running()) {
return;
}
std::lock_guard ClientGuard(Client->Mutex_);
if(Client->Valid_ && Client->Connected_ ) {
Runner->Report().ev_log++;
try {
Poco::JSON::Object::Ptr Message{new Poco::JSON::Object}, Params{new Poco::JSON::Object};
Params->set("serial", Client->SerialNumber_);
Params->set("uuid", Client->UUID_);
Params->set("severity", Severity);
Params->set("log", LogLine);
OWLSutils::MakeHeader(Message,"log",Params);
if (Client->SendObject(__func__,Message)) {
return;
}
} catch (const Poco::Exception &E) {
poco_warning(Client->Logger_,fmt::format("Log({}): exception {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
poco_warning(Client->Logger_,fmt::format("KeLogepAlive({}): std::exception {}", Client->SerialNumber_, E.what()));
}
OWLSClientEvents::Disconnect(__func__, ClientGuard,Client, Runner, "Error while sending a Log event", true);
}
}
}

View File

@@ -0,0 +1,40 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
namespace OpenWifi::OWLSClientEvents {
void PendingConfig(std::lock_guard<std::mutex> &ClientGuard, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
if(!Runner->Running()) {
return;
}
if(Client->Valid_ && Client->Connected_) {
Runner->Report().ev_configpendingchange++;
try {
Poco::JSON::Object::Ptr Message{new Poco::JSON::Object}, Params{new Poco::JSON::Object};
Params->set("serial", Client->SerialNumber_);
Params->set("uuid", Client->UUID_);
Params->set("active", Client->Active_);
OWLSutils::MakeHeader(Message,"cfgpending",Params);
if (Client->SendObject(__func__,Message)) {
return;
}
} catch (const Poco::Exception &E) {
poco_warning(Client->Logger_,fmt::format("PendingConfig({}): exception {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
poco_warning(Client->Logger_,fmt::format("PendingConfig({}): std::exception {}", Client->SerialNumber_, E.what()));
}
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Runner, "Error while sending ConfigPendingEvent", true);
}
}
}

34
src/OWLS_Reconnect.cpp Normal file
View File

@@ -0,0 +1,34 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
#include "OWLS_utils.h"
namespace OpenWifi::OWLSClientEvents {
void Reconnect(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
if(!Runner->Running()) {
return;
}
std::lock_guard ClientGuard(Client->Mutex_);
try {
if(Client->Valid_) {
Runner->Report().ev_reconnect++;
Client->Connected_ = false;
Runner->Scheduler().in(std::chrono::seconds(Client->Backoff()), OWLSClientEvents::EstablishConnection, Client, Runner);
}
} catch (const Poco::Exception &E) {
poco_warning(Client->Logger_,fmt::format("Reconnect({}): exception {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
poco_warning(Client->Logger_,fmt::format("Reconnect({}): std::exception {}", Client->SerialNumber_, E.what()));
}
}
}

60
src/OWLS_State.cpp Normal file
View File

@@ -0,0 +1,60 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <fmt/format.h>
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimStats.h"
#include "OWLSdefinitions.h"
#include "OWLSclientEvents.h"
namespace OpenWifi::OWLSClientEvents {
void State(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
if(!Runner->Running()) {
return;
}
std::lock_guard ClientGuard(Client->Mutex_);
if(Client->Valid_ && Client->Connected_) {
Runner->Report().ev_state++;
try {
Poco::JSON::Object::Ptr Message{new Poco::JSON::Object}, TempParams{new Poco::JSON::Object}, Params{new Poco::JSON::Object};
TempParams->set(uCentralProtocol::SERIAL, Client->SerialNumber_);
TempParams->set(uCentralProtocol::UUID, Client->UUID_);
TempParams->set(uCentralProtocol::STATE, Client->CreateStatePtr());
std::ostringstream os;
TempParams->stringify(os);
unsigned long BufSize = os.str().size() + 4000;
std::vector<Bytef> Buffer(BufSize);
compress(&Buffer[0], &BufSize, (Bytef *)os.str().c_str(), os.str().size());
auto CompressedBase64Encoded = OpenWifi::Utils::base64encode(&Buffer[0], BufSize);
Params->set("compress_64", CompressedBase64Encoded);
Params->set("compress_sz", os.str().size());
OWLSutils::MakeHeader(Message,uCentralProtocol::STATE,Params);
if (Client->SendObject(__func__, Message)) {
Runner->Scheduler().in(std::chrono::seconds(Client->StatisticsInterval_),
OWLSClientEvents::State, Client, Runner);
return;
}
} catch (const Poco::Exception &E) {
poco_warning(Client->Logger_,fmt::format("State({}): exception {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
poco_warning(Client->Logger_,fmt::format("State({}): std::exception {}", Client->SerialNumber_, E.what()));
}
OWLSClientEvents::Disconnect(__func__, ClientGuard,Client, Runner, "Error sending stats event", true);
}
}
}

34
src/OWLS_Update.cpp Normal file
View File

@@ -0,0 +1,34 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
namespace OpenWifi::OWLSClientEvents {
void Update(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
if(!Runner->Running()) {
return;
}
std::lock_guard ClientGuard(Client->Mutex_);
try {
if(Client->Valid_ && Client->Connected_) {
Runner->Report().ev_update++;
Client->Update();
Runner->Scheduler().in(std::chrono::seconds(30),
OWLSClientEvents::Update, Client, Runner);
}
} catch (const Poco::Exception &E) {
poco_warning(Client->Logger_,fmt::format("Update({}): exception {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
poco_warning(Client->Logger_,fmt::format("Update({}): std::exception {}", Client->SerialNumber_, E.what()));
}
}
}

35
src/OWLS_WSPing.cpp Normal file
View File

@@ -0,0 +1,35 @@
//
// Created by stephane bourque on 2023-04-12.
//
#include <Poco/NObserver.h>
#include "OWLSclient.h"
#include "SimulationRunner.h"
#include "SimStats.h"
#include "OWLSclientEvents.h"
namespace OpenWifi::OWLSClientEvents {
void WSPing(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner) {
if(!Runner->Running()) {
return;
}
std::lock_guard<std::mutex> ClientGuard(Client->Mutex_);
if(Client->Valid_ && Client->Connected_) {
Runner->Report().ev_wsping++;
try {
Client->WS_->sendFrame(
"", 0, Poco::Net::WebSocket::FRAME_OP_PING | Poco::Net::WebSocket::FRAME_FLAG_FIN);
Runner->Scheduler().in(std::chrono::seconds(60 * 3),
OWLSClientEvents::WSPing, Client, Runner);
return;
} catch (const Poco::Exception &E) {
poco_warning(Client->Logger_,fmt::format("WSPing({}): exception {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
poco_warning(Client->Logger_,fmt::format("WSPing({}): std::exception {}", Client->SerialNumber_, E.what()));
}
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Runner, "Error in WSPing", true);
}
}
}

226
src/OWLS_utils.h Normal file
View File

@@ -0,0 +1,226 @@
//
// Created by stephane bourque on 2023-04-12.
//
#pragma once
#include <random>
#include <framework/MicroServiceFuncs.h>
#include <framework/ow_constants.h>
namespace OpenWifi {
enum class radio_bands {
band_2g, band_5g, band_6g
};
inline std::string to_string(radio_bands b) {
switch(b) {
case radio_bands::band_5g: return "5G";
case radio_bands::band_6g: return "6G";
default:
return "2G";
}
}
namespace OWLSutils {
/* template<typename T>
void AssignIfPresent(const nlohmann::json &doc, const char *name, T &Value, T default_value) {
if (doc.contains(name) && !doc[name].is_null())
Value = doc[name];
else
Value = default_value;
}
*/
template<typename T>
void AssignIfPresent(const Poco::JSON::Object::Ptr &doc, const char *name, T &Value, T default_value) {
if (doc->has(name) && !doc->isNull(name)) {
Value = doc->get(name);
} else {
Value = default_value;
}
}
inline std::string MakeMac(const char *S, int offset) {
char b[256];
int j = 0, i = 0;
for (int k = 0; k < 6; ++k) {
b[j++] = S[i++];
b[j++] = S[i++];
b[j++] = ':';
}
b[--j] = 0;
b[--j] = '0' + offset;
return b;
}
inline std::string RandomMAC() {
char b[64];
snprintf(b, sizeof(b), "%02x:%02x:%02x:%02x:%02x:%02x", (int) MicroServiceRandom(255),
(int) MicroServiceRandom(255), (int) MicroServiceRandom(255),
(int) MicroServiceRandom(255), (int) MicroServiceRandom(255),
(int) MicroServiceRandom(255));
return b;
}
inline std::string RandomIPv4() {
char b[64];
snprintf(b, sizeof(b), "%d.%d.%d.%d", (int) MicroServiceRandom(255),
(int) MicroServiceRandom(255), (int) MicroServiceRandom(255),
(int) MicroServiceRandom(255));
return b;
}
inline std::string RandomIPv6() {
char b[128];
snprintf(b, sizeof(b), "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x",
(uint) MicroServiceRandom(0x0ffff), (uint) MicroServiceRandom(0x0ffff),
(uint) MicroServiceRandom(0x0ffff), (uint) MicroServiceRandom(0x0ffff),
(uint) MicroServiceRandom(0x0ffff), (uint) MicroServiceRandom(0x0ffff),
(uint) MicroServiceRandom(0x0ffff), (uint) MicroServiceRandom(0x0ffff));
return b;
}
inline std::int64_t local_random(std::int64_t min, std::int64_t max) {
static std::random_device rd;
static std::mt19937_64 gen{rd()};
if (min > max)
std::swap(min, max);
std::uniform_int_distribution<> dis(min, max);
return dis(gen);
}
inline auto local_random(std::int64_t max) { return local_random(0, max); }
static std::vector<std::uint64_t> Channels_2G{1, 6, 11};
static std::vector<std::uint64_t>
Channels_5G{36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 96, 100, 102, 104, 106,
108,
110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 132, 136, 138, 140, 142, 144, 149, 151,
153, 155, 157, 159, 161};
static std::vector<std::uint64_t> Channels_6G{1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65,
69, 73, 77, 81, 85, 89, 93, 97, 101, 105, 109, 113, 117,
121, 125, 129, 133, 137, 141, 145, 149, 153, 157, 161, 165, 169,
173, 177, 181, 185, 189, 193, 197, 201, 205, 209,
213, 221, 225, 229, 233};
inline void FillinFrequencies(std::uint64_t channel, radio_bands band, std::uint64_t width,
std::vector<std::uint64_t> &channels, std::vector<std::uint64_t> &frequencies) {
if (band == radio_bands::band_2g) { // 2.4GHz band
if (channel >= 1 && channel <= 11) {
channels.push_back(channel);
std::uint64_t frequency = 2401 + (channel - 1) * 5;
frequencies.push_back(frequency);
if (width == 20) {
frequencies.push_back(frequency + 22);
} else if (width == 40) {
frequencies.push_back(frequency + 32);
} else if (width == 80) {
frequencies.push_back(frequency + 52);
} else {
throw std::invalid_argument("Invalid channel width for 2.4GHz band.");
}
} else {
throw std::invalid_argument("Invalid channel number for 2.4GHz band.");
}
} else if (band == radio_bands::band_5g) { // 5GHz band
if (channel >= 36 && channel <= 165) {
std::uint64_t frequency = 5170 + (channel - 36) * 5;
channels.push_back(channel);
if (width == 20) {
frequencies.push_back(frequency);
frequencies.push_back(frequency + 20);
} else if (width == 40) {
channels.push_back(channel + 2);
frequencies.push_back(frequency - 10);
frequencies.push_back(frequency + 30);
} else if (width == 80) {
channels.push_back(channel + 6);
frequencies.push_back(frequency - 30);
frequencies.push_back(frequency + 50);
} else if (width == 160) {
channels.push_back(channel + 12);
frequencies.push_back(frequency - 70);
frequencies.push_back(frequency + 90);
} else {
throw std::invalid_argument("Invalid channel width for 5GHz band.");
}
} else {
throw std::invalid_argument("Invalid channel number for 5GHz band.");
}
} else if (band == radio_bands::band_6g) { // 6GHz band
if (channel >= 1 && channel <= 233) {
std::uint64_t frequency = 5945 + (channel - 1) * 5;
channels.push_back(channel);
if (width == 20) {
frequencies.push_back(frequency);
frequencies.push_back(frequency + 19);
} else if (width == 40) {
channels.push_back(channel + 2);
frequencies.push_back(frequency - 10);
frequencies.push_back(frequency + 29);
} else if (width == 80) {
channels.push_back(channel + 6);
frequencies.push_back(frequency - 30);
frequencies.push_back(frequency + 49);
} else if (width == 160) {
channels.push_back(channel + 12);
frequencies.push_back(frequency - 70);
frequencies.push_back(frequency + 89);
} else {
throw std::invalid_argument("Invalid channel width for 6GHz band.");
}
} else {
throw std::invalid_argument("Invalid channel number for 6GHz band.");
}
} else {
throw std::invalid_argument("Invalid band number.");
}
}
inline std::uint64_t FindAutoChannel(radio_bands band, [[maybe_unused]] std::uint64_t channel_width) {
std::uint64_t num_chan = 1;
if (channel_width == 20) {
num_chan = 1;
} else if (channel_width == 40) {
num_chan = 2;
} else if (channel_width == 80) {
num_chan = 3;
} else if (channel_width == 160) {
num_chan = 4;
} else if (channel_width == 320) {
num_chan = 5;
}
switch (band) {
case radio_bands::band_2g:
return Channels_2G[std::rand() % Channels_2G.size()];
case radio_bands::band_5g:
return Channels_5G[std::rand() % (Channels_5G.size() - num_chan)];
case radio_bands::band_6g:
return Channels_6G[std::rand() % (Channels_6G.size() - num_chan)];
}
return Channels_2G[std::rand() % Channels_2G.size()];
}
inline void MakeHeader(Poco::JSON::Object::Ptr Message, const char *method, const Poco::JSON::Object::Ptr &Params) {
Message->set(uCentralProtocol::JSONRPC, "2.0");
Message->set(uCentralProtocol::METHOD, method);
Message->set(uCentralProtocol::PARAMS, Params);
}
inline void MakeRPCHeader(Poco::JSON::Object::Ptr Message, std::uint64_t Id, const Poco::JSON::Object::Ptr &Result) {
Message->set(uCentralProtocol::JSONRPC, "2.0");
Message->set(uCentralProtocol::ID, Id);
Message->set(uCentralProtocol::RESULT, Result);
}
inline bool is_integer(const std::string &s) {
return std::all_of(s.begin(),s.end(),[](char c) { return std::isdigit(c); });
}
}
}

636
src/OWLSclient.cpp Normal file
View File

@@ -0,0 +1,636 @@
//
// Created by stephane bourque on 2021-03-12.
//
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <thread>
#include <tuple>
#include <fmt/format.h>
#include <Poco/NObserver.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/URI.h>
#include "framework/MicroServiceFuncs.h"
#include "OWLS_utils.h"
#include "OWLSclient.h"
#include "OWLSdefinitions.h"
#include "SimStats.h"
#include "SimulationCoordinator.h"
using namespace std::chrono_literals;
namespace OpenWifi {
OWLSclient::OWLSclient(std::string SerialNumber,
Poco::Logger &Logger, SimulationRunner *runner,
Poco::Net::SocketReactor &R)
: Logger_(Logger), SerialNumber_(std::move(SerialNumber)),
Memory_(1),
Load_(1),
Runner_(runner),
Reactor_(R) {
AllInterfaceNames_[ap_interface_types::upstream] = "up0v0";
AllInterfaceNames_[ap_interface_types::downstream] = "down0v0";
AllInterfaceRoles_[ap_interface_types::upstream] = "upstream";
AllInterfaceRoles_[ap_interface_types::downstream] = "downstream";
AllPortNames_[ap_interface_types::upstream] = "eth0";
AllPortNames_[ap_interface_types::downstream] = "eth1";
SetFirmware();
Active_ = UUID_ = Utils::Now();
srand(UUID_);
mac_lan = OWLSutils::MakeMac(SerialNumber_.c_str(), 0);
CurrentConfig_ = SimulationCoordinator()->GetSimConfigurationPtr(Utils::Now());
UpdateConfiguration();
Valid_ = true;
}
void OWLSclient::CreateLanClients(uint64_t min, uint64_t max) {
AllLanClients_.clear();
uint64_t Num = MicroServiceRandom(min, max);
for (uint64_t i = 0; i < Num; i++) {
MockLanClient CI;
CI.mac = OWLSutils::RandomMAC();
CI.ipv4_addresses.push_back(OWLSutils::RandomIPv4());
CI.ipv6_addresses.push_back(OWLSutils::RandomIPv6());
CI.ports.emplace_back("eth1");
AllLanClients_.push_back(CI);
}
Load_.SetSize(AllLanClients_.size()+CountAssociations());
Memory_.SetSize(AllLanClients_.size()+CountAssociations());
}
void OWLSclient::CreateAssociations(const interface_location_t &interface, const std::string &bssid, uint64_t min,
uint64_t max) {
auto interface_hint = AllAssociations_.find(interface);
if(interface_hint==end(AllAssociations_)) {
MockAssociations M;
AllAssociations_[interface] = M;
interface_hint = AllAssociations_.find(interface);
}
interface_hint->second.clear();
auto NumberOfAssociations = MicroServiceRandom(min, max);
while (NumberOfAssociations) {
MockAssociation FA;
FA.bssid = bssid;
FA.station = OWLSutils::RandomMAC();
FA.ack_signal_avg = OWLSutils::local_random(-40, -60);
FA.ack_signal = FA.ack_signal_avg;
FA.ipaddr_v4 = OWLSutils::RandomIPv4();
FA.ipaddr_v6 = OWLSutils::RandomIPv6();
FA.rssi = OWLSutils::local_random(-40, -90);
interface_hint->second.push_back(FA);
--NumberOfAssociations;
}
Load_.SetSize(AllLanClients_.size()+CountAssociations());
Memory_.SetSize(AllLanClients_.size()+CountAssociations());
}
void OWLSclient::Update() {
Memory_.next();
Load_.next();
for(auto &[_,radio]:AllRadios_) {
radio.next();
}
for(auto &[_,counters]:AllCounters_) {
counters.next();
}
for(auto &[_,associations]:AllAssociations_) {
for(auto &association:associations) {
association.next();
}
}
for(auto &lan_client:AllLanClients_) {
lan_client.next();
}
}
bool OWLSclient::FindInterfaceRole(const std::string &role,
OpenWifi::ap_interface_types &interface) {
for (const auto &[interface_type, interface_name] : AllInterfaceRoles_) {
if (role == interface_name) {
interface = interface_type;
return true;
}
}
return false;
}
void OWLSclient::Reset() {
Memory_.reset();
Load_.reset();
for (auto &[_, radio] : AllRadios_) {
radio.reset();
}
for (auto &[_, association_list] : AllAssociations_) {
for (auto &association : association_list) {
association.reset();
}
}
for (auto &[_, counter] : AllCounters_) {
counter.reset();
}
for(auto &lan_client:AllLanClients_) {
lan_client.reset();
}
}
void OWLSclient::UpdateConfiguration() {
// go through the config and harvest the SSID names, also update all the client stuff
auto Interfaces = CurrentConfig_->getArray("interfaces");
AllAssociations_.clear();
AllLanClients_.clear();
AllRadios_.clear();
bssid_index = 1;
for (uint interface_index=0;interface_index<Interfaces->size();interface_index++) {
auto interfacePtr = Interfaces->get(interface_index);
auto interface = interfacePtr.extract<Poco::JSON::Object::Ptr>();
if (interface->has("role")) {
ap_interface_types current_interface_role = upstream;
if (FindInterfaceRole(interface->get("role"), current_interface_role)) {
auto SSIDs = interface->getArray("ssids");
for (uint ssid_index=0; ssid_index< SSIDs->size(); ++ssid_index) {
auto SSIDptr = SSIDs->get(ssid_index);
auto SSID = SSIDptr.extract<Poco::JSON::Object::Ptr>();
auto Bands = SSID->getArray("wifi-bands");
for(uint band_index=0;band_index<Bands->size(); band_index++) {
std::string band = Bands->get(band_index);
std::string ssidName = SSID->get("name");
auto bssid_num = Utils::SerialToMAC(Utils::IntToSerialNumber(
Utils::SerialNumberToInt(SerialNumber_) +
bssid_index++));
if (band == "2G") {
auto index = std::make_tuple(current_interface_role, ssidName,
radio_bands::band_2g);
CreateAssociations(index, bssid_num,
Runner_->Details().minAssociations,
Runner_->Details().maxAssociations);
}
if (band == "5G") {
auto index = std::make_tuple(current_interface_role, ssidName,
radio_bands::band_5g);
CreateAssociations(index, bssid_num,
Runner_->Details().minAssociations,
Runner_->Details().maxAssociations);
}
if (band == "6G") {
auto index = std::make_tuple(current_interface_role, ssidName,
radio_bands::band_6g);
CreateAssociations(index,bssid_num,
Runner_->Details().minAssociations,
Runner_->Details().maxAssociations);
}
}
}
MockCounters F;
AllCounters_[current_interface_role] = F;
}
}
}
CreateLanClients(Runner_->Details().minClients, Runner_->Details().maxClients);
auto radios = CurrentConfig_->getArray("radios");
for (uint radio_index=0;radio_index<radios->size();radio_index++) {
auto radioPtr = radios->get(radio_index);
auto radio = radioPtr.extract<Poco::JSON::Object::Ptr>();
std::string band = radio->get("band");
MockRadio R;
R.band.push_back(band);
if (band == "2G") {
R.radioBands = radio_bands::band_2g;
} else if (band == "5G") {
R.radioBands = radio_bands::band_5g;
} else if (band == "6G") {
R.radioBands = radio_bands::band_6g;
}
if(radio->has("channel-width")) {
R.channel_width = radio->get("channel-width");
} else {
R.channel_width = 20;
}
if (!radio->has("channel")) {
R.channel = OWLSutils::FindAutoChannel(R.radioBands,R.channel_width);
} else {
std::string channel = radio->get("channel").toString();
if(OWLSutils::is_integer(channel)) {
R.channel = std::strtoll(channel.c_str(), nullptr,10);
} else {
R.channel = OWLSutils::FindAutoChannel(R.radioBands, R.channel_width);
}
}
OWLSutils::FillinFrequencies(R.channel, R.radioBands, R.channel_width, R.channels, R.frequency);
OWLSutils::AssignIfPresent(radio, "tx_power", R.tx_power, (uint_fast64_t)23);
if (radio_index == 0)
R.phy = "platform/soc/c000000.wifi";
else
R.phy = "platform/soc/c000000.wifi+" + std::to_string(radio_index);
R.index = radio_index;
AllRadios_[R.radioBands] = R;
}
}
Poco::JSON::Object::Ptr OWLSclient::CreateLinkStatePtr() {
Poco::JSON::Object::Ptr res{new Poco::JSON::Object};
for (const auto &[interface_type, _] : AllCounters_) {
Poco::JSON::Object InterfaceInfo, InterfacePort;
InterfaceInfo.set("carrier",1);
InterfaceInfo.set("duplex","full");
InterfaceInfo.set("speed",1000);
InterfacePort.set(AllPortNames_[interface_type],InterfaceInfo);
res->set(AllInterfaceRoles_[interface_type], InterfacePort);
}
return res;
}
Poco::JSON::Object::Ptr OWLSclient::CreateStatePtr() {
Poco::JSON::Object::Ptr State{new Poco::JSON::Object},Unit{new Poco::JSON::Object};
auto now = Utils::Now();
Memory_.to_json(*Unit);
Load_.to_json(*Unit);
Unit->set("localtime", now);
Unit->set("uptime", now - StartTime_);
Unit->set("temperature", std::vector<std::int64_t> { OWLSutils::local_random(48,58), OWLSutils::local_random(48,58)});
Poco::JSON::Array::Ptr RadioArray{new Poco::JSON::Array};
for (auto &[_, radio] : AllRadios_) {
Poco::JSON::Object doc;
radio.to_json(doc);
RadioArray->add(doc);
}
Poco::JSON::Array::Ptr all_interfaces{new Poco::JSON::Array};
for (const auto &ap_interface_type :
{ap_interface_types::upstream, ap_interface_types::downstream}) {
if (AllCounters_.find(ap_interface_type) != AllCounters_.end()) {
Poco::JSON::Object::Ptr current_interface{new Poco::JSON::Object};
Poco::JSON::Array::Ptr ue_clients{new Poco::JSON::Array}, up_ssids{new Poco::JSON::Array};
uint64_t ssid_num = 0, interfaces = 0;
for (auto &[interface, associations] : AllAssociations_) {
auto &[interface_type, ssid, band] = interface;
if (interface_type == ap_interface_type) {
Poco::JSON::Array::Ptr association_list{new Poco::JSON::Array};
std::string bssid;
for (auto &association : associations) {
bssid = association.bssid;
Poco::JSON::Object doc;
association.to_json(doc);
association_list->add(doc);
Poco::JSON::Object ue;
ue.set("mac", association.station);
ue.set("ipv4_addresses", std::vector<std::string>{association.ipaddr_v4});
ue.set("ipv6_addresses", std::vector<std::string>{association.ipaddr_v6});
if(interface_type==upstream) {
ue.set("ports", std::vector<std::string>{"wwan0"});
}
else {
ue.set("ports", std::vector<std::string>{"wlan0"});
}
ue.set("last_seen", 0);
ue_clients->add(ue);
}
Poco::JSON::Object ssid_info;
ssid_info.set("associations", association_list);
ssid_info.set("bssid", bssid);
ssid_info.set("band", OpenWifi::to_string(band));
Poco::JSON::Object Counters;
AllCounters_[interface_type].to_json(Counters);
ssid_info.set("counters", Counters);
ssid_info.set("frequency", AllRadios_[band].frequency);
ssid_info.set("iface", AllPortNames_[interface_type]);
ssid_info.set("mode", "ap");
ssid_info.set("ssid", ssid);
ssid_info.set("phy", AllRadios_[band].phy);
ssid_info.set("location", "/interfaces/" + std::to_string(interfaces) +
"/ssids/" + std::to_string(ssid_num++));
ssid_info.set("name", AllInterfaceNames_[ap_interface_type]);
Poco::JSON::Object R;
R.set("$ref",
"#/radios/" + std::to_string(AllRadios_[band].index));
ssid_info.set("radio", R);
up_ssids->add(ssid_info);
}
}
current_interface->set("ssids", up_ssids);
Poco::JSON::Object C;
AllCounters_[ap_interface_type].to_json(C);
current_interface->set("counters", C);
// if we have 2 interfaces, then the clients go to the downstream interface
// if we only have 1 interface then this is bridged and therefore clients go on the
// upstream
if ((AllCounters_.size() == 1 &&
ap_interface_type == ap_interface_types::upstream) ||
(AllCounters_.size() == 2 &&
ap_interface_type == ap_interface_types::downstream)) {
Poco::JSON::Array::Ptr ip_clients{new Poco::JSON::Array};
for (const auto &lan_client : AllLanClients_) {
Poco::JSON::Object d;
lan_client.to_json(d);
ip_clients->add(d);
}
for (const auto &ue_client : *ue_clients) {
ip_clients->add(ue_client);
}
current_interface->set("clients", ip_clients);
}
current_interface->set("name", AllInterfaceNames_[ap_interface_type]);
all_interfaces->add(current_interface);
}
}
State->set("version" , 1 );
State->set("radios", RadioArray);
State->set("link-state", CreateLinkStatePtr());
State->set("unit", Unit);
State->set("interfaces", all_interfaces);
return State;
}
void OWLSclient::DoConfigure(const std::shared_ptr<OWLSclient> &Client, uint64_t Id, Poco::JSON::Object::Ptr Params) {
std::lock_guard ClientGuard(Client->Mutex_);
try {
if (Params->has(uCentralProtocol::SERIAL) &&
Params->has(uCentralProtocol::CONFIG) &&
Params->has(uCentralProtocol::UUID)) {
std::string Serial = Params->get(uCentralProtocol::SERIAL);
std::uint64_t NewUUID = Params->get(uCentralProtocol::UUID);
auto Configuration = Params->getObject("config");
Client->UUID_ = Client->Active_ = NewUUID;
Client->CurrentConfig_ = Configuration;
if(Configuration->isObject("metrics")) {
auto Metrics = Configuration->getObject("metrics");
if(Metrics->isObject("health")) {
auto Health = Metrics->getObject("health");
Client->HealthInterval_ = Health->get("interval");
}
if(Metrics->isObject("statistics")) {
auto Statistics = Metrics->getObject("statistics");
Client->StatisticsInterval_ = Statistics->get("interval");
}
}
// prepare response...
Poco::JSON::Object::Ptr Answer{new Poco::JSON::Object}, Result{new Poco::JSON::Object}, Status{new Poco::JSON::Object};
Status->set(uCentralProtocol::ERROR, 0);
Status->set(uCentralProtocol::TEXT, "Success");
Result->set(uCentralProtocol::SERIAL, Serial);
Result->set(uCentralProtocol::UUID, Client->UUID_);
Result->set(uCentralProtocol::STATUS, Status);
OWLSutils::MakeRPCHeader(Answer, Id, Result);
poco_information(Client->Logger_,fmt::format("configure({}): done.", Client->SerialNumber_));
// std::this_thread::sleep_for(std::chrono::seconds(OWLSutils::local_random(10,30)));
if(!Client->SendObject(__func__,Answer)) {
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Client->Runner_, "Command: configure - failed.", true);
}
} else {
poco_warning(Client->Logger_,fmt::format("configure({}): Illegal command.", Client->SerialNumber_));
}
} catch (const Poco::Exception &E) {
DEBUG_LINE("exception 1");
poco_warning(Client->Logger_,
fmt::format("configure({}): Exception. {}", Client->SerialNumber_, E.displayText()));
} catch (const std::exception &E) {
DEBUG_LINE("exception2");
}
}
void OWLSclient::Disconnect(const char *context, [[maybe_unused]] std::lock_guard<std::mutex> &Guard) {
if(fd_!=-1) {
Runner_->RemoveClientFd(fd_);
fd_ = -1;
}
if(Valid_) {
Runner_->Report().ev_disconnect++;
SimStats()->Disconnect(Runner_->Id());
if (Connected_) {
Reactor_.removeEventHandler(
*WS_, Poco::NObserver<SimulationRunner, Poco::Net::ReadableNotification>(
*Runner_, &SimulationRunner::OnSocketReadable));
Reactor_.removeEventHandler(
*WS_, Poco::NObserver<SimulationRunner, Poco::Net::ErrorNotification>(
*Runner_, &SimulationRunner::OnSocketError));
Reactor_.removeEventHandler(
*WS_, Poco::NObserver<SimulationRunner, Poco::Net::ShutdownNotification>(
*Runner_, &SimulationRunner::OnSocketShutdown));
(*WS_).close();
Connected_ = false;
poco_debug(Logger_, fmt::format("Disconnecting a client({}){}: ", context, SerialNumber_));
}
}
}
void OWLSclient::DoReboot(const std::shared_ptr<OWLSclient> &Client, uint64_t Id, Poco::JSON::Object::Ptr Params) {
std::lock_guard ClientGuard(Client->Mutex_);
try {
if (Params->has("serial") && Params->has("when")) {
std::string Serial = Params->get("serial");
Poco::JSON::Object::Ptr Answer{new Poco::JSON::Object}, Result{new Poco::JSON::Object}, Status{new Poco::JSON::Object};
Status->set(uCentralProtocol::ERROR, 0);
Status->set(uCentralProtocol::TEXT, "Success");
Result->set(uCentralProtocol::SERIAL, Serial);
Result->set(uCentralProtocol::UUID, Client->UUID_);
Result->set(uCentralProtocol::STATUS, Status);
OWLSutils::MakeRPCHeader(Answer,Id,Result);
poco_information(Client->Logger_,fmt::format("reboot({}): done.", Client->SerialNumber_));
if(!Client->SendObject(__func__ ,Answer)) {
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Client->Runner_, "Command: reboot failed", true);
} else {
Client->Disconnect(__func__, ClientGuard);
Client->Reset();
std::this_thread::sleep_for(std::chrono::seconds(20));
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Client->Runner_, "Command: reboot", true);
}
} else {
Client->Logger_.warning(fmt::format("reboot({}): Illegal command.", Client->SerialNumber_));
}
} catch (const Poco::Exception &E) {
Client->Logger_.warning(
fmt::format("reboot({}): Exception. {}", Client->SerialNumber_, E.displayText()));
}
}
std::string GetFirmware(const std::string &U) {
Poco::URI uri(U);
auto p = uri.getPath();
auto tokens = Poco::StringTokenizer(p, "-");
if (tokens.count() > 4 &&
(tokens[2] == "main" || tokens[2] == "next" || tokens[2] == "staging")) {
return "TIP-devel-" + tokens[3];
}
if (tokens.count() > 5) {
return "TIP-" + tokens[2] + "-" + tokens[3] + "-" + tokens[4];
}
return p;
}
void OWLSclient::DoUpgrade(const std::shared_ptr<OWLSclient> &Client, uint64_t Id, Poco::JSON::Object::Ptr Params) {
std::lock_guard ClientGuard(Client->Mutex_);
try {
if (Params->has("serial") && Params->has("uri")) {
std::string Serial = Params->get("serial");
std::string URI = Params->get("uri");
Poco::JSON::Object::Ptr Answer{new Poco::JSON::Object}, Result{new Poco::JSON::Object}, Status{new Poco::JSON::Object};
Status->set(uCentralProtocol::ERROR, 0);
Status->set(uCentralProtocol::TEXT, "Success");
Result->set(uCentralProtocol::SERIAL, Serial);
Result->set(uCentralProtocol::UUID, Client->UUID_);
Result->set(uCentralProtocol::STATUS, Status);
OWLSutils::MakeRPCHeader(Answer, Id, Result);
poco_information(Client->Logger_,fmt::format("upgrade({}): from URI={}.", Client->SerialNumber_, URI));
if(!Client->SendObject(__func__ , Answer)) {
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Client->Runner_, "Command: upgrade failed", true);
} else {
Client->Disconnect(__func__,ClientGuard);
Client->Version_++;
Client->SetFirmware(GetFirmware(URI));
std::this_thread::sleep_for(std::chrono::seconds(30));
Client->Reset();
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Client->Runner_, "Command: upgrade", true);
}
} else {
Client->Logger_.warning(fmt::format("upgrade({}): Illegal command.", Client->SerialNumber_));
}
} catch (const Poco::Exception &E) {
Client->Logger_.warning(
fmt::format("upgrade({}): Exception. {}", Client->SerialNumber_, E.displayText()));
}
}
void OWLSclient::DoFactory(const std::shared_ptr<OWLSclient> &Client, uint64_t Id, Poco::JSON::Object::Ptr Params) {
std::lock_guard ClientGuard(Client->Mutex_);
try {
if (Params->has("serial") && Params->has("when")) {
std::string Serial = Params->get("serial");
Client->Version_ = 1;
Client->SetFirmware();
Poco::JSON::Object::Ptr Answer{new Poco::JSON::Object}, Result{new Poco::JSON::Object}, Status{new Poco::JSON::Object};
Status->set(uCentralProtocol::ERROR, 0);
Status->set(uCentralProtocol::TEXT, "Success");
Result->set(uCentralProtocol::SERIAL, Serial);
Result->set(uCentralProtocol::UUID, Client->UUID_);
Result->set(uCentralProtocol::STATUS, Status);
OWLSutils::MakeRPCHeader(Answer, Id, Result);
poco_information(Client->Logger_, fmt::format("factory({}): done.", Client->SerialNumber_));
if(!Client->SendObject(__func__ , Answer)) {
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Client->Runner_, "Command: factory failed", true);
} else {
Client->Disconnect(__func__, ClientGuard);
Client->CurrentConfig_ = SimulationCoordinator()->GetSimConfigurationPtr(Utils::Now());
Client->UpdateConfiguration();
std::this_thread::sleep_for(std::chrono::seconds(5));
Client->Reset();
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Client->Runner_, "Command: upgrade", true);
}
} else {
Client->Logger_.warning(fmt::format("factory({}): Illegal command.", Client->SerialNumber_));
}
} catch (const Poco::Exception &E) {
Client->Logger_.warning(
fmt::format("factory({}): Exception. {}", Client->SerialNumber_, E.displayText()));
}
}
void OWLSclient::DoLEDs(const std::shared_ptr<OWLSclient> &Client, uint64_t Id, Poco::JSON::Object::Ptr Params) {
std::lock_guard ClientGuard(Client->Mutex_);
try {
if (Params->has("serial") && Params->has("pattern")) {
std::string Serial = Params->get("serial");
auto Pattern = Params->get("pattern").toString();
uint64_t Duration = Params->has("when") ? (uint64_t)Params->get("durarion") : 10;
Poco::JSON::Object::Ptr Answer{new Poco::JSON::Object}, Result{new Poco::JSON::Object}, Status{new Poco::JSON::Object};
Status->set(uCentralProtocol::ERROR, 0);
Status->set(uCentralProtocol::TEXT, "Success");
Result->set(uCentralProtocol::SERIAL, Serial);
Result->set(uCentralProtocol::UUID, Client->UUID_);
Result->set(uCentralProtocol::STATUS, Status);
OWLSutils::MakeRPCHeader(Answer, Id, Result);
poco_information(Client->Logger_,fmt::format("LEDs({}): pattern set to: {} for {} ms.",
Client->SerialNumber_, Duration, Pattern));
if(!Client->SendObject(__func__ , Answer)) {
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Client->Runner_, "Command: LEDs failed", true);
}
} else {
Client->Logger_.warning(fmt::format("LEDs({}): Illegal command.", Client->SerialNumber_));
}
} catch (const Poco::Exception &E) {
Client->Logger_.warning(fmt::format("LEDs({}): Exception. {}", Client->SerialNumber_, E.displayText()));
}
}
void OWLSclient::UnSupportedCommand([[
maybe_unused]] std::lock_guard<std::mutex> &ClientGuard,const std::shared_ptr<OWLSclient> &Client, uint64_t Id,
const std::string & Method) {
try {
Poco::JSON::Object::Ptr Answer{new Poco::JSON::Object}, Result{new Poco::JSON::Object}, Status{new Poco::JSON::Object};
Status->set("error", 1);
Status->set("text", "Command not supported");
Result->set("serial", Client->SerialNumber_);
Result->set("status", Status);
OWLSutils::MakeRPCHeader(Answer, Id, Result);
poco_information(Logger_,fmt::format("UNSUPPORTED({}): command {} not allowed for simulated devices.",
SerialNumber_, Method));
if(!SendObject(__func__, Answer)) {
OWLSClientEvents::Disconnect(__func__, ClientGuard, Client, Client->Runner_, "Command: unsupported failed", true);
}
} catch(const Poco::Exception &E) {
}
}
bool OWLSclient::SendObject(const char *context, const Poco::JSON::Object::Ptr &Object) {
if(!Runner_->Running()) {
return false;
}
auto os = std::make_unique<std::ostringstream>();
try {
Object->stringify(*os);
uint32_t BytesSent = WS_->sendFrame(os->str().c_str(), os->str().size());
if (BytesSent == os->str().size()) {
SimStats()->AddOutMsg(Runner_->Id(),BytesSent);
return true;
} else {
std::cout << fmt::format("SendObject({},{}): size={} sent={}", context, SerialNumber_, os->str().size(), BytesSent) << std::endl;
Logger_.warning(fmt::format("SendObject({},{}): size={} sent={}", context, SerialNumber_, os->str().size(), BytesSent));
}
} catch (const Poco::Exception &E) {
std::cout << fmt::format("SendObject({},{}): size={} exception={}", context, SerialNumber_, os->str().size(), E.displayText()) << std::endl;
Logger_.log(E);
} catch (const std::exception &E) {
DEBUG_LINE("exception2");
}
return false;
}
} // namespace OpenWifi

157
src/OWLSclient.h Normal file
View File

@@ -0,0 +1,157 @@
//
// Created by stephane bourque on 2021-03-12.
//
#pragma once
#include <map>
#include <mutex>
#include <random>
#include <tuple>
#include <fmt/format.h>
#include <Poco/AutoPtr.h>
#include <Poco/JSON/Object.h>
#include <Poco/Logger.h>
#include <Poco/Net/SocketNotification.h>
#include <Poco/Net/SocketReactor.h>
#include <Poco/Net/WebSocket.h>
#include <Poco/Thread.h>
#include "framework/utils.h"
#include "OWLSdefinitions.h"
#include "MockElements.h"
#include "OWLSclientEvents.h"
namespace OpenWifi {
class SimulationRunner;
class OWLSclient {
public:
OWLSclient(std::string SerialNumber,
Poco::Logger &Logger, SimulationRunner *runner, Poco::Net::SocketReactor &R);
~OWLSclient() {
poco_debug(Logger_,fmt::format("{} simulator client done.", SerialNumber_));
}
// bool Send(const std::string &Cmd);
// bool SendWSPing();
[[nodiscard]] bool SendObject(const char *context, const Poco::JSON::Object::Ptr &O);
void SetFirmware(const std::string &S = "sim-firmware-1") { Firmware_ = S; }
[[nodiscard]] const std::string &Serial() const { return SerialNumber_; }
[[nodiscard]] uint64_t UUID() const { return UUID_; }
[[nodiscard]] uint64_t Active() const { return Active_; }
[[nodiscard]] const std::string &Firmware() const { return Firmware_; }
[[nodiscard]] bool Connected() const { return Connected_; }
[[nodiscard]] inline uint64_t GetStartTime() const { return StartTime_; }
static void DoConfigure(const std::shared_ptr<OWLSclient> &Client, uint64_t Id, Poco::JSON::Object::Ptr Params);
static void DoReboot(const std::shared_ptr<OWLSclient> &Client, uint64_t Id, Poco::JSON::Object::Ptr Params);
static void DoUpgrade(const std::shared_ptr<OWLSclient> &Client, uint64_t Id, Poco::JSON::Object::Ptr Params);
static void DoFactory(const std::shared_ptr<OWLSclient> &Client, uint64_t Id, Poco::JSON::Object::Ptr Params);
static void DoLEDs(const std::shared_ptr<OWLSclient> &Client, uint64_t Id, Poco::JSON::Object::Ptr Params);
void UnSupportedCommand(std::lock_guard<std::mutex> &G,const std::shared_ptr<OWLSclient> &Client, uint64_t Id, const std::string &Method);
using interface_location_t = std::tuple<ap_interface_types, std::string, radio_bands>;
using associations_map_t = std::map<interface_location_t, MockAssociations>;
void Disconnect(const char *context, std::lock_guard<std::mutex> &Guard);
void CreateAssociations(const interface_location_t &interface,const std::string &bssid, uint64_t min,
uint64_t max);
void CreateLanClients(uint64_t min, uint64_t max);
Poco::JSON::Object::Ptr CreateStatePtr();
Poco::JSON::Object::Ptr CreateLinkStatePtr();
Poco::Logger &Logger() { return Logger_; };
[[nodiscard]] uint64_t GetStateInterval() { return StatisticsInterval_; }
[[nodiscard]] uint64_t GetHealthInterval() { return HealthInterval_; }
void UpdateConfiguration();
bool FindInterfaceRole(const std::string &role, ap_interface_types &interface);
void Reset();
inline std::uint64_t CountAssociations() {
std::uint64_t Total=0;
for(const auto &[_,associations]:AllAssociations_) {
Total += associations.size();
}
return Total;
}
inline const auto & Memory() { return Memory_; }
inline const auto & Load() { return Load_; }
void Update();
[[nodiscard ]] inline auto Backoff() {
if(Backoff_>300) {
Backoff_ = 15;
} else {
Backoff_ *=2;
}
return Backoff_;
}
friend class SimulationRunner;
friend void OWLSClientEvents::EstablishConnection(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
friend void OWLSClientEvents::Reconnect(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
// friend void OWLSClientEvents::Connect(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
friend bool OWLSClientEvents::Connect(std::lock_guard<std::mutex> & ClientGuard, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
friend void OWLSClientEvents::Log(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner, std::uint64_t Severity, const std::string & LogLine);
friend void OWLSClientEvents::State(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
friend void OWLSClientEvents::HealthCheck(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
friend void OWLSClientEvents::Update(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
friend void OWLSClientEvents::WSPing(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
friend void OWLSClientEvents::KeepAlive(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
friend void OWLSClientEvents::Disconnect(const char *context, std::lock_guard<std::mutex> &g, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner, const std::string &Reason, bool Reconnect);
friend void OWLSClientEvents::CrashLog(std::lock_guard<std::mutex> &g, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
friend void OWLSClientEvents::PendingConfig(std::lock_guard<std::mutex> &g, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
private:
// std::recursive_mutex Mutex_;
std::mutex Mutex_;
Poco::Logger &Logger_;
Poco::JSON::Object::Ptr CurrentConfig_;
std::string SerialNumber_;
std::string Firmware_;
std::unique_ptr<Poco::Net::WebSocket> WS_;
volatile bool Valid_=false;
std::uint64_t Active_ = 0;
std::uint64_t UUID_ = 0;
bool Connected_ = false;
bool KeepRedirector_ = false;
uint64_t Version_ = 0;
uint64_t StartTime_ = Utils::Now();
std::string mac_lan;
std::uint64_t HealthInterval_ = 60;
std::uint64_t StatisticsInterval_ = 60;
uint64_t bssid_index = 1;
std::int64_t fd_=-1;
MockMemory Memory_;
MockCPULoad Load_;
std::uint16_t Backoff_=0;
SimulationRunner *Runner_ = nullptr;
Poco::Net::SocketReactor &Reactor_;
MockLanClients AllLanClients_;
associations_map_t AllAssociations_;
std::map<radio_bands, MockRadio> AllRadios_;
std::map<ap_interface_types, MockCounters> AllCounters_;
std::map<ap_interface_types, std::string> AllInterfaceNames_;
std::map<ap_interface_types, std::string> AllInterfaceRoles_;
std::map<ap_interface_types, std::string> AllPortNames_;
};
} // namespace OpenWifi

27
src/OWLSclientEvents.h Normal file
View File

@@ -0,0 +1,27 @@
//
// Created by stephane bourque on 2023-04-12.
//
#pragma once
#include <memory>
namespace OpenWifi {
class OWLSclient;
class SimulationRunner;
}
namespace OpenWifi::OWLSClientEvents {
void EstablishConnection(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
void Reconnect(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
bool Connect(std::lock_guard<std::mutex> & ClientGuard, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
void State(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
void HealthCheck(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
void Log(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner, std::uint64_t Severity, const std::string & LogLine);
void WSPing(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
void Update(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
void KeepAlive(const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
void Disconnect(const char *context, std::lock_guard<std::mutex> &g, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner, const std::string &Reason, bool Reconnect);
void CrashLog(std::lock_guard<std::mutex> &g, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
void PendingConfig(std::lock_guard<std::mutex> &g, const std::shared_ptr<OWLSclient> &Client, SimulationRunner *Runner);
};

33
src/OWLSdefinitions.h Normal file
View File

@@ -0,0 +1,33 @@
//
// Created by stephane bourque on 2021-04-03.
//
#pragma once
#include <mutex>
namespace OpenWifi {
enum OWLSeventType {
ev_none,
ev_reconnect,
ev_connect,
ev_state,
ev_healthcheck,
ev_log,
ev_crashlog,
ev_configpendingchange,
ev_keepalive,
ev_reboot,
ev_disconnect,
ev_wsping,
ev_update
};
using my_mutex = std::recursive_mutex;
using my_guard = std::lock_guard<my_mutex>;
enum ap_interface_types { upstream, downstream };
#define DEBUG_LINE(X) std::cout << __LINE__ << ": " << __func__ << " :" << X << std::endl;
}

View File

@@ -9,8 +9,8 @@
namespace OpenWifi {
void RESTAPI_deviceDashboardHandler::DoGet() {
Daemon()->GetDashboard().Create();
Poco::JSON::Object Answer;
Poco::JSON::Object Answer;
Daemon()->GetDashboard().Report().to_json(Answer);
ReturnObject(Answer);
}
}
} // namespace OpenWifi

View File

@@ -7,22 +7,22 @@
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_deviceDashboardHandler : public RESTAPIHandler {
public:
RESTAPI_deviceDashboardHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{
Poco::Net::HTTPRequest::HTTP_GET, Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server,
TransactionId,
Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/owlsDashboard"};}
void DoGet();
void DoPost() {};
void DoPut() {};
void DoDelete() {};
private:
class RESTAPI_deviceDashboardHandler : public RESTAPIHandler {
public:
RESTAPI_deviceDashboardHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server,
uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/owlsDashboard"}; }
void DoGet();
void DoPost(){};
void DoPut(){};
void DoDelete(){};
};
}
private:
};
} // namespace OpenWifi

View File

@@ -3,44 +3,46 @@
//
#include "RESTAPI_operation_handler.h"
#include "Simulation.h"
#include "SimStats.h"
#include "SimulationCoordinator.h"
namespace OpenWifi {
void RESTAPI_operation_handler::DoPost() {
void RESTAPI_operation_handler::DoPost() {
std::string Op;
if(!HasParameter("operation", Op) ||
( Op != "start" && Op!= "stop" && Op != "cancel")) {
auto Id = GetBinding("id","");
if(Id.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
std::string Id;
if(HasParameter("id",Id) && Op=="start") {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
std::string Op;
if (!HasParameter("operation", Op) || (Op != "start" && Op != "stop" && Op != "cancel")) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
std::string SimId;
if(HasParameter("simulationId",SimId) && Op!="start") {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
std::string SimId;
if (!HasParameter("runningId", SimId) && Op!="start") {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
std::string Error;
if(Op=="start") {
SimulationCoordinator()->StartSim(SimId,Id,Error, UserInfo_.userinfo.email);
} else if(Op=="stop") {
SimulationCoordinator()->StopSim(Id,Error);
} else if(Op=="cancel") {
SimulationCoordinator()->CancelSim(Id,Error);
}
auto Error=OpenWifi::RESTAPI::Errors::SUCCESS;
if (Op == "start") {
if(SimulationCoordinator()->IsSimulationRunning(Id)) {
return BadRequest(RESTAPI::Errors::SimulationIsAlreadyRunning);
}
SimulationCoordinator()->StartSim(SimId, Id, Error, UserInfo_.userinfo);
} else if (Op == "stop") {
SimulationCoordinator()->StopSim(SimId, Error, UserInfo_.userinfo);
} else if (Op == "cancel") {
SimulationCoordinator()->CancelSim(SimId, Error, UserInfo_.userinfo);
}
if(Error.empty()) {
OWLSObjects::SimulationStatus S;
SimStats()->GetCurrent(S);
Poco::JSON::Object Answer;
S.to_json(Answer);
return ReturnObject(Answer);
}
return BadRequest(RESTAPI::Errors::CouldNotPerformCommand);
}
}
if (Error.err_num==OpenWifi::RESTAPI::Errors::SUCCESS.err_num) {
OWLSObjects::SimulationStatus S;
SimStats()->GetCurrent(SimId,S, UserInfo_.userinfo);
Poco::JSON::Object Answer;
S.to_json(Answer);
return ReturnObject(Answer);
}
return BadRequest(Error);
}
} // namespace OpenWifi

View File

@@ -7,22 +7,21 @@
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_operation_handler : public RESTAPIHandler {
public:
RESTAPI_operation_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{
Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server,
TransactionId,
Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/operation"};}
void DoGet() final {};
void DoPost() final ;
void DoPut() final {};
void DoDelete() final {};
private:
class RESTAPI_operation_handler : public RESTAPIHandler {
public:
RESTAPI_operation_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/operation/{id}"}; }
void DoGet() final{};
void DoPost() final;
void DoPut() final{};
void DoDelete() final{};
};
}
private:
};
} // namespace OpenWifi

View File

@@ -8,20 +8,29 @@
namespace OpenWifi {
void RESTAPI_results_handler::DoGet() {
std::vector<OWLSObjects::SimulationStatus> Results;
StorageService()->SimulationResultsDB().GetRecords(1,10000,Results);
return ReturnObject("list",Results);
}
void RESTAPI_results_handler::DoGet() {
void RESTAPI_results_handler::DoDelete() {
std::string id;
if(!HasParameter("id",id) || id.empty()) {
auto sim_id = GetBinding("id","");
if(sim_id.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
if(!StorageService()->SimulationResultsDB().DeleteRecord("id",id))
return NotFound();
return OK();
}
}
std::vector<OWLSObjects::SimulationStatus> Results;
auto where = fmt::format(" simulationId='{}' ", sim_id);
StorageService()->SimulationResultsDB().GetRecords(QB_.Offset, QB_.Limit, Results, where, " ORDER BY startTime DESC ");
return ReturnObject("list", Results);
}
void RESTAPI_results_handler::DoDelete() {
auto id = GetBinding("id","");
if (id.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
if (!StorageService()->SimulationResultsDB().DeleteRecord("id", id))
return NotFound();
return OK();
}
} // namespace OpenWifi

View File

@@ -7,24 +7,23 @@
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_results_handler : public RESTAPIHandler {
public:
RESTAPI_results_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{
Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_DELETE,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server,
TransactionId,
Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/results"};}
void DoGet() final;
void DoPost() final {};
void DoPut() final {};
void DoDelete() final ;
private:
class RESTAPI_results_handler : public RESTAPIHandler {
public:
RESTAPI_results_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_DELETE,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/results/{id}"}; }
void DoGet() final;
void DoPost() final{};
void DoPut() final{};
void DoDelete() final;
};
private:
};
}
} // namespace OpenWifi

View File

@@ -13,26 +13,20 @@
namespace OpenWifi {
Poco::Net::HTTPRequestHandler * RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t TransactionId) {
return RESTAPI_Router<
RESTAPI_system_command,
RESTAPI_deviceDashboardHandler,
RESTAPI_operation_handler,
RESTAPI_results_handler,
RESTAPI_simulation_handler,
RESTAPI_status_handler,
RESTAPI_webSocketServer
>(Path,Bindings,L, S, TransactionId);
}
Poco::Net::HTTPRequestHandler *
RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t TransactionId) {
return RESTAPI_Router<RESTAPI_system_command, RESTAPI_deviceDashboardHandler,
RESTAPI_operation_handler, RESTAPI_results_handler,
RESTAPI_simulation_handler, RESTAPI_status_handler,
RESTAPI_webSocketServer>(Path, Bindings, L, S, TransactionId);
}
Poco::Net::HTTPRequestHandler * RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t TransactionId) {
return RESTAPI_Router_I<
RESTAPI_operation_handler,
RESTAPI_results_handler,
RESTAPI_simulation_handler,
RESTAPI_system_command
>(Path, Bindings, L, S, TransactionId);
}
}
Poco::Net::HTTPRequestHandler *
RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t TransactionId) {
return RESTAPI_Router_I<RESTAPI_operation_handler, RESTAPI_results_handler,
RESTAPI_simulation_handler, RESTAPI_system_command>(
Path, Bindings, L, S, TransactionId);
}
} // namespace OpenWifi

View File

@@ -9,136 +9,145 @@
#include "Poco/Net/HTTPCookie.h"
#include "Poco/Net/NameValueCollection.h"
#include "framework/MicroServiceFuncs.h"
#include <framework/default_device_types.h>
namespace OpenWifi {
static const std::vector<std::string> DefaultDeviceTypes{
"actiontec_web7200",
"cig_wf188n",
"cig_wf194c",
"cig_wf194c4",
"cig_wf196",
"cig_wf610d",
"cig_wf808",
"cybertan_eww622-a1",
"edgecore_eap101",
"edgecore_eap102",
"edgecore_eap104",
"edgecore_ecs4100-12ph",
"edgecore_ecw5211",
"edgecore_ecw5410",
"edgecore_oap100",
"edgecore_spw2ac1200",
"edgecore_spw2ac1200-lan-poe",
"edgecore_ssw2ac2600",
"hfcl_ion4",
"hfcl_ion4x",
"hfcl_ion4x_2",
"hfcl_ion4xe",
"hfcl_ion4xi",
"indio_um-305ac",
"indio_um-305ax",
"indio_um-310ax-v1",
"indio_um-325ac",
"indio_um-510ac-v3",
"indio_um-510axm-v1",
"indio_um-510axp-v1",
"indio_um-550ac",
"linksys_e8450-ubi",
"linksys_ea6350-v4",
"linksys_ea8300",
"liteon_wpx8324",
"meshpp_s618_cp01",
"meshpp_s618_cp03",
"tp-link_ec420-g1",
"tplink_ex227",
"tplink_ex228",
"tplink_ex447",
"udaya_a5-id2",
"wallys_dr40x9",
"wallys_dr6018",
"wallys_dr6018_v4",
"x64_vm",
"yuncore_ax840",
"yuncore_fap640",
"yuncore_fap650"};
static bool GooDeviceType(const std::string &D) {
for(const auto &i:DefaultDeviceTypes) {
if(i==D)
return true;
static bool GooDeviceType(const std::string &D) {
for(const auto &[name,_]:DefaultDeviceTypeList) {
if(name==D) return true;
}
return false;
}
void RESTAPI_simulation_handler::DoPost() {
OWLSObjects::SimulationDetails D;
const auto &Raw = ParsedBody_;
if(!D.from_json(Raw) ||
D.name.empty() ||
D.gateway.empty() ||
D.macPrefix.size()!=6 ||
D.deviceType.empty() ||
!GooDeviceType(D.deviceType) ||
(D.maxClients<D.minClients) ||
(D.maxAssociations<D.minAssociations)) {
return BadRequest(RESTAPI::Errors::InvalidJSONDocument);
}
D.id = MicroServiceCreateUUID();
if(StorageService()->SimulationDB().CreateRecord(D)) {
OWLSObjects::SimulationDetails N;
StorageService()->SimulationDB().GetRecord("id", D.id, N);
Poco::JSON::Object Answer;
N.to_json(Answer);
return ReturnObject(Answer);
}
BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
}
void RESTAPI_simulation_handler::DoGet() {
std::vector<OWLSObjects::SimulationDetails> Sims;
StorageService()->SimulationDB().GetRecords(1,1000,Sims);
ReturnObject("list", Sims);
}
auto id = GetBinding("id","");
void RESTAPI_simulation_handler::DoDelete() {
std::string id;
if(!HasParameter("id",id) || id.empty()) {
if(id.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
if(!StorageService()->SimulationDB().DeleteRecord("id",id))
return NotFound();
return OK();
if(id == "*") {
std::vector<OWLSObjects::SimulationDetails> Sims;
StorageService()->SimulationDB().GetRecords(QB_.Offset, QB_.Limit, Sims);
return ReturnObject("list", Sims);
}
OWLSObjects::SimulationDetails Sim;
if(StorageService()->SimulationDB().GetRecord("id",id, Sim)) {
Poco::JSON::Object Answer;
Sim.to_json(Answer);
return ReturnObject(Answer);
}
return NotFound();
}
void RESTAPI_simulation_handler::DoPut() {
OWLSObjects::SimulationDetails D;
const auto &Raw = ParsedBody_;
static bool ValidateSimulation(const OWLSObjects::SimulationDetails & ExistingSimulation ) {
if( ExistingSimulation.name.empty() ||
ExistingSimulation.gateway.empty() ||
ExistingSimulation.deviceType.empty() ||
!GooDeviceType(ExistingSimulation.deviceType) ||
ExistingSimulation.maxClients < ExistingSimulation.minClients ||
ExistingSimulation.maxAssociations < ExistingSimulation.minAssociations ||
ExistingSimulation.devices <1 || ExistingSimulation.devices>50000 ||
ExistingSimulation.healthCheckInterval < 30 || ExistingSimulation.healthCheckInterval >600 ||
ExistingSimulation.stateInterval < 30 || ExistingSimulation.healthCheckInterval>600 ||
ExistingSimulation.minAssociations > 4 ||
ExistingSimulation.maxAssociations > 64 ||
ExistingSimulation.minClients > 4 ||
ExistingSimulation.maxAssociations > 16 ||
ExistingSimulation.keepAlive <120 || ExistingSimulation.keepAlive>3000 ||
ExistingSimulation.reconnectInterval <10 || ExistingSimulation.reconnectInterval>300 ||
ExistingSimulation.concurrentDevices < 1 || ExistingSimulation.concurrentDevices >1000 ||
ExistingSimulation.threads < 4 || ExistingSimulation.threads > 1024 ||
ExistingSimulation.macPrefix.size()!=6 ) {
return false;
}
return true;
}
if(!D.from_json(Raw) ||
D.id.empty() ||
D.name.empty() ||
D.gateway.empty() ||
D.macPrefix.size()!=6 ||
D.deviceType.empty() ||
!GooDeviceType(D.deviceType) ||
(D.maxClients<D.minClients) ||
(D.maxAssociations<D.minAssociations)) {
void RESTAPI_simulation_handler::DoPost() {
OWLSObjects::SimulationDetails NewSimulation;
const auto &Raw = ParsedBody_;
if (!NewSimulation.from_json(Raw)) {
return BadRequest(RESTAPI::Errors::InvalidJSONDocument);
}
if(StorageService()->SimulationDB().UpdateRecord("id", D.id, D)) {
OWLSObjects::SimulationDetails N;
StorageService()->SimulationDB().GetRecord("id", D.id, N);
Poco::JSON::Object Answer;
N.to_json(Answer);
return ReturnObject(Answer);
if(!ValidateSimulation(NewSimulation)) {
return BadRequest(RESTAPI::Errors::InvalidJSONDocument);
}
NewSimulation.id = MicroServiceCreateUUID();
if (StorageService()->SimulationDB().CreateRecord(NewSimulation)) {
OWLSObjects::SimulationDetails N;
StorageService()->SimulationDB().GetRecord("id", NewSimulation.id, N);
Poco::JSON::Object Answer;
N.to_json(Answer);
return ReturnObject(Answer);
}
BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
void RESTAPI_simulation_handler::DoDelete() {
auto id = GetBinding("id","");
if (id.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
if (!StorageService()->SimulationDB().DeleteRecord("id", id))
return NotFound();
return OK();
}
void RESTAPI_simulation_handler::DoPut() {
OWLSObjects::SimulationDetails NewSimulation;
auto id = GetBinding("id","");
if (id.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
NotFound();
}
}
if (!NewSimulation.from_json(ParsedBody_)) {
return BadRequest(RESTAPI::Errors::InvalidJSONDocument);
}
OWLSObjects::SimulationDetails ExistingSimulation;
if(!StorageService()->SimulationDB().GetRecord("id", id, ExistingSimulation)) {
return NotFound();
}
AssignIfPresent(ParsedBody_, "name", ExistingSimulation.name);
AssignIfPresent(ParsedBody_, "gateway", ExistingSimulation.gateway);
AssignIfPresent(ParsedBody_, "macPrefix", ExistingSimulation.macPrefix);
AssignIfPresent(ParsedBody_, "deviceType", ExistingSimulation.deviceType);
AssignIfPresent(ParsedBody_, "devices", ExistingSimulation.devices);
AssignIfPresent(ParsedBody_, "healthCheckInterval", ExistingSimulation.healthCheckInterval);
AssignIfPresent(ParsedBody_, "stateInterval", ExistingSimulation.stateInterval);
AssignIfPresent(ParsedBody_, "minAssociations", ExistingSimulation.minAssociations);
AssignIfPresent(ParsedBody_, "maxAssociations", ExistingSimulation.maxAssociations);
AssignIfPresent(ParsedBody_, "minClients", ExistingSimulation.minClients);
AssignIfPresent(ParsedBody_, "maxClients", ExistingSimulation.maxClients);
AssignIfPresent(ParsedBody_, "simulationLength", ExistingSimulation.simulationLength);
AssignIfPresent(ParsedBody_, "threads", ExistingSimulation.threads);
AssignIfPresent(ParsedBody_, "keepAlive", ExistingSimulation.keepAlive);
AssignIfPresent(ParsedBody_, "reconnectInterval", ExistingSimulation.reconnectInterval);
AssignIfPresent(ParsedBody_, "concurrentDevices", ExistingSimulation.concurrentDevices);
if(!ValidateSimulation(NewSimulation)) {
return BadRequest(RESTAPI::Errors::InvalidJSONDocument);
}
if (StorageService()->SimulationDB().UpdateRecord("id", id, ExistingSimulation)) {
OWLSObjects::SimulationDetails N;
StorageService()->SimulationDB().GetRecord("id", ExistingSimulation.id, N);
Poco::JSON::Object Answer;
N.to_json(Answer);
return ReturnObject(Answer);
}
NotFound();
}
} // namespace OpenWifi

View File

@@ -7,26 +7,24 @@
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_simulation_handler : public RESTAPIHandler {
public:
RESTAPI_simulation_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{
Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_PUT,
Poco::Net::HTTPRequest::HTTP_DELETE,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server,
TransactionId,
Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/simulation"};}
void DoGet() final;
void DoPost() final;
void DoPut() final;
void DoDelete() final;
private:
};
}
class RESTAPI_simulation_handler : public RESTAPIHandler {
public:
RESTAPI_simulation_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_PUT,
Poco::Net::HTTPRequest::HTTP_DELETE,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/simulation/{id}"}; }
void DoGet() final;
void DoPost() final;
void DoPut() final;
void DoDelete() final;
private:
};
} // namespace OpenWifi

View File

@@ -7,11 +7,30 @@
#include "SimStats.h"
namespace OpenWifi {
void RESTAPI_status_handler::DoGet() {
OWLSObjects::SimulationStatus S;
SimStats()->GetCurrent(S);
Poco::JSON::Object Answer;
S.to_json(Answer);
ReturnObject(Answer);
}
}
void RESTAPI_status_handler::DoGet() {
auto id = GetBinding("id","");
if(id.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
std::vector<OWLSObjects::SimulationStatus> Statuses;
if(id=="*") {
SimStats()->GetAllSimulations(Statuses, UserInfo_.userinfo);
} else {
OWLSObjects::SimulationStatus S;
SimStats()->GetCurrent(id, S, UserInfo_.userinfo);
Statuses.emplace_back(S);
}
Poco::JSON::Array Arr;
for(const auto &status:Statuses) {
Poco::JSON::Object Obj;
status.to_json(Obj);
Arr.add(Obj);
}
std::ostringstream os;
Arr.stringify(os);
ReturnRawJSON(os.str());
}
} // namespace OpenWifi

View File

@@ -7,23 +7,22 @@
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_status_handler : public RESTAPIHandler {
public:
RESTAPI_status_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{
Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server,
TransactionId,
Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/status"};}
void DoGet() final;
void DoPost() final {};
void DoPut() final {};
void DoDelete() final {};
private:
class RESTAPI_status_handler : public RESTAPIHandler {
public:
RESTAPI_status_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/status/{id}"}; }
void DoGet() final;
void DoPost() final{};
void DoPut() final{};
void DoDelete() final{};
};
private:
};
}
} // namespace OpenWifi

File diff suppressed because it is too large Load Diff

View File

@@ -10,414 +10,334 @@
namespace OpenWifi {
namespace AnalyticsObjects {
struct Report {
uint64_t snapShot = 0;
void reset();
void to_json(Poco::JSON::Object &Obj) const;
};
struct VenueInfo {
OpenWifi::Types::UUID_t id;
std::string name;
std::string description;
uint64_t retention = 0;
uint64_t interval = 0;
bool monitorSubVenues = false;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct BoardInfo {
ProvObjects::ObjectInfo info;
std::vector<VenueInfo> venueList;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
inline bool operator<(const BoardInfo &bb) const {
return info.id < bb.info.id;
}
inline bool operator==(const BoardInfo &bb) const {
return info.id == bb.info.id;
}
};
struct DeviceInfo {
std::string boardId;
std::string type;
std::string serialNumber;
std::string deviceType;
uint64_t lastContact = 0 ;
uint64_t lastPing = 0;
uint64_t lastState = 0;
std::string lastFirmware;
uint64_t lastFirmwareUpdate = 0;
uint64_t lastConnection = 0;
uint64_t lastDisconnection = 0;
uint64_t pings = 0;
uint64_t states = 0;
bool connected = false;
std::string connectionIp;
uint64_t associations_2g = 0;
uint64_t associations_5g = 0;
uint64_t associations_6g = 0;
uint64_t health = 0;
uint64_t lastHealth = 0;
std::string locale;
uint64_t uptime = 0;
double memory = 0.0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceInfoList {
std::vector<DeviceInfo> devices;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
enum wifi_band {
band_2g = 0, band_5g = 1, band_6g = 2
};
struct TIDstat_entry {
uint64_t rx_msdu = 0,
tx_msdu = 0,
tx_msdu_failed = 0,
tx_msdu_retries = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct UE_rate {
uint64_t bitrate=0;
uint64_t mcs=0;
uint64_t nss=0;
bool ht=false;
bool sgi=false;
uint64_t chwidth=0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct AveragePoint {
double min = 0.0,
max = 0.0,
avg = 0.0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct UETimePoint {
std::string station;
int64_t rssi = 0;
uint64_t tx_bytes = 0,
rx_bytes = 0,
tx_duration = 0,
rx_packets = 0,
tx_packets = 0,
tx_retries = 0,
tx_failed = 0,
connected = 0,
inactive = 0;
double tx_bytes_bw = 0.0 ,
rx_bytes_bw = 0.0 ,
tx_packets_bw = 0.0 ,
rx_packets_bw = 0.0 ,
tx_failed_pct = 0.0 ,
tx_retries_pct = 0.0 ,
tx_duration_pct = 0.0;
uint64_t tx_bytes_delta = 0,
rx_bytes_delta = 0,
tx_duration_delta = 0,
rx_packets_delta = 0,
tx_packets_delta = 0,
tx_retries_delta = 0,
tx_failed_delta = 0;
UE_rate tx_rate,
rx_rate;
std::vector<TIDstat_entry> tidstats;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
enum SSID_MODES {
unknown = 0,
ap,
mesh,
sta,
wds_ap,
wds_sta,
wds_repeater
};
inline SSID_MODES SSID_Mode(const std::string &m) {
if (m == "ap")
return ap;
if (m == "sta")
return sta;
if (m == "mesh")
return mesh;
if (m == "wds-ap")
return wds_ap;
if (m == "wds-sta")
return wds_sta;
if (m == "wds-repeater")
return wds_repeater;
return unknown;
}
struct SSIDTimePoint {
std::string bssid,
mode,
ssid;
uint64_t band=0,
channel=0;
std::vector<UETimePoint> associations;
AveragePoint tx_bytes_bw,
rx_bytes_bw,
tx_packets_bw,
rx_packets_bw,
tx_failed_pct,
tx_retries_pct,
tx_duration_pct;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct APTimePoint {
uint64_t collisions = 0,
multicast = 0,
rx_bytes = 0,
rx_dropped = 0,
rx_errors = 0,
rx_packets = 0,
tx_bytes = 0,
tx_dropped = 0,
tx_errors = 0,
tx_packets = 0;
double tx_bytes_bw = 0.0 ,
rx_bytes_bw = 0.0 ,
rx_dropped_pct = 0.0,
tx_dropped_pct = 0.0,
rx_packets_bw = 0.0,
tx_packets_bw = 0.0,
rx_errors_pct = 0.0 ,
tx_errors_pct = 0.0;
uint64_t tx_bytes_delta = 0,
rx_bytes_delta = 0 ,
rx_dropped_delta = 0,
tx_dropped_delta = 0,
rx_packets_delta = 0,
tx_packets_delta = 0,
rx_errors_delta = 0,
tx_errors_delta = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RadioTimePoint {
uint64_t band = 0,
channel_width = 0;
uint64_t active_ms = 0,
busy_ms = 0,
receive_ms = 0,
transmit_ms = 0,
tx_power = 0,
channel = 0;
int64_t temperature = 0,
noise = 0;
double active_pct = 0.0 ,
busy_pct = 0.0,
receive_pct = 0.0,
transmit_pct = 0.0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceTimePoint {
std::string id;
std::string boardId;
uint64_t timestamp = 0;
APTimePoint ap_data;
std::vector<SSIDTimePoint> ssid_data;
std::vector<RadioTimePoint> radio_data;
AnalyticsObjects::DeviceInfo device_info;
std::string serialNumber;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
inline bool operator<(const DeviceTimePoint &rhs) const {
if(timestamp < rhs.timestamp)
return true;
if(timestamp > rhs.timestamp)
return false;
if(device_info.serialNumber < rhs.device_info.serialNumber)
return true;
return false;
}
inline bool operator==(const DeviceTimePoint &rhs) const {
return timestamp==rhs.timestamp && device_info.serialNumber==rhs.device_info.serialNumber;
}
inline bool operator>(const DeviceTimePoint &rhs) const {
if(timestamp > rhs.timestamp)
return true;
if(timestamp < rhs.timestamp)
return false;
if(device_info.serialNumber > rhs.device_info.serialNumber)
return true;
return false;
}
};
struct DeviceTimePointAnalysis {
uint64_t timestamp;
AveragePoint noise;
AveragePoint temperature;
AveragePoint active_pct;
AveragePoint busy_pct;
AveragePoint receive_pct;
AveragePoint transmit_pct;
AveragePoint tx_power;
AveragePoint tx_bytes_bw;
AveragePoint rx_bytes_bw;
AveragePoint rx_dropped_pct;
AveragePoint tx_dropped_pct;
AveragePoint rx_packets_bw;
AveragePoint tx_packets_bw;
AveragePoint rx_errors_pct;
AveragePoint tx_errors_pct;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceTimePointList {
std::vector<DeviceTimePoint> points;
std::vector<DeviceTimePointAnalysis> stats;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct BandwidthAnalysisEntry {
uint64_t timestamp = 0;
};
struct BandwidthAnalysis {
};
struct AverageValueSigned {
int64_t peak=0, avg=0, low=0;
};
struct AverageValueUnsigned {
uint64_t peak=0, avg=0, low=0;
};
struct RadioAnalysis {
uint64_t timestamp=0;
AverageValueSigned noise, temperature;
AverageValueUnsigned active_ms,
busy_ms,
transmit_ms,
receive_ms;
};
struct DeviceTimePointStats {
uint64_t firstPoint=0;
uint64_t lastPoint=0;
uint64_t count=0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WifiClientRate {
uint32_t bitrate=0;
uint32_t chwidth=0;
uint16_t mcs=0;
uint16_t nss=0;
bool vht=false;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WifiClientHistory {
uint64_t timestamp=Utils::Now();
std::string station_id;
std::string bssid;
std::string ssid;
int64_t rssi=0;
uint32_t rx_bitrate=0;
uint32_t rx_chwidth=0;
uint16_t rx_mcs=0;
uint16_t rx_nss=0;
bool rx_vht=false;
uint32_t tx_bitrate=0;
uint32_t tx_chwidth=0;
uint16_t tx_mcs=0;
uint16_t tx_nss=0;
bool tx_vht=false;
uint64_t rx_bytes=0;
uint64_t tx_bytes=0;
uint64_t rx_duration=0;
uint64_t tx_duration=0;
uint64_t rx_packets=0;
uint64_t tx_packets=0;
std::string ipv4;
std::string ipv6;
uint64_t channel_width=0;
int64_t noise=0;
uint64_t tx_power=0;
uint64_t channel=0;
uint64_t active_ms=0;
uint64_t busy_ms=0;
uint64_t receive_ms=0;
std::string mode;
int64_t ack_signal=0;
int64_t ack_signal_avg=0;
uint64_t connected=0;
uint64_t inactive=0;
uint64_t tx_retries=0;
std::string venue_id;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
}
}
namespace AnalyticsObjects {
struct Report {
uint64_t snapShot = 0;
void reset();
void to_json(Poco::JSON::Object &Obj) const;
};
struct VenueInfo {
OpenWifi::Types::UUID_t id;
std::string name;
std::string description;
uint64_t retention = 0;
uint64_t interval = 0;
bool monitorSubVenues = false;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct BoardInfo {
ProvObjects::ObjectInfo info;
std::vector<VenueInfo> venueList;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
inline bool operator<(const BoardInfo &bb) const { return info.id < bb.info.id; }
inline bool operator==(const BoardInfo &bb) const { return info.id == bb.info.id; }
};
struct DeviceInfo {
std::string boardId;
std::string type;
std::string serialNumber;
std::string deviceType;
uint64_t lastContact = 0;
uint64_t lastPing = 0;
uint64_t lastState = 0;
std::string lastFirmware;
uint64_t lastFirmwareUpdate = 0;
uint64_t lastConnection = 0;
uint64_t lastDisconnection = 0;
uint64_t pings = 0;
uint64_t states = 0;
bool connected = false;
std::string connectionIp;
uint64_t associations_2g = 0;
uint64_t associations_5g = 0;
uint64_t associations_6g = 0;
uint64_t health = 0;
uint64_t lastHealth = 0;
std::string locale;
uint64_t uptime = 0;
double memory = 0.0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceInfoList {
std::vector<DeviceInfo> devices;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
enum wifi_band { band_2g = 0, band_5g = 1, band_6g = 2 };
struct TIDstat_entry {
uint64_t rx_msdu = 0, tx_msdu = 0, tx_msdu_failed = 0, tx_msdu_retries = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct UE_rate {
uint64_t bitrate = 0;
uint64_t mcs = 0;
uint64_t nss = 0;
bool ht = false;
bool sgi = false;
uint64_t chwidth = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct AveragePoint {
double min = 0.0, max = 0.0, avg = 0.0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct UETimePoint {
std::string station;
int64_t rssi = 0;
uint64_t tx_bytes = 0, rx_bytes = 0, tx_duration = 0, rx_packets = 0, tx_packets = 0,
tx_retries = 0, tx_failed = 0, connected = 0, inactive = 0;
double tx_bytes_bw = 0.0, rx_bytes_bw = 0.0, tx_packets_bw = 0.0, rx_packets_bw = 0.0,
tx_failed_pct = 0.0, tx_retries_pct = 0.0, tx_duration_pct = 0.0;
uint64_t tx_bytes_delta = 0, rx_bytes_delta = 0, tx_duration_delta = 0,
rx_packets_delta = 0, tx_packets_delta = 0, tx_retries_delta = 0,
tx_failed_delta = 0;
UE_rate tx_rate, rx_rate;
std::vector<TIDstat_entry> tidstats;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
enum SSID_MODES { unknown = 0, ap, mesh, sta, wds_ap, wds_sta, wds_repeater };
inline SSID_MODES SSID_Mode(const std::string &m) {
if (m == "ap")
return ap;
if (m == "sta")
return sta;
if (m == "mesh")
return mesh;
if (m == "wds-ap")
return wds_ap;
if (m == "wds-sta")
return wds_sta;
if (m == "wds-repeater")
return wds_repeater;
return unknown;
}
struct SSIDTimePoint {
std::string bssid, mode, ssid;
uint64_t band = 0, channel = 0;
std::vector<UETimePoint> associations;
AveragePoint tx_bytes_bw, rx_bytes_bw, tx_packets_bw, rx_packets_bw, tx_failed_pct,
tx_retries_pct, tx_duration_pct;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct APTimePoint {
uint64_t collisions = 0, multicast = 0, rx_bytes = 0, rx_dropped = 0, rx_errors = 0,
rx_packets = 0, tx_bytes = 0, tx_dropped = 0, tx_errors = 0, tx_packets = 0;
double tx_bytes_bw = 0.0, rx_bytes_bw = 0.0, rx_dropped_pct = 0.0, tx_dropped_pct = 0.0,
rx_packets_bw = 0.0, tx_packets_bw = 0.0, rx_errors_pct = 0.0,
tx_errors_pct = 0.0;
uint64_t tx_bytes_delta = 0, rx_bytes_delta = 0, rx_dropped_delta = 0,
tx_dropped_delta = 0, rx_packets_delta = 0, tx_packets_delta = 0,
rx_errors_delta = 0, tx_errors_delta = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RadioTimePoint {
uint64_t band = 0, channel_width = 0;
uint64_t active_ms = 0, busy_ms = 0, receive_ms = 0, transmit_ms = 0, tx_power = 0,
channel = 0;
int64_t temperature = 0, noise = 0;
double active_pct = 0.0, busy_pct = 0.0, receive_pct = 0.0, transmit_pct = 0.0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceTimePoint {
std::string id;
std::string boardId;
uint64_t timestamp = 0;
APTimePoint ap_data;
std::vector<SSIDTimePoint> ssid_data;
std::vector<RadioTimePoint> radio_data;
AnalyticsObjects::DeviceInfo device_info;
std::string serialNumber;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
inline bool operator<(const DeviceTimePoint &rhs) const {
if (timestamp < rhs.timestamp)
return true;
if (timestamp > rhs.timestamp)
return false;
if (device_info.serialNumber < rhs.device_info.serialNumber)
return true;
return false;
}
inline bool operator==(const DeviceTimePoint &rhs) const {
return timestamp == rhs.timestamp &&
device_info.serialNumber == rhs.device_info.serialNumber;
}
inline bool operator>(const DeviceTimePoint &rhs) const {
if (timestamp > rhs.timestamp)
return true;
if (timestamp < rhs.timestamp)
return false;
if (device_info.serialNumber > rhs.device_info.serialNumber)
return true;
return false;
}
};
struct DeviceTimePointAnalysis {
uint64_t timestamp;
AveragePoint noise;
AveragePoint temperature;
AveragePoint active_pct;
AveragePoint busy_pct;
AveragePoint receive_pct;
AveragePoint transmit_pct;
AveragePoint tx_power;
AveragePoint tx_bytes_bw;
AveragePoint rx_bytes_bw;
AveragePoint rx_dropped_pct;
AveragePoint tx_dropped_pct;
AveragePoint rx_packets_bw;
AveragePoint tx_packets_bw;
AveragePoint rx_errors_pct;
AveragePoint tx_errors_pct;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceTimePointList {
std::vector<DeviceTimePoint> points;
std::vector<DeviceTimePointAnalysis> stats;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct BandwidthAnalysisEntry {
uint64_t timestamp = 0;
};
struct BandwidthAnalysis {};
struct AverageValueSigned {
int64_t peak = 0, avg = 0, low = 0;
};
struct AverageValueUnsigned {
uint64_t peak = 0, avg = 0, low = 0;
};
struct RadioAnalysis {
uint64_t timestamp = 0;
AverageValueSigned noise, temperature;
AverageValueUnsigned active_ms, busy_ms, transmit_ms, receive_ms;
};
struct DeviceTimePointStats {
uint64_t firstPoint = 0;
uint64_t lastPoint = 0;
uint64_t count = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WifiClientRate {
uint32_t bitrate = 0;
uint32_t chwidth = 0;
uint16_t mcs = 0;
uint16_t nss = 0;
bool vht = false;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WifiClientHistory {
uint64_t timestamp = Utils::Now();
std::string station_id;
std::string bssid;
std::string ssid;
int64_t rssi = 0;
uint32_t rx_bitrate = 0;
uint32_t rx_chwidth = 0;
uint16_t rx_mcs = 0;
uint16_t rx_nss = 0;
bool rx_vht = false;
uint32_t tx_bitrate = 0;
uint32_t tx_chwidth = 0;
uint16_t tx_mcs = 0;
uint16_t tx_nss = 0;
bool tx_vht = false;
uint64_t rx_bytes = 0;
uint64_t tx_bytes = 0;
uint64_t rx_duration = 0;
uint64_t tx_duration = 0;
uint64_t rx_packets = 0;
uint64_t tx_packets = 0;
std::string ipv4;
std::string ipv6;
uint64_t channel_width = 0;
int64_t noise = 0;
uint64_t tx_power = 0;
uint64_t channel = 0;
uint64_t active_ms = 0;
uint64_t busy_ms = 0;
uint64_t receive_ms = 0;
std::string mode;
int64_t ack_signal = 0;
int64_t ack_signal_avg = 0;
uint64_t connected = 0;
uint64_t inactive = 0;
uint64_t tx_retries = 0;
std::string venue_id;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
} // namespace AnalyticsObjects
} // namespace OpenWifi

View File

@@ -5,206 +5,208 @@
#include "RESTAPI_CertObjects.h"
#include "framework/RESTAPI_utils.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::field_to_json;
namespace OpenWifi::CertObjects {
void CertificateEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id);
field_to_json(Obj,"entity", entity);
field_to_json(Obj,"creator", creator);
field_to_json(Obj,"type", type);
field_to_json(Obj,"status", status);
field_to_json(Obj,"certificate", certificate);
field_to_json(Obj,"key", key);
field_to_json(Obj,"devid", devid);
field_to_json(Obj,"cas", cas);
field_to_json(Obj,"manufacturer", manufacturer);
field_to_json(Obj,"model", model);
field_to_json(Obj,"redirector", redirector);
field_to_json(Obj,"commonName", commonName);
field_to_json(Obj,"certificateId", certificateId);
field_to_json(Obj,"batch", batch);
field_to_json(Obj,"created", created);
field_to_json(Obj,"modified", modified);
field_to_json(Obj,"revoked", revoked);
field_to_json(Obj,"revokeCount", revokeCount);
field_to_json(Obj,"synched", synched);
}
void CertificateEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "entity", entity);
field_to_json(Obj, "creator", creator);
field_to_json(Obj, "type", type);
field_to_json(Obj, "status", status);
field_to_json(Obj, "certificate", certificate);
field_to_json(Obj, "key", key);
field_to_json(Obj, "devid", devid);
field_to_json(Obj, "cas", cas);
field_to_json(Obj, "manufacturer", manufacturer);
field_to_json(Obj, "model", model);
field_to_json(Obj, "redirector", redirector);
field_to_json(Obj, "commonName", commonName);
field_to_json(Obj, "certificateId", certificateId);
field_to_json(Obj, "batch", batch);
field_to_json(Obj, "created", created);
field_to_json(Obj, "modified", modified);
field_to_json(Obj, "revoked", revoked);
field_to_json(Obj, "revokeCount", revokeCount);
field_to_json(Obj, "synched", synched);
field_to_json(Obj, "expiryDate", expiryDate);
}
bool CertificateEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"id", id);
field_from_json(Obj,"entity", entity);
field_from_json(Obj,"creator", creator);
field_from_json(Obj,"type", type);
field_from_json(Obj,"status", status);
field_from_json(Obj,"certificate", certificate);
field_from_json(Obj,"key", key);
field_from_json(Obj,"devid", devid);
field_from_json(Obj,"cas", cas);
field_from_json(Obj,"manufacturer", manufacturer);
field_from_json(Obj,"model", model);
field_from_json(Obj,"redirector", redirector);
field_from_json(Obj,"commonName", commonName);
field_from_json(Obj,"certificateId", certificateId);
field_from_json(Obj,"batch", batch);
field_from_json(Obj,"created", created);
field_from_json(Obj,"modified", modified);
field_from_json(Obj,"revoked", revoked);
field_from_json(Obj,"revokeCount", revokeCount);
field_from_json(Obj,"synched", synched);
return true;
} catch (...) {
}
return false;
}
bool CertificateEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "entity", entity);
field_from_json(Obj, "creator", creator);
field_from_json(Obj, "type", type);
field_from_json(Obj, "status", status);
field_from_json(Obj, "certificate", certificate);
field_from_json(Obj, "key", key);
field_from_json(Obj, "devid", devid);
field_from_json(Obj, "cas", cas);
field_from_json(Obj, "manufacturer", manufacturer);
field_from_json(Obj, "model", model);
field_from_json(Obj, "redirector", redirector);
field_from_json(Obj, "commonName", commonName);
field_from_json(Obj, "certificateId", certificateId);
field_from_json(Obj, "batch", batch);
field_from_json(Obj, "created", created);
field_from_json(Obj, "modified", modified);
field_from_json(Obj, "revoked", revoked);
field_from_json(Obj, "revokeCount", revokeCount);
field_from_json(Obj, "synched", synched);
field_from_json(Obj, "expiryDate", expiryDate);
return true;
} catch (...) {
}
return false;
}
void EntityEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id);
field_to_json(Obj,"creator", creator);
field_to_json(Obj,"name", name);
field_to_json(Obj,"description", description);
field_to_json(Obj,"defaultRedirector", defaultRedirector);
field_to_json(Obj,"apiKey", apiKey);
field_to_json(Obj,"serverEnrollmentProfile", serverEnrollmentProfile);
field_to_json(Obj,"clientEnrollmentProfile", clientEnrollmentProfile);
field_to_json(Obj,"organization", organization);
field_to_json(Obj,"created", created);
field_to_json(Obj,"modified", modified);
field_to_json(Obj,"suspended", suspended);
field_to_json(Obj,"deleted", deleted);
field_to_json(Obj,"notes", notes);
}
void EntityEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "creator", creator);
field_to_json(Obj, "name", name);
field_to_json(Obj, "description", description);
field_to_json(Obj, "defaultRedirector", defaultRedirector);
field_to_json(Obj, "apiKey", apiKey);
field_to_json(Obj, "serverEnrollmentProfile", serverEnrollmentProfile);
field_to_json(Obj, "clientEnrollmentProfile", clientEnrollmentProfile);
field_to_json(Obj, "organization", organization);
field_to_json(Obj, "created", created);
field_to_json(Obj, "modified", modified);
field_to_json(Obj, "suspended", suspended);
field_to_json(Obj, "deleted", deleted);
field_to_json(Obj, "notes", notes);
}
bool EntityEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"id", id);
field_from_json(Obj,"creator", creator);
field_from_json(Obj,"name", name);
field_from_json(Obj,"description", description);
field_from_json(Obj,"defaultRedirector", defaultRedirector);
field_from_json(Obj,"apiKey", apiKey);
field_from_json(Obj,"serverEnrollmentProfile", serverEnrollmentProfile);
field_from_json(Obj,"clientEnrollmentProfile", clientEnrollmentProfile);
field_from_json(Obj,"organization", organization);
field_from_json(Obj,"created", created);
field_from_json(Obj,"modified", modified);
field_from_json(Obj,"suspended", suspended);
field_from_json(Obj,"deleted", deleted);
field_from_json(Obj,"notes", notes);
return true;
} catch (...) {
}
return false;
}
bool EntityEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "creator", creator);
field_from_json(Obj, "name", name);
field_from_json(Obj, "description", description);
field_from_json(Obj, "defaultRedirector", defaultRedirector);
field_from_json(Obj, "apiKey", apiKey);
field_from_json(Obj, "serverEnrollmentProfile", serverEnrollmentProfile);
field_from_json(Obj, "clientEnrollmentProfile", clientEnrollmentProfile);
field_from_json(Obj, "organization", organization);
field_from_json(Obj, "created", created);
field_from_json(Obj, "modified", modified);
field_from_json(Obj, "suspended", suspended);
field_from_json(Obj, "deleted", deleted);
field_from_json(Obj, "notes", notes);
return true;
} catch (...) {
}
return false;
}
void BatchEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id);
field_to_json(Obj,"entity", entity);
field_to_json(Obj,"creator", creator);
field_to_json(Obj,"name", name);
field_to_json(Obj,"description", description);
field_to_json(Obj,"manufacturer", manufacturer);
field_to_json(Obj,"model", model);
field_to_json(Obj,"redirector", redirector);
field_to_json(Obj,"commonNames", commonNames);
field_to_json(Obj,"jobHistory", jobHistory);
field_to_json(Obj,"notes", notes);
field_to_json(Obj,"submitted", submitted);
field_to_json(Obj,"started", started);
field_to_json(Obj,"completed", completed);
field_to_json(Obj,"modified", modified);
}
void BatchEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "entity", entity);
field_to_json(Obj, "creator", creator);
field_to_json(Obj, "name", name);
field_to_json(Obj, "description", description);
field_to_json(Obj, "manufacturer", manufacturer);
field_to_json(Obj, "model", model);
field_to_json(Obj, "redirector", redirector);
field_to_json(Obj, "commonNames", commonNames);
field_to_json(Obj, "jobHistory", jobHistory);
field_to_json(Obj, "notes", notes);
field_to_json(Obj, "submitted", submitted);
field_to_json(Obj, "started", started);
field_to_json(Obj, "completed", completed);
field_to_json(Obj, "modified", modified);
}
bool BatchEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"id", id);
field_from_json(Obj,"entity", entity);
field_from_json(Obj,"creator", creator);
field_from_json(Obj,"name", name);
field_from_json(Obj,"description", description);
field_from_json(Obj,"manufacturer", manufacturer);
field_from_json(Obj,"model", model);
field_from_json(Obj,"redirector", redirector);
field_from_json(Obj,"commonNames", commonNames);
field_from_json(Obj,"jobHistory", jobHistory);
field_from_json(Obj,"notes", notes);
field_from_json(Obj,"submitted", submitted);
field_from_json(Obj,"started", started);
field_from_json(Obj,"completed", completed);
field_from_json(Obj,"modified", modified);
return true;
} catch (...) {
}
return false;
}
bool BatchEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "entity", entity);
field_from_json(Obj, "creator", creator);
field_from_json(Obj, "name", name);
field_from_json(Obj, "description", description);
field_from_json(Obj, "manufacturer", manufacturer);
field_from_json(Obj, "model", model);
field_from_json(Obj, "redirector", redirector);
field_from_json(Obj, "commonNames", commonNames);
field_from_json(Obj, "jobHistory", jobHistory);
field_from_json(Obj, "notes", notes);
field_from_json(Obj, "submitted", submitted);
field_from_json(Obj, "started", started);
field_from_json(Obj, "completed", completed);
field_from_json(Obj, "modified", modified);
return true;
} catch (...) {
}
return false;
}
void JobEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id);
field_to_json(Obj,"entity", entity);
field_to_json(Obj,"creator", creator);
field_to_json(Obj,"batch", batch);
field_to_json(Obj,"commonNames", commonNames);
field_to_json(Obj,"completedNames", completedNames);
field_to_json(Obj,"errorNames", errorNames);
field_to_json(Obj,"status", status);
field_to_json(Obj,"command", command);
field_to_json(Obj,"parameters", parameters);
field_to_json(Obj,"submitted", submitted);
field_to_json(Obj,"started", started);
field_to_json(Obj,"completed", completed);
field_to_json(Obj,"requesterUsername", requesterUsername);
}
void JobEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "entity", entity);
field_to_json(Obj, "creator", creator);
field_to_json(Obj, "batch", batch);
field_to_json(Obj, "commonNames", commonNames);
field_to_json(Obj, "completedNames", completedNames);
field_to_json(Obj, "errorNames", errorNames);
field_to_json(Obj, "status", status);
field_to_json(Obj, "command", command);
field_to_json(Obj, "parameters", parameters);
field_to_json(Obj, "submitted", submitted);
field_to_json(Obj, "started", started);
field_to_json(Obj, "completed", completed);
field_to_json(Obj, "requesterUsername", requesterUsername);
}
bool JobEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"id", id);
field_from_json(Obj,"entity", entity);
field_from_json(Obj,"creator", creator);
field_from_json(Obj,"batch", batch);
field_from_json(Obj,"commonNames", commonNames);
field_from_json(Obj,"completedNames", completedNames);
field_from_json(Obj,"errorNames", errorNames);
field_from_json(Obj,"status", status);
field_from_json(Obj,"command", command);
field_from_json(Obj,"parameters", parameters);
field_from_json(Obj,"submitted", submitted);
field_from_json(Obj,"started", started);
field_from_json(Obj,"completed", completed);
field_from_json(Obj,"requesterUsername", requesterUsername);
return true;
} catch (...) {
}
return false;
}
bool JobEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "entity", entity);
field_from_json(Obj, "creator", creator);
field_from_json(Obj, "batch", batch);
field_from_json(Obj, "commonNames", commonNames);
field_from_json(Obj, "completedNames", completedNames);
field_from_json(Obj, "errorNames", errorNames);
field_from_json(Obj, "status", status);
field_from_json(Obj, "command", command);
field_from_json(Obj, "parameters", parameters);
field_from_json(Obj, "submitted", submitted);
field_from_json(Obj, "started", started);
field_from_json(Obj, "completed", completed);
field_from_json(Obj, "requesterUsername", requesterUsername);
return true;
} catch (...) {
}
return false;
}
void DashBoardYearlyStats::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "year", year);
field_to_json(Obj, "activeCerts", activeCerts);
field_to_json(Obj, "revokedCerts", revokedCerts);
}
void DashBoardYearlyStats::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "year", year);
field_to_json(Obj, "activeCerts", activeCerts);
field_to_json(Obj, "revokedCerts", revokedCerts);
}
void Dashboard::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"snapshot", snapshot);
field_to_json(Obj,"numberOfIssuedCerts", numberOfIssuedCerts);
field_to_json(Obj,"numberOfRevokedCerts", numberOfRevokedCerts);
field_to_json(Obj,"activeCertsPerOrganization", activeCertsPerOrganization);
field_to_json(Obj,"revokedCertsPerOrganization", revokedCertsPerOrganization);
field_to_json(Obj,"numberOfRedirectors", numberOfRedirectors);
field_to_json(Obj,"deviceTypes", deviceTypes);
field_to_json(Obj,"monthlyNumberOfCerts", monthlyNumberOfCerts);
field_to_json(Obj,"monthlyNumberOfCertsPerOrgPerYear", monthlyNumberOfCertsPerOrgPerYear);
}
void Dashboard::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "snapshot", snapshot);
field_to_json(Obj, "numberOfIssuedCerts", numberOfIssuedCerts);
field_to_json(Obj, "numberOfRevokedCerts", numberOfRevokedCerts);
field_to_json(Obj, "activeCertsPerOrganization", activeCertsPerOrganization);
field_to_json(Obj, "revokedCertsPerOrganization", revokedCertsPerOrganization);
field_to_json(Obj, "numberOfRedirectors", numberOfRedirectors);
field_to_json(Obj, "deviceTypes", deviceTypes);
field_to_json(Obj, "monthlyNumberOfCerts", monthlyNumberOfCerts);
field_to_json(Obj, "monthlyNumberOfCertsPerOrgPerYear", monthlyNumberOfCertsPerOrgPerYear);
}
void Dashboard::reset() {
snapshot=0;
numberOfRevokedCerts = numberOfIssuedCerts = 0;
activeCertsPerOrganization.clear();
revokedCertsPerOrganization.clear();
numberOfRedirectors.clear();
deviceTypes.clear();
monthlyNumberOfCerts.clear();
monthlyNumberOfCertsPerOrgPerYear.clear();
}
}
void Dashboard::reset() {
snapshot = 0;
numberOfRevokedCerts = numberOfIssuedCerts = 0;
activeCertsPerOrganization.clear();
revokedCertsPerOrganization.clear();
numberOfRedirectors.clear();
deviceTypes.clear();
monthlyNumberOfCerts.clear();
monthlyNumberOfCertsPerOrgPerYear.clear();
}
} // namespace OpenWifi::CertObjects

View File

@@ -4,120 +4,121 @@
#pragma once
#include <string>
#include "framework/OpenWifiTypes.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "framework/OpenWifiTypes.h"
#include <string>
namespace OpenWifi::CertObjects {
struct CertificateEntry {
OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t entity;
OpenWifi::Types::UUID_t creator;
std::string type;
std::string status;
std::string certificate;
std::string key;
std::string devid;
std::string cas;
std::string manufacturer;
std::string model;
std::string redirector;
std::string commonName;
std::string certificateId;
OpenWifi::Types::UUID_t batch;
uint64_t created = 0;
uint64_t modified = 0;
uint64_t revoked = 0;
uint64_t revokeCount = 0;
uint64_t synched = 0;
struct CertificateEntry {
OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t entity;
OpenWifi::Types::UUID_t creator;
std::string type;
std::string status;
std::string certificate;
std::string key;
std::string devid;
std::string cas;
std::string manufacturer;
std::string model;
std::string redirector;
std::string commonName;
std::string certificateId;
OpenWifi::Types::UUID_t batch;
uint64_t created = 0;
uint64_t modified = 0;
uint64_t revoked = 0;
uint64_t revokeCount = 0;
uint64_t synched = 0;
uint64_t expiryDate = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct EntityEntry {
OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t creator;
std::string name;
std::string description;
std::string defaultRedirector;
std::string apiKey;
std::string serverEnrollmentProfile;
std::string clientEnrollmentProfile;
std::string organization;
SecurityObjects::NoteInfoVec notes;
bool suspended=false;
bool deleted=false;
uint64_t created = 0 ;
uint64_t modified = 0 ;
struct EntityEntry {
OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t creator;
std::string name;
std::string description;
std::string defaultRedirector;
std::string apiKey;
std::string serverEnrollmentProfile;
std::string clientEnrollmentProfile;
std::string organization;
SecurityObjects::NoteInfoVec notes;
bool suspended = false;
bool deleted = false;
uint64_t created = 0;
uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct BatchEntry {
OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t entity;
OpenWifi::Types::UUID_t creator;
std::string name;
std::string description;
std::string manufacturer;
std::string model;
std::string redirector;
std::vector<std::string> commonNames;
std::vector<std::string> jobHistory;
SecurityObjects::NoteInfoVec notes;
uint64_t submitted = 0 ;
uint64_t started = 0 ;
uint64_t completed = 0 ;
uint64_t modified = 0 ;
struct BatchEntry {
OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t entity;
OpenWifi::Types::UUID_t creator;
std::string name;
std::string description;
std::string manufacturer;
std::string model;
std::string redirector;
std::vector<std::string> commonNames;
std::vector<std::string> jobHistory;
SecurityObjects::NoteInfoVec notes;
uint64_t submitted = 0;
uint64_t started = 0;
uint64_t completed = 0;
uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct JobEntry {
OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t entity;
OpenWifi::Types::UUID_t creator;
OpenWifi::Types::UUID_t batch;
std::string command;
OpenWifi::Types::StringVec commonNames;
OpenWifi::Types::StringVec completedNames;
OpenWifi::Types::StringVec errorNames;
Types::StringPairVec parameters;
std::string status;
uint64_t submitted=0;
uint64_t started=0;
uint64_t completed=0;
std::string requesterUsername;
struct JobEntry {
OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t entity;
OpenWifi::Types::UUID_t creator;
OpenWifi::Types::UUID_t batch;
std::string command;
OpenWifi::Types::StringVec commonNames;
OpenWifi::Types::StringVec completedNames;
OpenWifi::Types::StringVec errorNames;
Types::StringPairVec parameters;
std::string status;
uint64_t submitted = 0;
uint64_t started = 0;
uint64_t completed = 0;
std::string requesterUsername;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DashBoardYearlyStats {
uint64_t year=0;
OpenWifi::Types::Counted3DMapSII activeCerts;
OpenWifi::Types::Counted3DMapSII revokedCerts;
struct DashBoardYearlyStats {
uint64_t year = 0;
OpenWifi::Types::Counted3DMapSII activeCerts;
OpenWifi::Types::Counted3DMapSII revokedCerts;
void to_json(Poco::JSON::Object &Obj) const;
};
void to_json(Poco::JSON::Object &Obj) const;
};
struct Dashboard {
uint64_t snapshot=0;
uint64_t numberOfIssuedCerts=0;
uint64_t numberOfRevokedCerts=0;
OpenWifi::Types::CountedMap activeCertsPerOrganization;
OpenWifi::Types::CountedMap revokedCertsPerOrganization;
OpenWifi::Types::CountedMap numberOfRedirectors;
OpenWifi::Types::CountedMap deviceTypes;
OpenWifi::Types::CountedMap monthlyNumberOfCerts;
std::vector<DashBoardYearlyStats> monthlyNumberOfCertsPerOrgPerYear;
struct Dashboard {
uint64_t snapshot = 0;
uint64_t numberOfIssuedCerts = 0;
uint64_t numberOfRevokedCerts = 0;
OpenWifi::Types::CountedMap activeCertsPerOrganization;
OpenWifi::Types::CountedMap revokedCertsPerOrganization;
OpenWifi::Types::CountedMap numberOfRedirectors;
OpenWifi::Types::CountedMap deviceTypes;
OpenWifi::Types::CountedMap monthlyNumberOfCerts;
std::vector<DashBoardYearlyStats> monthlyNumberOfCertsPerOrgPerYear;
void to_json(Poco::JSON::Object &Obj) const;
void reset();
};
void to_json(Poco::JSON::Object &Obj) const;
void reset();
};
}
} // namespace OpenWifi::CertObjects

View File

@@ -6,305 +6,293 @@
#include "framework/RESTAPI_utils.h"
#include "framework/utils.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::field_to_json;
namespace OpenWifi::FMSObjects {
void Firmware::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "release", release);
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "description", description);
field_to_json(Obj, "revision", revision);
field_to_json(Obj, "uri", uri);
field_to_json(Obj, "image", image);
field_to_json(Obj, "imageDate", imageDate);
field_to_json(Obj, "size", size);
field_to_json(Obj, "downloadCount", downloadCount);
field_to_json(Obj, "firmwareHash", firmwareHash);
field_to_json(Obj, "owner", owner);
field_to_json(Obj, "location", location);
field_to_json(Obj, "uploader", uploader);
field_to_json(Obj, "digest", digest);
field_to_json(Obj, "latest", latest);
field_to_json(Obj, "notes", notes);
field_to_json(Obj, "created", created);
};
void Firmware::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "release", release);
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "description", description);
field_to_json(Obj, "revision", revision);
field_to_json(Obj, "uri", uri);
field_to_json(Obj, "image", image);
field_to_json(Obj, "imageDate", imageDate);
field_to_json(Obj, "size", size);
field_to_json(Obj, "downloadCount", downloadCount);
field_to_json(Obj, "firmwareHash", firmwareHash);
field_to_json(Obj, "owner", owner);
field_to_json(Obj, "location", location);
field_to_json(Obj, "uploader", uploader);
field_to_json(Obj, "digest", digest);
field_to_json(Obj, "latest", latest);
field_to_json(Obj, "notes", notes);
field_to_json(Obj, "created", created);
};
bool Firmware::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "release", release);
field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "description", description);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "uri", uri);
field_from_json(Obj, "image", image);
field_from_json(Obj, "imageDate", imageDate);
field_from_json(Obj, "size", size);
field_from_json(Obj, "downloadCount", downloadCount);
field_from_json(Obj, "firmwareHash", firmwareHash);
field_from_json(Obj, "owner", owner);
field_from_json(Obj, "location", location);
field_from_json(Obj, "uploader", uploader);
field_from_json(Obj, "digest", digest);
field_from_json(Obj, "latest", latest);
field_from_json(Obj, "notes", notes);
field_from_json(Obj, "created", created);
return true;
} catch (...) {
bool Firmware::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "release", release);
field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "description", description);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "uri", uri);
field_from_json(Obj, "image", image);
field_from_json(Obj, "imageDate", imageDate);
field_from_json(Obj, "size", size);
field_from_json(Obj, "downloadCount", downloadCount);
field_from_json(Obj, "firmwareHash", firmwareHash);
field_from_json(Obj, "owner", owner);
field_from_json(Obj, "location", location);
field_from_json(Obj, "uploader", uploader);
field_from_json(Obj, "digest", digest);
field_from_json(Obj, "latest", latest);
field_from_json(Obj, "notes", notes);
field_from_json(Obj, "created", created);
return true;
} catch (...) {
}
return true;
}
}
return true;
}
void FirmwareList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "firmwares", firmwares);
}
void FirmwareList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"firmwares",firmwares);
}
bool FirmwareList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "firmwares", firmwares);
return true;
} catch (...) {
}
return false;
}
bool FirmwareList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "firmwares", firmwares);
return true;
} catch (...) {
void DeviceType::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "manufacturer", manufacturer);
field_to_json(Obj, "model", model);
field_to_json(Obj, "policy", policy);
field_to_json(Obj, "notes", notes);
field_to_json(Obj, "lastUpdate", lastUpdate);
field_to_json(Obj, "created", created);
field_to_json(Obj, "id", id);
field_to_json(Obj, "id", id);
field_to_json(Obj, "id", id);
}
}
return false;
}
bool DeviceType::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "manufacturer", manufacturer);
field_from_json(Obj, "model", model);
field_from_json(Obj, "policy", policy);
field_from_json(Obj, "notes", notes);
field_from_json(Obj, "lastUpdate", lastUpdate);
field_from_json(Obj, "created", created);
field_from_json(Obj, "id", id);
field_from_json(Obj, "id", id);
field_from_json(Obj, "id", id);
return true;
} catch (...) {
}
return false;
}
void DeviceType::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "manufacturer", manufacturer);
field_to_json(Obj, "model", model);
field_to_json(Obj, "policy", policy);
field_to_json(Obj, "notes", notes);
field_to_json(Obj, "lastUpdate", lastUpdate);
field_to_json(Obj, "created", created);
field_to_json(Obj, "id", id);
field_to_json(Obj, "id", id);
field_to_json(Obj, "id", id);
}
void DeviceTypeList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "deviceTypes", deviceTypes);
}
bool DeviceType::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "manufacturer", manufacturer);
field_from_json(Obj, "model", model);
field_from_json(Obj, "policy", policy);
field_from_json(Obj, "notes", notes);
field_from_json(Obj, "lastUpdate", lastUpdate);
field_from_json(Obj, "created", created);
field_from_json(Obj, "id", id);
field_from_json(Obj, "id", id);
field_from_json(Obj, "id", id);
return true;
} catch (...) {
bool DeviceTypeList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "deviceTypes", deviceTypes);
return true;
} catch (...) {
}
return false;
}
}
return false;
}
void RevisionHistoryEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "fromRelease", fromRelease);
field_to_json(Obj, "toRelease", toRelease);
field_to_json(Obj, "commandUUID", commandUUID);
field_to_json(Obj, "revisionId", revisionId);
field_to_json(Obj, "upgraded", upgraded);
}
void DeviceTypeList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"deviceTypes", deviceTypes);
}
bool RevisionHistoryEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "fromRelease", fromRelease);
field_from_json(Obj, "toRelease", toRelease);
field_from_json(Obj, "commandUUID", commandUUID);
field_from_json(Obj, "revisionId", revisionId);
field_from_json(Obj, "upgraded", upgraded);
return true;
} catch (...) {
}
return false;
}
bool DeviceTypeList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"deviceTypes", deviceTypes);
return true;
} catch(...) {
void RevisionHistoryEntryList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "deviceTypes", history);
}
}
return false;
}
bool RevisionHistoryEntryList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "deviceTypes", history);
return true;
} catch (...) {
}
return false;
}
void RevisionHistoryEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "fromRelease", fromRelease);
field_to_json(Obj, "toRelease", toRelease);
field_to_json(Obj, "commandUUID", commandUUID);
field_to_json(Obj, "revisionId", revisionId);
field_to_json(Obj, "upgraded", upgraded);
}
void FirmwareAgeDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "latestId", latestId);
field_to_json(Obj, "image", image);
field_to_json(Obj, "imageDate", imageDate);
field_to_json(Obj, "revision", revision);
field_to_json(Obj, "uri", uri);
field_to_json(Obj, "age", age);
field_to_json(Obj, "latest", latest);
}
bool RevisionHistoryEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "fromRelease", fromRelease);
field_from_json(Obj, "toRelease", toRelease);
field_from_json(Obj, "commandUUID", commandUUID);
field_from_json(Obj, "revisionId", revisionId);
field_from_json(Obj, "upgraded", upgraded);
return true;
} catch(...) {
bool FirmwareAgeDetails::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "latestId", latestId);
field_from_json(Obj, "image", image);
field_from_json(Obj, "imageDate", imageDate);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "uri", uri);
field_from_json(Obj, "age", age);
field_from_json(Obj, "latest", latest);
return true;
} catch (...) {
}
return false;
}
}
return false;
}
void DeviceConnectionInformation::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "revision", revision);
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "endPoint", endPoint);
field_to_json(Obj, "lastUpdate", lastUpdate);
field_to_json(Obj, "status", status);
}
void RevisionHistoryEntryList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"deviceTypes", history);
}
bool DeviceConnectionInformation::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "endPoint", endPoint);
field_from_json(Obj, "lastUpdate", lastUpdate);
field_from_json(Obj, "status", status);
return true;
} catch (...) {
}
return false;
}
bool RevisionHistoryEntryList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"deviceTypes", history);
return true;
} catch(...) {
void DeviceReport::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "ouis", OUI_);
field_to_json(Obj, "revisions", Revisions_);
field_to_json(Obj, "deviceTypes", DeviceTypes_);
field_to_json(Obj, "status", Status_);
field_to_json(Obj, "endPoints", EndPoints_);
field_to_json(Obj, "usingLatest", UsingLatest_);
field_to_json(Obj, "unknownFirmwares", UnknownFirmwares_);
field_to_json(Obj, "snapshot", snapshot);
field_to_json(Obj, "numberOfDevices", numberOfDevices);
field_to_json(Obj, "totalSecondsOld", totalSecondsOld_);
}
}
return false;
}
void DeviceReport::reset() {
OUI_.clear();
Revisions_.clear();
DeviceTypes_.clear();
Status_.clear();
EndPoints_.clear();
UsingLatest_.clear();
UnknownFirmwares_.clear();
totalSecondsOld_.clear();
numberOfDevices = 0;
snapshot = Utils::Now();
}
void FirmwareAgeDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"latestId", latestId);
field_to_json(Obj,"image", image);
field_to_json(Obj,"imageDate", imageDate);
field_to_json(Obj,"revision", revision);
field_to_json(Obj,"uri", uri);
field_to_json(Obj,"age", age);
field_to_json(Obj,"latest",latest);
}
bool DeviceReport::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) {
try {
bool FirmwareAgeDetails::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"latestId", latestId);
field_from_json(Obj,"image", image);
field_from_json(Obj,"imageDate", imageDate);
field_from_json(Obj,"revision", revision);
field_from_json(Obj,"uri", uri);
field_from_json(Obj,"age", age);
field_from_json(Obj,"latest", latest);
return true;
} catch(...) {
return true;
} catch (...) {
}
return false;
}
}
return false;
}
void DeviceInformation::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "history", history);
field_to_json(Obj, "currentFirmware", currentFirmware);
field_to_json(Obj, "currentFirmwareDate", currentFirmwareDate);
field_to_json(Obj, "latestFirmware", latestFirmware);
field_to_json(Obj, "latestFirmwareDate", latestFirmwareDate);
field_to_json(Obj, "latestFirmwareAvailable", latestFirmwareAvailable);
field_to_json(Obj, "latestFirmwareURI", latestFirmwareURI);
}
void DeviceConnectionInformation::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "revision", revision);
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "endPoint", endPoint);
field_to_json(Obj, "lastUpdate", lastUpdate);
field_to_json(Obj, "status", status);
}
bool DeviceInformation::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "history", history);
field_from_json(Obj, "currentFirmware", currentFirmware);
field_from_json(Obj, "currentFirmwareDate", currentFirmwareDate);
field_from_json(Obj, "latestFirmware", latestFirmware);
field_from_json(Obj, "latestFirmwareDate", latestFirmwareDate);
field_from_json(Obj, "latestFirmwareAvailable", latestFirmwareAvailable);
field_from_json(Obj, "latestFirmwareURI", latestFirmwareURI);
return true;
} catch (...) {
}
return false;
}
bool DeviceConnectionInformation::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "endPoint", endPoint);
field_from_json(Obj, "lastUpdate", lastUpdate);
field_from_json(Obj, "status", status);
return true;
} catch(...) {
void DeviceCurrentInfo::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "revision", revision);
field_to_json(Obj, "upgraded", upgraded);
}
}
return false;
}
bool DeviceCurrentInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "upgraded", upgraded);
return true;
} catch (...) {
}
return false;
}
void DeviceReport::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "ouis",OUI_);
field_to_json(Obj, "revisions", Revisions_);
field_to_json(Obj, "deviceTypes", DeviceTypes_);
field_to_json(Obj, "status", Status_);
field_to_json(Obj, "endPoints", EndPoints_);
field_to_json(Obj, "usingLatest", UsingLatest_);
field_to_json(Obj, "unknownFirmwares", UnknownFirmwares_);
field_to_json(Obj,"snapshot",snapshot);
field_to_json(Obj,"numberOfDevices",numberOfDevices);
field_to_json(Obj, "totalSecondsOld", totalSecondsOld_);
}
void DeviceCurrentInfoList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "devices", devices);
}
void DeviceReport::reset() {
OUI_.clear();
Revisions_.clear();
DeviceTypes_.clear();
Status_.clear();
EndPoints_.clear();
UsingLatest_.clear();
UnknownFirmwares_.clear();
totalSecondsOld_.clear();
numberOfDevices = 0 ;
snapshot = Utils::Now();
}
bool DeviceCurrentInfoList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "devices", devices);
return true;
} catch (...) {
}
return false;
}
bool DeviceReport::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) {
try {
return true;
} catch (...) {
}
return false;
}
void DeviceInformation::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "serialNumber",serialNumber);
field_to_json(Obj, "history", history);
field_to_json(Obj, "currentFirmware", currentFirmware);
field_to_json(Obj, "currentFirmwareDate", currentFirmwareDate);
field_to_json(Obj, "latestFirmware", latestFirmware);
field_to_json(Obj, "latestFirmwareDate", latestFirmwareDate);
field_to_json(Obj, "latestFirmwareAvailable",latestFirmwareAvailable);
field_to_json(Obj, "latestFirmwareURI",latestFirmwareURI);
}
bool DeviceInformation::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "serialNumber",serialNumber);
field_from_json(Obj, "history", history);
field_from_json(Obj, "currentFirmware", currentFirmware);
field_from_json(Obj, "currentFirmwareDate", currentFirmwareDate);
field_from_json(Obj, "latestFirmware", latestFirmware);
field_from_json(Obj, "latestFirmwareDate", latestFirmwareDate);
field_from_json(Obj, "latestFirmwareAvailable",latestFirmwareAvailable);
field_from_json(Obj, "latestFirmwareURI",latestFirmwareURI);
return true;
} catch(...) {
}
return false;
}
void DeviceCurrentInfo::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "serialNumber",serialNumber);
field_to_json(Obj, "revision", revision);
field_to_json(Obj, "upgraded", upgraded);
}
bool DeviceCurrentInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "serialNumber",serialNumber);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "upgraded", upgraded);
return true;
} catch(...) {
}
return false;
}
void DeviceCurrentInfoList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "devices",devices);
}
bool DeviceCurrentInfoList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "devices",devices);
return true;
} catch(...) {
}
return false;
}
}
} // namespace OpenWifi::FMSObjects

View File

@@ -11,149 +11,149 @@
namespace OpenWifi::FMSObjects {
struct Firmware {
std::string id;
std::string release;
std::string deviceType;
std::string description;
std::string revision;
std::string uri;
std::string image;
uint64_t imageDate=0;
uint64_t size=0;
uint64_t downloadCount=0;
std::string firmwareHash;
std::string owner;
std::string location;
std::string uploader;
std::string digest;
bool latest=false;
SecurityObjects::NoteInfoVec notes;
uint64_t created=0;
struct Firmware {
std::string id;
std::string release;
std::string deviceType;
std::string description;
std::string revision;
std::string uri;
std::string image;
uint64_t imageDate = 0;
uint64_t size = 0;
uint64_t downloadCount = 0;
std::string firmwareHash;
std::string owner;
std::string location;
std::string uploader;
std::string digest;
bool latest = false;
SecurityObjects::NoteInfoVec notes;
uint64_t created = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<Firmware> FirmwareVec;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<Firmware> FirmwareVec;
struct FirmwareList {
FirmwareVec firmwares;
struct FirmwareList {
FirmwareVec firmwares;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceType {
std::string id;
std::string deviceType;
std::string manufacturer;
std::string model;
std::string policy;
SecurityObjects::NoteInfoVec notes;
uint64_t lastUpdate=0;
uint64_t created=0;
struct DeviceType {
std::string id;
std::string deviceType;
std::string manufacturer;
std::string model;
std::string policy;
SecurityObjects::NoteInfoVec notes;
uint64_t lastUpdate = 0;
uint64_t created = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<DeviceType> DeviceTypeVec;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<DeviceType> DeviceTypeVec;
struct DeviceTypeList {
DeviceTypeVec deviceTypes;
struct DeviceTypeList {
DeviceTypeVec deviceTypes;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RevisionHistoryEntry {
std::string id;
std::string serialNumber;
std::string fromRelease;
std::string toRelease;
std::string commandUUID;
std::string revisionId;
uint64_t upgraded;
struct RevisionHistoryEntry {
std::string id;
std::string serialNumber;
std::string fromRelease;
std::string toRelease;
std::string commandUUID;
std::string revisionId;
uint64_t upgraded;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<RevisionHistoryEntry> RevisionHistoryEntryVec;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<RevisionHistoryEntry> RevisionHistoryEntryVec;
struct RevisionHistoryEntryList {
RevisionHistoryEntryVec history;
struct RevisionHistoryEntryList {
RevisionHistoryEntryVec history;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct FirmwareAgeDetails {
std::string latestId;
std::string image;
uint64_t imageDate;
std::string revision;
std::string uri;
uint64_t age=0;
bool latest=true;
struct FirmwareAgeDetails {
std::string latestId;
std::string image;
uint64_t imageDate;
std::string revision;
std::string uri;
uint64_t age = 0;
bool latest = true;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceConnectionInformation {
std::string serialNumber;
std::string revision;
std::string deviceType;
std::string endPoint;
uint64_t lastUpdate;
std::string status;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceConnectionInformation {
std::string serialNumber;
std::string revision;
std::string deviceType;
std::string endPoint;
uint64_t lastUpdate;
std::string status;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceReport {
uint64_t snapshot=0;
uint64_t numberOfDevices=0;
Types::CountedMap OUI_;
Types::CountedMap Revisions_;
Types::CountedMap DeviceTypes_;
Types::CountedMap Status_;
Types::CountedMap EndPoints_;
Types::CountedMap UsingLatest_;
Types::CountedMap UnknownFirmwares_;
Types::CountedMap totalSecondsOld_;
void to_json(Poco::JSON::Object &Obj) const;
void reset();
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceReport {
uint64_t snapshot = 0;
uint64_t numberOfDevices = 0;
Types::CountedMap OUI_;
Types::CountedMap Revisions_;
Types::CountedMap DeviceTypes_;
Types::CountedMap Status_;
Types::CountedMap EndPoints_;
Types::CountedMap UsingLatest_;
Types::CountedMap UnknownFirmwares_;
Types::CountedMap totalSecondsOld_;
void to_json(Poco::JSON::Object &Obj) const;
void reset();
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceInformation {
std::string serialNumber;
RevisionHistoryEntryList history;
std::string currentFirmware;
uint64_t currentFirmwareDate=0;
std::string latestFirmware;
uint64_t latestFirmwareDate=0;
bool latestFirmwareAvailable;
std::string latestFirmwareURI;
struct DeviceInformation {
std::string serialNumber;
RevisionHistoryEntryList history;
std::string currentFirmware;
uint64_t currentFirmwareDate = 0;
std::string latestFirmware;
uint64_t latestFirmwareDate = 0;
bool latestFirmwareAvailable;
std::string latestFirmwareURI;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceCurrentInfo {
std::string serialNumber;
std::string revision;
uint64_t upgraded=0;
struct DeviceCurrentInfo {
std::string serialNumber;
std::string revision;
uint64_t upgraded = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceCurrentInfoList {
std::vector<DeviceCurrentInfo> devices;
struct DeviceCurrentInfoList {
std::vector<DeviceCurrentInfo> devices;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
}
} // namespace OpenWifi::FMSObjects

View File

@@ -10,50 +10,55 @@
#include "Poco/JSON/Stringifier.h"
#include "Daemon.h"
#ifdef TIP_GATEWAY_SERVICE
#ifdef TIP_GATEWAY_SERVICE
#include "AP_WS_Server.h"
#include "CapabilitiesCache.h"
#include "RADIUSSessionTracker.h"
#endif
#include "RESTAPI_GWobjects.h"
#include "framework/RESTAPI_utils.h"
#include "framework/utils.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::EmbedDocument;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::field_to_json;
namespace OpenWifi::GWObjects {
void Device::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"serialNumber", SerialNumber);
field_to_json(Obj, "serialNumber", SerialNumber);
#ifdef TIP_GATEWAY_SERVICE
field_to_json(Obj,"deviceType", CapabilitiesCache::instance()->GetPlatform(Compatible));
field_to_json(Obj, "deviceType", CapabilitiesCache::instance()->GetPlatform(Compatible));
field_to_json(Obj, "hasRADIUSSessions", RADIUSSessionTracker()->HasSessions(SerialNumber));
#endif
field_to_json(Obj,"macAddress", MACAddress);
field_to_json(Obj,"manufacturer", Manufacturer);
field_to_json(Obj,"UUID", UUID);
field_to_json(Obj, "macAddress", MACAddress);
field_to_json(Obj, "manufacturer", Manufacturer);
field_to_json(Obj, "UUID", UUID);
EmbedDocument("configuration", Obj, Configuration);
field_to_json(Obj,"notes", Notes);
field_to_json(Obj,"createdTimestamp", CreationTimestamp);
field_to_json(Obj,"lastConfigurationChange", LastConfigurationChange);
field_to_json(Obj,"lastConfigurationDownload", LastConfigurationDownload);
field_to_json(Obj,"lastFWUpdate", LastFWUpdate);
field_to_json(Obj,"owner", Owner);
field_to_json(Obj,"location", Location);
field_to_json(Obj,"venue", Venue);
field_to_json(Obj,"firmware", Firmware);
field_to_json(Obj,"compatible", Compatible);
field_to_json(Obj,"fwUpdatePolicy", FWUpdatePolicy);
field_to_json(Obj,"devicePassword", DevicePassword);
field_to_json(Obj,"subscriber", subscriber);
field_to_json(Obj,"entity", entity);
field_to_json(Obj,"modified", modified);
field_to_json(Obj,"locale", locale);
field_to_json(Obj,"restrictedDevice", restrictedDevice);
field_to_json(Obj,"pendingConfiguration", pendingConfiguration);
field_to_json(Obj,"pendingConfigurationCmd", pendingConfigurationCmd);
field_to_json(Obj,"restrictionDetails", restrictionDetails);
field_to_json(Obj, "notes", Notes);
field_to_json(Obj, "createdTimestamp", CreationTimestamp);
field_to_json(Obj, "lastConfigurationChange", LastConfigurationChange);
field_to_json(Obj, "lastConfigurationDownload", LastConfigurationDownload);
field_to_json(Obj, "lastFWUpdate", LastFWUpdate);
field_to_json(Obj, "owner", Owner);
field_to_json(Obj, "location", Location);
field_to_json(Obj, "venue", Venue);
field_to_json(Obj, "firmware", Firmware);
field_to_json(Obj, "compatible", Compatible);
field_to_json(Obj, "fwUpdatePolicy", FWUpdatePolicy);
field_to_json(Obj, "devicePassword", DevicePassword);
field_to_json(Obj, "subscriber", subscriber);
field_to_json(Obj, "entity", entity);
field_to_json(Obj, "modified", modified);
field_to_json(Obj, "locale", locale);
field_to_json(Obj, "restrictedDevice", restrictedDevice);
field_to_json(Obj, "pendingConfiguration", pendingConfiguration);
field_to_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd);
field_to_json(Obj, "restrictionDetails", restrictionDetails);
field_to_json(Obj, "pendingUUID", pendingUUID);
field_to_json(Obj, "simulated", simulated);
field_to_json(Obj, "lastRecordedContact", lastRecordedContact);
}
void Device::to_json_with_status(Poco::JSON::Object &Obj) const {
@@ -63,41 +68,60 @@ namespace OpenWifi::GWObjects {
ConnectionState ConState;
if (AP_WS_Server()->GetState(SerialNumber, ConState)) {
ConState.to_json(Obj);
ConState.to_json(SerialNumber,Obj);
} else {
field_to_json(Obj,"ipAddress", "");
field_to_json(Obj,"txBytes", (uint64_t) 0);
field_to_json(Obj,"rxBytes", (uint64_t )0);
field_to_json(Obj,"messageCount", (uint64_t )0);
field_to_json(Obj,"connected", false);
field_to_json(Obj,"lastContact", "");
field_to_json(Obj,"verifiedCertificate", "NO_CERTIFICATE");
field_to_json(Obj,"associations_2G", (uint64_t) 0);
field_to_json(Obj,"associations_5G", (uint64_t) 0);
field_to_json(Obj,"associations_6G", (uint64_t) 0);
field_to_json(Obj, "ipAddress", "");
field_to_json(Obj, "txBytes", (uint64_t)0);
field_to_json(Obj, "rxBytes", (uint64_t)0);
field_to_json(Obj, "messageCount", (uint64_t)0);
field_to_json(Obj, "connected", false);
field_to_json(Obj, "lastContact", "");
field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE");
field_to_json(Obj, "associations_2G", (uint64_t)0);
field_to_json(Obj, "associations_5G", (uint64_t)0);
field_to_json(Obj, "associations_6G", (uint64_t)0);
field_to_json(Obj, "hasRADIUSSessions", false);
field_to_json(Obj, "hasGPS", ConState.hasGPS);
field_to_json(Obj, "sanity", ConState.sanity);
field_to_json(Obj, "memoryUsed", ConState.memoryUsed);
field_to_json(Obj, "sanity", ConState.sanity);
field_to_json(Obj, "load", ConState.load);
field_to_json(Obj, "temperature", ConState.temperature);
}
#endif
}
bool Device::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"serialNumber",SerialNumber);
field_from_json(Obj,"deviceType",DeviceType);
field_from_json(Obj,"macAddress",MACAddress);
field_from_json(Obj,"configuration",Configuration);
field_from_json(Obj,"notes",Notes);
field_from_json(Obj,"manufacturer",Manufacturer);
field_from_json(Obj,"owner",Owner);
field_from_json(Obj,"location",Location);
field_from_json(Obj,"venue",Venue);
field_from_json(Obj,"compatible",Compatible);
field_from_json(Obj,"subscriber", subscriber);
field_from_json(Obj,"entity", entity);
field_from_json(Obj,"locale", locale);
field_from_json(Obj,"restrictedDevice", restrictedDevice);
field_from_json(Obj,"pendingConfiguration", pendingConfiguration);
field_from_json(Obj,"pendingConfigurationCmd", pendingConfigurationCmd);
field_from_json(Obj,"restrictionDetails", restrictionDetails);
field_from_json(Obj, "serialNumber", SerialNumber);
field_from_json(Obj, "deviceType", DeviceType);
field_from_json(Obj, "macAddress", MACAddress);
field_from_json(Obj, "manufacturer", Manufacturer);
field_from_json(Obj, "UUID", UUID);
field_from_json(Obj, "configuration", Configuration);
field_from_json(Obj, "notes", Notes);
field_from_json(Obj, "createdTimestamp", CreationTimestamp);
field_from_json(Obj, "lastConfigurationChange", LastConfigurationChange);
field_from_json(Obj, "lastConfigurationDownload", LastConfigurationDownload);
field_from_json(Obj, "lastFWUpdate", LastFWUpdate);
field_from_json(Obj, "owner", Owner);
field_from_json(Obj, "location", Location);
field_from_json(Obj, "venue", Venue);
field_from_json(Obj, "firmware", Firmware);
field_from_json(Obj, "compatible", Compatible);
field_from_json(Obj, "fwUpdatePolicy", FWUpdatePolicy);
field_from_json(Obj, "devicePassword", DevicePassword);
field_from_json(Obj, "subscriber", subscriber);
field_from_json(Obj, "entity", entity);
field_from_json(Obj, "modified", modified);
field_from_json(Obj, "locale", locale);
field_from_json(Obj, "restrictedDevice", restrictedDevice);
field_from_json(Obj, "pendingConfiguration", pendingConfiguration);
field_from_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd);
field_from_json(Obj, "restrictionDetails", restrictionDetails);
field_from_json(Obj, "pendingUUID", pendingUUID);
field_from_json(Obj, "simulated", simulated);
field_from_json(Obj, "lastRecordedContact", lastRecordedContact);
return true;
} catch (const Poco::Exception &E) {
}
@@ -105,73 +129,76 @@ namespace OpenWifi::GWObjects {
}
void Device::Print() const {
std::cout << "Device: " << SerialNumber << " DeviceType:" << DeviceType << " MACAddress:" << MACAddress << " Manufacturer:"
<< Manufacturer << " " << Configuration << std::endl;
std::cout << "Device: " << SerialNumber << " DeviceType:" << DeviceType
<< " MACAddress:" << MACAddress << " Manufacturer:" << Manufacturer << " "
<< Configuration << std::endl;
}
void Statistics::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("data", Obj, Data);
field_to_json(Obj,"UUID", UUID);
field_to_json(Obj,"recorded", Recorded);
field_to_json(Obj, "UUID", UUID);
field_to_json(Obj, "recorded", Recorded);
}
void Capabilities::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("capabilities", Obj, Capabilities);
field_to_json(Obj,"firstUpdate", FirstUpdate);
field_to_json(Obj,"lastUpdate", LastUpdate);
field_to_json(Obj, "firstUpdate", FirstUpdate);
field_to_json(Obj, "lastUpdate", LastUpdate);
}
void DeviceLog::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("data", Obj, Data);
field_to_json(Obj,"log", Log);
field_to_json(Obj,"severity", Severity);
field_to_json(Obj,"recorded", Recorded);
field_to_json(Obj,"logType", LogType);
field_to_json(Obj,"UUID", UUID);
field_to_json(Obj, "log", Log);
field_to_json(Obj, "severity", Severity);
field_to_json(Obj, "recorded", Recorded);
field_to_json(Obj, "logType", LogType);
field_to_json(Obj, "UUID", UUID);
}
void HealthCheck::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("values", Obj, Data);
field_to_json(Obj,"UUID", UUID);
field_to_json(Obj,"sanity", Sanity);
field_to_json(Obj,"recorded", Recorded);
field_to_json(Obj, "UUID", UUID);
field_to_json(Obj, "sanity", Sanity);
field_to_json(Obj, "recorded", Recorded);
}
void DefaultConfiguration::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("configuration", Obj, Configuration);
field_to_json(Obj,"name", Name);
field_to_json(Obj,"modelIds", Models);
field_to_json(Obj,"description", Description);
field_to_json(Obj,"created", Created);
field_to_json(Obj,"lastModified", LastModified);
field_to_json(Obj, "name", Name);
field_to_json(Obj, "modelIds", Models);
field_to_json(Obj, "description", Description);
field_to_json(Obj, "created", Created);
field_to_json(Obj, "lastModified", LastModified);
}
void CommandDetails::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("details", Obj, Details);
EmbedDocument("results", Obj, Results);
field_to_json(Obj,"UUID", UUID);
field_to_json(Obj,"serialNumber", SerialNumber);
field_to_json(Obj,"command", Command);
field_to_json(Obj,"errorText", ErrorText);
field_to_json(Obj,"submittedBy", SubmittedBy);
field_to_json(Obj,"status", Status);
field_to_json(Obj,"submitted", Submitted);
field_to_json(Obj,"executed", Executed);
field_to_json(Obj,"completed", Completed);
field_to_json(Obj,"when", RunAt);
field_to_json(Obj,"errorCode", ErrorCode);
field_to_json(Obj,"custom", Custom);
field_to_json(Obj,"waitingForFile", WaitingForFile);
field_to_json(Obj,"attachFile", AttachDate);
field_to_json(Obj,"executionTime", executionTime);
field_to_json(Obj, "UUID", UUID);
field_to_json(Obj, "serialNumber", SerialNumber);
field_to_json(Obj, "command", Command);
field_to_json(Obj, "errorText", ErrorText);
field_to_json(Obj, "submittedBy", SubmittedBy);
field_to_json(Obj, "status", Status);
field_to_json(Obj, "submitted", Submitted);
field_to_json(Obj, "executed", Executed);
field_to_json(Obj, "completed", Completed);
field_to_json(Obj, "when", RunAt);
field_to_json(Obj, "errorCode", ErrorCode);
field_to_json(Obj, "custom", Custom);
field_to_json(Obj, "waitingForFile", WaitingForFile);
field_to_json(Obj, "attachFile", AttachDate);
field_to_json(Obj, "executionTime", executionTime);
field_to_json(Obj, "lastTry", lastTry);
field_to_json(Obj, "deferred", deferred);
}
bool DefaultConfiguration::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"name",Name);
field_from_json(Obj,"configuration",Configuration);
field_from_json(Obj,"modelIds",Models);
field_from_json(Obj,"description",Description);
field_from_json(Obj, "name", Name);
field_from_json(Obj, "configuration", Configuration);
field_from_json(Obj, "modelIds", Models);
field_from_json(Obj, "description", Description);
return true;
} catch (const Poco::Exception &E) {
}
@@ -179,72 +206,96 @@ namespace OpenWifi::GWObjects {
}
void BlackListedDevice::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"serialNumber", serialNumber);
field_to_json(Obj,"author", author);
field_to_json(Obj,"reason", reason);
field_to_json(Obj,"created", created);
field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "author", author);
field_to_json(Obj, "reason", reason);
field_to_json(Obj, "created", created);
}
bool BlackListedDevice::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"serialNumber",serialNumber);
field_from_json(Obj,"author",author);
field_from_json(Obj,"reason",reason);
field_from_json(Obj,"created",created);
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "author", author);
field_from_json(Obj, "reason", reason);
field_from_json(Obj, "created", created);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
void ConnectionState::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"ipAddress", Address);
field_to_json(Obj,"txBytes", TX);
field_to_json(Obj,"rxBytes", RX);
field_to_json(Obj,"messageCount", MessageCount);
field_to_json(Obj,"UUID", UUID);
field_to_json(Obj,"connected", Connected);
field_to_json(Obj,"firmware", Firmware);
field_to_json(Obj,"lastContact", LastContact);
field_to_json(Obj,"associations_2G", Associations_2G);
field_to_json(Obj,"associations_5G", Associations_5G);
field_to_json(Obj,"associations_6G", Associations_6G);
field_to_json(Obj,"webSocketClients", webSocketClients);
field_to_json(Obj,"websocketPackets", websocketPackets);
field_to_json(Obj,"kafkaClients", kafkaClients);
field_to_json(Obj,"kafkaPackets", kafkaPackets);
field_to_json(Obj,"locale", locale);
field_to_json(Obj,"started", started);
field_to_json(Obj,"sessionId", sessionId);
field_to_json(Obj,"connectionCompletionTime", connectionCompletionTime);
field_to_json(Obj,"totalConnectionTime", Utils::Now() - started);
field_to_json(Obj,"certificateExpiryDate", certificateExpiryDate);
void ConnectionState::to_json([[maybe_unused]] const std::string &SerialNumber, Poco::JSON::Object &Obj) {
field_to_json(Obj, "ipAddress", Address);
field_to_json(Obj, "txBytes", TX);
field_to_json(Obj, "rxBytes", RX);
field_to_json(Obj, "messageCount", MessageCount);
field_to_json(Obj, "UUID", UUID);
field_to_json(Obj, "connected", Connected);
field_to_json(Obj, "firmware", Firmware);
field_to_json(Obj, "lastContact", LastContact);
field_to_json(Obj, "associations_2G", Associations_2G);
field_to_json(Obj, "associations_5G", Associations_5G);
field_to_json(Obj, "associations_6G", Associations_6G);
field_to_json(Obj, "webSocketClients", webSocketClients);
field_to_json(Obj, "websocketPackets", websocketPackets);
field_to_json(Obj, "kafkaClients", kafkaClients);
field_to_json(Obj, "kafkaPackets", kafkaPackets);
field_to_json(Obj, "locale", locale);
field_to_json(Obj, "started", started);
field_to_json(Obj, "sessionId", sessionId);
field_to_json(Obj, "connectionCompletionTime", connectionCompletionTime);
field_to_json(Obj, "totalConnectionTime", Utils::Now() - started);
field_to_json(Obj, "certificateExpiryDate", certificateExpiryDate);
field_to_json(Obj, "connectReason", connectReason);
switch(VerifiedCertificate) {
case NO_CERTIFICATE:
field_to_json(Obj,"verifiedCertificate", "NO_CERTIFICATE"); break;
case VALID_CERTIFICATE:
field_to_json(Obj,"verifiedCertificate", "VALID_CERTIFICATE"); break;
case MISMATCH_SERIAL:
field_to_json(Obj,"verifiedCertificate", "MISMATCH_SERIAL"); break;
case VERIFIED:
field_to_json(Obj,"verifiedCertificate", "VERIFIED"); break;
default:
field_to_json(Obj,"verifiedCertificate", "NO_CERTIFICATE"); break;
#ifdef TIP_GATEWAY_SERVICE
hasRADIUSSessions = RADIUSSessionTracker()->HasSessions(SerialNumber);
AP_WS_Server()->ExtendedAttributes(SerialNumber, hasGPS, sanity,
memoryUsed,
load,
temperature);
#endif
field_to_json(Obj, "hasRADIUSSessions", hasRADIUSSessions );
field_to_json(Obj, "hasGPS", hasGPS);
field_to_json(Obj, "sanity", sanity);
field_to_json(Obj, "memoryUsed", memoryUsed);
field_to_json(Obj, "sanity", sanity);
field_to_json(Obj, "load", load);
field_to_json(Obj, "temperature", temperature);
switch (VerifiedCertificate) {
case NO_CERTIFICATE:
field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE");
break;
case VALID_CERTIFICATE:
field_to_json(Obj, "verifiedCertificate", "VALID_CERTIFICATE");
break;
case MISMATCH_SERIAL:
field_to_json(Obj, "verifiedCertificate", "MISMATCH_SERIAL");
break;
case VERIFIED:
field_to_json(Obj, "verifiedCertificate", "VERIFIED");
break;
case SIMULATED:
field_to_json(Obj, "verifiedCertificate", "SIMULATED");
break;
default:
field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE");
break;
}
}
void DeviceConnectionStatistics::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"averageConnectionTime", averageConnectionTime);
field_to_json(Obj,"connectedDevices", connectedDevices );
field_to_json(Obj,"connectingDevices", connectingDevices );
field_to_json(Obj, "averageConnectionTime", averageConnectionTime);
field_to_json(Obj, "connectedDevices", connectedDevices);
field_to_json(Obj, "connectingDevices", connectingDevices);
}
bool DeviceConnectionStatistics::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"averageConnectionTime", averageConnectionTime);
field_from_json(Obj,"connectedDevices", connectedDevices );
field_from_json(Obj,"connectingDevices", connectingDevices );
field_from_json(Obj, "averageConnectionTime", averageConnectionTime);
field_from_json(Obj, "connectedDevices", connectedDevices);
field_from_json(Obj, "connectingDevices", connectingDevices);
return true;
} catch (const Poco::Exception &E) {
}
@@ -252,37 +303,37 @@ namespace OpenWifi::GWObjects {
}
void RttySessionDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"serialNumber", SerialNumber);
field_to_json(Obj,"server", Server);
field_to_json(Obj,"port", Port);
field_to_json(Obj,"token",Token);
field_to_json(Obj,"timeout", TimeOut);
field_to_json(Obj,"connectionId",ConnectionId);
field_to_json(Obj,"commandUUID",CommandUUID);
field_to_json(Obj,"started", Started);
field_to_json(Obj,"viewport",ViewPort);
field_to_json(Obj,"password",DevicePassword);
field_to_json(Obj, "serialNumber", SerialNumber);
field_to_json(Obj, "server", Server);
field_to_json(Obj, "port", Port);
field_to_json(Obj, "token", Token);
field_to_json(Obj, "timeout", TimeOut);
field_to_json(Obj, "connectionId", ConnectionId);
field_to_json(Obj, "commandUUID", CommandUUID);
field_to_json(Obj, "started", Started);
field_to_json(Obj, "viewport", ViewPort);
field_to_json(Obj, "password", DevicePassword);
}
void Dashboard::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"commands",commands);
field_to_json(Obj,"upTimes",upTimes);
field_to_json(Obj,"memoryUsed",memoryUsed);
field_to_json(Obj,"load1",load1);
field_to_json(Obj,"load5",load5);
field_to_json(Obj,"load15",load15);
field_to_json(Obj,"vendors",vendors);
field_to_json(Obj,"status",status);
field_to_json(Obj,"deviceType",deviceType);
field_to_json(Obj,"healths",healths);
field_to_json(Obj,"certificates",certificates);
field_to_json(Obj,"lastContact",lastContact);
field_to_json(Obj,"associations",associations);
field_to_json(Obj,"snapshot",snapshot);
field_to_json(Obj,"numberOfDevices",numberOfDevices);
field_to_json(Obj, "commands", commands);
field_to_json(Obj, "upTimes", upTimes);
field_to_json(Obj, "memoryUsed", memoryUsed);
field_to_json(Obj, "load1", load1);
field_to_json(Obj, "load5", load5);
field_to_json(Obj, "load15", load15);
field_to_json(Obj, "vendors", vendors);
field_to_json(Obj, "status", status);
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "healths", healths);
field_to_json(Obj, "certificates", certificates);
field_to_json(Obj, "lastContact", lastContact);
field_to_json(Obj, "associations", associations);
field_to_json(Obj, "snapshot", snapshot);
field_to_json(Obj, "numberOfDevices", numberOfDevices);
}
void Dashboard::reset() {
void Dashboard::reset() {
commands.clear();
upTimes.clear();
memoryUsed.clear();
@@ -296,38 +347,38 @@ namespace OpenWifi::GWObjects {
certificates.clear();
lastContact.clear();
associations.clear();
numberOfDevices = 0 ;
numberOfDevices = 0;
snapshot = Utils::Now();
}
void CapabilitiesModel::to_json(Poco::JSON::Object &Obj) const{
field_to_json(Obj,"deviceType", deviceType);
field_to_json(Obj,"capabilities", capabilities);
void CapabilitiesModel::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "capabilities", capabilities);
};
void ScriptRequest::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"serialNumber",serialNumber);
field_to_json(Obj,"timeout",timeout);
field_to_json(Obj,"type",type);
field_to_json(Obj,"scriptId",scriptId);
field_to_json(Obj,"script",script);
field_to_json(Obj,"when",when);
field_to_json(Obj,"signature", signature);
field_to_json(Obj,"deferred", deferred);
field_to_json(Obj,"uri", uri);
field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "timeout", timeout);
field_to_json(Obj, "type", type);
field_to_json(Obj, "scriptId", scriptId);
field_to_json(Obj, "script", script);
field_to_json(Obj, "when", when);
field_to_json(Obj, "signature", signature);
field_to_json(Obj, "deferred", deferred);
field_to_json(Obj, "uri", uri);
}
bool ScriptRequest::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"serialNumber",serialNumber);
field_from_json(Obj,"timeout",timeout);
field_from_json(Obj,"type",type);
field_from_json(Obj,"script",script);
field_from_json(Obj,"scriptId",scriptId);
field_from_json(Obj,"when",when);
field_from_json(Obj,"signature", signature);
field_from_json(Obj,"deferred", deferred);
field_from_json(Obj,"uri", uri);
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "timeout", timeout);
field_from_json(Obj, "type", type);
field_from_json(Obj, "script", script);
field_from_json(Obj, "scriptId", scriptId);
field_from_json(Obj, "when", when);
field_from_json(Obj, "signature", signature);
field_from_json(Obj, "deferred", deferred);
field_from_json(Obj, "uri", uri);
return true;
} catch (const Poco::Exception &E) {
}
@@ -335,12 +386,12 @@ namespace OpenWifi::GWObjects {
}
void RadiusProxyPoolList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"pools",pools);
field_to_json(Obj, "pools", pools);
}
bool RadiusProxyPoolList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"pools",pools);
field_from_json(Obj, "pools", pools);
return true;
} catch (const Poco::Exception &E) {
}
@@ -348,22 +399,22 @@ namespace OpenWifi::GWObjects {
}
void RadiusProxyPool::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"name",name);
field_to_json(Obj,"description",description);
field_to_json(Obj,"authConfig",authConfig);
field_to_json(Obj,"acctConfig",acctConfig);
field_to_json(Obj,"coaConfig",coaConfig);
field_to_json(Obj,"useByDefault",useByDefault);
field_to_json(Obj, "name", name);
field_to_json(Obj, "description", description);
field_to_json(Obj, "authConfig", authConfig);
field_to_json(Obj, "acctConfig", acctConfig);
field_to_json(Obj, "coaConfig", coaConfig);
field_to_json(Obj, "useByDefault", useByDefault);
}
bool RadiusProxyPool::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"name",name);
field_from_json(Obj,"description",description);
field_from_json(Obj,"authConfig",authConfig);
field_from_json(Obj,"acctConfig",acctConfig);
field_from_json(Obj,"coaConfig",coaConfig);
field_from_json(Obj,"useByDefault",useByDefault);
field_from_json(Obj, "name", name);
field_from_json(Obj, "description", description);
field_from_json(Obj, "authConfig", authConfig);
field_from_json(Obj, "acctConfig", acctConfig);
field_from_json(Obj, "coaConfig", coaConfig);
field_from_json(Obj, "useByDefault", useByDefault);
return true;
} catch (const Poco::Exception &E) {
}
@@ -371,20 +422,20 @@ namespace OpenWifi::GWObjects {
}
void RadiusProxyServerConfig::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"strategy",strategy);
field_to_json(Obj,"monitor",monitor);
field_to_json(Obj,"monitorMethod",monitorMethod);
field_to_json(Obj,"methodParameters",methodParameters);
field_to_json(Obj,"servers",servers);
field_to_json(Obj, "strategy", strategy);
field_to_json(Obj, "monitor", monitor);
field_to_json(Obj, "monitorMethod", monitorMethod);
field_to_json(Obj, "methodParameters", methodParameters);
field_to_json(Obj, "servers", servers);
}
bool RadiusProxyServerConfig::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"strategy",strategy);
field_from_json(Obj,"monitor",monitor);
field_from_json(Obj,"monitorMethod",monitorMethod);
field_from_json(Obj,"methodParameters",methodParameters);
field_from_json(Obj,"servers",servers);
field_from_json(Obj, "strategy", strategy);
field_from_json(Obj, "monitor", monitor);
field_from_json(Obj, "monitorMethod", monitorMethod);
field_from_json(Obj, "methodParameters", methodParameters);
field_from_json(Obj, "servers", servers);
return true;
} catch (const Poco::Exception &E) {
}
@@ -392,40 +443,40 @@ namespace OpenWifi::GWObjects {
}
void RadiusProxyServerEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"name",name);
field_to_json(Obj,"ip",ip);
field_to_json(Obj,"port",port);
field_to_json(Obj,"weight",weight);
field_to_json(Obj,"secret",secret);
field_to_json(Obj,"certificate",certificate);
field_to_json(Obj,"radsec",radsec);
field_to_json(Obj,"allowSelfSigned",allowSelfSigned);
field_to_json(Obj,"radsecPort",radsecPort);
field_to_json(Obj,"radsecSecret",radsecSecret);
field_to_json(Obj,"radsecCacerts",radsecCacerts);
field_to_json(Obj,"radsecCert",radsecCert);
field_to_json(Obj,"radsecKey",radsecKey);
field_to_json(Obj,"radsecRealms",radsecRealms);
field_to_json(Obj,"ignore",ignore);
field_to_json(Obj, "name", name);
field_to_json(Obj, "ip", ip);
field_to_json(Obj, "port", port);
field_to_json(Obj, "weight", weight);
field_to_json(Obj, "secret", secret);
field_to_json(Obj, "certificate", certificate);
field_to_json(Obj, "radsec", radsec);
field_to_json(Obj, "allowSelfSigned", allowSelfSigned);
field_to_json(Obj, "radsecPort", radsecPort);
field_to_json(Obj, "radsecSecret", radsecSecret);
field_to_json(Obj, "radsecCacerts", radsecCacerts);
field_to_json(Obj, "radsecCert", radsecCert);
field_to_json(Obj, "radsecKey", radsecKey);
field_to_json(Obj, "radsecRealms", radsecRealms);
field_to_json(Obj, "ignore", ignore);
}
bool RadiusProxyServerEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"name",name);
field_from_json(Obj,"ip",ip);
field_from_json(Obj,"port",port);
field_from_json(Obj,"weight",weight);
field_from_json(Obj,"secret",secret);
field_from_json(Obj,"certificate",certificate);
field_from_json(Obj,"radsec",radsec);
field_from_json(Obj,"allowSelfSigned",allowSelfSigned);
field_from_json(Obj,"radsecSecret",radsecSecret);
field_from_json(Obj,"radsecPort",radsecPort);
field_from_json(Obj,"radsecCacerts",radsecCacerts);
field_from_json(Obj,"radsecCert",radsecCert);
field_from_json(Obj,"radsecKey",radsecKey);
field_from_json(Obj,"radsecRealms",radsecRealms);
field_from_json(Obj,"ignore",ignore);
field_from_json(Obj, "name", name);
field_from_json(Obj, "ip", ip);
field_from_json(Obj, "port", port);
field_from_json(Obj, "weight", weight);
field_from_json(Obj, "secret", secret);
field_from_json(Obj, "certificate", certificate);
field_from_json(Obj, "radsec", radsec);
field_from_json(Obj, "allowSelfSigned", allowSelfSigned);
field_from_json(Obj, "radsecSecret", radsecSecret);
field_from_json(Obj, "radsecPort", radsecPort);
field_from_json(Obj, "radsecCacerts", radsecCacerts);
field_from_json(Obj, "radsecCert", radsecCert);
field_from_json(Obj, "radsecKey", radsecKey);
field_from_json(Obj, "radsecRealms", radsecRealms);
field_from_json(Obj, "ignore", ignore);
return true;
} catch (const Poco::Exception &E) {
}
@@ -433,38 +484,38 @@ namespace OpenWifi::GWObjects {
}
void ScriptEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id);
field_to_json(Obj,"name", name);
field_to_json(Obj,"description", description);
field_to_json(Obj,"uri", uri);
field_to_json(Obj,"content", content);
field_to_json(Obj,"version", version);
field_to_json(Obj,"type", type);
field_to_json(Obj,"created", created);
field_to_json(Obj,"modified", modified);
field_to_json(Obj,"author", author);
field_to_json(Obj,"restricted", restricted);
field_to_json(Obj,"deferred", deferred);
field_to_json(Obj,"timeout", timeout);
field_to_json(Obj,"defaultUploadURI", defaultUploadURI);
field_to_json(Obj, "id", id);
field_to_json(Obj, "name", name);
field_to_json(Obj, "description", description);
field_to_json(Obj, "uri", uri);
field_to_json(Obj, "content", content);
field_to_json(Obj, "version", version);
field_to_json(Obj, "type", type);
field_to_json(Obj, "created", created);
field_to_json(Obj, "modified", modified);
field_to_json(Obj, "author", author);
field_to_json(Obj, "restricted", restricted);
field_to_json(Obj, "deferred", deferred);
field_to_json(Obj, "timeout", timeout);
field_to_json(Obj, "defaultUploadURI", defaultUploadURI);
}
bool ScriptEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"id", id);
field_from_json(Obj,"name", name);
field_from_json(Obj,"description", description);
field_from_json(Obj,"uri", uri);
field_from_json(Obj,"content", content);
field_from_json(Obj,"version", version);
field_from_json(Obj,"type", type);
field_from_json(Obj,"created", created);
field_from_json(Obj,"modified", modified);
field_from_json(Obj,"author", author);
field_from_json(Obj,"restricted", restricted);
field_from_json(Obj,"deferred", deferred);
field_from_json(Obj,"timeout", timeout);
field_from_json(Obj,"defaultUploadURI", defaultUploadURI);
field_from_json(Obj, "id", id);
field_from_json(Obj, "name", name);
field_from_json(Obj, "description", description);
field_from_json(Obj, "uri", uri);
field_from_json(Obj, "content", content);
field_from_json(Obj, "version", version);
field_from_json(Obj, "type", type);
field_from_json(Obj, "created", created);
field_from_json(Obj, "modified", modified);
field_from_json(Obj, "author", author);
field_from_json(Obj, "restricted", restricted);
field_from_json(Obj, "deferred", deferred);
field_from_json(Obj, "timeout", timeout);
field_from_json(Obj, "defaultUploadURI", defaultUploadURI);
return true;
} catch (const Poco::Exception &E) {
}
@@ -472,76 +523,132 @@ namespace OpenWifi::GWObjects {
}
void ScriptEntryList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"scripts",scripts);
field_to_json(Obj, "scripts", scripts);
}
bool ScriptEntryList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"scripts",scripts);
field_from_json(Obj, "scripts", scripts);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
void RangeOptions::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "NO_IR", NO_IR);
field_to_json(Obj, "AUTO_BW", AUTO_BW);
field_to_json(Obj, "DFS", DFS);
field_to_json(Obj, "NO_OUTDOOR", NO_OUTDOOR);
field_to_json(Obj, "wmmrule_ETSI", wmmrule_ETSI);
field_to_json(Obj, "NO_OFDM", NO_OFDM);
}
void FrequencyRange::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "from", from);
field_to_json(Obj, "to", to);
field_to_json(Obj, "channelWidth", channelWidth);
field_to_json(Obj, "powerDb", powerDb);
field_to_json(Obj, "options", options);
}
void RegulatoryCountryInfo::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "country", country);
field_to_json(Obj, "domain", domain);
field_to_json(Obj, "ranges", ranges);
}
void DeviceRestrictionsKeyInfo::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"vendor", vendor);
field_to_json(Obj,"algo", algo);
field_to_json(Obj, "vendor", vendor);
field_to_json(Obj, "algo", algo);
}
bool DeviceRestrictionsKeyInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"vendor", vendor);
field_from_json(Obj,"algo", algo);
field_from_json(Obj, "vendor", vendor);
field_from_json(Obj, "algo", algo);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
void DeviceRestrictions::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"dfs", dfs);
field_to_json(Obj,"ssh", ssh);
field_to_json(Obj,"rtty", rtty);
field_to_json(Obj,"tty", tty);
field_to_json(Obj,"developer", developer);
field_to_json(Obj,"upgrade", upgrade);
field_to_json(Obj,"commands", commands);
field_to_json(Obj,"country", country);
field_to_json(Obj,"key_info", key_info);
field_to_json(Obj, "dfs", dfs);
field_to_json(Obj, "ssh", ssh);
field_to_json(Obj, "rtty", rtty);
field_to_json(Obj, "tty", tty);
field_to_json(Obj, "developer", developer);
field_to_json(Obj, "upgrade", upgrade);
field_to_json(Obj, "commands", commands);
field_to_json(Obj, "country", country);
field_to_json(Obj, "key_info", key_info);
}
bool DeviceRestrictions::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"dfs", dfs);
field_from_json(Obj,"ssh", ssh);
field_from_json(Obj,"rtty", rtty);
field_from_json(Obj,"tty", tty);
field_from_json(Obj,"developer", developer);
field_from_json(Obj,"upgrade", upgrade);
field_from_json(Obj,"commands", commands);
field_from_json(Obj,"country", country);
field_from_json(Obj,"key_info", key_info);
field_from_json(Obj, "dfs", dfs);
field_from_json(Obj, "ssh", ssh);
field_from_json(Obj, "rtty", rtty);
field_from_json(Obj, "tty", tty);
field_from_json(Obj, "developer", developer);
field_from_json(Obj, "upgrade", upgrade);
field_from_json(Obj, "commands", commands);
field_from_json(Obj, "country", country);
field_from_json(Obj, "key_info", key_info);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
bool DeviceRestrictionsKeyInfo::operator!=(const OpenWifi::GWObjects::DeviceRestrictionsKeyInfo &T) const {
return (T.algo!=algo) || (T.vendor!=vendor);
bool DeviceRestrictionsKeyInfo::operator!=(
const OpenWifi::GWObjects::DeviceRestrictionsKeyInfo &T) const {
return (T.algo != algo) || (T.vendor != vendor);
}
bool DeviceRestrictions::operator!=(const OpenWifi::GWObjects::DeviceRestrictions &T) const {
return ( (T.dfs!=dfs) ||
(T.rtty!=rtty) ||
(T.upgrade!=upgrade) ||
(T.commands != commands) ||
(T.developer != developer) ||
(T.ssh !=ssh) ||
(T.key_info != key_info) ||
(T.country != country) );
return ((T.dfs != dfs) || (T.rtty != rtty) || (T.upgrade != upgrade) ||
(T.commands != commands) || (T.developer != developer) || (T.ssh != ssh) ||
(T.key_info != key_info) || (T.country != country));
}
}
void RADIUSSession::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "started", started);
field_to_json(Obj, "lastTransaction", lastTransaction);
field_to_json(Obj, "destination", destination);
field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "userName", userName);
field_to_json(Obj, "accountingSessionId", accountingSessionId);
field_to_json(Obj, "accountingMultiSessionId", accountingMultiSessionId);
field_to_json(Obj, "inputPackets", inputPackets);
field_to_json(Obj, "outputPackets", outputPackets);
field_to_json(Obj, "inputOctets", inputOctets);
field_to_json(Obj, "outputOctets", outputOctets);
field_to_json(Obj, "inputGigaWords", inputGigaWords);
field_to_json(Obj, "outputGigaWords", outputGigaWords);
field_to_json(Obj, "sessionTime", sessionTime);
field_to_json(Obj, "callingStationId", callingStationId);
field_to_json(Obj, "chargeableUserIdentity", chargeableUserIdentity);
field_to_json(Obj, "interface", interface);
field_to_json(Obj, "secret", secret);
field_to_json(Obj, "nasId", nasId);
}
void RADIUSSessionList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "sessions", sessions);
}
bool RadiusCoADMParameters::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "accountingSessionId", accountingSessionId);
field_from_json(Obj, "accountingMultiSessionId", accountingMultiSessionId);
field_from_json(Obj, "callingStationId", callingStationId);
field_from_json(Obj, "chargeableUserIdentity", chargeableUserIdentity);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
} // namespace OpenWifi::GWObjects

View File

@@ -11,64 +11,70 @@
#include "Poco/JSON/Object.h"
#include "RESTAPI_SecurityObjects.h"
#ifdef TIP_GATEWAY_SERVICE
#include <RADIUS_helpers.h>
#endif
namespace OpenWifi::GWObjects {
enum CertificateValidation {
NO_CERTIFICATE,
VALID_CERTIFICATE,
MISMATCH_SERIAL,
VERIFIED
};
enum CertificateValidation { NO_CERTIFICATE, VALID_CERTIFICATE, MISMATCH_SERIAL, VERIFIED, SIMULATED };
struct ConnectionState {
uint64_t MessageCount = 0 ;
uint64_t MessageCount = 0;
std::string Address;
uint64_t UUID = 0 ;
uint64_t PendingUUID = 0 ;
uint64_t UUID = 0;
uint64_t PendingUUID = 0;
uint64_t TX = 0, RX = 0;
uint64_t Associations_2G=0;
uint64_t Associations_5G=0;
uint64_t Associations_6G=0;
uint64_t Associations_2G = 0;
uint64_t Associations_5G = 0;
uint64_t Associations_6G = 0;
bool Connected = false;
uint64_t LastContact=0;
uint64_t LastContact = 0;
std::string Firmware;
CertificateValidation VerifiedCertificate = NO_CERTIFICATE;
std::string Compatible;
uint64_t kafkaClients=0;
uint64_t webSocketClients=0;
uint64_t kafkaPackets=0;
uint64_t websocketPackets=0;
std::string locale;
uint64_t started=0;
uint64_t sessionId=0;
double connectionCompletionTime=0.0;
std::uint64_t certificateExpiryDate=0;
std::string Compatible;
uint64_t kafkaClients = 0;
uint64_t webSocketClients = 0;
uint64_t kafkaPackets = 0;
uint64_t websocketPackets = 0;
std::string locale;
uint64_t started = 0;
uint64_t sessionId = 0;
double connectionCompletionTime = 0.0;
std::uint64_t certificateExpiryDate = 0;
std::uint64_t hasRADIUSSessions = 0;
bool hasGPS = false;
std::uint64_t sanity=0;
std::double_t memoryUsed=0.0;
std::double_t load=0.0;
std::double_t temperature=0.0;
std::string connectReason;
void to_json(Poco::JSON::Object &Obj) const;
void to_json(const std::string &SerialNumber, Poco::JSON::Object &Obj) ;
};
struct DeviceRestrictionsKeyInfo {
std::string vendor;
std::string algo;
std::string vendor;
std::string algo;
bool operator !=(const DeviceRestrictionsKeyInfo &b) const;
bool operator!=(const DeviceRestrictionsKeyInfo &b) const;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceRestrictions {
bool dfs = false;
bool ssh = false;
bool rtty = false;
bool tty = false;
bool developer = false;
bool upgrade = false;
bool commands = false;
std::vector<std::string> country;
DeviceRestrictionsKeyInfo key_info;
bool dfs = false;
bool ssh = false;
bool rtty = false;
bool tty = false;
bool developer = false;
bool upgrade = false;
bool commands = false;
std::vector<std::string> country;
DeviceRestrictionsKeyInfo key_info;
bool operator !=(const DeviceRestrictions &D) const;
bool operator!=(const DeviceRestrictions &D) const;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
@@ -80,27 +86,30 @@ namespace OpenWifi::GWObjects {
std::string MACAddress;
std::string Manufacturer;
std::string Configuration;
SecurityObjects::NoteInfoVec Notes;
SecurityObjects::NoteInfoVec Notes;
std::string Owner;
std::string Location;
std::string Firmware;
std::string Compatible;
std::string FWUpdatePolicy;
uint64_t UUID = 0 ;
uint64_t CreationTimestamp = 0 ;
uint64_t LastConfigurationChange = 0 ;
uint64_t LastConfigurationDownload = 0 ;
uint64_t LastFWUpdate = 0 ;
uint64_t UUID = 0;
uint64_t CreationTimestamp = 0;
uint64_t LastConfigurationChange = 0;
uint64_t LastConfigurationDownload = 0;
uint64_t LastFWUpdate = 0;
std::string Venue;
std::string DevicePassword;
std::string subscriber;
std::string entity;
uint64_t modified=0;
uint64_t modified = 0;
std::string locale;
bool restrictedDevice=false;
bool restrictedDevice = false;
std::string pendingConfiguration;
std::string pendingConfigurationCmd;
DeviceRestrictions restrictionDetails;
DeviceRestrictions restrictionDetails;
std::uint64_t pendingUUID = 0;
bool simulated=false;
std::uint64_t lastRecordedContact=0;
void to_json(Poco::JSON::Object &Obj) const;
void to_json_with_status(Poco::JSON::Object &Obj) const;
@@ -119,26 +128,26 @@ namespace OpenWifi::GWObjects {
struct Statistics {
std::string SerialNumber;
uint64_t UUID = 0 ;
uint64_t UUID = 0;
std::string Data;
uint64_t Recorded = 0;
uint64_t Recorded = 0;
void to_json(Poco::JSON::Object &Obj) const;
};
struct HealthCheck {
std::string SerialNumber;
uint64_t UUID = 0 ;
uint64_t UUID = 0;
std::string Data;
uint64_t Recorded = 0 ;
uint64_t Sanity = 0 ;
uint64_t Recorded = 0;
uint64_t Sanity = 0;
void to_json(Poco::JSON::Object &Obj) const;
};
struct Capabilities {
std::string Capabilities;
uint64_t FirstUpdate = 0 ;
uint64_t LastUpdate = 0 ;
void to_json(Poco::JSON::Object &Obj) const;
uint64_t FirstUpdate = 0;
uint64_t LastUpdate = 0;
void to_json(Poco::JSON::Object &Obj) const;
};
struct DeviceLog {
@@ -155,11 +164,11 @@ namespace OpenWifi::GWObjects {
std::string SerialNumber;
std::string Log;
std::string Data;
uint64_t Severity = 0 ;
uint64_t Recorded = 0 ;
uint64_t LogType = 0 ;
uint64_t UUID = 0 ;
void to_json(Poco::JSON::Object &Obj) const;
uint64_t Severity = 0;
uint64_t Recorded = 0;
uint64_t LogType = 0;
uint64_t UUID = 0;
void to_json(Poco::JSON::Object &Obj) const;
};
struct DefaultConfiguration {
@@ -167,10 +176,10 @@ namespace OpenWifi::GWObjects {
std::string Configuration;
Types::StringVec Models;
std::string Description;
uint64_t Created;
uint64_t LastModified;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
uint64_t Created;
uint64_t LastModified;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct CommandDetails {
@@ -184,16 +193,20 @@ namespace OpenWifi::GWObjects {
std::string ErrorText;
uint64_t Submitted = time(nullptr);
uint64_t Executed = 0;
uint64_t Completed = 0 ;
uint64_t RunAt = 0 ;
uint64_t ErrorCode = 0 ;
uint64_t Custom = 0 ;
uint64_t WaitingForFile = 0 ;
uint64_t AttachDate = 0 ;
uint64_t AttachSize = 0 ;
uint64_t Completed = 0;
uint64_t RunAt = 0;
uint64_t ErrorCode = 0;
uint64_t Custom = 0;
uint64_t WaitingForFile = 0;
uint64_t AttachDate = 0;
uint64_t AttachSize = 0;
std::string AttachType;
double executionTime = 0.0;
double executionTime = 0.0;
std::uint64_t lastTry = 0;
bool deferred = false;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct BlackListedDevice {
@@ -208,20 +221,20 @@ namespace OpenWifi::GWObjects {
struct RttySessionDetails {
std::string SerialNumber;
std::string Server;
uint64_t Port = 0 ;
uint64_t Port = 0;
std::string Token;
uint64_t TimeOut = 0 ;
uint64_t TimeOut = 0;
std::string ConnectionId;
uint64_t Started = 0 ;
uint64_t Started = 0;
std::string CommandUUID;
uint64_t ViewPort = 0 ;
uint64_t ViewPort = 0;
std::string DevicePassword;
void to_json(Poco::JSON::Object &Obj) const;
};
struct Dashboard {
uint64_t snapshot = 0 ;
uint64_t numberOfDevices = 0 ;
uint64_t snapshot = 0;
uint64_t numberOfDevices = 0;
Types::CountedMap commands;
Types::CountedMap upTimes;
Types::CountedMap memoryUsed;
@@ -247,27 +260,27 @@ namespace OpenWifi::GWObjects {
};
struct ScriptEntry {
std::string id;
std::string name;
std::string description;
std::string uri;
std::string content;
std::string version;
std::string type;
std::uint64_t created;
std::uint64_t modified;
std::string author;
Types::StringVec restricted;
bool deferred=false;
std::uint64_t timeout=30;
std::string defaultUploadURI;
std::string id;
std::string name;
std::string description;
std::string uri;
std::string content;
std::string version;
std::string type;
std::uint64_t created;
std::uint64_t modified;
std::string author;
Types::StringVec restricted;
bool deferred = false;
std::uint64_t timeout = 30;
std::string defaultUploadURI;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct ScriptEntryList {
std::vector<ScriptEntry> scripts;
std::vector<ScriptEntry> scripts;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
@@ -275,7 +288,7 @@ namespace OpenWifi::GWObjects {
struct ScriptRequest {
std::string serialNumber;
uint64_t timeout=30;
uint64_t timeout = 30;
std::string type;
std::string script;
std::string scriptId;
@@ -291,52 +304,125 @@ namespace OpenWifi::GWObjects {
struct RadiusProxyServerEntry {
std::string name;
std::string ip;
uint16_t port=0;
uint64_t weight=0;
uint16_t port = 0;
uint64_t weight = 0;
std::string secret;
std::string certificate;
bool radsec=false;
bool allowSelfSigned=false;
uint16_t radsecPort=2083;
bool radsec = false;
bool allowSelfSigned = false;
uint16_t radsecPort = 2083;
std::string radsecSecret;
std::string radsecKey;
std::string radsecCert;
std::vector<std::string> radsecCacerts;
std::vector<std::string> radsecRealms;
bool ignore=false;
std::vector<std::string> radsecCacerts;
std::vector<std::string> radsecRealms;
bool ignore = false;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RadiusProxyServerConfig {
std::string strategy;
bool monitor=false;
std::string monitorMethod;
std::vector<std::string> methodParameters;
std::vector<RadiusProxyServerEntry> servers;
std::string strategy;
bool monitor = false;
std::string monitorMethod;
std::vector<std::string> methodParameters;
std::vector<RadiusProxyServerEntry> servers;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RadiusProxyPool {
struct RadiusProxyPool {
std::string name;
std::string description;
RadiusProxyServerConfig authConfig;
RadiusProxyServerConfig acctConfig;
RadiusProxyServerConfig coaConfig;
bool useByDefault=false;
RadiusProxyServerConfig authConfig;
RadiusProxyServerConfig acctConfig;
RadiusProxyServerConfig coaConfig;
bool useByDefault = false;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RadiusProxyPoolList {
std::vector<RadiusProxyPool> pools;
std::vector<RadiusProxyPool> pools;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
}
struct RangeOptions {
bool NO_IR=false;
bool AUTO_BW=false;
bool DFS=false;
bool NO_OUTDOOR=false;
bool wmmrule_ETSI=false;
bool NO_OFDM=false;
void to_json(Poco::JSON::Object &Obj) const;
};
struct FrequencyRange {
float from = 0.0;
float to = 0.0;
int channelWidth = 0;
int powerDb = 0;
RangeOptions options;
void to_json(Poco::JSON::Object &Obj) const;
};
struct RegulatoryCountryInfo {
std::string country;
std::string domain;
std::vector<FrequencyRange> ranges;
void to_json(Poco::JSON::Object &Obj) const;
};
using RegulatoryInfoCountryMap = std::map<std::string,RegulatoryCountryInfo>;
struct RADIUSSession {
std::uint64_t started=0,
lastTransaction=0;
std::string serialNumber,
destination,
userName,
accountingSessionId,
accountingMultiSessionId,
callingStationId,
chargeableUserIdentity,
secret,
interface,
nasId;
std::uint64_t inputPackets = 0,
outputPackets = 0,
inputOctets = 0,
outputOctets = 0,
inputGigaWords = 0,
outputGigaWords = 0;
std::uint32_t sessionTime = 0;
#ifdef TIP_GATEWAY_SERVICE
RADIUS::RadiusPacket accountingPacket;
#endif
void to_json(Poco::JSON::Object &Obj) const;
};
struct RADIUSSessionList {
std::vector<RADIUSSession> sessions;
void to_json(Poco::JSON::Object &Obj) const;
};
struct RadiusCoADMParameters {
std::string accountingSessionId,
accountingMultiSessionId,
callingStationId,
chargeableUserIdentity;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
} // namespace OpenWifi::GWObjects

View File

@@ -4,9 +4,9 @@
#include "framework/RESTAPI_utils.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::EmbedDocument;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::field_to_json;
#include "RESTAPI_OWLSobjects.h"
@@ -14,97 +14,90 @@ using OpenWifi::RESTAPI_utils::EmbedDocument;
namespace OpenWifi::OWLSObjects {
void SimulationDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id);
field_to_json(Obj,"name", name);
field_to_json(Obj,"gateway", gateway);
field_to_json(Obj,"certificate", certificate);
field_to_json(Obj,"key", key);
field_to_json(Obj,"macPrefix", macPrefix);
field_to_json(Obj,"deviceType", deviceType);
field_to_json(Obj,"devices", devices);
field_to_json(Obj,"healthCheckInterval", healthCheckInterval);
field_to_json(Obj,"stateInterval", stateInterval);
field_to_json(Obj,"minAssociations", minAssociations);
field_to_json(Obj,"maxAssociations", maxAssociations);
field_to_json(Obj,"minClients", minClients);
field_to_json(Obj,"maxClients", maxClients);
field_to_json(Obj,"simulationLength", simulationLength);
field_to_json(Obj,"threads", threads);
field_to_json(Obj,"clientInterval", clientInterval);
field_to_json(Obj,"keepAlive", keepAlive);
field_to_json(Obj,"reconnectInterval", reconnectInterval);
field_to_json(Obj,"concurrentDevices", concurrentDevices);
}
void SimulationDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "name", name);
field_to_json(Obj, "gateway", gateway);
field_to_json(Obj, "certificate", certificate);
field_to_json(Obj, "key", key);
field_to_json(Obj, "macPrefix", macPrefix);
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "devices", devices);
field_to_json(Obj, "healthCheckInterval", healthCheckInterval);
field_to_json(Obj, "stateInterval", stateInterval);
field_to_json(Obj, "minAssociations", minAssociations);
field_to_json(Obj, "maxAssociations", maxAssociations);
field_to_json(Obj, "minClients", minClients);
field_to_json(Obj, "maxClients", maxClients);
field_to_json(Obj, "simulationLength", simulationLength);
field_to_json(Obj, "threads", threads);
field_to_json(Obj, "clientInterval", clientInterval);
field_to_json(Obj, "keepAlive", keepAlive);
field_to_json(Obj, "reconnectInterval", reconnectInterval);
field_to_json(Obj, "concurrentDevices", concurrentDevices);
}
bool SimulationDetails::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"id", id);
field_from_json(Obj,"name", name);
field_from_json(Obj,"gateway", gateway);
field_from_json(Obj,"certificate", certificate);
field_from_json(Obj,"key", key);
field_from_json(Obj,"macPrefix", macPrefix);
field_from_json(Obj,"deviceType", deviceType);
field_from_json(Obj,"devices", devices);
field_from_json(Obj,"healthCheckInterval", healthCheckInterval);
field_from_json(Obj,"stateInterval", stateInterval);
field_from_json(Obj,"minAssociations", minAssociations);
field_from_json(Obj,"maxAssociations", maxAssociations);
field_from_json(Obj,"minClients", minClients);
field_from_json(Obj,"maxClients", maxClients);
field_from_json(Obj,"simulationLength", simulationLength);
field_from_json(Obj,"threads", threads);
field_from_json(Obj,"clientInterval", clientInterval);
field_from_json(Obj,"keepAlive", keepAlive);
field_from_json(Obj,"reconnectInterval", reconnectInterval);
field_from_json(Obj,"concurrentDevices", concurrentDevices);
return true;
} catch(...) {
bool SimulationDetails::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "name", name);
field_from_json(Obj, "gateway", gateway);
field_from_json(Obj, "certificate", certificate);
field_from_json(Obj, "key", key);
field_from_json(Obj, "macPrefix", macPrefix);
field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "devices", devices);
field_from_json(Obj, "healthCheckInterval", healthCheckInterval);
field_from_json(Obj, "stateInterval", stateInterval);
field_from_json(Obj, "minAssociations", minAssociations);
field_from_json(Obj, "maxAssociations", maxAssociations);
field_from_json(Obj, "minClients", minClients);
field_from_json(Obj, "maxClients", maxClients);
field_from_json(Obj, "simulationLength", simulationLength);
field_from_json(Obj, "threads", threads);
field_from_json(Obj, "clientInterval", clientInterval);
field_from_json(Obj, "keepAlive", keepAlive);
field_from_json(Obj, "reconnectInterval", reconnectInterval);
field_from_json(Obj, "concurrentDevices", concurrentDevices);
return true;
} catch (...) {
}
return false;
}
}
return false;
}
void SimulationDetailsList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "list", list);
}
void SimulationDetailsList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"list", list);
}
bool SimulationDetailsList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "list", list);
return true;
} catch (...) {
}
return false;
}
bool SimulationDetailsList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"list", list);
return true;
} catch(...) {
void SimulationStatus::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "simulationId", simulationId);
field_to_json(Obj, "state", state);
field_to_json(Obj, "tx", tx);
field_to_json(Obj, "rx", rx);
field_to_json(Obj, "msgsTx", msgsTx);
field_to_json(Obj, "msgsRx", msgsRx);
field_to_json(Obj, "liveDevices", liveDevices);
field_to_json(Obj, "timeToFullDevices", timeToFullDevices);
field_to_json(Obj, "startTime", startTime);
field_to_json(Obj, "endTime", endTime);
field_to_json(Obj, "errorDevices", errorDevices);
field_to_json(Obj, "owner", owner);
field_to_json(Obj, "expectedDevices", expectedDevices);
}
}
return false;
}
void Dashboard::to_json([[maybe_unused]] Poco::JSON::Object &Obj) const {}
void SimulationStatus::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id);
field_to_json(Obj,"simulationId", simulationId);
field_to_json(Obj,"state", state);
field_to_json(Obj,"tx", tx);
field_to_json(Obj,"rx", rx);
field_to_json(Obj,"msgsTx", msgsTx);
field_to_json(Obj,"msgsRx", msgsRx);
field_to_json(Obj,"liveDevices", liveDevices);
field_to_json(Obj,"timeToFullDevices", timeToFullDevices);
field_to_json(Obj,"startTime", startTime);
field_to_json(Obj,"endTime", endTime);
field_to_json(Obj,"errorDevices", errorDevices);
field_to_json(Obj,"owner", owner);
}
bool Dashboard::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) { return true; }
void Dashboard::to_json([[maybe_unused]] Poco::JSON::Object &Obj) const {
}
bool Dashboard::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) {
return true;
}
void Dashboard::reset() {
}
}
void Dashboard::reset() {}
} // namespace OpenWifi::OWLSObjects

View File

@@ -5,73 +5,71 @@
#ifndef UCENTRALSIM_RESTAPI_OWLSOBJECTS_H
#define UCENTRALSIM_RESTAPI_OWLSOBJECTS_H
#include <vector>
#include "Poco/JSON/Object.h"
#include <vector>
namespace OpenWifi::OWLSObjects {
struct SimulationDetails {
std::string id;
std::string name;
std::string gateway;
std::string certificate;
std::string key;
std::string macPrefix;
std::string deviceType;
uint64_t devices = 5;
uint64_t healthCheckInterval = 60;
uint64_t stateInterval = 60 ;
uint64_t minAssociations = 1;
uint64_t maxAssociations = 3;
uint64_t minClients = 1 ;
uint64_t maxClients = 3;
uint64_t simulationLength = 60 * 60;
uint64_t threads = 16;
uint64_t clientInterval = 1;
uint64_t keepAlive = 300;
uint64_t reconnectInterval = 30 ;
uint64_t concurrentDevices = 5;
struct SimulationDetails {
std::string id;
std::string name;
std::string gateway;
std::string certificate;
std::string key;
std::string macPrefix;
std::string deviceType;
uint64_t devices = 10;
uint64_t healthCheckInterval = 60;
uint64_t stateInterval = 60;
uint64_t minAssociations = 2;
uint64_t maxAssociations = 8;
uint64_t minClients = 2;
uint64_t maxClients = 4;
uint64_t simulationLength = 60 * 60;
uint64_t threads = 16;
uint64_t clientInterval = 1;
uint64_t keepAlive = 300;
uint64_t reconnectInterval = 30;
uint64_t concurrentDevices = 5;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SimulationDetailsList {
std::vector<SimulationDetails> list;
struct SimulationDetailsList {
std::vector<SimulationDetails> list;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SimulationStatus {
std::string id;
std::string simulationId;
std::string state;
uint64_t tx;
uint64_t rx;
uint64_t msgsTx;
uint64_t msgsRx;
uint64_t liveDevices;
uint64_t timeToFullDevices;
uint64_t startTime;
uint64_t endTime;
uint64_t errorDevices;
std::string owner;
struct SimulationStatus {
std::string id;
std::string simulationId;
std::string state;
uint64_t tx;
uint64_t rx;
uint64_t msgsTx;
uint64_t msgsRx;
uint64_t liveDevices;
uint64_t timeToFullDevices;
uint64_t startTime;
uint64_t endTime;
uint64_t errorDevices;
std::string owner;
uint64_t expectedDevices;
void to_json(Poco::JSON::Object &Obj) const;
};
void to_json(Poco::JSON::Object &Obj) const;
};
struct Dashboard {
int O;
struct Dashboard {
int O;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
void reset();
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
void reset();
} // namespace OpenWifi::OWLSObjects
};
}
#endif //UCENTRALSIM_RESTAPI_OWLSOBJECTS_H
#endif // UCENTRALSIM_RESTAPI_OWLSOBJECTS_H

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -8,361 +8,364 @@
#pragma once
#include <string>
#include <type_traits>
#include "framework/OpenWifiTypes.h"
#include "Poco/JSON/Object.h"
#include "Poco/Data/LOB.h"
#include "Poco/Data/LOBStream.h"
#include "Poco/JSON/Object.h"
#include "framework/OpenWifiTypes.h"
#include "framework/utils.h"
#include <string>
#include <type_traits>
namespace OpenWifi {
uint64_t Now();
namespace SecurityObjects {
typedef std::string USER_ID_TYPE;
uint64_t Now();
namespace SecurityObjects {
struct AclTemplate {
bool Read_ = true;
bool ReadWrite_ = true;
bool ReadWriteCreate_ = true;
bool Delete_ = true;
bool PortalLogin_ = true;
typedef std::string USER_ID_TYPE;
AclTemplate() noexcept = default;
struct AclTemplate {
bool Read_ = true;
bool ReadWrite_ = true;
bool ReadWriteCreate_ = true;
bool Delete_ = true;
bool PortalLogin_ = true;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
AclTemplate() noexcept = default;
static_assert( std::is_nothrow_move_constructible_v<AclTemplate> );
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WebToken {
std::string access_token_;
std::string refresh_token_;
std::string id_token_;
std::string token_type_;
std::string username_;
bool userMustChangePassword=false;
uint64_t errorCode=0;
uint64_t expires_in_=0;
uint64_t idle_timeout_=0;
AclTemplate acl_template_;
uint64_t created_=0;
uint64_t lastRefresh_=0;
static_assert(std::is_nothrow_move_constructible_v<AclTemplate>);
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WebToken {
std::string access_token_;
std::string refresh_token_;
std::string id_token_;
std::string token_type_;
std::string username_;
bool userMustChangePassword = false;
uint64_t errorCode = 0;
uint64_t expires_in_ = 0;
uint64_t idle_timeout_ = 0;
AclTemplate acl_template_;
uint64_t created_ = 0;
uint64_t lastRefresh_ = 0;
enum USER_ROLE {
UNKNOWN, ROOT, ADMIN, SUBSCRIBER, CSR, SYSTEM, INSTALLER, NOC, ACCOUNTING, PARTNER
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
USER_ROLE UserTypeFromString(const std::string &U);
std::string UserTypeToString(USER_ROLE U);
enum USER_ROLE {
UNKNOWN,
ROOT,
ADMIN,
SUBSCRIBER,
CSR,
SYSTEM,
INSTALLER,
NOC,
ACCOUNTING,
PARTNER
};
struct NoteInfo {
uint64_t created=0; // = Utils::Now();
std::string createdBy;
std::string note;
USER_ROLE UserTypeFromString(const std::string &U);
std::string UserTypeToString(USER_ROLE U);
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<NoteInfo> NoteInfoVec;
struct NoteInfo {
uint64_t created = 0; // = Utils::Now();
std::string createdBy;
std::string note;
struct MobilePhoneNumber {
std::string number;
bool verified = false;
bool primary = false;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<NoteInfo> NoteInfoVec;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct MobilePhoneNumber {
std::string number;
bool verified = false;
bool primary = false;
struct MfaAuthInfo {
bool enabled = false;
std::string method;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct MfaAuthInfo {
bool enabled = false;
std::string method;
struct UserLoginLoginExtensions {
std::vector<MobilePhoneNumber> mobiles;
struct MfaAuthInfo mfa;
std::string authenticatorSecret;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct UserLoginLoginExtensions {
std::vector<MobilePhoneNumber> mobiles;
struct MfaAuthInfo mfa;
std::string authenticatorSecret;
struct MFAChallengeRequest {
std::string uuid;
std::string question;
std::string method;
uint64_t created = Utils::Now();
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct MFAChallengeRequest {
std::string uuid;
std::string question;
std::string method;
uint64_t created = Utils::Now();
struct MFAChallengeResponse {
std::string uuid;
std::string answer;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct MFAChallengeResponse {
std::string uuid;
std::string answer;
struct UserInfo {
std::string id;
std::string name;
std::string description;
std::string avatar;
std::string email;
bool validated = false;
std::string validationEmail;
uint64_t validationDate = 0;
uint64_t creationDate = 0;
std::string validationURI;
bool changePassword = false;
uint64_t lastLogin = 0;
std::string currentLoginURI;
uint64_t lastPasswordChange = 0;
uint64_t lastEmailCheck = 0;
bool waitingForEmailCheck = false;
std::string locale;
NoteInfoVec notes;
std::string location;
std::string owner;
bool suspended = false;
bool blackListed = false;
USER_ROLE userRole;
UserLoginLoginExtensions userTypeProprietaryInfo;
std::string securityPolicy;
uint64_t securityPolicyChange = 0 ;
std::string currentPassword;
OpenWifi::Types::StringVec lastPasswords;
std::string oauthType;
std::string oauthUserInfo;
uint64_t modified;
std::string signingUp;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<UserInfo> UserInfoVec;
struct UserInfo {
std::string id;
std::string name;
std::string description;
std::string avatar;
std::string email;
bool validated = false;
std::string validationEmail;
uint64_t validationDate = 0;
uint64_t creationDate = 0;
std::string validationURI;
bool changePassword = false;
uint64_t lastLogin = 0;
std::string currentLoginURI;
uint64_t lastPasswordChange = 0;
uint64_t lastEmailCheck = 0;
bool waitingForEmailCheck = false;
std::string locale;
NoteInfoVec notes;
std::string location;
std::string owner;
bool suspended = false;
bool blackListed = false;
USER_ROLE userRole;
UserLoginLoginExtensions userTypeProprietaryInfo;
std::string securityPolicy;
uint64_t securityPolicyChange = 0;
std::string currentPassword;
OpenWifi::Types::StringVec lastPasswords;
std::string oauthType;
std::string oauthUserInfo;
uint64_t modified;
std::string signingUp;
struct UserInfoList {
std::vector<UserInfo> users;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<UserInfo> UserInfoVec;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct UserInfoList {
std::vector<UserInfo> users;
// bool append_from_json(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec & Notes);
bool MergeNotes(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec & Notes);
bool MergeNotes(const NoteInfoVec & NewNotes, const UserInfo &UInfo, NoteInfoVec & ExistingNotes);
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct InternalServiceInfo {
std::string privateURI;
std::string publicURI;
std::string token;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<InternalServiceInfo> InternalServiceInfoVec;
// bool append_from_json(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec &
// Notes);
bool MergeNotes(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec &Notes);
bool MergeNotes(const NoteInfoVec &NewNotes, const UserInfo &UInfo,
NoteInfoVec &ExistingNotes);
struct InternalSystemServices {
std::string key;
std::string version;
InternalServiceInfoVec services;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct InternalServiceInfo {
std::string privateURI;
std::string publicURI;
std::string token;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<InternalServiceInfo> InternalServiceInfoVec;
struct SystemEndpoint {
std::string type;
uint64_t id = 0;
std::string vendor{"OpenWiFi"};
std::string uri;
std::string authenticationType{"internal_v1"};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<SystemEndpoint> SystemEndpointVec;
struct InternalSystemServices {
std::string key;
std::string version;
InternalServiceInfoVec services;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SystemEndpointList {
SystemEndpointVec endpoints;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SystemEndpoint {
std::string type;
uint64_t id = 0;
std::string vendor{"OpenWiFi"};
std::string uri;
std::string authenticationType{"internal_v1"};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<SystemEndpoint> SystemEndpointVec;
struct UserInfoAndPolicy {
WebToken webtoken;
UserInfo userinfo;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::map<std::string,SecurityObjects::UserInfoAndPolicy> UserInfoCache;
struct SystemEndpointList {
SystemEndpointVec endpoints;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
enum ResourceAccessType {
NONE,
READ,
MODIFY,
DELETE,
CREATE,
TEST,
MOVE
};
struct UserInfoAndPolicy {
WebToken webtoken;
UserInfo userinfo;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::map<std::string, SecurityObjects::UserInfoAndPolicy> UserInfoCache;
ResourceAccessType ResourceAccessTypeFromString(const std::string &s);
std::string ResourceAccessTypeToString(const ResourceAccessType & T);
enum ResourceAccessType { NONE, READ, MODIFY, DELETE, CREATE, TEST, MOVE };
struct ProfileAction {
std::string resource;
ResourceAccessType access;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<ProfileAction> ProfileActionVec;
ResourceAccessType ResourceAccessTypeFromString(const std::string &s);
std::string ResourceAccessTypeToString(const ResourceAccessType &T);
struct SecurityProfile {
uint64_t id=0;
std::string name;
std::string description;
ProfileActionVec policy;
std::string role;
NoteInfoVec notes;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<SecurityProfile> SecurityProfileVec;
struct ProfileAction {
std::string resource;
ResourceAccessType access;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<ProfileAction> ProfileActionVec;
struct SecurityProfileList {
SecurityProfileVec profiles;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SecurityProfile {
uint64_t id = 0;
std::string name;
std::string description;
ProfileActionVec policy;
std::string role;
NoteInfoVec notes;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<SecurityProfile> SecurityProfileVec;
enum LinkActions {
FORGOT_PASSWORD=1,
VERIFY_EMAIL,
SUB_FORGOT_PASSWORD,
SUB_VERIFY_EMAIL,
SUB_SIGNUP,
EMAIL_INVITATION
};
struct SecurityProfileList {
SecurityProfileVec profiles;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct ActionLink {
std::string id;
uint64_t action;
std::string userId;
std::string actionTemplate;
Types::StringPairVec variables;
std::string locale;
std::string message;
uint64_t sent=0;
uint64_t created=Utils::Now();
uint64_t expires=0;
uint64_t completed=0;
uint64_t canceled=0;
bool userAction=true;
enum LinkActions {
FORGOT_PASSWORD = 1,
VERIFY_EMAIL,
SUB_FORGOT_PASSWORD,
SUB_VERIFY_EMAIL,
SUB_SIGNUP,
EMAIL_INVITATION
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct ActionLink {
std::string id;
uint64_t action;
std::string userId;
std::string actionTemplate;
Types::StringPairVec variables;
std::string locale;
std::string message;
uint64_t sent = 0;
uint64_t created = Utils::Now();
uint64_t expires = 0;
uint64_t completed = 0;
uint64_t canceled = 0;
bool userAction = true;
struct Preferences {
std::string id;
uint64_t modified;
Types::StringPairVec data;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SubMfaConfig {
std::string id;
std::string type;
std::string sms;
std::string email;
struct Preferences {
std::string id;
uint64_t modified;
Types::StringPairVec data;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SubMfaConfig {
std::string id;
std::string type;
std::string sms;
std::string email;
struct Token {
std::string token;
std::string refreshToken;
std::string tokenType;
std::string userName;
uint64_t created=0;
uint64_t expires=0;
uint64_t idleTimeout=0;
uint64_t revocationDate=0;
uint64_t lastRefresh=0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct Token {
std::string token;
std::string refreshToken;
std::string tokenType;
std::string userName;
uint64_t created = 0;
uint64_t expires = 0;
uint64_t idleTimeout = 0;
uint64_t revocationDate = 0;
uint64_t lastRefresh = 0;
struct Avatar {
std::string id;
std::string type;
uint64_t created=0;
std::string name;
Poco::Data::BLOB avatar;
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct LoginRecordInfo {
std::string sessionId;
std::string userId;
std::string email;
uint64_t login=0;
uint64_t logout=0;
struct Avatar {
std::string id;
std::string type;
uint64_t created = 0;
std::string name;
Poco::Data::BLOB avatar;
};
void to_json(Poco::JSON::Object &Obj) const;
};
struct LoginRecordInfo {
std::string sessionId;
std::string userId;
std::string email;
uint64_t login = 0;
uint64_t logout = 0;
struct ApiKeyAccessRight {
std::string service;
std::string access;
void to_json(Poco::JSON::Object &Obj) const;
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct ApiKeyAccessRight {
std::string service;
std::string access;
struct ApiKeyAccessRightList {
std::vector<ApiKeyAccessRight> acls;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct ApiKeyAccessRightList {
std::vector<ApiKeyAccessRight> acls;
struct ApiKeyEntry {
Types::UUID_t id;
Types::UUID_t userUuid;
std::string name;
std::string description;
std::string apiKey;
std::string salt;
std::uint64_t created;
std::uint64_t expiresOn=0;
ApiKeyAccessRightList rights;
std::uint64_t lastUse=0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct ApiKeyEntry {
Types::UUID_t id;
Types::UUID_t userUuid;
std::string name;
std::string description;
std::string apiKey;
std::string salt;
std::uint64_t created;
std::uint64_t expiresOn = 0;
ApiKeyAccessRightList rights;
std::uint64_t lastUse = 0;
struct ApiKeyEntryList {
std::vector<ApiKeyEntry> apiKeys;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct ApiKeyEntryList {
std::vector<ApiKeyEntry> apiKeys;
}
}
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
} // namespace SecurityObjects
} // namespace OpenWifi

File diff suppressed because it is too large Load Diff

View File

@@ -11,312 +11,312 @@
namespace OpenWifi::SubObjects {
struct HomeDeviceMode {
bool enableLEDS = true;
std::string type; // bridge, manual, automatic
std::string subnet;
std::string subnetMask;
std::string startIP;
std::string endIP;
uint64_t created = 0 ;
uint64_t modified = 0 ;
std::string subnetV6;
int subnetMaskV6=0;
std::string startIPV6;
std::string endIPV6;
std::string leaseTime;
struct HomeDeviceMode {
bool enableLEDS = true;
std::string type; // bridge, manual, automatic
std::string subnet;
std::string subnetMask;
std::string startIP;
std::string endIP;
uint64_t created = 0;
uint64_t modified = 0;
std::string subnetV6;
int subnetMaskV6 = 0;
std::string startIPV6;
std::string endIPV6;
std::string leaseTime;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct IPReservation {
std::string nickname;
std::string ipAddress;
std::string macAddress;
struct IPReservation {
std::string nickname;
std::string ipAddress;
std::string macAddress;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct IPReservationList {
std::string id;
std::vector<IPReservation> reservations;
uint64_t created = 0 ;
uint64_t modified = 0 ;
struct IPReservationList {
std::string id;
std::vector<IPReservation> reservations;
uint64_t created = 0;
uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DnsConfiguration {
bool ISP=false;
bool custom=false;
std::string primary;
std::string secondary;
std::string primaryV6;
std::string secondaryV6;
struct DnsConfiguration {
bool ISP = false;
bool custom = false;
std::string primary;
std::string secondary;
std::string primaryV6;
std::string secondaryV6;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct InternetConnection {
std::string type; // automatic, pppoe, manual
std::string username;
std::string password;
std::string ipAddress;
std::string subnetMask;
std::string defaultGateway;
bool sendHostname = true;
std::string primaryDns;
std::string secondaryDns;
uint64_t created=0;
uint64_t modified=0;
bool ipV6Support=false;
std::string ipAddressV6;
int subnetMaskV6=0;
std::string defaultGatewayV6;
std::string primaryDnsV6;
std::string secondaryDnsV6;
struct InternetConnection {
std::string type; // automatic, pppoe, manual
std::string username;
std::string password;
std::string ipAddress;
std::string subnetMask;
std::string defaultGateway;
bool sendHostname = true;
std::string primaryDns;
std::string secondaryDns;
uint64_t created = 0;
uint64_t modified = 0;
bool ipV6Support = false;
std::string ipAddressV6;
int subnetMaskV6 = 0;
std::string defaultGatewayV6;
std::string primaryDnsV6;
std::string secondaryDnsV6;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WifiNetwork {
std::string type; // main, guest
std::string name;
std::string password;
std::string encryption;
std::vector<std::string> bands;
struct WifiNetwork {
std::string type; // main, guest
std::string name;
std::string password;
std::string encryption;
std::vector<std::string> bands;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WifiNetworkList {
std::vector<WifiNetwork> wifiNetworks;
uint64_t created=0;
uint64_t modified=0;
struct WifiNetworkList {
std::vector<WifiNetwork> wifiNetworks;
uint64_t created = 0;
uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct AccessTime {
std::string day;
std::vector<std::string> rangeList;
struct AccessTime {
std::string day;
std::vector<std::string> rangeList;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct AccessTimes {
std::vector<AccessTime> schedule;
uint64_t created=0;
uint64_t modified=0;
struct AccessTimes {
std::vector<AccessTime> schedule;
uint64_t created = 0;
uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SubscriberDevice {
std::string name;
std::string description;
std::string macAddress;
std::string manufacturer;
uint64_t firstContact=0;
uint64_t lastContact=0;
std::string group;
std::string icon;
bool suspended=false;
std::string ip;
std::vector<AccessTimes> schedule;
struct SubscriberDevice {
std::string name;
std::string description;
std::string macAddress;
std::string manufacturer;
uint64_t firstContact = 0;
uint64_t lastContact = 0;
std::string group;
std::string icon;
bool suspended = false;
std::string ip;
std::vector<AccessTimes> schedule;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SubscriberDeviceList {
std::vector<SubscriberDevice> devices;
uint64_t created=0;
uint64_t modified=0;
struct SubscriberDeviceList {
std::vector<SubscriberDevice> devices;
uint64_t created = 0;
uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct Association {
std::string name;
std::string ssid;
std::string macAddress;
int rssi=0;
int power=0;
std::string ipv4;
std::string ipv6;
uint64_t tx=0;
uint64_t rx=0;
std::string manufacturer;
struct Association {
std::string name;
std::string ssid;
std::string macAddress;
int rssi = 0;
int power = 0;
std::string ipv4;
std::string ipv6;
uint64_t tx = 0;
uint64_t rx = 0;
std::string manufacturer;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct AssociationList {
std::vector<Association> associations;
uint64_t created=0;
uint64_t modified=0;
struct AssociationList {
std::vector<Association> associations;
uint64_t created = 0;
uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct Client {
std::string macAddress;
std::string speed;
std::string mode;
std::string ipv4;
std::string ipv6;
uint64_t tx=0;
uint64_t rx=0;
std::string manufacturer;
struct Client {
std::string macAddress;
std::string speed;
std::string mode;
std::string ipv4;
std::string ipv6;
uint64_t tx = 0;
uint64_t rx = 0;
std::string manufacturer;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct ClientList {
std::vector<Client> clients;
uint64_t created=0;
uint64_t modified=0;
struct ClientList {
std::vector<Client> clients;
uint64_t created = 0;
uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct Location {
std::string buildingName;
std::vector<std::string> addressLines;
std::string city;
std::string state;
std::string postal;
std::string country;
std::vector<std::string> phones;
std::vector<std::string> mobiles;
struct Location {
std::string buildingName;
std::vector<std::string> addressLines;
std::string city;
std::string state;
std::string postal;
std::string country;
std::vector<std::string> phones;
std::vector<std::string> mobiles;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RadioHE {
bool multipleBSSID = false;
bool ema = false;
uint64_t bssColor = 64;
struct RadioHE {
bool multipleBSSID = false;
bool ema = false;
uint64_t bssColor = 64;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RadioRates {
uint64_t beacon = 6000;
uint64_t multicast = 24000;
struct RadioRates {
uint64_t beacon = 6000;
uint64_t multicast = 24000;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RadioInformation {
std::string band;
uint64_t bandwidth;
uint64_t channel = 0 ;
std::string country;
std::string channelMode{"HE"};
uint64_t channelWidth = 80;
std::string requireMode;
uint64_t txpower=0;
bool legacyRates = false;
uint64_t beaconInterval = 100;
uint64_t dtimPeriod = 2;
uint64_t maximumClients = 64;
RadioRates rates;
RadioHE he;
bool allowDFS=false;
std::string mimo;
std::vector<std::string> rawInfo;
struct RadioInformation {
std::string band;
uint64_t bandwidth;
uint64_t channel = 0;
std::string country;
std::string channelMode{"HE"};
uint64_t channelWidth = 80;
std::string requireMode;
uint64_t txpower = 0;
bool legacyRates = false;
uint64_t beaconInterval = 100;
uint64_t dtimPeriod = 2;
uint64_t maximumClients = 64;
RadioRates rates;
RadioHE he;
bool allowDFS = false;
std::string mimo;
std::vector<std::string> rawInfo;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct AccessPoint {
std::string id;
std::string macAddress;
std::string serialNumber;
std::string name;
std::string deviceType;
SubscriberDeviceList subscriberDevices;
IPReservationList ipReservations;
Location address;
WifiNetworkList wifiNetworks;
InternetConnection internetConnection;
HomeDeviceMode deviceMode;
DnsConfiguration dnsConfiguration;
std::vector<RadioInformation> radios;
bool automaticUpgrade = true;
std::string configurationUUID;
std::string currentFirmware;
uint64_t currentFirmwareDate;
std::string latestFirmware;
uint64_t latestFirmwareDate;
bool newFirmwareAvailable;
std::string latestFirmwareURI;
struct AccessPoint {
std::string id;
std::string macAddress;
std::string serialNumber;
std::string name;
std::string deviceType;
SubscriberDeviceList subscriberDevices;
IPReservationList ipReservations;
Location address;
WifiNetworkList wifiNetworks;
InternetConnection internetConnection;
HomeDeviceMode deviceMode;
DnsConfiguration dnsConfiguration;
std::vector<RadioInformation> radios;
bool automaticUpgrade = true;
std::string configurationUUID;
std::string currentFirmware;
uint64_t currentFirmwareDate;
std::string latestFirmware;
uint64_t latestFirmwareDate;
bool newFirmwareAvailable;
std::string latestFirmwareURI;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct AccessPointList {
std::vector<AccessPoint> list;
struct AccessPointList {
std::vector<AccessPoint> list;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SubscriberInfo {
std::string id;
std::string userId;
std::string firstName;
std::string initials;
std::string lastName;
std::string phoneNumber;
std::string secondaryEmail;
AccessPointList accessPoints;
Location serviceAddress;
Location billingAddress;
uint64_t created = 0;
uint64_t modified = 0;
struct SubscriberInfo {
std::string id;
std::string userId;
std::string firstName;
std::string initials;
std::string lastName;
std::string phoneNumber;
std::string secondaryEmail;
AccessPointList accessPoints;
Location serviceAddress;
Location billingAddress;
uint64_t created = 0;
uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct StatsEntry {
uint64_t timestamp=0;
uint64_t tx=0;
uint64_t rx=0;
struct StatsEntry {
uint64_t timestamp = 0;
uint64_t tx = 0;
uint64_t rx = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct StatsBlock {
uint64_t modified=0;
std::vector<StatsEntry> external, internal;
struct StatsBlock {
uint64_t modified = 0;
std::vector<StatsEntry> external, internal;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
}
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
} // namespace OpenWifi::SubObjects
#endif //OWSUB_RESTAPI_SUBOBJECTS_H
#endif // OWSUB_RESTAPI_SUBOBJECTS_H

View File

@@ -4,137 +4,188 @@
#pragma once
#include "framework/SubSystemServer.h"
#include "framework/utils.h"
#include "RESTObjects/RESTAPI_OWLSobjects.h"
#include <framework/SubSystemServer.h>
#include <framework/utils.h>
#include <RESTObjects/RESTAPI_OWLSobjects.h>
#include <RESTObjects/RESTAPI_SecurityObjects.h>
namespace OpenWifi {
class SimStats : public SubSystemServer {
class SimStats : public SubSystemServer {
public:
inline void Connect() {
public:
inline void Connect(const std::string &id) {
std::lock_guard G(Mutex_);
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return;
}
stats_hint->second.liveDevices++;
if ((stats_hint->second.timeToFullDevices == 0) && (stats_hint->second.liveDevices == stats_hint->second.expectedDevices)) {
uint64_t Now = Utils::Now();
stats_hint->second.timeToFullDevices = Now - stats_hint->second.startTime;
}
}
inline void Disconnect(const std::string &id) {
std::lock_guard G(Mutex_);
Status_.liveDevices++;
if( (Status_.timeToFullDevices == 0) && (Status_.liveDevices == ExpectedDevices_) ) {
uint64_t Now = Utils::Now();
Status_.timeToFullDevices = Now - Status_.startTime;
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return;
}
}
inline void Disconnect() {
if(CollectInfo_) {
std::lock_guard G(Mutex_);
if(Status_.liveDevices)
Status_.liveDevices--;
}
}
if (stats_hint->second.liveDevices)
stats_hint->second.liveDevices--;
}
static auto instance() {
static auto instance_ = new SimStats;
return instance_;
}
static auto instance() {
static auto instance_ = new SimStats;
return instance_;
}
inline void AddRX(uint64_t N) {
if(CollectInfo_) {
std::lock_guard G(Mutex_);
Status_.rx += N;
}
}
inline void AddOutMsg() {
if(CollectInfo_) {
std::lock_guard G(Mutex_);
Status_.msgsTx++;
}
}
inline void AddInMsg() {
if(CollectInfo_) {
std::lock_guard G(Mutex_);
Status_.msgsRx++;
}
}
inline void AddTX(uint64_t N) {
if(CollectInfo_) {
std::lock_guard G(Mutex_);
Status_.tx += N;
}
}
inline void GetCurrent( OWLSObjects::SimulationStatus & S) {
inline void AddOutMsg(const std::string &id, int64_t N) {
std::lock_guard G(Mutex_);
S = Status_;
}
inline int Start() final {
Reset();
return 0;
}
inline void Stop() {
}
inline void StartSim(const std::string &id , const std::string & simid, uint64_t Devices, const std::string & owner) {
std::lock_guard G(Mutex_);
CollectInfo_ = true;
ExpectedDevices_ = Devices;
Status_.id = id;
Status_.simulationId = simid;
Status_.state = "running";
Status_.liveDevices = Status_.endTime = Status_.rx =
Status_.tx = Status_.msgsTx = Status_.msgsRx = Status_.timeToFullDevices =
Status_.errorDevices = 0;
Status_.startTime = Utils::Now();
Status_.owner = owner;
}
inline void EndSim() {
std::lock_guard G(Mutex_);
CollectInfo_ = false;
Status_.state = "completed";
Status_.endTime = Utils::Now();
}
inline void SetState(const std::string &S) {
std::lock_guard G(Mutex_);
Status_.state = S;
}
[[nodiscard]] inline const std::string & GetState() {
std::lock_guard G(Mutex_);
return Status_.state;
}
[[nodiscard]] inline const std::string & Id() const {
return Status_.id;
}
inline void Reset() {
ExpectedDevices_ = Status_.liveDevices = Status_.tx = Status_.msgsRx = Status_.msgsTx = Status_.rx =
Status_.endTime = Status_.errorDevices = Status_.startTime = Status_.timeToFullDevices = 0;
Status_.simulationId = Status_.id = Status_.state = "";
}
[[nodiscard]] inline uint64_t GetStartTime() const { return Status_.startTime; }
[[nodiscard]] inline uint64_t GetLiveDevices() const { return Status_.liveDevices; }
private:
OWLSObjects::SimulationStatus Status_;
uint64_t ExpectedDevices_=0;
std::atomic_bool CollectInfo_=false;
SimStats() noexcept:
SubSystemServer("SimStats", "SIM-STATS", "stats")
{
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return;
}
};
stats_hint->second.msgsTx++;
stats_hint->second.tx += N;
}
inline SimStats * SimStats() { return SimStats::instance(); }
}
inline void AddInMsg(const std::string &id, int64_t N) {
std::lock_guard G(Mutex_);
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return;
}
stats_hint->second.rx += N;
stats_hint->second.msgsRx++;
}
inline void GetCurrent(const std::string &id, OWLSObjects::SimulationStatus &S,
const SecurityObjects::UserInfo & UInfo) {
std::lock_guard G(Mutex_);
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return;
}
if(UInfo.userRole==SecurityObjects::ROOT || UInfo.email==stats_hint->second.owner)
S = stats_hint->second;
}
inline int Start() final {
return 0;
}
inline void Stop() {
}
inline void StartSim(const std::string &id, const std::string &simid, uint64_t Devices,
const SecurityObjects::UserInfo & UInfo) {
std::lock_guard G(Mutex_);
auto & CurrentStatus = Status_[id];
CurrentStatus.expectedDevices = Devices;
CurrentStatus.id = id;
CurrentStatus.simulationId = simid;
CurrentStatus.state = "running";
CurrentStatus.liveDevices = CurrentStatus.endTime = CurrentStatus.rx = CurrentStatus.tx = CurrentStatus.msgsTx =
CurrentStatus.msgsRx = CurrentStatus.timeToFullDevices = CurrentStatus.errorDevices = 0;
CurrentStatus.startTime = Utils::Now();
CurrentStatus.owner = UInfo.email;
}
inline void EndSim(const std::string &id) {
std::lock_guard G(Mutex_);
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return;
}
stats_hint->second.state = "completed";
stats_hint->second.endTime = Utils::Now();
}
inline void RemoveSim(const std::string &id) {
std::lock_guard G(Mutex_);
Status_.erase(id);
}
inline void SetState(const std::string &id, const std::string &S) {
std::lock_guard G(Mutex_);
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return;
}
stats_hint->second.state = S;
}
[[nodiscard]] inline std::string GetState(const std::string &id) {
std::lock_guard G(Mutex_);
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return "";
}
return stats_hint->second.state;
}
inline void Reset(const std::string &id) {
std::lock_guard G(Mutex_);
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return;
}
stats_hint->second.liveDevices =
stats_hint->second.rx =
stats_hint->second.tx =
stats_hint->second.msgsRx =
stats_hint->second.msgsTx =
stats_hint->second.errorDevices =
stats_hint->second.startTime =
stats_hint->second.endTime = 0;
stats_hint->second.state = "idle";
}
[[nodiscard]] inline uint64_t GetStartTime(const std::string &id) {
std::lock_guard G(Mutex_);
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return 0;
}
return stats_hint->second.startTime;
}
[[nodiscard]] inline uint64_t GetLiveDevices(const std::string &id) {
std::lock_guard G(Mutex_);
auto stats_hint = Status_.find(id);
if(stats_hint==end(Status_)) {
return 0;
}
return stats_hint->second.liveDevices;
}
inline void GetAllSimulations(std::vector<OWLSObjects::SimulationStatus> & Statuses, const SecurityObjects::UserInfo & UInfo) {
Statuses.clear();
std::lock_guard G(Mutex_);
for(const auto &[id,status]:Status_) {
if(UInfo.userRole==SecurityObjects::ROOT || UInfo.email==status.owner) {
Statuses.emplace_back(status);
}
}
}
private:
std::map<std::string,OWLSObjects::SimulationStatus> Status_;
SimStats() noexcept : SubSystemServer("SimStats", "SIM-STATS", "stats") {}
};
inline auto SimStats() { return SimStats::instance(); }
} // namespace OpenWifi

View File

@@ -1,75 +0,0 @@
//
// Created by stephane bourque on 2021-11-03.
//
#pragma once
#include <chrono>
#include <random>
#include "framework/SubSystemServer.h"
#include "RESTObjects/RESTAPI_OWLSobjects.h"
#include "Simulator.h"
#include "nlohmann/json-schema.hpp"
namespace OpenWifi {
struct SimThread {
Poco::Thread Thread;
Simulator Sim;
SimThread(uint Index, std::string SerialBase, uint NumClients, Poco::Logger &L):
Sim(Index,std::move(SerialBase),NumClients,L) {};
};
class SimulationCoordinator : public SubSystemServer, Poco::Runnable {
public:
static SimulationCoordinator *instance() {
static auto * instance_ = new SimulationCoordinator;
return instance_;
}
int Start() final;
void Stop() final;
void run() final;
bool StartSim(const std::string &SimId, std::string & Id, std::string &Error, const std::string & Owner);
bool StopSim(const std::string &Id, std::string &Error);
bool CancelSim(const std::string &Id, std::string &Error);
[[nodiscard]] inline const OWLSObjects::SimulationDetails & GetSimulationInfo() {
return CurrentSim_;
}
[[nodiscard]] inline const std::string & GetCasLocation() { return CASLocation_; }
[[nodiscard]] inline const std::string & GetCertFileName() { return CertFileName_; }
[[nodiscard]] inline const std::string & GetKeyFileName() { return KeyFileName_; }
[[nodiscard]] inline const std::string & GetRootCAFileName() { return RootCAFileName_; }
[[nodiscard]] inline int GetLevel() const { return Level_; }
[[nodiscard]] const nlohmann::json & GetSimCapabilities() { return DefaultCapabilities_; }
[[nodiscard]] nlohmann::json GetSimConfiguration( uint64_t uuid );
private:
Poco::Thread Worker_;
std::atomic_bool Running_=false;
std::atomic_bool SimRunning_ = false;
std::vector<std::unique_ptr<SimThread>> SimThreads_;
OWLSObjects::SimulationDetails CurrentSim_;
std::string CASLocation_;
std::string CertFileName_;
std::string KeyFileName_;
std::string RootCAFileName_;
nlohmann::json DefaultCapabilities_;
int Level_=0;
SimulationCoordinator() noexcept:
SubSystemServer("SimulationCoordinator", "SIM-COORDINATOR", "coordinator")
{
}
void StartSimulators();
void StopSimulators();
void CancelSimulators();
};
inline SimulationCoordinator * SimulationCoordinator() { return SimulationCoordinator::instance(); }
}

View File

@@ -2,175 +2,189 @@
// Created by stephane bourque on 2021-11-03.
//
#include "Simulation.h"
#include "StorageService.h"
#include "SimStats.h"
#include <fmt/format.h>
#include <Poco/JSON/Parser.h>
#include <framework/MicroServiceFuncs.h>
#include <framework/utils.h>
#include "SimulationCoordinator.h"
#include "SimStats.h"
#include "StorageService.h"
#include "framework/MicroServiceFuncs.h"
#include "Poco/Environment.h"
#include "framework/utils.h"
#include "fmt/format.h"
namespace OpenWifi {
int SimulationCoordinator::Start() {
CASLocation_ = MicroServiceConfigPath("ucentral.cas","");
KeyFileName_ = MicroServiceConfigPath("ucentral.key","");
CertFileName_ = MicroServiceConfigPath("ucentral.cert","");
RootCAFileName_ = MicroServiceConfigPath("ucentral.rootca","");
std::string L = MicroServiceConfigGetString("ucentral.security","");
if (L == "strict") {
Level_ = Poco::Net::Context::VERIFY_STRICT;
} else if (L == "none") {
Level_ = Poco::Net::Context::VERIFY_NONE;
} else if (L == "relaxed") {
Level_ = Poco::Net::Context::VERIFY_RELAXED;
} else if (L == "once")
Level_ = Poco::Net::Context::VERIFY_ONCE;
Worker_.start(*this);
return 0;
}
int SimulationCoordinator::Start() {
CASLocation_ = MicroServiceConfigPath("ucentral.cas", "");
KeyFileName_ = MicroServiceConfigPath("ucentral.key", "");
CertFileName_ = MicroServiceConfigPath("ucentral.cert", "");
RootCAFileName_ = MicroServiceConfigPath("ucentral.rootca", "");
std::string L = MicroServiceConfigGetString("ucentral.security", "");
if (L == "strict") {
Level_ = Poco::Net::Context::VERIFY_STRICT;
} else if (L == "none") {
Level_ = Poco::Net::Context::VERIFY_NONE;
} else if (L == "relaxed") {
Level_ = Poco::Net::Context::VERIFY_RELAXED;
} else if (L == "once")
Level_ = Poco::Net::Context::VERIFY_ONCE;
Worker_.start(*this);
return 0;
}
void SimulationCoordinator::Stop() {
if(Running_) {
Running_ = false;
Worker_.wakeUp();
Worker_.join();
}
}
void SimulationCoordinator::Stop() {
if (Running_) {
Running_ = false;
Worker_.wakeUp();
Worker_.join();
void SimulationCoordinator::run() {
Running_ = true ;
while(Running_) {
Poco::Thread::trySleep(2000);
if(!Running_)
break;
if(SimStats()->GetState()!="running") {
continue;
std::lock_guard G(Mutex_);
for(auto &[_,simulation]:Simulations_) {
simulation->Runner.Stop();
}
Simulations_.clear();
}
}
uint64_t Now = Utils::Now();
if( CurrentSim_.simulationLength!=0 && (Now - SimStats()->GetStartTime()) > CurrentSim_.simulationLength ) {
std::string Error;
StopSim( SimStats()->Id(), Error );
void SimulationCoordinator::run() {
Running_ = true;
while (Running_) {
Poco::Thread::trySleep(20000);
if (!Running_)
break;
uint64_t Now = Utils::Now();
std::lock_guard G(Mutex_);
for(auto it = Simulations_.begin(); it!=end(Simulations_); ) {
const auto &id = it->first;
const auto &simulation = it->second;
if (simulation->Details.simulationLength != 0 &&
(Now - SimStats()->GetStartTime(id)) > simulation->Details.simulationLength) {
poco_information(Logger(),fmt::format("Simulation'{}' ({}) just completed.", simulation->Details.name,
simulation->Runner.Id()));
std::string Error;
simulation->Runner.Stop();
SimStats()->EndSim(id);
OWLSObjects::SimulationStatus S;
SimStats()->GetCurrent(id, S, simulation->UInfo);
StorageService()->SimulationResultsDB().CreateRecord(S);
SimStats()->RemoveSim(id);
it = Simulations_.erase(it);
} else {
poco_information(Logger(),fmt::format("Simulation'{}' ({}) still running.", simulation->Details.name,
simulation->Runner.Id()));
++it;
}
}
}
}
}
}
void SimulationCoordinator::StartSimulators() {
Logger().notice("Starting simulation threads...");
for(const auto &i:SimThreads_) {
i->Thread.start(i->Sim);
}
}
void SimulationCoordinator::CancelSimulations() {
Logger().notice("Cancel simulation threads...");
for (auto &[_,simulation] : Simulations_) {
simulation->Runner.Stop();
SimStats()->EndSim(simulation->Runner.Id());
}
Simulations_.clear();
}
void SimulationCoordinator::CancelSimulators() {
Logger().notice("Cancel simulation threads...");
SimStats()->EndSim();
for(const auto &i:SimThreads_) {
i->Sim.stop();
i->Thread.join();
void SimulationCoordinator::StopSimulations() {
Logger().notice("Stopping simulation threads...");
for (auto &[_,simulation] : Simulations_) {
simulation->Runner.Stop();
SimStats()->EndSim(simulation->Runner.Id());
}
SimThreads_.clear();
}
Simulations_.clear();
}
void SimulationCoordinator::StopSimulators() {
Logger().notice("Stopping simulation threads...");
SimStats()->EndSim();
for(const auto &i:SimThreads_) {
i->Sim.stop();
i->Thread.join();
}
SimThreads_.clear();
}
static const nlohmann::json DefaultCapabilities = R"(
static const std::string DefaultCapabilitiesStr = R"(
{"compatible":"edgecore_eap101","label_macaddr":"90:3c:b3:bb:1e:04","macaddr":{"lan":"90:3c:b3:bb:1e:05","wan":"90:3c:b3:bb:1e:04"},"model":"EdgeCore EAP101","network":{"lan":["eth1","eth2"],"wan":["eth0"]},"platform":"ap","switch":{"switch0":{"enable":false,"reset":false}},"wifi":{"platform/soc/c000000.wifi":{"band":["5G"],"channels":[36,40,44,48,52,56,60,64,100,104,108,112,116,120,124,128,132,136,140,144,149,153,157,161,165],"dfs_channels":[52,56,60,64,100,104,108,112,116,120,124,128,132,136,140,144],"frequencies":[5180,5200,5220,5240,5260,5280,5300,5320,5500,5520,5540,5560,5580,5600,5620,5640,5660,5680,5700,5720,5745,5765,5785,5805,5825],"he_mac_capa":[13,39432,4160],"he_phy_capa":[28700,34892,49439,1155,11265,0],"ht_capa":6639,"htmode":["HT20","HT40","VHT20","VHT40","VHT80","HE20","HE40","HE80","HE160","HE80+80"],"rx_ant":3,"tx_ant":3,"vht_capa":1939470770},"platform/soc/c000000.wifi+1":{"band":["2G"],"channels":[1,2,3,4,5,6,7,8,9,10,11],"frequencies":[2412,2417,2422,2427,2432,2437,2442,2447,2452,2457,2462],"he_mac_capa":[13,39432,4160],"he_phy_capa":[28674,34828,49439,1155,11265,0],"ht_capa":6639,"htmode":["HT20","HT40","VHT20","VHT40","VHT80","HE20","HE40"],"rx_ant":3,"tx_ant":3,"vht_capa":1939437970}}}
)"_json;
)";
bool SimulationCoordinator::StartSim(const std::string &SimId, [[maybe_unused]] std::string & Id, std::string &Error, const std::string & Owner) {
if(SimRunning_) {
Error = "Another simulation is already running.";
return false;
}
if(!StorageService()->SimulationDB().GetRecord("id",SimId,CurrentSim_)) {
Error = "Simulation ID specified does not exist.";
return false;
}
DefaultCapabilities_ = DefaultCapabilities;
DefaultCapabilities_["compatible"] = CurrentSim_.deviceType;
auto ClientCount = CurrentSim_.devices;
auto NumClientsPerThread = CurrentSim_.devices;
// create the actual simulation...
if(CurrentSim_.threads==0) {
CurrentSim_.threads = Poco::Environment::processorCount() * 4;
}
if(CurrentSim_.devices>250) {
if(CurrentSim_.devices % CurrentSim_.threads == 0)
{
NumClientsPerThread = CurrentSim_.devices / CurrentSim_.threads;
}
else
{
NumClientsPerThread = CurrentSim_.devices / (CurrentSim_.threads+1);
}
}
// Poco::Logger & ClientLogger = Poco::Logger::get("WS-CLIENT");
// ClientLogger.setLevel(Poco::Message::PRIO_WARNING);
for(auto i=0;ClientCount;i++)
{
auto Clients = std::min(ClientCount,NumClientsPerThread);
auto NewSimThread = std::make_unique<SimThread>(i,CurrentSim_.macPrefix,Clients, Logger());
NewSimThread->Sim.Initialize();
SimThreads_.push_back(std::move(NewSimThread));
ClientCount -= Clients;
}
StartSimulators();
SimRunning_ = true ;
SimStats()->StartSim(MicroServiceCreateUUID(), SimId, CurrentSim_.devices, Owner);
return true;
Poco::JSON::Object::Ptr SimulationCoordinator::GetSimCapabilitiesPtr() {
Poco::JSON::Object::Ptr Res;
Poco::JSON::Parser P;
Res = P.parse(DefaultCapabilitiesStr).extract<Poco::JSON::Object::Ptr>();
return Res;
}
bool SimulationCoordinator::StopSim([[maybe_unused]] const std::string &Id, std::string &Error) {
if(!SimRunning_) {
Error = "No simulation is running.";
bool SimulationCoordinator::IsSimulationRunning(const std::string &id) {
std::lock_guard G(Mutex_);
for(const auto &[instance_id,simulation]:Simulations_) {
if(simulation->Details.id==id)
return true;
}
return false;
}
bool SimulationCoordinator::StartSim(std::string &SimId, const std::string &Id,
RESTAPI::Errors::msg &Error, const SecurityObjects::UserInfo &UInfo) {
std::lock_guard G(Mutex_);
OWLSObjects::SimulationDetails NewSim;
if (!StorageService()->SimulationDB().GetRecord("id", Id, NewSim)) {
Error = RESTAPI::Errors::SimulationDoesNotExist;
return false;
}
DefaultCapabilities_ = GetSimCapabilitiesPtr();
DefaultCapabilities_->set("compatible", NewSim.deviceType);
SimId = MicroServiceCreateUUID();
auto NewSimulation = std::make_shared<SimulationRecord>(NewSim, Logger(), SimId, UInfo);
Simulations_[SimId] = NewSimulation;
Simulations_[SimId]->Runner.Start();
SimStats()->StartSim(SimId, Id, NewSim.devices, UInfo);
return true;
}
bool SimulationCoordinator::StopSim(const std::string &Id, RESTAPI::Errors::msg &Error, const SecurityObjects::UserInfo &UInfo) {
std::lock_guard G(Mutex_);
auto sim_hint = Simulations_.find(Id);
if(sim_hint==end(Simulations_)) {
Error = RESTAPI::Errors::SimulationDoesNotExist;
return false;
}
StopSimulators();
SimRunning_ = false;
if(UInfo.userRole==SecurityObjects::ROOT || UInfo.email==sim_hint->second->UInfo.email) {
sim_hint->second->Runner.Stop();
OWLSObjects::SimulationStatus S;
SimStats()->EndSim(sim_hint->second->Runner.Id());
SimStats()->GetCurrent(sim_hint->second->Runner.Id(), S, sim_hint->second->UInfo);
StorageService()->SimulationResultsDB().CreateRecord(S);
SimStats()->RemoveSim(sim_hint->second->Runner.Id());
Simulations_.erase(sim_hint);
return true;
}
Error = RESTAPI::Errors::ACCESS_DENIED;
return false;
}
OWLSObjects::SimulationStatus S;
SimStats()->GetCurrent(S);
StorageService()->SimulationResultsDB().CreateRecord(S);
bool SimulationCoordinator::CancelSim(const std::string &Id, RESTAPI::Errors::msg &Error, const SecurityObjects::UserInfo &UInfo) {
std::lock_guard G(Mutex_);
return true;
}
bool SimulationCoordinator::CancelSim([[maybe_unused]] const std::string &Id, std::string &Error) {
if(!SimRunning_) {
Error = "No simulation is running.";
auto sim_hint = Simulations_.find(Id);
if(sim_hint==end(Simulations_)) {
Error = RESTAPI::Errors::SimulationDoesNotExist;
return false;
}
CancelSimulators();
StopSimulators();
SimRunning_ = false;
SimStats()->SetState("none");
if(UInfo.userRole==SecurityObjects::ROOT || UInfo.email==sim_hint->second->UInfo.email) {
sim_hint->second->Runner.Stop();
SimStats()->SetState(sim_hint->second->Runner.Id(), "none");
SimStats()->RemoveSim(sim_hint->second->Runner.Id());
Simulations_.erase(sim_hint);
return true;
}
Error = RESTAPI::Errors::ACCESS_DENIED;
return false;
}
return true;
}
static const nlohmann::json DefaultConfiguration = R"~~~(
static const std::string DefaultConfigurationStr = R"~~~(
{
"interfaces": [
{
@@ -347,12 +361,16 @@ namespace OpenWifi {
},
"uuid": 1635660963
}
)~~~"_json;
)~~~";
nlohmann::json SimulationCoordinator::GetSimConfiguration( uint64_t uuid ) {
nlohmann::json Temp = DefaultConfiguration;
Temp["uuid"] = uuid;
return Temp;
Poco::JSON::Object::Ptr SimulationCoordinator::GetSimConfigurationPtr(uint64_t uuid) {
Poco::JSON::Object::Ptr res;
Poco::JSON::Parser P;
res = P.parse(DefaultConfigurationStr).extract<Poco::JSON::Object::Ptr>();
res->set("uuid", uuid);
return res;
}
}
} // namespace OpenWifi

View File

@@ -0,0 +1,93 @@
//
// Created by stephane bourque on 2021-11-03.
//
#pragma once
#include <chrono>
#include <random>
#include <framework/SubSystemServer.h>
#include <RESTObjects/RESTAPI_OWLSobjects.h>
#include <RESTObjects/RESTAPI_SecurityObjects.h>
#include "SimulationRunner.h"
namespace OpenWifi {
struct SimulationRecord {
SimulationRecord(const OWLSObjects::SimulationDetails & details,Poco::Logger &L, const std::string &id, const SecurityObjects::UserInfo &uinfo) :
Details(details),
Runner(details, L, id, uinfo),
UInfo(uinfo){
}
std::atomic_bool SimRunning = false;
OWLSObjects::SimulationDetails Details;
SimulationRunner Runner;
SecurityObjects::UserInfo UInfo;
};
class SimulationCoordinator : public SubSystemServer, Poco::Runnable {
public:
static auto instance() {
static auto instance_ = new SimulationCoordinator;
return instance_;
}
int Start() final;
void Stop() final;
void run() final;
bool StartSim(std::string &SimId, const std::string &Id, RESTAPI::Errors::msg &Error, const SecurityObjects::UserInfo &UInfo);
bool StopSim(const std::string &Id, RESTAPI::Errors::msg &Error, const SecurityObjects::UserInfo &UInfo);
bool CancelSim(const std::string &Id, RESTAPI::Errors::msg &Error, const SecurityObjects::UserInfo &UInfo);
[[nodiscard]] inline bool GetSimulationInfo( OWLSObjects::SimulationDetails & Details , const std::string &uuid = "" ) {
std::lock_guard G(Mutex_);
if(Simulations_.empty())
return false;
if(uuid.empty()) {
Details = Simulations_.begin()->second->Details;
return true;
}
auto sim_hint = Simulations_.find(uuid);
if(sim_hint==end(Simulations_))
return false;
Details = sim_hint->second->Details;
return true;
}
[[nodiscard]] inline const std::string &GetCasLocation() { return CASLocation_; }
[[nodiscard]] inline const std::string &GetCertFileName() { return CertFileName_; }
[[nodiscard]] inline const std::string &GetKeyFileName() { return KeyFileName_; }
[[nodiscard]] inline const std::string &GetRootCAFileName() { return RootCAFileName_; }
[[nodiscard]] inline int GetLevel() const { return Level_; }
[[nodiscard]] Poco::JSON::Object::Ptr GetSimConfigurationPtr(uint64_t uuid);
[[nodiscard]] Poco::JSON::Object::Ptr GetSimCapabilitiesPtr();
bool IsSimulationRunning(const std::string &id);
private:
Poco::Thread Worker_;
std::atomic_bool Running_ = false;
std::map<std::string,std::shared_ptr<SimulationRecord>> Simulations_;
std::string CASLocation_;
std::string CertFileName_;
std::string KeyFileName_;
std::string RootCAFileName_;
Poco::JSON::Object::Ptr DefaultCapabilities_;
int Level_ = 0;
SimulationCoordinator() noexcept
: SubSystemServer("SimulationCoordinator", "SIM-COORDINATOR", "coordinator") {}
void StopSimulations();
void CancelSimulations();
};
inline auto SimulationCoordinator() {
return SimulationCoordinator::instance();
}
} // namespace OpenWifi

256
src/SimulationRunner.cpp Normal file
View File

@@ -0,0 +1,256 @@
//
// Created by stephane bourque on 2021-03-13.
//
#include <random>
#include <thread>
#include <chrono>
#include <fmt/format.h>
#include <Poco/Logger.h>
#include <Poco/Net/NetException.h>
#include <Poco/Net/SSLException.h>
#include <Poco/NObserver.h>
#include "SimStats.h"
#include "SimulationRunner.h"
#include "UI_Owls_WebSocketNotifications.h"
namespace OpenWifi {
void SimulationRunner::Start() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(5, 25);
Running_ = true;
std::lock_guard Lock(Mutex_);
NumberOfReactors_ = Poco::Environment::processorCount() * 2;
for(std::uint64_t i=0;i<NumberOfReactors_;i++) {
auto NewReactor = std::make_unique<Poco::Net::SocketReactor>();
auto NewReactorThread = std::make_unique<Poco::Thread>();
NewReactorThread->start(*NewReactor);
SocketReactorPool_.push_back(std::move(NewReactor));
SocketReactorThreadPool_.push_back(std::move(NewReactorThread));
}
std::uint64_t ReactorIndex=0;
for (uint64_t i = 0; i < Details_.devices; i++) {
char Buffer[32];
snprintf(Buffer, sizeof(Buffer), "%s%05x0", Details_.macPrefix.c_str(), (unsigned int)i);
auto Client = std::make_shared<OWLSclient>(Buffer, Logger_, this, *SocketReactorPool_[ReactorIndex++ % NumberOfReactors_]);
Client->SerialNumber_ = Buffer;
Client->Valid_ = true;
Scheduler_.in(std::chrono::seconds(distrib(gen)), OWLSClientEvents::EstablishConnection, Client, this);
Clients_[Buffer] = Client;
}
UpdateTimerCallback_ = std::make_unique<Poco::TimerCallback<SimulationRunner>>(
*this, &SimulationRunner::onUpdateTimer);
UpdateTimer_.setStartInterval(10000);
UpdateTimer_.setPeriodicInterval(2 * 1000);
UpdateTimer_.start(*UpdateTimerCallback_, MicroServiceTimerPool());
}
void SimulationRunner::onUpdateTimer([[maybe_unused]] Poco::Timer &timer) {
if(Running_) {
OWLSNotifications::SimulationUpdate_t Notification;
SimStats()->GetCurrent(Id_, Notification.content, UInfo_);
OWLSNotifications::SimulationUpdate(Notification);
++StatsUpdates_;
if((StatsUpdates_ % 15) == 0) {
std::lock_guard Lock(Mutex_);
for(auto &client:Clients_) {
if(!Running_) {
return;
}
if(client.second->Mutex_.try_lock()) {
if (client.second->Connected_) {
client.second->Update();
}
client.second->Mutex_.unlock();
}
}
}
}
}
void SimulationRunner::ProgressUpdate(SimulationRunner *sim) {
if(sim->Running_) {
OWLSNotifications::SimulationUpdate_t Notification;
SimStats()->GetCurrent(sim->Id_, Notification.content, sim->UInfo_);
OWLSNotifications::SimulationUpdate(Notification);
// sim->Scheduler_.in(std::chrono::seconds(10), ProgressUpdate, sim);
}
}
void SimulationRunner::Stop() {
if (Running_) {
Running_ = false;
UpdateTimer_.stop();
std::lock_guard Guard(Mutex_);
std::for_each(SocketReactorPool_.begin(),SocketReactorPool_.end(),[](auto &reactor) { reactor->stop(); });
std::for_each(SocketReactorThreadPool_.begin(),SocketReactorThreadPool_.end(),[](auto &t){ t->join(); });
SocketReactorThreadPool_.clear();
SocketReactorPool_.clear();
Clients_.clear();
}
}
void SimulationRunner::OnSocketError(const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf) {
std::lock_guard G(Mutex_);
std::cout << "SimulationRunner::OnSocketError" << std::endl;
auto socket = pNf->socket().impl()->sockfd();
std::map<std::int64_t, std::shared_ptr<OWLSclient>>::iterator client_hint;
std::shared_ptr<OWLSclient> client;
{
std::lock_guard GG(SocketFdMutex_);
client_hint = Clients_fd_.find(socket);
if (client_hint == end(Clients_fd_)) {
pNf->socket().impl()->close();
poco_warning(Logger_, fmt::format("{}: Invalid socket", socket));
return;
}
client = client_hint->second;
}
{
std::lock_guard Guard(client->Mutex_);
client->Disconnect(__func__, Guard);
}
if (Running_) {
OWLSClientEvents::Reconnect(client, this);
}
}
void SimulationRunner::OnSocketShutdown(const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf) {
auto socket = pNf->socket().impl()->sockfd();
std::shared_ptr<OWLSclient> client;
{
std::lock_guard G(SocketFdMutex_);
auto client_hint = Clients_fd_.find(socket);
if (client_hint == end(Clients_fd_)) {
pNf->socket().impl()->close();
poco_warning(Logger_, fmt::format("{}: Invalid socket", socket));
return;
}
client = client_hint->second;
}
{
std::lock_guard Guard(client->Mutex_);
client->Disconnect(__func__ , Guard);
}
if(Running_)
OWLSClientEvents::Reconnect(client,this);
}
void SimulationRunner::OnSocketReadable(const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf) {
std::shared_ptr<OWLSclient> client;
int socket;
{
std::lock_guard G(SocketFdMutex_);
socket = pNf->socket().impl()->sockfd();
auto client_hint = Clients_fd_.find(socket);
if (client_hint == end(Clients_fd_)) {
poco_warning(Logger_, fmt::format("{}: Invalid socket", socket));
return;
}
client = client_hint->second;
}
std::lock_guard Guard(client->Mutex_);
try {
Poco::Buffer<char> IncomingFrame(0);
int Flags;
auto MessageSize = client->WS_->receiveFrame(IncomingFrame, Flags);
auto Op = Flags & Poco::Net::WebSocket::FRAME_OP_BITMASK;
if (MessageSize == 0 && Flags == 0 && Op == 0) {
OWLSClientEvents::Disconnect(__func__, Guard, client, this, "Error while waiting for data in WebSocket", true);
return;
}
IncomingFrame.append(0);
switch (Op) {
case Poco::Net::WebSocket::FRAME_OP_PING: {
client->WS_->sendFrame("", 0,
Poco::Net::WebSocket::FRAME_OP_PONG |
Poco::Net::WebSocket::FRAME_FLAG_FIN);
} break;
case Poco::Net::WebSocket::FRAME_OP_PONG: {
} break;
case Poco::Net::WebSocket::FRAME_OP_TEXT: {
if (MessageSize > 0) {
SimStats()->AddInMsg(Id_, MessageSize);
Poco::JSON::Parser parser;
auto Frame = parser.parse(IncomingFrame.begin()).extract<Poco::JSON::Object::Ptr>();
if (Frame->has("jsonrpc") && Frame->has("id") &&
Frame->has("method") && Frame->has("params")) {
ProcessCommand(Guard,client, Frame);
} else {
Logger_.warning(
fmt::format("MESSAGE({}): invalid incoming message.", client->SerialNumber_));
}
}
} break;
default: {
} break;
}
return;
} catch (const Poco::Net::SSLException &E) {
Logger_.warning(
fmt::format("Exception({}): SSL exception: {}", client->SerialNumber_, E.displayText()));
} catch (const Poco::Exception &E) {
Logger_.warning(fmt::format("Exception({}): Generic exception: {}", client->SerialNumber_,
E.displayText()));
}
OWLSClientEvents::Disconnect(__func__, Guard,client, this, "Error while waiting for data in WebSocket", true);
}
void SimulationRunner::ProcessCommand(std::lock_guard<std::mutex> &ClientGuard, const std::shared_ptr<OWLSclient> & Client, Poco::JSON::Object::Ptr Frame) {
std::string Method = Frame->get("method");
std::uint64_t Id = Frame->get("id");
auto Params = Frame->getObject("params");
if (Method == "configure") {
CensusReport_.ev_configure++;
std::thread t(OWLSclient::DoConfigure,Client, Id, Params);
t.detach();
} else if (Method == "reboot") {
CensusReport_.ev_reboot++;
std::thread t(OWLSclient::DoReboot, Client, Id, Params);
t.detach();
} else if (Method == "upgrade") {
CensusReport_.ev_firmwareupgrade++;
std::thread t(OWLSclient::DoUpgrade, Client, Id, Params);
t.detach();
} else if (Method == "factory") {
CensusReport_.ev_factory++;
std::thread t(OWLSclient::DoFactory, Client, Id, Params);
t.detach();
} else if (Method == "leds") {
CensusReport_.ev_leds++;
std::thread t(OWLSclient::DoLEDs, Client, Id, Params);
t.detach();
} else {
Logger_.warning(fmt::format("COMMAND({}): unknown method '{}'", Client->SerialNumber_, Method));
Client->UnSupportedCommand(ClientGuard,Client, Id, Method);
}
}
} // namespace OpenWifi

85
src/SimulationRunner.h Normal file
View File

@@ -0,0 +1,85 @@
//
// Created by stephane bourque on 2021-03-13.
//
#pragma once
#include <map>
#include <set>
#include <string>
#include <Poco/Thread.h>
#include <Poco/Environment.h>
#include <Poco/Timer.h>
#include <RESTObjects/RESTAPI_OWLSobjects.h>
#include <libs/Scheduler.h>
#include <RESTObjects/RESTAPI_SecurityObjects.h>
#include "OWLSclient.h"
#include "CensusReport.h"
namespace OpenWifi {
class SimulationRunner {
public:
explicit SimulationRunner(const OWLSObjects::SimulationDetails &Details, Poco::Logger &L, const std::string &id, const SecurityObjects::UserInfo &uinfo)
: Details_(Details), Logger_(L), Id_(id)
, Scheduler_(Poco::Environment::processorCount()*16)
, UInfo_(uinfo){
}
void Stop();
void Start();
inline const OWLSObjects::SimulationDetails & Details() const { return Details_; }
CensusReport & Report() { return CensusReport_; }
void OnSocketReadable(const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf);
void OnSocketError(const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf);
void OnSocketShutdown(const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf);
const std::string & Id() const { return Id_; }
inline void AddClientFd(std::int64_t fd, const std::shared_ptr<OWLSclient> &c) {
std::lock_guard G(SocketFdMutex_);
Clients_fd_[fd] = c;
}
inline void RemoveClientFd(std::int64_t fd) {
std::lock_guard G(SocketFdMutex_);
Clients_fd_.erase(fd);
}
void ProcessCommand(std::lock_guard<std::mutex> &G, const std::shared_ptr<OWLSclient> &Client, Poco::JSON::Object::Ptr Vars);
inline auto & Scheduler() { return Scheduler_; }
inline bool Running() { return Running_; }
void onUpdateTimer(Poco::Timer &timer);
private:
std::mutex SocketFdMutex_;
my_mutex Mutex_;
OWLSObjects::SimulationDetails Details_;
Poco::Logger &Logger_;
std::vector<std::unique_ptr<Poco::Net::SocketReactor>> SocketReactorPool_;
std::vector<std::unique_ptr<Poco::Thread>> SocketReactorThreadPool_;
std::map<std::string, std::shared_ptr<OWLSclient>> Clients_;
std::map<std::int64_t, std::shared_ptr<OWLSclient>> Clients_fd_;
std::atomic_bool Running_ = false;
CensusReport CensusReport_;
std::string State_{"stopped"};
std::string Id_;
Bosma::Scheduler Scheduler_;
SecurityObjects::UserInfo UInfo_;
std::uint64_t NumberOfReactors_=0;
std::uint64_t StatsUpdates_=0;
Poco::Timer UpdateTimer_;
std::unique_ptr<Poco::TimerCallback<SimulationRunner>> UpdateTimerCallback_;
static void ProgressUpdate(SimulationRunner *s);
};
} // namespace OpenWifi

View File

@@ -1,219 +0,0 @@
//
// Created by stephane bourque on 2021-03-13.
//
#include <thread>
#include <random>
#include "Poco/Logger.h"
#include "Simulator.h"
#include "uCentralEvent.h"
#include "SimStats.h"
#include "fmt/format.h"
#include "UI_Owls_WebSocketNotifications.h"
namespace OpenWifi {
void Simulator::Initialize(/*Poco::Logger &ClientLogger*/) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(1, 15);
std::lock_guard Lock(Mutex_);
for(uint64_t i=0;i<NumClients_;i++)
{
char Buffer[32];
snprintf(Buffer,sizeof(Buffer),"%s%02x%03x0",SerialStart_.c_str(),(unsigned int)Index_,(unsigned int)i);
auto Client = std::make_shared<uCentralClient>( Reactor_,
Buffer,
Logger_);
Client->AddEvent(ev_reconnect, distrib(gen) );
Clients_[Buffer] = std::move(Client);
}
}
void Simulator::stop() {
if(Running_) {
Running_ = false;
Reactor_.stop();
SocketReactorThread_.join();
}
}
void Simulator::run() {
Logger_.notice(fmt::format("Starting reactor {}...",Index_));
Running_ = true;
SocketReactorThread_.start(Reactor_);
while(Running_)
{
// wake up every quarter second
Poco::Thread::sleep(1000);
if(State_=="paused")
continue;
if(State_=="cancel")
break;
my_guard Lock(Mutex_);
try {
CensusReport_.Reset();
for (const auto &i:Clients_)
i.second->DoCensus(CensusReport_);
for (const auto &i:Clients_) {
auto Client = i.second;
auto Event = Client->NextEvent(false);
switch (Event) {
case ev_none: {
// nothing to do
}
break;
case ev_reconnect: {
Logger_.information(fmt::format("reconnect({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
Client->EstablishConnection();
});
T.detach();
}
break;
case ev_connect: {
Logger_.information(fmt::format("connect({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
ConnectEvent E(Client);
E.Send();
});
T.detach();
}
break;
case ev_healthcheck: {
Logger_.information(fmt::format("healthcheck({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
HealthCheckEvent E(Client);
E.Send();
});
T.detach();
}
break;
case ev_state: {
Logger_.information(fmt::format("state({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
StateEvent E(Client);
E.Send();
});
T.detach();
}
break;
case ev_log: {
Logger_.information(fmt::format("log({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
LogEvent E(Client, std::string("log"), 2);
E.Send();
});
T.detach();
}
break;
case ev_crashlog: {
Logger_.information(fmt::format("crash-log({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
CrashLogEvent E(Client);
E.Send();
});
T.detach();
}
break;
case ev_configpendingchange: {
Logger_.information(fmt::format("pendingchange({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
ConfigChangePendingEvent E(Client);
E.Send();
});
T.detach();
}
break;
case ev_keepalive: {
Logger_.information(fmt::format("keepalive({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
KeepAliveEvent E(Client);
E.Send();
});
T.detach();
}
break;
case ev_reboot: {
Logger_.information(fmt::format("reboot({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
RebootEvent E(Client);
E.Send();
});
T.detach();
}
break;
case ev_disconnect: {
Logger_.information(fmt::format("disconnect({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
DisconnectEvent E(Client);
E.Send();
});
T.detach();
}
break;
case ev_wsping: {
Logger_.information(fmt::format("ws-ping({}): ", Client->Serial()));
std::thread T([Client]() {
Client->NextEvent(true);
WSPingEvent E(Client);
E.Send();
});
T.detach();
}
break;
}
}
OWLSNotifications::SimulationUpdate_t Notification;
SimStats()->GetCurrent(Notification.content);
OWLSNotifications::SimulationUpdate(Notification);
} catch ( const Poco::Exception & E) {
Logger_.warning(fmt::format("SIMULATOR({}): Crashed. Poco exception:{}",Index_,E.displayText()));
} catch ( const std::exception & E ) {
std::string S = E.what();
Logger_.warning(fmt::format("SIMULATOR({}): Crashed. std::exception:{}",Index_,S));
}
}
for(auto &[Key,Client]:Clients_) {
Client->Disconnect("Simulation termination", false);
}
Clients_.clear();
Logger_.notice(fmt::format("Stopped reactor {}...",Index_));
}
}

View File

@@ -1,46 +0,0 @@
//
// Created by stephane bourque on 2021-03-13.
//
#pragma once
#include <string>
#include <map>
#include <set>
#include "Poco/Thread.h"
#include "uCentralClient.h"
namespace OpenWifi {
class Simulator : public Poco::Runnable {
public:
Simulator(uint64_t Index,std::string SerialStart, uint64_t NumClients, Poco::Logger &L) :
Logger_(L),
Index_(Index),
SerialStart_(std::move(SerialStart)),
NumClients_(NumClients)
{
}
void run() override;
void stop();
void Initialize(/* Poco::Logger & ClientLogger*/);
void Cancel() { State_ = "cancel"; SocketReactorThread_.wakeUp(); }
private:
Poco::Logger &Logger_;
my_mutex Mutex_;
Poco::Net::SocketReactor Reactor_;
std::map<std::string,std::shared_ptr<uCentralClient>> Clients_;
Poco::Thread SocketReactorThread_;
std::atomic_bool Running_ = false;
uint64_t Index_ = 0 ;
std::string SerialStart_;
uint64_t NumClients_ = 0 ;
CensusReport CensusReport_;
std::string State_{"stopped"};
};
}

View File

@@ -11,25 +11,26 @@
namespace OpenWifi {
int Storage::Start() {
std::lock_guard Guard(Mutex_);
std::lock_guard Guard(Mutex_);
Logger().notice("Starting.");
StorageClass::Start();
SimulationDB_ = std::make_unique<OpenWifi::SimulationDB>(dbType_,*Pool_, Logger());
SimulationDB_ = std::make_unique<OpenWifi::SimulationDB>(dbType_, *Pool_, Logger());
SimulationDB_->Create();
SimulationResultsDB_ = std::make_unique<OpenWifi::SimulationResultsDB>(dbType_,*Pool_, Logger());
SimulationResultsDB_ =
std::make_unique<OpenWifi::SimulationResultsDB>(dbType_, *Pool_, Logger());
SimulationResultsDB_->Create();
return 0;
}
return 0;
}
void Storage::Stop() {
std::lock_guard Guard(Mutex_);
Logger().notice("Stopping.");
std::lock_guard Guard(Mutex_);
Logger().notice("Stopping.");
StorageClass::Stop();
}
}
StorageClass::Stop();
}
} // namespace OpenWifi
// namespace

View File

@@ -8,30 +8,30 @@
#pragma once
#include "framework/StorageClass.h"
#include "storage/storage_simulations.h"
#include "storage/storage_results.h"
#include <framework/StorageClass.h>
#include <storage/storage_results.h>
#include <storage/storage_simulations.h>
namespace OpenWifi {
class Storage : public StorageClass {
public:
static Storage *instance() {
static auto * instance_ = new Storage;
return instance_;
}
class Storage : public StorageClass {
public:
static Storage *instance() {
static auto *instance_ = new Storage;
return instance_;
}
OpenWifi::SimulationDB & SimulationDB() { return *SimulationDB_; }
OpenWifi::SimulationResultsDB & SimulationResultsDB() { return *SimulationResultsDB_; }
OpenWifi::SimulationDB &SimulationDB() { return *SimulationDB_; }
OpenWifi::SimulationResultsDB &SimulationResultsDB() { return *SimulationResultsDB_; }
int Start() override;
void Stop() override;
int Start() override;
void Stop() override;
private:
std::unique_ptr<OpenWifi::SimulationDB> SimulationDB_;
std::unique_ptr<OpenWifi::SimulationResultsDB> SimulationResultsDB_;
};
private:
std::unique_ptr<OpenWifi::SimulationDB> SimulationDB_;
std::unique_ptr<OpenWifi::SimulationResultsDB> SimulationResultsDB_;
};
inline class Storage * StorageService() { return Storage::instance(); }
inline class Storage *StorageService() { return Storage::instance(); }
} // namespace
} // namespace OpenWifi

View File

@@ -2,26 +2,26 @@
// Created by stephane bourque on 2022-10-30.
//
#include "UI_Owls_WebSocketNotifications.h"
#include "framework/UI_WebSocketClientServer.h"
#include <framework/UI_WebSocketClientServer.h>
#include <UI_Owls_WebSocketNotifications.h>
namespace OpenWifi::OWLSNotifications {
void SimulationUpdate( SimulationUpdate_t &N) {
N.type_id = 1000;
UI_WebSocketClientServer()->SendNotification(N);
}
void SimulationUpdate(SimulationUpdate_t &N) {
N.type_id = 1000;
UI_WebSocketClientServer()->SendNotification(N);
}
void SimulationUpdate( const std::string & User, SimulationUpdate_t &N) {
N.type_id = 1000;
UI_WebSocketClientServer()->SendUserNotification(User,N);
}
void SimulationUpdate(const std::string &User, SimulationUpdate_t &N) {
N.type_id = 1000;
UI_WebSocketClientServer()->SendUserNotification(User, N);
}
void Register() {
static const UI_WebSocketClientServer::NotificationTypeIdVec Notifications = {
{ 1000, "owls_simulation_update" }
};
void Register() {
static const UI_WebSocketClientServer::NotificationTypeIdVec Notifications = {
{1000, "owls_simulation_update"}};
UI_WebSocketClientServer()->RegisterNotifications(Notifications);
}
} // OpenWifi
UI_WebSocketClientServer()->RegisterNotifications(Notifications);
}
} // namespace OpenWifi::OWLSNotifications

View File

@@ -4,17 +4,16 @@
#pragma once
#include "framework/UI_WebSocketClientNotifications.h"
#include "RESTObjects/RESTAPI_OWLSobjects.h"
#include <framework/UI_WebSocketClientNotifications.h>
#include <RESTObjects/RESTAPI_OWLSobjects.h>
namespace OpenWifi::OWLSNotifications {
typedef WebSocketNotification<OpenWifi::OWLSObjects::SimulationStatus> SimulationUpdate_t;
typedef WebSocketNotification<OpenWifi::OWLSObjects::SimulationStatus> SimulationUpdate_t;
void Register();
void Register();
void SimulationUpdate( SimulationUpdate_t &N);
void SimulationUpdate( const std::string & User, SimulationUpdate_t &N);
} // OpenWifi
void SimulationUpdate(SimulationUpdate_t &N);
void SimulationUpdate(const std::string &User, SimulationUpdate_t &N);
} // namespace OpenWifi::OWLSNotifications

View File

@@ -4,17 +4,19 @@
#include "ALBserver.h"
#include "framework/utils.h"
#include "framework/MicroServiceFuncs.h"
#include "fmt/format.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h"
namespace OpenWifi {
void ALBRequestHandler::handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) {
void ALBRequestHandler::handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest &Request,
Poco::Net::HTTPServerResponse &Response) {
Utils::SetThreadName("alb-request");
try {
if((id_ % 100) == 0) {
Logger_.debug(fmt::format("ALB-REQUEST({}): ALB Request {}.", Request.clientAddress().toString(), id_));
if ((id_ % 100) == 0) {
Logger_.debug(fmt::format("ALB-REQUEST({}): ALB Request {}.",
Request.clientAddress().toString(), id_));
}
Response.setChunkedTransferEncoding(true);
Response.setContentType("text/html");
@@ -24,33 +26,29 @@ namespace OpenWifi {
Response.set("Connection", "keep-alive");
Response.setVersion(Poco::Net::HTTPMessage::HTTP_1_1);
std::ostream &Answer = Response.send();
Answer << "process Alive and kicking!";
Answer << ALBHealthCheckServer()->CallbackText();
} catch (...) {
}
}
ALBRequestHandlerFactory::ALBRequestHandlerFactory(Poco::Logger & L):
Logger_(L) {
}
ALBRequestHandlerFactory::ALBRequestHandlerFactory(Poco::Logger &L) : Logger_(L) {}
ALBRequestHandler* ALBRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest& request) {
ALBRequestHandler *
ALBRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &request) {
if (request.getURI() == "/")
return new ALBRequestHandler(Logger_, req_id_++);
else
return nullptr;
}
ALBHealthCheckServer::ALBHealthCheckServer() :
SubSystemServer("ALBHealthCheckServer", "ALB-SVR", "alb")
{
}
ALBHealthCheckServer::ALBHealthCheckServer()
: SubSystemServer("ALBHealthCheckServer", "ALB-SVR", "alb") {}
int ALBHealthCheckServer::Start() {
if(MicroServiceConfigGetBool("alb.enable",false)) {
poco_information(Logger(),"Starting...");
Running_=true;
Port_ = (int)MicroServiceConfigGetInt("alb.port",15015);
if (MicroServiceConfigGetBool("alb.enable", false)) {
poco_information(Logger(), "Starting...");
Running_ = true;
Port_ = (int)MicroServiceConfigGetInt("alb.port", 15015);
Poco::Net::IPAddress Addr(Poco::Net::IPAddress::wildcard(
Poco::Net::Socket::supportsIPv6() ? Poco::Net::AddressFamily::IPv6
: Poco::Net::AddressFamily::IPv4));
@@ -60,7 +58,8 @@ namespace OpenWifi {
Socket_ = std::make_unique<Poco::Net::ServerSocket>(SockAddr, Port_);
auto Params = new Poco::Net::HTTPServerParams;
Params->setName("ws:alb");
Server_ = std::make_unique<Poco::Net::HTTPServer>(new ALBRequestHandlerFactory(Logger()), *Socket_, Params);
Server_ = std::make_unique<Poco::Net::HTTPServer>(
new ALBRequestHandlerFactory(Logger()), *Socket_, Params);
Server_->start();
}
@@ -68,10 +67,10 @@ namespace OpenWifi {
}
void ALBHealthCheckServer::Stop() {
poco_information(Logger(),"Stopping...");
if(Running_)
poco_information(Logger(), "Stopping...");
if (Running_)
Server_->stopAll(true);
poco_information(Logger(),"Stopped...");
poco_information(Logger(), "Stopped...");
}
} // namespace OpenWifi

View File

@@ -7,37 +7,38 @@
#include "framework/SubSystemServer.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
namespace OpenWifi {
class ALBRequestHandler: public Poco::Net::HTTPRequestHandler {
class ALBRequestHandler : public Poco::Net::HTTPRequestHandler {
public:
explicit ALBRequestHandler(Poco::Logger & L, uint64_t id)
: Logger_(L), id_(id) {
}
explicit ALBRequestHandler(Poco::Logger &L, uint64_t id) : Logger_(L), id_(id) {}
void handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) override;
void handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest &Request,
Poco::Net::HTTPServerResponse &Response) override;
private:
Poco::Logger & Logger_;
uint64_t id_;
Poco::Logger &Logger_;
uint64_t id_;
};
class ALBRequestHandlerFactory: public Poco::Net::HTTPRequestHandlerFactory
{
class ALBRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
public:
explicit ALBRequestHandlerFactory(Poco::Logger & L);
ALBRequestHandler* createRequestHandler(const Poco::Net::HTTPServerRequest& request) override;
explicit ALBRequestHandlerFactory(Poco::Logger &L);
ALBRequestHandler *
createRequestHandler(const Poco::Net::HTTPServerRequest &request) override;
private:
Poco::Logger &Logger_;
inline static std::atomic_uint64_t req_id_=1;
Poco::Logger &Logger_;
inline static std::atomic_uint64_t req_id_ = 1;
};
typedef std::string ALBHealthMessageCallback();
class ALBHealthCheckServer : public SubSystemServer {
public:
ALBHealthCheckServer();
@@ -49,15 +50,26 @@ namespace OpenWifi {
int Start() override;
void Stop() override;
inline void RegisterExtendedHealthMessage(ALBHealthMessageCallback *F) {
Callback_=F;
};
inline std::string CallbackText() {
if(Callback_== nullptr) {
return "process Alive and kicking!";
} else {
return Callback_();
}
}
private:
std::unique_ptr<Poco::Net::HTTPServer> Server_;
std::unique_ptr<Poco::Net::ServerSocket> Socket_;
int Port_ = 0;
mutable std::atomic_bool Running_=false;
std::unique_ptr<Poco::Net::HTTPServer> Server_;
std::unique_ptr<Poco::Net::ServerSocket> Socket_;
ALBHealthMessageCallback *Callback_= nullptr;
int Port_ = 0;
mutable std::atomic_bool Running_ = false;
};
inline auto ALBHealthCheckServer() { return ALBHealthCheckServer::instance(); }
} // namespace OpenWifi

View File

@@ -4,96 +4,94 @@
#pragma once
#include "Poco/Logger.h"
#include "Poco/JSON/Parser.h"
#include "Poco/Logger.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/URI.h"
#include "framework/MicroServiceFuncs.h"
namespace OpenWifi {
inline void API_Proxy( Poco::Logger &Logger,
Poco::Net::HTTPServerRequest *Request,
Poco::Net::HTTPServerResponse *Response,
const char * ServiceType,
const char * PathRewrite,
uint64_t msTimeout_ = 10000 ) {
try {
auto Services = MicroServiceGetServices(ServiceType);
for(auto const &Svc:Services) {
Poco::URI SourceURI(Request->getURI());
Poco::URI DestinationURI(Svc.PrivateEndPoint);
DestinationURI.setPath(PathRewrite);
DestinationURI.setQuery(SourceURI.getQuery());
inline void API_Proxy(Poco::Logger &Logger, Poco::Net::HTTPServerRequest *Request,
Poco::Net::HTTPServerResponse *Response, const char *ServiceType,
const char *PathRewrite, uint64_t msTimeout_ = 10000) {
try {
auto Services = MicroServiceGetServices(ServiceType);
for (auto const &Svc : Services) {
Poco::URI SourceURI(Request->getURI());
Poco::URI DestinationURI(Svc.PrivateEndPoint);
DestinationURI.setPath(PathRewrite);
DestinationURI.setQuery(SourceURI.getQuery());
// std::cout << " Source: " << SourceURI.toString() << std::endl;
// std::cout << "Destination: " << DestinationURI.toString() << std::endl;
// std::cout << " Source: " << SourceURI.toString() << std::endl;
// std::cout << "Destination: " << DestinationURI.toString() << std::endl;
Poco::Net::HTTPSClientSession Session(DestinationURI.getHost(), DestinationURI.getPort());
Session.setKeepAlive(true);
Session.setTimeout(Poco::Timespan(msTimeout_/1000, msTimeout_ % 1000));
Poco::Net::HTTPRequest ProxyRequest(Request->getMethod(),
DestinationURI.getPathAndQuery(),
Poco::Net::HTTPMessage::HTTP_1_1);
if(Request->has("Authorization")) {
ProxyRequest.add("Authorization", Request->get("Authorization"));
} else {
ProxyRequest.add("X-API-KEY", Svc.AccessKey);
ProxyRequest.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
}
Poco::Net::HTTPSClientSession Session(DestinationURI.getHost(),
DestinationURI.getPort());
Session.setKeepAlive(true);
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Poco::Net::HTTPRequest ProxyRequest(Request->getMethod(),
DestinationURI.getPathAndQuery(),
Poco::Net::HTTPMessage::HTTP_1_1);
if (Request->has("Authorization")) {
ProxyRequest.add("Authorization", Request->get("Authorization"));
} else {
ProxyRequest.add("X-API-KEY", Svc.AccessKey);
ProxyRequest.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
}
if(Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE) {
Session.sendRequest(ProxyRequest);
Poco::Net::HTTPResponse ProxyResponse;
Session.receiveResponse(ProxyResponse);
Response->setStatus(ProxyResponse.getStatus());
Response->send();
return;
} else {
Poco::JSON::Parser P;
std::stringstream SS;
try {
auto Body = P.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>();
Poco::JSON::Stringifier::condense(Body,SS);
SS << "\r\n\r\n";
} catch(const Poco::Exception &E) {
Logger.log(E);
}
if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE) {
Session.sendRequest(ProxyRequest);
Poco::Net::HTTPResponse ProxyResponse;
Session.receiveResponse(ProxyResponse);
Response->setStatus(ProxyResponse.getStatus());
Response->send();
return;
} else {
Poco::JSON::Parser P;
std::stringstream SS;
try {
auto Body = P.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>();
Poco::JSON::Stringifier::condense(Body, SS);
SS << "\r\n\r\n";
} catch (const Poco::Exception &E) {
Logger.log(E);
}
if(SS.str().empty()) {
Session.sendRequest(ProxyRequest);
} else {
ProxyRequest.setContentType("application/json");
ProxyRequest.setContentLength(SS.str().size());
std::ostream & os = Session.sendRequest(ProxyRequest);
os << SS.str() ;
}
if (SS.str().empty()) {
Session.sendRequest(ProxyRequest);
} else {
ProxyRequest.setContentType("application/json");
ProxyRequest.setContentLength(SS.str().size());
std::ostream &os = Session.sendRequest(ProxyRequest);
os << SS.str();
}
Poco::Net::HTTPResponse ProxyResponse;
std::stringstream SSR;
try {
std::istream &ProxyResponseStream = Session.receiveResponse(ProxyResponse);
Poco::JSON::Parser P2;
auto ProxyResponseBody = P2.parse(ProxyResponseStream).extract<Poco::JSON::Object::Ptr>();
Poco::JSON::Stringifier::condense(ProxyResponseBody,SSR);
Response->setContentType("application/json");
Response->setContentLength(SSR.str().size());
Response->setStatus(ProxyResponse.getStatus());
Response->sendBuffer(SSR.str().c_str(),SSR.str().size());
return;
} catch( const Poco::Exception & E) {
Poco::Net::HTTPResponse ProxyResponse;
std::stringstream SSR;
try {
std::istream &ProxyResponseStream = Session.receiveResponse(ProxyResponse);
Poco::JSON::Parser P2;
auto ProxyResponseBody =
P2.parse(ProxyResponseStream).extract<Poco::JSON::Object::Ptr>();
Poco::JSON::Stringifier::condense(ProxyResponseBody, SSR);
Response->setContentType("application/json");
Response->setContentLength(SSR.str().size());
Response->setStatus(ProxyResponse.getStatus());
Response->sendBuffer(SSR.str().c_str(), SSR.str().size());
return;
} catch (const Poco::Exception &E) {
}
Response->setStatus(ProxyResponse.getStatus());
Response->send();
return;
}
}
}
Response->setStatus(ProxyResponse.getStatus());
Response->send();
return;
}
}
} catch (const Poco::Exception &E) {
Logger.log(E);
}
}
}
} catch (const Poco::Exception &E) {
Logger.log(E);
}
}
} // namespace OpenWifi

View File

@@ -4,13 +4,13 @@
#pragma once
#include <string>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "Poco/StreamCopier.h"
#include "Poco/File.h"
#include "Poco/StreamCopier.h"
#include "framework/MicroServiceFuncs.h"
@@ -18,7 +18,6 @@
namespace OpenWifi {
class AppServiceRegistry {
public:
AppServiceRegistry() {
@@ -26,9 +25,9 @@ namespace OpenWifi {
Poco::File F(FileName);
try {
if(F.exists()) {
std::ostringstream OS;
std::ifstream IF(FileName);
if (F.exists()) {
std::ostringstream OS;
std::ifstream IF(FileName);
Poco::StreamCopier::copyStream(IF, OS);
Registry_ = nlohmann::json::parse(OS.str());
}
@@ -37,55 +36,53 @@ namespace OpenWifi {
}
}
static AppServiceRegistry & instance() {
static auto instance_= new AppServiceRegistry;
static AppServiceRegistry &instance() {
static auto instance_ = new AppServiceRegistry;
return *instance_;
}
inline ~AppServiceRegistry() {
Save();
}
inline ~AppServiceRegistry() { Save(); }
inline void Save() {
std::istringstream IS( to_string(Registry_));
std::ofstream OF;
OF.open(FileName,std::ios::binary | std::ios::trunc);
std::istringstream IS(to_string(Registry_));
std::ofstream OF;
OF.open(FileName, std::ios::binary | std::ios::trunc);
Poco::StreamCopier::copyStream(IS, OF);
}
inline void Set(const char *Key, uint64_t Value ) {
inline void Set(const char *Key, uint64_t Value) {
Registry_[Key] = Value;
Save();
}
inline void Set(const char *Key, const std::string &Value ) {
inline void Set(const char *Key, const std::string &Value) {
Registry_[Key] = Value;
Save();
}
inline void Set(const char *Key, bool Value ) {
inline void Set(const char *Key, bool Value) {
Registry_[Key] = Value;
Save();
}
inline bool Get(const char *Key, bool & Value ) {
if(Registry_[Key].is_boolean()) {
inline bool Get(const char *Key, bool &Value) {
if (Registry_[Key].is_boolean()) {
Value = Registry_[Key].get<bool>();
return true;
}
return false;
}
inline bool Get(const char *Key, uint64_t & Value ) {
if(Registry_[Key].is_number_unsigned()) {
inline bool Get(const char *Key, uint64_t &Value) {
if (Registry_[Key].is_number_unsigned()) {
Value = Registry_[Key].get<uint64_t>();
return true;
}
return false;
}
inline bool Get(const char *Key, std::string & Value ) {
if(Registry_[Key].is_string()) {
inline bool Get(const char *Key, std::string &Value) {
if (Registry_[Key].is_string()) {
Value = Registry_[Key].get<std::string>();
return true;
}
@@ -93,10 +90,10 @@ namespace OpenWifi {
}
private:
std::string FileName;
nlohmann::json Registry_;
std::string FileName;
nlohmann::json Registry_;
};
inline auto AppServiceRegistry() { return AppServiceRegistry::instance(); }
}
} // namespace OpenWifi

View File

@@ -4,41 +4,40 @@
#include "Poco/Net/HTTPServerResponse.h"
#include "fmt/format.h"
#include "framework/AuthClient.h"
#include "framework/MicroServiceNames.h"
#include "framework/OpenAPIRequests.h"
#include "framework/utils.h"
#include "fmt/format.h"
namespace OpenWifi {
bool AuthClient::RetrieveTokenInformation(const std::string & SessionToken,
SecurityObjects::UserInfoAndPolicy & UInfo,
std::uint64_t TID,
bool & Expired, bool & Contacted, bool Sub) {
bool AuthClient::RetrieveTokenInformation(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy &UInfo,
std::uint64_t TID, bool &Expired, bool &Contacted,
bool Sub) {
try {
Types::StringPairVec QueryData;
QueryData.push_back(std::make_pair("token",SessionToken));
std::string AlternateURIForLogging = fmt::format("{}?token={}", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken", Utils::SanitizeToken(SessionToken));
OpenAPIRequestGet Req( uSERVICE_SECURITY,
QueryData.push_back(std::make_pair("token", SessionToken));
std::string AlternateURIForLogging = fmt::format(
"{}?token={}", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken",
Utils::SanitizeToken(SessionToken));
OpenAPIRequestGet Req(uSERVICE_SECURITY,
Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken",
QueryData,
10000,
AlternateURIForLogging
);
QueryData, 10000, AlternateURIForLogging);
Poco::JSON::Object::Ptr Response;
auto StatusCode = Req.Do(Response);
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) {
if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) {
Contacted = false;
return false;
}
Contacted = true;
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_OK) {
if(Response->has("tokenInfo") && Response->has("userInfo")) {
if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_OK) {
if (Response->has("tokenInfo") && Response->has("userInfo")) {
UInfo.from_json(Response);
if(IsTokenExpired(UInfo.webtoken)) {
if (IsTokenExpired(UInfo.webtoken)) {
Expired = true;
return false;
}
@@ -50,18 +49,19 @@ namespace OpenWifi {
}
}
} catch (...) {
poco_error(Logger(),fmt::format("Failed to retrieve token={} for TID={}", Utils::SanitizeToken(SessionToken), TID));
poco_error(Logger(), fmt::format("Failed to retrieve token={} for TID={}",
Utils::SanitizeToken(SessionToken), TID));
}
Expired = false;
return false;
}
bool AuthClient::IsAuthorized(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo,
std::uint64_t TID,
bool & Expired, bool & Contacted, bool Sub) {
bool AuthClient::IsAuthorized(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
bool &Expired, bool &Contacted, bool Sub) {
auto User = Cache_.get(SessionToken);
if(!User.isNull()) {
if(IsTokenExpired(User->webtoken)) {
if (!User.isNull()) {
if (IsTokenExpired(User->webtoken)) {
Expired = true;
Cache_.remove(SessionToken);
return false;
@@ -73,57 +73,60 @@ namespace OpenWifi {
return RetrieveTokenInformation(SessionToken, UInfo, TID, Expired, Contacted, Sub);
}
bool AuthClient::RetrieveApiKeyInformation(const std::string & SessionToken,
SecurityObjects::UserInfoAndPolicy & UInfo,
std::uint64_t TID,
bool & Expired, bool & Contacted) {
try {
Types::StringPairVec QueryData;
QueryData.push_back(std::make_pair("apikey",SessionToken));
std::string AlternateURIForLogging = fmt::format("/api/v1/validateApiKey?apiKey={}", Utils::SanitizeToken(SessionToken));
OpenAPIRequestGet Req( uSERVICE_SECURITY,
"/api/v1/validateApiKey" ,
QueryData,
10000,
AlternateURIForLogging);
Poco::JSON::Object::Ptr Response;
bool AuthClient::RetrieveApiKeyInformation(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy &UInfo,
std::uint64_t TID, bool &Expired, bool &Contacted,
[[maybe_unused]] bool &Suspended) {
try {
Types::StringPairVec QueryData;
QueryData.push_back(std::make_pair("apikey", SessionToken));
std::string AlternateURIForLogging =
fmt::format("/api/v1/validateApiKey?apiKey={}", Utils::SanitizeToken(SessionToken));
OpenAPIRequestGet Req(uSERVICE_SECURITY, "/api/v1/validateApiKey", QueryData, 10000,
AlternateURIForLogging);
Poco::JSON::Object::Ptr Response;
auto StatusCode = Req.Do(Response);
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) {
Contacted = false;
return false;
}
auto StatusCode = Req.Do(Response);
if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) {
Contacted = false;
return false;
}
Contacted = true;
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_OK) {
if(Response->has("tokenInfo") && Response->has("userInfo") && Response->has("expiresOn")) {
UInfo.from_json(Response);
Expired = false;
ApiKeyCache_.update(SessionToken, ApiKeyCacheEntry{ .UserInfo = UInfo, .ExpiresOn = Response->get("expiresOn")});
return true;
} else {
return false;
}
}
} catch (...) {
poco_error(Logger(),fmt::format("Failed to retrieve api key={} for TID={}", Utils::SanitizeToken(SessionToken), TID));
}
Expired = false;
return false;
}
Contacted = true;
if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_OK) {
if (Response->has("tokenInfo") && Response->has("userInfo") &&
Response->has("expiresOn")) {
UInfo.from_json(Response);
Expired = false;
ApiKeyCache_.update(SessionToken,
ApiKeyCacheEntry{.UserInfo = UInfo,
.ExpiresOn = Response->get("expiresOn")});
return true;
} else {
return false;
}
}
} catch (...) {
poco_error(Logger(), fmt::format("Failed to retrieve api key={} for TID={}",
Utils::SanitizeToken(SessionToken), TID));
}
Expired = false;
return false;
}
bool AuthClient::IsValidApiKey(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy &UInfo,
std::uint64_t TID, bool &Expired, bool &Contacted) {
auto User = ApiKeyCache_.get(SessionToken);
if (!User.isNull()) {
if(User->ExpiresOn < Utils::Now()) {
Expired = false;
UInfo = User->UserInfo;
return true;
}
bool AuthClient::IsValidApiKey(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
bool &Expired, bool &Contacted, bool &Suspended) {
auto User = ApiKeyCache_.get(SessionToken);
if (!User.isNull()) {
if (User->ExpiresOn < Utils::Now()) {
Expired = false;
UInfo = User->UserInfo;
return true;
}
ApiKeyCache_.remove(SessionToken);
}
return RetrieveApiKeyInformation(SessionToken, UInfo, TID, Expired, Contacted);
}
}
return RetrieveApiKeyInformation(SessionToken, UInfo, TID, Expired, Contacted, Suspended);
}
} // namespace OpenWifi

View File

@@ -4,9 +4,9 @@
#pragma once
#include "framework/SubSystemServer.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "Poco/ExpireLRUCache.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "framework/SubSystemServer.h"
#include "framework/utils.h"
namespace OpenWifi {
@@ -14,66 +14,59 @@ namespace OpenWifi {
class AuthClient : public SubSystemServer {
public:
explicit AuthClient() noexcept:
SubSystemServer("Authentication", "AUTH-CLNT", "authentication")
{
}
explicit AuthClient() noexcept
: SubSystemServer("Authentication", "AUTH-CLNT", "authentication") {}
static auto instance() {
static auto instance_ = new AuthClient;
return instance_;
}
struct ApiKeyCacheEntry {
OpenWifi::SecurityObjects::UserInfoAndPolicy UserInfo;
std::uint64_t ExpiresOn;
};
struct ApiKeyCacheEntry {
OpenWifi::SecurityObjects::UserInfoAndPolicy UserInfo;
std::uint64_t ExpiresOn;
};
inline int Start() override {
return 0;
}
inline int Start() override { return 0; }
inline void Stop() override {
poco_information(Logger(),"Stopping...");
std::lock_guard G(Mutex_);
poco_information(Logger(), "Stopping...");
std::lock_guard G(Mutex_);
Cache_.clear();
poco_information(Logger(),"Stopped...");
poco_information(Logger(), "Stopped...");
}
inline void RemovedCachedToken(const std::string &Token) {
Cache_.remove(Token);
ApiKeyCache_.remove(Token);
ApiKeyCache_.remove(Token);
}
inline static bool IsTokenExpired(const SecurityObjects::WebToken &T) {
return ((T.expires_in_+T.created_) < Utils::Now());
return ((T.expires_in_ + T.created_) < Utils::Now());
}
bool RetrieveTokenInformation(const std::string & SessionToken,
SecurityObjects::UserInfoAndPolicy & UInfo,
std::uint64_t TID,
bool & Expired, bool & Contacted, bool Sub=false);
bool RetrieveTokenInformation(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
bool &Expired, bool &Contacted, bool Sub = false);
bool RetrieveApiKeyInformation(const std::string & SessionToken,
SecurityObjects::UserInfoAndPolicy & UInfo,
std::uint64_t TID,
bool & Expired, bool & Contacted);
bool RetrieveApiKeyInformation(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
bool &Expired, bool &Contacted, bool &Suspended);
bool IsAuthorized(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo,
std::uint64_t TID,
bool & Expired, bool & Contacted, bool Sub = false);
bool IsAuthorized(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
bool &Expired, bool &Contacted, bool Sub = false);
bool IsValidApiKey(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo,
std::uint64_t TID,
bool & Expired, bool & Contacted);
bool IsValidApiKey(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
bool &Expired, bool &Contacted, bool &Suspended);
private:
Poco::ExpireLRUCache<std::string,OpenWifi::SecurityObjects::UserInfoAndPolicy> Cache_{512,1200000 };
Poco::ExpireLRUCache<std::string,ApiKeyCacheEntry> ApiKeyCache_{512,1200000 };
Poco::ExpireLRUCache<std::string, OpenWifi::SecurityObjects::UserInfoAndPolicy> Cache_{
512, 1200000};
Poco::ExpireLRUCache<std::string, ApiKeyCacheEntry> ApiKeyCache_{512, 1200000};
};
inline auto AuthClient() { return AuthClient::instance(); }
} // namespace OpenWifi

View File

@@ -21,13 +21,13 @@ namespace OpenWifi::CIDR {
}
static bool cidr6_match(const in6_addr &address, const in6_addr &network, uint8_t bits) {
#ifdef __linux__
#ifdef __linux__
const uint32_t *a = address.s6_addr32;
const uint32_t *n = network.s6_addr32;
#else
#else
const uint32_t *a = address.__u6_addr.__u6_addr32;
const uint32_t *n = network.__u6_addr.__u6_addr32;
#endif
#endif
int bits_whole, bits_incomplete;
bits_whole = bits >> 5; // number of whole u32
bits_incomplete = bits & 0x1F; // number of bits in incomplete u32
@@ -152,4 +152,4 @@ namespace OpenWifi::CIDR {
[[nodiscard]] inline bool ValidateIpRanges(const Types::StringVec &Ranges) {
return std::all_of(cbegin(Ranges), cend(Ranges), ValidateRange);
}
}
} // namespace OpenWifi::CIDR

File diff suppressed because it is too large Load Diff

View File

@@ -4,39 +4,46 @@
#pragma once
#include <nlohmann/json-schema.hpp>
#include "framework/SubSystemServer.h"
using nlohmann::json;
using nlohmann::json_schema::json_validator;
#include <valijson/adapters/poco_json_adapter.hpp>
#include <valijson/constraints/constraint.hpp>
#include <valijson/constraints/constraint_visitor.hpp>
#include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp>
#include <valijson/utils/poco_json_utils.hpp>
#include <valijson/validator.hpp>
namespace OpenWifi {
class ConfigurationValidator : public SubSystemServer {
public:
class ConfigurationValidator : public SubSystemServer {
public:
static auto instance() {
static auto instance_ = new ConfigurationValidator;
return instance_;
}
static auto instance() {
static auto instance_ = new ConfigurationValidator;
return instance_;
}
bool Validate(const std::string &C, std::vector<std::string> &Errors, bool Strict);
int Start() override;
void Stop() override;
void reinitialize(Poco::Util::Application &self) override;
bool Validate(const std::string &C, std::string &Error);
static void my_format_checker(const std::string &format, const std::string &value);
int Start() override;
void Stop() override;
void reinitialize(Poco::Util::Application &self) override;
private:
bool Initialized_ = false;
bool Working_ = false;
void Init();
std::unique_ptr<valijson::Schema> RootSchema_;
std::unique_ptr<valijson::SchemaParser> SchemaParser_;
std::unique_ptr<valijson::adapters::PocoJsonAdapter> PocoJsonAdapter_;
Poco::JSON::Object::Ptr SchemaDocPtr_;
bool SetSchema(const std::string &SchemaStr);
private:
bool Initialized_=false;
bool Working_=false;
void Init();
nlohmann::json RootSchema_;
ConfigurationValidator():
SubSystemServer("ConfigValidator", "CFG-VALIDATOR", "config.validator") {
}
};
inline auto ConfigurationValidator() { return ConfigurationValidator::instance(); }
inline bool ValidateUCentralConfiguration(const std::string &C, std::string &Error) { return ConfigurationValidator::instance()->Validate(C, Error); }
}
ConfigurationValidator()
: SubSystemServer("ConfigValidator", "CFG-VALIDATOR", "config.validator") {}
};
inline auto ConfigurationValidator() { return ConfigurationValidator::instance(); }
inline bool ValidateUCentralConfiguration(const std::string &C, std::vector<std::string> &Error,
bool strict) {
return ConfigurationValidator::instance()->Validate(C, Error, strict);
}
} // namespace OpenWifi

View File

@@ -4,268 +4,266 @@
#pragma once
#include <vector>
#include <string>
#include <utility>
#include <vector>
namespace OpenWifi {
struct CountryInfo {
std::string code;
std::string name;
};
inline static const std::vector<CountryInfo> CountryCodes {
{ .code= "US", .name= "United States" },
{ .code= "GB", .name= "United Kingdom" },
{ .code= "CA", .name= "Canada" },
{ .code= "AF", .name= "Afghanistan" },
{ .code= "AX", .name= "Aland Islands" },
{ .code= "AL", .name= "Albania" },
{ .code= "DZ", .name= "Algeria" },
{ .code= "AS", .name= "American Samoa" },
{ .code= "AD", .name= "Andorra" },
{ .code= "AO", .name= "Angola" },
{ .code= "AI", .name= "Anguilla" },
{ .code= "AQ", .name= "Antarctica" },
{ .code= "AG", .name= "Antigua And Barbuda" },
{ .code= "AR", .name= "Argentina" },
{ .code= "AM", .name= "Armenia" },
{ .code= "AN", .name= "Netherlands Antilles" },
{ .code= "AW", .name= "Aruba" },
{ .code= "AU", .name= "Australia" },
{ .code= "AT", .name= "Austria" },
{ .code= "AZ", .name= "Azerbaijan" },
{ .code= "BS", .name= "Bahamas" },
{ .code= "BH", .name= "Bahrain" },
{ .code= "BD", .name= "Bangladesh" },
{ .code= "BB", .name= "Barbados" },
{ .code= "BY", .name= "Belarus" },
{ .code= "BE", .name= "Belgium" },
{ .code= "BZ", .name= "Belize" },
{ .code= "BJ", .name= "Benin" },
{ .code= "BM", .name= "Bermuda" },
{ .code= "BT", .name= "Bhutan" },
{ .code= "BO", .name= "Bolivia" },
{ .code= "BA", .name= "Bosnia And Herzegovina" },
{ .code= "BW", .name= "Botswana" },
{ .code= "BV", .name= "Bouvet Island" },
{ .code= "BR", .name= "Brazil" },
{ .code= "IO", .name= "British Indian Ocean Territory" },
{ .code= "BN", .name= "Brunei Darussalam" },
{ .code= "BG", .name= "Bulgaria" },
{ .code= "BF", .name= "Burkina Faso" },
{ .code= "BI", .name= "Burundi" },
{ .code= "KH", .name= "Cambodia" },
{ .code= "CM", .name= "Cameroon" },
{ .code= "CA", .name= "Canada" },
{ .code= "CV", .name= "Cape Verde" },
{ .code= "KY", .name= "Cayman Islands" },
{ .code= "CF", .name= "Central African Republic" },
{ .code= "TD", .name= "Chad" },
{ .code= "CL", .name= "Chile" },
{ .code= "CN", .name= "China" },
{ .code= "CX", .name= "Christmas Island" },
{ .code= "CC", .name= "Cocos (Keeling) Islands" },
{ .code= "CO", .name= "Colombia" },
{ .code= "KM", .name= "Comoros" },
{ .code= "CG", .name= "Congo" },
{ .code= "CD", .name= "Congo, Democratic Republic" },
{ .code= "CK", .name= "Cook Islands" },
{ .code= "CR", .name= "Costa Rica" },
{ .code= "CI", .name= "Cote D\"Ivoire" },
{ .code= "HR", .name= "Croatia" },
{ .code= "CU", .name= "Cuba" },
{ .code= "CY", .name= "Cyprus" },
{ .code= "CZ", .name= "Czech Republic" },
{ .code= "DK", .name= "Denmark" },
{ .code= "DJ", .name= "Djibouti" },
{ .code= "DM", .name= "Dominica" },
{ .code= "DO", .name= "Dominican Republic" },
{ .code= "EC", .name= "Ecuador" },
{ .code= "EG", .name= "Egypt" },
{ .code= "SV", .name= "El Salvador" },
{ .code= "GQ", .name= "Equatorial Guinea" },
{ .code= "ER", .name= "Eritrea" },
{ .code= "EE", .name= "Estonia" },
{ .code= "ET", .name= "Ethiopia" },
{ .code= "FK", .name= "Falkland Islands (Malvinas)" },
{ .code= "FO", .name= "Faroe Islands" },
{ .code= "FJ", .name= "Fiji" },
{ .code= "FI", .name= "Finland" },
{ .code= "FR", .name= "France" },
{ .code= "GF", .name= "French Guiana" },
{ .code= "PF", .name= "French Polynesia" },
{ .code= "TF", .name= "French Southern Territories" },
{ .code= "GA", .name= "Gabon" },
{ .code= "GM", .name= "Gambia" },
{ .code= "GE", .name= "Georgia" },
{ .code= "DE", .name= "Germany" },
{ .code= "GH", .name= "Ghana" },
{ .code= "GI", .name= "Gibraltar" },
{ .code= "GR", .name= "Greece" },
{ .code= "GL", .name= "Greenland" },
{ .code= "GD", .name= "Grenada" },
{ .code= "GP", .name= "Guadeloupe" },
{ .code= "GU", .name= "Guam" },
{ .code= "GT", .name= "Guatemala" },
{ .code= "GG", .name= "Guernsey" },
{ .code= "GN", .name= "Guinea" },
{ .code= "GW", .name= "Guinea-Bissau" },
{ .code= "GY", .name= "Guyana" },
{ .code= "HT", .name= "Haiti" },
{ .code= "HM", .name= "Heard Island & Mcdonald Islands" },
{ .code= "VA", .name= "Holy See (Vatican City State)" },
{ .code= "HN", .name= "Honduras" },
{ .code= "HK", .name= "Hong Kong" },
{ .code= "HU", .name= "Hungary" },
{ .code= "IS", .name= "Iceland" },
{ .code= "IN", .name= "India" },
{ .code= "ID", .name= "Indonesia" },
{ .code= "IR", .name= "Iran, Islamic Republic Of" },
{ .code= "IQ", .name= "Iraq" },
{ .code= "IE", .name= "Ireland" },
{ .code= "IM", .name= "Isle Of Man" },
{ .code= "IL", .name= "Israel" },
{ .code= "IT", .name= "Italy" },
{ .code= "JM", .name= "Jamaica" },
{ .code= "JP", .name= "Japan" },
{ .code= "JE", .name= "Jersey" },
{ .code= "JO", .name= "Jordan" },
{ .code= "KZ", .name= "Kazakhstan" },
{ .code= "KE", .name= "Kenya" },
{ .code= "KI", .name= "Kiribati" },
{ .code= "KR", .name= "Korea" },
{ .code= "KW", .name= "Kuwait" },
{ .code= "KG", .name= "Kyrgyzstan" },
{ .code= "LA", .name= "Lao People\"s Democratic Republic" },
{ .code= "LV", .name= "Latvia" },
{ .code= "LB", .name= "Lebanon" },
{ .code= "LS", .name= "Lesotho" },
{ .code= "LR", .name= "Liberia" },
{ .code= "LY", .name= "Libyan Arab Jamahiriya" },
{ .code= "LI", .name= "Liechtenstein" },
{ .code= "LT", .name= "Lithuania" },
{ .code= "LU", .name= "Luxembourg" },
{ .code= "MO", .name= "Macao" },
{ .code= "MK", .name= "Macedonia" },
{ .code= "MG", .name= "Madagascar" },
{ .code= "MW", .name= "Malawi" },
{ .code= "MY", .name= "Malaysia" },
{ .code= "MV", .name= "Maldives" },
{ .code= "ML", .name= "Mali" },
{ .code= "MT", .name= "Malta" },
{ .code= "MH", .name= "Marshall Islands" },
{ .code= "MQ", .name= "Martinique" },
{ .code= "MR", .name= "Mauritania" },
{ .code= "MU", .name= "Mauritius" },
{ .code= "YT", .name= "Mayotte" },
{ .code= "MX", .name= "Mexico" },
{ .code= "FM", .name= "Micronesia, Federated States Of" },
{ .code= "MD", .name= "Moldova" },
{ .code= "MC", .name= "Monaco" },
{ .code= "MN", .name= "Mongolia" },
{ .code= "ME", .name= "Montenegro" },
{ .code= "MS", .name= "Montserrat" },
{ .code= "MA", .name= "Morocco" },
{ .code= "MZ", .name= "Mozambique" },
{ .code= "MM", .name= "Myanmar" },
{ .code= "NA", .name= "Namibia" },
{ .code= "NR", .name= "Nauru" },
{ .code= "NP", .name= "Nepal" },
{ .code= "NL", .name= "Netherlands" },
{ .code= "AN", .name= "Netherlands Antilles" },
{ .code= "NC", .name= "New Caledonia" },
{ .code= "NZ", .name= "New Zealand" },
{ .code= "NI", .name= "Nicaragua" },
{ .code= "NE", .name= "Niger" },
{ .code= "NG", .name= "Nigeria" },
{ .code= "NU", .name= "Niue" },
{ .code= "NF", .name= "Norfolk Island" },
{ .code= "MP", .name= "Northern Mariana Islands" },
{ .code= "NO", .name= "Norway" },
{ .code= "OM", .name= "Oman" },
{ .code= "PK", .name= "Pakistan" },
{ .code= "PW", .name= "Palau" },
{ .code= "PS", .name= "Palestinian Territory, Occupied" },
{ .code= "PA", .name= "Panama" },
{ .code= "PG", .name= "Papua New Guinea" },
{ .code= "PY", .name= "Paraguay" },
{ .code= "PE", .name= "Peru" },
{ .code= "PH", .name= "Philippines" },
{ .code= "PN", .name= "Pitcairn" },
{ .code= "PL", .name= "Poland" },
{ .code= "PT", .name= "Portugal" },
{ .code= "PR", .name= "Puerto Rico" },
{ .code= "QA", .name= "Qatar" },
{ .code= "RE", .name= "Reunion" },
{ .code= "RO", .name= "Romania" },
{ .code= "RU", .name= "Russian Federation" },
{ .code= "RW", .name= "Rwanda" },
{ .code= "BL", .name= "Saint Barthelemy" },
{ .code= "SH", .name= "Saint Helena" },
{ .code= "KN", .name= "Saint Kitts And Nevis" },
{ .code= "LC", .name= "Saint Lucia" },
{ .code= "MF", .name= "Saint Martin" },
{ .code= "PM", .name= "Saint Pierre And Miquelon" },
{ .code= "VC", .name= "Saint Vincent And Grenadines" },
{ .code= "WS", .name= "Samoa" },
{ .code= "SM", .name= "San Marino" },
{ .code= "ST", .name= "Sao Tome And Principe" },
{ .code= "SA", .name= "Saudi Arabia" },
{ .code= "SN", .name= "Senegal" },
{ .code= "RS", .name= "Serbia" },
{ .code= "SC", .name= "Seychelles" },
{ .code= "SL", .name= "Sierra Leone" },
{ .code= "SG", .name= "Singapore" },
{ .code= "SK", .name= "Slovakia" },
{ .code= "SI", .name= "Slovenia" },
{ .code= "SB", .name= "Solomon Islands" },
{ .code= "SO", .name= "Somalia" },
{ .code= "ZA", .name= "South Africa" },
{ .code= "GS", .name= "South Georgia And Sandwich Isl." },
{ .code= "ES", .name= "Spain" },
{ .code= "LK", .name= "Sri Lanka" },
{ .code= "SD", .name= "Sudan" },
{ .code= "SR", .name= "Suriname" },
{ .code= "SJ", .name= "Svalbard And Jan Mayen" },
{ .code= "SZ", .name= "Swaziland" },
{ .code= "SE", .name= "Sweden" },
{ .code= "CH", .name= "Switzerland" },
{ .code= "SY", .name= "Syrian Arab Republic" },
{ .code= "TW", .name= "Taiwan" },
{ .code= "TJ", .name= "Tajikistan" },
{ .code= "TZ", .name= "Tanzania" },
{ .code= "TH", .name= "Thailand" },
{ .code= "TL", .name= "Timor-Leste" },
{ .code= "TG", .name= "Togo" },
{ .code= "TK", .name= "Tokelau" },
{ .code= "TO", .name= "Tonga" },
{ .code= "TT", .name= "Trinidad And Tobago" },
{ .code= "TN", .name= "Tunisia" },
{ .code= "TR", .name= "Turkey" },
{ .code= "TM", .name= "Turkmenistan" },
{ .code= "TC", .name= "Turks And Caicos Islands" },
{ .code= "TV", .name= "Tuvalu" },
{ .code= "UG", .name= "Uganda" },
{ .code= "UA", .name= "Ukraine" },
{ .code= "AE", .name= "United Arab Emirates" },
{ .code= "GB", .name= "United Kingdom" },
{ .code= "US", .name= "United States" },
{ .code= "UM", .name= "United States Outlying Islands" },
{ .code= "UY", .name= "Uruguay" },
{ .code= "UZ", .name= "Uzbekistan" },
{ .code= "VU", .name= "Vanuatu" },
{ .code= "VE", .name= "Venezuela" },
{ .code= "VN", .name= "Viet Nam" },
{ .code= "VG", .name= "Virgin Islands, British" },
{ .code= "VI", .name= "Virgin Islands, U.S." },
{ .code= "WF", .name= "Wallis And Futuna" },
{ .code= "EH", .name= "Western Sahara" },
{ .code= "YE", .name= "Yemen" },
{ .code= "ZM", .name= "Zambia" },
{ .code= "ZW", .name= "Zimbabwe" }
};
}
struct CountryInfo {
std::string code;
std::string name;
};
inline static const std::vector<CountryInfo> CountryCodes{
{.code = "US", .name = "United States"},
{.code = "GB", .name = "United Kingdom"},
{.code = "CA", .name = "Canada"},
{.code = "AF", .name = "Afghanistan"},
{.code = "AX", .name = "Aland Islands"},
{.code = "AL", .name = "Albania"},
{.code = "DZ", .name = "Algeria"},
{.code = "AS", .name = "American Samoa"},
{.code = "AD", .name = "Andorra"},
{.code = "AO", .name = "Angola"},
{.code = "AI", .name = "Anguilla"},
{.code = "AQ", .name = "Antarctica"},
{.code = "AG", .name = "Antigua And Barbuda"},
{.code = "AR", .name = "Argentina"},
{.code = "AM", .name = "Armenia"},
{.code = "AN", .name = "Netherlands Antilles"},
{.code = "AW", .name = "Aruba"},
{.code = "AU", .name = "Australia"},
{.code = "AT", .name = "Austria"},
{.code = "AZ", .name = "Azerbaijan"},
{.code = "BS", .name = "Bahamas"},
{.code = "BH", .name = "Bahrain"},
{.code = "BD", .name = "Bangladesh"},
{.code = "BB", .name = "Barbados"},
{.code = "BY", .name = "Belarus"},
{.code = "BE", .name = "Belgium"},
{.code = "BZ", .name = "Belize"},
{.code = "BJ", .name = "Benin"},
{.code = "BM", .name = "Bermuda"},
{.code = "BT", .name = "Bhutan"},
{.code = "BO", .name = "Bolivia"},
{.code = "BA", .name = "Bosnia And Herzegovina"},
{.code = "BW", .name = "Botswana"},
{.code = "BV", .name = "Bouvet Island"},
{.code = "BR", .name = "Brazil"},
{.code = "IO", .name = "British Indian Ocean Territory"},
{.code = "BN", .name = "Brunei Darussalam"},
{.code = "BG", .name = "Bulgaria"},
{.code = "BF", .name = "Burkina Faso"},
{.code = "BI", .name = "Burundi"},
{.code = "KH", .name = "Cambodia"},
{.code = "CM", .name = "Cameroon"},
{.code = "CA", .name = "Canada"},
{.code = "CV", .name = "Cape Verde"},
{.code = "KY", .name = "Cayman Islands"},
{.code = "CF", .name = "Central African Republic"},
{.code = "TD", .name = "Chad"},
{.code = "CL", .name = "Chile"},
{.code = "CN", .name = "China"},
{.code = "CX", .name = "Christmas Island"},
{.code = "CC", .name = "Cocos (Keeling) Islands"},
{.code = "CO", .name = "Colombia"},
{.code = "KM", .name = "Comoros"},
{.code = "CG", .name = "Congo"},
{.code = "CD", .name = "Congo, Democratic Republic"},
{.code = "CK", .name = "Cook Islands"},
{.code = "CR", .name = "Costa Rica"},
{.code = "CI", .name = "Cote D\"Ivoire"},
{.code = "HR", .name = "Croatia"},
{.code = "CU", .name = "Cuba"},
{.code = "CY", .name = "Cyprus"},
{.code = "CZ", .name = "Czech Republic"},
{.code = "DK", .name = "Denmark"},
{.code = "DJ", .name = "Djibouti"},
{.code = "DM", .name = "Dominica"},
{.code = "DO", .name = "Dominican Republic"},
{.code = "EC", .name = "Ecuador"},
{.code = "EG", .name = "Egypt"},
{.code = "SV", .name = "El Salvador"},
{.code = "GQ", .name = "Equatorial Guinea"},
{.code = "ER", .name = "Eritrea"},
{.code = "EE", .name = "Estonia"},
{.code = "ET", .name = "Ethiopia"},
{.code = "FK", .name = "Falkland Islands (Malvinas)"},
{.code = "FO", .name = "Faroe Islands"},
{.code = "FJ", .name = "Fiji"},
{.code = "FI", .name = "Finland"},
{.code = "FR", .name = "France"},
{.code = "GF", .name = "French Guiana"},
{.code = "PF", .name = "French Polynesia"},
{.code = "TF", .name = "French Southern Territories"},
{.code = "GA", .name = "Gabon"},
{.code = "GM", .name = "Gambia"},
{.code = "GE", .name = "Georgia"},
{.code = "DE", .name = "Germany"},
{.code = "GH", .name = "Ghana"},
{.code = "GI", .name = "Gibraltar"},
{.code = "GR", .name = "Greece"},
{.code = "GL", .name = "Greenland"},
{.code = "GD", .name = "Grenada"},
{.code = "GP", .name = "Guadeloupe"},
{.code = "GU", .name = "Guam"},
{.code = "GT", .name = "Guatemala"},
{.code = "GG", .name = "Guernsey"},
{.code = "GN", .name = "Guinea"},
{.code = "GW", .name = "Guinea-Bissau"},
{.code = "GY", .name = "Guyana"},
{.code = "HT", .name = "Haiti"},
{.code = "HM", .name = "Heard Island & Mcdonald Islands"},
{.code = "VA", .name = "Holy See (Vatican City State)"},
{.code = "HN", .name = "Honduras"},
{.code = "HK", .name = "Hong Kong"},
{.code = "HU", .name = "Hungary"},
{.code = "IS", .name = "Iceland"},
{.code = "IN", .name = "India"},
{.code = "ID", .name = "Indonesia"},
{.code = "IR", .name = "Iran, Islamic Republic Of"},
{.code = "IQ", .name = "Iraq"},
{.code = "IE", .name = "Ireland"},
{.code = "IM", .name = "Isle Of Man"},
{.code = "IL", .name = "Israel"},
{.code = "IT", .name = "Italy"},
{.code = "JM", .name = "Jamaica"},
{.code = "JP", .name = "Japan"},
{.code = "JE", .name = "Jersey"},
{.code = "JO", .name = "Jordan"},
{.code = "KZ", .name = "Kazakhstan"},
{.code = "KE", .name = "Kenya"},
{.code = "KI", .name = "Kiribati"},
{.code = "KR", .name = "Korea"},
{.code = "KW", .name = "Kuwait"},
{.code = "KG", .name = "Kyrgyzstan"},
{.code = "LA", .name = "Lao People\"s Democratic Republic"},
{.code = "LV", .name = "Latvia"},
{.code = "LB", .name = "Lebanon"},
{.code = "LS", .name = "Lesotho"},
{.code = "LR", .name = "Liberia"},
{.code = "LY", .name = "Libyan Arab Jamahiriya"},
{.code = "LI", .name = "Liechtenstein"},
{.code = "LT", .name = "Lithuania"},
{.code = "LU", .name = "Luxembourg"},
{.code = "MO", .name = "Macao"},
{.code = "MK", .name = "Macedonia"},
{.code = "MG", .name = "Madagascar"},
{.code = "MW", .name = "Malawi"},
{.code = "MY", .name = "Malaysia"},
{.code = "MV", .name = "Maldives"},
{.code = "ML", .name = "Mali"},
{.code = "MT", .name = "Malta"},
{.code = "MH", .name = "Marshall Islands"},
{.code = "MQ", .name = "Martinique"},
{.code = "MR", .name = "Mauritania"},
{.code = "MU", .name = "Mauritius"},
{.code = "YT", .name = "Mayotte"},
{.code = "MX", .name = "Mexico"},
{.code = "FM", .name = "Micronesia, Federated States Of"},
{.code = "MD", .name = "Moldova"},
{.code = "MC", .name = "Monaco"},
{.code = "MN", .name = "Mongolia"},
{.code = "ME", .name = "Montenegro"},
{.code = "MS", .name = "Montserrat"},
{.code = "MA", .name = "Morocco"},
{.code = "MZ", .name = "Mozambique"},
{.code = "MM", .name = "Myanmar"},
{.code = "NA", .name = "Namibia"},
{.code = "NR", .name = "Nauru"},
{.code = "NP", .name = "Nepal"},
{.code = "NL", .name = "Netherlands"},
{.code = "AN", .name = "Netherlands Antilles"},
{.code = "NC", .name = "New Caledonia"},
{.code = "NZ", .name = "New Zealand"},
{.code = "NI", .name = "Nicaragua"},
{.code = "NE", .name = "Niger"},
{.code = "NG", .name = "Nigeria"},
{.code = "NU", .name = "Niue"},
{.code = "NF", .name = "Norfolk Island"},
{.code = "MP", .name = "Northern Mariana Islands"},
{.code = "NO", .name = "Norway"},
{.code = "OM", .name = "Oman"},
{.code = "PK", .name = "Pakistan"},
{.code = "PW", .name = "Palau"},
{.code = "PS", .name = "Palestinian Territory, Occupied"},
{.code = "PA", .name = "Panama"},
{.code = "PG", .name = "Papua New Guinea"},
{.code = "PY", .name = "Paraguay"},
{.code = "PE", .name = "Peru"},
{.code = "PH", .name = "Philippines"},
{.code = "PN", .name = "Pitcairn"},
{.code = "PL", .name = "Poland"},
{.code = "PT", .name = "Portugal"},
{.code = "PR", .name = "Puerto Rico"},
{.code = "QA", .name = "Qatar"},
{.code = "RE", .name = "Reunion"},
{.code = "RO", .name = "Romania"},
{.code = "RU", .name = "Russian Federation"},
{.code = "RW", .name = "Rwanda"},
{.code = "BL", .name = "Saint Barthelemy"},
{.code = "SH", .name = "Saint Helena"},
{.code = "KN", .name = "Saint Kitts And Nevis"},
{.code = "LC", .name = "Saint Lucia"},
{.code = "MF", .name = "Saint Martin"},
{.code = "PM", .name = "Saint Pierre And Miquelon"},
{.code = "VC", .name = "Saint Vincent And Grenadines"},
{.code = "WS", .name = "Samoa"},
{.code = "SM", .name = "San Marino"},
{.code = "ST", .name = "Sao Tome And Principe"},
{.code = "SA", .name = "Saudi Arabia"},
{.code = "SN", .name = "Senegal"},
{.code = "RS", .name = "Serbia"},
{.code = "SC", .name = "Seychelles"},
{.code = "SL", .name = "Sierra Leone"},
{.code = "SG", .name = "Singapore"},
{.code = "SK", .name = "Slovakia"},
{.code = "SI", .name = "Slovenia"},
{.code = "SB", .name = "Solomon Islands"},
{.code = "SO", .name = "Somalia"},
{.code = "ZA", .name = "South Africa"},
{.code = "GS", .name = "South Georgia And Sandwich Isl."},
{.code = "ES", .name = "Spain"},
{.code = "LK", .name = "Sri Lanka"},
{.code = "SD", .name = "Sudan"},
{.code = "SR", .name = "Suriname"},
{.code = "SJ", .name = "Svalbard And Jan Mayen"},
{.code = "SZ", .name = "Swaziland"},
{.code = "SE", .name = "Sweden"},
{.code = "CH", .name = "Switzerland"},
{.code = "SY", .name = "Syrian Arab Republic"},
{.code = "TW", .name = "Taiwan"},
{.code = "TJ", .name = "Tajikistan"},
{.code = "TZ", .name = "Tanzania"},
{.code = "TH", .name = "Thailand"},
{.code = "TL", .name = "Timor-Leste"},
{.code = "TG", .name = "Togo"},
{.code = "TK", .name = "Tokelau"},
{.code = "TO", .name = "Tonga"},
{.code = "TT", .name = "Trinidad And Tobago"},
{.code = "TN", .name = "Tunisia"},
{.code = "TR", .name = "Turkey"},
{.code = "TM", .name = "Turkmenistan"},
{.code = "TC", .name = "Turks And Caicos Islands"},
{.code = "TV", .name = "Tuvalu"},
{.code = "UG", .name = "Uganda"},
{.code = "UA", .name = "Ukraine"},
{.code = "AE", .name = "United Arab Emirates"},
{.code = "GB", .name = "United Kingdom"},
{.code = "US", .name = "United States"},
{.code = "UM", .name = "United States Outlying Islands"},
{.code = "UY", .name = "Uruguay"},
{.code = "UZ", .name = "Uzbekistan"},
{.code = "VU", .name = "Vanuatu"},
{.code = "VE", .name = "Venezuela"},
{.code = "VN", .name = "Viet Nam"},
{.code = "VG", .name = "Virgin Islands, British"},
{.code = "VI", .name = "Virgin Islands, U.S."},
{.code = "WF", .name = "Wallis And Futuna"},
{.code = "EH", .name = "Western Sahara"},
{.code = "YE", .name = "Yemen"},
{.code = "ZM", .name = "Zambia"},
{.code = "ZW", .name = "Zimbabwe"}};
} // namespace OpenWifi

View File

@@ -4,45 +4,46 @@
#include "framework/EventBusManager.h"
#include "framework/KafkaManager.h"
#include "framework/utils.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h"
namespace OpenWifi {
EventBusManager::EventBusManager(Poco::Logger &L) :
Logger_(L) {
}
EventBusManager::EventBusManager(Poco::Logger &L) : Logger_(L) {}
void EventBusManager::run() {
Running_ = true;
Utils::SetThreadName("fmwk:EventMgr");
auto Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_JOIN);
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false);
while(Running_) {
auto Msg = std::make_shared<std::string>(MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_JOIN));
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg,
false);
while (Running_) {
Poco::Thread::trySleep((unsigned long)MicroServiceDaemonBusTimer());
if(!Running_)
if (!Running_)
break;
Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE);
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false);
Msg = std::make_shared<std::string>(MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE));
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(),
Msg, false);
}
Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_LEAVE);
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false);
Msg = std::make_shared<std::string>(MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_LEAVE));
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg,
false);
};
void EventBusManager::Start() {
poco_information(Logger(),"Starting...");
if(KafkaManager()->Enabled()) {
poco_information(Logger(), "Starting...");
if (KafkaManager()->Enabled()) {
Thread_.start(*this);
}
}
void EventBusManager::Stop() {
if(KafkaManager()->Enabled()) {
poco_information(Logger(),"Stopping...");
if (KafkaManager()->Enabled()) {
poco_information(Logger(), "Stopping...");
Running_ = false;
Thread_.wakeUp();
Thread_.join();
poco_information(Logger(),"Stopped...");
poco_information(Logger(), "Stopped...");
}
}

View File

@@ -4,8 +4,8 @@
#pragma once
#include "Poco/Runnable.h"
#include "Poco/Logger.h"
#include "Poco/Runnable.h"
#include "Poco/Thread.h"
namespace OpenWifi {
@@ -16,13 +16,12 @@ namespace OpenWifi {
void run() final;
void Start();
void Stop();
inline Poco::Logger & Logger() { return Logger_; }
inline Poco::Logger &Logger() { return Logger_; }
private:
mutable std::atomic_bool Running_ = false;
Poco::Thread Thread_;
Poco::Logger &Logger_;
mutable std::atomic_bool Running_ = false;
Poco::Thread Thread_;
Poco::Logger &Logger_;
};
} // namespace OpenWifi

View File

@@ -4,251 +4,260 @@
#include "KafkaManager.h"
#include "framework/MicroServiceFuncs.h"
#include "fmt/format.h"
#include "framework/MicroServiceFuncs.h"
namespace OpenWifi {
void KafkaLoggerFun([[maybe_unused]] cppkafka::KafkaHandleBase & handle, int level, const std::string & facility, const std::string &message) {
switch ((cppkafka::LogLevel) level) {
void KafkaLoggerFun([[maybe_unused]] cppkafka::KafkaHandleBase &handle, int level,
const std::string &facility, const std::string &message) {
switch ((cppkafka::LogLevel)level) {
case cppkafka::LogLevel::LogNotice: {
poco_notice(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
}
break;
poco_notice(KafkaManager()->Logger(),
fmt::format("kafka-log: facility: {} message: {}", facility, message));
} break;
case cppkafka::LogLevel::LogDebug: {
poco_debug(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
}
break;
poco_debug(KafkaManager()->Logger(),
fmt::format("kafka-log: facility: {} message: {}", facility, message));
} break;
case cppkafka::LogLevel::LogInfo: {
poco_information(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
}
break;
poco_information(KafkaManager()->Logger(),
fmt::format("kafka-log: facility: {} message: {}", facility, message));
} break;
case cppkafka::LogLevel::LogWarning: {
poco_warning(KafkaManager()->Logger(), fmt::format("kafka-log: facility: {} message: {}",facility, message));
}
break;
poco_warning(KafkaManager()->Logger(),
fmt::format("kafka-log: facility: {} message: {}", facility, message));
} break;
case cppkafka::LogLevel::LogAlert:
case cppkafka::LogLevel::LogCrit: {
poco_critical(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
}
break;
poco_critical(KafkaManager()->Logger(),
fmt::format("kafka-log: facility: {} message: {}", facility, message));
} break;
case cppkafka::LogLevel::LogErr:
case cppkafka::LogLevel::LogEmerg:
default: {
poco_error(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
}
break;
poco_error(KafkaManager()->Logger(),
fmt::format("kafka-log: facility: {} message: {}", facility, message));
} break;
}
}
inline void KafkaErrorFun([[maybe_unused]] cppkafka::KafkaHandleBase & handle, int error, const std::string &reason) {
poco_error(KafkaManager()->Logger(),fmt::format("kafka-error: {}, reason: {}", error, reason));
inline void KafkaErrorFun([[maybe_unused]] cppkafka::KafkaHandleBase &handle, int error,
const std::string &reason) {
poco_error(KafkaManager()->Logger(),
fmt::format("kafka-error: {}, reason: {}", error, reason));
}
inline void AddKafkaSecurity(cppkafka::Configuration & Config) {
auto CA = MicroServiceConfigGetString("openwifi.kafka.ssl.ca.location","");
auto Certificate = MicroServiceConfigGetString("openwifi.kafka.ssl.certificate.location","");
auto Key = MicroServiceConfigGetString("openwifi.kafka.ssl.key.location","");
auto Password = MicroServiceConfigGetString("openwifi.kafka.ssl.key.password","");
inline void AddKafkaSecurity(cppkafka::Configuration &Config) {
auto CA = MicroServiceConfigGetString("openwifi.kafka.ssl.ca.location", "");
auto Certificate =
MicroServiceConfigGetString("openwifi.kafka.ssl.certificate.location", "");
auto Key = MicroServiceConfigGetString("openwifi.kafka.ssl.key.location", "");
auto Password = MicroServiceConfigGetString("openwifi.kafka.ssl.key.password", "");
if(CA.empty() || Certificate.empty() || Key.empty())
if (CA.empty() || Certificate.empty() || Key.empty())
return;
Config.set("ssl.ca.location", CA);
Config.set("ssl.certificate.location", Certificate);
Config.set("ssl.key.location", Key);
if(!Password.empty())
if (!Password.empty())
Config.set("ssl.key.password", Password);
}
void KafkaManager::initialize(Poco::Util::Application & self) {
void KafkaManager::initialize(Poco::Util::Application &self) {
SubSystemServer::initialize(self);
KafkaEnabled_ = MicroServiceConfigGetBool("openwifi.kafka.enable",false);
KafkaEnabled_ = MicroServiceConfigGetBool("openwifi.kafka.enable", false);
}
inline void KafkaProducer::run() {
Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-PRODUCER", KafkaManager()->Logger().getChannel());
poco_information(Logger_,"Starting...");
Poco::Logger &Logger_ =
Poco::Logger::create("KAFKA-PRODUCER", KafkaManager()->Logger().getChannel());
poco_information(Logger_, "Starting...");
Utils::SetThreadName("Kafka:Prod");
cppkafka::Configuration Config({
{ "client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "") },
{ "metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist", "") }
});
cppkafka::Configuration Config(
{{"client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "")},
{"metadata.broker.list",
MicroServiceConfigGetString("openwifi.kafka.brokerlist", "")}});
AddKafkaSecurity(Config);
Config.set_log_callback(KafkaLoggerFun);
Config.set_error_callback(KafkaErrorFun);
KafkaManager()->SystemInfoWrapper_ = R"lit({ "system" : { "id" : )lit" +
std::to_string(MicroServiceID()) +
R"lit( , "host" : ")lit" + MicroServicePrivateEndPoint() +
R"lit(" } , "payload" : )lit" ;
KafkaManager()->SystemInfoWrapper_ =
R"lit({ "system" : { "id" : )lit" + std::to_string(MicroServiceID()) +
R"lit( , "host" : ")lit" + MicroServicePrivateEndPoint() +
R"lit(" } , "payload" : )lit";
cppkafka::Producer Producer(Config);
cppkafka::Producer Producer(Config);
Running_ = true;
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
while(Note && Running_) {
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
while (Note && Running_) {
try {
auto Msg = dynamic_cast<KafkaMessage *>(Note.get());
if (Msg != nullptr) {
Producer.produce(
cppkafka::MessageBuilder(Msg->Topic()).key(Msg->Key()).payload(Msg->Payload()));
Producer.produce(cppkafka::MessageBuilder(Msg->Topic())
.key(Msg->Key())
.payload(Msg->Payload()));
}
} catch (const cppkafka::HandleException &E) {
poco_warning(Logger_,fmt::format("Caught a Kafka exception (producer): {}", E.what()));
} catch( const Poco::Exception &E) {
poco_warning(Logger_,
fmt::format("Caught a Kafka exception (producer): {}", E.what()));
} catch (const Poco::Exception &E) {
Logger_.log(E);
} catch (...) {
poco_error(Logger_,"std::exception");
poco_error(Logger_, "std::exception");
}
Note = Queue_.waitDequeueNotification();
}
poco_information(Logger_,"Stopped...");
poco_information(Logger_, "Stopped...");
}
inline void KafkaConsumer::run() {
Utils::SetThreadName("Kafka:Cons");
Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-CONSUMER", KafkaManager()->Logger().getChannel());
Poco::Logger &Logger_ =
Poco::Logger::create("KAFKA-CONSUMER", KafkaManager()->Logger().getChannel());
poco_information(Logger_,"Starting...");
poco_information(Logger_, "Starting...");
cppkafka::Configuration Config({
{ "client.id", MicroServiceConfigGetString("openwifi.kafka.client.id","") },
{ "metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist","") },
{ "group.id", MicroServiceConfigGetString("openwifi.kafka.group.id","") },
{ "enable.auto.commit", MicroServiceConfigGetBool("openwifi.kafka.auto.commit",false) },
{ "auto.offset.reset", "latest" } ,
{ "enable.partition.eof", false }
});
cppkafka::Configuration Config(
{{"client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "")},
{"metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist", "")},
{"group.id", MicroServiceConfigGetString("openwifi.kafka.group.id", "")},
{"enable.auto.commit", MicroServiceConfigGetBool("openwifi.kafka.auto.commit", false)},
{"auto.offset.reset", "latest"},
{"enable.partition.eof", false}});
AddKafkaSecurity(Config);
Config.set_log_callback(KafkaLoggerFun);
Config.set_error_callback(KafkaErrorFun);
cppkafka::TopicConfiguration topic_config = {
{ "auto.offset.reset", "smallest" }
};
cppkafka::TopicConfiguration topic_config = {{"auto.offset.reset", "smallest"}};
// Now configure it to be the default topic config
Config.set_default_topic_configuration(topic_config);
cppkafka::Consumer Consumer(Config);
Consumer.set_assignment_callback([&](cppkafka::TopicPartitionList& partitions) {
if(!partitions.empty()) {
poco_information(Logger_,fmt::format("Partition assigned: {}...",
partitions.front().get_partition()));
Consumer.set_assignment_callback([&](cppkafka::TopicPartitionList &partitions) {
if (!partitions.empty()) {
poco_information(Logger_, fmt::format("Partition assigned: {}...",
partitions.front().get_partition()));
}
});
Consumer.set_revocation_callback([&](const cppkafka::TopicPartitionList& partitions) {
if(!partitions.empty()) {
poco_information(Logger_,fmt::format("Partition revocation: {}...",
partitions.front().get_partition()));
Consumer.set_revocation_callback([&](const cppkafka::TopicPartitionList &partitions) {
if (!partitions.empty()) {
poco_information(Logger_, fmt::format("Partition revocation: {}...",
partitions.front().get_partition()));
}
});
bool AutoCommit = MicroServiceConfigGetBool("openwifi.kafka.auto.commit",false);
auto BatchSize = MicroServiceConfigGetInt("openwifi.kafka.consumer.batchsize",20);
bool AutoCommit = MicroServiceConfigGetBool("openwifi.kafka.auto.commit", false);
auto BatchSize = MicroServiceConfigGetInt("openwifi.kafka.consumer.batchsize", 20);
Types::StringVec Topics;
Types::StringVec Topics;
KafkaManager()->Topics(Topics);
Consumer.subscribe(Topics);
Running_ = true;
while(Running_) {
while (Running_) {
try {
std::vector<cppkafka::Message> MsgVec = Consumer.poll_batch(BatchSize, std::chrono::milliseconds(100));
for(auto const &Msg:MsgVec) {
std::vector<cppkafka::Message> MsgVec =
Consumer.poll_batch(BatchSize, std::chrono::milliseconds(100));
for (auto const &Msg : MsgVec) {
if (!Msg)
continue;
if (Msg.get_error()) {
if (!Msg.is_eof()) {
poco_error(Logger_,fmt::format("Error: {}", Msg.get_error().to_string()));
poco_error(Logger_,
fmt::format("Error: {}", Msg.get_error().to_string()));
}
if(!AutoCommit)
if (!AutoCommit)
Consumer.async_commit(Msg);
continue;
}
KafkaManager()->Dispatch(Msg.get_topic(), Msg.get_key(),Msg.get_payload() );
KafkaManager()->Dispatch(Msg.get_topic().c_str(), Msg.get_key(), std::make_shared<std::string>(Msg.get_payload()));
if (!AutoCommit)
Consumer.async_commit(Msg);
}
} catch (const cppkafka::HandleException &E) {
poco_warning(Logger_,fmt::format("Caught a Kafka exception (consumer): {}", E.what()));
poco_warning(Logger_,
fmt::format("Caught a Kafka exception (consumer): {}", E.what()));
} catch (const Poco::Exception &E) {
Logger_.log(E);
} catch (...) {
poco_error(Logger_,"std::exception");
poco_error(Logger_, "std::exception");
}
}
Consumer.unsubscribe();
poco_information(Logger_,"Stopped...");
poco_information(Logger_, "Stopped...");
}
void KafkaProducer::Start() {
if(!Running_) {
Running_=true;
if (!Running_) {
Running_ = true;
Worker_.start(*this);
}
}
void KafkaProducer::Stop() {
if(Running_) {
Running_=false;
if (Running_) {
Running_ = false;
Queue_.wakeUpAll();
Worker_.join();
}
}
void KafkaProducer::Produce(const std::string &Topic, const std::string &Key, const std::string &Payload) {
std::lock_guard G(Mutex_);
Queue_.enqueueNotification( new KafkaMessage(Topic,Key,Payload));
void KafkaProducer::Produce(const char *Topic, const std::string &Key,
std::shared_ptr<std::string> Payload) {
std::lock_guard G(Mutex_);
Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload));
}
void KafkaConsumer::Start() {
if(!Running_) {
Running_=true;
if (!Running_) {
Running_ = true;
Worker_.start(*this);
}
}
void KafkaConsumer::Stop() {
if(Running_) {
Running_=false;
if (Running_) {
Running_ = false;
Worker_.wakeUp();
Worker_.join();
}
}
void KafkaDispatcher::Start() {
if(!Running_) {
Running_=true;
if (!Running_) {
Running_ = true;
Worker_.start(*this);
}
}
void KafkaDispatcher::Stop() {
if(Running_) {
Running_=false;
if (Running_) {
Running_ = false;
Queue_.wakeUpAll();
Worker_.join();
}
}
auto KafkaDispatcher::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) {
auto KafkaDispatcher::RegisterTopicWatcher(const std::string &Topic,
Types::TopicNotifyFunction &F) {
std::lock_guard G(Mutex_);
auto It = Notifiers_.find(Topic);
if(It == Notifiers_.end()) {
if (It == Notifiers_.end()) {
Types::TopicNotifyFunctionList L;
L.emplace(L.end(),std::make_pair(F,FunctionId_));
L.emplace(L.end(), std::make_pair(F, FunctionId_));
Notifiers_[Topic] = std::move(L);
} else {
It->second.emplace(It->second.end(),std::make_pair(F,FunctionId_));
It->second.emplace(It->second.end(), std::make_pair(F, FunctionId_));
}
return FunctionId_++;
}
@@ -256,110 +265,115 @@ namespace OpenWifi {
void KafkaDispatcher::UnregisterTopicWatcher(const std::string &Topic, int Id) {
std::lock_guard G(Mutex_);
auto It = Notifiers_.find(Topic);
if(It != Notifiers_.end()) {
Types::TopicNotifyFunctionList & L = It->second;
for(auto it=L.begin(); it!=L.end(); it++)
if(it->second == Id) {
if (It != Notifiers_.end()) {
Types::TopicNotifyFunctionList &L = It->second;
for (auto it = L.begin(); it != L.end(); it++)
if (it->second == Id) {
L.erase(it);
break;
}
}
}
void KafkaDispatcher::Dispatch(const std::string &Topic, const std::string &Key, const std::string &Payload) {
std::lock_guard G(Mutex_);
void KafkaDispatcher::Dispatch(const char *Topic, const std::string &Key,
const std::shared_ptr<std::string> Payload) {
std::lock_guard G(Mutex_);
auto It = Notifiers_.find(Topic);
if(It!=Notifiers_.end()) {
if (It != Notifiers_.end()) {
Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload));
}
}
void KafkaDispatcher::run() {
Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-DISPATCHER", KafkaManager()->Logger().getChannel());
poco_information(Logger_,"Starting...");
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
Poco::Logger &Logger_ =
Poco::Logger::create("KAFKA-DISPATCHER", KafkaManager()->Logger().getChannel());
poco_information(Logger_, "Starting...");
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
Utils::SetThreadName("kafka:dispatch");
while(Note && Running_) {
auto Msg = dynamic_cast<KafkaMessage*>(Note.get());
if(Msg!= nullptr) {
while (Note && Running_) {
auto Msg = dynamic_cast<KafkaMessage *>(Note.get());
if (Msg != nullptr) {
auto It = Notifiers_.find(Msg->Topic());
if (It != Notifiers_.end()) {
const auto & FL = It->second;
for(const auto &[CallbackFunc,_]:FL) {
const auto &FL = It->second;
for (const auto &[CallbackFunc, _] : FL) {
CallbackFunc(Msg->Key(), Msg->Payload());
}
}
}
Note = Queue_.waitDequeueNotification();
}
poco_information(Logger_,"Stopped...");
poco_information(Logger_, "Stopped...");
}
void KafkaDispatcher::Topics(std::vector<std::string> &T) {
T.clear();
for(const auto &[TopicName,_]:Notifiers_)
for (const auto &[TopicName, _] : Notifiers_)
T.push_back(TopicName);
}
int KafkaManager::Start() {
if(!KafkaEnabled_)
if (!KafkaEnabled_)
return 0;
ConsumerThr_.Start();
ConsumerThr_.Start();
ProducerThr_.Start();
Dispatcher_.Start();
return 0;
}
void KafkaManager::Stop() {
if(KafkaEnabled_) {
poco_information(Logger(),"Stopping...");
void KafkaManager::Stop() {
if (KafkaEnabled_) {
poco_information(Logger(), "Stopping...");
Dispatcher_.Stop();
ProducerThr_.Stop();
ConsumerThr_.Stop();
poco_information(Logger(),"Stopped...");
poco_information(Logger(), "Stopped...");
return;
}
}
void KafkaManager::PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage ) {
if(KafkaEnabled_) {
ProducerThr_.Produce(topic,key,WrapMessage ? WrapSystemId(PayLoad) : PayLoad);
void KafkaManager::PostMessage(const char *topic, const std::string &key,
const std::shared_ptr<std::string> PayLoad, bool WrapMessage) {
if (KafkaEnabled_) {
ProducerThr_.Produce(topic, key, WrapMessage ? WrapSystemId(PayLoad) : PayLoad);
}
}
void KafkaManager::Dispatch(const std::string &Topic, const std::string & Key, const std::string &Payload) {
void KafkaManager::Dispatch(const char *Topic, const std::string &Key,
const std::shared_ptr<std::string> Payload) {
Dispatcher_.Dispatch(Topic, Key, Payload);
}
[[nodiscard]] std::string KafkaManager::WrapSystemId(const std::string & PayLoad) {
return SystemInfoWrapper_ + PayLoad + "}";
[[nodiscard]] const std::shared_ptr<std::string> KafkaManager::WrapSystemId(const std::shared_ptr<std::string> PayLoad) {
*PayLoad = SystemInfoWrapper_ + *PayLoad + "}";
return PayLoad;
}
uint64_t KafkaManager::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) {
if(KafkaEnabled_) {
return Dispatcher_.RegisterTopicWatcher(Topic,F);
uint64_t KafkaManager::RegisterTopicWatcher(const std::string &Topic,
Types::TopicNotifyFunction &F) {
if (KafkaEnabled_) {
return Dispatcher_.RegisterTopicWatcher(Topic, F);
} else {
return 0;
}
}
void KafkaManager::UnregisterTopicWatcher(const std::string &Topic, uint64_t Id) {
if(KafkaEnabled_) {
if (KafkaEnabled_) {
Dispatcher_.UnregisterTopicWatcher(Topic, Id);
}
}
void KafkaManager::Topics(std::vector<std::string> &T) {
Dispatcher_.Topics(T);
void KafkaManager::Topics(std::vector<std::string> &T) { Dispatcher_.Topics(T); }
void KafkaManager::PartitionAssignment(const cppkafka::TopicPartitionList &partitions) {
poco_information(
Logger(), fmt::format("Partition assigned: {}...", partitions.front().get_partition()));
}
void KafkaManager::PartitionAssignment(const cppkafka::TopicPartitionList& partitions) {
poco_information(Logger(),fmt::format("Partition assigned: {}...", partitions.front().get_partition()));
}
void KafkaManager::PartitionRevocation(const cppkafka::TopicPartitionList& partitions) {
poco_information(Logger(),fmt::format("Partition revocation: {}...",partitions.front().get_partition()));
void KafkaManager::PartitionRevocation(const cppkafka::TopicPartitionList &partitions) {
poco_information(Logger(), fmt::format("Partition revocation: {}...",
partitions.front().get_partition()));
}
} // namespace OpenWifi

View File

@@ -7,44 +7,43 @@
#include "Poco/Notification.h"
#include "Poco/NotificationQueue.h"
#include "framework/SubSystemServer.h"
#include "framework/OpenWifiTypes.h"
#include "framework/utils.h"
#include "framework/KafkaTopics.h"
#include "framework/OpenWifiTypes.h"
#include "framework/SubSystemServer.h"
#include "framework/utils.h"
#include "cppkafka/cppkafka.h"
namespace OpenWifi {
class KafkaMessage: public Poco::Notification {
class KafkaMessage : public Poco::Notification {
public:
KafkaMessage( const std::string &Topic, const std::string &Key, const std::string & Payload) :
Topic_(Topic), Key_(Key), Payload_(Payload) {
}
KafkaMessage(const char * Topic, const std::string &Key, std::shared_ptr<std::string> Payload)
: Topic_(Topic), Key_(Key), Payload_(Payload) {}
inline const std::string & Topic() { return Topic_; }
inline const std::string & Key() { return Key_; }
inline const std::string & Payload() { return Payload_; }
inline const char * Topic() { return Topic_; }
inline const std::string &Key() { return Key_; }
inline const std::string &Payload() { return *Payload_; }
private:
std::string Topic_;
std::string Key_;
std::string Payload_;
const char *Topic_;
std::string Key_;
std::shared_ptr<std::string> Payload_;
};
class KafkaProducer : public Poco::Runnable {
public:
void run () override;
void Start();
void Stop();
void Produce(const std::string &Topic, const std::string &Key, const std::string &Payload);
public:
void run() override;
void Start();
void Stop();
void Produce(const char *Topic, const std::string &Key, std::shared_ptr<std::string> Payload);
private:
std::recursive_mutex Mutex_;
Poco::Thread Worker_;
mutable std::atomic_bool Running_=false;
Poco::NotificationQueue Queue_;
};
std::recursive_mutex Mutex_;
Poco::Thread Worker_;
mutable std::atomic_bool Running_ = false;
Poco::NotificationQueue Queue_;
};
class KafkaConsumer : public Poco::Runnable {
public:
@@ -53,9 +52,9 @@ namespace OpenWifi {
void Stop();
private:
std::recursive_mutex Mutex_;
Poco::Thread Worker_;
mutable std::atomic_bool Running_=false;
std::recursive_mutex Mutex_;
Poco::Thread Worker_;
mutable std::atomic_bool Running_ = false;
};
class KafkaDispatcher : public Poco::Runnable {
@@ -64,26 +63,25 @@ namespace OpenWifi {
void Stop();
auto RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F);
void UnregisterTopicWatcher(const std::string &Topic, int Id);
void Dispatch(const std::string &Topic, const std::string &Key, const std::string &Payload);
void Dispatch(const char *Topic, const std::string &Key, const std::shared_ptr<std::string> Payload);
void run() override;
void Topics(std::vector<std::string> &T);
private:
std::recursive_mutex Mutex_;
Types::NotifyTable Notifiers_;
Poco::Thread Worker_;
mutable std::atomic_bool Running_=false;
uint64_t FunctionId_=1;
Poco::NotificationQueue Queue_;
std::recursive_mutex Mutex_;
Types::NotifyTable Notifiers_;
Poco::Thread Worker_;
mutable std::atomic_bool Running_ = false;
uint64_t FunctionId_ = 1;
Poco::NotificationQueue Queue_;
};
class KafkaManager : public SubSystemServer {
public:
friend class KafkaConsumer;
friend class KafkaProducer;
inline void initialize(Poco::Util::Application & self) override;
inline void initialize(Poco::Util::Application &self) override;
static auto instance() {
static auto instance_ = new KafkaManager;
@@ -93,30 +91,28 @@ namespace OpenWifi {
int Start() override;
void Stop() override;
void PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage = true );
void Dispatch(const std::string &Topic, const std::string & Key, const std::string &Payload);
[[nodiscard]] std::string WrapSystemId(const std::string & PayLoad);
void PostMessage(const char *topic, const std::string &key,
std::shared_ptr<std::string> PayLoad, bool WrapMessage = true);
void Dispatch(const char *Topic, const std::string &Key, std::shared_ptr<std::string> Payload);
[[nodiscard]] const std::shared_ptr<std::string> WrapSystemId(std::shared_ptr<std::string> PayLoad);
[[nodiscard]] inline bool Enabled() const { return KafkaEnabled_; }
uint64_t RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F);
void UnregisterTopicWatcher(const std::string &Topic, uint64_t Id);
void Topics(std::vector<std::string> &T);
private:
bool KafkaEnabled_ = false;
std::string SystemInfoWrapper_;
KafkaProducer ProducerThr_;
KafkaConsumer ConsumerThr_;
KafkaDispatcher Dispatcher_;
bool KafkaEnabled_ = false;
std::string SystemInfoWrapper_;
KafkaProducer ProducerThr_;
KafkaConsumer ConsumerThr_;
KafkaDispatcher Dispatcher_;
void PartitionAssignment(const cppkafka::TopicPartitionList& partitions);
void PartitionRevocation(const cppkafka::TopicPartitionList& partitions);
void PartitionAssignment(const cppkafka::TopicPartitionList &partitions);
void PartitionRevocation(const cppkafka::TopicPartitionList &partitions);
KafkaManager() noexcept:
SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka") {
}
KafkaManager() noexcept : SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka") {}
};
inline auto KafkaManager() { return KafkaManager::instance(); }
} // namespace OpenWifi

View File

@@ -10,33 +10,32 @@
#include <string>
namespace OpenWifi::KafkaTopics {
static const std::string HEALTHCHECK{"healthcheck"};
static const std::string STATE{"state"};
static const std::string CONNECTION{"connection"};
static const std::string WIFISCAN{"wifiscan"};
static const std::string ALERTS{"alerts"};
static const std::string COMMAND{"command"};
static const std::string SERVICE_EVENTS{"service_events"};
static const std::string DEVICE_EVENT_QUEUE{"device_event_queue"};
static const std::string DEVICE_TELEMETRY{"device_telemetry"};
static const std::string PROVISIONING_CHANGE{"provisioning_change"};
inline const char * HEALTHCHECK = "healthcheck";
inline const char * STATE = "state";
inline const char * CONNECTION = "connection";
inline const char * WIFISCAN = "wifiscan";
inline const char * ALERTS = "alerts";
inline const char * COMMAND = "command";
inline const char * SERVICE_EVENTS = "service_events";
inline const char * DEVICE_EVENT_QUEUE = "device_event_queue";
inline const char * DEVICE_TELEMETRY = "device_telemetry";
inline const char * PROVISIONING_CHANGE = "provisioning_change";
namespace ServiceEvents {
static const std::string EVENT_JOIN{"join"};
static const std::string EVENT_LEAVE{"leave"};
static const std::string EVENT_KEEP_ALIVE{"keep-alive"};
static const std::string EVENT_REMOVE_TOKEN{"remove-token"};
inline const char * EVENT_JOIN = "join";
inline const char * EVENT_LEAVE = "leave";
inline const char * EVENT_KEEP_ALIVE = "keep-alive";
inline const char * EVENT_REMOVE_TOKEN = "remove-token";
namespace Fields {
static const std::string EVENT{"event"};
static const std::string ID{"id"};
static const std::string TYPE{"type"};
static const std::string PUBLIC{"publicEndPoint"};
static const std::string PRIVATE{"privateEndPoint"};
static const std::string KEY{"key"};
static const std::string VRSN{"version"};
static const std::string TOKEN{"token"};
}
}
}
inline const char * EVENT = "event";
inline const char * ID = "id";
inline const char * TYPE = "type";
inline const char * PUBLIC = "publicEndPoint";
inline const char * PRIVATE = "privateEndPoint";
inline const char * KEY = "key";
inline const char * VRSN = "version";
inline const char * TOKEN = "token";
} // namespace Fields
} // namespace ServiceEvents
} // namespace OpenWifi::KafkaTopics

View File

@@ -2,40 +2,39 @@
// Created by stephane bourque on 2022-10-26.
//
#include "Poco/FileChannel.h"
#include "Poco/ConsoleChannel.h"
#include "Poco/PatternFormatter.h"
#include "Poco/FormattingChannel.h"
#include "Poco/AsyncChannel.h"
#include "Poco/NullChannel.h"
#include "Poco/SplitterChannel.h"
#include "Poco/Net/HTTPStreamFactory.h"
#include "Poco/Net/HTTPSStreamFactory.h"
#include "Poco/ConsoleChannel.h"
#include "Poco/FileChannel.h"
#include "Poco/FormattingChannel.h"
#include "Poco/JSON/JSONException.h"
#include "Poco/Net/FTPSStreamFactory.h"
#include "Poco/Net/FTPStreamFactory.h"
#include "Poco/Net/HTTPSStreamFactory.h"
#include "Poco/Net/HTTPStreamFactory.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/JSON/JSONException.h"
#include "Poco/NullChannel.h"
#include "Poco/PatternFormatter.h"
#include "Poco/SplitterChannel.h"
#include "framework/ALBserver.h"
#include "framework/AuthClient.h"
#include "framework/KafkaManager.h"
#include "framework/MicroService.h"
#include "framework/MicroServiceErrorHandler.h"
#include "framework/UI_WebSocketClientServer.h"
#include "framework/MicroServiceNames.h"
#include "framework/AuthClient.h"
#include "framework/ALBserver.h"
#include "framework/KafkaManager.h"
#include "framework/RESTAPI_GenericServerAccounting.h"
#include "framework/RESTAPI_ExtServer.h"
#include "framework/RESTAPI_GenericServerAccounting.h"
#include "framework/RESTAPI_IntServer.h"
#include "framework/utils.h"
#include "framework/UI_WebSocketClientServer.h"
#include "framework/WebSocketLogger.h"
#include "framework/utils.h"
namespace OpenWifi {
void MicroService::Exit(int Reason) {
std::exit(Reason);
}
void MicroService::Exit(int Reason) { std::exit(Reason); }
void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key, const std::string & Payload) {
void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key,
const std::string &Payload) {
std::lock_guard G(InfraMutex_);
try {
Poco::JSON::Parser P;
@@ -43,66 +42,101 @@ namespace OpenWifi {
if (Object->has(KafkaTopics::ServiceEvents::Fields::ID) &&
Object->has(KafkaTopics::ServiceEvents::Fields::EVENT)) {
uint64_t ID = Object->get(KafkaTopics::ServiceEvents::Fields::ID);
auto Event = Object->get(KafkaTopics::ServiceEvents::Fields::EVENT).toString();
uint64_t ID = Object->get(KafkaTopics::ServiceEvents::Fields::ID);
auto Event = Object->get(KafkaTopics::ServiceEvents::Fields::EVENT).toString();
if (ID != ID_) {
if( Event==KafkaTopics::ServiceEvents::EVENT_JOIN ||
Event==KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE ||
Event==KafkaTopics::ServiceEvents::EVENT_LEAVE ) {
if( Object->has(KafkaTopics::ServiceEvents::Fields::TYPE) &&
if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN ||
Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE ||
Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) {
if (Object->has(KafkaTopics::ServiceEvents::Fields::TYPE) &&
Object->has(KafkaTopics::ServiceEvents::Fields::PUBLIC) &&
Object->has(KafkaTopics::ServiceEvents::Fields::PRIVATE) &&
Object->has(KafkaTopics::ServiceEvents::Fields::VRSN) &&
Object->has(KafkaTopics::ServiceEvents::Fields::KEY)) {
auto PrivateEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString();
if (Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE && Services_.find(PrivateEndPoint) != Services_.end()) {
auto PrivateEndPoint =
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString();
if (Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE &&
Services_.find(PrivateEndPoint) != Services_.end()) {
Services_[PrivateEndPoint].LastUpdate = Utils::Now();
} else if (Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) {
Services_.erase(PrivateEndPoint);
poco_debug(logger(),fmt::format("Service {} ID={} leaving system.",Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),ID));
} else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN || Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) {
poco_debug(logger(),fmt::format("Service {} ID={} joining system.",Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),ID));
poco_debug(
logger(),
fmt::format(
"Service {} ID={} leaving system.",
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
ID));
} else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN ||
Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) {
poco_debug(
logger(),
fmt::format(
"Service {} ID={} joining system.",
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
ID));
Services_[PrivateEndPoint] = Types::MicroServiceMeta{
.Id = ID,
.Type = Poco::toLower(Object->get(KafkaTopics::ServiceEvents::Fields::TYPE).toString()),
.PrivateEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),
.PublicEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PUBLIC).toString(),
.AccessKey = Object->get(KafkaTopics::ServiceEvents::Fields::KEY).toString(),
.Version = Object->get(KafkaTopics::ServiceEvents::Fields::VRSN).toString(),
.LastUpdate = Utils::Now() };
.Type = Poco::toLower(
Object->get(KafkaTopics::ServiceEvents::Fields::TYPE)
.toString()),
.PrivateEndPoint =
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
.PublicEndPoint =
Object->get(KafkaTopics::ServiceEvents::Fields::PUBLIC)
.toString(),
.AccessKey =
Object->get(KafkaTopics::ServiceEvents::Fields::KEY)
.toString(),
.Version = Object->get(KafkaTopics::ServiceEvents::Fields::VRSN)
.toString(),
.LastUpdate = Utils::Now()};
std::string SvcList;
for (const auto &Svc: Services_) {
if(SvcList.empty())
for (const auto &Svc : Services_) {
if (SvcList.empty())
SvcList = Svc.second.Type;
else
SvcList += ", " + Svc.second.Type;
}
poco_information(logger(),fmt::format("Current list of microservices: {}", SvcList));
poco_information(
logger(),
fmt::format("Current list of microservices: {}", SvcList));
}
} else {
poco_error(logger(),fmt::format("KAFKA-MSG: invalid event '{}', missing a field.",Event));
poco_error(
logger(),
fmt::format("KAFKA-MSG: invalid event '{}', missing a field.",
Event));
}
} else if (Event==KafkaTopics::ServiceEvents::EVENT_REMOVE_TOKEN) {
if(Object->has(KafkaTopics::ServiceEvents::Fields::TOKEN)) {
#ifndef TIP_SECURITY_SERVICE
AuthClient()->RemovedCachedToken(Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString());
#endif
} else if (Event == KafkaTopics::ServiceEvents::EVENT_REMOVE_TOKEN) {
if (Object->has(KafkaTopics::ServiceEvents::Fields::TOKEN)) {
#ifndef TIP_SECURITY_SERVICE
AuthClient()->RemovedCachedToken(
Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString());
#endif
} else {
poco_error(logger(),fmt::format("KAFKA-MSG: invalid event '{}', missing token",Event));
poco_error(
logger(),
fmt::format("KAFKA-MSG: invalid event '{}', missing token", Event));
}
} else {
poco_error(logger(),fmt::format("Unknown Event: {} Source: {}", Event, ID));
poco_error(logger(),
fmt::format("Unknown Event: {} Source: {}", Event, ID));
}
}
} else {
poco_error(logger(),"Bad bus message.");
poco_error(logger(), "Bad bus message.");
std::ostringstream os;
Object->stringify(std::cout);
}
auto i=Services_.begin();
auto i = Services_.begin();
auto now = Utils::Now();
for(;i!=Services_.end();) {
if((now - i->second.LastUpdate)>60) {
for (; i != Services_.end();) {
if ((now - i->second.LastUpdate) > 60) {
i = Services_.erase(i);
} else
++i;
@@ -113,13 +147,13 @@ namespace OpenWifi {
}
}
Types::MicroServiceMetaVec MicroService::GetServices(const std::string & Type) {
Types::MicroServiceMetaVec MicroService::GetServices(const std::string &Type) {
std::lock_guard G(InfraMutex_);
auto T = Poco::toLower(Type);
Types::MicroServiceMetaVec Res;
for(const auto &[_,ServiceRec]:Services_) {
if(ServiceRec.Type==T)
Types::MicroServiceMetaVec Res;
for (const auto &[_, ServiceRec] : Services_) {
if (ServiceRec.Type == T)
Res.push_back(ServiceRec);
}
return Res;
@@ -128,23 +162,25 @@ namespace OpenWifi {
Types::MicroServiceMetaVec MicroService::GetServices() {
std::lock_guard G(InfraMutex_);
Types::MicroServiceMetaVec Res;
for(const auto &[_,ServiceRec]:Services_) {
Types::MicroServiceMetaVec Res;
for (const auto &[_, ServiceRec] : Services_) {
Res.push_back(ServiceRec);
}
return Res;
}
void MicroService::LoadConfigurationFile() {
std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR,".");
ConfigFileName_ = ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_;
std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR, ".");
ConfigFileName_ =
ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_;
Poco::Path ConfigFile(ConfigFileName_);
if(!ConfigFile.isFile())
{
std::cerr << DAEMON_APP_NAME << ": Configuration "
<< ConfigFile.toString() << " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR
+ " env variable the path of the " + DAEMON_PROPERTIES_FILENAME + " file." << std::endl;
if (!ConfigFile.isFile()) {
std::cerr << DAEMON_APP_NAME << ": Configuration " << ConfigFile.toString()
<< " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR +
" env variable the path of the " + DAEMON_PROPERTIES_FILENAME +
" file."
<< std::endl;
std::exit(Poco::Util::Application::EXIT_CONFIG);
}
@@ -159,11 +195,12 @@ namespace OpenWifi {
}
void MicroService::LoadMyConfig() {
NoAPISecurity_ = ConfigGetBool("openwifi.security.restapi.disable",false);
std::string KeyFile = ConfigPath("openwifi.service.key","");
if(!KeyFile.empty()) {
NoAPISecurity_ = ConfigGetBool("openwifi.security.restapi.disable", false);
std::string KeyFile = ConfigPath("openwifi.service.key", "");
if (!KeyFile.empty()) {
std::string KeyFilePassword = ConfigPath("openwifi.service.key.password", "");
AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword));
AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(
new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword));
Cipher_ = CipherFactory_.createCipher(*AppKey_);
Signer_.setRSAKey(AppKey_);
Signer_.addAllAlgorithms();
@@ -173,8 +210,8 @@ namespace OpenWifi {
}
ID_ = Utils::GetSystemId();
if(!DebugMode_)
DebugMode_ = ConfigGetBool("openwifi.system.debug",false);
if (!DebugMode_)
DebugMode_ = ConfigGetBool("openwifi.system.debug", false);
MyPrivateEndPoint_ = ConfigGetString("openwifi.system.uri.private");
MyPublicEndPoint_ = ConfigGetString("openwifi.system.uri.public");
UIURI_ = ConfigGetString("openwifi.system.uri.ui");
@@ -184,151 +221,170 @@ namespace OpenWifi {
void MicroService::InitializeLoggingSystem() {
static auto initialized = false;
if(!initialized) {
if (!initialized) {
initialized = true;
LoadConfigurationFile();
auto LoggingDestination = MicroService::instance().ConfigGetString("logging.type", "file");
auto LoggingFormat = MicroService::instance().ConfigGetString("logging.format",
"%Y-%m-%d %H:%M:%S.%i %s: [%p][thr:%I] %t");
auto LoggingDestination =
MicroService::instance().ConfigGetString("logging.type", "file");
auto LoggingFormat = MicroService::instance().ConfigGetString(
"logging.format", "%Y-%m-%d %H:%M:%S.%i %s: [%p][thr:%I] %t");
auto UseAsyncLogs_ = MicroService::instance().ConfigGetBool("logging.asynch", true);
auto DisableWebSocketLogging = MicroService::instance().ConfigGetBool("logging.websocket",false);
auto DisableWebSocketLogging =
MicroService::instance().ConfigGetBool("logging.websocket", false);
if (LoggingDestination == "null") {
Poco::AutoPtr<Poco::NullChannel> DevNull(new Poco::NullChannel);
Poco::Logger::root().setChannel(DevNull);
} else if (LoggingDestination == "console") {
SetConsoleLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
SetConsoleLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
} else if (LoggingDestination == "colorconsole") {
SetColorConsoleLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
SetColorConsoleLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
} else if (LoggingDestination == "sql") {
SetSQLLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
SetSQLLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
} else if (LoggingDestination == "syslog") {
SetSyslogLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
SetSyslogLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
} else {
SetFileLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat, DAEMON_ROOT_ENV_VAR);
}
SetFileLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat,
DAEMON_ROOT_ENV_VAR);
}
auto Level = Poco::Logger::parseLevel(MicroService::instance().ConfigGetString("logging.level", "debug"));
auto Level = Poco::Logger::parseLevel(
MicroService::instance().ConfigGetString("logging.level", "debug"));
Poco::Logger::root().setLevel(Level);
if(!DisableWebSocketLogging) {
if (!DisableWebSocketLogging) {
static const UI_WebSocketClientServer::NotificationTypeIdVec Notifications = {
{1, "log"}};
UI_WebSocketClientServer()->RegisterNotifications(Notifications);
}
}
}
}
void MicroService::SetConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern) {
void MicroService::SetConsoleLogs(bool UseAsync, bool DisableWebSocketLogging,
const std::string &FormatterPattern) {
Poco::AutoPtr<Poco::ConsoleChannel> Console(new Poco::ConsoleChannel);
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
Formatter->setProperty("pattern", FormatterPattern);
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, Console));
Poco::AutoPtr<Poco::ConsoleChannel> Console(new Poco::ConsoleChannel);
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
Formatter->setProperty("pattern", FormatterPattern);
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(
new Poco::FormattingChannel(Formatter, Console));
if(DisableWebSocketLogging) {
if(UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(FormattingChannel);
}
} else {
Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger);
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
Splitter->addChannel(WSLogger);
Splitter->addChannel(FormattingChannel);
if(UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(Splitter);
}
}
Poco::Logger::root().information(fmt::format("Enabled console logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging));
}
if (DisableWebSocketLogging) {
if (UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(FormattingChannel);
}
} else {
Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger);
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
Splitter->addChannel(WSLogger);
Splitter->addChannel(FormattingChannel);
if (UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(Splitter);
}
}
Poco::Logger::root().information(fmt::format("Enabled console logs: asynch={} websocket={}",
UseAsync, DisableWebSocketLogging));
}
void MicroService::SetColorConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern) {
void MicroService::SetColorConsoleLogs(bool UseAsync, bool DisableWebSocketLogging,
const std::string &FormatterPattern) {
Poco::AutoPtr<Poco::ColorConsoleChannel> Console(new Poco::ColorConsoleChannel);
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
Formatter->setProperty("pattern", FormatterPattern);
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, Console));
Poco::AutoPtr<Poco::ColorConsoleChannel> Console(new Poco::ColorConsoleChannel);
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
Formatter->setProperty("pattern", FormatterPattern);
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(
new Poco::FormattingChannel(Formatter, Console));
if(DisableWebSocketLogging) {
if(UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(FormattingChannel);
}
} else {
Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger);
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
Splitter->addChannel(WSLogger);
Splitter->addChannel(FormattingChannel);
if(UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(Splitter);
}
}
Poco::Logger::root().information(fmt::format("Enabled color console logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging));
}
if (DisableWebSocketLogging) {
if (UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(FormattingChannel);
}
} else {
Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger);
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
Splitter->addChannel(WSLogger);
Splitter->addChannel(FormattingChannel);
if (UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(Splitter);
}
}
Poco::Logger::root().information(
fmt::format("Enabled color console logs: asynch={} websocket={}", UseAsync,
DisableWebSocketLogging));
}
void MicroService::SetSQLLogs([[maybe_unused]] bool UseAsync,[[maybe_unused]] bool DisableWebSocketLogging,[[maybe_unused]] const std::string & FormatterPattern) {
//"CREATE TABLE T_POCO_LOG (Source VARCHAR, Name VARCHAR, ProcessId INTEGER, Thread VARCHAR, ThreadId INTEGER, Priority INTEGER, Text VARCHAR, DateTime DATE)"
}
void MicroService::SetSQLLogs([[maybe_unused]] bool UseAsync,
[[maybe_unused]] bool DisableWebSocketLogging,
[[maybe_unused]] const std::string &FormatterPattern) {
//"CREATE TABLE T_POCO_LOG (Source VARCHAR, Name VARCHAR, ProcessId INTEGER, Thread VARCHAR,
//ThreadId INTEGER, Priority INTEGER, Text VARCHAR, DateTime DATE)"
}
void MicroService::SetSyslogLogs([[maybe_unused]] bool UseAsync,[[maybe_unused]] bool DisableWebSocketLogging,[[maybe_unused]] const std::string & FormatterPattern) {
void MicroService::SetSyslogLogs([[maybe_unused]] bool UseAsync,
[[maybe_unused]] bool DisableWebSocketLogging,
[[maybe_unused]] const std::string &FormatterPattern) {}
}
void MicroService::SetFileLogs(bool UseAsync, bool DisableWebSocketLogging,
const std::string &FormatterPattern,
const std::string &root_env_var) {
std::string DefaultLogPath = fmt::format("${}/logs", root_env_var);
auto LoggingLocationDir =
MicroService::instance().ConfigPath("logging.path", DefaultLogPath);
Poco::File LD(LoggingLocationDir);
try {
if (!LD.exists()) {
LD.createDirectory();
}
} catch (const Poco::Exception &E) {
std::cout << "Cannot create " << LD.path() << " Error: " << E.message() << std::endl;
}
auto LoggingLocationDirFilePattern = LoggingLocationDir + "/log";
void MicroService::SetFileLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern, const std::string & root_env_var) {
std::string DefaultLogPath = fmt::format("${}/logs",root_env_var);
auto LoggingLocationDir = MicroService::instance().ConfigPath("logging.path", DefaultLogPath);
Poco::File LD(LoggingLocationDir);
try {
if(!LD.exists()) {
LD.createDirectory();
}
} catch(const Poco::Exception &E) {
std::cout << "Cannot create " << LD.path() << " Error: " << E.message() << std::endl;
}
auto LoggingLocationDirFilePattern = LoggingLocationDir + "/log";
Poco::AutoPtr<Poco::FileChannel> FileChannel(new Poco::FileChannel);
FileChannel->setProperty("rotation", "10 M");
FileChannel->setProperty("archive", "timestamp");
FileChannel->setProperty("purgeCount", "10");
FileChannel->setProperty("path", LoggingLocationDirFilePattern);
Poco::AutoPtr<Poco::FileChannel> FileChannel(new Poco::FileChannel);
FileChannel->setProperty("rotation", "10 M");
FileChannel->setProperty("archive", "timestamp");
FileChannel->setProperty("purgeCount", "10");
FileChannel->setProperty("path", LoggingLocationDirFilePattern);
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
Formatter->setProperty("pattern", FormatterPattern);
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(
new Poco::FormattingChannel(Formatter, FileChannel));
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
Formatter->setProperty("pattern", FormatterPattern);
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, FileChannel));
if(DisableWebSocketLogging) {
if(UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(FormattingChannel);
}
} else {
Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger);
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
Splitter->addChannel(WSLogger);
Splitter->addChannel(FormattingChannel);
if(UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(Splitter);
}
}
Poco::Logger::root().information(fmt::format("Enabled file logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging));
}
if (DisableWebSocketLogging) {
if (UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(FormattingChannel);
}
} else {
Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger);
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
Splitter->addChannel(WSLogger);
Splitter->addChannel(FormattingChannel);
if (UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
Poco::Logger::root().setChannel(Async);
} else {
Poco::Logger::root().setChannel(Splitter);
}
}
Poco::Logger::root().information(fmt::format("Enabled file logs: asynch={} websocket={}",
UseAsync, DisableWebSocketLogging));
}
void DaemonPostInitialization(Poco::Util::Application &self);
@@ -341,35 +397,39 @@ namespace OpenWifi {
SubSystems_.push_back(ALBHealthCheckServer());
SubSystems_.push_back(RESTAPI_ExtServer());
SubSystems_.push_back(RESTAPI_IntServer());
#ifndef TIP_SECURITY_SERVICE
#ifndef TIP_SECURITY_SERVICE
SubSystems_.push_back(AuthClient());
#endif
#endif
Poco::Net::initializeSSL();
Poco::Net::HTTPStreamFactory::registerFactory();
Poco::Net::HTTPSStreamFactory::registerFactory();
Poco::Net::FTPStreamFactory::registerFactory();
Poco::Net::FTPSStreamFactory::registerFactory();
Poco::File DataDir(ConfigPath("openwifi.system.data"));
Poco::File DataDir(ConfigPath("openwifi.system.data"));
DataDir_ = DataDir.path();
if(!DataDir.exists()) {
if (!DataDir.exists()) {
try {
DataDir.createDirectory();
} catch (const Poco::Exception &E) {
logger().log(E);
}
}
WWWAssetsDir_ = ConfigPath("openwifi.restapi.wwwassets","");
if(WWWAssetsDir_.empty())
WWWAssetsDir_ = ConfigPath("openwifi.restapi.wwwassets", "");
if (WWWAssetsDir_.empty())
WWWAssetsDir_ = DataDir_;
LoadMyConfig();
AllowExternalMicroServices_ = ConfigGetBool("allowexternalmicroservices", true);
InitializeSubSystemServers();
ServerApplication::initialize(self);
DaemonPostInitialization(self);
Types::TopicNotifyFunction F = [this](const std::string &Key,const std::string &Payload) { this->BusMessageReceived(Key, Payload); };
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) {
this->BusMessageReceived(Key, Payload);
};
KafkaManager()->RegisterTopicWatcher(KafkaTopics::SERVICE_EVENTS, F);
}
@@ -390,58 +450,64 @@ namespace OpenWifi {
Poco::Util::Option("help", "", "display help information on command line arguments")
.required(false)
.repeatable(false)
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleHelp)));
.callback(
Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleHelp)));
options.addOption(
Poco::Util::Option("file", "", "specify the configuration file")
.required(false)
.repeatable(false)
.argument("file")
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleConfig)));
options.addOption(Poco::Util::Option("file", "", "specify the configuration file")
.required(false)
.repeatable(false)
.argument("file")
.callback(Poco::Util::OptionCallback<MicroService>(
this, &MicroService::handleConfig)));
options.addOption(
Poco::Util::Option("debug", "", "to run in debug, set to true")
.required(false)
.repeatable(false)
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleDebug)));
options.addOption(Poco::Util::Option("debug", "", "to run in debug, set to true")
.required(false)
.repeatable(false)
.callback(Poco::Util::OptionCallback<MicroService>(
this, &MicroService::handleDebug)));
options.addOption(
Poco::Util::Option("logs", "", "specify the log directory and file (i.e. dir/file.log)")
.required(false)
.repeatable(false)
.argument("dir")
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleLogs)));
options.addOption(
Poco::Util::Option("version", "", "get the version and quit.")
.required(false)
.repeatable(false)
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleVersion)));
.callback(
Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleLogs)));
options.addOption(Poco::Util::Option("version", "", "get the version and quit.")
.required(false)
.repeatable(false)
.callback(Poco::Util::OptionCallback<MicroService>(
this, &MicroService::handleVersion)));
}
void MicroService::handleHelp([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) {
void MicroService::handleHelp([[maybe_unused]] const std::string &name,
[[maybe_unused]] const std::string &value) {
HelpRequested_ = true;
displayHelp();
stopOptionsProcessing();
}
void MicroService::handleVersion([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) {
void MicroService::handleVersion([[maybe_unused]] const std::string &name,
[[maybe_unused]] const std::string &value) {
HelpRequested_ = true;
std::cout << Version() << std::endl;
stopOptionsProcessing();
}
void MicroService::handleDebug([[maybe_unused]] const std::string &name, const std::string &value) {
if(value == "true")
DebugMode_ = true ;
void MicroService::handleDebug([[maybe_unused]] const std::string &name,
const std::string &value) {
if (value == "true")
DebugMode_ = true;
}
void MicroService::handleLogs([[maybe_unused]] const std::string &name, const std::string &value) {
void MicroService::handleLogs([[maybe_unused]] const std::string &name,
const std::string &value) {
LogDir_ = value;
}
void MicroService::handleConfig([[maybe_unused]] const std::string &name, const std::string &value) {
void MicroService::handleConfig([[maybe_unused]] const std::string &name,
const std::string &value) {
ConfigFileName_ = value;
}
@@ -454,31 +520,32 @@ namespace OpenWifi {
}
void MicroService::InitializeSubSystemServers() {
for(auto i:SubSystems_) {
for (auto i : SubSystems_) {
addSubsystem(i);
}
}
void MicroService::StartSubSystemServers() {
AddActivity("Starting");
for(auto i:SubSystems_) {
for (auto i : SubSystems_) {
i->Start();
}
EventBusManager_ = std::make_unique<EventBusManager>(Poco::Logger::create("EventBusManager",Poco::Logger::root().getChannel(),Poco::Logger::root().getLevel()));
EventBusManager_ = std::make_unique<EventBusManager>(Poco::Logger::create(
"EventBusManager", Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel()));
EventBusManager_->Start();
}
void MicroService::StopSubSystemServers() {
AddActivity("Stopping");
EventBusManager_->Stop();
for(auto i=SubSystems_.rbegin(); i!=SubSystems_.rend(); ++i) {
for (auto i = SubSystems_.rbegin(); i != SubSystems_.rend(); ++i) {
(*i)->Stop();
}
}
[[nodiscard]] std::string MicroService::CreateUUID() {
static std::random_device rd;
static std::mt19937_64 gen(rd());
static std::random_device rd;
static std::mt19937_64 gen(rd());
static std::uniform_int_distribution<> dis(0, 15);
static std::uniform_int_distribution<> dis2(8, 11);
@@ -508,7 +575,8 @@ namespace OpenWifi {
return ss.str();
}
bool MicroService::SetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) {
bool MicroService::SetSubsystemLogLevel(const std::string &SubSystem,
const std::string &Level) {
try {
auto P = Poco::Logger::parseLevel(Level);
auto Sub = Poco::toLower(SubSystem);
@@ -526,7 +594,7 @@ namespace OpenWifi {
}
}
}
} catch (const Poco::Exception & E) {
} catch (const Poco::Exception &E) {
std::cerr << "Exception" << std::endl;
}
return false;
@@ -543,7 +611,7 @@ namespace OpenWifi {
Types::StringVec MicroService::GetSubSystems() const {
Types::StringVec Result;
for(auto i:SubSystems_)
for (auto i : SubSystems_)
Result.push_back(Poco::toLower(i->Name()));
return Result;
}
@@ -551,35 +619,32 @@ namespace OpenWifi {
Types::StringPairVec MicroService::GetLogLevels() {
Types::StringPairVec Result;
for(auto &i:SubSystems_) {
auto P = std::make_pair( i->Name(), Utils::LogLevelToString(i->GetLoggingLevel()));
for (auto &i : SubSystems_) {
auto P = std::make_pair(i->Name(), Utils::LogLevelToString(i->GetLoggingLevel()));
Result.push_back(P);
}
return Result;
}
const Types::StringVec & MicroService::GetLogLevelNames() {
static Types::StringVec LevelNames{"none", "fatal", "critical", "error", "warning", "notice", "information", "debug", "trace" };
const Types::StringVec &MicroService::GetLogLevelNames() {
static Types::StringVec LevelNames{"none", "fatal", "critical", "error", "warning",
"notice", "information", "debug", "trace"};
return LevelNames;
}
uint64_t MicroService::ConfigGetInt(const std::string &Key,uint64_t Default) {
return (uint64_t) config().getInt64(Key,Default);
uint64_t MicroService::ConfigGetInt(const std::string &Key, uint64_t Default) {
return (uint64_t)config().getInt64(Key, Default);
}
uint64_t MicroService::ConfigGetInt(const std::string &Key) {
return config().getInt(Key);
uint64_t MicroService::ConfigGetInt(const std::string &Key) { return config().getInt(Key); }
uint64_t MicroService::ConfigGetBool(const std::string &Key, bool Default) {
return config().getBool(Key, Default);
}
uint64_t MicroService::ConfigGetBool(const std::string &Key,bool Default) {
return config().getBool(Key,Default);
}
uint64_t MicroService::ConfigGetBool(const std::string &Key) { return config().getBool(Key); }
uint64_t MicroService::ConfigGetBool(const std::string &Key) {
return config().getBool(Key);
}
std::string MicroService::ConfigGetString(const std::string &Key,const std::string & Default) {
std::string MicroService::ConfigGetString(const std::string &Key, const std::string &Default) {
return config().getString(Key, Default);
}
@@ -587,7 +652,7 @@ namespace OpenWifi {
return config().getString(Key);
}
std::string MicroService::ConfigPath(const std::string &Key,const std::string & Default) {
std::string MicroService::ConfigPath(const std::string &Key, const std::string &Default) {
std::string R = config().getString(Key, Default);
return Poco::Path::expand(R);
}
@@ -598,28 +663,30 @@ namespace OpenWifi {
}
std::string MicroService::Encrypt(const std::string &S) {
if(NoBuiltInCrypto_) {
if (NoBuiltInCrypto_) {
return S;
}
return Cipher_->encryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);;
return Cipher_->encryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);
;
}
std::string MicroService::Decrypt(const std::string &S) {
if(NoBuiltInCrypto_) {
if (NoBuiltInCrypto_) {
return S;
}
return Cipher_->decryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);;
return Cipher_->decryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);
;
}
std::string MicroService::MakeSystemEventMessage( const std::string & Type ) const {
Poco::JSON::Object Obj;
Obj.set(KafkaTopics::ServiceEvents::Fields::EVENT,Type);
Obj.set(KafkaTopics::ServiceEvents::Fields::ID,ID_);
Obj.set(KafkaTopics::ServiceEvents::Fields::TYPE,Poco::toLower(DAEMON_APP_NAME));
Obj.set(KafkaTopics::ServiceEvents::Fields::PUBLIC,MyPublicEndPoint_);
Obj.set(KafkaTopics::ServiceEvents::Fields::PRIVATE,MyPrivateEndPoint_);
Obj.set(KafkaTopics::ServiceEvents::Fields::KEY,MyHash_);
Obj.set(KafkaTopics::ServiceEvents::Fields::VRSN,Version_);
std::string MicroService::MakeSystemEventMessage(const std::string &Type) const {
Poco::JSON::Object Obj;
Obj.set(KafkaTopics::ServiceEvents::Fields::EVENT, Type);
Obj.set(KafkaTopics::ServiceEvents::Fields::ID, ID_);
Obj.set(KafkaTopics::ServiceEvents::Fields::TYPE, Poco::toLower(DAEMON_APP_NAME));
Obj.set(KafkaTopics::ServiceEvents::Fields::PUBLIC, MyPublicEndPoint_);
Obj.set(KafkaTopics::ServiceEvents::Fields::PRIVATE, MyPrivateEndPoint_);
Obj.set(KafkaTopics::ServiceEvents::Fields::KEY, MyHash_);
Obj.set(KafkaTopics::ServiceEvents::Fields::VRSN, Version_);
std::stringstream ResultText;
Poco::JSON::Stringifier::stringify(Obj, ResultText);
return ResultText.str();
@@ -638,75 +705,73 @@ namespace OpenWifi {
void MicroService::SavePID() {
try {
std::ofstream O;
O.open(MicroService::instance().DataDir() + "/pidfile",std::ios::binary | std::ios::trunc);
O.open(MicroService::instance().DataDir() + "/pidfile",
std::ios::binary | std::ios::trunc);
O << Poco::Process::id();
O.close();
} catch (...)
{
} catch (...) {
std::cout << "Could not save system ID" << std::endl;
}
}
int MicroService::main([[maybe_unused]] const ArgVec &args) {
MicroServiceErrorHandler ErrorHandler(*this);
MicroServiceErrorHandler ErrorHandler(*this);
Poco::ErrorHandler::set(&ErrorHandler);
if (!HelpRequested_) {
SavePID();
Poco::Logger &logger = Poco::Logger::get(DAEMON_APP_NAME);
logger.notice(fmt::format("Starting {} version {}.",DAEMON_APP_NAME, Version()));
logger.notice(fmt::format("Starting {} version {}.", DAEMON_APP_NAME, Version()));
if(Poco::Net::Socket::supportsIPv6())
poco_information(logger,"System supports IPv6.");
if (Poco::Net::Socket::supportsIPv6())
poco_information(logger, "System supports IPv6.");
else
poco_information(logger,"System does NOT support IPv6.");
poco_information(logger, "System does NOT support IPv6.");
if (config().getBool("application.runAsDaemon", false)) {
poco_information(logger,"Starting as a daemon.");
poco_information(logger, "Starting as a daemon.");
}
poco_information(logger,fmt::format("System ID set to {}",ID_));
poco_information(logger, fmt::format("System ID set to {}", ID_));
StartSubSystemServers();
waitForTerminationRequest();
StopSubSystemServers();
logger.notice(fmt::format("Stopped {}...",DAEMON_APP_NAME));
logger.notice(fmt::format("Stopped {}...", DAEMON_APP_NAME));
}
return Application::EXIT_OK;
}
void MicroService::AddActivity(const std::string &Activity) {
if(!DataDir_.empty()) {
std::string ActivityFile{ DataDir_ + "/activity.log"};
if (!DataDir_.empty()) {
std::string ActivityFile{DataDir_ + "/activity.log"};
try {
std::ofstream of(ActivityFile,std::ios_base::app | std::ios_base::out );
std::ofstream of(ActivityFile, std::ios_base::app | std::ios_base::out);
auto t = std::chrono::system_clock::now();
std::time_t now = std::chrono::system_clock::to_time_t(t);
of << Activity << " at " << std::ctime(&now) ;
of << Activity << " at " << std::ctime(&now);
} catch (...) {
}
}
}
[[nodiscard]] std::string MicroService::Sign(Poco::JWT::Token &T, const std::string &Algo) {
if(NoBuiltInCrypto_) {
if (NoBuiltInCrypto_) {
return T.toString();
} else {
return Signer_.sign(T,Algo);
return Signer_.sign(T, Algo);
}
}
void MicroService::DeleteOverrideConfiguration() {
Poco::File F(DataDir_ + ExtraConfigurationFilename);
Poco::File F(DataDir_ + ExtraConfigurationFilename);
try {
if(F.exists())
if (F.exists())
F.remove();
} catch (...) {
}
}
}
} // namespace OpenWifi

View File

@@ -9,12 +9,11 @@
#pragma once
#include <array>
#include <iostream>
#include <vector>
#include <fstream>
#include <random>
#include <ctime>
#include <fstream>
#include <iostream>
#include <random>
#include <vector>
// This must be defined for poco_debug and poco_trace macros to function.
@@ -23,97 +22,94 @@
#endif
namespace OpenWifi {
inline uint64_t Now() { return std::time(nullptr); };
}
inline uint64_t Now() { return std::time(nullptr); };
} // namespace OpenWifi
#include "Poco/Util/Application.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Crypto/RSAKey.h"
#include "Poco/Crypto/CipherFactory.h"
#include "Poco/AutoPtr.h"
#include "Poco/Crypto/Cipher.h"
#include "Poco/Crypto/CipherFactory.h"
#include "Poco/Crypto/RSAKey.h"
#include "Poco/Environment.h"
#include "Poco/JSON/Object.h"
#include "Poco/JWT/Signer.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Process.h"
#include "Poco/Util/Application.h"
#include "Poco/Util/HelpFormatter.h"
#include "Poco/JSON/Object.h"
#include "Poco/AutoPtr.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/PropertyFileConfiguration.h"
#include "Poco/JWT/Signer.h"
#include "Poco/Environment.h"
#include "Poco/Util/ServerApplication.h"
#include "framework/OpenWifiTypes.h"
#include "framework/EventBusManager.h"
#include "framework/SubSystemServer.h"
#include "framework/ow_constants.h"
#include "framework/utils.h"
#include "framework/SubSystemServer.h"
#include "framework/EventBusManager.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "cppkafka/cppkafka.h"
#include "fmt/core.h"
#include "nlohmann/json.hpp"
#include "ow_version.h"
#include "fmt/core.h"
#define _OWDEBUG_ std::cout<< __FILE__ <<":" << __LINE__ << std::endl;
#define _OWDEBUG_ std::cout << __FILE__ << ":" << __LINE__ << std::endl;
// #define _OWDEBUG_ Logger().debug(Poco::format("%s: %lu",__FILE__,__LINE__));
namespace OpenWifi {
class MicroService : public Poco::Util::ServerApplication {
public:
explicit MicroService( std::string PropFile,
std::string RootEnv,
std::string ConfigVar,
std::string AppName,
uint64_t BusTimer,
SubSystemVec Subsystems) :
DAEMON_PROPERTIES_FILENAME(std::move(PropFile)),
DAEMON_ROOT_ENV_VAR(std::move(RootEnv)),
DAEMON_CONFIG_ENV_VAR(std::move(ConfigVar)),
DAEMON_APP_NAME(std::move(AppName)),
DAEMON_BUS_TIMER(BusTimer),
SubSystems_(std::move(Subsystems)),
Logger_(Poco::Logger::get("FRAMEWORK")) {
instance_ = this;
RandomEngine_.seed(std::chrono::steady_clock::now().time_since_epoch().count());
explicit MicroService(std::string PropFile, std::string RootEnv, std::string ConfigVar,
std::string AppName, uint64_t BusTimer, SubSystemVec Subsystems)
: DAEMON_PROPERTIES_FILENAME(std::move(PropFile)),
DAEMON_ROOT_ENV_VAR(std::move(RootEnv)), DAEMON_CONFIG_ENV_VAR(std::move(ConfigVar)),
DAEMON_APP_NAME(std::move(AppName)), DAEMON_BUS_TIMER(BusTimer),
SubSystems_(std::move(Subsystems)), Logger_(Poco::Logger::get("FRAMEWORK")) {
instance_ = this;
RandomEngine_.seed(std::chrono::steady_clock::now().time_since_epoch().count());
// Logger_ = Poco::Logger::root().get("BASE-SVC");
}
inline static const char * ExtraConfigurationFilename = "/configuration_override.json";
inline static const char *ExtraConfigurationFilename = "/configuration_override.json";
inline void SaveConfig() { PropConfigurationFile_->save(ConfigFileName_); }
inline auto UpdateConfig() { return PropConfigurationFile_; }
inline bool NoAPISecurity() const { return NoAPISecurity_; }
inline Poco::ThreadPool & TimerPool() { return TimerPool_; }
inline Poco::ThreadPool &TimerPool() { return TimerPool_; }
[[nodiscard]] std::string Version() { return Version_; }
[[nodiscard]] inline const std::string & DataDir() { return DataDir_; }
[[nodiscard]] inline const std::string & WWWAssetsDir() { return WWWAssetsDir_; }
[[nodiscard]] inline const std::string &DataDir() { return DataDir_; }
[[nodiscard]] inline const std::string &WWWAssetsDir() { return WWWAssetsDir_; }
[[nodiscard]] bool Debug() const { return DebugMode_; }
[[nodiscard]] uint64_t ID() const { return ID_; }
[[nodiscard]] std::string Hash() const { return MyHash_; };
[[nodiscard]] std::string ServiceType() const { return DAEMON_APP_NAME; };
[[nodiscard]] std::string PrivateEndPoint() const { return MyPrivateEndPoint_; };
[[nodiscard]] std::string PublicEndPoint() const { return MyPublicEndPoint_; };
[[nodiscard]] const SubSystemVec & GetFullSubSystems() { return SubSystems_; }
[[nodiscard]] const SubSystemVec &GetFullSubSystems() { return SubSystems_; }
inline uint64_t DaemonBusTimer() const { return DAEMON_BUS_TIMER; };
[[nodiscard]] const std::string & AppName() { return DAEMON_APP_NAME; }
[[nodiscard]] const std::string &AppName() { return DAEMON_APP_NAME; }
static inline uint64_t GetPID() { return Poco::Process::id(); };
[[nodiscard]] inline const std::string GetPublicAPIEndPoint() { return MyPublicEndPoint_ + "/api/v1"; };
[[nodiscard]] inline const std::string & GetUIURI() const { return UIURI_;};
[[nodiscard]] inline uint64_t Random(uint64_t ceiling) { return (RandomEngine_() % ceiling); }
[[nodiscard]] inline uint64_t Random(uint64_t min, uint64_t max) {
return ((RandomEngine_() % (max-min)) + min);
[[nodiscard]] inline const std::string GetPublicAPIEndPoint() {
return MyPublicEndPoint_ + "/api/v1";
};
[[nodiscard]] inline const std::string &GetUIURI() const { return UIURI_; };
[[nodiscard]] inline uint64_t Random(uint64_t ceiling) {
return (RandomEngine_() % ceiling);
}
virtual void GetExtraConfiguration(Poco::JSON::Object & Cfg) {
Cfg.set("additionalConfiguration",false);
}
static MicroService & instance() { return *instance_; }
[[nodiscard]] inline uint64_t Random(uint64_t min, uint64_t max) {
return ((RandomEngine_() % (max - min)) + min);
}
virtual void GetExtraConfiguration(Poco::JSON::Object &Cfg) {
Cfg.set("additionalConfiguration", false);
}
static MicroService &instance() { return *instance_; }
inline void Exit(int Reason);
void BusMessageReceived(const std::string &Key, const std::string & Payload);
Types::MicroServiceMetaVec GetServices(const std::string & Type);
inline void Exit(int Reason);
void BusMessageReceived(const std::string &Key, const std::string &Payload);
Types::MicroServiceMetaVec GetServices(const std::string &Type);
Types::MicroServiceMetaVec GetServices();
void LoadConfigurationFile();
void Reload();
@@ -136,69 +132,78 @@ namespace OpenWifi {
void Reload(const std::string &Sub);
Types::StringVec GetSubSystems() const;
Types::StringPairVec GetLogLevels();
const Types::StringVec & GetLogLevelNames();
uint64_t ConfigGetInt(const std::string &Key,uint64_t Default);
const Types::StringVec &GetLogLevelNames();
uint64_t ConfigGetInt(const std::string &Key, uint64_t Default);
uint64_t ConfigGetInt(const std::string &Key);
uint64_t ConfigGetBool(const std::string &Key,bool Default);
uint64_t ConfigGetBool(const std::string &Key, bool Default);
uint64_t ConfigGetBool(const std::string &Key);
std::string ConfigGetString(const std::string &Key,const std::string & Default);
std::string ConfigGetString(const std::string &Key, const std::string &Default);
std::string ConfigGetString(const std::string &Key);
std::string ConfigPath(const std::string &Key,const std::string & Default);
std::string ConfigPath(const std::string &Key, const std::string &Default);
std::string ConfigPath(const std::string &Key);
std::string Encrypt(const std::string &S);
std::string Decrypt(const std::string &S);
std::string MakeSystemEventMessage( const std::string & Type ) const;
std::string MakeSystemEventMessage(const std::string &Type) const;
[[nodiscard]] bool IsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request);
static void SavePID();
int main(const ArgVec &args) override;
void InitializeLoggingSystem();
void InitializeLoggingSystem();
void DeleteOverrideConfiguration();
[[nodiscard]] std::string Sign(Poco::JWT::Token &T, const std::string &Algo);
void AddActivity(const std::string &Activity);
static void SetConsoleLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
static void SetColorConsoleLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
static void SetSQLLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
static void SetSyslogLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
static void SetFileLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern, const std::string & root_env_var);
static void SetConsoleLogs(bool UseAsync, bool AllowWebSocket,
const std::string &FormatterPattern);
static void SetColorConsoleLogs(bool UseAsync, bool AllowWebSocket,
const std::string &FormatterPattern);
static void SetSQLLogs(bool UseAsync, bool AllowWebSocket,
const std::string &FormatterPattern);
static void SetSyslogLogs(bool UseAsync, bool AllowWebSocket,
const std::string &FormatterPattern);
static void SetFileLogs(bool UseAsync, bool AllowWebSocket,
const std::string &FormatterPattern,
const std::string &root_env_var);
inline bool AllowExternalMicroServices() const { return AllowExternalMicroServices_; }
private:
static MicroService * instance_;
bool HelpRequested_ = false;
std::string LogDir_;
std::string ConfigFileName_;
uint64_t ID_ = 1;
Poco::SharedPtr<Poco::Crypto::RSAKey> AppKey_;
bool DebugMode_ = false;
std::string DataDir_;
std::string WWWAssetsDir_;
Poco::Crypto::CipherFactory & CipherFactory_ = Poco::Crypto::CipherFactory::defaultFactory();
Poco::Crypto::Cipher * Cipher_ = nullptr;
Types::MicroServiceMetaMap Services_;
std::string MyHash_;
std::string MyPrivateEndPoint_;
std::string MyPublicEndPoint_;
std::string UIURI_;
std::string Version_{ OW_VERSION::VERSION + "("+ OW_VERSION::BUILD + ")" + " - " + OW_VERSION::HASH };
std::recursive_mutex InfraMutex_;
std::default_random_engine RandomEngine_;
Poco::Util::PropertyFileConfiguration * PropConfigurationFile_ = nullptr;
std::string DAEMON_PROPERTIES_FILENAME;
std::string DAEMON_ROOT_ENV_VAR;
std::string DAEMON_CONFIG_ENV_VAR;
std::string DAEMON_APP_NAME;
uint64_t DAEMON_BUS_TIMER;
SubSystemVec SubSystems_;
bool NoAPISecurity_=false;
bool NoBuiltInCrypto_=false;
Poco::JWT::Signer Signer_;
Poco::Logger &Logger_;
Poco::ThreadPool TimerPool_{"timer:pool",2,32};
std::unique_ptr<EventBusManager> EventBusManager_;
};
static MicroService *instance_;
bool HelpRequested_ = false;
std::string LogDir_;
std::string ConfigFileName_;
uint64_t ID_ = 1;
Poco::SharedPtr<Poco::Crypto::RSAKey> AppKey_;
bool DebugMode_ = false;
std::string DataDir_;
std::string WWWAssetsDir_;
Poco::Crypto::CipherFactory &CipherFactory_ = Poco::Crypto::CipherFactory::defaultFactory();
Poco::Crypto::Cipher *Cipher_ = nullptr;
Types::MicroServiceMetaMap Services_;
std::string MyHash_;
std::string MyPrivateEndPoint_;
std::string MyPublicEndPoint_;
std::string UIURI_;
std::string Version_{OW_VERSION::VERSION + "(" + OW_VERSION::BUILD + ")" + " - " +
OW_VERSION::HASH};
std::recursive_mutex InfraMutex_;
std::default_random_engine RandomEngine_;
Poco::Util::PropertyFileConfiguration *PropConfigurationFile_ = nullptr;
std::string DAEMON_PROPERTIES_FILENAME;
std::string DAEMON_ROOT_ENV_VAR;
std::string DAEMON_CONFIG_ENV_VAR;
std::string DAEMON_APP_NAME;
uint64_t DAEMON_BUS_TIMER;
SubSystemVec SubSystems_;
bool NoAPISecurity_ = false;
bool NoBuiltInCrypto_ = false;
bool AllowExternalMicroServices_ = false;
Poco::JWT::Signer Signer_;
Poco::Logger &Logger_;
Poco::ThreadPool TimerPool_{"timer:pool", 2, 32};
std::unique_ptr<EventBusManager> EventBusManager_;
};
inline MicroService * MicroService::instance_ = nullptr;
inline MicroService *MicroService::instance_ = nullptr;
}
} // namespace OpenWifi

View File

@@ -4,25 +4,24 @@
#pragma once
#include "fmt/format.h"
#include "Poco/Util/Application.h"
#include "Poco/ErrorHandler.h"
#include "Poco/JSON/JSONException.h"
#include "Poco/JSON/Template.h"
#include "Poco/Net/NetException.h"
#include "Poco/Net/SSLException.h"
#include "Poco/JSON/Template.h"
#include "Poco/JSON/JSONException.h"
#include "Poco/Thread.h"
#include "Poco/Util/Application.h"
#include "fmt/format.h"
namespace OpenWifi {
class MicroServiceErrorHandler : public Poco::ErrorHandler {
public:
explicit MicroServiceErrorHandler(Poco::Util::Application &App) : App_(App) {
}
explicit MicroServiceErrorHandler(Poco::Util::Application &App) : App_(App) {}
inline void exception(const Poco::Exception & Base) override {
inline void exception(const Poco::Exception &Base) override {
try {
if(Poco::Thread::current()!= nullptr) {
if (Poco::Thread::current() != nullptr) {
t_name = Poco::Thread::current()->getName();
t_id = Poco::Thread::current()->id();
} else {
@@ -34,179 +33,167 @@ namespace OpenWifi {
Base.rethrow();
} catch (const Poco::Net::InvalidCertificateException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::InvalidCertificateException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(),
fmt::format("Poco::Net::InvalidCertificateException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(),
E.what()));
} catch (const Poco::Net::InvalidSocketException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::InvalidSocketException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(),
fmt::format("Poco::Net::InvalidSocketException thr_name={} thr_id={} "
"code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(),
E.what()));
} catch (const Poco::Net::WebSocketException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::WebSocketException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::Net::WebSocketException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::Net::ConnectionResetException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::ConnectionResetException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(),
fmt::format("Poco::Net::ConnectionResetException thr_name={} thr_id={} "
"code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(),
E.what()));
} catch (const Poco::Net::CertificateValidationException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::CertificateValidationException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(),
fmt::format("Poco::Net::CertificateValidationException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(),
E.what()));
} catch (const Poco::Net::SSLConnectionUnexpectedlyClosedException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::SSLConnectionUnexpectedlyClosedException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(),
fmt::format("Poco::Net::SSLConnectionUnexpectedlyClosedException "
"thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(),
E.what()));
} catch (const Poco::Net::SSLContextException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::SSLContextException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::Net::SSLContextException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::Net::SSLException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::SSLException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::Net::SSLException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::Net::InvalidAddressException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::InvalidAddressException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(),
fmt::format("Poco::Net::InvalidAddressException thr_name={} thr_id={} "
"code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(),
E.what()));
} catch (const Poco::Net::NetException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::NetException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::Net::NetException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::IOException &E) {
poco_error(App_.logger(), fmt::format("Poco::IOException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(
App_.logger(),
fmt::format(
"Poco::IOException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(), E.what()));
} catch (const Poco::TimeoutException &E) {
poco_error(App_.logger(), fmt::format("Poco::TimeoutException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::TimeoutException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::NoThreadAvailableException &E) {
poco_error(App_.logger(), fmt::format("Poco::NoThreadAvailableException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(),
fmt::format("Poco::NoThreadAvailableException thr_name={} thr_id={} "
"code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(),
E.what()));
} catch (const Poco::OutOfMemoryException &E) {
poco_error(App_.logger(), fmt::format("Poco::OutOfMemoryException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::OutOfMemoryException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::BadCastException &E) {
poco_error(App_.logger(), fmt::format("Poco::BadCastException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::BadCastException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::DataException &E) {
poco_error(App_.logger(), fmt::format("Poco::DataException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(
App_.logger(),
fmt::format(
"Poco::DataException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(), E.what()));
} catch (const Poco::PoolOverflowException &E) {
poco_error(App_.logger(), fmt::format("Poco::PoolOverflowException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::PoolOverflowException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::SystemException &E) {
poco_error(App_.logger(), fmt::format("Poco::SystemException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::SystemException thr_name={} thr_id={} "
"code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::RuntimeException &E) {
poco_error(App_.logger(), fmt::format("Poco::RuntimeException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::RuntimeException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::JSON::JSONTemplateException &E) {
poco_error(App_.logger(), fmt::format("Poco::JSON::JSONTemplateException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(),
fmt::format("Poco::JSON::JSONTemplateException thr_name={} thr_id={} "
"code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(),
E.what()));
} catch (const Poco::JSON::JSONException &E) {
poco_error(App_.logger(), fmt::format("Poco::JSON::JSONException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::JSON::JSONException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::ApplicationException &E) {
poco_error(App_.logger(), fmt::format("Poco::ApplicationException thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(App_.logger(), fmt::format("Poco::ApplicationException thr_name={} "
"thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(),
E.message(), E.what()));
} catch (const Poco::Exception &E) {
poco_error(App_.logger(), fmt::format("Poco::Exception thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(),
E.displayText(),
E.message(),
E.what()));
poco_error(
App_.logger(),
fmt::format(
"Poco::Exception thr_name={} thr_id={} code={} text={} msg={} what={}",
t_name, t_id, E.code(), E.displayText(), E.message(), E.what()));
} catch (...) {
poco_error(App_.logger(), fmt::format("Poco:Generic thr_name={}",t_name, t_id));
poco_error(App_.logger(), fmt::format("Poco:Generic thr_name={}", t_name, t_id));
}
}
inline void exception(const std::exception & E) override {
if(Poco::Thread::current()!= nullptr) {
inline void exception(const std::exception &E) override {
if (Poco::Thread::current() != nullptr) {
t_name = Poco::Thread::current()->getName();
t_id = Poco::Thread::current()->id();
} else {
t_name = "startup_code";
t_id = 0;
}
poco_warning(App_.logger(), fmt::format("std::exception in {}: {} thr_id={}",
t_name,E.what(),
t_id));
poco_warning(App_.logger(),
fmt::format("std::exception in {}: {} thr_id={}", t_name, E.what(), t_id));
}
inline void exception() override {
if(Poco::Thread::current()!= nullptr) {
if (Poco::Thread::current() != nullptr) {
t_name = Poco::Thread::current()->getName();
t_id = Poco::Thread::current()->id();
} else {
t_name = "startup_code";
t_id = 0;
}
poco_warning(App_.logger(), fmt::format("generic exception in {} thr_id={}",
t_name, t_id));
poco_warning(App_.logger(),
fmt::format("generic exception in {} thr_id={}", t_name, t_id));
}
private:
Poco::Util::Application &App_;
std::string t_name;
int t_id=0;
Poco::Util::Application &App_;
std::string t_name;
int t_id = 0;
};
}
} // namespace OpenWifi

View File

@@ -4,8 +4,8 @@
#pragma once
#include <string>
#include <map>
#include <string>
#include "Poco/BasicEvent.h"
#include "Poco/ExpireLRUCache.h"
@@ -13,46 +13,40 @@
namespace OpenWifi {
class ConfigurationEntry {
public:
template <typename T> explicit ConfigurationEntry(T def) :
Default_(def),
Current_(def){
template <typename T> explicit ConfigurationEntry(T def) : Default_(def), Current_(def) {}
template <typename T>
explicit ConfigurationEntry(T def, T cur, const std::string &Hint = "")
: Default_(def), Current_(cur), Hint_(Hint) {}
inline ConfigurationEntry() = default;
inline ~ConfigurationEntry() = default;
template <typename T> explicit operator T() const { return std::get<T>(Current_); }
inline ConfigurationEntry &operator=(const char *v) {
Current_ = std::string(v);
return *this;
}
template <typename T> ConfigurationEntry &operator=(T v) {
Current_ = (T)v;
return *this;
}
template <typename T> explicit ConfigurationEntry(T def, T cur, const std::string &Hint="") :
Default_(def),
Current_(cur),
Hint_(Hint){
}
inline ConfigurationEntry()=default;
inline ~ConfigurationEntry()=default;
template <typename T> explicit operator T () const { return std::get<T>(Current_); }
inline ConfigurationEntry & operator=(const char *v) { Current_ = std::string(v); return *this;}
template <typename T> ConfigurationEntry & operator=(T v) { Current_ = (T) v; return *this;}
void reset() {
Current_ = Default_;
}
void reset() { Current_ = Default_; }
private:
std::variant<bool,uint64_t,std::string> Default_, Current_;
std::variant<bool, uint64_t, std::string> Default_, Current_;
std::string Hint_;
};
inline std::string to_string(const ConfigurationEntry &v) { return (std::string) v; }
inline std::string to_string(const ConfigurationEntry &v) { return (std::string)v; }
typedef std::map<std::string,ConfigurationEntry> ConfigurationMap_t;
typedef std::map<std::string, ConfigurationEntry> ConfigurationMap_t;
template <typename T> class FIFO {
public:
explicit FIFO(uint32_t Size) :
Size_(Size) {
Buffer_ = new T [Size_];
}
explicit FIFO(uint32_t Size) : Size_(Size) { Buffer_ = new T[Size_]; }
~FIFO() {
delete [] Buffer_;
}
~FIFO() { delete[] Buffer_; }
mutable Poco::BasicEvent<bool> Writable_;
mutable Poco::BasicEvent<bool> Readable_;
@@ -84,7 +78,7 @@ namespace OpenWifi {
Write_ = 0;
}
Used_++;
MaxEverUsed_ = std::max(Used_,MaxEverUsed_);
MaxEverUsed_ = std::max(Used_, MaxEverUsed_);
}
bool flag = true;
Readable_.notify(this, flag);
@@ -93,40 +87,32 @@ namespace OpenWifi {
inline bool isFull() {
std::lock_guard M(Mutex_);
return Used_==Buffer_->capacity();
return Used_ == Buffer_->capacity();
}
inline auto MaxEverUser() const { return MaxEverUsed_; }
private:
std::recursive_mutex Mutex_;
uint32_t Size_=0;
uint32_t Read_=0;
uint32_t Write_=0;
uint32_t Used_=0;
uint32_t MaxEverUsed_=0;
T * Buffer_ = nullptr;
std::recursive_mutex Mutex_;
uint32_t Size_ = 0;
uint32_t Read_ = 0;
uint32_t Write_ = 0;
uint32_t Used_ = 0;
uint32_t MaxEverUsed_ = 0;
T *Buffer_ = nullptr;
};
template <class Record, typename KeyType = std::string, int Size=256, int Expiry=60000> class RecordCache {
template <class Record, typename KeyType = std::string, int Size = 256, int Expiry = 60000>
class RecordCache {
public:
explicit RecordCache( KeyType Record::* Q) :
MemberOffset(Q){
};
inline auto update(const Record &R) {
return Cache_.update(R.*MemberOffset, R);
}
inline auto get(const KeyType &K) {
return Cache_.get(K);
}
inline auto remove(const KeyType &K) {
return Cache_.remove(K);
}
inline auto remove(const Record &R) {
return Cache_.remove(R.*MemberOffset);
}
explicit RecordCache(KeyType Record::*Q) : MemberOffset(Q){};
inline auto update(const Record &R) { return Cache_.update(R.*MemberOffset, R); }
inline auto get(const KeyType &K) { return Cache_.get(K); }
inline auto remove(const KeyType &K) { return Cache_.remove(K); }
inline auto remove(const Record &R) { return Cache_.remove(R.*MemberOffset); }
private:
KeyType Record::* MemberOffset;
Poco::ExpireLRUCache<KeyType,Record> Cache_{Size,Expiry};
KeyType Record::*MemberOffset;
Poco::ExpireLRUCache<KeyType, Record> Cache_{Size, Expiry};
};
}
} // namespace OpenWifi

View File

@@ -2,120 +2,131 @@
// Created by stephane bourque on 2022-10-25.
//
#include "framework/MicroService.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/MicroService.h"
#include "framework/ALBserver.h"
namespace OpenWifi {
const std::string &MicroServiceDataDirectory() { return MicroService::instance().DataDir(); }
const std::string &MicroServiceDataDirectory() { return MicroService::instance().DataDir(); }
Types::MicroServiceMetaVec MicroServiceGetServices(const std::string &Type) {
return MicroService::instance().GetServices(Type);
}
Types::MicroServiceMetaVec MicroServiceGetServices(const std::string &Type) {
return MicroService::instance().GetServices(Type);
}
Types::MicroServiceMetaVec MicroServiceGetServices() {
return MicroService::instance().GetServices();
}
Types::MicroServiceMetaVec MicroServiceGetServices() {
return MicroService::instance().GetServices();
}
std::string MicroServicePublicEndPoint() { return MicroService::instance().PublicEndPoint(); }
std::string MicroServicePublicEndPoint() { return MicroService::instance().PublicEndPoint(); }
std::string MicroServiceConfigGetString(const std::string &Key, const std::string &DefaultValue) {
return MicroService::instance().ConfigGetString(Key, DefaultValue);
}
std::string MicroServiceConfigGetString(const std::string &Key,
const std::string &DefaultValue) {
return MicroService::instance().ConfigGetString(Key, DefaultValue);
}
bool MicroServiceConfigGetBool(const std::string &Key, bool DefaultValue) {
return MicroService::instance().ConfigGetBool(Key, DefaultValue);
}
bool MicroServiceConfigGetBool(const std::string &Key, bool DefaultValue) {
return MicroService::instance().ConfigGetBool(Key, DefaultValue);
}
std::uint64_t MicroServiceConfigGetInt(const std::string &Key, std::uint64_t DefaultValue) {
return MicroService::instance().ConfigGetInt(Key, DefaultValue);
}
std::uint64_t MicroServiceConfigGetInt(const std::string &Key, std::uint64_t DefaultValue) {
return MicroService::instance().ConfigGetInt(Key, DefaultValue);
}
std::string MicroServicePrivateEndPoint() { return MicroService::instance().PrivateEndPoint(); }
std::string MicroServicePrivateEndPoint() { return MicroService::instance().PrivateEndPoint(); }
std::uint64_t MicroServiceID() { return MicroService::instance().ID(); }
std::uint64_t MicroServiceID() { return MicroService::instance().ID(); }
bool MicroServiceIsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request) {
return MicroService::instance().IsValidAPIKEY(Request);
}
bool MicroServiceIsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request) {
return MicroService::instance().IsValidAPIKEY(Request);
}
bool MicroServiceNoAPISecurity() { return MicroService::instance().NoAPISecurity(); }
bool MicroServiceNoAPISecurity() { return MicroService::instance().NoAPISecurity(); }
void MicroServiceLoadConfigurationFile() { MicroService::instance().LoadConfigurationFile(); }
void MicroServiceLoadConfigurationFile() { MicroService::instance().LoadConfigurationFile(); }
void MicroServiceReload() { MicroService::instance().Reload(); }
void MicroServiceReload() { MicroService::instance().Reload(); }
void MicroServiceReload(const std::string &Type) { MicroService::instance().Reload(Type); }
void MicroServiceReload(const std::string &Type) { MicroService::instance().Reload(Type); }
const Types::StringVec MicroServiceGetLogLevelNames() {
return MicroService::instance().GetLogLevelNames();
}
Types::StringVec MicroServiceGetLogLevelNames() {
return MicroService::instance().GetLogLevelNames();
}
const Types::StringVec MicroServiceGetSubSystems() {
return MicroService::instance().GetSubSystems();
}
Types::StringVec MicroServiceGetSubSystems() {
return MicroService::instance().GetSubSystems();
}
Types::StringPairVec MicroServiceGetLogLevels() { return MicroService::instance().GetLogLevels(); }
Types::StringPairVec MicroServiceGetLogLevels() {
return MicroService::instance().GetLogLevels();
}
bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) {
return MicroService::instance().SetSubsystemLogLevel(SubSystem, Level);
}
bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) {
return MicroService::instance().SetSubsystemLogLevel(SubSystem, Level);
}
void MicroServiceGetExtraConfiguration(Poco::JSON::Object &Answer) {
MicroService::instance().GetExtraConfiguration(Answer);
}
void MicroServiceGetExtraConfiguration(Poco::JSON::Object &Answer) {
MicroService::instance().GetExtraConfiguration(Answer);
}
std::string MicroServiceVersion() { return MicroService::instance().Version(); }
std::string MicroServiceVersion() { return MicroService::instance().Version(); }
std::uint64_t MicroServiceUptimeTotalSeconds() {
return MicroService::instance().uptime().totalSeconds();
}
std::uint64_t MicroServiceUptimeTotalSeconds() {
return MicroService::instance().uptime().totalSeconds();
}
std::uint64_t MicroServiceStartTimeEpochTime() {
return MicroService::instance().startTime().epochTime();
}
std::uint64_t MicroServiceStartTimeEpochTime() {
return MicroService::instance().startTime().epochTime();
}
std::string MicroServiceGetUIURI() { return MicroService::instance().GetUIURI(); }
std::string MicroServiceGetUIURI() { return MicroService::instance().GetUIURI(); }
const SubSystemVec MicroServiceGetFullSubSystems() {
return MicroService::instance().GetFullSubSystems();
}
SubSystemVec MicroServiceGetFullSubSystems() {
return MicroService::instance().GetFullSubSystems();
}
std::string MicroServiceCreateUUID() { return MicroService::CreateUUID(); }
std::string MicroServiceCreateUUID() { return MicroService::CreateUUID(); }
std::uint64_t MicroServiceDaemonBusTimer() { return MicroService::instance().DaemonBusTimer(); }
std::uint64_t MicroServiceDaemonBusTimer() { return MicroService::instance().DaemonBusTimer(); }
std::string MicroServiceMakeSystemEventMessage(const std::string &Type) {
return MicroService::instance().MakeSystemEventMessage(Type);
}
std::string MicroServiceMakeSystemEventMessage(const char *Type) {
return MicroService::instance().MakeSystemEventMessage(Type);
}
Poco::ThreadPool &MicroServiceTimerPool() { return MicroService::instance().TimerPool(); }
Poco::ThreadPool &MicroServiceTimerPool() { return MicroService::instance().TimerPool(); }
std::string MicroServiceConfigPath(const std::string &Key,
const std::string &DefaultValue) {
return MicroService::instance().ConfigPath(Key, DefaultValue);
}
std::string MicroServiceConfigPath(const std::string &Key, const std::string &DefaultValue) {
return MicroService::instance().ConfigPath(Key, DefaultValue);
}
std::string MicroServiceWWWAssetsDir() {
return MicroService::instance().WWWAssetsDir();
}
std::string MicroServiceWWWAssetsDir() { return MicroService::instance().WWWAssetsDir(); }
std::uint64_t MicroServiceRandom(std::uint64_t Start,std::uint64_t End) {
return MicroService::instance().Random(Start, End);
}
std::uint64_t MicroServiceRandom(std::uint64_t Start, std::uint64_t End) {
return MicroService::instance().Random(Start, End);
}
std::uint64_t MicroServiceRandom(std::uint64_t Range) {
return MicroService::instance().Random(Range);
}
std::uint64_t MicroServiceRandom(std::uint64_t Range) {
return MicroService::instance().Random(Range);
}
std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo) {
return MicroService::instance().Sign(T, Algo);
}
std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo) {
return MicroService::instance().Sign(T, Algo);
}
std::string MicroServiceGetPublicAPIEndPoint() {
return MicroService::instance().GetPublicAPIEndPoint();
}
std::string MicroServiceGetPublicAPIEndPoint() {
return MicroService::instance().GetPublicAPIEndPoint();
}
void MicroServiceDeleteOverrideConfiguration() {
return MicroService::instance().DeleteOverrideConfiguration();
}
}
bool AllowExternalMicroServices() {
return MicroService::instance().AllowExternalMicroServices();
}
void MicroServiceALBCallback( std::string Callback()) {
return ALBHealthCheckServer()->RegisterExtendedHealthMessage(Callback);
}
} // namespace OpenWifi

View File

@@ -8,20 +8,20 @@
#include "framework/OpenWifiTypes.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/JSON/Object.h"
#include "Poco/ThreadPool.h"
#include "Poco/JWT/Token.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/ThreadPool.h"
namespace OpenWifi {
class SubSystemServer;
using SubSystemVec=std::vector<SubSystemServer *>;
const std::string & MicroServiceDataDirectory();
Types::MicroServiceMetaVec MicroServiceGetServices(const std::string & Type);
Types::MicroServiceMetaVec MicroServiceGetServices();
using SubSystemVec = std::vector<SubSystemServer *>;
const std::string &MicroServiceDataDirectory();
Types::MicroServiceMetaVec MicroServiceGetServices(const std::string &Type);
Types::MicroServiceMetaVec MicroServiceGetServices();
std::string MicroServicePublicEndPoint();
std::string MicroServiceConfigGetString(const std::string &Key, const std::string &DefaultValue);
std::string MicroServiceConfigGetString(const std::string &Key,
const std::string &DefaultValue);
bool MicroServiceConfigGetBool(const std::string &Key, bool DefaultValue);
std::uint64_t MicroServiceConfigGetInt(const std::string &Key, std::uint64_t DefaultValue);
std::string MicroServicePrivateEndPoint();
@@ -31,8 +31,8 @@ namespace OpenWifi {
void MicroServiceLoadConfigurationFile();
void MicroServiceReload();
void MicroServiceReload(const std::string &Type);
const Types::StringVec MicroServiceGetLogLevelNames();
const Types::StringVec MicroServiceGetSubSystems();
Types::StringVec MicroServiceGetLogLevelNames();
Types::StringVec MicroServiceGetSubSystems();
Types::StringPairVec MicroServiceGetLogLevels();
bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level);
void MicroServiceGetExtraConfiguration(Poco::JSON::Object &Answer);
@@ -40,17 +40,18 @@ namespace OpenWifi {
std::uint64_t MicroServiceUptimeTotalSeconds();
std::uint64_t MicroServiceStartTimeEpochTime();
std::string MicroServiceGetUIURI();
const SubSystemVec MicroServiceGetFullSubSystems();
SubSystemVec MicroServiceGetFullSubSystems();
std::string MicroServiceCreateUUID();
std::uint64_t MicroServiceDaemonBusTimer();
std::string MicroServiceMakeSystemEventMessage( const std::string & Type );
Poco::ThreadPool & MicroServiceTimerPool();
std::string MicroServiceConfigPath(const std::string &Key,
const std::string &DefaultValue);
std::string MicroServiceWWWAssetsDir();
std::uint64_t MicroServiceRandom(std::uint64_t Start,std::uint64_t End);
std::uint64_t MicroServiceRandom(std::uint64_t Range);
std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo);
std::string MicroServiceGetPublicAPIEndPoint();
std::string MicroServiceMakeSystemEventMessage(const char *Type);
Poco::ThreadPool &MicroServiceTimerPool();
std::string MicroServiceConfigPath(const std::string &Key, const std::string &DefaultValue);
std::string MicroServiceWWWAssetsDir();
std::uint64_t MicroServiceRandom(std::uint64_t Start, std::uint64_t End);
std::uint64_t MicroServiceRandom(std::uint64_t Range);
std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo);
std::string MicroServiceGetPublicAPIEndPoint();
void MicroServiceDeleteOverrideConfiguration();
}
bool AllowExternalMicroServices();
void MicroServiceALBCallback( std::string Callback());
} // namespace OpenWifi

View File

@@ -10,13 +10,13 @@ namespace OpenWifi {
static const std::string uSERVICE_SECURITY{"owsec"};
static const std::string uSERVICE_GATEWAY{"owgw"};
static const std::string uSERVICE_FIRMWARE{ "owfms"};
static const std::string uSERVICE_TOPOLOGY{ "owtopo"};
static const std::string uSERVICE_PROVISIONING{ "owprov"};
static const std::string uSERVICE_OWLS{ "owls"};
static const std::string uSERVICE_SUBCRIBER{ "owsub"};
static const std::string uSERVICE_INSTALLER{ "owinst"};
static const std::string uSERVICE_ANALYTICS{ "owanalytics"};
static const std::string uSERVICE_OWRRM{ "owrrm"};
static const std::string uSERVICE_FIRMWARE{"owfms"};
static const std::string uSERVICE_TOPOLOGY{"owtopo"};
static const std::string uSERVICE_PROVISIONING{"owprov"};
static const std::string uSERVICE_OWLS{"owls"};
static const std::string uSERVICE_SUBCRIBER{"owsub"};
static const std::string uSERVICE_INSTALLER{"owinst"};
static const std::string uSERVICE_ANALYTICS{"owanalytics"};
static const std::string uSERVICE_OWRRM{"owrrm"};
}
} // namespace OpenWifi

View File

@@ -4,286 +4,281 @@
#include "OpenAPIRequests.h"
#include "Poco/JSON/Parser.h"
#include "Poco/Logger.h"
#include "Poco/URI.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/JSON/Parser.h"
#include "Poco/URI.h"
#include "fmt/format.h"
#include "framework/MicroServiceFuncs.h"
namespace OpenWifi {
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestGet::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) {
try {
Poco::Net::HTTPServerResponse::HTTPStatus
OpenAPIRequestGet::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string &BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_);
for(auto const &Svc:Services) {
Poco::URI URI(Svc.PrivateEndPoint);
auto Services = MicroServiceGetServices(Type_);
for (auto const &Svc : Services) {
Poco::URI URI(Svc.PrivateEndPoint);
auto Secure = (URI.getScheme() == "https");
auto Secure = (URI.getScheme() == "https");
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET,
Path,
Poco::Net::HTTPMessage::HTTP_1_1);
std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET, Path,
Poco::Net::HTTPMessage::HTTP_1_1);
poco_debug(Poco::Logger::get("REST-CALLER-GET"), fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
poco_debug(Poco::Logger::get("REST-CALLER-GET"),
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
if(BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
if(Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
}
}
}
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-GET").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestPut::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_);
for(auto const &Svc:Services) {
Poco::URI URI(Svc.PrivateEndPoint);
auto Secure = (URI.getScheme() == "https");
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
poco_debug(Poco::Logger::get("REST-CALLER-PUT"), fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_PUT,
Path,
Poco::Net::HTTPMessage::HTTP_1_1);
std::ostringstream obody;
Poco::JSON::Stringifier::stringify(Body_,obody);
Request.setContentType("application/json");
Request.setContentLength(obody.str().size());
if(BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
if(Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
if (BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
if (Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
}
return Response.getStatus();
}
} catch (const Poco::Exception &E) {
Poco::Logger::get("REST-CALLER-GET").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-PUT").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestPost::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_);
Poco::Net::HTTPServerResponse::HTTPStatus
OpenAPIRequestPut::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string &BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_);
for (auto const &Svc : Services) {
Poco::URI URI(Svc.PrivateEndPoint);
for(auto const &Svc:Services) {
Poco::URI URI(Svc.PrivateEndPoint);
auto Secure = (URI.getScheme() == "https");
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
auto Secure = (URI.getScheme() == "https");
poco_debug(Poco::Logger::get("REST-CALLER-PUT"),
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
std::string Path(URI.getPathAndQuery());
poco_debug(Poco::Logger::get("REST-CALLER-POST"),fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_PUT, Path,
Poco::Net::HTTPMessage::HTTP_1_1);
std::ostringstream obody;
Poco::JSON::Stringifier::stringify(Body_, obody);
std::string Path(URI.getPathAndQuery());
Request.setContentType("application/json");
Request.setContentLength(obody.str().size());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST,
Path,
Poco::Net::HTTPMessage::HTTP_1_1);
std::ostringstream obody;
Poco::JSON::Stringifier::stringify(Body_,obody);
Request.setContentType("application/json");
Request.setContentLength(obody.str().size());
if(BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
if(Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
if (BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
if (Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
}
return Response.getStatus();
}
} catch (const Poco::Exception &E) {
Poco::Logger::get("REST-CALLER-PUT").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-POST").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestDelete::Do(const std::string & BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_);
Poco::Net::HTTPServerResponse::HTTPStatus
OpenAPIRequestPost::Do(Poco::JSON::Object::Ptr &ResponseObject,
const std::string &BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_);
for(auto const &Svc:Services) {
Poco::URI URI(Svc.PrivateEndPoint);
for (auto const &Svc : Services) {
Poco::URI URI(Svc.PrivateEndPoint);
auto Secure = (URI.getScheme() == "https");
auto Secure = (URI.getScheme() == "https");
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
poco_debug(Poco::Logger::get("REST-CALLER-DELETE"),fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
poco_debug(Poco::Logger::get("REST-CALLER-POST"),
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
std::string Path(URI.getPathAndQuery());
std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_DELETE,
Path,
Poco::Net::HTTPMessage::HTTP_1_1);
if(BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
if(Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
Session.receiveResponse(Response);
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
Session.receiveResponse(Response);
return Response.getStatus();
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST, Path,
Poco::Net::HTTPMessage::HTTP_1_1);
std::ostringstream obody;
Poco::JSON::Stringifier::stringify(Body_, obody);
Request.setContentType("application/json");
Request.setContentLength(obody.str().size());
if (BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
if (Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
}
}
} catch (const Poco::Exception &E) {
Poco::Logger::get("REST-CALLER-POST").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-DELETE").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
Poco::Net::HTTPServerResponse::HTTPStatus
OpenAPIRequestDelete::Do(const std::string &BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_);
for (auto const &Svc : Services) {
Poco::URI URI(Svc.PrivateEndPoint);
auto Secure = (URI.getScheme() == "https");
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
poco_debug(Poco::Logger::get("REST-CALLER-DELETE"),
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_DELETE, Path,
Poco::Net::HTTPMessage::HTTP_1_1);
if (BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
if (Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
Session.receiveResponse(Response);
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
Session.receiveResponse(Response);
return Response.getStatus();
}
}
} catch (const Poco::Exception &E) {
Poco::Logger::get("REST-CALLER-DELETE").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
} // namespace OpenWifi

View File

@@ -15,96 +15,79 @@ namespace OpenWifi {
class OpenAPIRequestGet {
public:
explicit OpenAPIRequestGet( const std::string & Type,
const std::string & EndPoint,
const Types::StringPairVec & QueryData,
uint64_t msTimeout,
const std::string &LoggingStr=""):
Type_(Type),
EndPoint_(EndPoint),
QueryData_(QueryData),
msTimeout_(msTimeout),
LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = "");
explicit OpenAPIRequestGet(const std::string &Type, const std::string &EndPoint,
const Types::StringPairVec &QueryData, uint64_t msTimeout,
const std::string &LoggingStr = "")
: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject,
const std::string &BearerToken = "");
private:
std::string Type_;
std::string EndPoint_;
Types::StringPairVec QueryData_;
uint64_t msTimeout_;
std::string LoggingStr_;
std::string Type_;
std::string EndPoint_;
Types::StringPairVec QueryData_;
uint64_t msTimeout_;
std::string LoggingStr_;
};
class OpenAPIRequestPut {
public:
explicit OpenAPIRequestPut( const std::string & Type,
const std::string & EndPoint,
const Types::StringPairVec & QueryData,
const Poco::JSON::Object & Body,
uint64_t msTimeout,
const std::string &LoggingStr=""):
Type_(Type),
EndPoint_(EndPoint),
QueryData_(QueryData),
msTimeout_(msTimeout),
Body_(Body),
LoggingStr_(LoggingStr){};
explicit OpenAPIRequestPut(const std::string &Type, const std::string &EndPoint,
const Types::StringPairVec &QueryData,
const Poco::JSON::Object &Body, uint64_t msTimeout,
const std::string &LoggingStr = "")
: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
Body_(Body), LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = "");
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject,
const std::string &BearerToken = "");
private:
std::string Type_;
std::string EndPoint_;
Types::StringPairVec QueryData_;
uint64_t msTimeout_;
Poco::JSON::Object Body_;
std::string LoggingStr_;
std::string Type_;
std::string EndPoint_;
Types::StringPairVec QueryData_;
uint64_t msTimeout_;
Poco::JSON::Object Body_;
std::string LoggingStr_;
};
class OpenAPIRequestPost {
public:
explicit OpenAPIRequestPost( const std::string & Type,
const std::string & EndPoint,
const Types::StringPairVec & QueryData,
const Poco::JSON::Object & Body,
uint64_t msTimeout,
const std::string &LoggingStr=""):
Type_(Type),
EndPoint_(EndPoint),
QueryData_(QueryData),
msTimeout_(msTimeout),
Body_(Body),
LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = "");
explicit OpenAPIRequestPost(const std::string &Type, const std::string &EndPoint,
const Types::StringPairVec &QueryData,
const Poco::JSON::Object &Body, uint64_t msTimeout,
const std::string &LoggingStr = "")
: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
Body_(Body), LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject,
const std::string &BearerToken = "");
private:
std::string Type_;
std::string EndPoint_;
Types::StringPairVec QueryData_;
uint64_t msTimeout_;
Poco::JSON::Object Body_;
std::string LoggingStr_;
std::string Type_;
std::string EndPoint_;
Types::StringPairVec QueryData_;
uint64_t msTimeout_;
Poco::JSON::Object Body_;
std::string LoggingStr_;
};
class OpenAPIRequestDelete {
public:
explicit OpenAPIRequestDelete( const std::string & Type,
const std::string & EndPoint,
const Types::StringPairVec & QueryData,
uint64_t msTimeout,
const std::string &LoggingStr=""):
Type_(Type),
EndPoint_(EndPoint),
QueryData_(QueryData),
msTimeout_(msTimeout),
LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(const std::string & BearerToken = "");
explicit OpenAPIRequestDelete(const std::string &Type, const std::string &EndPoint,
const Types::StringPairVec &QueryData, uint64_t msTimeout,
const std::string &LoggingStr = "")
: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(const std::string &BearerToken = "");
private:
std::string Type_;
std::string EndPoint_;
Types::StringPairVec QueryData_;
uint64_t msTimeout_;
Poco::JSON::Object Body_;
std::string LoggingStr_;
std::string Type_;
std::string EndPoint_;
Types::StringPairVec QueryData_;
uint64_t msTimeout_;
Poco::JSON::Object Body_;
std::string LoggingStr_;
};
} // namespace OpenWifi

View File

@@ -4,70 +4,74 @@
#pragma once
#include <functional>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <functional>
#include <string>
#include <queue>
#include <list>
#include <set>
namespace OpenWifi::Types {
typedef std::pair<std::string,std::string> StringPair;
typedef std::vector<StringPair> StringPairVec;
typedef std::queue<StringPair> StringPairQueue;
typedef std::vector<std::string> StringVec;
typedef std::set<std::string> StringSet;
typedef std::map<std::string,std::set<std::string>> StringMapStringSet;
typedef std::function<void(const std::string &, const std::string &)> TopicNotifyFunction;
typedef std::list<std::pair<TopicNotifyFunction,int>> TopicNotifyFunctionList;
typedef std::map<std::string, TopicNotifyFunctionList> NotifyTable;
typedef std::map<std::string,uint64_t> CountedMap;
typedef std::vector<uint64_t> TagList;
typedef std::string UUID_t;
typedef std::vector<UUID_t> UUIDvec_t;
typedef std::map<std::string,std::map<uint32_t,uint64_t>> Counted3DMapSII;
typedef std::pair<std::string, std::string> StringPair;
typedef std::vector<StringPair> StringPairVec;
typedef std::queue<StringPair> StringPairQueue;
typedef std::vector<std::string> StringVec;
typedef std::set<std::string> StringSet;
typedef std::map<std::string, std::set<std::string>> StringMapStringSet;
typedef std::function<void(const std::string &, const std::string &)> TopicNotifyFunction;
typedef std::list<std::pair<TopicNotifyFunction, int>> TopicNotifyFunctionList;
typedef std::map<std::string, TopicNotifyFunctionList> NotifyTable;
typedef std::map<std::string, uint64_t> CountedMap;
typedef std::vector<uint64_t> TagList;
typedef std::string UUID_t;
typedef std::vector<UUID_t> UUIDvec_t;
typedef std::map<std::string, std::map<uint32_t, uint64_t>> Counted3DMapSII;
typedef std::vector<int64_t> IntList;
typedef std::vector<uint64_t> UIntList;
typedef std::vector<double> DoubleList;
struct MicroServiceMeta {
uint64_t Id=0;
std::string Type;
std::string PrivateEndPoint;
std::string PublicEndPoint;
std::string AccessKey;
std::string Version;
uint64_t LastUpdate=0;
uint64_t Id = 0;
std::string Type;
std::string PrivateEndPoint;
std::string PublicEndPoint;
std::string AccessKey;
std::string Version;
uint64_t LastUpdate = 0;
};
typedef std::map<std::string, MicroServiceMeta> MicroServiceMetaMap;
typedef std::vector<MicroServiceMeta> MicroServiceMetaVec;
}
typedef std::map<std::string, MicroServiceMeta> MicroServiceMetaMap;
typedef std::vector<MicroServiceMeta> MicroServiceMetaVec;
} // namespace OpenWifi::Types
namespace OpenWifi {
inline void UpdateCountedMap(OpenWifi::Types::CountedMap &M, const std::string &S, uint64_t Increment=1) {
auto it = M.find(S);
if(it==M.end())
M[S] = Increment;
else
it->second += Increment;
}
inline void UpdateCountedMap(OpenWifi::Types::CountedMap &M, const std::string &S,
uint64_t Increment = 1) {
auto it = M.find(S);
if (it == M.end())
M[S] = Increment;
else
it->second += Increment;
}
inline void UpdateCountedMap(OpenWifi::Types::Counted3DMapSII &M, const std::string &S, uint32_t Index, uint64_t Increment=1) {
auto it = M.find(S);
if(it==M.end()) {
std::map<uint32_t,uint64_t> E;
E[Index] = Increment;
M[S] = E;
}
else {
std::map<uint32_t,uint64_t> & IndexMap = it->second;
auto it_index = IndexMap.find(Index);
if(it_index == IndexMap.end()) {
IndexMap[Index] = Increment;
} else {
it_index->second += Increment;
}
}
}
}
inline void UpdateCountedMap(OpenWifi::Types::Counted3DMapSII &M, const std::string &S,
uint32_t Index, uint64_t Increment = 1) {
auto it = M.find(S);
if (it == M.end()) {
std::map<uint32_t, uint64_t> E;
E[Index] = Increment;
M[S] = E;
} else {
std::map<uint32_t, uint64_t> &IndexMap = it->second;
auto it_index = IndexMap.find(Index);
if (it_index == IndexMap.end()) {
IndexMap[Index] = Increment;
} else {
it_index->second += Increment;
}
}
}
} // namespace OpenWifi

View File

@@ -6,22 +6,23 @@
namespace OpenWifi {
Poco::Net::HTTPRequestHandler *ExtRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &Request) {
Poco::Net::HTTPRequestHandler *
ExtRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &Request) {
try {
Poco::URI uri(Request.getURI());
auto TID = NextTransactionId_++;
Utils::SetThreadName(fmt::format("x-rest:{}",TID).c_str());
Utils::SetThreadName(fmt::format("x-rest:{}", TID).c_str());
return RESTAPI_ExtServer()->CallServer(uri.getPath(), TID);
} catch (...) {
}
return nullptr;
}
Poco::Net::HTTPRequestHandler *RESTAPI_ExtServer::CallServer(const std::string &Path, uint64_t Id) {
Poco::Net::HTTPRequestHandler *RESTAPI_ExtServer::CallServer(const std::string &Path,
uint64_t Id) {
RESTAPIHandler::BindingMap Bindings;
Utils::SetThreadName(fmt::format("x-rest:{}",Id).c_str());
Utils::SetThreadName(fmt::format("x-rest:{}", Id).c_str());
return RESTAPI_ExtRouter(Path, Bindings, Logger(), Server_, Id);
}
}
} // namespace OpenWifi

View File

@@ -6,20 +6,23 @@
#include "Poco/Net/HTTPServer.h"
#include "framework/SubSystemServer.h"
#include "framework/RESTAPI_Handler.h"
#include "framework/SubSystemServer.h"
namespace OpenWifi {
Poco::Net::HTTPRequestHandler * RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t Id);
Poco::Net::HTTPRequestHandler *
RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t Id);
class ExtRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
public:
ExtRequestHandlerFactory() = default;
Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override;
Poco::Net::HTTPRequestHandler *
createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override;
private:
static inline std::atomic_uint64_t NextTransactionId_ = 1;
static inline std::atomic_uint64_t NextTransactionId_ = 1;
};
class RESTAPI_ExtServer : public SubSystemServer {
@@ -30,16 +33,21 @@ namespace OpenWifi {
}
inline int Start() override {
poco_information(Logger(),"Starting.");
poco_information(Logger(), "Starting.");
Server_.InitLogging();
for(const auto & Svr: ConfigServersList_) {
for (const auto &Svr : ConfigServersList_) {
if(MicroServiceNoAPISecurity()) {
poco_information(Logger(),fmt::format("Starting: {}:{}. Security has been disabled for APIs.", Svr.Address(), Svr.Port()));
if (MicroServiceNoAPISecurity()) {
poco_information(
Logger(),
fmt::format("Starting: {}:{}. Security has been disabled for APIs.",
Svr.Address(), Svr.Port()));
} else {
poco_information(Logger(),fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}", Svr.Address(), Svr.Port(),
Svr.KeyFile(),Svr.CertFile()));
poco_information(Logger(),
fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}",
Svr.Address(), Svr.Port(), Svr.KeyFile(),
Svr.CertFile()));
Svr.LogCert(Logger());
if (!Svr.RootCA().empty())
Svr.LogCas(Logger());
@@ -49,13 +57,15 @@ namespace OpenWifi {
Params->setKeepAlive(true);
Params->setName("ws:xrest");
std::unique_ptr<Poco::Net::HTTPServer> NewServer;
if(MicroServiceNoAPISecurity()) {
std::unique_ptr<Poco::Net::HTTPServer> NewServer;
if (MicroServiceNoAPISecurity()) {
auto Sock{Svr.CreateSocket(Logger())};
NewServer = std::make_unique<Poco::Net::HTTPServer>(new ExtRequestHandlerFactory, Pool_, Sock, Params);
NewServer = std::make_unique<Poco::Net::HTTPServer>(
new ExtRequestHandlerFactory, Pool_, Sock, Params);
} else {
auto Sock{Svr.CreateSecureSocket(Logger())};
NewServer = std::make_unique<Poco::Net::HTTPServer>(new ExtRequestHandlerFactory, Pool_, Sock, Params);
NewServer = std::make_unique<Poco::Net::HTTPServer>(
new ExtRequestHandlerFactory, Pool_, Sock, Params);
};
NewServer->start();
RESTServers_.push_back(std::move(NewServer));
@@ -64,36 +74,34 @@ namespace OpenWifi {
}
inline void Stop() override {
poco_information(Logger(),"Stopping...");
for( const auto & svr : RESTServers_ )
poco_information(Logger(), "Stopping...");
for (const auto &svr : RESTServers_)
svr->stopAll(true);
Pool_.stopAll();
Pool_.joinAll();
RESTServers_.clear();
poco_information(Logger(),"Stopped...");
poco_information(Logger(), "Stopped...");
}
inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override {
MicroServiceLoadConfigurationFile();
poco_information(Logger(),"Reinitializing.");
poco_information(Logger(), "Reinitializing.");
Stop();
Start();
}
Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id);
const Poco::ThreadPool & Pool() { return Pool_; }
const Poco::ThreadPool &Pool() { return Pool_; }
private:
std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_;
Poco::ThreadPool Pool_{"x-rest",8,128};
RESTAPI_GenericServerAccounting Server_;
std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_;
Poco::ThreadPool Pool_{"x-rest", 8, 128};
RESTAPI_GenericServerAccounting Server_;
RESTAPI_ExtServer() noexcept:
SubSystemServer("RESTAPI_ExtServer", "REST-XSRV", "openwifi.restapi")
{
}
RESTAPI_ExtServer() noexcept
: SubSystemServer("RESTAPI_ExtServer", "REST-XSRV", "openwifi.restapi") {}
};
inline auto RESTAPI_ExtServer() { return RESTAPI_ExtServer::instance(); };
}
} // namespace OpenWifi

Some files were not shown because too many files have changed in this diff Show More