Skip to content
Snippets Groups Projects
Commit 12df8404 authored by Amin Ben Romdhane's avatar Amin Ben Romdhane
Browse files

Added support for DeviceInfo object

parent 0651008d
Branches
No related tags found
1 merge request!1Added support for DeviceInfo object
Pipeline #179718 passed
Showing
with 1397 additions and 0 deletions
src/sysmngr
src/*.o
src/*.so
variables:
SOURCE_FOLDER: "src"
CFLAGS: "-DBBF_VENDOR_PREFIX=\\\"X_IOPSYS_EU_\\\""
include:
- project: 'iopsys/gitlab-ci-pipeline'
file: '/static-code-analysis.yml'
ref: '1.2'
stages:
- static_code_analysis
LICENSE 0 → 100644
BSD 3-Clause License
Copyright (c) 2024, IOPSYS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
title: "System Manager"
nav:
- "arch"
- "api"
- "spec"
- "guide"
- "..."
title: "System Manager"
nav:
- "..."
title: "System Manager"
hide: true
title: "System Manager"
nav:
- "..."
# Design For Firmware Activation
According to the TR181 data model, the Activate() command is an operation to activate the firmware image immediately or schedule it in another time.
In fact, the Linux system already provides us a cron to schedule some jobs. And since Openwrt is one of the Linux systems, so we can use a cron job as solution to handle the firmware activation.
The Activate() command has as arguments the TimeWindow object which is used to activate the required firmware in a specified time. For that, foreach TimeWindow instance a cron job will be created.
> Note: As per TR181 data model, max 5 instances of TimeWindow is supported.
Below is an example of an 'Activate()' command call with three TimeWindow instances. As a result, three jobs are created according to the defined TimeWindow.{i}.Start:
```bash
root@iopsys-44d43771aff0:~# ubus call bbfdm operate '{"path":"Device.DeviceInfo.FirmwareImage.2.", "action":"Activate()", "input":{"TimeWindow.1
.Start":"1800", "TimeWindow.1.End":"3600", "TimeWindow.1.Mode":"WhenIdle", "TimeWindow.2.Start":"5400", "TimeWindow.2.End":"9000", "TimeWindow
.2.Mode":"WhenIdle", "TimeWindow.3.Start":"86400", "TimeWindow.3.End":"172800", "TimeWindow.3.Mode":"Immediately"}}'
{
"Results": [
{
"path": "Device.DeviceInfo.FirmwareImage.2.Activate()",
"result": [
{
}
]
}
]
}
root@iopsys-44d43771aff0:~# crontab -l
52 22 21 2 * sh /usr/share/bbfdm/scripts/bbf_activate_handler.sh 'WhenIdle' '2' '1800' '0' '' ''
52 23 21 2 * sh /usr/share/bbfdm/scripts/bbf_activate_handler.sh 'WhenIdle' '2' '3600' '0' '' ''
22 22 22 2 * sh /usr/share/bbfdm/scripts/bbf_activate_handler.sh 'Immediately' '2' '86400' '1' '' ''
root@iopsys-44d43771aff0:~#
```
For those cron jobs it is required to give the handler script to be executed which is in our case [bbf_activate_handler.sh](../../libbbfdm/scripts/bbf_activate_handler.sh). And, it is located under '/usr/share/bbfdm/' in the device.
## Cron job specification
For each cron job related to the activated firmware, it is needed to define it as below:
```bash
* * * * * command to execute * * * * * *
- - - - - - - - - - - -
| | | | | | | | | | | |
| | | | | | | | | | | --- Message that informs the user of a new activation request
| | | | | | | | | | ----- Maximum number of retries
| | | | | | | | | ------- Force firmware activation when it's not idle (0 - 1)
| | | | | | | | --------- End of the time window
| | | | | | | ----------- Firmware Bank id to be activated
| | | | | | ------------- Mode (AnyTime, Immediately, WhenIdle, ConfirmationNeeded)
| | | | | -------------------------------- Activate firmware script 'bbf_activate_handler.sh'
| | | | ---------------------------------- Day of week (0 - 6) (Sunday =0)
| | | ------------------------------------ Month (1 - 12)
| | -------------------------------------- Day (1 - 31)
| ---------------------------------------- Hour (0 - 23)
------------------------------------------ Minute (0 - 59)
```
## Activate Handler script
As described, we create a cron job for each TimeWindow in order to activate the required firmware within a specified time by running the [bbf_activate_handler.sh](../../libbbfdm/scripts/bbf_activate_handler.sh) handler script.
In fact, the aim of this script is to manage firmware images based on the **mode** and the other passed arguments.
### 1. Mode 'AnyTime' and 'Immediately':
For these modes and based on the firmware bank id, the required firmware image will be immediately activated at start time. The TimeWindow.{i}.End is ignored.
### 2. How to handle 'WhenIdle' mode:
Definition of WhenIdle may vary for each deployment and customer, to make it customizable [bbf_check_idle.sh](../../libbbfdm/scripts/bbf_check_idle.sh) script is used. It is assumed that customer shall overwrite this file using customer-config to match with there requirement.
In this mode, [bbf_activate_handler.sh](../../libbbfdm/scripts/bbf_activate_handler.sh) script calls this script [bbf_check_idle.sh](../../libbbfdm/scripts/bbf_check_idle.sh) to determine the idle state of the device. [bbf_activate_handler.sh](../../libbbfdm/scripts/bbf_activate_handler.sh) assumes the device as idle if the exit status of the above script is 0, or if the [bbf_check_idle.sh](../../libbbfdm/scripts/bbf_check_idle.sh) is not present in the predefined path "ACTIVATE_HANDLER_FILE@dmcommon.h".
If the exit code from the idle script is zero then firmware image can be activated. Otherwise, it has to wait for next time slot which is defined by 'RETRY_TIME' variable.
> Note1: The time slot is set through 'RETRY_TIME' variable which is defined under '/usr/share/bbfdm/scripts/bbf_activate_handler.sh' script.
> Note2: The exit status of the script [bbf_check_idle.sh](../../libbbfdm/scripts/bbf_check_idle.sh) is important because based on it, the '[bbf_activate_handler.sh](../../libbbfdm/scripts/bbf_activate_handler.sh) script will decide whether the image can be activated or not.
> Note3: Algorithm/Logic to determine the Idle state of device is out of scope of this document and it is expected that users overwrite this script with the logic to determine the same in actual deployment.
> Note4: If 1 or more TimeWindow.{i}.Mode is set to 'WhenIdle' and all of them fails to get the idle state. The latest TimeWindow instance will force the device to activate the firmware image.
> Note5: If the idle script [bbf_check_idle.sh](../../libbbfdm/scripts/bbf_check_idle.sh) not present in the pre-defined path "ACTIVATE_HANDLER_FILE@dmcommon.h", then the device is assumed to be in ideal state and the firmware shall be activated instantly.
> Note6: It is very likely that TimeWindow with 'WhenIdle' mode might not find any suitable Idle state, in that case firmware shall not be activated. If users/operators want to make sure that firmware gets activated at the end, then they can add a TimeWindow with 'AnyTime/Immediate' mode at the end, to activate the firmware.
## Good to know
* TimeWindow instance arguments are optional.
* TimeWindow instances attributes must not overlap.
* If TimeWindow.{i}.Start is set, TimeWindow.{i}.End and TimeWindow.{i}.Mode become mondatory.
* The firmware activation is done by [bbf_activate_handler.sh](../../libbbfdm/scripts/bbf_activate_handler.sh) script as per the defined Mode in TimeWindow, but if the TimeWindow is not defined, it will activate the requested FirmwareImage instance immediately.
* If the customer wants to be sure that the required firmware is getting activated at the end then they can define the TimeWindow.{i}.Mode as 'AnyTime' or 'Immediately' in the last TimeWindow instance.
* This document is only target for Firmware management using USP.
* TimeWindow.{i}.Mode = 'ConfirmationNeeded' is not supported.
## Vendor extension option to keep config while firmware download
It deployments for some customers, its required to do a factory reset after doing a firmware upgrade to start the CPE from clean state and then provision it from ACS/Controller.
As per standard datamodel, it's at-least 2 step time consuming process:
- Download the Firmware using 'Device.DeviceInfo.FirmwareImage.{i}.Download()' operate command with AutoActivate=1
- Wait for the 'Device.Boot!' event
- Factory reset the CPE using 'Device.FactoryReset()'
- Wait for the Boot event and then start provisioning.
We added an addition vendor specific input option which can be used by USP controller to factoryReset the CPE along with Firmware Upgrade, with this customer can save the cost of one additional reboot, which result into faster provisioning of the CPE.
Below are the current input options defined for Download operate command
```bash
Device.DeviceInfo.FirmwareImage.{i}.Download()
Device.DeviceInfo.FirmwareImage.{i}.Download() input:AutoActivate
Device.DeviceInfo.FirmwareImage.{i}.Download() input:CheckSum
Device.DeviceInfo.FirmwareImage.{i}.Download() input:CheckSumAlgorithm
Device.DeviceInfo.FirmwareImage.{i}.Download() input:CommandKey
Device.DeviceInfo.FirmwareImage.{i}.Download() input:FileSize
Device.DeviceInfo.FirmwareImage.{i}.Download() input:Password
Device.DeviceInfo.FirmwareImage.{i}.Download() input:URL
Device.DeviceInfo.FirmwareImage.{i}.Download() input:Username
Device.DeviceInfo.FirmwareImage.{i}.Download() input:X_IOPSYS_EU_KeepConfig
```
Customer can use X_IOPSYS_EU_KeepConfig=0, to do factory reset(not copy the current config to next firmware) while doing the download.
> Note: Default value of X_IOPSYS_EU_KeepConfig is 1, so in case this option not used, it keeps the config(as the default behavior of the CPE).
# Design for Reboot Data Model
In TR-181 version 2.18, a new object, Device.DeviceInfo.Reboots, was introduced to track and monitor reboot operations. This object provides details such as reboot reasons, counts, timestamps, and more, offering a comprehensive view of the device's state. It simplifies diagnostics and troubleshooting for applications and processes running on the device.
Currently, there is no standard configuration mapping to this object. However, we propose introducing a custom config called `deviceinfo` to manage this information effectively.
The idea is to maintain a 1-to-1 mapping between the parameters and UCI config. To achieve this, we need to create an `init.d` service script that generates a UCI section each time the boot() function is called. Essentially, when the boot() function is executed, it will check the `/tmp/reset_reason` file for specific markers, such as (reset reason) and (reset triggered), to identify the cause of the last boot. And based on these markers, it will calculate the required counter for data model parameters and commit the changes in `deviceinfo.globals` section. Furthermore, if necessary, it will create a UCI reboot section by checking `deviceinfo.globals.max_reboot_entries` and adjusting the config accordingly.
This approach ensures that the data model maps directly to UCI config as closely as possible, eliminating the need for any adjustments at the data model layer.
## Parameter Mapping Details
- Device.DeviceInfo.Reboots.BootCount: Maps to deviceinfo.globals.boot_count. This value is determined based on the marker (reset triggered: defaultreset) defined in `/tmp/reset_reason` file.
- Device.DeviceInfo.Reboots.CurrentVersionBootCount: Maps to deviceinfo.globals.curr_version_boot_count. This value is determined based on the marker (reset triggered: upgrade) defined in `/tmp/reset_reason` file.
- Device.DeviceInfo.Reboots.WatchdogBootCount: Maps to deviceinfo.globals.watchdog_boot_count. This value is determined based on the marker (reset reason: WATCHDOG) defined in `/tmp/reset_reason` file.
- Device.DeviceInfo.Reboots.ColdBootCount:
- Device.DeviceInfo.Reboots.WarmBootCount:
- Device.DeviceInfo.Reboots.MaxRebootEntries: Maps to deviceinfo.globals.max_reboot_entries. Possible values include {-1, 0, etc..}. Each case will be handled internally by bbfdm and default value is 3 and maximum reboot entry supported is 255.
- Device.DeviceInfo.Reboots.RebootNumberOfEntries: This is an internal bbfdm mechanism used to count the number of reboot entries.
- Device.DeviceInfo.Reboots.RemoveAllReboots(): An internal bbfdm API to remove all reboot sections.
- Device.DeviceInfo.Reboots.Reboot.{i}.: Each reboot entry is stored in a 'reboot' section.
- Device.DeviceInfo.Reboots.Reboot.{i}.Alias: Maps to deviceinfo.reboot[i].alias. This is managed internally by bbfdm.
- Device.DeviceInfo.Reboots.Reboot.{i}.TimeStamp: Maps to deviceinfo.reboot[i].time_stamp. This value is based on system uptime.
- Device.DeviceInfo.Reboots.Reboot.{i}.FirmwareUpdated: Maps to deviceinfo.reboot[i].firmware_updated.
- Device.DeviceInfo.Reboots.Reboot.{i}.Cause: Maps to deviceinfo.reboot[i].cause. Possible values include {LocalReboot, RemoteReboot, FactoryReset, LocalFactoryReset, RemoteFactoryReset}.
- Device.DeviceInfo.Reboots.Reboot.{i}.Reason: Maps to deviceinfo.reboot[i].reason. This value is determined based on the marker (reset reason) defined in `/tmp/reset_reason` file.
- Device.DeviceInfo.Reboots.Reboot.{i}.Remove(): An internal bbfdm API to remove the current 'reboot' section.
## Example Configuration
Below is an example of the configuration file:
```bash
cat /etc/config/deviceinfo
config globals 'globals'
option boot_count '2'
option curr_version_boot_count '4'
option watchdog_boot_count '3'
option cold_boot_count '2'
option warm_boot_count '2'
option max_reboot_entries '3'
config reboot 'reboot_1'
option alias 'cpe-1'
option time_stamp '2024-09-22T20:34:45Z'
option firmware_updated '0'
option cause 'RemoteReboot'
option reason 'REBOOT'
config reboot 'reboot_2'
option alias 'cpe-2'
option time_stamp '2024-09-22T21:55:09Z'
option firmware_updated '0'
option cause 'LocalReboot'
option reason 'POR_RESET'
config reboot 'reboot_3'
option alias 'cpe-3'
option time_stamp '2024-09-23T04:11:24Z'
option firmware_updated '1'
option cause 'LocalReboot'
option reason 'upgrade'
config reboot 'reboot_4'
option alias 'cpe-4'
option time_stamp '2024-09-23T04:15:53Z'
option firmware_updated '0'
option cause 'RemoteFactoryReset'
option reason 'REBOOT'
```
title: "System Manager"
hide: true
#!/bin/bash
echo "install dependencies for tests"
source ./gitlab-ci/shared.sh
# install bbfdm
install_bbfdm
#!/bin/bash
function exec_cmd()
{
echo "executing $@"
$@ >/dev/null 2>&1
if [ $? -ne 0 ]; then
echo "Failed to execute $@"
exit 1
fi
}
function install_bbfdm()
{
[ -d "/opt/dev/bbfdm" ] && return 0
if [ -n "${BBFDM_BRANCH}" ]; then
exec_cmd git clone -b ${BBFDM_BRANCH} https://dev.iopsys.eu/bbf/bbfdm.git /opt/dev/bbfdm
else
exec_cmd git clone -b sysmngr https://dev.iopsys.eu/bbf/bbfdm.git /opt/dev/bbfdm
fi
cd /opt/dev/bbfdm
./gitlab-ci/install-dependencies.sh install
./gitlab-ci/setup.sh install
}
PROG = sysmngr
OBJS = sysmngr.o deviceinfo.o utils.o
PROG_CFLAGS = $(CFLAGS) -Wall -Werror -fstrict-aliasing -g
PROG_LDFLAGS = $(LDFLAGS) -luci -lubus -lubox -lblobmsg_json -ljson-c -lssl -lcrypto -lbbfdm-ubus -lbbfdm-api
FPIC := -fPIC
ifeq ($(SYSMNGR_VENDOR_CONFIG_FILE),y)
OBJS += configs.o
PROG_CFLAGS += -DSYSMNGR_VENDOR_CONFIG_FILE
endif
ifeq ($(SYSMNGR_MEMORY_STATUS),y)
OBJS += memory.o
PROG_CFLAGS += -DSYSMNGR_MEMORY_STATUS
endif
ifeq ($(SYSMNGR_PROCESS_STATUS),y)
OBJS += processes.o
PROG_CFLAGS += -DSYSMNGR_PROCESS_STATUS
endif
ifeq ($(SYSMNGR_SUPPORTED_DATA_MODEL),y)
OBJS += supported_dm.o
PROG_CFLAGS += -DSYSMNGR_SUPPORTED_DATA_MODEL
endif
ifeq ($(SYSMNGR_FIRMWARE_IMAGE),y)
OBJS += fw_images.o
PROG_CFLAGS += -DSYSMNGR_FIRMWARE_IMAGE
endif
ifeq ($(SYSMNGR_REBOOTS),y)
OBJS += reboots.o
PROG_CFLAGS += -DSYSMNGR_REBOOTS
endif
ifeq ($(SYSMNGR_VENDOR_EXTENSIONS),y)
PROG_CFLAGS += -DSYSMNGR_VENDOR_EXTENSIONS
endif
.PHONY: all clean
%.o: %.c
$(CC) $(PROG_CFLAGS) $(FPIC) -c -o $@ $<
all: $(PROG)
$(PROG): $(OBJS)
$(CC) $(PROG_CFLAGS) -o $@ $^ $(PROG_LDFLAGS)
clean:
rm -f *.o $(PROG)
/*
* Copyright (C) 2019-2024 iopsys Software Solutions AB
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation
*
* Author: Amin Ben Romdhane <amin.benromdhane@iopsys.eu>
*
*/
#include "utils.h"
#define CONFIG_BACKUP "/tmp/bbf_config_backup"
/*************************************************************
* COMMON FUNCTIONS
**************************************************************/
static int dmmap_synchronizeVcfInst(struct dmctx *dmctx, DMNODE *parent_node, void *prev_data, char *prev_instance)
{
struct uci_section *s = NULL, *stmp = NULL;
DIR *dir;
struct dirent *d_file;
sysfs_foreach_file(DEFAULT_CONFIG_DIR, dir, d_file) {
if(d_file->d_name[0] == '.')
continue;
if (!is_dmmap_section_exist_eq("dmmap", "vcf", "name", d_file->d_name)) {
dmuci_add_section_bbfdm("dmmap", "vcf", &s);
dmuci_set_value_by_section(s, "name", d_file->d_name);
dmuci_set_value_by_section(s, "backup_restore", "1");
}
}
if (dir)
closedir (dir);
uci_path_foreach_sections_safe(bbfdm, "dmmap", "vcf", stmp, s) {
char cfg_path[128] = {0};
char *cfg_name = NULL;
dmuci_get_value_by_section_string(s, "name", &cfg_name);
snprintf(cfg_path, sizeof(cfg_path), "%s%s", DEFAULT_CONFIG_DIR, cfg_name);
if (!file_exists(cfg_path))
dmuci_delete_by_section_bbfdm(s, NULL, NULL);
}
return 0;
}
static int bbf_config_backup(const char *url, const char *username, const char *password,
char *config_name, const char *command, const char *obj_path)
{
int res = 0;
char fault_msg[128] = {0};
time_t complete_time = 0;
time_t start_time = time(NULL);
// Export config file to backup file
if (dmuci_export_package(config_name, CONFIG_BACKUP)) {
snprintf(fault_msg, sizeof(fault_msg), "Failed to export the configurations");
res = -1;
goto end;
}
// Upload the config file
long res_code = upload_file(CONFIG_BACKUP, url, username, password);
complete_time = time(NULL);
// Check if the upload operation was successful
if (!validate_server_response_code(url, res_code)) {
res = -1;
snprintf(fault_msg, sizeof(fault_msg), "Upload operation is failed, fault code (%ld)", res_code);
}
end:
// Send the transfer complete event
send_transfer_complete_event(command, obj_path, url, fault_msg, start_time, complete_time, NULL, "Upload");
// Remove temporary file
if (file_exists(CONFIG_BACKUP) && remove(CONFIG_BACKUP))
res = -1;
return res;
}
static int bbf_config_restore(const char *url, const char *username, const char *password,
const char *file_size, const char *checksum_algorithm, const char *checksum,
const char *command, const char *obj_path)
{
char config_restore[256] = {0};
int res = 0;
char fault_msg[128] = {0};
time_t complete_time = 0;
time_t start_time = time(NULL);
DM_STRNCPY(config_restore, "/tmp/bbf_config_restore", sizeof(config_restore));
// Check the file system size if there is sufficient space for downloading the config file
if (!validate_file_system_size(file_size)) {
snprintf(fault_msg, sizeof(fault_msg), "Available memory space is less than required for the operation");
res = -1;
goto end;
}
// Download the firmware image
long res_code = download_file(config_restore, url, username, password);
complete_time = time(NULL);
// Check if the download operation was successful
if (!validate_server_response_code(url, res_code)) {
snprintf(fault_msg, sizeof(fault_msg), "Upload operation is failed, fault code (%ld)", res_code);
res = -1;
goto end;
}
// Validate the CheckSum value according to its algorithm
if (!validate_checksum_value(config_restore, checksum_algorithm, checksum)) {
snprintf(fault_msg, sizeof(fault_msg), "Checksum of the downloaded file is mismatched");
res = -1;
goto end;
}
// Apply config file
if (dmuci_import(NULL, config_restore)) {
snprintf(fault_msg, sizeof(fault_msg), "Failed to import the configurations");
res = -1;
}
end:
// Send the transfer complete event
send_transfer_complete_event(command, obj_path, url, fault_msg, start_time, complete_time, NULL, "Download");
// Remove temporary file
if (file_exists(config_restore) && strncmp(url, FILE_URI, strlen(FILE_URI)) && remove(config_restore))
res = -1;
return res;
}
/*************************************************************
* ENTRY METHOD
**************************************************************/
int browseVcfInst(struct dmctx *dmctx, DMNODE *parent_node, void *prev_data, char *prev_instance)
{
struct dm_data curr_data = {0};
struct uci_section *s = NULL;
char *inst = NULL;
dmmap_synchronizeVcfInst(dmctx, parent_node, prev_data, prev_instance);
uci_path_foreach_sections(bbfdm, "dmmap", "vcf", s) {
curr_data.config_section = s;
inst = handle_instance(dmctx, parent_node, s, "vcf_instance", "vcf_alias");
if (DM_LINK_INST_OBJ(dmctx, parent_node, (void *)&curr_data, inst) == DM_STOP)
break;
}
return 0;
}
/*************************************************************
* GET & SET PARAM
**************************************************************/
int get_DeviceInfo_VendorConfigFileNumberOfEntries(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
int cnt = get_number_of_entries(ctx, data, instance, browseVcfInst);
dmasprintf(value, "%d", cnt);
return 0;
}
static int get_vcf_name(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_value_by_section_string(((struct dm_data *)data)->config_section, "name", value);
return 0;
}
static int get_vcf_version(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_value_by_section_string(((struct dm_data *)data)->config_section, "version", value);
return 0;
}
static int get_vcf_date(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
DIR *dir = NULL;
struct dirent *d_file = NULL;
char *config_name = NULL;
*value = dmstrdup("0001-01-01T00:00:00Z");
dmuci_get_value_by_section_string(((struct dm_data *)data)->config_section, "name", &config_name);
if ((dir = opendir (DEFAULT_CONFIG_DIR)) != NULL) {
while ((d_file = readdir (dir)) != NULL) {
if (config_name && DM_STRCMP(config_name, d_file->d_name) == 0) {
char date[sizeof("AAAA-MM-JJTHH:MM:SSZ")], path[280] = {0};
struct stat attr;
snprintf(path, sizeof(path), "%s%s", DEFAULT_CONFIG_DIR, d_file->d_name);
stat(path, &attr);
strftime(date, sizeof(date), "%Y-%m-%dT%H:%M:%SZ", gmtime(&attr.st_mtime));
*value = dmstrdup(date);
}
}
closedir (dir);
}
return 0;
}
static int get_vcf_backup_restore(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_value_by_section_string(((struct dm_data *)data)->config_section, "backup_restore", value);
return 0;
}
static int get_vcf_desc(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_value_by_section_string(((struct dm_data *)data)->config_section, "description", value);
return 0;
}
static int get_vcf_alias(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
return bbf_get_alias(ctx, ((struct dm_data *)data)->config_section, "vcf_alias", instance, value);
}
static int set_vcf_alias(char *refparam, struct dmctx *ctx, void *data, char *instance, char *value, int action)
{
return bbf_set_alias(ctx, ((struct dm_data *)data)->config_section, "vcf_alias", instance, value);
}
/*************************************************************
* OPERATE COMMANDS
*************************************************************/
static operation_args vendor_config_file_backup_args = {
.in = (const char *[]) {
"URL",
"Username",
"Password",
NULL
}
};
static int get_operate_args_DeviceInfoVendorConfigFile_Backup(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
*value = (char *)&vendor_config_file_backup_args;
return 0;
}
static int operate_DeviceInfoVendorConfigFile_Backup(char *refparam, struct dmctx *ctx, void *data, char *instance, char *value, int action)
{
const char *backup_command = "Backup()";
char backup_path[256] = {'\0'};
char *vcf_name = NULL;
char *ret = DM_STRRCHR(refparam, '.');
if (!ret)
return USP_FAULT_INVALID_ARGUMENT;
if ((ret - refparam + 2) < sizeof(backup_path))
snprintf(backup_path, ret - refparam + 2, "%s", refparam);
char *url = dmjson_get_value((json_object *)value, 1, "URL");
if (url[0] == '\0')
return USP_FAULT_INVALID_ARGUMENT;
char *user = dmjson_get_value((json_object *)value, 1, "Username");
char *pass = dmjson_get_value((json_object *)value, 1, "Password");
dmuci_get_value_by_section_string(((struct dm_data *)data)->config_section, "name", &vcf_name);
int res = bbf_config_backup(url, user, pass, vcf_name, backup_command, backup_path);
return res ? USP_FAULT_COMMAND_FAILURE : 0;
}
static operation_args vendor_config_file_restore_args = {
.in = (const char *[]) {
"URL",
"Username",
"Password",
"FileSize",
"TargetFileName",
"CheckSumAlgorithm",
"CheckSum",
NULL
}
};
static int get_operate_args_DeviceInfoVendorConfigFile_Restore(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
*value = (char *)&vendor_config_file_restore_args;
return 0;
}
static int operate_DeviceInfoVendorConfigFile_Restore(char *refparam, struct dmctx *ctx, void *data, char *instance, char *value, int action)
{
const char *restore_command = "Restore()";
char restore_path[256] = {'\0'};
char *ret = DM_STRRCHR(refparam, '.');
if (!ret)
return USP_FAULT_INVALID_ARGUMENT;
if ((ret - refparam + 2) < sizeof(restore_path))
snprintf(restore_path, ret - refparam + 2, "%s", refparam);
char *url = dmjson_get_value((json_object *)value, 1, "URL");
if (url[0] == '\0')
return USP_FAULT_INVALID_ARGUMENT;
char *user = dmjson_get_value((json_object *)value, 1, "Username");
char *pass = dmjson_get_value((json_object *)value, 1, "Password");
char *file_size = dmjson_get_value((json_object *)value, 1, "FileSize");
char *checksum_algorithm = dmjson_get_value((json_object *)value, 1, "CheckSumAlgorithm");
char *checksum = dmjson_get_value((json_object *)value, 1, "CheckSum");
int res = bbf_config_restore(url, user, pass, file_size, checksum_algorithm, checksum, restore_command, restore_path);
return res ? USP_FAULT_COMMAND_FAILURE : 0;
}
/**********************************************************************************************************************************
* OBJ & LEAF DEFINITION
***********************************************************************************************************************************/
/* *** Device.DeviceInfo.VendorConfigFile.{i}. *** */
DMLEAF tDeviceInfoVendorConfigFileParams[] = {
/* PARAM, permission, type, getvalue, setvalue, bbfdm_type, version*/
{"Alias", &DMWRITE, DMT_STRING, get_vcf_alias, set_vcf_alias, BBFDM_BOTH, DM_FLAG_UNIQUE},
{"Name", &DMREAD, DMT_STRING, get_vcf_name, NULL, BBFDM_BOTH, DM_FLAG_UNIQUE},
{"Version", &DMREAD, DMT_STRING, get_vcf_version, NULL, BBFDM_BOTH},
{"Date", &DMREAD, DMT_TIME, get_vcf_date, NULL, BBFDM_BOTH},
{"Description", &DMREAD, DMT_STRING, get_vcf_desc, NULL, BBFDM_BOTH},
{"UseForBackupRestore", &DMREAD, DMT_BOOL, get_vcf_backup_restore, NULL, BBFDM_BOTH},
{"Backup()", &DMASYNC, DMT_COMMAND, get_operate_args_DeviceInfoVendorConfigFile_Backup, operate_DeviceInfoVendorConfigFile_Backup, BBFDM_USP},
{"Restore()", &DMASYNC, DMT_COMMAND, get_operate_args_DeviceInfoVendorConfigFile_Restore, operate_DeviceInfoVendorConfigFile_Restore, BBFDM_USP},
{0}
};
/*
* Copyright (C) 2019-2024 iopsys Software Solutions AB
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation
*
* Author: Amin Ben Romdhane <amin.benromdhane@iopsys.eu>
*
*/
#ifndef __CONFIGS_H
#define __CONFIGS_H
extern DMLEAF tDeviceInfoVendorConfigFileParams[];
int browseVcfInst(struct dmctx *dmctx, DMNODE *parent_node, void *prev_data, char *prev_instance);
int get_DeviceInfo_VendorConfigFileNumberOfEntries(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value);
#endif //__CONFIGS_H
{
"Device.": {
"type": "object",
"protocols": [
"cwmp",
"usp"
],
"description": "The top-level object for a Device.",
"access": false,
"array": false,
"Device.DeviceInfo.": {
"type": "object",
"protocols": [
"cwmp",
"usp"
],
"description": "This object contains general device information.",
"access": false,
"array": false,
"{BBF_VENDOR_PREFIX}BaseMACAddress": {
"type": "string",
"read": true,
"write": false,
"protocols": [
"cwmp",
"usp"
],
"description": "The MAC Address of the device.",
"datatype": "MACAddress",
"range": [
{
"max": 17
}
],
"pattern": [
"",
"([0-9A-Fa-f][0-9A-Fa-f]:){5}([0-9A-Fa-f][0-9A-Fa-f])"
]
}
}
}
}
/*
* Copyright (C) 2019-2024 iopsys Software Solutions AB
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation
*
* Author: Amin Ben Romdhane <amin.benromdhane@iopsys.eu>
*
*/
#include <libbbfdm-api/dmcommon.h>
#ifdef SYSMNGR_VENDOR_CONFIG_FILE
#include "configs.h"
#endif
#ifdef SYSMNGR_FIRMWARE_IMAGE
#include "fw_images.h"
#endif
#ifdef SYSMNGR_MEMORY_STATUS
#include "memory.h"
#endif
#ifdef SYSMNGR_PROCESS_STATUS
#include "processes.h"
#endif
#ifdef SYSMNGR_REBOOTS
#include "reboots.h"
#endif
#ifdef SYSMNGR_SUPPORTED_DATA_MODEL
#include "supported_dm.h"
#endif
/*************************************************************
* GET & SET PARAM
**************************************************************/
static int get_device_devicecategory(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
db_get_value_string("device", "deviceinfo", "DeviceCategory", value);
return 0;
}
static int get_device_manufacturer(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_option_value_string("cwmp","cpe","manufacturer", value);
if (*value[0] == '\0')
db_get_value_string("device", "deviceinfo", "Manufacturer", value);
return 0;
}
static int get_device_manufactureroui(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_option_value_string("cwmp", "cpe", "manufacturer_oui", value);
if (*value[0] == '\0')
db_get_value_string("device", "deviceinfo", "ManufacturerOUI", value);
return 0;
}
static int get_device_modelname(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_option_value_string("cwmp", "cpe", "model_name", value);
if (*value[0] == '\0')
db_get_value_string("device", "deviceinfo", "ModelName", value);
return 0;
}
static int get_device_description(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_option_value_string("cwmp", "cpe", "description", value);
if (*value[0] == '\0')
db_get_value_string("device", "deviceinfo", "Description", value);
return 0;
}
static int get_device_productclass(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_option_value_string("cwmp", "cpe", "product_class", value);
if (*value[0] == '\0')
db_get_value_string("device", "deviceinfo", "ProductClass", value);
return 0;
}
static int get_device_serialnumber(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_option_value_string("cwmp", "cpe", "serial_number", value);
if (*value[0] == '\0')
db_get_value_string("device", "deviceinfo", "SerialNumber", value);
return 0;
}
static int get_device_hardwareversion(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
db_get_value_string("device", "deviceinfo", "HardwareVersion", value);
return 0;
}
static int get_device_softwareversion(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_option_value_string("cwmp", "cpe", "software_version", value);
if (*value[0] == '\0')
db_get_value_string("device", "deviceinfo", "SoftwareVersion", value);
return 0;
}
static int get_device_additionalhardwareversion(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
db_get_value_string("device", "deviceinfo", "AdditionalHardwareVersion", value);
return 0;
}
static int get_device_additionalsoftwareversion(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
db_get_value_string("device", "deviceinfo", "AdditionalSoftwareVersion", value);
return 0;
}
static int get_device_provisioningcode(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
char *dhcp = NULL, *provisioning_code = NULL, *dhcp_provisioning_code = NULL;
bool discovery = false;
dmuci_get_option_value_string("cwmp", "acs", "dhcp_discovery", &dhcp);
dmuci_get_option_value_string("cwmp", "cpe", "provisioning_code", &provisioning_code);
dmuci_get_option_value_string("cwmp", "cpe", "dhcp_provisioning_code", &dhcp_provisioning_code);
discovery = dmuci_string_to_boolean(dhcp);
if ((discovery == true) && (DM_STRLEN(dhcp_provisioning_code) != 0))
*value = dhcp_provisioning_code;
else
*value = provisioning_code;
return 0;
}
static int set_device_provisioningcode(char *refparam, struct dmctx *ctx, void *data, char *instance, char *value, int action)
{
switch (action) {
case VALUECHECK:
if (bbfdm_validate_string(ctx, value, -1, 64, NULL, NULL))
return FAULT_9007;
return 0;
case VALUESET:
dmuci_set_value("cwmp", "cpe", "provisioning_code", value);
return 0;
}
return 0;
}
static int get_device_info_uptime(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
*value = get_uptime();
return 0;
}
static int get_device_info_firstusedate(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_option_value_string("time", "global", "first_use_date", value);
return 0;
}
static int get_deviceinfo_cid (char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
db_get_value_string("device", "deviceinfo", "CID", value);
return 0;
}
static int get_deviceinfo_friendlyname(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
db_get_value_string("device", "deviceinfo", "FriendlyName", value);
return 0;
}
static int get_deviceinfo_pen (char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
db_get_value_string("device", "deviceinfo", "PEN", value);
return 0;
}
static int get_deviceinfo_modelnumber (char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
db_get_value_string("device", "deviceinfo", "ModelNumber", value);
return 0;
}
static int get_DeviceInfo_HostName(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
dmuci_get_option_value_string("system", "@system[0]", "hostname", value);
return 0;
}
static int set_DeviceInfo_HostName(char *refparam, struct dmctx *ctx, void *data, char *instance, char *value, int action)
{
switch (action) {
case VALUECHECK:
if (bbfdm_validate_string(ctx, value, -1, 255, NULL, NULL))
return FAULT_9007;
break;
case VALUESET:
dmuci_set_value("system", "@system[0]", "hostname", value);
break;
}
return 0;
}
#ifdef SYSMNGR_VENDOR_EXTENSIONS
static int get_deviceinfo_base_mac_addr(char *refparam, struct dmctx *ctx, void *data, char *instance, char **value)
{
db_get_value_string("device", "deviceinfo", "BaseMACAddress", value);
return 0;
}
#endif
/**********************************************************************************************************************************
* OBJ & LEAF DEFINITION
***********************************************************************************************************************************/
/* *** Device.DeviceInfo. *** */
DMOBJ tDeviceInfoObj[] = {
/* OBJ, permission, addobj, delobj, checkdep, browseinstobj, nextdynamicobj, dynamicleaf, nextobj, leaf, linker, bbfdm_type*/
#ifdef SYSMNGR_VENDOR_CONFIG_FILE
{"VendorConfigFile", &DMREAD, NULL, NULL, NULL, browseVcfInst, NULL, NULL, NULL, tDeviceInfoVendorConfigFileParams, NULL, BBFDM_BOTH},
#endif
#ifdef SYSMNGR_MEMORY_STATUS
{"MemoryStatus", &DMREAD, NULL, NULL, NULL, NULL, NULL, NULL, NULL, tDeviceInfoMemoryStatusParams, NULL, BBFDM_BOTH},
#endif
#ifdef SYSMNGR_PROCESS_STATUS
{"ProcessStatus", &DMREAD, NULL, NULL, NULL, NULL, NULL, NULL, tDeviceInfoProcessStatusObj, tDeviceInfoProcessStatusParams, NULL, BBFDM_BOTH},
#endif
#ifdef SYSMNGR_SUPPORTED_DATA_MODEL
{"SupportedDataModel", &DMREAD, NULL, NULL, NULL, browseDeviceInfoSupportedDataModelInst, NULL, NULL, NULL, tDeviceInfoSupportedDataModelParams, NULL, BBFDM_CWMP},
#endif
#ifdef SYSMNGR_FIRMWARE_IMAGE
{"FirmwareImage", &DMREAD, NULL, NULL, "file:/usr/libexec/rpcd/fwbank", browseDeviceInfoFirmwareImageInst, NULL, NULL, NULL, tDeviceInfoFirmwareImageParams, NULL, BBFDM_BOTH},
#endif
#ifdef SYSMNGR_REBOOTS
{"Reboots", &DMREAD, NULL, NULL, NULL, NULL, NULL, NULL, tDeviceInfoRebootsObj, tDeviceInfoRebootsParams, NULL, BBFDM_USP},
#endif
{0}
};
DMLEAF tDeviceInfoParams[] = {
/* PARAM, permission, type, getvalue, setvalue, bbfdm_type*/
{"DeviceCategory", &DMREAD, DMT_STRING, get_device_devicecategory, NULL, BBFDM_BOTH},
{"Manufacturer", &DMREAD, DMT_STRING, get_device_manufacturer, NULL, BBFDM_BOTH},
{"ManufacturerOUI", &DMREAD, DMT_STRING, get_device_manufactureroui, NULL, BBFDM_BOTH},
{"ModelName", &DMREAD, DMT_STRING, get_device_modelname, NULL, BBFDM_BOTH},
{"Description", &DMREAD, DMT_STRING, get_device_description, NULL, BBFDM_BOTH},
{"ProductClass", &DMREAD, DMT_STRING, get_device_productclass, NULL, BBFDM_BOTH},
{"SerialNumber", &DMREAD, DMT_STRING, get_device_serialnumber, NULL, BBFDM_BOTH},
{"HardwareVersion", &DMREAD, DMT_STRING, get_device_hardwareversion, NULL, BBFDM_BOTH},
{"SoftwareVersion", &DMREAD, DMT_STRING, get_device_softwareversion, NULL, BBFDM_BOTH},
{"AdditionalHardwareVersion", &DMREAD, DMT_STRING, get_device_additionalhardwareversion, NULL, BBFDM_BOTH},
{"AdditionalSoftwareVersion", &DMREAD, DMT_STRING, get_device_additionalsoftwareversion, NULL, BBFDM_BOTH},
{"ProvisioningCode", &DMWRITE, DMT_STRING, get_device_provisioningcode, set_device_provisioningcode, BBFDM_BOTH},
{"UpTime", &DMREAD, DMT_UNINT, get_device_info_uptime, NULL, BBFDM_BOTH},
{"FirstUseDate", &DMREAD, DMT_TIME, get_device_info_firstusedate, NULL, BBFDM_BOTH},
{"CID", &DMREAD, DMT_STRING, get_deviceinfo_cid, NULL, BBFDM_USP},
{"FriendlyName", &DMREAD, DMT_STRING, get_deviceinfo_friendlyname, NULL, BBFDM_USP},
{"PEN", &DMREAD, DMT_STRING, get_deviceinfo_pen, NULL, BBFDM_USP},
{"ModelNumber", &DMREAD, DMT_STRING, get_deviceinfo_modelnumber, NULL, BBFDM_BOTH},
{"HostName", &DMWRITE, DMT_STRING, get_DeviceInfo_HostName, set_DeviceInfo_HostName, BBFDM_BOTH},
#ifdef SYSMNGR_VENDOR_CONFIG_FILE
{"VendorConfigFileNumberOfEntries", &DMREAD, DMT_UNINT, get_DeviceInfo_VendorConfigFileNumberOfEntries, NULL, BBFDM_BOTH},
#endif
#ifdef SYSMNGR_SUPPORTED_DATA_MODEL
{"SupportedDataModelNumberOfEntries", &DMREAD, DMT_UNINT, get_DeviceInfo_SupportedDataModelNumberOfEntries, NULL, BBFDM_CWMP},
#endif
#ifdef SYSMNGR_FIRMWARE_IMAGE
{"ActiveFirmwareImage", &DMREAD, DMT_STRING, get_device_active_fwimage, NULL, BBFDM_BOTH, DM_FLAG_REFERENCE},
{"BootFirmwareImage", &DMWRITE, DMT_STRING, get_device_boot_fwimage, set_device_boot_fwimage, BBFDM_BOTH, DM_FLAG_REFERENCE},
{"MaxNumberOfActivateTimeWindows", &DMREAD, DMT_UNINT, get_DeviceInfo_MaxNumberOfActivateTimeWindows, NULL, BBFDM_USP},
{"FirmwareImageNumberOfEntries", &DMREAD, DMT_UNINT, get_DeviceInfo_FirmwareImageNumberOfEntries, NULL, BBFDM_BOTH},
#endif
#ifdef SYSMNGR_VENDOR_EXTENSIONS
{BBF_VENDOR_PREFIX"BaseMACAddress", &DMREAD, DMT_STRING, get_deviceinfo_base_mac_addr, NULL, BBFDM_BOTH},
#endif
{0}
};
/* *** Device. *** */
DMOBJ tDMDeviceInfoObj[] = {
/* OBJ, permission, addobj, delobj, checkdep, browseinstobj, nextdynamicobj, dynamicleaf, nextobj, leaf, linker, bbfdm_type*/
{"DeviceInfo", &DMREAD, NULL, NULL, NULL, NULL, NULL, NULL, tDeviceInfoObj, tDeviceInfoParams, NULL, BBFDM_BOTH},
{0}
};
DM_MAP_OBJ tDynamicObj[] = {
/* parentobj, nextobject, parameter */
{"Device.", tDMDeviceInfoObj, NULL},
{0}
};
#!/bin/sh
# Script to activate image in specified time.
#
# Copyright © 2022 IOPSYS Software Solutions AB
# Author: Amin Ben Romdhane <amin.benromdhane@iopsys.eu>
#
ROOT="$(dirname "${0}")"
CHECK_IDLE_FILE="${ROOT}/bbf_check_idle.sh"
RETRY_TIME=300
START_TIME=$(date +%s)
MODE="${1}"
log() {
echo "${@}"|logger -t bbf.activate_firmware -p info
}
activate_and_reboot_device() {
local bank_id="${1}"
local success
success=$(ubus call fwbank set_bootbank "{'bank':${bank_id}}" | jsonfilter -e @.success)
if [ "${success}" != "true" ]; then
log "Can't activate the bank id ${bank_id}"
exit 1
fi
log "The device will restart after a few seconds"
ubus call rpc-sys reboot
exit 0
}
handle_whenidle_mode() {
local bank_id="${1}"
local end_time="${2}"
local force_activation="${3}"
local diff=0
[ ! -x "${CHECK_IDLE_FILE}" ] && {
activate_and_reboot_device "${bank_id}"
}
sh "${CHECK_IDLE_FILE}"
if [ "$?" = "0" ]; then
activate_and_reboot_device "${bank_id}"
else
[ "${end_time}" -gt "$((diff + RETRY_TIME))" ] && {
sleep "${RETRY_TIME}"
}
diff=$(($(date +%s) - START_TIME))
fi
while [ "${end_time}" -gt "${diff}" ]; do
sh "${CHECK_IDLE_FILE}"
if [ "$?" = "0" ]; then
activate_and_reboot_device "${bank_id}"
else
if [ "${end_time}" -gt "$((diff + RETRY_TIME))" ]; then
sleep "${RETRY_TIME}"
else
break
fi
diff=$(($(date +%s) - START_TIME))
fi
done
[ "${force_activation}" = "1" ] && {
activate_and_reboot_device "${bank_id}"
}
}
handle_confirmation_needed_mode() {
log "[ConfirmationNeeded] mode is not implemented"
exit 0
}
######################## main ########################
if [ "${MODE}" = "Immediately" ] || [ "${MODE}" = "AnyTime" ]; then
activate_and_reboot_device "${2}"
elif [ "${MODE}" = "WhenIdle" ]; then
handle_whenidle_mode "${2}" "${3}" "${4}"
elif [ "${MODE}" = "ConfirmationNeeded" ]; then
handle_confirmation_needed_mode "${2}" "${3}" "${4}" "${5}" "${6}"
else
log "[${MODE}] mode is not supported"
exit 1
fi
#!/bin/sh
# Script to check idle state
#
# This script is used to determine if the device is in idle state or not
# And any idle state checking should be implemented here
# The value returned by this script is more important because based on it, will decide whether the image can be activated or not
# If (returned idle state == '0'), device is in idle state and can be activated. Otherwise, '1'
exit 0
\ No newline at end of file
#!/bin/sh
# Script to handle Reboots Object
#
# Copyright © 2024 IOPSYS Software Solutions AB
# Author: Amin Ben Romdhane <amin.benromdhane@iopsys.eu>
#
. /lib/functions.sh
RESET_REASON_PATH="/tmp/reset_reason"
MAX_RETRIES=3
RETRY_DELAY=1
log() {
echo "$@" | logger -t bbf_reboot -p info
}
reset_option_counter() {
local option_name=$1
local option_value=$2
uci_set "deviceinfo" "globals" "${option_name}" "${option_value}"
}
increment_option_counter() {
local option_name=$1
local option_value=$(uci_get "deviceinfo" "globals" "${option_name}" "0")
local counter=$((option_value + 1))
uci_set "deviceinfo" "globals" "${option_name}" "$counter"
}
get_boot_trigger() {
local trigger
trigger=$(grep "triggered" ${RESET_REASON_PATH} | cut -d ':' -f2 | xargs)
echo "${trigger}"
}
get_boot_reason() {
local reason
reason=$(grep "reason" ${RESET_REASON_PATH} | cut -d ':' -f2 | xargs)
echo "${reason}"
}
calculate_boot_time() {
# Get current time and uptime in seconds
local current_time uptime_seconds boot_time boot_time_formatted
current_time=$(date +%s)
uptime_seconds=$(awk '{print $1}' /proc/uptime | cut -d. -f1)
# Calculate the boot time by subtracting the uptime from the current time
boot_time=$((current_time - uptime_seconds))
# Convert the boot time to a human-readable format
boot_time_formatted=$(date -d "@$boot_time" +"%Y-%m-%dT%H:%M:%SZ")
echo "${boot_time_formatted}"
}
boot_reason_message() {
# Generate a human-readable message based on the boot reason and trigger
local trigger reason
trigger=$(get_boot_trigger)
if [ -n "${trigger}" ]; then
case "${trigger}" in
"defaultreset")
echo "FACTORY RESET"
;;
"upgrade")
echo "FIRMWARE UPGRADE"
;;
*)
echo "${trigger}"
;;
esac
else
reason=$(get_boot_reason)
case "${reason}" in
"POR_RESET")
echo "POWER ON RESET"
;;
*)
echo "${reason}"
;;
esac
fi
}
create_reboot_section() {
local trigger=$1
local reboot_sec
reboot_sec="reboot_$(date +%Y%m%d%H%M%S)"
uci_add "deviceinfo" "reboot" "${reboot_sec}"
uci_set "deviceinfo" "${reboot_sec}" "time_stamp" "$(calculate_boot_time)"
if [ "${trigger}" = "upgrade" ]; then
uci_set "deviceinfo" "${reboot_sec}" "firmware_updated" "1"
else
uci_set "deviceinfo" "${reboot_sec}" "firmware_updated" "0"
fi
if [ "${trigger}" = "defaultreset" ]; then
uci_set "deviceinfo" "${reboot_sec}" "cause" "FactoryReset"
else
local last_reboot_cause
last_reboot_cause=$(uci_get "deviceinfo" "globals" "last_reboot_cause" "LocalReboot")
uci_set "deviceinfo" "${reboot_sec}" "cause" "${last_reboot_cause}"
uci_set "deviceinfo" "globals" "last_reboot_cause" ""
fi
uci_set "deviceinfo" "${reboot_sec}" "reason" "$(boot_reason_message)"
}
handle_reboot_action() {
local trigger reason max_reboot_entries retry_count reboot_sec_num
retry_count=0
# Retry fetching the reset reason file
while [ ! -f "${RESET_REASON_PATH}" ] && [ $retry_count -lt $MAX_RETRIES ]; do
log "Warning: '${RESET_REASON_PATH}' not found. Attempt $((retry_count + 1)) of ${MAX_RETRIES}"
sleep $RETRY_DELAY
retry_count=$((retry_count + 1))
done
if [ ! -f "${RESET_REASON_PATH}" ]; then
log "Error: '${RESET_REASON_PATH}' is not generated after ${MAX_RETRIES} attempts!!!"
return 1
fi
uci_load "deviceinfo"
trigger=$(get_boot_trigger)
reason=$(get_boot_reason)
# Reset or increment boot counter based on trigger
if [ "${trigger}" = "defaultreset" ]; then
## Reset all counters ##
reset_option_counter "boot_count" "1"
reset_option_counter "curr_version_boot_count" "0"
reset_option_counter "watchdog_boot_count" "0"
reset_option_counter "cold_boot_count" "0"
reset_option_counter "warm_boot_count" "0"
else
# Incrementing boot counter
increment_option_counter "boot_count"
fi
# Reset or increment current version boot counter based on trigger
if [ "${trigger}" = "upgrade" ]; then
# Resetting current version boot counter
reset_option_counter "curr_version_boot_count" "1"
else
# Incrementing current version boot counter
increment_option_counter "curr_version_boot_count"
fi
# Increment watchdog boot counter if the reason indicates a watchdog reset
if echo "${reason}" | grep -qi "watchdog"; then
# Incrementing watchdog boot counter
increment_option_counter "watchdog_boot_count"
fi
# Increment cold or warm boot counter based on the reason
if [ "${reason}" = "POR_RESET" ]; then
increment_option_counter "cold_boot_count"
else
increment_option_counter "warm_boot_count"
fi
# Get the max reboot entries
max_reboot_entries=$(uci_get "deviceinfo" "globals" "max_reboot_entries" "3")
if [ "${max_reboot_entries}" -eq 0 ]; then
# Commit the UCI changes to persist the configuration
uci_commit "deviceinfo"
return 0
fi
if [ $max_reboot_entries -gt 0 ]; then
# Calculate the number of reboot sections in the config
reboot_sec_num=$(uci -q show deviceinfo | grep "=reboot" | wc -l)
# Delete excess reboot sections if they exceed the max reboot entries
if [ "${reboot_sec_num}" -ge "${max_reboot_entries}" ]; then
local diff=$((reboot_sec_num - max_reboot_entries + 1))
for i in $(seq 1 $diff); do
uci_remove "deviceinfo" "@reboot[0]"
done
fi
fi
# Create a new reboot section with the current boot information
create_reboot_section "${trigger}"
# Commit the UCI changes to persist the configuration
uci_commit "deviceinfo"
}
# Run the main function
handle_reboot_action
exit 0
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment