mirror of
https://github.com/Telecominfraproject/wlan-cloud-ucentralfms.git
synced 2025-10-29 18:02:20 +00:00
Compare commits
71 Commits
v2.1.0-RC1
...
release/v2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce4e5ee376 | ||
|
|
8eb3178254 | ||
|
|
684e69152f | ||
|
|
76ddbdb5af | ||
|
|
01c01bfa6b | ||
|
|
ee24d01d1b | ||
|
|
4fb8903b66 | ||
|
|
a917ab9f78 | ||
|
|
df1641871c | ||
|
|
6c386444ab | ||
|
|
720f7f7006 | ||
|
|
5f14599ee7 | ||
|
|
e16c97ba51 | ||
|
|
494f67eb42 | ||
|
|
348782179e | ||
|
|
5455bfc601 | ||
|
|
cb9827bcd2 | ||
|
|
5b1fe4a037 | ||
|
|
7de2709d7f | ||
|
|
979bd11a7b | ||
|
|
0f495bff29 | ||
|
|
d5f933c7c5 | ||
|
|
1d70c072e8 | ||
|
|
04e796b9ac | ||
|
|
3fcfc046c6 | ||
|
|
9909a2e0d9 | ||
|
|
bb31ba0d94 | ||
|
|
5e33881a4e | ||
|
|
a2edf350c9 | ||
|
|
44951bedb2 | ||
|
|
c025cd1416 | ||
|
|
5ba3b00557 | ||
|
|
706d6a071c | ||
|
|
2859e07216 | ||
|
|
abcfdcf34a | ||
|
|
5bf49fa6fa | ||
|
|
3c97df5ebd | ||
|
|
20eb25406f | ||
|
|
b6d10b19ab | ||
|
|
dbf0d0ecbe | ||
|
|
fca5b5f7e1 | ||
|
|
061ca2c140 | ||
|
|
28bf8f556a | ||
|
|
013ae293d1 | ||
|
|
8c16868dc3 | ||
|
|
d1930ff075 | ||
|
|
1edb8dd5a8 | ||
|
|
220dedc677 | ||
|
|
d5e41b22ba | ||
|
|
ef36521119 | ||
|
|
8e18a33747 | ||
|
|
70c8a128dc | ||
|
|
bb1f145bf9 | ||
|
|
e066c638ff | ||
|
|
51b9e58b0f | ||
|
|
56e3b717a2 | ||
|
|
c35353d34e | ||
|
|
ddd6ae7b5c | ||
|
|
41f13b9d64 | ||
|
|
d305ee43d6 | ||
|
|
a9412cd338 | ||
|
|
1c328a381d | ||
|
|
d3e7906815 | ||
|
|
d7d47bce48 | ||
|
|
cddc5e178e | ||
|
|
b6c1065fd2 | ||
|
|
f0c95b11d4 | ||
|
|
168b5f4e75 | ||
|
|
64596cb622 | ||
|
|
fcf356ddfe | ||
|
|
be984a186a |
6
.github/workflows/ci.yml
vendored
6
.github/workflows/ci.yml
vendored
@@ -28,7 +28,7 @@ jobs:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Build Docker image
|
||||
run: docker build -t wlan-cloud-ucentralfms:${{ github.sha }} .
|
||||
run: docker build -t wlan-cloud-owfms:${{ github.sha }} .
|
||||
|
||||
- name: Tag Docker image
|
||||
run: |
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
fi
|
||||
echo "Result tags: $TAGS"
|
||||
for tag in $TAGS; do
|
||||
docker tag wlan-cloud-ucentralfms:${{ github.sha }} ${{ env.DOCKER_REGISTRY_URL }}/ucentralfms:$tag
|
||||
docker tag wlan-cloud-owfms:${{ github.sha }} ${{ env.DOCKER_REGISTRY_URL }}/owfms:$tag
|
||||
done
|
||||
- name: Log into Docker registry
|
||||
if: startsWith(github.ref, 'refs/tags/') || startsWith(github.ref, 'refs/pull/') || github.ref == 'refs/heads/main'
|
||||
@@ -62,4 +62,4 @@ jobs:
|
||||
- name: Push Docker images
|
||||
if: startsWith(github.ref, 'refs/tags/') || startsWith(github.ref, 'refs/pull/') || github.ref == 'refs/heads/main'
|
||||
run: |
|
||||
docker images | grep ${{ env.DOCKER_REGISTRY_URL }}/ucentralfms | awk -F ' ' '{print $1":"$2}' | xargs -I {} docker push {}
|
||||
docker images | grep ${{ env.DOCKER_REGISTRY_URL }}/owfms | awk -F ' ' '{print $1":"$2}' | xargs -I {} docker push {}
|
||||
|
||||
2
.github/workflows/cleanup.yml
vendored
2
.github/workflows/cleanup.yml
vendored
@@ -16,4 +16,4 @@ jobs:
|
||||
steps:
|
||||
- run: |
|
||||
export PR_BRANCH_TAG=$(echo ${GITHUB_HEAD_REF#refs/heads/} | tr '/' '-')
|
||||
curl -uucentral:${{ secrets.DOCKER_REGISTRY_PASSWORD }} -X DELETE "https://tip.jfrog.io/artifactory/tip-wlan-cloud-ucentral/ucentralfms/$PR_BRANCH_TAG"
|
||||
curl -uucentral:${{ secrets.DOCKER_REGISTRY_PASSWORD }} -X DELETE "https://tip.jfrog.io/artifactory/tip-wlan-cloud-ucentral/owfms/$PR_BRANCH_TAG"
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -9,6 +9,8 @@ install_manifest.txt
|
||||
compile_commands.json
|
||||
CTestTestfile.cmake
|
||||
certs/*.*
|
||||
/logs/
|
||||
/data/
|
||||
_deps
|
||||
*.pem
|
||||
*.id
|
||||
|
||||
61
CLI.md
61
CLI.md
@@ -1,10 +1,10 @@
|
||||
# Firmware Service (FMS) CLI Documentation
|
||||
|
||||
## Before using the CLI
|
||||
You must set the environment variable `UCENTRALSEC`. You must specify the host and port for the security service
|
||||
You must set the environment variable `OWSEC`. You must specify the host and port for the security service
|
||||
associated with the FMS Service. Here is an example
|
||||
```csh
|
||||
export UCENTRALSEC=mysecurityservice,example.com:16001
|
||||
export OWSEC=mysecurityservice.example.com:16001
|
||||
```
|
||||
Once set, you can start using the `CLI`.
|
||||
|
||||
@@ -12,37 +12,48 @@ Once set, you can start using the `CLI`.
|
||||
Most commands will take from 0 to 2 parameters. You should include all parameters in double quotes when possible.
|
||||
|
||||
## The commands
|
||||
### getfirmwares
|
||||
Get a lit of firmwares.
|
||||
|
||||
### `cli getfirmwares <device_type>`
|
||||
This will list all firmwares that apply to the `device_type`. You can get a list of `device_types` with the `cli devicetypes` command.
|
||||
### latestfirmware <device_type>
|
||||
Get the latest firmware for the device_type specified.
|
||||
|
||||
### `latestfirmware <device_type>`
|
||||
Get the latest firmware version for a given `device_type`.
|
||||
### revisions
|
||||
Get a list of revisions available.
|
||||
|
||||
### `cli revisions`
|
||||
Get the list of currently available revisions.
|
||||
### devicetypes
|
||||
Get the list of device types supported.
|
||||
|
||||
### `cli devicetypes`
|
||||
Retrieve the list of known `device_types`
|
||||
### firmwareage <device_type> <revision>
|
||||
Calculate how out of date a specific release it.
|
||||
|
||||
### `cli firmwareage <device_type> <revision>`
|
||||
If you specify your `device_type` and `revision`, the system will do its best to estimate how
|
||||
far in the past you `revision` is compared to the latest revision.
|
||||
### gethistory <device serial number>
|
||||
Get the device firmware history.
|
||||
|
||||
### `cli gethistory <serialNumber>`
|
||||
Get the revision history for a given device.
|
||||
### connecteddevice <device serial number>
|
||||
Get the device status.
|
||||
|
||||
### `cli connecteddevices`
|
||||
Get a list of the currently known devices and the last connection information we have about the,
|
||||
### connectedDevices
|
||||
Get the list of connected devices.
|
||||
|
||||
### `cli connecteddevice <serialNumber>`
|
||||
Get the information relevant to a specific device.
|
||||
### devicereport
|
||||
Get the dashboard.
|
||||
|
||||
### `cli devicereport`
|
||||
Give a simplified dashboard report of the data in the service.
|
||||
### setloglevel <subsystem> <loglevel>
|
||||
Set the log level for s specific subsystem.
|
||||
|
||||
### `cli fmsversion`
|
||||
Display the version of the service.
|
||||
### getloglevels
|
||||
Get the current log levels for all subsystems.
|
||||
|
||||
### getloglevelnames
|
||||
Get the log level names available.
|
||||
|
||||
### getsubsystemnames
|
||||
Get the list of subsystems.
|
||||
|
||||
### systeminfo
|
||||
Get basic system information.
|
||||
|
||||
### reloadsubsystem <subsystem name>
|
||||
Reload the configuration for a subsystem.
|
||||
|
||||
### `cli fmstimes`
|
||||
Display the uptime and start time of the service.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.13)
|
||||
project(ucentralfms VERSION 2.1.0)
|
||||
project(owfms VERSION 2.2.0)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
|
||||
@@ -48,7 +48,7 @@ endif()
|
||||
|
||||
include_directories(/usr/local/include /usr/local/opt/openssl/include src include/kafka /usr/local/opt/mysql-client/include)
|
||||
|
||||
add_executable( ucentralfms
|
||||
add_executable( owfms
|
||||
build
|
||||
src/Dashboard.cpp src/Dashboard.h
|
||||
src/Daemon.cpp src/Daemon.h
|
||||
@@ -86,9 +86,11 @@ add_executable( ucentralfms
|
||||
src/FirmwareCache.cpp src/FirmwareCache.h
|
||||
src/RESTAPI_connectedDeviceHandler.cpp src/RESTAPI_connectedDeviceHandler.h
|
||||
src/RESTAPI_deviceReportHandler.cpp src/RESTAPI_deviceReportHandler.h
|
||||
src/OpenWifiTypes.h )
|
||||
src/RESTAPI_GenericServer.cpp src/RESTAPI_GenericServer.h
|
||||
src/OpenWifiTypes.h
|
||||
src/RESTAPI_errors.h)
|
||||
|
||||
target_link_libraries(ucentralfms PUBLIC
|
||||
target_link_libraries(owfms PUBLIC
|
||||
${Poco_LIBRARIES} ${MySQL_LIBRARIES}
|
||||
${Boost_LIBRARIES}
|
||||
${ZLIB_LIBRARIES} ${AWSSDK_LINK_LIBRARIES}
|
||||
|
||||
38
Dockerfile
38
Dockerfile
@@ -37,38 +37,42 @@ RUN cmake ..
|
||||
RUN cmake --build . --config Release -j8
|
||||
RUN cmake --build . --target install
|
||||
|
||||
ADD CMakeLists.txt build /ucentralfms/
|
||||
ADD cmake /ucentralfms/cmake
|
||||
ADD src /ucentralfms/src
|
||||
ADD CMakeLists.txt build /owfms/
|
||||
ADD cmake /owfms/cmake
|
||||
ADD src /owfms/src
|
||||
|
||||
WORKDIR /ucentralfms
|
||||
WORKDIR /owfms
|
||||
RUN mkdir cmake-build
|
||||
WORKDIR /ucentralfms/cmake-build
|
||||
WORKDIR /owfms/cmake-build
|
||||
RUN cmake ..
|
||||
RUN cmake --build . --config Release -j8
|
||||
|
||||
FROM alpine
|
||||
|
||||
ENV UCENTRALFMS_USER=ucentralfms \
|
||||
UCENTRALFMS_ROOT=/ucentralfms-data \
|
||||
UCENTRALFMS_CONFIG=/ucentralfms-data
|
||||
ENV OWFMS_USER=owfms \
|
||||
OWFMS_ROOT=/owfms-data \
|
||||
OWFMS_CONFIG=/owfms-data
|
||||
|
||||
RUN addgroup -S "$UCENTRALFMS_USER" && \
|
||||
adduser -S -G "$UCENTRALFMS_USER" "$UCENTRALFMS_USER"
|
||||
RUN addgroup -S "$OWFMS_USER" && \
|
||||
adduser -S -G "$OWFMS_USER" "$OWFMS_USER"
|
||||
|
||||
RUN mkdir /ucentral
|
||||
RUN mkdir -p "$UCENTRALFMS_ROOT" "$UCENTRALFMS_CONFIG" && \
|
||||
chown "$UCENTRALFMS_USER": "$UCENTRALFMS_ROOT" "$UCENTRALFMS_CONFIG"
|
||||
RUN apk add --update --no-cache librdkafka curl-dev mariadb-connector-c libpq unixodbc su-exec
|
||||
RUN mkdir /openwifi
|
||||
RUN mkdir -p "$OWFMS_ROOT" "$OWFMS_CONFIG" && \
|
||||
chown "$OWFMS_USER": "$OWFMS_ROOT" "$OWFMS_CONFIG"
|
||||
RUN apk add --update --no-cache librdkafka curl-dev mariadb-connector-c libpq unixodbc su-exec gettext ca-certificates
|
||||
|
||||
COPY --from=builder /ucentralfms/cmake-build/ucentralfms /ucentral/ucentralfms
|
||||
COPY --from=builder /owfms/cmake-build/owfms /openwifi/owfms
|
||||
COPY --from=builder /cppkafka/cmake-build/src/lib/* /lib/
|
||||
COPY --from=builder /poco/cmake-build/lib/* /lib/
|
||||
COPY --from=builder /aws-sdk-cpp/cmake-build/aws-cpp-sdk-core/libaws-cpp-sdk-core.so /lib/
|
||||
COPY --from=builder /aws-sdk-cpp/cmake-build/aws-cpp-sdk-s3/libaws-cpp-sdk-s3.so /lib/
|
||||
|
||||
COPY owfms.properties.tmpl ${OWFMS_CONFIG}/
|
||||
COPY docker-entrypoint.sh /
|
||||
RUN wget https://raw.githubusercontent.com/Telecominfraproject/wlan-cloud-ucentral-deploy/main/docker-compose/certs/restapi-ca.pem \
|
||||
-O /usr/local/share/ca-certificates/restapi-ca-selfsigned.pem
|
||||
|
||||
EXPOSE 16004 17004 16104
|
||||
|
||||
COPY docker-entrypoint.sh /
|
||||
ENTRYPOINT ["/docker-entrypoint.sh"]
|
||||
CMD ["/ucentral/ucentralfms"]
|
||||
CMD ["/openwifi/owfms"]
|
||||
|
||||
94
README.md
94
README.md
@@ -128,30 +128,6 @@ cmake ..
|
||||
make -j
|
||||
```
|
||||
|
||||
### Raspberry
|
||||
The build on a rPI takes a while. You can shorten that build time and requirements by disabling all the larger database
|
||||
support. You can build with only SQLite support by not installing the packages for ODBC, PostgreSQL, and MySQL by
|
||||
adding -DSMALL_BUILD=1 on the cmake build line.
|
||||
|
||||
```
|
||||
sudo apt install git cmake g++ libssl-dev libaprutil1-dev apache2-dev libboost-all-dev libyaml-cpp-dev
|
||||
git clone https://github.com/stephb9959/poco
|
||||
cd poco
|
||||
mkdir cmake-build
|
||||
cd cmake-build
|
||||
cmake ..
|
||||
cmake --build . --config Release
|
||||
sudo cmake --build . --target install
|
||||
|
||||
cd ~
|
||||
git clone https://github.com/Telecominfraproject/wlan-cloud-ucentralfms
|
||||
cd wlan-cloud-ucentralfms
|
||||
mkdir cmake-build
|
||||
cd cmake-build
|
||||
cmake -DSMALL_BUILD=1 ..
|
||||
make
|
||||
```
|
||||
|
||||
### After completing the build
|
||||
After completing the build, you can remove the Poco source as it is no longer needed.
|
||||
|
||||
@@ -167,11 +143,77 @@ mkdir data
|
||||
Love'em of hate'em, we gotta use'em. So we tried to make this as easy as possible for you.
|
||||
|
||||
#### The `certs` directory
|
||||
For all deployments, you will need the following certs directory, populated with the proper files.
|
||||
For all deployments, you will need the following `certs` directory, populated with the proper files.
|
||||
|
||||
```asm
|
||||
certs ---+--- root.pem
|
||||
certs ---+---
|
||||
+--- restapi-ca.pem
|
||||
+--- restapi-cert.pem
|
||||
+--- restapi-key.pem
|
||||
```
|
||||
|
||||
### Configuration
|
||||
The configuration is kep in the file `owfms.properties`. This is a text file read by the service at startup time.
|
||||
|
||||
#### Basic configuration
|
||||
You must set the environment variables:
|
||||
- OWFMS_ROOT: represents where the root of the installation is for this service.
|
||||
- OWFMS_CONFIG: represents the path where the configuration is kept.
|
||||
|
||||
#### The file section
|
||||
#### RESTAPI
|
||||
```json
|
||||
openwifi.restapi.host.0.backlog = 100
|
||||
openwifi.restapi.host.0.security = relaxed
|
||||
openwifi.restapi.host.0.rootca = $OWFMS_ROOT/certs/restapi-ca.pem
|
||||
openwifi.restapi.host.0.address = *
|
||||
openwifi.restapi.host.0.port = 16004
|
||||
openwifi.restapi.host.0.cert = $OWFMS_ROOT/certs/restapi-cert.pem
|
||||
openwifi.restapi.host.0.key = $OWFMS_ROOT/certs/restapi-key.pem
|
||||
openwifi.restapi.host.0.key.password = mypassword
|
||||
```
|
||||
Of importance are the `.port` which should point to the port used.
|
||||
|
||||
#### Internal microservice interface
|
||||
```json
|
||||
openwifi.internal.restapi.host.0.backlog = 100
|
||||
openwifi.internal.restapi.host.0.security = relaxed
|
||||
openwifi.internal.restapi.host.0.rootca = $OWFMS_ROOT/certs/restapi-ca.pem
|
||||
openwifi.internal.restapi.host.0.address = *
|
||||
openwifi.internal.restapi.host.0.port = 17004
|
||||
openwifi.internal.restapi.host.0.cert = $OWFMS_ROOT/certs/restapi-cert.pem
|
||||
openwifi.internal.restapi.host.0.key = $OWFMS_ROOT/certs/restapi-key.pem
|
||||
openwifi.internal.restapi.host.0.key.password = mypassword
|
||||
```
|
||||
You can leave all the default values for this one.
|
||||
|
||||
#### System values
|
||||
In the following values, you need to change `.uri.public` and `uri.ui`. The `.uri.public` must point to an externally available FQDN to access the service. The `.uri.ui` must point to web server running
|
||||
the UI for the service. `firmwaredb.refresh` tells the service how often to refresh the firmware database in seconds. `firmwaredb.maxage` tells the service how old you
|
||||
want to accept release for. This value is in days.
|
||||
|
||||
```json
|
||||
openwifi.service.key = $OWFMS_ROOT/certs/restapi-key.pem
|
||||
openwifi.service.key.password = mypassword
|
||||
openwifi.system.data = $OWFMS_ROOT/data
|
||||
openwifi.system.debug = false
|
||||
openwifi.system.uri.private = https://localhost:17004
|
||||
openwifi.system.uri.public = https://ucentral.dpaas.arilia.com:16004
|
||||
openwifi.system.commandchannel = /tmp/app.owfms
|
||||
openwifi.system.uri.ui = ucentral-ui.arilia.com
|
||||
firmwaredb.refresh = 1800
|
||||
firmwaredb.maxage = 90
|
||||
```
|
||||
|
||||
#### S3 configuration
|
||||
The service mua read the information about firmware from an Amazon S3 Bucket. You need to replace `s3.secret` and `s3.key` with your own.
|
||||
|
||||
```json
|
||||
s3.bucketname = ucentral-ap-firmware
|
||||
s3.region = us-east-1
|
||||
s3.secret = *******************************************
|
||||
s3.key = *******************************************
|
||||
s3.retry = 60
|
||||
s3.bucket.uri = ucentral-ap-firmware.s3.amazonaws.com
|
||||
|
||||
```
|
||||
@@ -1,11 +1,53 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
if [ "$1" = '/ucentral/ucentralfms' -a "$(id -u)" = '0' ]; then
|
||||
if [ "$SELFSIGNED_CERTS" = 'true' ]; then
|
||||
update-ca-certificates
|
||||
fi
|
||||
|
||||
if [[ "$TEMPLATE_CONFIG" = 'true' && ! -f "$OWFMS_CONFIG"/owfms.properties ]]; then
|
||||
RESTAPI_HOST_ROOTCA=${RESTAPI_HOST_ROOTCA:-"\$OWFMS_ROOT/certs/restapi-ca.pem"} \
|
||||
RESTAPI_HOST_PORT=${RESTAPI_HOST_PORT:-"16004"} \
|
||||
RESTAPI_HOST_CERT=${RESTAPI_HOST_CERT:-"\$OWFMS_ROOT/certs/restapi-cert.pem"} \
|
||||
RESTAPI_HOST_KEY=${RESTAPI_HOST_KEY:-"\$OWFMS_ROOT/certs/restapi-key.pem"} \
|
||||
RESTAPI_HOST_KEY_PASSWORD=${RESTAPI_HOST_KEY_PASSWORD:-"mypassword"} \
|
||||
INTERNAL_RESTAPI_HOST_ROOTCA=${INTERNAL_RESTAPI_HOST_ROOTCA:-"\$OWFMS_ROOT/certs/restapi-ca.pem"} \
|
||||
INTERNAL_RESTAPI_HOST_PORT=${INTERNAL_RESTAPI_HOST_PORT:-"17004"} \
|
||||
INTERNAL_RESTAPI_HOST_CERT=${INTERNAL_RESTAPI_HOST_CERT:-"\$OWFMS_ROOT/certs/restapi-cert.pem"} \
|
||||
INTERNAL_RESTAPI_HOST_KEY=${INTERNAL_RESTAPI_HOST_KEY:-"\$OWFMS_ROOT/certs/restapi-key.pem"} \
|
||||
INTERNAL_RESTAPI_HOST_KEY_PASSWORD=${INTERNAL_RESTAPI_HOST_KEY_PASSWORD:-"mypassword"} \
|
||||
SERVICE_KEY=${SERVICE_KEY:-"\$OWFMS_ROOT/certs/restapi-key.pem"} \
|
||||
SERVICE_KEY_PASSWORD=${SERVICE_KEY_PASSWORD:-"mypassword"} \
|
||||
SYSTEM_DATA=${SYSTEM_DATA:-"\$OWFMS_ROOT/data"} \
|
||||
SYSTEM_URI_PRIVATE=${SYSTEM_URI_PRIVATE:-"https://localhost:17004"} \
|
||||
SYSTEM_URI_PUBLIC=${SYSTEM_URI_PUBLIC:-"https://localhost:16004"} \
|
||||
SYSTEM_URI_UI=${SYSTEM_URI_UI:-"http://localhost"} \
|
||||
S3_BUCKETNAME=${S3_BUCKETNAME:-"ucentral-ap-firmware"} \
|
||||
S3_REGION=${S3_REGION:-"us-east-1"} \
|
||||
S3_SECRET=${S3_SECRET:-"*******************************************"} \
|
||||
S3_KEY=${S3_KEY:-"*******************************************"} \
|
||||
S3_BUCKET_URI=${S3_BUCKET_URI:-"ucentral-ap-firmware.s3.amazonaws.com"} \
|
||||
KAFKA_ENABLE=${KAFKA_ENABLE:-"true"} \
|
||||
KAFKA_BROKERLIST=${KAFKA_BROKERLIST:-"localhost:9092"} \
|
||||
STORAGE_TYPE=${STORAGE_TYPE:-"sqlite"} \
|
||||
STORAGE_TYPE_POSTGRESQL_HOST=${STORAGE_TYPE_POSTGRESQL_HOST:-"localhost"} \
|
||||
STORAGE_TYPE_POSTGRESQL_USERNAME=${STORAGE_TYPE_POSTGRESQL_USERNAME:-"owfms"} \
|
||||
STORAGE_TYPE_POSTGRESQL_PASSWORD=${STORAGE_TYPE_POSTGRESQL_PASSWORD:-"owfms"} \
|
||||
STORAGE_TYPE_POSTGRESQL_DATABASE=${STORAGE_TYPE_POSTGRESQL_DATABASE:-"owfms"} \
|
||||
STORAGE_TYPE_POSTGRESQL_PORT=${STORAGE_TYPE_POSTGRESQL_PORT:-"5432"} \
|
||||
STORAGE_TYPE_MYSQL_HOST=${STORAGE_TYPE_MYSQL_HOST:-"localhost"} \
|
||||
STORAGE_TYPE_MYSQL_USERNAME=${STORAGE_TYPE_MYSQL_USERNAME:-"owfms"} \
|
||||
STORAGE_TYPE_MYSQL_PASSWORD=${STORAGE_TYPE_MYSQL_PASSWORD:-"owfms"} \
|
||||
STORAGE_TYPE_MYSQL_DATABASE=${STORAGE_TYPE_MYSQL_DATABASE:-"owfms"} \
|
||||
STORAGE_TYPE_MYSQL_PORT=${STORAGE_TYPE_MYSQL_PORT:-"3306"} \
|
||||
envsubst < $OWFMS_CONFIG/owfms.properties.tmpl > $OWFMS_CONFIG/owfms.properties
|
||||
fi
|
||||
|
||||
if [ "$1" = '/openwifi/owfms' -a "$(id -u)" = '0' ]; then
|
||||
if [ "$RUN_CHOWN" = 'true' ]; then
|
||||
chown -R "$UCENTRALFMS_USER": "$UCENTRALFMS_ROOT" "$UCENTRALFMS_CONFIG"
|
||||
chown -R "$OWFMS_USER": "$OWFMS_ROOT" "$OWFMS_CONFIG"
|
||||
fi
|
||||
exec su-exec "$UCENTRALFMS_USER" "$@"
|
||||
exec su-exec "$OWFMS_USER" "$@"
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
apiVersion: v2
|
||||
appVersion: "1.0"
|
||||
description: A Helm chart for Kubernetes
|
||||
name: ucentralfms
|
||||
name: owfms
|
||||
version: 0.1.0
|
||||
dependencies:
|
||||
- name: postgresql
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ucentralfms
|
||||
# owfms
|
||||
|
||||
This Helm chart helps to deploy uCentralSec to the Kubernetes clusters. It is mainly used in [assembly chart](https://github.com/Telecominfraproject/wlan-cloud-ucentral-deploy/tree/main/chart) as uCentralSec requires other services as dependencies that are considered in that Helm chart. This chart is purposed to define deployment logic close to the application code itself and define default values that could be overriden during deployment.
|
||||
This Helm chart helps to deploy OpenWIFI Firmware service (further on refered as __Firmware__) to the Kubernetes clusters. It is mainly used in [assembly chart](https://github.com/Telecominfraproject/wlan-cloud-ucentral-deploy/tree/main/chart) as uCentralSec requires other services as dependencies that are considered in that Helm chart. This chart is purposed to define deployment logic close to the application code itself and define default values that could be overriden during deployment.
|
||||
|
||||
|
||||
## TL;DR;
|
||||
@@ -11,7 +11,7 @@ $ helm install .
|
||||
|
||||
## Introduction
|
||||
|
||||
This chart bootstraps an ucentralfms on a [Kubernetes](http://kubernetes.io) cluster using the [Helm](https://helm.sh) package manager.
|
||||
This chart bootstraps the Firmware on a [Kubernetes](http://kubernetes.io) cluster using the [Helm](https://helm.sh) package manager.
|
||||
|
||||
## Installing the Chart
|
||||
|
||||
@@ -23,7 +23,7 @@ To install the chart with the release name `my-release`:
|
||||
$ helm install --name my-release git+https://github.com/Telecominfraproject/wlan-cloud-ucentralfms@helm?ref=main
|
||||
```
|
||||
|
||||
The command deploys ucentralfms on the Kubernetes cluster in the default configuration. The [configuration](#configuration) section lists the parameters that can be configured during installation.
|
||||
The command deploys the Firmware on the Kubernetes cluster in the default configuration. The [configuration](#configuration) section lists the parameters that can be configured during installation.
|
||||
|
||||
> **Tip**: List all releases using `helm list`
|
||||
|
||||
@@ -47,30 +47,30 @@ The following table lists the configurable parameters of the chart and their def
|
||||
| strategyType | string | Application deployment strategy | `'Recreate'` |
|
||||
| nameOverride | string | Override to be used for application deployment | |
|
||||
| fullnameOverride | string | Override to be used for application deployment (has priority over nameOverride) | |
|
||||
| images.ucentralfms.repository | string | Docker image repository | |
|
||||
| images.ucentralfms.tag | string | Docker image tag | `'master'` |
|
||||
| images.ucentralfms.pullPolicy | string | Docker image pull policy | `'Always'` |
|
||||
| services.ucentralfms.type | string | uCentralSec service type | `'LoadBalancer'` |
|
||||
| services.ucentralfms.ports.restapi.servicePort | number | REST API endpoint port to be exposed on service | `16001` |
|
||||
| services.ucentralfms.ports.restapi.targetPort | number | REST API endpoint port to be targeted by service | `16001` |
|
||||
| services.ucentralfms.ports.restapi.protocol | string | REST API endpoint protocol | `'TCP'` |
|
||||
| services.ucentralfms.ports.restapiinternal.servicePort | string | Internal REST API endpoint port to be exposed on service | `17001` |
|
||||
| services.ucentralfms.ports.restapiinternal.targetPort | number | Internal REST API endpoint port to be targeted by service | `17001` |
|
||||
| services.ucentralfms.ports.restapiinternal.protocol | string | Internal REST API endpoint protocol | `'TCP'` |
|
||||
| checks.ucentralfms.liveness.httpGet.path | string | Liveness check path to be used | `'/'` |
|
||||
| checks.ucentralfms.liveness.httpGet.port | number | Liveness check port to be used (should be pointint to ALB endpoint) | `16101` |
|
||||
| checks.ucentralfms.readiness.httpGet.path | string | Readiness check path to be used | `'/'` |
|
||||
| checks.ucentralfms.readiness.httpGet.port | number | Readiness check port to be used (should be pointint to ALB endpoint) | `16101` |
|
||||
| images.owfms.repository | string | Docker image repository | |
|
||||
| images.owfms.tag | string | Docker image tag | `'master'` |
|
||||
| images.owfms.pullPolicy | string | Docker image pull policy | `'Always'` |
|
||||
| services.owfms.type | string | OpenWIFI Firmware service type | `'LoadBalancer'` |
|
||||
| services.owfms.ports.restapi.servicePort | number | REST API endpoint port to be exposed on service | `16001` |
|
||||
| services.owfms.ports.restapi.targetPort | number | REST API endpoint port to be targeted by service | `16001` |
|
||||
| services.owfms.ports.restapi.protocol | string | REST API endpoint protocol | `'TCP'` |
|
||||
| services.owfms.ports.restapiinternal.servicePort | string | Internal REST API endpoint port to be exposed on service | `17001` |
|
||||
| services.owfms.ports.restapiinternal.targetPort | number | Internal REST API endpoint port to be targeted by service | `17001` |
|
||||
| services.owfms.ports.restapiinternal.protocol | string | Internal REST API endpoint protocol | `'TCP'` |
|
||||
| checks.owfms.liveness.httpGet.path | string | Liveness check path to be used | `'/'` |
|
||||
| checks.owfms.liveness.httpGet.port | number | Liveness check port to be used (should be pointint to ALB endpoint) | `16101` |
|
||||
| checks.owfms.readiness.httpGet.path | string | Readiness check path to be used | `'/'` |
|
||||
| checks.owfms.readiness.httpGet.port | number | Readiness check port to be used (should be pointint to ALB endpoint) | `16101` |
|
||||
| ingresses.restapi.enabled | boolean | Defines if REST API endpoint should be exposed via Ingress controller | `False` |
|
||||
| ingresses.restapi.hosts | array | List of hosts for exposed REST API | |
|
||||
| ingresses.restapi.paths | array | List of paths to be exposed for REST API | |
|
||||
| volumes.ucentralfms | array | Defines list of volumes to be attached to uCentralSec | |
|
||||
| persistence.enabled | boolean | Defines if uCentralSec requires Persistent Volume (required for permanent files storage and SQLite DB if enabled) | `True` |
|
||||
| volumes.owfms | array | Defines list of volumes to be attached to the Firmware | |
|
||||
| persistence.enabled | boolean | Defines if the Firmware requires Persistent Volume (required for permanent files storage and SQLite DB if enabled) | `True` |
|
||||
| persistence.accessModes | array | Defines PV access modes | |
|
||||
| persistence.size | string | Defines PV size | `'10Gi'` |
|
||||
| public_env_variables | hash | Defines list of environment variables to be passed to uCentralSec | |
|
||||
| configProperties | hash | Configuration properties that should be passed to the application in `ucentralfms.properties`. May be passed by key in set (i.e. `configProperties."rtty\.token"`) | |
|
||||
| certs | hash | Defines files (keys and certificates) that should be passed to uCentralSec (PEM format is adviced to be used) (see `volumes.ucentralfms` on where it is mounted) | |
|
||||
| public_env_variables | hash | Defines list of environment variables to be passed to the Firmware | |
|
||||
| configProperties | hash | Configuration properties that should be passed to the application in `owfms.properties`. May be passed by key in set (i.e. `configProperties."rtty\.token"`) | |
|
||||
| certs | hash | Defines files (keys and certificates) that should be passed to the Firmware (PEM format is adviced to be used) (see `volumes.owfms` on where it is mounted) | |
|
||||
|
||||
|
||||
Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`. For example,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{{- define "ucentralfms.config" -}}
|
||||
{{- define "owfms.config" -}}
|
||||
{{- range $key, $value := .Values.configProperties }}
|
||||
{{ $key }} = {{ $value }}
|
||||
{{- end }}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
{{/*
|
||||
Expand the name of the chart.
|
||||
*/}}
|
||||
{{- define "ucentralfms.name" -}}
|
||||
{{- define "owfms.name" -}}
|
||||
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
|
||||
{{- end -}}
|
||||
|
||||
@@ -11,7 +11,7 @@ Create a default fully qualified app name.
|
||||
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
|
||||
If release name contains chart name it will be used as a full name.
|
||||
*/}}
|
||||
{{- define "ucentralfms.fullname" -}}
|
||||
{{- define "owfms.fullname" -}}
|
||||
{{- if .Values.fullnameOverride -}}
|
||||
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
|
||||
{{- else -}}
|
||||
@@ -27,6 +27,6 @@ If release name contains chart name it will be used as a full name.
|
||||
{{/*
|
||||
Create chart name and version as used by the chart label.
|
||||
*/}}
|
||||
{{- define "ucentralfms.chart" -}}
|
||||
{{- define "owfms.chart" -}}
|
||||
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
|
||||
{{- end -}}
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "ucentralfms.fullname" . }}
|
||||
name: {{ include "owfms.fullname" . }}
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ include "ucentralfms.name" . }}
|
||||
helm.sh/chart: {{ include "ucentralfms.chart" . }}
|
||||
app.kubernetes.io/name: {{ include "owfms.name" . }}
|
||||
helm.sh/chart: {{ include "owfms.chart" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
spec:
|
||||
@@ -15,28 +15,28 @@ spec:
|
||||
type: {{ .Values.strategyType }}
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: {{ include "ucentralfms.name" . }}
|
||||
app.kubernetes.io/name: {{ include "owfms.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
{{- with .Values.services.ucentralfms.labels }}
|
||||
{{- with .Values.services.owfms.labels }}
|
||||
{{- toYaml . | nindent 6 }}
|
||||
{{- end }}
|
||||
template:
|
||||
metadata:
|
||||
annotations:
|
||||
checksum/config: {{ include "ucentralfms.config" . | sha256sum }}
|
||||
checksum/config: {{ include "owfms.config" . | sha256sum }}
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ include "ucentralfms.name" . }}
|
||||
app.kubernetes.io/name: {{ include "owfms.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
{{- with .Values.services.ucentralfms.labels }}
|
||||
{{- with .Values.services.owfms.labels }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
|
||||
containers:
|
||||
|
||||
- name: ucentralfms
|
||||
image: "{{ .Values.images.ucentralfms.repository }}:{{ .Values.images.ucentralfms.tag }}"
|
||||
imagePullPolicy: {{ .Values.images.ucentralfms.pullPolicy }}
|
||||
- name: owfms
|
||||
image: "{{ .Values.images.owfms.repository }}:{{ .Values.images.owfms.tag }}"
|
||||
imagePullPolicy: {{ .Values.images.owfms.pullPolicy }}
|
||||
|
||||
env:
|
||||
- name: KUBERNETES_DEPLOYED
|
||||
@@ -49,19 +49,19 @@ spec:
|
||||
- name: {{ $key }}
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "ucentralfms.fullname" $root }}-env
|
||||
name: {{ include "owfms.fullname" $root }}-env
|
||||
key: {{ $key }}
|
||||
{{- end }}
|
||||
|
||||
ports:
|
||||
{{- range $port, $portValue := .Values.services.ucentralfms.ports }}
|
||||
{{- range $port, $portValue := .Values.services.owfms.ports }}
|
||||
- name: {{ $port }}
|
||||
containerPort: {{ $portValue.targetPort }}
|
||||
protocol: {{ $portValue.protocol }}
|
||||
{{- end }}
|
||||
|
||||
volumeMounts:
|
||||
{{- range .Values.volumes.ucentralfms }}
|
||||
{{- range .Values.volumes.owfms }}
|
||||
- name: {{ .name }}
|
||||
mountPath: {{ .mountPath }}
|
||||
{{- if .subPath }}
|
||||
@@ -69,13 +69,13 @@ spec:
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{- if .Values.checks.ucentralfms.liveness }}
|
||||
{{- if .Values.checks.owfms.liveness }}
|
||||
livenessProbe:
|
||||
{{- toYaml .Values.checks.ucentralfms.liveness | nindent 12 }}
|
||||
{{- toYaml .Values.checks.owfms.liveness | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- if .Values.checks.ucentralfms.readiness }}
|
||||
{{- if .Values.checks.owfms.readiness }}
|
||||
readinessProbe:
|
||||
{{- toYaml .Values.checks.ucentralfms.readiness | nindent 12 }}
|
||||
{{- toYaml .Values.checks.owfms.readiness | nindent 12 }}
|
||||
{{- end }}
|
||||
|
||||
{{- with .Values.resources }}
|
||||
@@ -89,7 +89,7 @@ spec:
|
||||
imagePullSecrets:
|
||||
{{- range $image, $imageValue := .Values.images }}
|
||||
{{- if $imageValue.regcred }}
|
||||
- name: {{ include "ucentralfms.fullname" $root }}-{{ $image }}-regcred
|
||||
- name: {{ include "owfms.fullname" $root }}-{{ $image }}-regcred
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
apiVersion: extensions/v1beta1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: {{ include "ucentralfms.fullname" $root }}-{{ $ingress }}
|
||||
name: {{ include "owfms.fullname" $root }}-{{ $ingress }}
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ include "ucentralfms.name" $root }}
|
||||
helm.sh/chart: {{ include "ucentralfms.chart" $root }}
|
||||
app.kubernetes.io/name: {{ include "owfms.name" $root }}
|
||||
helm.sh/chart: {{ include "owfms.chart" $root }}
|
||||
app.kubernetes.io/instance: {{ $root.Release.Name }}
|
||||
app.kubernetes.io/managed-by: {{ $root.Release.Service }}
|
||||
{{- with $ingressValue.annotations }}
|
||||
@@ -37,7 +37,7 @@ spec:
|
||||
{{- range $ingressValue.paths }}
|
||||
- path: {{ .path }}
|
||||
backend:
|
||||
serviceName: {{ include "ucentralfms.fullname" $root }}-{{ .serviceName }}
|
||||
serviceName: {{ include "owfms.fullname" $root }}-{{ .serviceName }}
|
||||
servicePort: {{ .servicePort }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: {{ template "ucentralfms.fullname" . }}-pvc
|
||||
name: {{ template "owfms.fullname" . }}-pvc
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ include "ucentralfms.name" . }}
|
||||
helm.sh/chart: {{ include "ucentralfms.chart" . }}
|
||||
app.kubernetes.io/name: {{ include "owfms.name" . }}
|
||||
helm.sh/chart: {{ include "owfms.chart" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
{{- with .Values.persistence.annotations }}
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
apiVersion: v1
|
||||
metadata:
|
||||
labels:
|
||||
app.kuberentes.io/name: {{ include "ucentralfms.name" . }}
|
||||
helm.sh/chart: {{ include "ucentralfms.chart" . }}
|
||||
app.kuberentes.io/name: {{ include "owfms.name" . }}
|
||||
helm.sh/chart: {{ include "owfms.chart" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
name: {{ include "ucentralfms.fullname" . }}-certs
|
||||
name: {{ include "owfms.fullname" . }}-certs
|
||||
kind: Secret
|
||||
type: Opaque
|
||||
data:
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
apiVersion: v1
|
||||
metadata:
|
||||
labels:
|
||||
app.kuberentes.io/name: {{ include "ucentralfms.name" . }}
|
||||
helm.sh/chart: {{ include "ucentralfms.chart" . }}
|
||||
app.kuberentes.io/name: {{ include "owfms.name" . }}
|
||||
helm.sh/chart: {{ include "owfms.chart" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
name: {{ include "ucentralfms.fullname" . }}-config
|
||||
name: {{ include "owfms.fullname" . }}-config
|
||||
kind: Secret
|
||||
type: Opaque
|
||||
data:
|
||||
ucentralfms.properties: {{ include "ucentralfms.config" . | b64enc }}
|
||||
owfms.properties: {{ include "owfms.config" . | b64enc }}
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
apiVersion: v1
|
||||
metadata:
|
||||
labels:
|
||||
app.kuberentes.io/name: {{ include "ucentralfms.name" . }}
|
||||
helm.sh/chart: {{ include "ucentralfms.chart" . }}
|
||||
app.kuberentes.io/name: {{ include "owfms.name" . }}
|
||||
helm.sh/chart: {{ include "owfms.chart" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
name: {{ include "ucentralfms.fullname" . }}-env
|
||||
name: {{ include "owfms.fullname" . }}-env
|
||||
kind: Secret
|
||||
type: Opaque
|
||||
data:
|
||||
|
||||
@@ -10,11 +10,11 @@ kind: Secret
|
||||
type: kubernetes.io/dockerconfigjson
|
||||
metadata:
|
||||
labels:
|
||||
app.kuberentes.io/name: {{ include "ucentralfms.name" $root }}
|
||||
helm.sh/chart: {{ include "ucentralfms.chart" $root }}
|
||||
app.kuberentes.io/name: {{ include "owfms.name" $root }}
|
||||
helm.sh/chart: {{ include "owfms.chart" $root }}
|
||||
app.kubernetes.io/instance: {{ $root.Release.Name }}
|
||||
app.kubernetes.io/managed-by: {{ $root.Release.Service }}
|
||||
name: {{ include "ucentralfms.fullname" $root }}-{{ $image }}-regcred
|
||||
name: {{ include "owfms.fullname" $root }}-{{ $image }}-regcred
|
||||
data:
|
||||
.dockerconfigjson: {{ template "imagePullSecret" $imageValue.regcred }}
|
||||
{{- end }}
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "ucentralfms.fullname" $root }}-{{ $service }}
|
||||
name: {{ include "owfms.fullname" $root }}-{{ $service }}
|
||||
{{- with $serviceValue.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ include "ucentralfms.name" $root }}
|
||||
helm.sh/chart: {{ include "ucentralfms.chart" $root }}
|
||||
app.kubernetes.io/name: {{ include "owfms.name" $root }}
|
||||
helm.sh/chart: {{ include "owfms.chart" $root }}
|
||||
app.kubernetes.io/instance: {{ $root.Release.Name }}
|
||||
app.kubernetes.io/managed-by: {{ $root.Release.Service }}
|
||||
|
||||
@@ -39,7 +39,7 @@ spec:
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
selector:
|
||||
app.kubernetes.io/name: {{ include "ucentralfms.name" $root }}
|
||||
app.kubernetes.io/name: {{ include "owfms.name" $root }}
|
||||
app.kubernetes.io/instance: {{ $root.Release.Name }}
|
||||
{{- with $serviceValue.labels }}
|
||||
{{- toYaml . | nindent 4 }}
|
||||
|
||||
@@ -6,9 +6,9 @@ nameOverride: ""
|
||||
fullnameOverride: ""
|
||||
|
||||
images:
|
||||
ucentralfms:
|
||||
repository: tip-tip-wlan-cloud-ucentral.jfrog.io/ucentralfms
|
||||
tag: main
|
||||
owfms:
|
||||
repository: tip-tip-wlan-cloud-ucentral.jfrog.io/owfms
|
||||
tag: v2.2.0-RC1
|
||||
pullPolicy: Always
|
||||
# regcred:
|
||||
# registry: tip-tip-wlan-cloud-ucentral.jfrog.io
|
||||
@@ -16,7 +16,7 @@ images:
|
||||
# password: password
|
||||
|
||||
services:
|
||||
ucentralfms:
|
||||
owfms:
|
||||
type: LoadBalancer
|
||||
ports:
|
||||
restapi:
|
||||
@@ -29,7 +29,7 @@ services:
|
||||
protocol: TCP
|
||||
|
||||
checks:
|
||||
ucentralfms:
|
||||
owfms:
|
||||
liveness:
|
||||
httpGet:
|
||||
path: /
|
||||
@@ -49,29 +49,29 @@ ingresses:
|
||||
- restapi.chart-example.local
|
||||
paths:
|
||||
- path: /
|
||||
serviceName: ucentralfms
|
||||
serviceName: owfms
|
||||
servicePort: restapi
|
||||
|
||||
volumes:
|
||||
ucentralfms:
|
||||
owfms:
|
||||
- name: config
|
||||
mountPath: /ucentralfms-data/ucentralfms.properties
|
||||
subPath: ucentralfms.properties
|
||||
mountPath: /owfms-data/owfms.properties
|
||||
subPath: owfms.properties
|
||||
# Template below will be rendered in template
|
||||
volumeDefinition: |
|
||||
secret:
|
||||
secretName: {{ include "ucentralfms.fullname" . }}-config
|
||||
secretName: {{ include "owfms.fullname" . }}-config
|
||||
- name: certs
|
||||
mountPath: /ucentralfms-data/certs
|
||||
mountPath: /owfms-data/certs
|
||||
volumeDefinition: |
|
||||
secret:
|
||||
secretName: {{ include "ucentralfms.fullname" . }}-certs
|
||||
secretName: {{ include "owfms.fullname" . }}-certs
|
||||
# Change this if you want to use another volume type
|
||||
- name: persist
|
||||
mountPath: /ucentralfms-data/persist
|
||||
mountPath: /owfms-data/persist
|
||||
volumeDefinition: |
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ template "ucentralfms.fullname" . }}-pvc
|
||||
claimName: {{ template "owfms.fullname" . }}-pvc
|
||||
|
||||
resources: {}
|
||||
# We usually recommend not to specify default resources and to leave this as a conscious
|
||||
@@ -101,28 +101,28 @@ persistence:
|
||||
|
||||
# Application
|
||||
public_env_variables:
|
||||
UCENTRALSEC_ROOT: /ucentralfms-data
|
||||
UCENTRALSEC_CONFIG: /ucentralfms-data
|
||||
OWFMS_ROOT: /owfms-data
|
||||
OWFMS_CONFIG: /owfms-data
|
||||
|
||||
secret_env_variables: {}
|
||||
|
||||
configProperties:
|
||||
# -> Public part
|
||||
# REST API
|
||||
ucentralfws.restapi.host.0.backlog: 100
|
||||
ucentralfws.restapi.host.0.security: relaxed
|
||||
ucentralfws.restapi.host.0.rootca: $UCENTRALFMS_ROOT/certs/restapi-ca.pem
|
||||
ucentralfws.restapi.host.0.address: "*"
|
||||
ucentralfws.restapi.host.0.port: 16004
|
||||
ucentralfws.restapi.host.0.cert: $UCENTRALFMS_ROOT/certs/restapi-cert.pem
|
||||
ucentralfws.restapi.host.0.key: $UCENTRALFMS_ROOT/certs/restapi-key.pem
|
||||
ucentral.internal.restapi.host.0.backlog: 100
|
||||
ucentral.internal.restapi.host.0.security: relaxed
|
||||
ucentral.internal.restapi.host.0.rootca: $UCENTRALFMS_ROOT/certs/restapi-ca.pem
|
||||
ucentral.internal.restapi.host.0.address: "*"
|
||||
ucentral.internal.restapi.host.0.port: 17004
|
||||
ucentral.internal.restapi.host.0.cert: $UCENTRALFMS_ROOT/certs/restapi-cert.pem
|
||||
ucentral.internal.restapi.host.0.key: $UCENTRALFMS_ROOT/certs/restapi-key.pem
|
||||
openwifi.restapi.host.0.backlog: 100
|
||||
openwifi.restapi.host.0.security: relaxed
|
||||
openwifi.restapi.host.0.rootca: $OWFMS_ROOT/certs/restapi-ca.pem
|
||||
openwifi.restapi.host.0.address: "*"
|
||||
openwifi.restapi.host.0.port: 16004
|
||||
openwifi.restapi.host.0.cert: $OWFMS_ROOT/certs/restapi-cert.pem
|
||||
openwifi.restapi.host.0.key: $OWFMS_ROOT/certs/restapi-key.pem
|
||||
openwifi.internal.restapi.host.0.backlog: 100
|
||||
openwifi.internal.restapi.host.0.security: relaxed
|
||||
openwifi.internal.restapi.host.0.rootca: $OWFMS_ROOT/certs/restapi-ca.pem
|
||||
openwifi.internal.restapi.host.0.address: "*"
|
||||
openwifi.internal.restapi.host.0.port: 17004
|
||||
openwifi.internal.restapi.host.0.cert: $OWFMS_ROOT/certs/restapi-cert.pem
|
||||
openwifi.internal.restapi.host.0.key: $OWFMS_ROOT/certs/restapi-key.pem
|
||||
# Firmware Microservice Specific Section
|
||||
s3.bucketname: ucentral-ap-firmware
|
||||
s3.region: us-east-1
|
||||
@@ -133,12 +133,12 @@ configProperties:
|
||||
alb.enable: "true"
|
||||
alb.port: 16104
|
||||
# Kafka
|
||||
ucentral.kafka.enable: "false"
|
||||
ucentral.kafka.group.id: firmware
|
||||
ucentral.kafka.client.id: firmware1
|
||||
ucentral.kafka.brokerlist: localhost:9092
|
||||
ucentral.kafka.auto.commit: false
|
||||
ucentral.kafka.queue.buffering.max.ms: 50
|
||||
openwifi.kafka.enable: "false"
|
||||
openwifi.kafka.group.id: firmware
|
||||
openwifi.kafka.client.id: firmware1
|
||||
openwifi.kafka.brokerlist: localhost:9092
|
||||
openwifi.kafka.auto.commit: false
|
||||
openwifi.kafka.queue.buffering.max.ms: 50
|
||||
# Storage
|
||||
storage.type: sqlite # (sqlite|postgresql|mysql|odbc)
|
||||
## SQLite
|
||||
@@ -149,24 +149,24 @@ configProperties:
|
||||
storage.type.postgresql.maxsessions: 64
|
||||
storage.type.postgresql.idletime: 60
|
||||
storage.type.postgresql.host: localhost
|
||||
storage.type.postgresql.database: ucentral
|
||||
storage.type.postgresql.database: owfms
|
||||
storage.type.postgresql.port: 5432
|
||||
storage.type.postgresql.connectiontimeout: 60
|
||||
## MySQL
|
||||
storage.type.mysql.maxsessions: 64
|
||||
storage.type.mysql.idletime: 60
|
||||
storage.type.mysql.host: localhost
|
||||
storage.type.mysql.database: ucentral
|
||||
storage.type.mysql.database: owfms
|
||||
storage.type.mysql.port: 3306
|
||||
storage.type.mysql.connectiontimeout: 60
|
||||
# System
|
||||
ucentral.service.key: $UCENTRALFMS_ROOT/certs/restapi-key.pem
|
||||
ucentral.system.data: $UCENTRALFMS_ROOT/persist
|
||||
ucentral.system.debug: "true"
|
||||
ucentral.system.uri.private: https://localhost:17004
|
||||
ucentral.system.uri.public: https://localhost:16004
|
||||
ucentral.system.uri.ui: https://localhost
|
||||
ucentral.system.commandchannel: /tmp/app_ucentralfms
|
||||
openwifi.service.key: $OWFMS_ROOT/certs/restapi-key.pem
|
||||
openwifi.system.data: $OWFMS_ROOT/persist
|
||||
openwifi.system.debug: "true"
|
||||
openwifi.system.uri.private: https://localhost:17004
|
||||
openwifi.system.uri.public: https://localhost:16004
|
||||
openwifi.system.uri.ui: https://localhost
|
||||
openwifi.system.commandchannel: /tmp/app_owfms
|
||||
# Logging
|
||||
logging.formatters.f1.class: PatternFormatter
|
||||
logging.formatters.f1.pattern: "%Y-%m-%d %H:%M:%S %s: [%p] %t"
|
||||
@@ -174,7 +174,7 @@ configProperties:
|
||||
logging.channels.c1.class: ConsoleChannel
|
||||
logging.channels.c1.formatter: f1
|
||||
logging.channels.c2.class: FileChannel
|
||||
logging.channels.c2.path: /tmp/log_ucentralfms
|
||||
logging.channels.c2.path: /tmp/log_owfms
|
||||
logging.channels.c2.formatter.class: PatternFormatter
|
||||
logging.channels.c2.formatter.pattern: "%Y-%m-%d %H:%M:%S %s: [%p] %t"
|
||||
logging.channels.c2.rotation: "20 M"
|
||||
@@ -187,8 +187,8 @@ configProperties:
|
||||
|
||||
# -> Secret part
|
||||
# REST API
|
||||
ucentral.restapi.host.0.key.password: mypassword
|
||||
ucentral.internal.restapi.host.0.key.password: mypassword
|
||||
openwifi.restapi.host.0.key.password: mypassword
|
||||
openwifi.internal.restapi.host.0.key.password: mypassword
|
||||
# Firmware Microservice Specific Section
|
||||
s3.secret: TOFILL
|
||||
s3.key: TOFILL
|
||||
|
||||
@@ -294,28 +294,6 @@ components:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagIntPair'
|
||||
|
||||
SystemCommandDetails:
|
||||
type: object
|
||||
properties:
|
||||
command:
|
||||
type: string
|
||||
enum:
|
||||
- setloglevels
|
||||
- getloglevels
|
||||
- getSubSystemNames
|
||||
- getLogLevelNames
|
||||
- stats
|
||||
parameters:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/StringList'
|
||||
- $ref: '#/components/schemas/TagValuePairList'
|
||||
|
||||
SystemCommandResults:
|
||||
type: object
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/StringList'
|
||||
- $ref: '#/components/schemas/TagValuePairList'
|
||||
|
||||
NoteInfo:
|
||||
type: object
|
||||
properties:
|
||||
@@ -327,12 +305,112 @@ components:
|
||||
note:
|
||||
type: string
|
||||
|
||||
#########################################################################################
|
||||
##
|
||||
## End of uCentral system wide values
|
||||
##
|
||||
#########################################################################################
|
||||
SystemInfoResults:
|
||||
type: object
|
||||
properties:
|
||||
version:
|
||||
type: string
|
||||
uptime:
|
||||
type: integer
|
||||
format: integer64
|
||||
start:
|
||||
type: integer
|
||||
format: integer64
|
||||
os:
|
||||
type: string
|
||||
processors:
|
||||
type: integer
|
||||
hostname:
|
||||
type: string
|
||||
certificates:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
filename:
|
||||
type: string
|
||||
expires:
|
||||
type: integer
|
||||
format: int64
|
||||
|
||||
SystemCommandSetLogLevel:
|
||||
type: object
|
||||
properties:
|
||||
command:
|
||||
type: string
|
||||
enum:
|
||||
- setloglevel
|
||||
subsystems:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/TagValuePair'
|
||||
|
||||
SystemCommandReload:
|
||||
type: object
|
||||
properties:
|
||||
command:
|
||||
type: string
|
||||
enum:
|
||||
- reload
|
||||
subsystems:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
example: these are the SubSystems names retrieve with the GetSubSystemsNamesResult.
|
||||
|
||||
SystemCommandGetLogLevels:
|
||||
type: object
|
||||
properties:
|
||||
command:
|
||||
type: string
|
||||
enum:
|
||||
- getloglevels
|
||||
|
||||
SystemGetLogLevelsResult:
|
||||
type: object
|
||||
properties:
|
||||
taglist:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/TagValuePair'
|
||||
|
||||
SystemCommandGetLogLevelNames:
|
||||
type: object
|
||||
properties:
|
||||
command:
|
||||
type: string
|
||||
enum:
|
||||
- getloglevelnames
|
||||
|
||||
SystemCommandGetSubsystemNames:
|
||||
type: object
|
||||
properties:
|
||||
command:
|
||||
type: string
|
||||
enum:
|
||||
- getsubsystemnames
|
||||
|
||||
SystemCommandGetLogLevelNamesResult:
|
||||
type: object
|
||||
properties:
|
||||
list:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
|
||||
SystemGetSubSystemNemesResult:
|
||||
type: object
|
||||
properties:
|
||||
taglist:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/TagValuePair'
|
||||
|
||||
#########################################################################################
|
||||
##
|
||||
## End of uCentral system-wide values
|
||||
##
|
||||
#########################################################################################
|
||||
paths:
|
||||
/firmwares:
|
||||
get:
|
||||
@@ -704,21 +782,29 @@ paths:
|
||||
post:
|
||||
tags:
|
||||
- System Commands
|
||||
summary: Perform some systeme wide commands
|
||||
summary: Perform some system wide commands
|
||||
operationId: systemCommand
|
||||
requestBody:
|
||||
description: Command details
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/SystemCommandDetails'
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/SystemCommandSetLogLevel'
|
||||
- $ref: '#/components/schemas/SystemCommandReload'
|
||||
- $ref: '#/components/schemas/SystemCommandGetLogLevels'
|
||||
- $ref: '#/components/schemas/SystemCommandGetLogLevelNames'
|
||||
- $ref: '#/components/schemas/SystemCommandGetSubsystemNames'
|
||||
responses:
|
||||
200:
|
||||
description: Successfull command execution
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/SystemCommandResults'
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/SystemGetLogLevelsResult'
|
||||
- $ref: '#/components/schemas/SystemCommandGetLogLevelNamesResult'
|
||||
- $ref: '#/components/schemas/SystemGetSubSystemNemesResult'
|
||||
403:
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
404:
|
||||
@@ -735,8 +821,7 @@ paths:
|
||||
schema:
|
||||
type: string
|
||||
enum:
|
||||
- version
|
||||
- times
|
||||
- info
|
||||
required: true
|
||||
|
||||
responses:
|
||||
@@ -745,7 +830,8 @@ paths:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/TagValuePair'
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/SystemInfoResults'
|
||||
403:
|
||||
$ref: '#/components/responses/Unauthorized'
|
||||
404:
|
||||
@@ -6,35 +6,37 @@
|
||||
#
|
||||
# REST API access
|
||||
#
|
||||
ucentralfws.restapi.host.0.backlog = 100
|
||||
ucentralfws.restapi.host.0.security = relaxed
|
||||
ucentralfws.restapi.host.0.rootca = $UCENTRALFMS_ROOT/certs/restapi-ca.pem
|
||||
ucentralfws.restapi.host.0.address = *
|
||||
ucentralfws.restapi.host.0.port = 16004
|
||||
ucentralfws.restapi.host.0.cert = $UCENTRALFMS_ROOT/certs/restapi-cert.pem
|
||||
ucentralfws.restapi.host.0.key = $UCENTRALFMS_ROOT/certs/restapi-key.pem
|
||||
ucentralfws.restapi.host.0.key.password = mypassword
|
||||
openwifi.restapi.host.0.backlog = 100
|
||||
openwifi.restapi.host.0.security = relaxed
|
||||
openwifi.restapi.host.0.rootca = $OWFMS_ROOT/certs/restapi-ca.pem
|
||||
openwifi.restapi.host.0.address = *
|
||||
openwifi.restapi.host.0.port = 16004
|
||||
openwifi.restapi.host.0.cert = $OWFMS_ROOT/certs/restapi-cert.pem
|
||||
openwifi.restapi.host.0.key = $OWFMS_ROOT/certs/restapi-key.pem
|
||||
openwifi.restapi.host.0.key.password = mypassword
|
||||
|
||||
ucentral.internal.restapi.host.0.backlog = 100
|
||||
ucentral.internal.restapi.host.0.security = relaxed
|
||||
ucentral.internal.restapi.host.0.rootca = $UCENTRALFMS_ROOT/certs/restapi-ca.pem
|
||||
ucentral.internal.restapi.host.0.address = *
|
||||
ucentral.internal.restapi.host.0.port = 17004
|
||||
ucentral.internal.restapi.host.0.cert = $UCENTRALFMS_ROOT/certs/restapi-cert.pem
|
||||
ucentral.internal.restapi.host.0.key = $UCENTRALFMS_ROOT/certs/restapi-key.pem
|
||||
ucentral.internal.restapi.host.0.key.password = mypassword
|
||||
openwifi.internal.restapi.host.0.backlog = 100
|
||||
openwifi.internal.restapi.host.0.security = relaxed
|
||||
openwifi.internal.restapi.host.0.rootca = $OWFMS_ROOT/certs/restapi-ca.pem
|
||||
openwifi.internal.restapi.host.0.address = *
|
||||
openwifi.internal.restapi.host.0.port = 17004
|
||||
openwifi.internal.restapi.host.0.cert = $OWFMS_ROOT/certs/restapi-cert.pem
|
||||
openwifi.internal.restapi.host.0.key = $OWFMS_ROOT/certs/restapi-key.pem
|
||||
openwifi.internal.restapi.host.0.key.password = mypassword
|
||||
|
||||
#
|
||||
# Generic section that all microservices must have
|
||||
#
|
||||
ucentral.service.key = $UCENTRALFMS_ROOT/certs/restapi-key.pem
|
||||
ucentral.service.key.password = mypassword
|
||||
ucentral.system.data = $UCENTRALFMS_ROOT/data
|
||||
ucentral.system.debug = false
|
||||
ucentral.system.uri.private = https://localhost:17004
|
||||
ucentral.system.uri.public = https://local.dpaas.arilia.com:16004
|
||||
ucentral.system.commandchannel = /tmp/app.ucentralfms
|
||||
ucentral.system.uri.ui = ucentral-ui.arilia.com
|
||||
openwifi.service.key = $OWFMS_ROOT/certs/restapi-key.pem
|
||||
openwifi.service.key.password = mypassword
|
||||
openwifi.system.data = $OWFMS_ROOT/data
|
||||
openwifi.system.debug = false
|
||||
openwifi.system.uri.private = https://localhost:17004
|
||||
openwifi.system.uri.public = https://ucentral.dpaas.arilia.com:16004
|
||||
openwifi.system.commandchannel = /tmp/app.owfms
|
||||
openwifi.system.uri.ui = ucentral-ui.arilia.com
|
||||
firmwaredb.refresh = 1800
|
||||
firmwaredb.maxage = 90
|
||||
|
||||
#
|
||||
# Firmware Microservice Specific Section
|
||||
@@ -46,7 +48,7 @@ s3.key = *******************************************
|
||||
s3.retry = 60
|
||||
s3.bucket.uri = ucentral-ap-firmware.s3.amazonaws.com
|
||||
|
||||
firmwaredb.refresh = 1800
|
||||
|
||||
#############################
|
||||
# Generic information for all micro services
|
||||
#############################
|
||||
@@ -59,13 +61,12 @@ alb.port = 16104
|
||||
#
|
||||
# Kafka
|
||||
#
|
||||
ucentral.kafka.group.id = firmware
|
||||
ucentral.kafka.client.id = firmware1
|
||||
ucentral.kafka.enable = true
|
||||
# ucentral.kafka.brokerlist = a1.arilia.com:9092
|
||||
ucentral.kafka.brokerlist = debfarm1-node-c.arilia.com:9092
|
||||
ucentral.kafka.auto.commit = false
|
||||
ucentral.kafka.queue.buffering.max.ms = 50
|
||||
openwifi.kafka.group.id = firmware
|
||||
openwifi.kafka.client.id = firmware1
|
||||
openwifi.kafka.enable = true
|
||||
openwifi.kafka.brokerlist = a1.arilia.com:9092
|
||||
openwifi.kafka.auto.commit = false
|
||||
openwifi.kafka.queue.buffering.max.ms = 50
|
||||
|
||||
#
|
||||
# This section select which form of persistence you need
|
||||
@@ -114,7 +115,7 @@ logging.channels.c1.formatter = f1
|
||||
|
||||
# This is where the logs will be written. This path MUST exist
|
||||
logging.channels.c2.class = FileChannel
|
||||
logging.channels.c2.path = $UCENTRALFMS_ROOT/logs/log
|
||||
logging.channels.c2.path = $OWFMS_ROOT/logs/log
|
||||
logging.channels.c2.formatter.class = PatternFormatter
|
||||
logging.channels.c2.formatter.pattern = %Y-%m-%d %H:%M:%S %s: [%p] %t
|
||||
logging.channels.c2.rotation = 20 M
|
||||
140
owfms.properties.tmpl
Normal file
140
owfms.properties.tmpl
Normal file
@@ -0,0 +1,140 @@
|
||||
#
|
||||
# uCentral protocol server for devices. This is where you point
|
||||
# all your devices. You can replace the * for address by the specific
|
||||
# address of one of your interfaces
|
||||
#
|
||||
|
||||
#
|
||||
# REST API access
|
||||
#
|
||||
openwifi.restapi.host.0.backlog = 100
|
||||
openwifi.restapi.host.0.security = relaxed
|
||||
openwifi.restapi.host.0.rootca = ${RESTAPI_HOST_ROOTCA}
|
||||
openwifi.restapi.host.0.address = *
|
||||
openwifi.restapi.host.0.port = ${RESTAPI_HOST_PORT}
|
||||
openwifi.restapi.host.0.cert = ${RESTAPI_HOST_CERT}
|
||||
openwifi.restapi.host.0.key = ${RESTAPI_HOST_KEY}
|
||||
openwifi.restapi.host.0.key.password = ${RESTAPI_HOST_KEY_PASSWORD}
|
||||
|
||||
openwifi.internal.restapi.host.0.backlog = 100
|
||||
openwifi.internal.restapi.host.0.security = relaxed
|
||||
openwifi.internal.restapi.host.0.rootca = ${INTERNAL_RESTAPI_HOST_ROOTCA}
|
||||
openwifi.internal.restapi.host.0.address = *
|
||||
openwifi.internal.restapi.host.0.port = ${INTERNAL_RESTAPI_HOST_PORT}
|
||||
openwifi.internal.restapi.host.0.cert = ${INTERNAL_RESTAPI_HOST_CERT}
|
||||
openwifi.internal.restapi.host.0.key = ${INTERNAL_RESTAPI_HOST_KEY}
|
||||
openwifi.internal.restapi.host.0.key.password = ${INTERNAL_RESTAPI_HOST_KEY_PASSWORD}
|
||||
|
||||
#
|
||||
# Generic section that all microservices must have
|
||||
#
|
||||
openwifi.service.key = ${SERVICE_KEY}
|
||||
openwifi.service.key.password = ${SERVICE_KEY_PASSWORD}
|
||||
openwifi.system.data = ${SYSTEM_DATA}
|
||||
openwifi.system.debug = false
|
||||
openwifi.system.uri.private = ${SYSTEM_URI_PRIVATE}
|
||||
openwifi.system.uri.public = ${SYSTEM_URI_PUBLIC}
|
||||
openwifi.system.commandchannel = /tmp/app.ucentralfms
|
||||
openwifi.system.uri.ui = ${SYSTEM_URI_UI}
|
||||
firmwaredb.refresh = 1800
|
||||
firmwaredb.maxage = 90
|
||||
|
||||
#
|
||||
# Firmware Microservice Specific Section
|
||||
#
|
||||
s3.bucketname = ${S3_BUCKETNAME}
|
||||
s3.region = ${S3_REGION}
|
||||
s3.secret = ${S3_SECRET}
|
||||
s3.key = ${S3_KEY}
|
||||
s3.retry = 60
|
||||
s3.bucket.uri = ${S3_BUCKET_URI}
|
||||
|
||||
#############################
|
||||
# Generic information for all micro services
|
||||
#############################
|
||||
#
|
||||
# NLB Support
|
||||
#
|
||||
alb.enable = true
|
||||
alb.port = 16104
|
||||
|
||||
#
|
||||
# Kafka
|
||||
#
|
||||
openwifi.kafka.group.id = firmware
|
||||
openwifi.kafka.client.id = firmware1
|
||||
openwifi.kafka.enable = ${KAFKA_ENABLE}
|
||||
openwifi.kafka.brokerlist = ${KAFKA_BROKERLIST}
|
||||
openwifi.kafka.auto.commit = false
|
||||
openwifi.kafka.queue.buffering.max.ms = 50
|
||||
|
||||
#
|
||||
# This section select which form of persistence you need
|
||||
# Only one selected at a time. If you select multiple, this service will die if a horrible
|
||||
# death and might make your beer flat.
|
||||
#
|
||||
storage.type = ${STORAGE_TYPE}
|
||||
|
||||
storage.type.sqlite.db = firmware.db
|
||||
storage.type.sqlite.idletime = 120
|
||||
storage.type.sqlite.maxsessions = 128
|
||||
|
||||
storage.type.postgresql.maxsessions = 64
|
||||
storage.type.postgresql.idletime = 60
|
||||
storage.type.postgresql.host = ${STORAGE_TYPE_POSTGRESQL_HOST}
|
||||
storage.type.postgresql.username = ${STORAGE_TYPE_POSTGRESQL_USERNAME}
|
||||
storage.type.postgresql.password = ${STORAGE_TYPE_POSTGRESQL_PASSWORD}
|
||||
storage.type.postgresql.database = ${STORAGE_TYPE_POSTGRESQL_DATABASE}
|
||||
storage.type.postgresql.port = ${STORAGE_TYPE_POSTGRESQL_PORT}
|
||||
storage.type.postgresql.connectiontimeout = 60
|
||||
|
||||
storage.type.mysql.maxsessions = 64
|
||||
storage.type.mysql.idletime = 60
|
||||
storage.type.mysql.host = ${STORAGE_TYPE_MYSQL_HOST}
|
||||
storage.type.mysql.username = ${STORAGE_TYPE_MYSQL_USERNAME}
|
||||
storage.type.mysql.password = ${STORAGE_TYPE_MYSQL_PASSWORD}
|
||||
storage.type.mysql.database = ${STORAGE_TYPE_MYSQL_DATABASE}
|
||||
storage.type.mysql.port = ${STORAGE_TYPE_MYSQL_PORT}
|
||||
storage.type.mysql.connectiontimeout = 60
|
||||
|
||||
|
||||
########################################################################
|
||||
########################################################################
|
||||
#
|
||||
# Logging: please leave as is for now.
|
||||
#
|
||||
########################################################################
|
||||
logging.formatters.f1.class = PatternFormatter
|
||||
logging.formatters.f1.pattern = %Y-%m-%d %H:%M:%S %s: [%p] %t
|
||||
logging.formatters.f1.times = UTC
|
||||
logging.channels.c1.class = ConsoleChannel
|
||||
logging.channels.c1.formatter = f1
|
||||
|
||||
# This is where the logs will be written. This path MUST exist
|
||||
logging.channels.c2.class = FileChannel
|
||||
logging.channels.c2.path = $UCENTRALSEC_ROOT/logs/log
|
||||
logging.channels.c2.formatter.class = PatternFormatter
|
||||
logging.channels.c2.formatter.pattern = %Y-%m-%d %H:%M:%S %s: [%p] %t
|
||||
logging.channels.c2.rotation = 20 M
|
||||
logging.channels.c2.archive = timestamp
|
||||
logging.channels.c2.purgeCount = 20
|
||||
logging.channels.c3.class = ConsoleChannel
|
||||
logging.channels.c3.pattern = %s: [%p] %t
|
||||
|
||||
# External Channel
|
||||
logging.loggers.root.channel = c1
|
||||
logging.loggers.root.level = debug
|
||||
|
||||
# Inline Channel with PatternFormatter
|
||||
# logging.loggers.l1.name = logger1
|
||||
# logging.loggers.l1.channel.class = ConsoleChannel
|
||||
# logging.loggers.l1.channel.pattern = %s: [%p] %t
|
||||
# logging.loggers.l1.level = information
|
||||
# SplitterChannel
|
||||
# logging.channels.splitter.class = SplitterChannel
|
||||
# logging.channels.splitter.channels = l1,l2
|
||||
# logging.loggers.l2.name = logger2
|
||||
# logging.loggers.l2.channel = splitter
|
||||
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Environment="UCENTRALFMS_ROOT=/home/admin/dev/wlan-cloud-ucentralfms"
|
||||
ExecStart=/home/admin/dev/wlan-cloud-ucentralfms/cmake-build/ucentralfms
|
||||
Environment="OWFMS_ROOT=/home/admin/dev/wlan-cloud-ucentralfms"
|
||||
ExecStart=/home/admin/dev/wlan-cloud-ucentralfms/cmake-build/owfms
|
||||
WorkingDirectory=/home/admin/dev/wlan-cloud-ucentralfms
|
||||
# ExecReload=/bin/kill -s HUP $MAINPID
|
||||
User=admin
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/bin/bash
|
||||
|
||||
export UCENTRALFMS_CONFIG=`pwd`
|
||||
export UCENTRALFMS_ROOT=`pwd`
|
||||
export OWFMS_CONFIG=`pwd`
|
||||
export OWFMS_ROOT=`pwd`
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
//
|
||||
// Created by stephane bourque on 2021-06-04.
|
||||
// License type: BSD 3-Clause License
|
||||
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
|
||||
//
|
||||
// Created by Stephane Bourque on 2021-03-04.
|
||||
// Arilia Wireless Inc.
|
||||
//
|
||||
|
||||
#ifndef UCENTRALGW_ALBHEALTHCHECKSERVER_H
|
||||
@@ -26,12 +30,12 @@ namespace OpenWifi {
|
||||
/// Return a HTML document with the current date and time.
|
||||
{
|
||||
public:
|
||||
ALBRequestHandler(Poco::Logger & L)
|
||||
explicit ALBRequestHandler(Poco::Logger & L)
|
||||
: Logger_(L)
|
||||
{
|
||||
}
|
||||
|
||||
void handleRequest(Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response)
|
||||
void handleRequest(Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) override
|
||||
{
|
||||
Logger_.information(Poco::format("ALB-REQUEST(%s): New ALB request.",Request.clientAddress().toString()));
|
||||
Response.setChunkedTransferEncoding(true);
|
||||
@@ -83,7 +87,7 @@ namespace OpenWifi {
|
||||
return instance_;
|
||||
}
|
||||
|
||||
int Start() {
|
||||
int Start() override {
|
||||
if(Daemon()->ConfigGetBool("alb.enable",false)) {
|
||||
Port_ = (int)Daemon()->ConfigGetInt("alb.port",15015);
|
||||
Socket_ = std::make_unique<Poco::Net::ServerSocket>(Port_);
|
||||
@@ -95,7 +99,7 @@ namespace OpenWifi {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void Stop() {
|
||||
void Stop() override {
|
||||
if(Server_)
|
||||
Server_->stop();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
//
|
||||
// Created by stephane bourque on 2021-06-30.
|
||||
// License type: BSD 3-Clause License
|
||||
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
|
||||
//
|
||||
// Created by Stephane Bourque on 2021-03-04.
|
||||
// Arilia Wireless Inc.
|
||||
//
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "AuthClient.h"
|
||||
@@ -20,7 +25,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void AuthClient::RemovedCachedToken(const std::string &Token) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
UserCache_.erase(Token);
|
||||
}
|
||||
|
||||
@@ -29,7 +34,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
bool AuthClient::IsAuthorized(Poco::Net::HTTPServerRequest & Request, std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo ) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
auto User = UserCache_.find(SessionToken);
|
||||
if(User != UserCache_.end() && !IsTokenExpired(User->second.webtoken)) {
|
||||
@@ -58,7 +63,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
bool AuthClient::IsTokenAuthorized(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
auto User = UserCache_.find(SessionToken);
|
||||
if(User != UserCache_.end() && !IsTokenExpired(User->second.webtoken)) {
|
||||
|
||||
16
src/Daemon.h
16
src/Daemon.h
@@ -22,20 +22,20 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
static const char * vDAEMON_PROPERTIES_FILENAME = "ucentralfms.properties";
|
||||
static const char * vDAEMON_ROOT_ENV_VAR = "UCENTRALFMS_ROOT";
|
||||
static const char * vDAEMON_CONFIG_ENV_VAR = "UCENTRALFMS_CONFIG";
|
||||
static const char * vDAEMON_PROPERTIES_FILENAME = "owfms.properties";
|
||||
static const char * vDAEMON_ROOT_ENV_VAR = "OWFMS_ROOT";
|
||||
static const char * vDAEMON_CONFIG_ENV_VAR = "OWFMS_CONFIG";
|
||||
static const char * vDAEMON_APP_NAME = uSERVICE_FIRMWARE.c_str();
|
||||
static const uint64_t vDAEMON_BUS_TIMER = 10000;
|
||||
|
||||
class Daemon : public MicroService {
|
||||
public:
|
||||
explicit Daemon(std::string PropFile,
|
||||
std::string RootEnv,
|
||||
std::string ConfigEnv,
|
||||
std::string AppName,
|
||||
explicit Daemon(const std::string & PropFile,
|
||||
const std::string & RootEnv,
|
||||
const std::string & ConfigEnv,
|
||||
const std::string & AppName,
|
||||
uint64_t BusTimer,
|
||||
Types::SubSystemVec SubSystems) :
|
||||
const Types::SubSystemVec & SubSystems) :
|
||||
MicroService( PropFile, RootEnv, ConfigEnv, AppName, BusTimer, SubSystems) {};
|
||||
|
||||
void initialize(Poco::Util::Application &self);
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace OpenWifi {
|
||||
void DeviceCache::AddToCache(
|
||||
const std::string &SerialNumber, const std::string & DeviceType,
|
||||
const std::string &Host, const std::string &Revision) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
auto Device = DeviceCache_.find(SerialNumber);
|
||||
|
||||
if(Device==DeviceCache_.end()) {
|
||||
@@ -33,7 +33,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
bool DeviceCache::GetDevice(const std::string &SerialNumber, DeviceCacheEntry & E) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
auto Device = DeviceCache_.find(SerialNumber);
|
||||
if(Device==DeviceCache_.end())
|
||||
return false;
|
||||
|
||||
@@ -17,13 +17,13 @@ namespace OpenWifi {
|
||||
class KafkaManager *KafkaManager::instance_ = nullptr;
|
||||
|
||||
KafkaManager::KafkaManager() noexcept:
|
||||
SubSystemServer("KafkaManager", "KAFKA-SVR", "ucentral.kafka")
|
||||
SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka")
|
||||
{
|
||||
}
|
||||
|
||||
void KafkaManager::initialize(Poco::Util::Application & self) {
|
||||
SubSystemServer::initialize(self);
|
||||
KafkaEnabled_ = Daemon()->ConfigGetBool("ucentral.kafka.enable",false);
|
||||
KafkaEnabled_ = Daemon()->ConfigGetBool("openwifi.kafka.enable",false);
|
||||
}
|
||||
|
||||
#ifdef SMALL_BUILD
|
||||
@@ -55,8 +55,8 @@ namespace OpenWifi {
|
||||
|
||||
void KafkaManager::ProducerThr() {
|
||||
cppkafka::Configuration Config({
|
||||
{ "client.id", Daemon()->ConfigGetString("ucentral.kafka.client.id") },
|
||||
{ "metadata.broker.list", Daemon()->ConfigGetString("ucentral.kafka.brokerlist") }
|
||||
{ "client.id", Daemon()->ConfigGetString("openwifi.kafka.client.id") },
|
||||
{ "metadata.broker.list", Daemon()->ConfigGetString("openwifi.kafka.brokerlist") }
|
||||
});
|
||||
SystemInfoWrapper_ = R"lit({ "system" : { "id" : )lit" +
|
||||
std::to_string(Daemon()->ID()) +
|
||||
@@ -68,7 +68,7 @@ namespace OpenWifi {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
try
|
||||
{
|
||||
SubMutexGuard G(ProducerMutex_);
|
||||
std::lock_guard G(ProducerMutex_);
|
||||
auto Num=0;
|
||||
while (!Queue_.empty()) {
|
||||
const auto M = Queue_.front();
|
||||
@@ -96,10 +96,10 @@ namespace OpenWifi {
|
||||
|
||||
void KafkaManager::ConsumerThr() {
|
||||
cppkafka::Configuration Config({
|
||||
{ "client.id", Daemon()->ConfigGetString("ucentral.kafka.client.id") },
|
||||
{ "metadata.broker.list", Daemon()->ConfigGetString("ucentral.kafka.brokerlist") },
|
||||
{ "group.id", Daemon()->ConfigGetString("ucentral.kafka.group.id") },
|
||||
{ "enable.auto.commit", Daemon()->ConfigGetBool("ucentral.kafka.auto.commit",false) },
|
||||
{ "client.id", Daemon()->ConfigGetString("openwifi.kafka.client.id") },
|
||||
{ "metadata.broker.list", Daemon()->ConfigGetString("openwifi.kafka.brokerlist") },
|
||||
{ "group.id", Daemon()->ConfigGetString("openwifi.kafka.group.id") },
|
||||
{ "enable.auto.commit", Daemon()->ConfigGetBool("openwifi.kafka.auto.commit",false) },
|
||||
{ "auto.offset.reset", "latest" } ,
|
||||
{ "enable.partition.eof", false }
|
||||
});
|
||||
@@ -125,8 +125,8 @@ namespace OpenWifi {
|
||||
}
|
||||
});
|
||||
|
||||
bool AutoCommit = Daemon()->ConfigGetBool("ucentral.kafka.auto.commit",false);
|
||||
auto BatchSize = Daemon()->ConfigGetInt("ucentral.kafka.consumer.batchsize",20);
|
||||
bool AutoCommit = Daemon()->ConfigGetBool("openwifi.kafka.auto.commit",false);
|
||||
auto BatchSize = Daemon()->ConfigGetInt("openwifi.kafka.consumer.batchsize",20);
|
||||
|
||||
Types::StringVec Topics;
|
||||
for(const auto &i:Notifiers_)
|
||||
@@ -148,7 +148,7 @@ namespace OpenWifi {
|
||||
Consumer.async_commit(Msg);
|
||||
continue;
|
||||
}
|
||||
SubMutexGuard G(ConsumerMutex_);
|
||||
std::lock_guard G(ConsumerMutex_);
|
||||
auto It = Notifiers_.find(Msg.get_topic());
|
||||
if (It != Notifiers_.end()) {
|
||||
Types::TopicNotifyFunctionList &FL = It->second;
|
||||
@@ -174,9 +174,9 @@ namespace OpenWifi {
|
||||
return std::move( SystemInfoWrapper_ + PayLoad + "}");
|
||||
}
|
||||
|
||||
void KafkaManager::PostMessage(std::string topic, std::string key, std::string PayLoad, bool WrapMessage ) {
|
||||
void KafkaManager::PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage ) {
|
||||
if(KafkaEnabled_) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
KMessage M{
|
||||
.Topic = topic,
|
||||
.Key = key,
|
||||
@@ -187,7 +187,7 @@ namespace OpenWifi {
|
||||
|
||||
int KafkaManager::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) {
|
||||
if(KafkaEnabled_) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
auto It = Notifiers_.find(Topic);
|
||||
if(It == Notifiers_.end()) {
|
||||
Types::TopicNotifyFunctionList L;
|
||||
@@ -204,7 +204,7 @@ namespace OpenWifi {
|
||||
|
||||
void KafkaManager::UnregisterTopicWatcher(const std::string &Topic, int Id) {
|
||||
if(KafkaEnabled_) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
auto It = Notifiers_.find(Topic);
|
||||
if(It != Notifiers_.end()) {
|
||||
Types::TopicNotifyFunctionList & L = It->second;
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace OpenWifi {
|
||||
int Start() override;
|
||||
void Stop() override;
|
||||
|
||||
void PostMessage(std::string topic, std::string key, std::string payload, bool WrapMessage = true);
|
||||
void PostMessage(const std::string &topic, const std::string & key, const std::string &payload, bool WrapMessage = true);
|
||||
[[nodiscard]] std::string WrapSystemId(const std::string & PayLoad);
|
||||
[[nodiscard]] bool Enabled() { return KafkaEnabled_; }
|
||||
int RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction & F);
|
||||
@@ -52,8 +52,8 @@ namespace OpenWifi {
|
||||
|
||||
private:
|
||||
static KafkaManager *instance_;
|
||||
SubMutex ProducerMutex_;
|
||||
SubMutex ConsumerMutex_;
|
||||
std::mutex ProducerMutex_;
|
||||
std::mutex ConsumerMutex_;
|
||||
bool KafkaEnabled_ = false;
|
||||
std::atomic_bool ProducerRunning_ = false;
|
||||
std::atomic_bool ConsumerRunning_ = false;
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
bool LatestFirmwareCache::AddToCache(const std::string & DeviceType, const std::string &Revision, const std::string &Id, uint64_t TimeStamp) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
RevisionSet_.insert(Revision);
|
||||
DeviceSet_.insert(DeviceType);
|
||||
@@ -32,7 +32,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
bool LatestFirmwareCache::FindLatestFirmware(const std::string &DeviceType, LatestFirmwareCacheEntry &Entry ) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
auto E=Cache_.find(DeviceType);
|
||||
if(E!=Cache_.end()) {
|
||||
@@ -44,7 +44,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
bool LatestFirmwareCache::IsLatest(const std::string &DeviceType, const std::string &Revision) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
auto E=Cache_.find(DeviceType);
|
||||
if(E!=Cache_.end()) {
|
||||
@@ -55,7 +55,7 @@ namespace OpenWifi {
|
||||
|
||||
|
||||
void LatestFirmwareCache::DumpCache() {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
for( auto &[Id,E]:Cache_) {
|
||||
std::cout << "Device: " << Id << " ID:" << E.Id << std::endl;
|
||||
|
||||
@@ -37,8 +37,8 @@ namespace OpenWifi {
|
||||
// void AddRevision(const std::string &Revision);
|
||||
bool FindLatestFirmware(const std::string &DeviceType, LatestFirmwareCacheEntry &Entry );
|
||||
void DumpCache();
|
||||
inline Types::StringSet GetRevisions() { SubMutexGuard G(Mutex_); return RevisionSet_; };
|
||||
inline Types::StringSet GetDevices() { SubMutexGuard G(Mutex_); return DeviceSet_; };
|
||||
inline Types::StringSet GetRevisions() { std::lock_guard G(Mutex_); return RevisionSet_; };
|
||||
inline Types::StringSet GetDevices() { std::lock_guard G(Mutex_); return DeviceSet_; };
|
||||
bool IsLatest(const std::string &DeviceType, const std::string &Revision);
|
||||
|
||||
private:
|
||||
|
||||
@@ -31,6 +31,7 @@ namespace OpenWifi {
|
||||
FirstRun = false;
|
||||
Logger_.information("Performing DB refresh");
|
||||
S3BucketContent BucketList;
|
||||
Storage()->RemoveOldFirmware();
|
||||
ReadBucket(BucketList);
|
||||
if(!Running_)
|
||||
break;
|
||||
@@ -42,6 +43,7 @@ namespace OpenWifi {
|
||||
|
||||
bool ManifestCreator::ComputeManifest(S3BucketContent &BucketContent) {
|
||||
|
||||
uint64_t Limit = std::time(nullptr) - MaxAge_, Rejected=0, Accepted=0, BadFormat=0, MissingJson=0;
|
||||
for(auto &[Name,Entry]:BucketContent) {
|
||||
std::string C = Entry.S3ContentManifest;
|
||||
|
||||
@@ -55,24 +57,38 @@ namespace OpenWifi {
|
||||
ParsedContent->has("timestamp"))
|
||||
{
|
||||
Entry.Timestamp = ParsedContent->get("timestamp");
|
||||
Entry.Compatible = ParsedContent->get("compatible").toString();
|
||||
Entry.Revision = ParsedContent->get("revision").toString();
|
||||
Entry.Image = ParsedContent->get("image").toString();
|
||||
auto FullNme = Name + "-upgrade.bin";
|
||||
if(FullNme!=Entry.Image) {
|
||||
Logger_.error(Poco::format("MANIFEST(%s): Image name does not match manifest name (%s).",Name,Entry.Image));
|
||||
if(Entry.Timestamp>Limit) {
|
||||
Entry.Compatible = ParsedContent->get("compatible").toString();
|
||||
Entry.Revision = ParsedContent->get("revision").toString();
|
||||
Entry.Image = ParsedContent->get("image").toString();
|
||||
auto FullNme = Name + "-upgrade.bin";
|
||||
if(FullNme!=Entry.Image) {
|
||||
Logger_.error(Poco::format("MANIFEST(%s): Image name does not match manifest name (%s).",Name,Entry.Image));
|
||||
Entry.Valid = false;
|
||||
BadFormat++;
|
||||
continue;
|
||||
}
|
||||
Accepted++;
|
||||
Entry.Valid = true;
|
||||
} else {
|
||||
Rejected++;
|
||||
Entry.Valid = false;
|
||||
continue;
|
||||
}
|
||||
Entry.Valid = true;
|
||||
} else {
|
||||
Logger_.error(Poco::format("MANIFEST(%s): Entry does not have a valid JSON manifest.",Name));
|
||||
MissingJson++;
|
||||
Entry.Valid = false;
|
||||
}
|
||||
} catch (const Poco::Exception &E ) {
|
||||
std::cout << "Exception parsing: " << C << std::endl;
|
||||
Logger_.log(E);
|
||||
}
|
||||
}
|
||||
|
||||
Logger_.information(Poco::format("Accepted %Lu firmwares.", Accepted));
|
||||
Logger_.information(Poco::format("Rejected %Lu too old firmwares.", Rejected));
|
||||
Logger_.information(Poco::format("Rejected %Lu bad JSON.", BadFormat));
|
||||
Logger_.information(Poco::format("Rejected %Lu missing JSON.", MissingJson));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -108,6 +124,7 @@ namespace OpenWifi {
|
||||
S3Retry_ = Daemon()->ConfigGetInt("s3.retry",60);
|
||||
|
||||
DBRefresh_ = Daemon()->ConfigGetInt("firmwaredb.refresh",30*60);
|
||||
MaxAge_ = Daemon()->ConfigGetInt("firmwaredb.maxage",90) * 24 * 60 * 60;
|
||||
|
||||
AwsConfig_.enableTcpKeepAlive = true;
|
||||
AwsConfig_.enableEndpointDiscovery = true;
|
||||
|
||||
@@ -49,6 +49,7 @@ namespace OpenWifi {
|
||||
bool GetBucketObjectContent(Aws::S3::S3Client &S3Client, const std::string &ObjectName, std::string & ObjectContent);
|
||||
void CloseBucket();
|
||||
void Print(const S3BucketContent &B);
|
||||
uint64_t MaxAge() const { return MaxAge_; }
|
||||
|
||||
private:
|
||||
static ManifestCreator *instance_;
|
||||
@@ -62,6 +63,7 @@ namespace OpenWifi {
|
||||
Aws::Client::ClientConfiguration AwsConfig_{"ARILIA"};
|
||||
Aws::Auth::AWSCredentials AwsCreds_;
|
||||
uint64_t DBRefresh_ = 30 * 60;
|
||||
uint64_t MaxAge_ = 0 ;
|
||||
|
||||
ManifestCreator() noexcept:
|
||||
SubSystemServer("ManifestCreator", "MANIFEST-MGR", "manifestcreator") {
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
//
|
||||
// Created by stephane bourque on 2021-06-22.
|
||||
// License type: BSD 3-Clause License
|
||||
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
|
||||
//
|
||||
// Created by Stephane Bourque on 2021-03-04.
|
||||
// Arilia Wireless Inc.
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <boost/algorithm/string.hpp>
|
||||
|
||||
@@ -57,7 +62,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void MicroService::BusMessageReceived(const std::string &Key, const std::string & Message) {
|
||||
SubMutexGuard G(InfraMutex_);
|
||||
std::lock_guard G(InfraMutex_);
|
||||
try {
|
||||
Poco::JSON::Parser P;
|
||||
auto Object = P.parse(Message).extract<Poco::JSON::Object::Ptr>();
|
||||
@@ -128,7 +133,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
MicroServiceMetaVec MicroService::GetServices(const std::string & Type) {
|
||||
SubMutexGuard G(InfraMutex_);
|
||||
std::lock_guard G(InfraMutex_);
|
||||
|
||||
auto T = Poco::toLower(Type);
|
||||
MicroServiceMetaVec Res;
|
||||
@@ -140,7 +145,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
MicroServiceMetaVec MicroService::GetServices() {
|
||||
SubMutexGuard G(InfraMutex_);
|
||||
std::lock_guard G(InfraMutex_);
|
||||
|
||||
MicroServiceMetaVec Res;
|
||||
for(const auto &[Id,ServiceRec]:Services_) {
|
||||
@@ -149,6 +154,42 @@ namespace OpenWifi {
|
||||
return Res;
|
||||
}
|
||||
|
||||
void MicroService::LoadConfigurationFile() {
|
||||
std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR,".");
|
||||
Poco::Path ConfigFile;
|
||||
|
||||
ConfigFile = ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : 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;
|
||||
std::exit(Poco::Util::Application::EXIT_CONFIG);
|
||||
}
|
||||
|
||||
loadConfiguration(ConfigFile.toString());
|
||||
}
|
||||
|
||||
void MicroService::Reload() {
|
||||
LoadConfigurationFile();
|
||||
LoadMyConfig();
|
||||
}
|
||||
|
||||
void MicroService::LoadMyConfig() {
|
||||
std::string KeyFile = ConfigPath("openwifi.service.key");
|
||||
std::string KeyFilePassword = ConfigPath("openwifi.service.key.password" , "" );
|
||||
AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword));
|
||||
Cipher_ = CipherFactory_.createCipher(*AppKey_);
|
||||
ID_ = Utils::GetSystemId();
|
||||
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");
|
||||
MyHash_ = CreateHash(MyPublicEndPoint_);
|
||||
}
|
||||
|
||||
void MicroService::initialize(Poco::Util::Application &self) {
|
||||
// add the default services
|
||||
SubSystems_.push_back(KafkaManager());
|
||||
@@ -159,22 +200,10 @@ namespace OpenWifi {
|
||||
Poco::Net::HTTPSStreamFactory::registerFactory();
|
||||
Poco::Net::FTPStreamFactory::registerFactory();
|
||||
Poco::Net::FTPSStreamFactory::registerFactory();
|
||||
std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR,".");
|
||||
Poco::Path ConfigFile;
|
||||
|
||||
ConfigFile = ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_;
|
||||
LoadConfigurationFile();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
static const char * LogFilePathKey = "logging.channels.c2.path";
|
||||
|
||||
loadConfiguration(ConfigFile.toString());
|
||||
static const char * LogFilePathKey = "logging.channels.c2.path";
|
||||
|
||||
if(LogDir_.empty()) {
|
||||
std::string OriginalLogFileValue = ConfigPath(LogFilePathKey);
|
||||
@@ -182,7 +211,8 @@ namespace OpenWifi {
|
||||
} else {
|
||||
config().setString(LogFilePathKey, LogDir_);
|
||||
}
|
||||
Poco::File DataDir(ConfigPath("ucentral.system.data"));
|
||||
|
||||
Poco::File DataDir(ConfigPath("openwifi.system.data"));
|
||||
DataDir_ = DataDir.path();
|
||||
if(!DataDir.exists()) {
|
||||
try {
|
||||
@@ -191,17 +221,9 @@ namespace OpenWifi {
|
||||
logger().log(E);
|
||||
}
|
||||
}
|
||||
std::string KeyFile = ConfigPath("ucentral.service.key");
|
||||
std::string KeyFilePassword = ConfigPath("ucentral.service.key.password" , "" );
|
||||
AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword));
|
||||
Cipher_ = CipherFactory_.createCipher(*AppKey_);
|
||||
ID_ = Utils::GetSystemId();
|
||||
if(!DebugMode_)
|
||||
DebugMode_ = ConfigGetBool("ucentral.system.debug",false);
|
||||
MyPrivateEndPoint_ = ConfigGetString("ucentral.system.uri.private");
|
||||
MyPublicEndPoint_ = ConfigGetString("ucentral.system.uri.public");
|
||||
UIURI_ = ConfigGetString("ucentral.system.uri.ui");
|
||||
MyHash_ = CreateHash(MyPublicEndPoint_);
|
||||
|
||||
LoadMyConfig();
|
||||
|
||||
InitializeSubSystemServers();
|
||||
ServerApplication::initialize(self);
|
||||
|
||||
@@ -336,14 +358,23 @@ namespace OpenWifi {
|
||||
return false;
|
||||
}
|
||||
|
||||
void MicroService::Reload(const std::string &Sub) {
|
||||
for (auto i : SubSystems_) {
|
||||
if (Poco::toLower(Sub) == Poco::toLower(i->Name())) {
|
||||
i->reinitialize(Poco::Util::Application::instance());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Types::StringVec MicroService::GetSubSystems() const {
|
||||
Types::StringVec Result;
|
||||
for(auto i:SubSystems_)
|
||||
Result.push_back(i->Name());
|
||||
Result.push_back(Poco::toLower(i->Name()));
|
||||
return Result;
|
||||
}
|
||||
|
||||
Types::StringPairVec MicroService::GetLogLevels() const {
|
||||
Types::StringPairVec MicroService::GetLogLevels() {
|
||||
Types::StringPairVec Result;
|
||||
|
||||
for(auto &i:SubSystems_) {
|
||||
@@ -353,7 +384,7 @@ namespace OpenWifi {
|
||||
return Result;
|
||||
}
|
||||
|
||||
const Types::StringVec & MicroService::GetLogLevelNames() const {
|
||||
const Types::StringVec & MicroService::GetLogLevelNames() {
|
||||
static Types::StringVec LevelNames{"none", "fatal", "critical", "error", "warning", "notice", "information", "debug", "trace" };
|
||||
return LevelNames;
|
||||
}
|
||||
@@ -427,7 +458,7 @@ namespace OpenWifi {
|
||||
Poco::Thread::trySleep((unsigned long)Daemon()->DaemonBusTimer());
|
||||
if(!Running_)
|
||||
break;
|
||||
auto Msg = Daemon()->MakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE);
|
||||
Msg = Daemon()->MakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE);
|
||||
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,Daemon()->PrivateEndPoint(),Msg, false);
|
||||
}
|
||||
Msg = Daemon()->MakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_LEAVE);
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
//
|
||||
// Created by stephane bourque on 2021-06-22.
|
||||
// License type: BSD 3-Clause License
|
||||
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
|
||||
//
|
||||
// Created by Stephane Bourque on 2021-03-04.
|
||||
// Arilia Wireless Inc.
|
||||
//
|
||||
|
||||
#ifndef UCENTRALGW_MICROSERVICE_H
|
||||
@@ -29,11 +33,12 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
static const std::string uSERVICE_SECURITY{"ucentralsec"};
|
||||
static const std::string uSERVICE_GATEWAY{"ucentralgw"};
|
||||
static const std::string uSERVICE_FIRMWARE{ "ucentralfms"};
|
||||
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"};
|
||||
|
||||
class MyErrorHandler : public Poco::ErrorHandler {
|
||||
public:
|
||||
@@ -82,9 +87,6 @@ namespace OpenWifi {
|
||||
DAEMON_APP_NAME(std::move(AppName)),
|
||||
DAEMON_BUS_TIMER(BusTimer),
|
||||
SubSystems_(std::move(Subsystems)) {
|
||||
std::string V{APP_VERSION};
|
||||
std::string B{BUILD_NUMBER};
|
||||
Version_ = V + "(" + B + ")";
|
||||
}
|
||||
|
||||
int main(const ArgVec &args) override;
|
||||
@@ -111,8 +113,8 @@ namespace OpenWifi {
|
||||
[[nodiscard]] bool Debug() const { return DebugMode_; }
|
||||
[[nodiscard]] uint64_t ID() const { return ID_; }
|
||||
[[nodiscard]] Types::StringVec GetSubSystems() const;
|
||||
[[nodiscard]] Types::StringPairVec GetLogLevels() const;
|
||||
[[nodiscard]] const Types::StringVec & GetLogLevelNames() const;
|
||||
[[nodiscard]] Types::StringPairVec GetLogLevels() ;
|
||||
[[nodiscard]] static const Types::StringVec & GetLogLevelNames();
|
||||
[[nodiscard]] std::string ConfigGetString(const std::string &Key,const std::string & Default);
|
||||
[[nodiscard]] std::string ConfigGetString(const std::string &Key);
|
||||
[[nodiscard]] std::string ConfigPath(const std::string &Key,const std::string & Default);
|
||||
@@ -129,6 +131,7 @@ namespace OpenWifi {
|
||||
[[nodiscard]] std::string PrivateEndPoint() const { return MyPrivateEndPoint_; };
|
||||
[[nodiscard]] std::string PublicEndPoint() const { return MyPublicEndPoint_; };
|
||||
[[nodiscard]] std::string MakeSystemEventMessage( const std::string & Type ) const ;
|
||||
[[nodiscard]] const Types::SubSystemVec & GetFullSubSystems() { return SubSystems_; }
|
||||
inline uint64_t DaemonBusTimer() const { return DAEMON_BUS_TIMER; };
|
||||
|
||||
void BusMessageReceived( const std::string & Key, const std::string & Message);
|
||||
@@ -136,11 +139,17 @@ namespace OpenWifi {
|
||||
[[nodiscard]] MicroServiceMetaVec GetServices();
|
||||
[[nodiscard]] bool IsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request);
|
||||
|
||||
void SavePID();
|
||||
inline uint64_t GetPID() { return Poco::Process::id(); };
|
||||
[[nodiscard]] inline const std::string GetPublicAPIEndPoint() const { return MyPublicEndPoint_ + "/api/v1"; };
|
||||
static void SavePID();
|
||||
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_;};
|
||||
|
||||
void Reload(const std::string &Name); // reload a subsystem
|
||||
void Reload(); // reload the daemon itself
|
||||
void LoadMyConfig();
|
||||
|
||||
void LoadConfigurationFile();
|
||||
|
||||
private:
|
||||
bool HelpRequested_ = false;
|
||||
std::string LogDir_;
|
||||
@@ -159,9 +168,9 @@ namespace OpenWifi {
|
||||
std::string MyPrivateEndPoint_;
|
||||
std::string MyPublicEndPoint_;
|
||||
std::string UIURI_;
|
||||
std::string Version_;
|
||||
std::string Version_{std::string(APP_VERSION) + "("+ BUILD_NUMBER + ")"};
|
||||
BusEventManager BusEventManager_;
|
||||
SubMutex InfraMutex_;
|
||||
std::mutex InfraMutex_;
|
||||
|
||||
std::string DAEMON_PROPERTIES_FILENAME;
|
||||
std::string DAEMON_ROOT_ENV_VAR;
|
||||
|
||||
@@ -36,63 +36,68 @@ namespace OpenWifi {
|
||||
|
||||
Types::StringPair S;
|
||||
{
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
S = NewConnections_.front();
|
||||
NewConnections_.pop();
|
||||
}
|
||||
auto SerialNumber = S.first;
|
||||
Poco::JSON::Parser Parser;
|
||||
auto Object = Parser.parse(S.second).extract<Poco::JSON::Object::Ptr>();
|
||||
|
||||
std::string EndPoint;
|
||||
try {
|
||||
auto SerialNumber = S.first;
|
||||
Poco::JSON::Parser Parser;
|
||||
auto Object = Parser.parse(S.second).extract<Poco::JSON::Object::Ptr>();
|
||||
|
||||
if(Object->has(uCentralProtocol::SYSTEM)) {
|
||||
auto SystemObj = Object->getObject(uCentralProtocol::SYSTEM);
|
||||
if(SystemObj->has(uCentralProtocol::HOST))
|
||||
EndPoint = SystemObj->get(uCentralProtocol::HOST).toString();
|
||||
}
|
||||
std::string EndPoint;
|
||||
|
||||
if(Object->has(uCentralProtocol::PAYLOAD)) {
|
||||
auto PayloadObj = Object->getObject(uCentralProtocol::PAYLOAD);
|
||||
if(PayloadObj->has(uCentralProtocol::CAPABILITIES)) {
|
||||
// std::cout << "CAPABILITIES:" << SerialNumber << std::endl;
|
||||
auto CapObj = PayloadObj->getObject(uCentralProtocol::CAPABILITIES);
|
||||
if(CapObj->has(uCentralProtocol::COMPATIBLE)) {
|
||||
auto DeviceType = CapObj->get(uCentralProtocol::COMPATIBLE).toString();
|
||||
auto Serial = PayloadObj->get(uCentralProtocol::SERIAL).toString();
|
||||
auto Revision = Storage::TrimRevision(PayloadObj->get(uCentralProtocol::FIRMWARE).toString());
|
||||
// std::cout << "ConnectionEvent: SerialNumber: " << SerialNumber << " DeviceType: " << DeviceType << " Revision:" << Revision << std::endl;
|
||||
FMSObjects::FirmwareAgeDetails FA;
|
||||
if(Storage()->ComputeFirmwareAge(DeviceType, Revision, FA)) {
|
||||
Storage()->SetDeviceRevision(SerialNumber, Revision, DeviceType, EndPoint);
|
||||
if(FA.age)
|
||||
Logger_.information(Poco::format("Device %s connection. Firmware is %s older than latest",SerialNumber, Utils::SecondsToNiceText(FA.age)));
|
||||
else
|
||||
Logger_.information(Poco::format("Device %s connection. Firmware age cannot be determined",SerialNumber));
|
||||
if(Object->has(uCentralProtocol::SYSTEM)) {
|
||||
auto SystemObj = Object->getObject(uCentralProtocol::SYSTEM);
|
||||
if(SystemObj->has(uCentralProtocol::HOST))
|
||||
EndPoint = SystemObj->get(uCentralProtocol::HOST).toString();
|
||||
}
|
||||
|
||||
if(Object->has(uCentralProtocol::PAYLOAD)) {
|
||||
auto PayloadObj = Object->getObject(uCentralProtocol::PAYLOAD);
|
||||
if(PayloadObj->has(uCentralProtocol::CAPABILITIES)) {
|
||||
// std::cout << "CAPABILITIES:" << SerialNumber << std::endl;
|
||||
auto CapObj = PayloadObj->getObject(uCentralProtocol::CAPABILITIES);
|
||||
if(CapObj->has(uCentralProtocol::COMPATIBLE)) {
|
||||
auto DeviceType = CapObj->get(uCentralProtocol::COMPATIBLE).toString();
|
||||
auto Serial = PayloadObj->get(uCentralProtocol::SERIAL).toString();
|
||||
auto Revision = Storage::TrimRevision(PayloadObj->get(uCentralProtocol::FIRMWARE).toString());
|
||||
// std::cout << "ConnectionEvent: SerialNumber: " << SerialNumber << " DeviceType: " << DeviceType << " Revision:" << Revision << std::endl;
|
||||
FMSObjects::FirmwareAgeDetails FA;
|
||||
if(Storage()->ComputeFirmwareAge(DeviceType, Revision, FA)) {
|
||||
Storage()->SetDeviceRevision(SerialNumber, Revision, DeviceType, EndPoint);
|
||||
if(FA.age)
|
||||
Logger_.information(Poco::format("Device %s connection. Firmware is %s older than latest",SerialNumber, Utils::SecondsToNiceText(FA.age)));
|
||||
else
|
||||
Logger_.information(Poco::format("Device %s connection. Firmware age cannot be determined",SerialNumber));
|
||||
}
|
||||
DeviceCache()->AddToCache(Serial, DeviceType, EndPoint, Revision);
|
||||
}
|
||||
DeviceCache()->AddToCache(Serial, DeviceType, EndPoint, Revision);
|
||||
}
|
||||
} else if(PayloadObj->has(uCentralProtocol::DISCONNECTION)) {
|
||||
auto DisconnectMessage = PayloadObj->getObject(uCentralProtocol::DISCONNECTION);
|
||||
if(DisconnectMessage->has(uCentralProtocol::SERIALNUMBER) && DisconnectMessage->has(uCentralProtocol::TIMESTAMP)) {
|
||||
auto SNum = DisconnectMessage->get(uCentralProtocol::SERIALNUMBER).toString();
|
||||
auto Timestamp = DisconnectMessage->get(uCentralProtocol::TIMESTAMP);
|
||||
Storage()->SetDeviceDisconnected(SNum,EndPoint);
|
||||
// std::cout << "DISCONNECTION:" << SerialNumber << std::endl;
|
||||
}
|
||||
} else if(PayloadObj->has(uCentralProtocol::PING)) {
|
||||
// std::cout << "PING:" << SerialNumber << std::endl;
|
||||
auto PingMessage = PayloadObj->getObject(uCentralProtocol::PING);
|
||||
if( PingMessage->has(uCentralProtocol::FIRMWARE) &&
|
||||
} else if(PayloadObj->has(uCentralProtocol::DISCONNECTION)) {
|
||||
auto DisconnectMessage = PayloadObj->getObject(uCentralProtocol::DISCONNECTION);
|
||||
if(DisconnectMessage->has(uCentralProtocol::SERIALNUMBER) && DisconnectMessage->has(uCentralProtocol::TIMESTAMP)) {
|
||||
auto SNum = DisconnectMessage->get(uCentralProtocol::SERIALNUMBER).toString();
|
||||
auto Timestamp = DisconnectMessage->get(uCentralProtocol::TIMESTAMP);
|
||||
Storage()->SetDeviceDisconnected(SNum,EndPoint);
|
||||
// std::cout << "DISCONNECTION:" << SerialNumber << std::endl;
|
||||
}
|
||||
} else if(PayloadObj->has(uCentralProtocol::PING)) {
|
||||
// std::cout << "PING:" << SerialNumber << std::endl;
|
||||
auto PingMessage = PayloadObj->getObject(uCentralProtocol::PING);
|
||||
if( PingMessage->has(uCentralProtocol::FIRMWARE) &&
|
||||
PingMessage->has(uCentralProtocol::SERIALNUMBER) &&
|
||||
PingMessage->has(uCentralProtocol::COMPATIBLE)) {
|
||||
auto Revision = Storage::TrimRevision(PingMessage->get(uCentralProtocol::FIRMWARE).toString());
|
||||
auto Serial = PingMessage->get( uCentralProtocol::SERIALNUMBER).toString();
|
||||
auto DeviceType = PingMessage->get( uCentralProtocol::COMPATIBLE).toString();
|
||||
Storage()->SetDeviceRevision(Serial, Revision, DeviceType, EndPoint);
|
||||
DeviceCache()->AddToCache(Serial, DeviceType, EndPoint, Revision);
|
||||
auto Revision = Storage::TrimRevision(PingMessage->get(uCentralProtocol::FIRMWARE).toString());
|
||||
auto Serial = PingMessage->get( uCentralProtocol::SERIALNUMBER).toString();
|
||||
auto DeviceType = PingMessage->get( uCentralProtocol::COMPATIBLE).toString();
|
||||
Storage()->SetDeviceRevision(Serial, Revision, DeviceType, EndPoint);
|
||||
DeviceCache()->AddToCache(Serial, DeviceType, EndPoint, Revision);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,7 +123,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void NewConnectionHandler::ConnectionReceived( const std::string & Key, const std::string & Message) {
|
||||
SubMutexGuard G(Mutex_);
|
||||
std::lock_guard G(Mutex_);
|
||||
NewConnections_.push(std::make_pair(Key,Message));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
//
|
||||
// Created by stephane bourque on 2021-06-13.
|
||||
// License type: BSD 3-Clause License
|
||||
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
|
||||
//
|
||||
// Created by Stephane Bourque on 2021-03-04.
|
||||
// Arilia Wireless Inc.
|
||||
//
|
||||
|
||||
#ifndef UCENTRALGW_UCENTRALTYPES_H
|
||||
@@ -16,6 +20,8 @@
|
||||
#include <queue>
|
||||
|
||||
#include "Poco/StringTokenizer.h"
|
||||
#include "Poco/JSON/Parser.h"
|
||||
#include "Poco/JSON/Stringifier.h"
|
||||
|
||||
namespace OpenWifi::Types {
|
||||
typedef std::pair<std::string,std::string> StringPair;
|
||||
@@ -42,26 +48,58 @@ namespace OpenWifi::Types {
|
||||
}
|
||||
|
||||
inline std::string to_string( const StringVec &V) {
|
||||
std::string Result;
|
||||
|
||||
bool first=true;
|
||||
Poco::JSON::Array O;
|
||||
for(const auto &i:V) {
|
||||
if(first) {
|
||||
Result += i;
|
||||
first = false;
|
||||
} else {
|
||||
Result += ",";
|
||||
Result += i;
|
||||
}
|
||||
O.add(i);
|
||||
}
|
||||
std::stringstream SS;
|
||||
Poco::JSON::Stringifier::stringify(O,SS);
|
||||
return SS.str();
|
||||
}
|
||||
|
||||
inline std::string to_string( const StringPairVec &V) {
|
||||
Poco::JSON::Array O;
|
||||
for(const auto &i:V) {
|
||||
Poco::JSON::Array OO;
|
||||
OO.add(i.first);
|
||||
OO.add(i.second);
|
||||
O.add(OO);
|
||||
}
|
||||
|
||||
std::stringstream SS;
|
||||
Poco::JSON::Stringifier::stringify(O,SS);
|
||||
return SS.str();
|
||||
}
|
||||
|
||||
inline void from_string(const std::string &S, StringPairVec &V) {
|
||||
try {
|
||||
Poco::JSON::Parser P;
|
||||
auto O = P.parse(S).extract<Poco::JSON::Array::Ptr>();
|
||||
|
||||
for(const auto &i:*O) {
|
||||
auto Inner = i.extract<Poco::JSON::Array::Ptr>();
|
||||
for(const auto &j:*Inner) {
|
||||
auto S1 = i[0].toString();
|
||||
auto S2 = i[1].toString();
|
||||
V.push_back(std::make_pair(S1,S2));
|
||||
}
|
||||
}
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
inline void from_string(const std::string &S, StringVec &V) {
|
||||
Poco::StringTokenizer Tokens(S,",",Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);
|
||||
try {
|
||||
Poco::JSON::Parser P;
|
||||
auto O = P.parse(S).extract<Poco::JSON::Array::Ptr>();
|
||||
|
||||
for(auto const &i:Tokens)
|
||||
V.emplace_back(i);
|
||||
for(auto const &i:*O) {
|
||||
V.push_back(i.toString());
|
||||
}
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
5
src/RESTAPI_GenericServer.cpp
Normal file
5
src/RESTAPI_GenericServer.cpp
Normal file
@@ -0,0 +1,5 @@
|
||||
//
|
||||
// Created by stephane bourque on 2021-09-15.
|
||||
//
|
||||
|
||||
#include "RESTAPI_GenericServer.h"
|
||||
78
src/RESTAPI_GenericServer.h
Normal file
78
src/RESTAPI_GenericServer.h
Normal file
@@ -0,0 +1,78 @@
|
||||
//
|
||||
// Created by stephane bourque on 2021-09-15.
|
||||
//
|
||||
|
||||
#ifndef OWPROV_RESTAPI_GENERICSERVER_H
|
||||
#define OWPROV_RESTAPI_GENERICSERVER_H
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
#include "Daemon.h"
|
||||
#include "Poco/StringTokenizer.h"
|
||||
#include "Poco/Net/HTTPRequest.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class RESTAPI_GenericServer {
|
||||
public:
|
||||
|
||||
enum {
|
||||
LOG_GET=0,
|
||||
LOG_DELETE,
|
||||
LOG_PUT,
|
||||
LOG_POST
|
||||
};
|
||||
|
||||
void inline SetFlags(bool External, const std::string &Methods) {
|
||||
Poco::StringTokenizer Tokens(Methods,",");
|
||||
auto Offset = (External ? 0 : 4);
|
||||
for(const auto &i:Tokens) {
|
||||
if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_DELETE)==0)
|
||||
LogFlags_[Offset+LOG_DELETE]=true;
|
||||
else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_PUT)==0)
|
||||
LogFlags_[Offset+LOG_PUT]=true;
|
||||
else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_POST)==0)
|
||||
LogFlags_[Offset+LOG_POST]=true;
|
||||
else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_GET)==0)
|
||||
LogFlags_[Offset+LOG_GET]=true;
|
||||
}
|
||||
}
|
||||
inline void InitLogging() {
|
||||
std::string Public = Daemon()->ConfigGetString("apilogging.public.methods","PUT,POST,DELETE");
|
||||
SetFlags(true, Public);
|
||||
std::string Private = Daemon()->ConfigGetString("apilogging.private.methods","PUT,POST,DELETE");
|
||||
SetFlags(false, Private);
|
||||
|
||||
std::string PublicBadTokens = Daemon()->ConfigGetString("apilogging.public.badtokens.methods","");
|
||||
LogBadTokens_[0] = (Poco::icompare(PublicBadTokens,"true")==0);
|
||||
std::string PrivateBadTokens = Daemon()->ConfigGetString("apilogging.private.badtokens.methods","");
|
||||
LogBadTokens_[1] = (Poco::icompare(PrivateBadTokens,"true")==0);
|
||||
}
|
||||
|
||||
[[nodiscard]] inline bool LogIt(const std::string &Method, bool External) const {
|
||||
auto Offset = (External ? 0 : 4);
|
||||
if(Method == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
return LogFlags_[Offset+LOG_GET];
|
||||
if(Method == Poco::Net::HTTPRequest::HTTP_POST)
|
||||
return LogFlags_[Offset+LOG_POST];
|
||||
if(Method == Poco::Net::HTTPRequest::HTTP_PUT)
|
||||
return LogFlags_[Offset+LOG_PUT];
|
||||
if(Method == Poco::Net::HTTPRequest::HTTP_DELETE)
|
||||
return LogFlags_[Offset+LOG_DELETE];
|
||||
return false;
|
||||
};
|
||||
|
||||
[[nodiscard]] inline bool LogBadTokens(bool External) const {
|
||||
return LogBadTokens_[ (External ? 0 : 1) ];
|
||||
};
|
||||
|
||||
private:
|
||||
std::array<bool,8> LogFlags_{false};
|
||||
std::array<bool,2> LogBadTokens_{false};
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
|
||||
#endif //OWPROV_RESTAPI_GENERICSERVER_H
|
||||
@@ -18,12 +18,13 @@ namespace OpenWifi {
|
||||
|
||||
class RESTAPI_InternalServer *RESTAPI_InternalServer::instance_ = nullptr;
|
||||
|
||||
RESTAPI_InternalServer::RESTAPI_InternalServer() noexcept: SubSystemServer("RESTAPIInternalServer", "REST-ISRV", "ucentral.internal.restapi")
|
||||
RESTAPI_InternalServer::RESTAPI_InternalServer() noexcept: SubSystemServer("RESTAPIInternalServer", "REST-ISRV", "openwifi.internal.restapi")
|
||||
{
|
||||
}
|
||||
|
||||
int RESTAPI_InternalServer::Start() {
|
||||
Logger_.information("Starting.");
|
||||
Server_.InitLogging();
|
||||
|
||||
for(const auto & Svr: ConfigServersList_) {
|
||||
Logger_.information(Poco::format("Starting: %s:%s Keyfile:%s CertFile: %s", Svr.Address(), std::to_string(Svr.Port()),
|
||||
@@ -39,7 +40,7 @@ namespace OpenWifi {
|
||||
Params->setMaxQueued(200);
|
||||
Params->setKeepAlive(true);
|
||||
|
||||
auto NewServer = std::make_unique<Poco::Net::HTTPServer>(new InternalRequestHandlerFactory, Pool_, Sock, Params);
|
||||
auto NewServer = std::make_unique<Poco::Net::HTTPServer>(new InternalRequestHandlerFactory(Server_), Pool_, Sock, Params);
|
||||
NewServer->start();
|
||||
RESTServers_.push_back(std::move(NewServer));
|
||||
}
|
||||
@@ -51,14 +52,17 @@ namespace OpenWifi {
|
||||
Logger_.information("Stopping ");
|
||||
for( const auto & svr : RESTServers_ )
|
||||
svr->stop();
|
||||
RESTServers_.clear();
|
||||
}
|
||||
|
||||
void RESTAPI_InternalServer::reinitialize(Poco::Util::Application &self) {
|
||||
Daemon()->LoadConfigurationFile();
|
||||
Logger_.information("Reinitializing.");
|
||||
Stop();
|
||||
Start();
|
||||
}
|
||||
|
||||
Poco::Net::HTTPRequestHandler *InternalRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest & Request) {
|
||||
|
||||
Logger_.debug(
|
||||
Poco::format("REQUEST(%s): %s %s", Utils::FormatIPv6(Request.clientAddress().toString()),
|
||||
Request.getMethod(), Request.getURI()));
|
||||
|
||||
Poco::URI uri(Request.getURI());
|
||||
const auto &Path = uri.getPath();
|
||||
RESTAPIHandler::BindingMap Bindings;
|
||||
@@ -69,7 +73,7 @@ namespace OpenWifi {
|
||||
RESTAPI_system_command,
|
||||
RESTAPI_connectedDevicesHandler,
|
||||
RESTAPI_connectedDeviceHandler
|
||||
>(Path, Bindings, Logger_);
|
||||
>(Path, Bindings, Logger_, Server_);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
#include "Poco/Net/HTTPRequestHandlerFactory.h"
|
||||
#include "Poco/Net/HTTPServerRequest.h"
|
||||
#include "Poco/Net/NetException.h"
|
||||
#include "RESTAPI_GenericServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
@@ -28,23 +29,27 @@ namespace OpenWifi {
|
||||
|
||||
int Start() override;
|
||||
void Stop() override;
|
||||
void reinitialize(Poco::Util::Application &self) override;
|
||||
|
||||
private:
|
||||
static RESTAPI_InternalServer *instance_;
|
||||
std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_;
|
||||
Poco::ThreadPool Pool_;
|
||||
Poco::ThreadPool Pool_;
|
||||
RESTAPI_GenericServer Server_;
|
||||
};
|
||||
|
||||
inline RESTAPI_InternalServer * RESTAPI_InternalServer() { return RESTAPI_InternalServer::instance(); };
|
||||
|
||||
class InternalRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
|
||||
public:
|
||||
InternalRequestHandlerFactory() :
|
||||
Logger_(RESTAPI_InternalServer()->Logger()){}
|
||||
InternalRequestHandlerFactory(RESTAPI_GenericServer & Server) :
|
||||
Logger_(RESTAPI_InternalServer()->Logger()),
|
||||
Server_(Server){}
|
||||
|
||||
Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &request) override;
|
||||
private:
|
||||
Poco::Logger & Logger_;
|
||||
RESTAPI_GenericServer &Server_;
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -160,7 +160,7 @@ namespace OpenWifi::SecurityObjects {
|
||||
typedef std::vector<ProfileAction> ProfileActionVec;
|
||||
|
||||
struct SecurityProfile {
|
||||
uint64_t id;
|
||||
uint64_t id=0;
|
||||
std::string name;
|
||||
std::string description;
|
||||
ProfileActionVec policy;
|
||||
|
||||
@@ -6,43 +6,25 @@
|
||||
#include "RESTAPI_FMSObjects.h"
|
||||
#include "StorageService.h"
|
||||
#include "RESTAPI_protocol.h"
|
||||
#include "RESTAPI_errors.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_connectedDeviceHandler::handleRequest(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
if (!ContinueProcessing(Request, Response))
|
||||
return;
|
||||
if (!IsAuthorized(Request, Response))
|
||||
return;
|
||||
if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
DoGet(Request, Response);
|
||||
else
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
|
||||
void RESTAPI_connectedDeviceHandler::DoGet(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
auto SerialNumber = GetBinding(RESTAPI::Protocol::SERIALNUMBER,"");
|
||||
void RESTAPI_connectedDeviceHandler::DoGet() {
|
||||
auto SerialNumber = GetBinding(RESTAPI::Protocol::SERIALNUMBER,"");
|
||||
|
||||
if(SerialNumber.empty()) {
|
||||
BadRequest(Request, Response, "SerialNumber must be specified.");
|
||||
return;
|
||||
}
|
||||
|
||||
FMSObjects::DeviceConnectionInformation DevInfo;
|
||||
if(Storage()->GetDevice(SerialNumber, DevInfo)) {
|
||||
Poco::JSON::Object Answer;
|
||||
DevInfo.to_json(Answer);
|
||||
ReturnObject(Request, Answer, Response);
|
||||
return;
|
||||
}
|
||||
NotFound(Request, Response);
|
||||
if(SerialNumber.empty()) {
|
||||
BadRequest(RESTAPI::Errors::MissingSerialNumber);
|
||||
return;
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
|
||||
FMSObjects::DeviceConnectionInformation DevInfo;
|
||||
if(Storage()->GetDevice(SerialNumber, DevInfo)) {
|
||||
Poco::JSON::Object Answer;
|
||||
DevInfo.to_json(Answer);
|
||||
ReturnObject(Answer);
|
||||
return;
|
||||
}
|
||||
NotFound();
|
||||
}
|
||||
}
|
||||
@@ -10,15 +10,19 @@
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_connectedDeviceHandler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_connectedDeviceHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, bool Internal)
|
||||
RESTAPI_connectedDeviceHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>
|
||||
{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
Internal) {}
|
||||
static const std::list<const char *> PathName() { return std::list<const char *>{"/api/v1/connectedDevice/{serialNumber}"};}
|
||||
void handleRequest(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) override;
|
||||
void DoGet(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response);
|
||||
|
||||
void DoGet() final;
|
||||
void DoDelete() final {};
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -10,40 +10,21 @@
|
||||
#include "RESTAPI_protocol.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_connectedDevicesHandler::handleRequest(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
if (!ContinueProcessing(Request, Response))
|
||||
return;
|
||||
if (!IsAuthorized(Request, Response))
|
||||
return;
|
||||
ParseParameters(Request);
|
||||
if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
DoGet(Request, Response);
|
||||
else
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
|
||||
void RESTAPI_connectedDevicesHandler::DoGet(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
InitQueryBlock();
|
||||
|
||||
std::vector<FMSObjects::DeviceConnectionInformation> Devices;
|
||||
if (Storage()->GetDevices(QB_.Offset, QB_.Limit, Devices)) {
|
||||
Poco::JSON::Array AnswerArr;
|
||||
for (const auto &i:Devices) {
|
||||
Poco::JSON::Object Obj;
|
||||
i.to_json(Obj);
|
||||
AnswerArr.add(Obj);
|
||||
}
|
||||
Poco::JSON::Object AnswerObj;
|
||||
AnswerObj.set(RESTAPI::Protocol::DEVICES, AnswerArr);
|
||||
ReturnObject(Request, AnswerObj, Response);
|
||||
return;
|
||||
void RESTAPI_connectedDevicesHandler::DoGet() {
|
||||
std::vector<FMSObjects::DeviceConnectionInformation> Devices;
|
||||
Poco::JSON::Object AnswerObj;
|
||||
Poco::JSON::Array AnswerArr;
|
||||
if (Storage()->GetDevices(QB_.Offset, QB_.Limit, Devices)) {
|
||||
for (const auto &i:Devices) {
|
||||
Poco::JSON::Object Obj;
|
||||
i.to_json(Obj);
|
||||
AnswerArr.add(Obj);
|
||||
}
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
AnswerObj.set(RESTAPI::Protocol::DEVICES, AnswerArr);
|
||||
ReturnObject(AnswerObj);
|
||||
return;
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
AnswerObj.set(RESTAPI::Protocol::DEVICES, AnswerArr);
|
||||
ReturnObject(AnswerObj);
|
||||
}
|
||||
}
|
||||
@@ -11,15 +11,19 @@
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_connectedDevicesHandler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_connectedDevicesHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, bool Internal)
|
||||
RESTAPI_connectedDevicesHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>
|
||||
{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
Internal) {}
|
||||
static const std::list<const char *> PathName() { return std::list<const char *>{"/api/v1/connectedDevices"};}
|
||||
void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response) override;
|
||||
void DoGet(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response);
|
||||
void DoGet() final;
|
||||
void DoDelete() final {};
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -9,29 +9,10 @@
|
||||
#include "Daemon.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_deviceReportHandler::handleRequest(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
if (!ContinueProcessing(Request, Response))
|
||||
return;
|
||||
if (!IsAuthorized(Request, Response))
|
||||
return;
|
||||
if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
DoGet(Request, Response);
|
||||
else
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
|
||||
void RESTAPI_deviceReportHandler::DoGet(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
Daemon()->CreateDashboard();
|
||||
Poco::JSON::Object O;
|
||||
Daemon()->GetDashboard().to_json(O);
|
||||
ReturnObject(Request, O, Response);
|
||||
return;
|
||||
} catch ( const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
void RESTAPI_deviceReportHandler::DoGet() {
|
||||
Daemon()->CreateDashboard();
|
||||
Poco::JSON::Object O;
|
||||
Daemon()->GetDashboard().to_json(O);
|
||||
ReturnObject(O);
|
||||
}
|
||||
}
|
||||
@@ -10,15 +10,18 @@
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_deviceReportHandler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_deviceReportHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, bool Internal)
|
||||
RESTAPI_deviceReportHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>
|
||||
{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
Internal) {}
|
||||
static const std::list<const char *> PathName() { return std::list<const char *>{"/api/v1/deviceReport"};}
|
||||
void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response) override;
|
||||
void DoGet(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response);
|
||||
void DoGet() final;
|
||||
void DoDelete() final {};
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
55
src/RESTAPI_errors.h
Normal file
55
src/RESTAPI_errors.h
Normal file
@@ -0,0 +1,55 @@
|
||||
//
|
||||
// Created by stephane bourque on 2021-09-12.
|
||||
//
|
||||
|
||||
#ifndef OWPROV_RESTAPI_ERRORS_H
|
||||
#define OWPROV_RESTAPI_ERRORS_H
|
||||
|
||||
namespace OpenWifi::RESTAPI::Errors {
|
||||
static const std::string MissingUUID{"Missing UUID."};
|
||||
static const std::string MissingSerialNumber{"Missing Serial Number."};
|
||||
static const std::string InternalError{"Internal error. Please try later."};
|
||||
static const std::string InvalidJSONDocument{"Invalid JSON document."};
|
||||
static const std::string UnsupportedHTTPMethod{"Unsupported HTTP Method"};
|
||||
static const std::string StillInUse{"Element still in use."};
|
||||
static const std::string CouldNotBeDeleted{"Element could not be deleted."};
|
||||
static const std::string NameMustBeSet{"The name property must be set."};
|
||||
static const std::string ConfigBlockInvalid{"Configuration block type invalid."};
|
||||
static const std::string UnknownId{"Unknown management policy."};
|
||||
static const std::string InvalidDeviceTypes{"Unknown or invalid device type(s)."};
|
||||
static const std::string RecordNotCreated{"Record could not be created."};
|
||||
static const std::string RecordNotUpdated{"Record could not be updated."};
|
||||
static const std::string UnknownManagementPolicyUUID{"Unknown management policy UUID."};
|
||||
static const std::string CannotDeleteRoot{"Root Entity cannot be removed, only modified."};
|
||||
static const std::string MustCreateRootFirst{"Root entity must be created first."};
|
||||
static const std::string ParentUUIDMustExist{"Parent UUID must exist."};
|
||||
static const std::string ConfigurationMustExist{"Configuration must exist."};
|
||||
static const std::string MissingOrInvalidParameters{"Invalid or missing parameters."};
|
||||
static const std::string UnknownSerialNumber{"Unknown Serial Number."};
|
||||
static const std::string InvalidSerialNumber{"Invalid Serial Number."};
|
||||
static const std::string SerialNumberExists{"Serial Number already exists."};
|
||||
static const std::string ValidNonRootUUID{"Must be a non-root, and valid UUID."};
|
||||
static const std::string VenueMustExist{"Venue does not exist."};
|
||||
static const std::string NotBoth{"You cannot specify both Entity and Venue"};
|
||||
static const std::string EntityMustExist{"Entity must exist."};
|
||||
static const std::string ParentOrEntityMustBeSet{"Parent or Entity must be set."};
|
||||
static const std::string ContactMustExist{"Contact must exist."};
|
||||
static const std::string LocationMustExist{"Location must exist."};
|
||||
static const std::string OnlyWSSupported{"This endpoint only supports WebSocket."};
|
||||
static const std::string SerialNumberMismatch{"Serial Number mismatch."};
|
||||
static const std::string InvalidCommand{"Invalid command."};
|
||||
static const std::string NoRecordsDeleted{"No records deleted."};
|
||||
static const std::string DeviceNotConnected{"Device is not currently connected."};
|
||||
static const std::string CannotCreateWS{"Telemetry system could not create WS endpoint. Please try again."};
|
||||
static const std::string BothDeviceTypeRevision{"Both deviceType and revision must be set."};
|
||||
static const std::string IdOrSerialEmpty{"SerialNumber and Id must not be empty."};
|
||||
static const std::string MissingUserID{"Missing user ID."};
|
||||
static const std::string IdMustBe0{"To create a user, you must set the ID to 0"};
|
||||
static const std::string InvalidUserRole{"Invalid userRole."};
|
||||
static const std::string InvalidEmailAddress{"Invalid email address."};
|
||||
static const std::string InvalidPassword{"Invalid password."};
|
||||
static const std::string PasswordRejected{"Password was rejected. This maybe an old password."};
|
||||
static const std::string InvalidIPRanges{"Invalid IP range specifications."};
|
||||
}
|
||||
|
||||
#endif //OWPROV_RESTAPI_ERRORS_H
|
||||
@@ -11,77 +11,57 @@
|
||||
#include "DeviceCache.h"
|
||||
#include "uCentralProtocol.h"
|
||||
#include "RESTAPI_protocol.h"
|
||||
#include "RESTAPI_errors.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_firmwareAgeHandler::handleRequest(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
if (!ContinueProcessing(Request, Response))
|
||||
return;
|
||||
if (!IsAuthorized(Request, Response))
|
||||
return;
|
||||
ParseParameters(Request);
|
||||
if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
DoGet(Request, Response);
|
||||
else
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
|
||||
void RESTAPI_firmwareAgeHandler::DoGet(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
InitQueryBlock();
|
||||
if (!QB_.Select.empty()) {
|
||||
Poco::JSON::Array Objects;
|
||||
std::vector<std::string> Numbers = Utils::Split(QB_.Select);
|
||||
for (auto &i : Numbers) {
|
||||
DeviceCacheEntry E;
|
||||
if (DeviceCache()->GetDevice(i, E)) {
|
||||
FMSObjects::FirmwareAgeDetails FA;
|
||||
if(Storage()->ComputeFirmwareAge(E.deviceType,E.revision,FA)) {
|
||||
Poco::JSON::Object O;
|
||||
FA.to_json(O);
|
||||
O.set(uCentralProtocol::SERIALNUMBER,i);
|
||||
Objects.add(O);
|
||||
} else {
|
||||
Poco::JSON::Object O;
|
||||
O.set(uCentralProtocol::SERIALNUMBER,i);
|
||||
Objects.add(O);
|
||||
}
|
||||
void RESTAPI_firmwareAgeHandler::DoGet() {
|
||||
if (!QB_.Select.empty()) {
|
||||
Poco::JSON::Array Objects;
|
||||
std::vector<std::string> Numbers = Utils::Split(QB_.Select);
|
||||
for (auto &i : Numbers) {
|
||||
DeviceCacheEntry E;
|
||||
if (DeviceCache()->GetDevice(i, E)) {
|
||||
FMSObjects::FirmwareAgeDetails FA;
|
||||
if(Storage()->ComputeFirmwareAge(E.deviceType,E.revision,FA)) {
|
||||
Poco::JSON::Object O;
|
||||
FA.to_json(O);
|
||||
O.set(uCentralProtocol::SERIALNUMBER,i);
|
||||
Objects.add(O);
|
||||
} else {
|
||||
Poco::JSON::Object O;
|
||||
O.set(uCentralProtocol::SERIALNUMBER,i);
|
||||
Objects.add(O);
|
||||
}
|
||||
}
|
||||
Poco::JSON::Object Answer;
|
||||
Answer.set(RESTAPI::Protocol::AGES, Objects);
|
||||
ReturnObject(Request, Answer, Response);
|
||||
return;
|
||||
} else {
|
||||
auto DeviceType = GetParameter(RESTAPI::Protocol::DEVICETYPE, "");
|
||||
auto Revision = GetParameter(RESTAPI::Protocol::REVISION, "");
|
||||
|
||||
if (DeviceType.empty() || Revision.empty()) {
|
||||
BadRequest(Request, Response, "Both deviceType and revision must be set.");
|
||||
return;
|
||||
}
|
||||
|
||||
Revision = Storage::TrimRevision(Revision);
|
||||
|
||||
FMSObjects::FirmwareAgeDetails FA;
|
||||
if (Storage()->ComputeFirmwareAge(DeviceType, Revision, FA)) {
|
||||
Poco::JSON::Object Answer;
|
||||
|
||||
FA.to_json(Answer);
|
||||
ReturnObject(Request, Answer, Response);
|
||||
return;
|
||||
} else {
|
||||
NotFound(Request, Response);
|
||||
Poco::JSON::Object O;
|
||||
O.set(uCentralProtocol::SERIALNUMBER,i);
|
||||
Objects.add(O);
|
||||
}
|
||||
}
|
||||
Poco::JSON::Object Answer;
|
||||
Answer.set(RESTAPI::Protocol::AGES, Objects);
|
||||
ReturnObject(Answer);
|
||||
return;
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
} else {
|
||||
auto DeviceType = GetParameter(RESTAPI::Protocol::DEVICETYPE, "");
|
||||
auto Revision = GetParameter(RESTAPI::Protocol::REVISION, "");
|
||||
|
||||
if (DeviceType.empty() || Revision.empty()) {
|
||||
BadRequest(RESTAPI::Errors::BothDeviceTypeRevision);
|
||||
return;
|
||||
}
|
||||
|
||||
Revision = Storage::TrimRevision(Revision);
|
||||
|
||||
FMSObjects::FirmwareAgeDetails FA;
|
||||
if (Storage()->ComputeFirmwareAge(DeviceType, Revision, FA)) {
|
||||
Poco::JSON::Object Answer;
|
||||
|
||||
FA.to_json(Answer);
|
||||
ReturnObject(Answer);
|
||||
return;
|
||||
}
|
||||
NotFound();
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
}
|
||||
@@ -10,15 +10,18 @@
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_firmwareAgeHandler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_firmwareAgeHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, bool Internal)
|
||||
RESTAPI_firmwareAgeHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>
|
||||
{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
Internal) {}
|
||||
static const std::list<const char *> PathName() { return std::list<const char *>{"/api/v1/firmwareAge"};}
|
||||
void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response) override;
|
||||
void DoGet(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response);
|
||||
void DoGet() final;
|
||||
void DoDelete() final {};
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -10,139 +10,98 @@
|
||||
#include "uCentralProtocol.h"
|
||||
#include "RESTAPI_protocol.h"
|
||||
#include "RESTAPI_utils.h"
|
||||
#include "RESTAPI_errors.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_firmwareHandler::handleRequest(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
if (!ContinueProcessing(Request, Response))
|
||||
void
|
||||
RESTAPI_firmwareHandler::DoPost() {
|
||||
auto Obj = ParseStream();
|
||||
FMSObjects::Firmware F;
|
||||
if (!F.from_json(Obj)) {
|
||||
BadRequest(RESTAPI::Errors::InvalidJSONDocument);
|
||||
return;
|
||||
|
||||
if (!IsAuthorized(Request, Response))
|
||||
}
|
||||
F.id = Daemon()->CreateUUID();
|
||||
if(Storage()->AddFirmware(F)) {
|
||||
Poco::JSON::Object Answer;
|
||||
F.to_json(Answer);
|
||||
ReturnObject(Answer);
|
||||
return;
|
||||
|
||||
ParseParameters(Request);
|
||||
|
||||
if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
DoGet(Request, Response);
|
||||
else if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_POST)
|
||||
DoPost(Request, Response);
|
||||
else if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_PUT)
|
||||
DoPut(Request, Response);
|
||||
else if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE)
|
||||
DoDelete(Request, Response);
|
||||
else
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
BadRequest(RESTAPI::Errors::RecordNotCreated);
|
||||
}
|
||||
|
||||
void
|
||||
RESTAPI_firmwareHandler::DoPost(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
Poco::JSON::Parser IncomingParser;
|
||||
Poco::JSON::Object::Ptr Obj =
|
||||
IncomingParser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>();
|
||||
RESTAPI_firmwareHandler::DoGet() {
|
||||
auto UUID = GetBinding(uCentralProtocol::ID, "");
|
||||
|
||||
FMSObjects::Firmware F;
|
||||
if (!F.from_json(Obj)) {
|
||||
BadRequest(Request, Response);
|
||||
return;
|
||||
}
|
||||
F.id = Daemon()->CreateUUID();
|
||||
if(Storage()->AddFirmware(F)) {
|
||||
Poco::JSON::Object Answer;
|
||||
F.to_json(Answer);
|
||||
ReturnObject(Request, Answer, Response);
|
||||
return;
|
||||
}
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
|
||||
void
|
||||
RESTAPI_firmwareHandler::DoGet(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
auto UUID = GetBinding(uCentralProtocol::ID, "");
|
||||
|
||||
if (!UUID.empty()) {
|
||||
FMSObjects::Firmware F;
|
||||
if (Storage()->GetFirmware(UUID, F)) {
|
||||
Poco::JSON::Object Object;
|
||||
F.to_json(Object);
|
||||
ReturnObject(Request, Object, Response);
|
||||
} else {
|
||||
NotFound(Request, Response);
|
||||
}
|
||||
return;
|
||||
}
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
|
||||
void
|
||||
RESTAPI_firmwareHandler::DoDelete(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
auto UUID = GetBinding(uCentralProtocol::ID, "");
|
||||
|
||||
if (!UUID.empty()) {
|
||||
if (Storage()->DeleteFirmware(UUID)) {
|
||||
OK(Request, Response);
|
||||
} else {
|
||||
NotFound(Request, Response);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
|
||||
void RESTAPI_firmwareHandler::DoPut(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
|
||||
auto UUID = GetBinding(uCentralProtocol::ID, "");
|
||||
if(UUID.empty()) {
|
||||
BadRequest(Request, Response, "UUID must be included in the request");
|
||||
return;
|
||||
}
|
||||
|
||||
Poco::JSON::Parser IncomingParser;
|
||||
Poco::JSON::Object::Ptr Obj =
|
||||
IncomingParser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>();
|
||||
|
||||
FMSObjects::Firmware F;
|
||||
if(!Storage()->GetFirmware(UUID, F)) {
|
||||
NotFound(Request, Response);
|
||||
return;
|
||||
}
|
||||
|
||||
if(Obj->has(RESTAPI::Protocol::DESCRIPTION))
|
||||
F.description = Obj->get(RESTAPI::Protocol::DESCRIPTION).toString();
|
||||
if(Obj->has(RESTAPI::Protocol::NOTES)) {
|
||||
SecurityObjects::NoteInfoVec NIV;
|
||||
NIV = RESTAPI_utils::to_object_array<SecurityObjects::NoteInfo>(Obj->get(RESTAPI::Protocol::NOTES).toString());
|
||||
for(auto const &i:NIV) {
|
||||
SecurityObjects::NoteInfo ii{.created=(uint64_t)std::time(nullptr), .createdBy=UserInfo_.userinfo.email, .note=i.note};
|
||||
F.notes.push_back(ii);
|
||||
}
|
||||
}
|
||||
|
||||
if(Storage()->UpdateFirmware(UUID, F)) {
|
||||
Poco::JSON::Object Answer;
|
||||
F.to_json(Answer);
|
||||
ReturnObject(Request, Answer, Response);
|
||||
} else {
|
||||
BadRequest(Request, Response, "Could not update the firmware entry. Please review your changes.");
|
||||
}
|
||||
if(UUID.empty()) {
|
||||
BadRequest(RESTAPI::Errors::MissingUUID);
|
||||
return;
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
|
||||
FMSObjects::Firmware F;
|
||||
if (Storage()->GetFirmware(UUID, F)) {
|
||||
Poco::JSON::Object Object;
|
||||
F.to_json(Object);
|
||||
ReturnObject(Object);
|
||||
return;
|
||||
}
|
||||
NotFound();
|
||||
}
|
||||
|
||||
void
|
||||
RESTAPI_firmwareHandler::DoDelete() {
|
||||
auto UUID = GetBinding(uCentralProtocol::ID, "");
|
||||
if(UUID.empty()) {
|
||||
BadRequest(RESTAPI::Errors::MissingUUID);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Storage()->DeleteFirmware(UUID)) {
|
||||
OK();
|
||||
return;
|
||||
}
|
||||
BadRequest(RESTAPI::Errors::CouldNotBeDeleted);
|
||||
}
|
||||
|
||||
void RESTAPI_firmwareHandler::DoPut() {
|
||||
auto UUID = GetBinding(uCentralProtocol::ID, "");
|
||||
if(UUID.empty()) {
|
||||
BadRequest(RESTAPI::Errors::MissingUUID);
|
||||
return;
|
||||
}
|
||||
|
||||
FMSObjects::Firmware F;
|
||||
if(!Storage()->GetFirmware(UUID, F)) {
|
||||
NotFound();
|
||||
return;
|
||||
}
|
||||
|
||||
auto Obj = ParseStream();
|
||||
FMSObjects::Firmware NewFirmware;
|
||||
if(!NewFirmware.from_json(Obj)) {
|
||||
BadRequest(RESTAPI::Errors::InvalidJSONDocument);
|
||||
return;
|
||||
}
|
||||
|
||||
if(Obj->has(RESTAPI::Protocol::DESCRIPTION))
|
||||
F.description = Obj->get(RESTAPI::Protocol::DESCRIPTION).toString();
|
||||
if(Obj->has(RESTAPI::Protocol::NOTES)) {
|
||||
SecurityObjects::NoteInfoVec NIV;
|
||||
NIV = RESTAPI_utils::to_object_array<SecurityObjects::NoteInfo>(Obj->get(RESTAPI::Protocol::NOTES).toString());
|
||||
for(auto const &i:NIV) {
|
||||
SecurityObjects::NoteInfo ii{.created=(uint64_t)std::time(nullptr), .createdBy=UserInfo_.userinfo.email, .note=i.note};
|
||||
F.notes.push_back(ii);
|
||||
}
|
||||
}
|
||||
|
||||
if(Storage()->UpdateFirmware(UUID, F)) {
|
||||
Poco::JSON::Object Answer;
|
||||
F.to_json(Answer);
|
||||
ReturnObject(Answer);
|
||||
return;
|
||||
}
|
||||
BadRequest(RESTAPI::Errors::RecordNotUpdated);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_firmwareHandler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_firmwareHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, bool Internal)
|
||||
RESTAPI_firmwareHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>
|
||||
{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
@@ -18,13 +18,13 @@ namespace OpenWifi {
|
||||
Poco::Net::HTTPRequest::HTTP_PUT,
|
||||
Poco::Net::HTTPRequest::HTTP_DELETE,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
Internal) {}
|
||||
static const std::list<const char *> PathName() { return std::list<const char *>{"/api/v1/firmware/{id}"};}
|
||||
void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response) override;
|
||||
void DoPost(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response);
|
||||
void DoGet(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response);
|
||||
void DoDelete(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response);
|
||||
void DoPut(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response);
|
||||
void DoGet() final;
|
||||
void DoDelete() final;
|
||||
void DoPost() final;
|
||||
void DoPut() final;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -8,116 +8,95 @@
|
||||
#include "RESTAPI_protocol.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_firmwaresHandler::handleRequest(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
if (!ContinueProcessing(Request, Response))
|
||||
return;
|
||||
if (!IsAuthorized(Request, Response))
|
||||
return;
|
||||
|
||||
ParseParameters(Request);
|
||||
if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
DoGet(Request, Response);
|
||||
else
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
|
||||
void
|
||||
RESTAPI_firmwaresHandler::DoGet(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
RESTAPI_firmwaresHandler::DoGet() {
|
||||
std::string DeviceType = GetParameter(RESTAPI::Protocol::DEVICETYPE, "");
|
||||
bool IdOnly = GetBoolParameter(RESTAPI::Protocol::IDONLY, false);
|
||||
bool RevisionSet = GetBoolParameter(RESTAPI::Protocol::REVISIONSET, false);
|
||||
bool LatestOnly = GetBoolParameter(RESTAPI::Protocol::LATESTONLY, false);
|
||||
bool DeviceSet = GetBoolParameter(RESTAPI::Protocol::DEVICESET, false);
|
||||
|
||||
InitQueryBlock();
|
||||
std::string DeviceType = GetParameter(RESTAPI::Protocol::DEVICETYPE, "");
|
||||
bool IdOnly = GetBoolParameter(RESTAPI::Protocol::IDONLY, false);
|
||||
bool RevisionSet = GetBoolParameter(RESTAPI::Protocol::REVISIONSET, false);
|
||||
bool LatestOnly = GetBoolParameter(RESTAPI::Protocol::LATESTONLY, false);
|
||||
bool DeviceSet = GetBoolParameter(RESTAPI::Protocol::DEVICESET, false);
|
||||
|
||||
if(DeviceSet) {
|
||||
auto Revisions = LatestFirmwareCache()->GetDevices();
|
||||
Poco::JSON::Array ObjectArray;
|
||||
for (const auto &i:Revisions) {
|
||||
ObjectArray.add(i);
|
||||
}
|
||||
Poco::JSON::Object RetObj;
|
||||
RetObj.set(RESTAPI::Protocol::DEVICETYPES, ObjectArray);
|
||||
ReturnObject(Request, RetObj, Response);
|
||||
return;
|
||||
if(DeviceSet) {
|
||||
auto Revisions = LatestFirmwareCache()->GetDevices();
|
||||
Poco::JSON::Array ObjectArray;
|
||||
for (const auto &i:Revisions) {
|
||||
ObjectArray.add(i);
|
||||
}
|
||||
Poco::JSON::Object RetObj;
|
||||
RetObj.set(RESTAPI::Protocol::DEVICETYPES, ObjectArray);
|
||||
ReturnObject(RetObj);
|
||||
return;
|
||||
}
|
||||
|
||||
if(RevisionSet) {
|
||||
auto Revisions = LatestFirmwareCache()->GetRevisions();
|
||||
Poco::JSON::Array ObjectArray;
|
||||
for (const auto &i:Revisions) {
|
||||
ObjectArray.add(i);
|
||||
}
|
||||
Poco::JSON::Object RetObj;
|
||||
RetObj.set(RESTAPI::Protocol::REVISIONS, ObjectArray);
|
||||
ReturnObject(Request, RetObj, Response);
|
||||
return;
|
||||
if(RevisionSet) {
|
||||
auto Revisions = LatestFirmwareCache()->GetRevisions();
|
||||
Poco::JSON::Array ObjectArray;
|
||||
for (const auto &i:Revisions) {
|
||||
ObjectArray.add(i);
|
||||
}
|
||||
Poco::JSON::Object RetObj;
|
||||
RetObj.set(RESTAPI::Protocol::REVISIONS, ObjectArray);
|
||||
ReturnObject(RetObj);
|
||||
return;
|
||||
}
|
||||
|
||||
// special cases: if latestOnly and deviceType
|
||||
if(!DeviceType.empty()) {
|
||||
if(LatestOnly) {
|
||||
LatestFirmwareCacheEntry Entry;
|
||||
if(!LatestFirmwareCache()->FindLatestFirmware(DeviceType,Entry)) {
|
||||
NotFound(Request, Response);
|
||||
return;
|
||||
}
|
||||
// special cases: if latestOnly and deviceType
|
||||
if(!DeviceType.empty()) {
|
||||
if(LatestOnly) {
|
||||
LatestFirmwareCacheEntry Entry;
|
||||
if(!LatestFirmwareCache()->FindLatestFirmware(DeviceType,Entry)) {
|
||||
NotFound();
|
||||
return;
|
||||
}
|
||||
|
||||
FMSObjects::Firmware F;
|
||||
if(Storage()->GetFirmware(Entry.Id,F)) {
|
||||
Poco::JSON::Object Answer;
|
||||
F.to_json(Answer);
|
||||
ReturnObject(Request, Answer, Response);
|
||||
return;
|
||||
FMSObjects::Firmware F;
|
||||
if(Storage()->GetFirmware(Entry.Id,F)) {
|
||||
Poco::JSON::Object Answer;
|
||||
F.to_json(Answer);
|
||||
ReturnObject(Answer);
|
||||
return;
|
||||
}
|
||||
NotFound();
|
||||
return;
|
||||
} else {
|
||||
std::vector<FMSObjects::Firmware> List;
|
||||
if (Storage()->GetFirmwares(QB_.Offset, QB_.Limit, DeviceType, List)) {
|
||||
Poco::JSON::Array ObjectArray;
|
||||
for (const auto &i:List) {
|
||||
if(IdOnly) {
|
||||
ObjectArray.add(i.id);
|
||||
} else {
|
||||
Poco::JSON::Object Obj;
|
||||
i.to_json(Obj);
|
||||
ObjectArray.add(Obj);
|
||||
}
|
||||
}
|
||||
NotFound(Request, Response);
|
||||
Poco::JSON::Object RetObj;
|
||||
RetObj.set(RESTAPI::Protocol::FIRMWARES, ObjectArray);
|
||||
ReturnObject(RetObj);
|
||||
return;
|
||||
} else {
|
||||
std::vector<FMSObjects::Firmware> List;
|
||||
if (Storage()->GetFirmwares(QB_.Offset, QB_.Limit, DeviceType, List)) {
|
||||
Poco::JSON::Array ObjectArray;
|
||||
for (const auto &i:List) {
|
||||
if(IdOnly) {
|
||||
ObjectArray.add(i.id);
|
||||
} else {
|
||||
Poco::JSON::Object Obj;
|
||||
i.to_json(Obj);
|
||||
ObjectArray.add(Obj);
|
||||
}
|
||||
}
|
||||
Poco::JSON::Object RetObj;
|
||||
RetObj.set(RESTAPI::Protocol::FIRMWARES, ObjectArray);
|
||||
ReturnObject(Request, RetObj, Response);
|
||||
return;
|
||||
} else {
|
||||
NotFound(Request, Response);
|
||||
return;
|
||||
}
|
||||
NotFound();
|
||||
return;
|
||||
}
|
||||
}
|
||||
std::vector<FMSObjects::Firmware> List;
|
||||
if (Storage()->GetFirmwares(QB_.Offset, QB_.Limit, DeviceType, List)) {
|
||||
Poco::JSON::Array ObjectArray;
|
||||
for (const auto &i:List) {
|
||||
if(IdOnly) {
|
||||
ObjectArray.add(i.id);
|
||||
} else {
|
||||
Poco::JSON::Object Obj;
|
||||
i.to_json(Obj);
|
||||
ObjectArray.add(Obj);
|
||||
}
|
||||
}
|
||||
Poco::JSON::Object RetObj;
|
||||
RetObj.set(RESTAPI::Protocol::FIRMWARES, ObjectArray);
|
||||
ReturnObject(Request, RetObj, Response);
|
||||
return;
|
||||
}
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
|
||||
std::vector<FMSObjects::Firmware> List;
|
||||
Poco::JSON::Array ObjectArray;
|
||||
Poco::JSON::Object Answer;
|
||||
if (Storage()->GetFirmwares(QB_.Offset, QB_.Limit, DeviceType, List)) {
|
||||
for (const auto &i:List) {
|
||||
if(IdOnly) {
|
||||
ObjectArray.add(i.id);
|
||||
} else {
|
||||
Poco::JSON::Object Obj;
|
||||
i.to_json(Obj);
|
||||
ObjectArray.add(Obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
Answer.set(RESTAPI::Protocol::FIRMWARES, ObjectArray);
|
||||
ReturnObject(Answer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,16 +10,19 @@
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_firmwaresHandler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_firmwaresHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, bool Internal)
|
||||
RESTAPI_firmwaresHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>
|
||||
{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
Internal) {}
|
||||
|
||||
void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response) override;
|
||||
static const std::list<const char *> PathName() { return std::list<const char *>{"/api/v1/firmwares"};}
|
||||
void DoGet(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response);
|
||||
void DoGet() final;
|
||||
void DoDelete() final {};
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
#include <cctype>
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <future>
|
||||
@@ -16,6 +17,8 @@
|
||||
#include "Poco/URI.h"
|
||||
#include "Poco/Net/OAuth20Credentials.h"
|
||||
|
||||
#include "RESTAPI_errors.h"
|
||||
|
||||
#ifdef TIP_SECURITY_SERVICE
|
||||
#include "AuthService.h"
|
||||
#else
|
||||
@@ -29,9 +32,41 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
bool RESTAPIHandler::ParseBindings(const std::string & Request, const std::list<const char *> & EndPoints, BindingMap &bindings) {
|
||||
std::string Param, Value;
|
||||
void RESTAPIHandler::handleRequest(Poco::Net::HTTPServerRequest &RequestIn,
|
||||
Poco::Net::HTTPServerResponse &ResponseIn) {
|
||||
try {
|
||||
Request = &RequestIn;
|
||||
Response = &ResponseIn;
|
||||
|
||||
if (!ContinueProcessing())
|
||||
return;
|
||||
|
||||
if (AlwaysAuthorize_ && !IsAuthorized())
|
||||
return;
|
||||
|
||||
ParseParameters();
|
||||
if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
DoGet();
|
||||
else if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_POST)
|
||||
DoPost();
|
||||
else if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE)
|
||||
DoDelete();
|
||||
else if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_PUT)
|
||||
DoPut();
|
||||
else
|
||||
BadRequest(RESTAPI::Errors::UnsupportedHTTPMethod);
|
||||
return;
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
BadRequest(RESTAPI::Errors::InternalError);
|
||||
}
|
||||
}
|
||||
|
||||
const Poco::JSON::Object::Ptr &RESTAPIHandler::ParseStream() {
|
||||
return IncomingParser_.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>();
|
||||
}
|
||||
|
||||
bool RESTAPIHandler::ParseBindings(const std::string & Request, const std::list<const char *> & EndPoints, BindingMap &bindings) {
|
||||
bindings.clear();
|
||||
std::vector<std::string> PathItems = Utils::Split(Request, '/');
|
||||
|
||||
@@ -42,7 +77,6 @@ namespace OpenWifi {
|
||||
|
||||
bool Matched = true;
|
||||
for (auto i = 0; i != PathItems.size() && Matched; i++) {
|
||||
// std::cout << "PATH:" << PathItems[i] << " ENDPOINT:" << ParamItems[i] << std::endl;
|
||||
if (PathItems[i] != ParamItems[i]) {
|
||||
if (ParamItems[i][0] == '{') {
|
||||
auto ParamName = ParamItems[i].substr(1, ParamItems[i].size() - 2);
|
||||
@@ -59,14 +93,14 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void RESTAPIHandler::PrintBindings() {
|
||||
for (auto &[key, value] : Bindings_)
|
||||
for (const auto &[key, value] : Bindings_)
|
||||
std::cout << "Key = " << key << " Value= " << value << std::endl;
|
||||
}
|
||||
|
||||
void RESTAPIHandler::ParseParameters(Poco::Net::HTTPServerRequest &request) {
|
||||
|
||||
Poco::URI uri(request.getURI());
|
||||
void RESTAPIHandler::ParseParameters() {
|
||||
Poco::URI uri(Request->getURI());
|
||||
Parameters_ = uri.getQueryParameters();
|
||||
InitQueryBlock();
|
||||
}
|
||||
|
||||
static bool is_number(const std::string &s) {
|
||||
@@ -80,35 +114,40 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
uint64_t RESTAPIHandler::GetParameter(const std::string &Name, const uint64_t Default) {
|
||||
|
||||
for (const auto &i : Parameters_) {
|
||||
if (i.first == Name) {
|
||||
if (!is_number(i.second))
|
||||
return Default;
|
||||
return std::stoi(i.second);
|
||||
}
|
||||
}
|
||||
return Default;
|
||||
auto Hint = std::find_if(Parameters_.begin(),Parameters_.end(),[Name](const std::pair<std::string,std::string> &S){ return S.first==Name; });
|
||||
if(Hint==Parameters_.end() || !is_number(Hint->second))
|
||||
return Default;
|
||||
return std::stoull(Hint->second);
|
||||
}
|
||||
|
||||
bool RESTAPIHandler::GetBoolParameter(const std::string &Name, bool Default) {
|
||||
|
||||
for (const auto &i : Parameters_) {
|
||||
if (i.first == Name) {
|
||||
if (!is_bool(i.second))
|
||||
return Default;
|
||||
return i.second == "true";
|
||||
}
|
||||
}
|
||||
return Default;
|
||||
auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[Name](const std::pair<std::string,std::string> &S){ return S.first==Name; });
|
||||
if(Hint==end(Parameters_) || !is_bool(Hint->second))
|
||||
return Default;
|
||||
return Hint->second=="true";
|
||||
}
|
||||
|
||||
std::string RESTAPIHandler::GetParameter(const std::string &Name, const std::string &Default) {
|
||||
for (const auto &i : Parameters_) {
|
||||
if (i.first == Name)
|
||||
return i.second;
|
||||
}
|
||||
return Default;
|
||||
auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[Name](const std::pair<std::string,std::string> &S){ return S.first==Name; });
|
||||
if(Hint==end(Parameters_))
|
||||
return Default;
|
||||
return Hint->second;
|
||||
}
|
||||
|
||||
bool RESTAPIHandler::HasParameter(const std::string &Name, std::string &Value) {
|
||||
auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[Name](const std::pair<std::string,std::string> &S){ return S.first==Name; });
|
||||
if(Hint==end(Parameters_))
|
||||
return false;
|
||||
Value = Hint->second;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RESTAPIHandler::HasParameter(const std::string &Name, uint64_t & Value) {
|
||||
auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[Name](const std::pair<std::string,std::string> &S){ return S.first==Name; });
|
||||
if(Hint==end(Parameters_))
|
||||
return false;
|
||||
Value = std::stoull(Hint->second);
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::string &RESTAPIHandler::GetBinding(const std::string &Name, const std::string &Default) {
|
||||
@@ -130,202 +169,225 @@ namespace OpenWifi {
|
||||
return Return;
|
||||
}
|
||||
|
||||
void RESTAPIHandler::AddCORS(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
auto Origin = Request.find("Origin");
|
||||
if (Origin != Request.end()) {
|
||||
Response.set("Access-Control-Allow-Origin", Origin->second);
|
||||
Response.set("Vary", "Origin");
|
||||
} else {
|
||||
Response.set("Access-Control-Allow-Origin", "*");
|
||||
}
|
||||
Response.set("Access-Control-Allow-Headers", "*");
|
||||
Response.set("Access-Control-Allow-Methods", MakeList(Methods_));
|
||||
Response.set("Access-Control-Max-Age", "86400");
|
||||
bool RESTAPIHandler::AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, std::string &Value) {
|
||||
if(O->has(Field)) {
|
||||
Value = O->get(Field).toString();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void RESTAPIHandler::SetCommonHeaders(Poco::Net::HTTPServerResponse &Response, bool CloseConnection) {
|
||||
Response.setVersion(Poco::Net::HTTPMessage::HTTP_1_1);
|
||||
Response.setChunkedTransferEncoding(true);
|
||||
Response.setContentType("application/json");
|
||||
bool RESTAPIHandler::AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, uint64_t &Value) {
|
||||
if(O->has(Field)) {
|
||||
Value = O->get(Field);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void RESTAPIHandler::AddCORS() {
|
||||
auto Origin = Request->find("Origin");
|
||||
if (Origin != Request->end()) {
|
||||
Response->set("Access-Control-Allow-Origin", Origin->second);
|
||||
Response->set("Vary", "Origin");
|
||||
} else {
|
||||
Response->set("Access-Control-Allow-Origin", "*");
|
||||
}
|
||||
Response->set("Access-Control-Allow-Headers", "*");
|
||||
Response->set("Access-Control-Allow-Methods", MakeList(Methods_));
|
||||
Response->set("Access-Control-Max-Age", "86400");
|
||||
}
|
||||
|
||||
void RESTAPIHandler::SetCommonHeaders(bool CloseConnection) {
|
||||
Response->setVersion(Poco::Net::HTTPMessage::HTTP_1_1);
|
||||
Response->setChunkedTransferEncoding(true);
|
||||
Response->setContentType("application/json");
|
||||
if(CloseConnection) {
|
||||
Response.set("Connection", "close");
|
||||
Response.setKeepAlive(false);
|
||||
Response->set("Connection", "close");
|
||||
Response->setKeepAlive(false);
|
||||
} else {
|
||||
Response.setKeepAlive(true);
|
||||
Response.set("Connection", "Keep-Alive");
|
||||
Response.set("Keep-Alive", "timeout=5, max=1000");
|
||||
Response->setKeepAlive(true);
|
||||
Response->set("Connection", "Keep-Alive");
|
||||
Response->set("Keep-Alive", "timeout=5, max=1000");
|
||||
}
|
||||
}
|
||||
|
||||
void RESTAPIHandler::ProcessOptions(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
AddCORS(Request, Response);
|
||||
SetCommonHeaders(Response);
|
||||
Response.setContentLength(0);
|
||||
Response.set("Access-Control-Allow-Credentials", "true");
|
||||
Response.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
|
||||
Response.set("Vary", "Origin, Access-Control-Request-Headers, Access-Control-Request-Method");
|
||||
/* std::cout << "RESPONSE:" << std::endl;
|
||||
for(const auto &[f,s]:Response)
|
||||
std::cout << "First: " << f << " second:" << s << std::endl;
|
||||
*/
|
||||
Response.send();
|
||||
void RESTAPIHandler::ProcessOptions() {
|
||||
AddCORS();
|
||||
SetCommonHeaders();
|
||||
Response->setContentLength(0);
|
||||
Response->set("Access-Control-Allow-Credentials", "true");
|
||||
Response->setStatus(Poco::Net::HTTPResponse::HTTP_OK);
|
||||
Response->set("Vary", "Origin, Access-Control-Request-Headers, Access-Control-Request-Method");
|
||||
Response->send();
|
||||
}
|
||||
|
||||
void RESTAPIHandler::PrepareResponse(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response,
|
||||
Poco::Net::HTTPResponse::HTTPStatus Status,
|
||||
void RESTAPIHandler::PrepareResponse( Poco::Net::HTTPResponse::HTTPStatus Status,
|
||||
bool CloseConnection) {
|
||||
Response.setStatus(Status);
|
||||
AddCORS(Request, Response);
|
||||
SetCommonHeaders(Response, CloseConnection);
|
||||
Response->setStatus(Status);
|
||||
AddCORS();
|
||||
SetCommonHeaders(CloseConnection);
|
||||
}
|
||||
|
||||
void RESTAPIHandler::BadRequest(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response,
|
||||
const std::string & Reason) {
|
||||
PrepareResponse(Request, Response, Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
|
||||
void RESTAPIHandler::BadRequest(const std::string & Reason) {
|
||||
PrepareResponse(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
|
||||
Poco::JSON::Object ErrorObject;
|
||||
ErrorObject.set("ErrorCode",500);
|
||||
ErrorObject.set("ErrorDetails",Request.getMethod());
|
||||
ErrorObject.set("ErrorCode",400);
|
||||
ErrorObject.set("ErrorDetails",Request->getMethod());
|
||||
ErrorObject.set("ErrorDescription",Reason.empty() ? "Command is missing parameters or wrong values." : Reason) ;
|
||||
std::ostream &Answer = Response.send();
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
|
||||
}
|
||||
|
||||
void RESTAPIHandler::UnAuthorized(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response,
|
||||
const std::string & Reason) {
|
||||
PrepareResponse(Request, Response, Poco::Net::HTTPResponse::HTTP_FORBIDDEN);
|
||||
void RESTAPIHandler::InternalError(const std::string & Reason) {
|
||||
PrepareResponse(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
|
||||
Poco::JSON::Object ErrorObject;
|
||||
ErrorObject.set("ErrorCode",500);
|
||||
ErrorObject.set("ErrorDetails",Request->getMethod());
|
||||
ErrorObject.set("ErrorDescription",Reason.empty() ? "Please try later or review the data submitted." : Reason) ;
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
|
||||
}
|
||||
|
||||
void RESTAPIHandler::UnAuthorized(const std::string & Reason) {
|
||||
PrepareResponse(Poco::Net::HTTPResponse::HTTP_FORBIDDEN);
|
||||
Poco::JSON::Object ErrorObject;
|
||||
ErrorObject.set("ErrorCode",403);
|
||||
ErrorObject.set("ErrorDetails",Request.getMethod());
|
||||
ErrorObject.set("ErrorDetails",Request->getMethod());
|
||||
ErrorObject.set("ErrorDescription",Reason.empty() ? "No access allowed." : Reason) ;
|
||||
std::ostream &Answer = Response.send();
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
|
||||
}
|
||||
|
||||
void RESTAPIHandler::NotFound(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
PrepareResponse(Request, Response, Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
|
||||
void RESTAPIHandler::NotFound() {
|
||||
PrepareResponse(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
|
||||
Poco::JSON::Object ErrorObject;
|
||||
ErrorObject.set("ErrorCode",404);
|
||||
ErrorObject.set("ErrorDetails",Request.getMethod());
|
||||
ErrorObject.set("ErrorDetails",Request->getMethod());
|
||||
ErrorObject.set("ErrorDescription","This resource does not exist.");
|
||||
std::ostream &Answer = Response.send();
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
|
||||
Logger_.debug(Poco::format("RES-NOTFOUND: User='%s' Method='%s' Path='%s",
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
Request->getMethod(),
|
||||
Request->getURI()));
|
||||
}
|
||||
|
||||
void RESTAPIHandler::OK(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
PrepareResponse(Request, Response);
|
||||
if( Request.getMethod()==Poco::Net::HTTPRequest::HTTP_DELETE ||
|
||||
Request.getMethod()==Poco::Net::HTTPRequest::HTTP_OPTIONS) {
|
||||
Response.send();
|
||||
void RESTAPIHandler::OK() {
|
||||
PrepareResponse();
|
||||
if( Request->getMethod()==Poco::Net::HTTPRequest::HTTP_DELETE ||
|
||||
Request->getMethod()==Poco::Net::HTTPRequest::HTTP_OPTIONS) {
|
||||
Response->send();
|
||||
} else {
|
||||
Poco::JSON::Object ErrorObject;
|
||||
ErrorObject.set("Code", 0);
|
||||
ErrorObject.set("Operation", Request.getMethod());
|
||||
ErrorObject.set("Operation", Request->getMethod());
|
||||
ErrorObject.set("Details", "Command completed.");
|
||||
std::ostream &Answer = Response.send();
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
|
||||
}
|
||||
}
|
||||
|
||||
void RESTAPIHandler::SendFile(Poco::File & File, const std::string & UUID, Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
Response.set("Content-Type","application/octet-stream");
|
||||
Response.set("Content-Disposition", "attachment; filename=" + UUID );
|
||||
Response.set("Content-Transfer-Encoding","binary");
|
||||
Response.set("Accept-Ranges", "bytes");
|
||||
Response.set("Cache-Control", "private");
|
||||
Response.set("Pragma", "private");
|
||||
Response.set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
Response.set("Content-Length", std::to_string(File.getSize()));
|
||||
AddCORS(Request, Response);
|
||||
Response.sendFile(File.path(),"application/octet-stream");
|
||||
void RESTAPIHandler::SendFile(Poco::File & File, const std::string & UUID) {
|
||||
Response->set("Content-Type","application/octet-stream");
|
||||
Response->set("Content-Disposition", "attachment; filename=" + UUID );
|
||||
Response->set("Content-Transfer-Encoding","binary");
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
Response->set("Cache-Control", "private");
|
||||
Response->set("Pragma", "private");
|
||||
Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
Response->set("Content-Length", std::to_string(File.getSize()));
|
||||
AddCORS();
|
||||
Response->sendFile(File.path(),"application/octet-stream");
|
||||
}
|
||||
|
||||
void RESTAPIHandler::SendFile(Poco::File & File, Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
void RESTAPIHandler::SendFile(Poco::File & File) {
|
||||
Poco::Path P(File.path());
|
||||
auto MT = Utils::FindMediaType(File);
|
||||
if(MT.Encoding==Utils::BINARY) {
|
||||
Response.set("Content-Transfer-Encoding","binary");
|
||||
Response.set("Accept-Ranges", "bytes");
|
||||
Response->set("Content-Transfer-Encoding","binary");
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
}
|
||||
Response.set("Cache-Control", "private");
|
||||
Response.set("Pragma", "private");
|
||||
Response.set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
AddCORS(Request, Response);
|
||||
Response.sendFile(File.path(),MT.ContentType);
|
||||
Response->set("Cache-Control", "private");
|
||||
Response->set("Pragma", "private");
|
||||
Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
AddCORS();
|
||||
Response->sendFile(File.path(),MT.ContentType);
|
||||
}
|
||||
|
||||
void RESTAPIHandler::SendFile(Poco::TemporaryFile &TempAvatar, const std::string &Type, const std::string & Name, Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
void RESTAPIHandler::SendFile(Poco::TemporaryFile &TempAvatar, const std::string &Type, const std::string & Name) {
|
||||
auto MT = Utils::FindMediaType(Name);
|
||||
if(MT.Encoding==Utils::BINARY) {
|
||||
Response.set("Content-Transfer-Encoding","binary");
|
||||
Response.set("Accept-Ranges", "bytes");
|
||||
Response->set("Content-Transfer-Encoding","binary");
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
}
|
||||
Response.set("Content-Disposition", "attachment; filename=" + Name );
|
||||
Response.set("Accept-Ranges", "bytes");
|
||||
Response.set("Cache-Control", "private");
|
||||
Response.set("Pragma", "private");
|
||||
Response.set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
AddCORS(Request, Response);
|
||||
Response.sendFile(TempAvatar.path(),MT.ContentType);
|
||||
Response->set("Content-Disposition", "attachment; filename=" + Name );
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
Response->set("Cache-Control", "private");
|
||||
Response->set("Pragma", "private");
|
||||
Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
AddCORS();
|
||||
Response->sendFile(TempAvatar.path(),MT.ContentType);
|
||||
}
|
||||
|
||||
void RESTAPIHandler::SendHTMLFileBack(Poco::File & File,
|
||||
Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response ,
|
||||
const Types::StringPairVec & FormVars) {
|
||||
Response.set("Pragma", "private");
|
||||
Response.set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
Response.set("Content-Length", std::to_string(File.getSize()));
|
||||
AddCORS(Request, Response);
|
||||
Response->set("Pragma", "private");
|
||||
Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
Response->set("Content-Length", std::to_string(File.getSize()));
|
||||
AddCORS();
|
||||
auto FormContent = Utils::LoadFile(File.path());
|
||||
Utils::ReplaceVariables(FormContent, FormVars);
|
||||
Response.setChunkedTransferEncoding(true);
|
||||
Response.setContentType("text/html");
|
||||
std::ostream& ostr = Response.send();
|
||||
Response->setChunkedTransferEncoding(true);
|
||||
Response->setContentType("text/html");
|
||||
std::ostream& ostr = Response->send();
|
||||
ostr << FormContent;
|
||||
}
|
||||
|
||||
void RESTAPIHandler::ReturnStatus(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response,
|
||||
Poco::Net::HTTPResponse::HTTPStatus Status,
|
||||
bool CloseConnection) {
|
||||
PrepareResponse(Request, Response, Status, CloseConnection);
|
||||
void RESTAPIHandler::ReturnStatus(Poco::Net::HTTPResponse::HTTPStatus Status, bool CloseConnection) {
|
||||
PrepareResponse(Status, CloseConnection);
|
||||
if(Status == Poco::Net::HTTPResponse::HTTP_NO_CONTENT) {
|
||||
Response.setContentLength(0);
|
||||
Response.erase("Content-Type");
|
||||
Response.setChunkedTransferEncoding(false);
|
||||
Response->setContentLength(0);
|
||||
Response->erase("Content-Type");
|
||||
Response->setChunkedTransferEncoding(false);
|
||||
}
|
||||
Response.send();
|
||||
Response->send();
|
||||
}
|
||||
|
||||
bool RESTAPIHandler::ContinueProcessing(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_OPTIONS) {
|
||||
ProcessOptions(Request, Response);
|
||||
bool RESTAPIHandler::ContinueProcessing() {
|
||||
if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_OPTIONS) {
|
||||
ProcessOptions();
|
||||
return false;
|
||||
} else if (std::find(Methods_.begin(), Methods_.end(), Request.getMethod()) == Methods_.end()) {
|
||||
BadRequest(Request, Response);
|
||||
} else if (std::find(Methods_.begin(), Methods_.end(), Request->getMethod()) == Methods_.end()) {
|
||||
BadRequest(RESTAPI::Errors::UnsupportedHTTPMethod);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RESTAPIHandler::IsAuthorized(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
bool RESTAPIHandler::IsAuthorized() {
|
||||
if(Internal_) {
|
||||
return Daemon()->IsValidAPIKEY(Request);
|
||||
auto Allowed = Daemon()->IsValidAPIKEY(*Request);
|
||||
if(!Allowed) {
|
||||
if(Server_.LogBadTokens(false)) {
|
||||
Logger_.debug(Poco::format("I-REQ-DENIED(%s): Method='%s' Path='%s",
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
Request->getMethod(), Request->getURI()));
|
||||
}
|
||||
} else {
|
||||
auto Id = Request->get("X-INTERNAL-NAME", "unknown");
|
||||
if(Server_.LogIt(Request->getMethod(),true)) {
|
||||
Logger_.debug(Poco::format("I-REQ-ALLOWED(%s): User='%s' Method='%s' Path='%s",
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()), Id,
|
||||
Request->getMethod(), Request->getURI()));
|
||||
}
|
||||
}
|
||||
return Allowed;
|
||||
} else {
|
||||
if (SessionToken_.empty()) {
|
||||
try {
|
||||
Poco::Net::OAuth20Credentials Auth(Request);
|
||||
|
||||
Poco::Net::OAuth20Credentials Auth(*Request);
|
||||
if (Auth.getScheme() == "Bearer") {
|
||||
SessionToken_ = Auth.getBearerToken();
|
||||
}
|
||||
@@ -334,37 +396,47 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
#ifdef TIP_SECURITY_SERVICE
|
||||
if (AuthService()->IsAuthorized(Request, SessionToken_, UserInfo_)) {
|
||||
if (AuthService()->IsAuthorized(*Request, SessionToken_, UserInfo_)) {
|
||||
#else
|
||||
if (AuthClient()->IsAuthorized(Request, SessionToken_, UserInfo_)) {
|
||||
if (AuthClient()->IsAuthorized(*Request, SessionToken_, UserInfo_)) {
|
||||
#endif
|
||||
if(Server_.LogIt(Request->getMethod(),true)) {
|
||||
Logger_.debug(Poco::format("X-REQ-ALLOWED(%s): User='%s@%s' Method='%s' Path='%s",
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
UserInfo_.userinfo.email,
|
||||
Request->clientAddress().toString(),
|
||||
Request->getMethod(),
|
||||
Request->getURI()));
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
UnAuthorized(Request, Response);
|
||||
if(Server_.LogBadTokens(true)) {
|
||||
Logger_.debug(Poco::format("X-REQ-DENIED(%s): Method='%s' Path='%s",
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
Request->getMethod(), Request->getURI()));
|
||||
}
|
||||
UnAuthorized();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
bool RESTAPIHandler::ValidateAPIKey(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
auto Key = Request.get("X-API-KEY", "");
|
||||
|
||||
if (Key.empty())
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
*/
|
||||
void RESTAPIHandler::ReturnObject(Poco::Net::HTTPServerRequest &Request, Poco::JSON::Object &Object,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
PrepareResponse(Request, Response);
|
||||
std::ostream &Answer = Response.send();
|
||||
void RESTAPIHandler::ReturnObject(Poco::JSON::Object &Object) {
|
||||
PrepareResponse();
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::JSON::Stringifier::stringify(Object, Answer);
|
||||
}
|
||||
|
||||
void RESTAPIHandler::ReturnCountOnly(uint64_t Count) {
|
||||
Poco::JSON::Object Answer;
|
||||
Answer.set("count", Count);
|
||||
ReturnObject(Answer);
|
||||
}
|
||||
|
||||
bool RESTAPIHandler::InitQueryBlock() {
|
||||
if(QueryBlockInitialized_)
|
||||
return true;
|
||||
QueryBlockInitialized_=true;
|
||||
QB_.SerialNumber = GetParameter(RESTAPI::Protocol::SERIALNUMBER, "");
|
||||
QB_.StartDate = GetParameter(RESTAPI::Protocol::STARTDATE, 0);
|
||||
QB_.EndDate = GetParameter(RESTAPI::Protocol::ENDDATE, 0);
|
||||
@@ -376,8 +448,10 @@ namespace OpenWifi {
|
||||
QB_.LogType = GetParameter(RESTAPI::Protocol::LOGTYPE,0);
|
||||
QB_.LastOnly = GetBoolParameter(RESTAPI::Protocol::LASTONLY,false);
|
||||
QB_.Newest = GetBoolParameter(RESTAPI::Protocol::NEWEST,false);
|
||||
QB_.CountOnly = GetBoolParameter(RESTAPI::Protocol::COUNTONLY,false);
|
||||
|
||||
if(QB_.Offset<1) return false;
|
||||
if(QB_.Offset<1)
|
||||
QB_.Offset=1;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -402,6 +476,4 @@ namespace OpenWifi {
|
||||
[[nodiscard]] uint64_t RESTAPIHandler::GetWhen(const Poco::JSON::Object::Ptr &Obj) {
|
||||
return RESTAPIHandler::Get(RESTAPI::Protocol::WHEN, Obj);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -25,6 +25,8 @@
|
||||
#include "Poco/NullStream.h"
|
||||
|
||||
#include "RESTAPI_SecurityObjects.h"
|
||||
#include "RESTAPI_utils.h"
|
||||
#include "RESTAPI_GenericServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
@@ -86,66 +88,78 @@ namespace OpenWifi {
|
||||
struct QueryBlock {
|
||||
uint64_t StartDate = 0 , EndDate = 0 , Offset = 0 , Limit = 0, LogType = 0 ;
|
||||
std::string SerialNumber, Filter, Select;
|
||||
bool Lifetime=false, LastOnly=false, Newest=false;
|
||||
bool Lifetime=false, LastOnly=false, Newest=false, CountOnly=false;
|
||||
};
|
||||
|
||||
typedef std::map<std::string, std::string> BindingMap;
|
||||
|
||||
RESTAPIHandler(BindingMap map, Poco::Logger &l, std::vector<std::string> Methods, bool Internal=false)
|
||||
: Bindings_(std::move(map)), Logger_(l), Methods_(std::move(Methods)), Internal_(Internal) {}
|
||||
RESTAPIHandler(BindingMap map, Poco::Logger &l, std::vector<std::string> Methods, RESTAPI_GenericServer & Server, bool Internal=false, bool AlwaysAuthorize=true)
|
||||
: Bindings_(std::move(map)), Logger_(l), Methods_(std::move(Methods)), Server_(Server), Internal_(Internal), AlwaysAuthorize_(AlwaysAuthorize) {}
|
||||
|
||||
static bool ParseBindings(const std::string & Request, const std::list<const char *> & EndPoints, BindingMap &Keys);
|
||||
void PrintBindings();
|
||||
void ParseParameters(Poco::Net::HTTPServerRequest &request);
|
||||
void ParseParameters();
|
||||
|
||||
void AddCORS(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &response);
|
||||
void SetCommonHeaders(Poco::Net::HTTPServerResponse &response, bool CloseConnection=false);
|
||||
void ProcessOptions(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &response);
|
||||
void AddCORS();
|
||||
void SetCommonHeaders(bool CloseConnection=false);
|
||||
void ProcessOptions();
|
||||
void
|
||||
PrepareResponse(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &response,
|
||||
Poco::Net::HTTPResponse::HTTPStatus Status = Poco::Net::HTTPResponse::HTTP_OK,
|
||||
PrepareResponse(Poco::Net::HTTPResponse::HTTPStatus Status = Poco::Net::HTTPResponse::HTTP_OK,
|
||||
bool CloseConnection = false);
|
||||
bool ContinueProcessing(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response);
|
||||
|
||||
bool IsAuthorized(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response);
|
||||
/* bool ValidateAPIKey(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response); */
|
||||
bool ContinueProcessing();
|
||||
bool IsAuthorized();
|
||||
|
||||
uint64_t GetParameter(const std::string &Name, uint64_t Default);
|
||||
std::string GetParameter(const std::string &Name, const std::string &Default);
|
||||
bool GetBoolParameter(const std::string &Name, bool Default);
|
||||
|
||||
void BadRequest(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response, const std::string &Reason = "");
|
||||
void UnAuthorized(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response, const std::string &Reason = "");
|
||||
void ReturnObject(Poco::Net::HTTPServerRequest &Request, Poco::JSON::Object &Object,
|
||||
Poco::Net::HTTPServerResponse &Response);
|
||||
void NotFound(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response);
|
||||
void OK(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response);
|
||||
void ReturnStatus(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response,
|
||||
Poco::Net::HTTPResponse::HTTPStatus Status,
|
||||
void BadRequest(const std::string &Reason );
|
||||
void InternalError(const std::string &Reason = "");
|
||||
void UnAuthorized(const std::string &Reason = "");
|
||||
void ReturnObject(Poco::JSON::Object &Object);
|
||||
void NotFound();
|
||||
void OK();
|
||||
void ReturnStatus(Poco::Net::HTTPResponse::HTTPStatus Status,
|
||||
bool CloseConnection=false);
|
||||
void SendFile(Poco::File & File, const std::string & UUID,
|
||||
Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response);
|
||||
void SendFile(Poco::File & File, const std::string & UUID);
|
||||
void SendHTMLFileBack(Poco::File & File,
|
||||
Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response ,
|
||||
const Types::StringPairVec & FormVars);
|
||||
void SendFile(Poco::TemporaryFile &TempAvatar, const std::string &Type, const std::string & Name, Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response);
|
||||
void SendFile(Poco::TemporaryFile &TempAvatar, const std::string &Type, const std::string & Name);
|
||||
|
||||
void SendFile(Poco::File & File, Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response);
|
||||
void SendFile(Poco::File & File);
|
||||
|
||||
const std::string &GetBinding(const std::string &Name, const std::string &Default);
|
||||
bool InitQueryBlock();
|
||||
|
||||
void ReturnCountOnly(uint64_t Count);
|
||||
|
||||
[[nodiscard]] static uint64_t Get(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, uint64_t Default=0);
|
||||
[[nodiscard]] static std::string GetS(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, const std::string & Default="");
|
||||
[[nodiscard]] static bool GetB(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, bool Default=false);
|
||||
[[nodiscard]] static uint64_t GetWhen(const Poco::JSON::Object::Ptr &Obj);
|
||||
bool HasParameter(const std::string &QueryParameter, std::string &Value);
|
||||
bool HasParameter(const std::string &QueryParameter, uint64_t & Value);
|
||||
|
||||
static bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, std::string &Value);
|
||||
static bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, uint64_t &Value);
|
||||
|
||||
template<typename T> void ReturnObject(const char *Name, const std::vector<T> & Objects) {
|
||||
Poco::JSON::Object Answer;
|
||||
RESTAPI_utils::field_to_json(Answer,Name,Objects);
|
||||
ReturnObject(Answer);
|
||||
}
|
||||
|
||||
Poco::Logger & Logger() { return Logger_; }
|
||||
|
||||
void handleRequest(Poco::Net::HTTPServerRequest &request,
|
||||
Poco::Net::HTTPServerResponse &response) final;
|
||||
|
||||
virtual void DoGet() = 0 ;
|
||||
virtual void DoDelete() = 0 ;
|
||||
virtual void DoPost() = 0 ;
|
||||
virtual void DoPut() = 0 ;
|
||||
|
||||
const Poco::JSON::Object::Ptr & ParseStream();
|
||||
|
||||
protected:
|
||||
BindingMap Bindings_;
|
||||
@@ -156,19 +170,23 @@ namespace OpenWifi {
|
||||
std::vector<std::string> Methods_;
|
||||
QueryBlock QB_;
|
||||
bool Internal_=false;
|
||||
bool QueryBlockInitialized_=false;
|
||||
Poco::Net::HTTPServerRequest *Request= nullptr;
|
||||
Poco::Net::HTTPServerResponse *Response= nullptr;
|
||||
bool AlwaysAuthorize_=true;
|
||||
Poco::JSON::Parser IncomingParser_;
|
||||
RESTAPI_GenericServer & Server_;
|
||||
};
|
||||
|
||||
class RESTAPI_UnknownRequestHandler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_UnknownRequestHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L)
|
||||
: RESTAPIHandler(bindings, L, std::vector<std::string>{}) {}
|
||||
void handleRequest(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) override {
|
||||
if (!IsAuthorized(Request, Response))
|
||||
return;
|
||||
BadRequest(Request, Response, "Unknown API endpoint");
|
||||
}
|
||||
};
|
||||
RESTAPI_UnknownRequestHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server)
|
||||
: RESTAPIHandler(bindings, L, std::vector<std::string>{}, Server) {}
|
||||
inline void DoGet() override {};
|
||||
inline void DoPost() override {};
|
||||
inline void DoPut() override {};
|
||||
inline void DoDelete() override {};
|
||||
};
|
||||
|
||||
template<class T>
|
||||
constexpr auto test_has_PathName_method(T*)
|
||||
@@ -182,30 +200,30 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
template<typename T, typename... Args>
|
||||
RESTAPIHandler * RESTAPI_Router(const std::string & RequestedPath, RESTAPIHandler::BindingMap &Bindings, Poco::Logger & Logger ) {
|
||||
RESTAPIHandler * RESTAPI_Router(const std::string & RequestedPath, RESTAPIHandler::BindingMap &Bindings, Poco::Logger & Logger, RESTAPI_GenericServer & Server) {
|
||||
static_assert(test_has_PathName_method((T*)nullptr), "Class must have a static PathName() method.");
|
||||
if(RESTAPIHandler::ParseBindings(RequestedPath,T::PathName(),Bindings)) {
|
||||
return new T(Bindings, Logger, false);
|
||||
return new T(Bindings, Logger, Server, false);
|
||||
}
|
||||
|
||||
if constexpr (sizeof...(Args) == 0) {
|
||||
return new RESTAPI_UnknownRequestHandler(Bindings,Logger);
|
||||
return new RESTAPI_UnknownRequestHandler(Bindings,Logger, Server);
|
||||
} else {
|
||||
return RESTAPI_Router<Args...>(RequestedPath, Bindings, Logger);
|
||||
return RESTAPI_Router<Args...>(RequestedPath, Bindings, Logger, Server);
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T, typename... Args>
|
||||
RESTAPIHandler * RESTAPI_Router_I(const std::string & RequestedPath, RESTAPIHandler::BindingMap &Bindings, Poco::Logger & Logger) {
|
||||
RESTAPIHandler * RESTAPI_Router_I(const std::string & RequestedPath, RESTAPIHandler::BindingMap &Bindings, Poco::Logger & Logger, RESTAPI_GenericServer & Server) {
|
||||
static_assert(test_has_PathName_method((T*)nullptr), "Class must have a static PathName() method.");
|
||||
if(RESTAPIHandler::ParseBindings(RequestedPath,T::PathName(),Bindings)) {
|
||||
return new T(Bindings, Logger, true);
|
||||
return new T(Bindings, Logger, Server, true);
|
||||
}
|
||||
|
||||
if constexpr (sizeof...(Args) == 0) {
|
||||
return new RESTAPI_UnknownRequestHandler(Bindings,Logger);
|
||||
return new RESTAPI_UnknownRequestHandler(Bindings,Logger, Server);
|
||||
} else {
|
||||
return RESTAPI_Router_I<Args...>(RequestedPath, Bindings, Logger);
|
||||
return RESTAPI_Router_I<Args...>(RequestedPath, Bindings, Logger, Server);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,71 +11,46 @@
|
||||
#include "RESTAPI_historyHandler.h"
|
||||
#include "StorageService.h"
|
||||
#include "RESTAPI_protocol.h"
|
||||
#include "RESTAPI_errors.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_historyHandler::handleRequest(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
if (!ContinueProcessing(Request, Response))
|
||||
return;
|
||||
if (!IsAuthorized(Request, Response))
|
||||
return;
|
||||
ParseParameters(Request);
|
||||
if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
DoGet(Request, Response);
|
||||
else if(Request.getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE)
|
||||
DoDelete(Request, Response);
|
||||
else
|
||||
BadRequest(Request, Response);
|
||||
}
|
||||
|
||||
void
|
||||
RESTAPI_historyHandler::DoGet(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
auto SerialNumber = GetBinding(RESTAPI::Protocol::SERIALNUMBER, "");
|
||||
RESTAPI_historyHandler::DoGet() {
|
||||
auto SerialNumber = GetBinding(RESTAPI::Protocol::SERIALNUMBER, "");
|
||||
|
||||
if (!SerialNumber.empty()) {
|
||||
FMSObjects::RevisionHistoryEntryVec H;
|
||||
InitQueryBlock();
|
||||
if (Storage()->GetHistory(SerialNumber, QB_.Offset, QB_.Limit, H)) {
|
||||
Poco::JSON::Array A;
|
||||
for (auto const &i:H) {
|
||||
Poco::JSON::Object O;
|
||||
i.to_json(O);
|
||||
A.add(O);
|
||||
}
|
||||
Poco::JSON::Object Answer;
|
||||
Answer.set(RESTAPI::Protocol::HISTORY, A);
|
||||
ReturnObject(Request, Answer, Response);
|
||||
} else {
|
||||
NotFound(Request, Response);
|
||||
}
|
||||
return;
|
||||
}
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
if(SerialNumber.empty()) {
|
||||
BadRequest(RESTAPI::Errors::MissingSerialNumber);
|
||||
return;
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
|
||||
FMSObjects::RevisionHistoryEntryVec H;
|
||||
if (Storage()->GetHistory(SerialNumber, QB_.Offset, QB_.Limit, H)) {
|
||||
Poco::JSON::Array A;
|
||||
for (auto const &i:H) {
|
||||
Poco::JSON::Object O;
|
||||
i.to_json(O);
|
||||
A.add(O);
|
||||
}
|
||||
Poco::JSON::Object Answer;
|
||||
Answer.set(RESTAPI::Protocol::HISTORY, A);
|
||||
ReturnObject(Answer);
|
||||
return;
|
||||
}
|
||||
NotFound();
|
||||
}
|
||||
|
||||
void RESTAPI_historyHandler::DoDelete(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
auto SerialNumber = GetBinding(RESTAPI::Protocol::SERIALNUMBER, "");
|
||||
auto Id = GetParameter(RESTAPI::Protocol::ID, "");
|
||||
if (SerialNumber.empty() || Id.empty()) {
|
||||
BadRequest(Request, Response, "SerialNumber and Id must not be empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Storage()->DeleteHistory(SerialNumber, Id)) {
|
||||
OK(Request, Response);
|
||||
return;
|
||||
}
|
||||
NotFound(Request, Response);
|
||||
void RESTAPI_historyHandler::DoDelete() {
|
||||
auto SerialNumber = GetBinding(RESTAPI::Protocol::SERIALNUMBER, "");
|
||||
auto Id = GetParameter(RESTAPI::Protocol::ID, "");
|
||||
if (SerialNumber.empty() || Id.empty()) {
|
||||
BadRequest(RESTAPI::Errors::IdOrSerialEmpty);
|
||||
return;
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
BadRequest(Request, Response);
|
||||
|
||||
if (!Storage()->DeleteHistory(SerialNumber, Id)) {
|
||||
OK();
|
||||
return;
|
||||
}
|
||||
NotFound();
|
||||
}
|
||||
}
|
||||
@@ -11,17 +11,19 @@
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_historyHandler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_historyHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, bool Internal)
|
||||
RESTAPI_historyHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, 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,
|
||||
Internal) {}
|
||||
static const std::list<const char *> PathName() { return std::list<const char *>{"/api/v1/revisionHistory/{serialNumber}"};}
|
||||
void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response) override;
|
||||
void DoGet(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response);
|
||||
void DoDelete(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response);
|
||||
void DoGet() final;
|
||||
void DoDelete() final;
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +69,13 @@ namespace OpenWifi::RESTAPI::Protocol {
|
||||
static const char * COMMANDUUID = "commandUUID";
|
||||
static const char * FIRMWARES = "firmwares";
|
||||
static const char * TOPIC = "topic";
|
||||
static const char * HOST = "host";
|
||||
static const char * OS = "os";
|
||||
static const char * HOSTNAME = "hostname";
|
||||
static const char * PROCESSORS = "processors";
|
||||
static const char * REASON = "reason";
|
||||
static const char * RELOAD = "reload";
|
||||
static const char * SUBSYSTEMS = "subsystems";
|
||||
static const char * FILEUUID = "uuid";
|
||||
static const char * USERID = "userId";
|
||||
static const char * PASSWORD = "password";
|
||||
@@ -122,6 +128,8 @@ namespace OpenWifi::RESTAPI::Protocol {
|
||||
static const char * PASSWORDPOLICY = "passwordPolicy";
|
||||
static const char * FORGOTPASSWORD = "forgotPassword";
|
||||
static const char * ME = "me";
|
||||
static const char * TELEMETRY = "telemetry";
|
||||
static const char * INTERVAL = "interval";
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -22,12 +22,13 @@ namespace OpenWifi {
|
||||
class RESTAPI_server *RESTAPI_server::instance_ = nullptr;
|
||||
|
||||
RESTAPI_server::RESTAPI_server() noexcept:
|
||||
SubSystemServer("RESTAPIServer", "RESTAPIServer", "ucentralfws.restapi")
|
||||
SubSystemServer("RESTAPIServer", "RESTAPIServer", "openwifi.restapi")
|
||||
{
|
||||
}
|
||||
|
||||
int RESTAPI_server::Start() {
|
||||
Logger_.information("Starting.");
|
||||
Server_.InitLogging();
|
||||
|
||||
for(const auto & Svr: ConfigServersList_) {
|
||||
Logger_.information(Poco::format("Starting: %s:%s Keyfile:%s CertFile: %s", Svr.Address(), std::to_string(Svr.Port()),
|
||||
@@ -44,7 +45,7 @@ namespace OpenWifi {
|
||||
Params->setMaxQueued(200);
|
||||
Params->setKeepAlive(true);
|
||||
|
||||
auto NewServer = std::make_unique<Poco::Net::HTTPServer>(new RequestHandlerFactory, Pool_, Sock, Params);
|
||||
auto NewServer = std::make_unique<Poco::Net::HTTPServer>(new RequestHandlerFactory(Server_), Pool_, Sock, Params);
|
||||
NewServer->start();
|
||||
RESTServers_.push_back(std::move(NewServer));
|
||||
}
|
||||
@@ -53,9 +54,6 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
Poco::Net::HTTPRequestHandler *RequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest & Request) {
|
||||
|
||||
Logger_.debug(Poco::format("REQUEST(%s): %s %s", Utils::FormatIPv6(Request.clientAddress().toString()), Request.getMethod(), Request.getURI()));
|
||||
|
||||
Poco::URI uri(Request.getURI());
|
||||
auto *Path = uri.getPath().c_str();
|
||||
RESTAPIHandler::BindingMap Bindings;
|
||||
@@ -71,13 +69,21 @@ namespace OpenWifi {
|
||||
RESTAPI_connectedDeviceHandler,
|
||||
RESTAPI_historyHandler,
|
||||
RESTAPI_deviceReportHandler
|
||||
>(Path,Bindings,Logger_);
|
||||
>(Path,Bindings,Logger_, Server_);
|
||||
}
|
||||
|
||||
void RESTAPI_server::Stop() {
|
||||
Logger_.information("Stopping ");
|
||||
for( const auto & svr : RESTServers_ )
|
||||
svr->stop();
|
||||
RESTServers_.clear();
|
||||
}
|
||||
|
||||
void RESTAPI_server::reinitialize(Poco::Util::Application &self) {
|
||||
Daemon()->LoadConfigurationFile();
|
||||
Logger_.information("Reinitializing.");
|
||||
Stop();
|
||||
Start();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include "Poco/Net/NetException.h"
|
||||
|
||||
#include "SubSystemServer.h"
|
||||
#include "RESTAPI_GenericServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
@@ -28,23 +29,30 @@ namespace OpenWifi {
|
||||
}
|
||||
int Start() override;
|
||||
void Stop() override;
|
||||
void reinitialize(Poco::Util::Application &self) override;
|
||||
|
||||
private:
|
||||
static RESTAPI_server *instance_;
|
||||
std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_;
|
||||
Poco::ThreadPool Pool_;
|
||||
Poco::ThreadPool Pool_;
|
||||
RESTAPI_GenericServer Server_;
|
||||
};
|
||||
|
||||
inline RESTAPI_server * RESTAPI_server() { return RESTAPI_server::instance(); };
|
||||
|
||||
class RequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
|
||||
public:
|
||||
RequestHandlerFactory() :
|
||||
Logger_(RESTAPI_server::instance()->Logger()){}
|
||||
RequestHandlerFactory(RESTAPI_GenericServer & Server) :
|
||||
Logger_(RESTAPI_server::instance()->Logger()),
|
||||
Server_(Server)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &request) override;
|
||||
private:
|
||||
Poco::Logger & Logger_;
|
||||
Poco::Logger &Logger_;
|
||||
RESTAPI_GenericServer &Server_;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -9,124 +9,138 @@
|
||||
|
||||
#include "Poco/Exception.h"
|
||||
#include "Poco/JSON/Parser.h"
|
||||
#include "Poco/DateTime.h"
|
||||
#include "Poco/DateTimeFormat.h"
|
||||
|
||||
#include "Daemon.h"
|
||||
#include "RESTAPI_protocol.h"
|
||||
#include "RESTAPI_errors.h"
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_system_command::handleRequest(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
|
||||
if (!ContinueProcessing(Request, Response))
|
||||
return;
|
||||
|
||||
if (!IsAuthorized(Request, Response))
|
||||
return;
|
||||
|
||||
if (Request.getMethod() == Poco::Net::HTTPRequest::HTTP_POST)
|
||||
DoPost(Request, Response);
|
||||
else if(Request.getMethod()==Poco::Net::HTTPRequest::HTTP_GET)
|
||||
DoGet(Request, Response);
|
||||
else
|
||||
BadRequest(Request, Response, "Unsupported method.");
|
||||
}
|
||||
|
||||
void RESTAPI_system_command::DoPost(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
Poco::JSON::Parser parser;
|
||||
auto Obj = parser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>();
|
||||
|
||||
if (Obj->has(RESTAPI::Protocol::COMMAND)) {
|
||||
auto Command = Poco::toLower(Obj->get(RESTAPI::Protocol::COMMAND).toString());
|
||||
if (Command == RESTAPI::Protocol::SETLOGLEVEL) {
|
||||
if (Obj->has(RESTAPI::Protocol::PARAMETERS) &&
|
||||
Obj->isArray(RESTAPI::Protocol::PARAMETERS)) {
|
||||
auto ParametersBlock = Obj->getArray(RESTAPI::Protocol::PARAMETERS);
|
||||
for (const auto &i:*ParametersBlock) {
|
||||
Poco::JSON::Parser pp;
|
||||
auto InnerObj = pp.parse(i).extract<Poco::JSON::Object::Ptr>();
|
||||
if (InnerObj->has(RESTAPI::Protocol::TAG) &&
|
||||
InnerObj->has(RESTAPI::Protocol::VALUE)) {
|
||||
auto Name = GetS(RESTAPI::Protocol::TAG, InnerObj);
|
||||
auto Value = GetS(RESTAPI::Protocol::VALUE, InnerObj);
|
||||
Daemon()->SetSubsystemLogLevel(Name, Value);
|
||||
Logger_.information(Poco::format("Setting log level for %s at %s", Name, Value));
|
||||
}
|
||||
void RESTAPI_system_command::DoPost() {
|
||||
auto Obj = ParseStream();
|
||||
if (Obj->has(RESTAPI::Protocol::COMMAND)) {
|
||||
auto Command = Poco::toLower(Obj->get(RESTAPI::Protocol::COMMAND).toString());
|
||||
if (Command == RESTAPI::Protocol::SETLOGLEVEL) {
|
||||
if (Obj->has(RESTAPI::Protocol::SUBSYSTEMS) &&
|
||||
Obj->isArray(RESTAPI::Protocol::SUBSYSTEMS)) {
|
||||
auto ParametersBlock = Obj->getArray(RESTAPI::Protocol::SUBSYSTEMS);
|
||||
for (const auto &i : *ParametersBlock) {
|
||||
Poco::JSON::Parser pp;
|
||||
auto InnerObj = pp.parse(i).extract<Poco::JSON::Object::Ptr>();
|
||||
if (InnerObj->has(RESTAPI::Protocol::TAG) &&
|
||||
InnerObj->has(RESTAPI::Protocol::VALUE)) {
|
||||
auto Name = GetS(RESTAPI::Protocol::TAG, InnerObj);
|
||||
auto Value = GetS(RESTAPI::Protocol::VALUE, InnerObj);
|
||||
Daemon()->SetSubsystemLogLevel(Name, Value);
|
||||
Logger_.information(
|
||||
Poco::format("Setting log level for %s at %s", Name, Value));
|
||||
}
|
||||
OK(Request, Response);
|
||||
return;
|
||||
}
|
||||
} else if (Command == RESTAPI::Protocol::GETLOGLEVELS) {
|
||||
auto CurrentLogLevels = Daemon()->GetLogLevels();
|
||||
Poco::JSON::Object Result;
|
||||
Poco::JSON::Array Array;
|
||||
for(auto &[Name,Level]:CurrentLogLevels) {
|
||||
Poco::JSON::Object Pair;
|
||||
Pair.set( RESTAPI::Protocol::TAG,Name);
|
||||
Pair.set(RESTAPI::Protocol::VALUE,Level);
|
||||
Array.add(Pair);
|
||||
}
|
||||
Result.set(RESTAPI::Protocol::TAGLIST,Array);
|
||||
ReturnObject(Request,Result,Response);
|
||||
OK();
|
||||
return;
|
||||
} else if (Command == RESTAPI::Protocol::GETLOGLEVELNAMES) {
|
||||
Poco::JSON::Object Result;
|
||||
Poco::JSON::Array LevelNamesArray;
|
||||
const Types::StringVec & LevelNames = Daemon()->GetLogLevelNames();
|
||||
for(const auto &i:LevelNames)
|
||||
LevelNamesArray.add(i);
|
||||
Result.set(RESTAPI::Protocol::LIST,LevelNamesArray);
|
||||
ReturnObject(Request,Result,Response);
|
||||
return;
|
||||
} else if (Command == RESTAPI::Protocol::GETSUBSYSTEMNAMES) {
|
||||
Poco::JSON::Object Result;
|
||||
Poco::JSON::Array LevelNamesArray;
|
||||
const Types::StringVec & SubSystemNames = Daemon()->GetSubSystems();
|
||||
for(const auto &i:SubSystemNames)
|
||||
LevelNamesArray.add(i);
|
||||
Result.set(RESTAPI::Protocol::LIST,LevelNamesArray);
|
||||
ReturnObject(Request,Result,Response);
|
||||
return;
|
||||
} else if (Command == RESTAPI::Protocol::STATS) {
|
||||
|
||||
}
|
||||
}
|
||||
} catch(const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
BadRequest(Request, Response, "Unsupported or missing parameters.");
|
||||
}
|
||||
} else if (Command == RESTAPI::Protocol::GETLOGLEVELS) {
|
||||
auto CurrentLogLevels = Daemon()->GetLogLevels();
|
||||
Poco::JSON::Object Result;
|
||||
Poco::JSON::Array Array;
|
||||
for (auto &[Name, Level] : CurrentLogLevels) {
|
||||
Poco::JSON::Object Pair;
|
||||
Pair.set(RESTAPI::Protocol::TAG, Name);
|
||||
Pair.set(RESTAPI::Protocol::VALUE, Level);
|
||||
Array.add(Pair);
|
||||
}
|
||||
Result.set(RESTAPI::Protocol::TAGLIST, Array);
|
||||
ReturnObject(Result);
|
||||
return;
|
||||
} else if (Command == RESTAPI::Protocol::GETLOGLEVELNAMES) {
|
||||
Poco::JSON::Object Result;
|
||||
Poco::JSON::Array LevelNamesArray;
|
||||
const Types::StringVec &LevelNames = Daemon()->GetLogLevelNames();
|
||||
for (const auto &i : LevelNames)
|
||||
LevelNamesArray.add(i);
|
||||
Result.set(RESTAPI::Protocol::LIST, LevelNamesArray);
|
||||
ReturnObject(Result);
|
||||
return;
|
||||
} else if (Command == RESTAPI::Protocol::GETSUBSYSTEMNAMES) {
|
||||
Poco::JSON::Object Result;
|
||||
Poco::JSON::Array LevelNamesArray;
|
||||
const Types::StringVec &SubSystemNames = Daemon()->GetSubSystems();
|
||||
for (const auto &i : SubSystemNames)
|
||||
LevelNamesArray.add(i);
|
||||
Result.set(RESTAPI::Protocol::LIST, LevelNamesArray);
|
||||
ReturnObject(Result);
|
||||
return;
|
||||
} else if (Command == RESTAPI::Protocol::STATS) {
|
||||
|
||||
void RESTAPI_system_command::DoGet(Poco::Net::HTTPServerRequest &Request, Poco::Net::HTTPServerResponse &Response) {
|
||||
try {
|
||||
ParseParameters(Request);
|
||||
auto Command = GetParameter(RESTAPI::Protocol::COMMAND, "");
|
||||
if (!Poco::icompare(Command, RESTAPI::Protocol::VERSION)) {
|
||||
Poco::JSON::Object Answer;
|
||||
Answer.set(RESTAPI::Protocol::TAG, RESTAPI::Protocol::VERSION);
|
||||
Answer.set(RESTAPI::Protocol::VALUE, Daemon()->Version());
|
||||
ReturnObject(Request, Answer, Response);
|
||||
} else if (Command == RESTAPI::Protocol::RELOAD) {
|
||||
if (Obj->has(RESTAPI::Protocol::SUBSYSTEMS) &&
|
||||
Obj->isArray(RESTAPI::Protocol::SUBSYSTEMS)) {
|
||||
auto SubSystems = Obj->getArray(RESTAPI::Protocol::SUBSYSTEMS);
|
||||
std::vector<std::string> Names;
|
||||
for (const auto &i : *SubSystems)
|
||||
Names.push_back(i.toString());
|
||||
std::thread ReloadThread([Names](){
|
||||
std::this_thread::sleep_for(10000ms);
|
||||
for(const auto &i:Names) {
|
||||
if(i=="daemon")
|
||||
Daemon()->Reload();
|
||||
else
|
||||
Daemon()->Reload(i);
|
||||
}
|
||||
});
|
||||
ReloadThread.detach();
|
||||
}
|
||||
OK();
|
||||
return;
|
||||
}
|
||||
if (!Poco::icompare(Command, RESTAPI::Protocol::TIMES)) {
|
||||
Poco::JSON::Array Array;
|
||||
Poco::JSON::Object Answer;
|
||||
Poco::JSON::Object UpTimeObj;
|
||||
UpTimeObj.set(RESTAPI::Protocol::TAG,RESTAPI::Protocol::UPTIME);
|
||||
UpTimeObj.set(RESTAPI::Protocol::VALUE, Daemon()->uptime().totalSeconds());
|
||||
Poco::JSON::Object StartObj;
|
||||
StartObj.set(RESTAPI::Protocol::TAG,RESTAPI::Protocol::START);
|
||||
StartObj.set(RESTAPI::Protocol::VALUE, Daemon()->startTime().epochTime());
|
||||
Array.add(UpTimeObj);
|
||||
Array.add(StartObj);
|
||||
Answer.set(RESTAPI::Protocol::TIMES, Array);
|
||||
ReturnObject(Request, Answer, Response);
|
||||
return;
|
||||
}
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
} else {
|
||||
BadRequest(RESTAPI::Errors::InvalidCommand);
|
||||
return;
|
||||
}
|
||||
BadRequest(Request, Response, "Unsupported or missing parameters.");
|
||||
BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
|
||||
}
|
||||
|
||||
void RESTAPI_system_command::DoGet() {
|
||||
std::string Arg;
|
||||
if(HasParameter("command",Arg) && Arg=="info") {
|
||||
Poco::JSON::Object Answer;
|
||||
Answer.set(RESTAPI::Protocol::VERSION, Daemon()->Version());
|
||||
Answer.set(RESTAPI::Protocol::UPTIME, Daemon()->uptime().totalSeconds());
|
||||
Answer.set(RESTAPI::Protocol::START, Daemon()->startTime().epochTime());
|
||||
Answer.set(RESTAPI::Protocol::OS, Poco::Environment::osName());
|
||||
Answer.set(RESTAPI::Protocol::PROCESSORS, Poco::Environment::processorCount());
|
||||
Answer.set(RESTAPI::Protocol::HOSTNAME, Poco::Environment::nodeName());
|
||||
|
||||
Poco::JSON::Array Certificates;
|
||||
auto SubSystems = Daemon()->GetFullSubSystems();
|
||||
std::set<std::string> CertNames;
|
||||
|
||||
for(const auto &i:SubSystems) {
|
||||
auto Hosts=i->HostSize();
|
||||
for(uint64_t j=0;j<Hosts;++j) {
|
||||
auto CertFileName = i->Host(j).CertFile();
|
||||
if(!CertFileName.empty()) {
|
||||
auto InsertResult = CertNames.insert(CertFileName);
|
||||
if(InsertResult.second) {
|
||||
Poco::JSON::Object Inner;
|
||||
Inner.set("filename", CertFileName);
|
||||
Poco::Crypto::X509Certificate C(CertFileName);
|
||||
auto ExpiresOn = C.expiresOn();
|
||||
Inner.set("expiresOn",ExpiresOn.timestamp().epochTime());
|
||||
Certificates.add(Inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Answer.set("certificates", Certificates);
|
||||
ReturnObject(Answer);
|
||||
return;
|
||||
}
|
||||
BadRequest(RESTAPI::Errors::InvalidCommand);
|
||||
}
|
||||
}
|
||||
@@ -14,19 +14,19 @@
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_system_command : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_system_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, bool Internal)
|
||||
RESTAPI_system_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST,
|
||||
Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
Internal) {}
|
||||
void handleRequest(Poco::Net::HTTPServerRequest &request,
|
||||
Poco::Net::HTTPServerResponse &response) override;
|
||||
static const std::list<const char *> PathName() { return std::list<const char *>{"/api/v1/system"};}
|
||||
void DoGet(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response);
|
||||
void DoPost(Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response);
|
||||
|
||||
void DoGet() final;
|
||||
void DoPost() final;
|
||||
void DoPut() final {};
|
||||
void DoDelete() final {};
|
||||
};
|
||||
}
|
||||
#endif // UCENTRALGW_RESTAPI_SYSTEM_COMMAND_H
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
int Storage::Start() {
|
||||
SubMutexGuard Guard(Mutex_);
|
||||
std::lock_guard Guard(Mutex_);
|
||||
|
||||
Logger_.setLevel(Poco::Message::PRIO_NOTICE);
|
||||
Logger_.notice("Starting.");
|
||||
@@ -61,7 +61,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void Storage::Stop() {
|
||||
SubMutexGuard Guard(Mutex_);
|
||||
std::lock_guard Guard(Mutex_);
|
||||
Logger_.notice("Stopping.");
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ namespace OpenWifi {
|
||||
bool AddHistory(FMSObjects::RevisionHistoryEntry &History);
|
||||
|
||||
void PopulateLatestFirmwareCache();
|
||||
void RemoveOldFirmware();
|
||||
|
||||
int Start() override;
|
||||
void Stop() override;
|
||||
|
||||
@@ -32,6 +32,7 @@ void SubSystemServer::initialize(Poco::Util::Application &self) {
|
||||
auto i = 0;
|
||||
bool good = true;
|
||||
|
||||
ConfigServersList_.clear();
|
||||
while (good) {
|
||||
std::string root{SubSystemConfigPrefix_ + ".host." + std::to_string(i) + "."};
|
||||
|
||||
@@ -81,10 +82,11 @@ void SubSystemServer::initialize(Poco::Util::Application &self) {
|
||||
}
|
||||
}
|
||||
|
||||
void SubSystemServer::uninitialize() {}
|
||||
void SubSystemServer::uninitialize() {
|
||||
}
|
||||
|
||||
void SubSystemServer::reinitialize(Poco::Util::Application &self) {
|
||||
// add your own reinitialization code here
|
||||
Logger_.information("Reloading of this subsystem is not supported.");
|
||||
}
|
||||
|
||||
void SubSystemServer::defineOptions(Poco::Util::OptionSet &options) {}
|
||||
|
||||
@@ -20,9 +20,6 @@
|
||||
|
||||
#include "Poco/Net/X509Certificate.h"
|
||||
|
||||
using SubMutex = std::recursive_mutex;
|
||||
using SubMutexGuard = std::lock_guard<SubMutex>;
|
||||
|
||||
namespace OpenWifi {
|
||||
class PropertiesFileServerEntry {
|
||||
public:
|
||||
@@ -79,7 +76,8 @@ class SubSystemServer : public Poco::Util::Application::Subsystem {
|
||||
inline const std::string & Name() const { return Name_; };
|
||||
const char * name() const override { return Name_.c_str(); }
|
||||
|
||||
const PropertiesFileServerEntry &Host(int index) { return ConfigServersList_[index]; };
|
||||
const PropertiesFileServerEntry & Host(uint64_t index) { return ConfigServersList_[index]; };
|
||||
uint64_t HostSize() const { return ConfigServersList_.size(); }
|
||||
Poco::Logger &Logger() { return Logger_; };
|
||||
void SetLoggingLevel(Poco::Message::Priority NewPriority) { Logger_.setLevel(NewPriority); }
|
||||
int GetLoggingLevel() { return Logger_.getLevel(); }
|
||||
@@ -87,11 +85,11 @@ class SubSystemServer : public Poco::Util::Application::Subsystem {
|
||||
virtual void Stop() = 0;
|
||||
|
||||
protected:
|
||||
SubMutex Mutex_{};
|
||||
Poco::Logger &Logger_;
|
||||
std::string Name_;
|
||||
std::recursive_mutex Mutex_;
|
||||
Poco::Logger &Logger_;
|
||||
std::string Name_;
|
||||
std::vector<PropertiesFileServerEntry> ConfigServersList_;
|
||||
std::string SubSystemConfigPrefix_;
|
||||
std::string SubSystemConfigPrefix_;
|
||||
};
|
||||
}
|
||||
#endif //UCENTRAL_SUBSYSTEMSERVER_H
|
||||
|
||||
@@ -151,7 +151,7 @@ namespace OpenWifi::Utils {
|
||||
if(input.length() % 4)
|
||||
throw std::runtime_error("Invalid base64 length!");
|
||||
|
||||
std::size_t padding{};
|
||||
std::size_t padding=0;
|
||||
|
||||
if(input.length())
|
||||
{
|
||||
@@ -162,7 +162,7 @@ namespace OpenWifi::Utils {
|
||||
std::vector<byte> decoded;
|
||||
decoded.reserve(((input.length() / 4) * 3) - padding);
|
||||
|
||||
std::uint32_t temp{};
|
||||
std::uint32_t temp=0;
|
||||
auto it = input.begin();
|
||||
|
||||
while(it < input.end())
|
||||
@@ -488,67 +488,4 @@ namespace OpenWifi::Utils {
|
||||
return Result;
|
||||
}
|
||||
|
||||
static bool cidr_match(const in_addr &addr, const in_addr &net, uint8_t bits) {
|
||||
if (bits == 0) {
|
||||
return true;
|
||||
}
|
||||
return !((addr.s_addr ^ net.s_addr) & htonl(0xFFFFFFFFu << (32 - bits)));
|
||||
}
|
||||
|
||||
static bool cidr6_match(const in6_addr &address, const in6_addr &network, uint8_t bits) {
|
||||
#ifdef __linux__
|
||||
const uint32_t *a = address.s6_addr32;
|
||||
const uint32_t *n = network.s6_addr32;
|
||||
#else
|
||||
const uint32_t *a = address.__u6_addr.__u6_addr32;
|
||||
const uint32_t *n = network.__u6_addr.__u6_addr32;
|
||||
#endif
|
||||
int bits_whole, bits_incomplete;
|
||||
bits_whole = bits >> 5; // number of whole u32
|
||||
bits_incomplete = bits & 0x1F; // number of bits in incomplete u32
|
||||
if (bits_whole) {
|
||||
if (memcmp(a, n, bits_whole << 2)!=0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (bits_incomplete) {
|
||||
uint32_t mask = htonl((0xFFFFFFFFu) << (32 - bits_incomplete));
|
||||
if ((a[bits_whole] ^ n[bits_whole]) & mask) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool ConvertStringToLong(const char *S, unsigned long &L) {
|
||||
char *end;
|
||||
L = std::strtol(S,&end,10);
|
||||
return end != S;
|
||||
}
|
||||
|
||||
bool IPinRange(const std::string &Range, const Poco::Net::IPAddress &IP) {
|
||||
Poco::StringTokenizer TimeTokens(Range,"/",Poco::StringTokenizer::TOK_TRIM);
|
||||
|
||||
Poco::Net::IPAddress RangeIP;
|
||||
if(Poco::Net::IPAddress::tryParse(TimeTokens[0],RangeIP)) {
|
||||
if(TimeTokens.count()==2) {
|
||||
if (RangeIP.family() == Poco::Net::IPAddress::IPv4) {
|
||||
unsigned long MaskLength;
|
||||
if (ConvertStringToLong(TimeTokens[1].c_str(), MaskLength)) {
|
||||
return cidr_match(*static_cast<const in_addr *>(RangeIP.addr()),
|
||||
*static_cast<const in_addr *>(IP.addr()), MaskLength);
|
||||
}
|
||||
} else if (RangeIP.family() == Poco::Net::IPAddress::IPv6) {
|
||||
unsigned long MaskLength;
|
||||
if (ConvertStringToLong(TimeTokens[1].c_str(), MaskLength)) {
|
||||
return cidr6_match(*static_cast<const in6_addr *>(RangeIP.addr()),
|
||||
*static_cast<const in6_addr *>(IP.addr()), MaskLength);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -71,11 +71,8 @@ namespace OpenWifi::Utils {
|
||||
|
||||
[[nodiscard]] MediaTypeEncoding FindMediaType(const Poco::File &F);
|
||||
[[nodiscard]] std::string BinaryFileToHexString( const Poco::File &F);
|
||||
|
||||
[[nodiscard]] std::string SecondsToNiceText(uint64_t Seconds);
|
||||
|
||||
[[nodiscard]] bool IPinRange(const std::string &Range, const Poco::Net::IPAddress &IP);
|
||||
|
||||
template< typename T >
|
||||
std::string int_to_hex( T i )
|
||||
{
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include "LatestFirmwareCache.h"
|
||||
#include "Daemon.h"
|
||||
#include <limits>
|
||||
#include "ManifestCreator.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
@@ -161,6 +162,23 @@ namespace OpenWifi {
|
||||
return false;
|
||||
}
|
||||
|
||||
void Storage::RemoveOldFirmware() {
|
||||
try {
|
||||
Poco::Data::Session Sess = Pool_->get();
|
||||
Poco::Data::Statement Delete(Sess);
|
||||
|
||||
std::cout << "Removing old firmware..." << std::endl;
|
||||
uint64_t Limit = std::time(nullptr) - ManifestCreator()->MaxAge();
|
||||
|
||||
std::string st{"DELETE FROM " + DBNAME_FIRMWARES + " WHERE imageDate<?"};
|
||||
Delete << ConvertParams(st),
|
||||
Poco::Data::Keywords::use(Limit);
|
||||
Delete.execute();
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
}
|
||||
}
|
||||
|
||||
bool Storage::GetFirmware(std::string & ID, FMSObjects::Firmware & F) {
|
||||
try {
|
||||
Poco::Data::Session Sess = Pool_->get();
|
||||
|
||||
@@ -88,6 +88,8 @@ namespace OpenWifi::uCentralProtocol {
|
||||
static const char * TIMESTAMP = "timestamp";
|
||||
static const char * SYSTEM = "system";
|
||||
static const char * HOST = "host";
|
||||
static const char * CONNECTIONIP = "connectionIp";
|
||||
static const char * TELEMETRY = "telemetry";
|
||||
|
||||
enum EVENT_MSG {
|
||||
ET_UNKNOWN,
|
||||
@@ -99,7 +101,8 @@ namespace OpenWifi::uCentralProtocol {
|
||||
ET_PING,
|
||||
ET_CFGPENDING,
|
||||
ET_RECOVERY,
|
||||
ET_DEVICEUPDATE
|
||||
ET_DEVICEUPDATE,
|
||||
ET_TELEMETRY
|
||||
};
|
||||
|
||||
static EVENT_MSG EventFromString(const std::string & Method) {
|
||||
@@ -121,6 +124,8 @@ namespace OpenWifi::uCentralProtocol {
|
||||
return ET_RECOVERY;
|
||||
} else if (!Poco::icompare(Method, DEVICEUPDATE)) {
|
||||
return ET_DEVICEUPDATE;
|
||||
} else if (!Poco::icompare(Method, TELEMETRY)) {
|
||||
return ET_TELEMETRY;
|
||||
} else
|
||||
return ET_UNKNOWN;
|
||||
};
|
||||
|
||||
@@ -20,10 +20,10 @@ then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "${UCENTRALSEC}" == "" ]]
|
||||
if [[ "${OWSEC}" == "" ]]
|
||||
then
|
||||
echo "You must set the variable UCENTRALSEC in order to use this script. Something like"
|
||||
echo "UCENTRALSEC=security.isp.com:16001"
|
||||
echo "You must set the variable OWSEC in order to use this script. Something like"
|
||||
echo "OWSEC=security.isp.com:16001"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -41,7 +41,7 @@ browser=""
|
||||
|
||||
login() {
|
||||
payload="{ \"userId\" : \"$username\" , \"password\" : \"$password\" }"
|
||||
token=$(curl ${FLAGS} -X POST -H "Content-Type: application/json" -d "$payload" "https://${UCENTRALSEC}/api/v1/oauth2" | jq -r '.access_token')
|
||||
token=$(curl ${FLAGS} -X POST -H "Content-Type: application/json" -d "$payload" "https://${OWSEC}/api/v1/oauth2" | jq -r '.access_token')
|
||||
|
||||
if [[ "${token}" == "" ]]
|
||||
then
|
||||
@@ -73,7 +73,7 @@ findbrowser() {
|
||||
}
|
||||
|
||||
setfms() {
|
||||
curl ${FLAGS} -X GET "https://${UCENTRALSEC}/api/v1/systemEndpoints" \
|
||||
curl ${FLAGS} -X GET "https://${OWSEC}/api/v1/systemEndpoints" \
|
||||
-H "accept: application/json" \
|
||||
-H "Authorization: Bearer ${token}" > ${result_file}
|
||||
# jq < ${result_file}
|
||||
@@ -93,7 +93,7 @@ setfms() {
|
||||
path="$(echo $url | grep / | cut -d/ -f2-)"
|
||||
if [[ ${url} != "null" ]]
|
||||
then
|
||||
if [[ ${svctype} == "ucentralfms" ]]
|
||||
if [[ ${svctype} == "owfms" ]]
|
||||
then
|
||||
# echo "url: $url"
|
||||
# echo " proto: $proto"
|
||||
@@ -101,102 +101,152 @@ setfms() {
|
||||
# echo " host: $host"
|
||||
# echo " port: $port"
|
||||
# echo " path: $path"
|
||||
UCENTRALFMS="${url}"
|
||||
OWFMS="${url}"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
done
|
||||
echo "Using ${UCENTRALFMS}..."
|
||||
echo "Using ${OWFMS}..."
|
||||
}
|
||||
|
||||
logout() {
|
||||
curl ${FLAGS} -X DELETE -H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"https://${UCENTRALSEC}/api/v1/oauth2/${token}"
|
||||
"https://${OWSEC}/api/v1/oauth2/${token}"
|
||||
rm -rf token.json
|
||||
}
|
||||
|
||||
getfirmwares() {
|
||||
curl ${FLAGS} -X GET -H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"https://${UCENTRALFMS}/api/v1/firmwares?deviceType=$1" > ${result_file}
|
||||
"https://${OWFMS}/api/v1/firmwares?deviceType=$1" > ${result_file}
|
||||
jq < ${result_file}
|
||||
}
|
||||
|
||||
latestfirmware() {
|
||||
curl ${FLAGS} -X GET -H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"https://${UCENTRALFMS}/api/v1/firmwares?latestOnly=true&deviceType=$1" > ${result_file}
|
||||
"https://${OWFMS}/api/v1/firmwares?latestOnly=true&deviceType=$1" > ${result_file}
|
||||
jq < ${result_file}
|
||||
}
|
||||
|
||||
revisions() {
|
||||
curl ${FLAGS} -X GET -H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"https://${UCENTRALFMS}/api/v1/firmwares?revisionSet=true" > ${result_file}
|
||||
"https://${OWFMS}/api/v1/firmwares?revisionSet=true" > ${result_file}
|
||||
jq < ${result_file}
|
||||
}
|
||||
|
||||
devicetypes() {
|
||||
curl ${FLAGS} -X GET -H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"https://${UCENTRALFMS}/api/v1/firmwares?deviceSet=true" > ${result_file}
|
||||
"https://${OWFMS}/api/v1/firmwares?deviceSet=true" > ${result_file}
|
||||
jq < ${result_file}
|
||||
}
|
||||
|
||||
firmwareage() {
|
||||
curl ${FLAGS} -G -H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"https://${UCENTRALFMS}/api/v1/firmwareAge" --data-urlencode "deviceType=$1" --data-urlencode "revision=$2" > ${result_file}
|
||||
"https://${OWFMS}/api/v1/firmwareAge" --data-urlencode "deviceType=$1" --data-urlencode "revision=$2" > ${result_file}
|
||||
jq < ${result_file}
|
||||
}
|
||||
|
||||
gethistory() {
|
||||
curl ${FLAGS} -X GET -H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"https://${UCENTRALFMS}/api/v1/revisionHistory/$1" > ${result_file}
|
||||
"https://${OWFMS}/api/v1/revisionHistory/$1" > ${result_file}
|
||||
jq < ${result_file}
|
||||
}
|
||||
|
||||
connecteddevice() {
|
||||
curl ${FLAGS} -X GET -H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"https://${UCENTRALFMS}/api/v1/connectedDevice/$1" > ${result_file}
|
||||
"https://${OWFMS}/api/v1/connectedDevice/$1" > ${result_file}
|
||||
jq < ${result_file}
|
||||
}
|
||||
|
||||
connecteddevices() {
|
||||
curl ${FLAGS} -X GET -H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"https://${UCENTRALFMS}/api/v1/connectedDevices" > ${result_file}
|
||||
"https://${OWFMS}/api/v1/connectedDevices" > ${result_file}
|
||||
jq < ${result_file}
|
||||
}
|
||||
|
||||
devicereport() {
|
||||
curl ${FLAGS} -X GET -H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"https://${UCENTRALFMS}/api/v1/deviceReport" > ${result_file}
|
||||
"https://${OWFMS}/api/v1/deviceReport" > ${result_file}
|
||||
jq < ${result_file}
|
||||
}
|
||||
|
||||
fmsversion() {
|
||||
curl ${FLAGS} -X GET "https://${UCENTRALFMS}/api/v1/system?command=version" \
|
||||
-H "accept: application/json" \
|
||||
-H "Authorization: Bearer ${token}" > ${result_file}
|
||||
setloglevel() {
|
||||
payload="{ \"command\" : \"setloglevel\" , \"subsystems\" : [ { \"tag\" : \"$1\" , \"value\" : \"$2\" } ] }"
|
||||
curl ${FLAGS} -X POST "https://${OWFMS}/api/v1/system" \
|
||||
-H "accept: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-d "$payload"
|
||||
}
|
||||
|
||||
getloglevels() {
|
||||
payload="{ \"command\" : \"getloglevels\" }"
|
||||
curl ${FLAGS} -X POST "https://${OWFMS}/api/v1/system" \
|
||||
-H "accept: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-d "$payload"
|
||||
}
|
||||
|
||||
getloglevelnames() {
|
||||
payload="{ \"command\" : \"getloglevelnames\" }"
|
||||
curl ${FLAGS} -X POST "https://${OWFMS}/api/v1/system" \
|
||||
-H "accept: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-d "$payload"
|
||||
}
|
||||
|
||||
getsubsystemnames() {
|
||||
payload="{ \"command\" : \"getsubsystemnames\" }"
|
||||
curl ${FLAGS} -X POST "https://${OWFMS}/api/v1/system" \
|
||||
-H "accept: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-d "$payload"
|
||||
}
|
||||
|
||||
systeminfo() {
|
||||
curl ${FLAGS} -X GET "https://${OWFMS}/api/v1/system?command=info" \
|
||||
-H "accept: application/json" \
|
||||
-H "Authorization: Bearer ${token}" > ${result_file}
|
||||
jq < ${result_file}
|
||||
}
|
||||
|
||||
fmstimes() {
|
||||
curl ${FLAGS} -X GET "https://${UCENTRALFMS}/api/v1/system?command=times" \
|
||||
-H "accept: application/json" \
|
||||
-H "Authorization: Bearer ${token}" > ${result_file}
|
||||
jq < ${result_file}
|
||||
reloadsubsystem() {
|
||||
payload="{ \"command\" : \"reload\", \"subsystems\" : [ \"$1\" ] }"
|
||||
curl ${FLAGS} -X POST "https://${OWFMS}/api/v1/system" \
|
||||
-H "accept: application/json" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-d "$payload"
|
||||
}
|
||||
|
||||
|
||||
help() {
|
||||
echo
|
||||
echo
|
||||
|
||||
echo "Usage: cli <cmd> [args]"
|
||||
echo
|
||||
echo "getfirmwares Get a lit of firmwares"
|
||||
echo "latestfirmware <device_type> Get the latest firmware for the device_type specified"
|
||||
echo "revisions Get a list of revisions available."
|
||||
echo "devicetypes Get the list of device types supported."
|
||||
echo "firmwareage <device_type> <revision> Calculate how out of date a specific release it."
|
||||
echo "gethistory <device serial number> Get the device firmware history."
|
||||
echo "connecteddevice <device serial number> Get the device status."
|
||||
echo "connectedDevices Get the list of connected devices."
|
||||
echo "devicereport Get the dashboard."
|
||||
echo "setloglevel <subsystem> <loglevel> Set the log level for s specific subsystem."
|
||||
echo "getloglevels Get the current log levels for all subsystems."
|
||||
echo "getloglevelnames Get the log level names available."
|
||||
echo "getsubsystemnames Get the list of subsystems."
|
||||
echo "systeminfo Get basic system information."
|
||||
echo "reloadsubsystem <subsystem name> Reload the configuration for a subsystem."
|
||||
echo
|
||||
echo
|
||||
}
|
||||
|
||||
shopt -s nocasematch
|
||||
@@ -211,8 +261,12 @@ case "$1" in
|
||||
"connecteddevices") login; connecteddevices ; logout ;;
|
||||
"connecteddevice") login; connecteddevice "$2" ; logout ;;
|
||||
"devicereport") login; devicereport; logout ;;
|
||||
"fmsversion") login; fmsversion; logout ;;
|
||||
"fmstimes") login; fmstimes; logout ;;
|
||||
"setloglevel") login; setloglevel "$2" "$3" ; logout ;;
|
||||
"getloglevels") login; getloglevels; logout ;;
|
||||
"getloglevelnames") login; getloglevelnames; logout ;;
|
||||
"getsubsystemnames") login; getsubsystemnames; logout ;;
|
||||
"reloadsubsystem") login; reloadsubsystem "$2"; logout ;;
|
||||
"systeminfo") login; systeminfo ; logout;;
|
||||
*) help ;;
|
||||
esac
|
||||
|
||||
|
||||
Reference in New Issue
Block a user