Skip to content

Conversation

@devkapilbansal
Copy link
Member

Closes #57

Removed logger calls to simplify the script

exit 1
fi
[ "$interval" -lt 1 ] && log -e "Interval is invalid. Use time value(eg: '10', '2m', '3h', '1d')"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we move all these checks to the agent as @feckert did recently in openwisp-config?
So we avoid to define the log function twice which is really bad.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left it here and instead send it to stderr because this will come when invalid value is provided in interval

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may do similar kind of refactoring here to as done in openwisp-config in future

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, see @feckert's proposals: openwisp/openwisp-config#109

@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch 2 times, most recently from be929b2 to 46dad97 Compare October 15, 2021 21:11
@devkapilbansal
Copy link
Member Author

This PR is tested and it works as expected. I will rebase and mark is as Ready for Review once #72 is merged

@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch from 46dad97 to 395d66e Compare October 19, 2021 17:38
Copy link
Member

@nemesifier nemesifier left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just merged #72 🚀

@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch from 395d66e to 2f48c70 Compare October 20, 2021 06:26
@devkapilbansal devkapilbansal changed the base branch from issues/46-delete-old-data to master October 20, 2021 06:26
@devkapilbansal devkapilbansal marked this pull request as ready for review October 20, 2021 21:58
Copy link
Member

@nemesifier nemesifier left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left one comment below.

@feckert would be good if you could double check this as well.

;;
-*)
echo "Invalid option: $1"
exit 1
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this exit 1 removed? Does echoerr returns non zero exit code or what?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

echoerr is defined above that echo the message to standard error and returns exit 1 too

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exit 1
fi
[ "$interval" -lt 1 ] && log -e "Interval is invalid. Use time value(eg: '10', '2m', '3h', '1d')"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, see @feckert's proposals: openwisp/openwisp-config#109

type="$2"
shift 2

if [ "$type" = "-v" ] && [ "$VERBOSE_MODE" -ne "1" ]; then
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the stupid question. What is the use case of the option -v?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To check if we are in verbose mode or not. By using -v option, message will be logged in verbose mode only

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't do it like that.
That's what the different log levels are for.
I would add an additional debug log-level here.
If the log-level of the software (your script) is higher than the log-level of the log message, then this message is not logged and so not displayed.

The option for the shell script is extended by the option --log-level.
This are the following options that could be used:

  • error
  • warn
  • info
  • debug
    Each message has one of this log-level.

I think this is more common.

log warn "Not enough memory available, skipping collect data."

or

log info "SIGUSR1 received! Sending data"

This is the loglevel handling in the kernel but this does also work for the userland.
https://www.linuxtopia.org/online_books/linux_kernel/kernel_configuration/re06.html

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@feckert some programs do have their own verbosity level, think of openvpn. Here it's a similar case but simpler. In verbose mode we make debugging easier.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@feckert BTW in recent OpenWrt versions filtering out log levels doesn't work because the logd implementation doesn't support it.

@devkapilbansal devkapilbansal marked this pull request as draft November 17, 2021 22:07
@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch from 9eb15c2 to d54c2a4 Compare November 18, 2021 15:17
@devkapilbansal devkapilbansal marked this pull request as ready for review November 18, 2021 15:19
@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch from d54c2a4 to 9e5f570 Compare November 18, 2021 15:20
@github-actions
Copy link

sh-checker report

To get the full details, please check in the job output.

shellcheck errors

'shellcheck ' returned error 1 finding the following syntactical issues:

----------

In monitoring_init line 15:
		local cfg="$1"
                ^-------^ SC3043: In POSIX sh, 'local' is undefined.


In monitoring_init line 16:
		local flag="$2"
                ^--------^ SC3043: In POSIX sh, 'local' is undefined.


In monitoring_init line 17:
		local option="$3"
                ^----------^ SC3043: In POSIX sh, 'local' is undefined.


In monitoring_init line 18:
		local default="$4"
                ^-----------^ SC3043: In POSIX sh, 'local' is undefined.


In monitoring_init line 19:
		local value
                ^---------^ SC3043: In POSIX sh, 'local' is undefined.

For more information:
  https://www.shellcheck.net/wiki/SC3043 -- In POSIX sh, 'local' is undefined.
----------

You can address the above issues in one of three ways:
1. Manually correct the issue in the offending shell script;
2. Disable specific issues by adding the comment:
  # shellcheck disable=NNNN
above the line that contains the issue, where NNNN is the error code;
3. Add '-e NNNN' to the SHELLCHECK_OPTS setting in your .yml action file.



shfmt errors
'shfmt ' found no issues.

@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch from 9e5f570 to 7fec7f7 Compare November 18, 2021 15:42
Copy link
Member

@nemesifier nemesifier left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @devkapilbansal! I think we should revamp this!

@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch from 7fec7f7 to b47e2a5 Compare January 13, 2023 18:44
Copy link
Member

@nemesifier nemesifier left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work @devkapilbansal, I spotted some minor typos and I think there's room for improvement to avoid repetition and simplifying the code further, please see below.

[ "$VERBOSE_MODE" -eq "1" ] \
&& logger -s "Not enough memory available, skipping collect data." \
-p daemon.warn
log -w -v "Not enough memory available, skipping collect data."
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After reading this code now.. it seems to me that this message shouldn't be logged only in verbose mode because it is not a condition which should happen often and when it happens we most likely want to know. What do you think?

I would change this in a separate commit/PR though, not now. Let's maintain the behavior unaltered in this PR.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, let's say that the memory is full. Then after every 5 mins this message will be logged unless the memory is freed once again. I thought that it will add unnecessary noise.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@devkapilbansal I think the openwrt logger allocates a certain amount of memory for its logging, it automatically deletes old log lines from memory to make room for new lines, therefore we should be fine, the logger will fille up with this message but it's fine, we definitely want to know if this happens. Without doing this, in most cases when memory runs out, we won't understand what's going on without switching to verbose mode.

-t openwisp-monitoring \
-p daemon.err
[ "$VERBOSE_MODE" -ne "1" ] && log -e -n "Data not sent successfully. Response code is \"$response_code\"." \
"Run with verbose mode to find more."
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's still repetition here which makes the code hard to read.
I think we need to edit the log function to avoid this.

Ideally we could do something like:

log -e -n "Data not sent successfully. Response code is \"$response_code\"." \
    -v "Error message is $error_message"

The non verbose output should be printed also in verbose mode, while the verbose output is appended to the non verbose output but only when in verbose mode, so in non verbose mode we would have:

Data not sent successfully. Response code is "400".`

While in verbose mode we would have:

Data not sent successfully. Response code is "400". Error message is ERROR_MESSAGE_HERE.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The condition is here to ensure that the logs are not added unnecessarily when the connection is interrupted due to some issue for a long time.

Discussed here in "Non-verbose mode" #42 (review)

if [ "$FAILING" -eq "1" ]; then
FAILING=0
rm -f "$RESPONSE_FILE"
[ "$VERBOSE_MODE" -ne "1" ] && log -i -n "Data sent successfully."
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: Data sent successfully. is repeated twice and there's another unnecessary if here.

Copy link
Member Author

@devkapilbansal devkapilbansal Jan 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added this so that we don't fill logs uncessarily when data is transferred normally. In non-verbose mode, it will add this log "Data sent successfully" only once and the line will appear again if the connection is interrupted.
If the variable FAILING is set to 1, then only this line will be logged.

@nemesifier nemesifier moved this to Ready for review/testing in 25.09 Release Sep 3, 2025
@nemesifier nemesifier moved this from Ready for review/testing to Backlog in 25.09 Release Oct 16, 2025
@github-project-automation github-project-automation bot moved this to In progress in 26.05 Release Jan 20, 2026
@nemesifier nemesifier moved this from In progress to Ready for review/testing in 26.05 Release Jan 20, 2026
@nemesifier
Copy link
Member

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Jan 20, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link

coderabbitai bot commented Jan 20, 2026

📝 Walkthrough

Walkthrough

Adds centralized logging and interval parsing to the agent and consolidates option assembly in the init script. monitoring.agent: introduces public log() and time_to_seconds(), replaces many direct or verbose-guarded logger calls with log(), validates INTERVAL via time_to_seconds(), adjusts messaging, tracks consecutive successful sends and inserts a randomized pause every 10 successes, and refines HTTP 404 handling. monitoring.init: adds add_option() to build command-line parameters from config, removes inline interval parsing, and creates separate procd instances for send_data and collect_data; minor lifecycle message punctuation updates.

Sequence Diagram(s)

sequenceDiagram
    participant Init as Init (monitoring.init)
    participant Agent as Agent (monitoring.agent)
    participant Collector as Collector (collect process)
    participant Server as HTTP API

    Init->>Agent: start send procd instance (PROG + add_option args)
    Init->>Collector: start collect procd instance (PROG + add_option args)
    Collector->>Agent: invoke collect_data -> produce payload
    Agent->>Server: POST /data (send_data)
    alt 200 OK
        Server-->>Agent: 200 Success
        Agent->>Agent: increment success_count
        alt success_count % 10 == 0
            Agent->>Agent: sleep(random pause)
        end
        Agent->>Init: log("data sent") via log()
    else 404 Not Found
        Server-->>Agent: 404
        Agent->>Agent: log("device may be deleted") via log()
        Agent->>Collector: continue (no forced exit)
    else other error
        Server-->>Agent: error
        Agent->>Agent: log("send error") and handle retries
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title mentions moving logger calls into a subroutine, which aligns with the main change of creating a log() wrapper function, though it could be more specific about the actual refactoring scope.
Description check ✅ Passed The description is minimal but covers the core change (removed logger calls to simplify the script) and references the linked issue #57. However, it lacks detail on implementation approach and omits several template sections like manual testing confirmation and documentation updates.
Linked Issues check ✅ Passed The PR successfully implements the core requirement from issue #57 by consolidating logger calls into a single log() wrapper function across both affected files (monitoring.agent and monitoring.init), reducing code repetition and improving clarity.
Out of Scope Changes check ✅ Passed While the PR includes scope creep beyond the original logger consolidation (time_to_seconds() utility, add_option helper, error handling refinements, and server throttling), these changes appear to be complementary refactoring aimed at improving overall code quality and maintainability.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@nemesifier nemesifier changed the title [enhancement] Move logger calls in subroutine #57 [chores] Move logger calls in subroutine #57 Jan 20, 2026
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@openwisp-monitoring/files/monitoring.agent`:
- Around line 98-104: The failure message is never logged because the loop
checks [ "$n" -eq 5 ] before incrementing n; update the retry logic in the until
loop that runs /usr/sbin/netjson-monitoring so the log -e -v "Collecting data
failed!" is executed when the final retry fails: either move the logging check
to after n=$((n + 1)) or change the condition to test for the last attempt
(e.g., [ "$n" -eq 4 ] or [ "$n" -ge 5 ]) so that when netjson-monitoring
(invoked with "$MONITORED_INTERFACES") has exhausted retries the log call inside
the loop runs; keep the loop structure with the variable n and the existing log
-e -v invocation.
- Around line 309-312: REGISTRATION_INTERVAL is computed before INTERVAL is
converted by time_to_seconds, causing values like "5m" to yield incorrect
arithmetic; move the REGISTRATION_INTERVAL=$((INTERVAL / 10)) line to after
INTERVAL="$(time_to_seconds "$INTERVAL")" (and after the [ -z "$INTERVAL" ]
invalid check) so REGISTRATION_INTERVAL is calculated from the numeric seconds
value returned by time_to_seconds; update any related comments or dependent
logic referencing REGISTRATION_INTERVAL to reflect the new position.
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 452f7f9 and e04b2b4.

📒 Files selected for processing (2)
  • openwisp-monitoring/files/monitoring.agent
  • openwisp-monitoring/files/monitoring.init
🔇 Additional comments (15)
openwisp-monitoring/files/monitoring.agent (12)

37-56: Well-structured logging wrapper.

The centralized log() function cleanly consolidates logger calls with level mapping and verbose-mode gating. The implementation correctly handles the -v type for verbose-only messages.

Minor observation: The type parameter accepts -v for verbose and implicitly -n for normal, but there's no validation if an invalid type is passed. Consider adding a case check for type similar to level if stricter validation is desired.


58-70: Time parsing function handles common formats.

The cascading conditional correctly parses numeric intervals and time suffixes (s, m, h, d). The unset cleanup is good shell hygiene.

Note: Values like 0, 0s, or negative numbers will return empty (since -ge 1 fails), which the caller handles at line 312. If zero intervals should be explicitly rejected with a clearer message, consider adding a dedicated check.


88-88: Appropriate logging level for memory warnings.

Using -n (non-verbose) ensures memory availability warnings are always logged, which aligns with the earlier review discussion that these rare but significant events should be visible without verbose mode.


134-134: LGTM!

Correctly converted to use the centralized log() wrapper with appropriate verbose-only level.


143-146: LGTM!

Signal handler logging appropriately converted to verbose-only mode.


179-197: Logging logic preserved from original implementation.

The FAILING state-based conditional logging correctly maintains the existing behavior where non-verbose mode only logs state transitions (first failure and first success after recovery). This addresses the earlier review discussion about avoiding log noise while still capturing important state changes.


152-152: LGTM!

Appropriate verbose-only logging for routine "no data" checks.


203-203: Good decision to always log HTTP 400 errors.

Since data is being discarded on HTTP 400, this warrants non-verbose (-n) logging so operators are aware of data loss.


219-231: LGTM!

Registration status messages appropriately use non-verbose logging since device registration is an important operational event.


239-239: LGTM!

Bootup delay notification appropriately uses non-verbose logging.


301-303: LGTM!

Punctuation standardization is consistent with other error messages.


340-340: LGTM!

Clear, well-punctuated error message for invalid mode.

openwisp-monitoring/files/monitoring.init (3)

12-24: Clean helper function for option construction.

The add_option() function effectively reduces code duplication by encapsulating the config_get + procd_append_param pattern. The shellcheck disable for SC3043 is appropriate since OpenWrt's ash shell supports local.


64-68: LGTM!

Consistent punctuation in start/stop log messages.


52-62: Missing --bootup_delay option for collect instance.

The collect instance doesn't pass --bootup_delay, so the agent always uses its hardcoded default of 10 seconds (line 314 in monitoring.agent). If this configuration should be user-configurable, consider adding:

add_option "monitoring" "--bootup_delay" bootup_delay "10"

If the hardcoded default is intentional, this can be ignored.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@github-project-automation github-project-automation bot moved this from Ready for review/testing to In progress in OpenWISP Priorities for next releases Jan 20, 2026
@github-project-automation github-project-automation bot moved this from Ready for review/testing to In progress in 26.05 Release Jan 20, 2026
@github-actions
Copy link

sh-checker report

To get the full details, please check in the job output.

shellcheck errors

'shellcheck ' returned error 1 finding the following syntactical issues:

----------

In monitoring_agent line 69:
	echo $seconds
             ^------^ SC2086 (info): Double quote to prevent globbing and word splitting.

Did you mean: 
	echo "$seconds"

For more information:
  https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...
----------

You can address the above issues in one of three ways:
1. Manually correct the issue in the offending shell script;
2. Disable specific issues by adding the comment:
  # shellcheck disable=NNNN
above the line that contains the issue, where NNNN is the error code;
3. Add '-e NNNN' to the SHELLCHECK_OPTS setting in your .yml action file.



shfmt errors

'shfmt ' returned error 1 finding the following formatting issues:

----------
diff monitoring_agent.orig monitoring_agent
--- monitoring_agent.orig
+++ monitoring_agent
@@ -201,7 +201,7 @@
 				# send data
 				response_code=$($CURL_COMMAND -H "Content-Type: application/json" -d "$data" "$url")
 				if [ "$response_code" = "200" ]; then
-          success=$((success + 1))
+					success=$((success + 1))
 					log -i -v "Data sent successfully."
 					# check if agent was already failing or not to avoid repeating log messages
 					if [ "$FAILING" -eq "1" ]; then
----------

You can reformat the above files to meet shfmt's requirements by typing:

  shfmt  -w filename


Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@openwisp-monitoring/files/monitoring.agent`:
- Line 204: The line setting the success counter ("success=$((success + 1))") is
indented with spaces while the rest of monitoring.agent uses tabs; replace the
leading spaces with a tab so the assignment aligns with surrounding tab-indented
blocks (ensure other similar lines use tabs for consistency) and save the file
with consistent indentation for the success variable and related statements.
♻️ Duplicate comments (1)
openwisp-monitoring/files/monitoring.agent (1)

100-106: Bug: Failure message is never logged.

The condition [ "$n" -eq 5 ] on line 103 is checked before n is incremented. The loop iterates with n values 0, 1, 2, 3, 4. On the final iteration when n=4, the check n -eq 5 is false, then n becomes 5 and the loop exits. The error message is never executed.

Proposed fix
 	until [ "$n" -ge 5 ]; do
 		/usr/sbin/netjson-monitoring --dump "$MONITORED_INTERFACES" && break

-		[ "$n" -eq 5 ] && log -e -v "Collecting data failed!"
+		[ "$n" -eq 4 ] && log -e -v "Collecting data failed!"
 		n=$((n + 1))
 		sleep 5
 	done
🧹 Nitpick comments (2)
openwisp-monitoring/files/monitoring.agent (2)

184-186: Inconsistency: Direct logger call should use log() wrapper.

This block still uses the direct logger command instead of the new log() wrapper, which contradicts the PR's goal of consolidating logger calls.

Proposed fix
-			[ "$VERBOSE_MODE" -eq "1" ] && logger -s "data file $filename not found." \
-				-p daemon.info
+			log -i -v "data file $filename not found."
 			continue

228-230: Inconsistency: Direct logger call should use log() wrapper.

This critical error message still uses the direct logger command instead of the log() wrapper. For consistency and maintainability, consider using the wrapper here as well.

Proposed fix
-						logger -s "Giving up and shutting down: the device may have been deleted from OpenWISP Controller" \
-							-t openwisp-monitoring \
-							-p daemon.err
+						log -e -n "Giving up and shutting down: the device may have been deleted from OpenWISP Controller"
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e04b2b4 and ad1897d.

📒 Files selected for processing (2)
  • openwisp-monitoring/files/monitoring.agent
  • openwisp-monitoring/files/monitoring.init
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: QA-Checks and Tests
  • GitHub Check: Build and upload package as artifacts
🔇 Additional comments (9)
openwisp-monitoring/files/monitoring.init (4)

12-24: LGTM! Good abstraction for config-to-command mapping.

The add_option function cleanly centralizes configuration retrieval and command building. Minor style note: the brace grouping around the local declarations (lines 14-20) is unnecessary since local operates at function scope, not block scope. The shellcheck disable comment applies to the following command regardless of braces.


26-52: Correct config loading sequence for first instance.

The flow correctly loads openwisp config first, captures respawn values (lines 30-32), adds http options (lines 37-42), then loads openwisp-monitoring before adding monitoring options (lines 46-48). This ordering is important since config_load replaces the previously loaded config.


54-64: Collect instance correctly configured without http options.

The second instance appropriately omits http config options since collect mode only gathers data locally. The respawn parameters (captured from http config at lines 30-32) are shared between both instances, which is sensible for consistent process management.


69-75: LGTM!

Standard procd pattern - the stop_service hook handles logging while procd manages actual process termination. The service_triggers correctly monitors both config files.

openwisp-monitoring/files/monitoring.agent (5)

39-58: LGTM!

The log() wrapper cleanly encapsulates level mapping, verbose-mode gating, and tagged logging. The early return for non-verbose mode prevents unnecessary logging calls.


60-72: LGTM!

The time_to_seconds() function correctly handles numeric values and common time suffixes. The fallback to empty output for invalid values is properly validated downstream in main().


129-150: LGTM!

The save_data() and handle_sigusr1() functions correctly use the new log() wrapper, maintaining consistent logging throughout the codebase.


252-278: LGTM!

The wait_until_registered() and bootup_delay() functions correctly use the new log() wrapper with appropriate log levels.


350-354: LGTM!

The INTERVAL conversion and REGISTRATION_INTERVAL computation are now correctly ordered — REGISTRATION_INTERVAL is computed after time_to_seconds() converts the interval to numeric seconds.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

logger -s "Data sent successfully." \
-t openwisp-monitoring \
-p daemon.info
success=$((success + 1))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Indentation inconsistency.

Line 204 uses spaces for indentation while the rest of the file uses tabs. This may cause issues with shell scripts that rely on consistent whitespace.

Proposed fix
-          success=$((success + 1))
+					success=$((success + 1))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
success=$((success + 1))
success=$((success + 1))
🤖 Prompt for AI Agents
In `@openwisp-monitoring/files/monitoring.agent` at line 204, The line setting the
success counter ("success=$((success + 1))") is indented with spaces while the
rest of monitoring.agent uses tabs; replace the leading spaces with a tab so the
assignment aligns with surrounding tab-indented blocks (ensure other similar
lines use tabs for consistency) and save the file with consistent indentation
for the success variable and related statements.

@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch 2 times, most recently from d80d4df to 7103595 Compare January 20, 2026 19:03
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
openwisp-monitoring/files/monitoring.agent (1)

242-246: Fix pause condition to avoid throttling with zero successes.

As written, the pause block triggers when success=0 (since 0 % 10 == 0), which contradicts the intent of “every 10 successful requests.” This adds avoidable delay on failed sends.

✅ Proposed fix
-			if [ $((success % 10)) -eq 0 ]; then
+			if [ "$success" -gt 0 ] && [ $((success % 10)) -eq 0 ]; then
 				pause_duration=$(/usr/sbin/openwisp-get-random-number 1 5)
 				sleep "$pause_duration"
 			fi
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ad1897d and d80d4df.

📒 Files selected for processing (1)
  • openwisp-monitoring/files/monitoring.agent
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Build and upload package as artifacts
  • GitHub Check: QA-Checks and Tests
🔇 Additional comments (2)
openwisp-monitoring/files/monitoring.agent (2)

39-72: LGTM: centralized logging + time parsing.

Clean consolidation of logging and interval parsing; the helper usage keeps behavior consistent and validation intact.

Also applies to: 351-352


90-90: LGTM on log() adoption and message cleanups.

The routing of messages through log() reads clearer and keeps verbose gating consistent.

Also applies to: 99-104, 138-148, 157-157, 191-198, 204-211, 216-216, 221-221, 256-262, 272-272, 343-343, 381-381

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@github-actions
Copy link

sh-checker report

To get the full details, please check in the job output.

shellcheck errors

'shellcheck ' returned error 1 finding the following syntactical issues:

----------

In monitoring_agent line 69:
	echo $seconds
             ^------^ SC2086 (info): Double quote to prevent globbing and word splitting.

Did you mean: 
	echo "$seconds"

For more information:
  https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...
----------

You can address the above issues in one of three ways:
1. Manually correct the issue in the offending shell script;
2. Disable specific issues by adding the comment:
  # shellcheck disable=NNNN
above the line that contains the issue, where NNNN is the error code;
3. Add '-e NNNN' to the SHELLCHECK_OPTS setting in your .yml action file.



shfmt errors

'shfmt ' returned error 1 finding the following formatting issues:

----------
diff monitoring_agent.orig monitoring_agent
--- monitoring_agent.orig
+++ monitoring_agent
@@ -201,7 +201,7 @@
 				# send data
 				response_code=$($CURL_COMMAND -H "Content-Type: application/json" -d "$data" "$url")
 				if [ "$response_code" = "200" ]; then
-          success=$((success + 1))
+					success=$((success + 1))
 					log -i -v "Data sent successfully."
 					# check if agent was already failing or not to avoid repeating log messages
 					if [ "$FAILING" -eq "1" ]; then
----------

You can reformat the above files to meet shfmt's requirements by typing:

  shfmt  -w filename


@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch from 7103595 to 7062db2 Compare January 20, 2026 19:06
@coveralls
Copy link

coveralls commented Jan 20, 2026

Pull Request Test Coverage Report for Build 21194873342

Details

  • 0 of 0 changed or added relevant lines in 0 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage remained the same at 99.663%

Totals Coverage Status
Change from base Build 20836093270: 0.0%
Covered Lines: 3254
Relevant Lines: 3265

💛 - Coveralls

Copy link
Member

@nemesifier nemesifier left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@devkapilbansal the PR history got completely messed up.

@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch from 7062db2 to bb5a19f Compare January 21, 2026 02:08
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@openwisp-monitoring/files/monitoring.init`:
- Around line 40-41: The two lines using add_option ("add_option \"http\"
\"--cacert\" cacert" and "add_option \"http\" \"--capath\" capath") are indented
with spaces; replace the leading spaces with a single tab (to match the file's
existing tab-based indentation) so the indentation is consistent with the rest
of the file.
🧹 Nitpick comments (2)
openwisp-monitoring/files/monitoring.agent (2)

184-186: Inconsistent: Direct logger call instead of log() wrapper.

This verbose-mode logger call should use the new log() wrapper for consistency with the rest of the refactoring.

Proposed fix
-			[ "$VERBOSE_MODE" -eq "1" ] && logger -s "data file $filename not found." \
-				-p daemon.info
+			log -i -v "Data file $filename not found."

228-230: Consider using log() wrapper for consistency.

While this error message is critical and should always be logged (correctly using -p daemon.err), using the log() wrapper would maintain consistency. However, since this is followed by an exit, the direct call is acceptable.

Optional: Use log() wrapper
-						logger -s "Giving up and shutting down: the device may have been deleted from OpenWISP Controller" \
-							-t openwisp-monitoring \
-							-p daemon.err
+						log -e -n "Giving up and shutting down: the device may have been deleted from OpenWISP Controller"
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bb5a19f and 2c66e47.

📒 Files selected for processing (2)
  • openwisp-monitoring/files/monitoring.agent
  • openwisp-monitoring/files/monitoring.init
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Build and upload package as artifacts
  • GitHub Check: QA-Checks and Tests
🔇 Additional comments (14)
openwisp-monitoring/files/monitoring.init (4)

12-24: LGTM! Clean helper function for config-to-command mapping.

The add_option() function correctly encapsulates the pattern of reading a config value and conditionally appending it to the procd command. The shellcheck disable for local in POSIX sh is appropriately documented.


34-52: First procd instance setup looks correct.

The openwisp-monitoring_send_data instance is properly configured with HTTP options, monitoring options, and the --mode send flag. The respawn parameters are correctly applied.


54-64: Second procd instance setup looks correct.

The openwisp-monitoring_collect_data instance is properly configured with monitoring-specific options (monitored_interfaces, required_memory) and the --mode collect flag.


66-71: LGTM! Lifecycle logging with consistent punctuation.

The punctuation changes ("started." and "stopping.") are consistent and improve message clarity.

openwisp-monitoring/files/monitoring.agent (10)

39-58: LGTM! Well-structured logging wrapper.

The log() function cleanly centralizes logging, respects verbose mode, and maps level flags to syslog priorities. This addresses the PR objective of moving logger calls into a subroutine.


60-72: Time parsing function is functional, validation handled downstream.

The function correctly parses numeric and suffixed time values. Invalid inputs result in an empty output, which main() properly validates with the [ -z "$INTERVAL" ] check on line 352.

One edge case to note: values like "0" or "0s" will fail the -ge 1 checks and produce empty output, but a zero interval is likely invalid anyway, so this behavior is acceptable.


90-91: Good: Memory warning now logs in non-verbose mode.

This aligns with the discussion in past reviews—memory issues should be logged regardless of verbose mode since they indicate important system state.


97-107: LGTM! Retry logic bug fixed.

The condition on line 103 is now correctly [ "$n" -eq 4 ], ensuring the failure message is logged on the final retry attempt before the loop exits.


129-145: LGTM! Clean logging wrapper usage.


191-211: State-tracking logic for FAILING flag is clear and functional.

The logic correctly avoids spamming logs during prolonged failures and logs status transitions appropriately.


242-247: Good addition: Throttling to prevent server overload.

The random pause every 10 successful requests is a sensible addition to prevent overwhelming the server when there's a backlog of data to send.


252-264: LGTM! Clean logging wrapper usage for registration flow.


350-354: LGTM! Interval conversion order fixed.

REGISTRATION_INTERVAL is now correctly computed after time_to_seconds() converts INTERVAL to numeric seconds, fixing the previously identified bug.


367-382: Mode handling and final flow looks correct.

Both collect and send modes are properly initialized with their respective configuration and entry points.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@devkapilbansal devkapilbansal force-pushed the issues/57-move-logger-call-in-subroutine branch from 2c66e47 to 9cc4b5e Compare January 21, 2026 02:21
@github-actions
Copy link

sh-checker report

To get the full details, please check in the job output.

shellcheck errors

'shellcheck ' returned error 1 finding the following syntactical issues:

----------

In monitoring_agent line 69:
	echo $seconds
             ^------^ SC2086 (info): Double quote to prevent globbing and word splitting.

Did you mean: 
	echo "$seconds"

For more information:
  https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...
----------

You can address the above issues in one of three ways:
1. Manually correct the issue in the offending shell script;
2. Disable specific issues by adding the comment:
  # shellcheck disable=NNNN
above the line that contains the issue, where NNNN is the error code;
3. Add '-e NNNN' to the SHELLCHECK_OPTS setting in your .yml action file.



shfmt errors

'shfmt ' returned error 1 finding the following formatting issues:

----------
diff monitoring_init.orig monitoring_init
--- monitoring_init.orig
+++ monitoring_init
@@ -37,8 +37,8 @@
 	add_option "http" "--url" url
 	add_option "http" "--uuid" uuid
 	add_option "http" "--key" key
-  add_option "http" "--cacert" cacert
-  add_option "http" "--capath" capath
+	add_option "http" "--cacert" cacert
+	add_option "http" "--capath" capath
 	add_option "http" "--verify_ssl" verify_ssl "1"
 
 	config_load openwisp-monitoring
----------

You can reformat the above files to meet shfmt's requirements by typing:

  shfmt  -w filename


Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@openwisp-monitoring/files/monitoring.init`:
- Around line 30-32: The three variables are being set with command substitution
which yields nothing because config_get assigns variables rather than printing
them; replace the "$(config_get ...)" usages with direct calls to config_get so
that config_get assigns respawn_threshold, respawn_timeout, and respawn_retry
(i.e., call config_get http respawn_threshold, config_get http respawn_timeout,
config_get http respawn_retry) and keep the existing default fallbacks
("${respawn_threshold:-3600}", etc.) intact.
♻️ Duplicate comments (1)
openwisp-monitoring/files/monitoring.agent (1)

86-91: Confirm low-memory logging is now non-verbose.
Line 90 uses -n, so this logs even when verbose mode is off. If the prior behavior was verbose-only, please confirm this change is intended.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c66e47 and 9cc4b5e.

📒 Files selected for processing (2)
  • openwisp-monitoring/files/monitoring.agent
  • openwisp-monitoring/files/monitoring.init
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: QA-Checks and Tests
  • GitHub Check: Build and upload package as artifacts
🔇 Additional comments (9)
openwisp-monitoring/files/monitoring.agent (6)

39-58: Centralized log() wrapper reads clean and keeps severity mapping explicit.


60-72: time_to_seconds() parsing looks solid for s/m/h/d suffixes.


97-149: Log wrapper usage in collect/save/signal flows is consistent.


152-234: Send-path log consolidation looks good.


249-270: Registration/bootup log updates are clear.


339-349: Interval validation and clearer error messages look good.

Also applies to: 377-378

openwisp-monitoring/files/monitoring.init (3)

12-23: add_option helper nicely encapsulates option assembly.


34-62: Splitting send/collect procd instances with add_option reads clean.


66-70: Lifecycle log punctuation update is fine.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment on lines +30 to +32
respawn_threshold=$(config_get http respawn_threshold)
respawn_timeout=$(config_get http respawn_timeout)
respawn_retry=$(config_get http respawn_retry)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

find . -type f -name "monitoring.init" | head -5

Repository: openwisp/openwrt-openwisp-monitoring

Length of output: 123


🏁 Script executed:

# Search for config_get function definition
rg "config_get" -B 3 -A 5 | head -100

Repository: openwisp/openwrt-openwisp-monitoring

Length of output: 1345


🏁 Script executed:

cat -n ./openwisp-monitoring/files/monitoring.init

Repository: openwisp/openwrt-openwisp-monitoring

Length of output: 2700


🌐 Web query:

OpenWrt config_get function behavior libuci.sh

💡 Result:

Summary — config_get (libuci / functions.sh)

  • What it does: config_get

    [default] reads the option value for from the in-memory UCI config loaded by config_load and stores it in the shell variable named by . It does not call the uci binary each time — it reads the data exported to the environment by config_load. [1][2]

  • Lists: If the option is a UCI list, config_get returns the list items joined by spaces (e.g. "item1 item2"). This can break if list items contain spaces; use config_list_foreach to iterate list elements safely. [3]

  • Boolean helper: config_get_bool parses common truthy/falsey strings ("on","off","yes","no","true","false","enabled","disabled") and returns 1 or 0. [1]

  • Key difference vs uci_get: config_get operates on the config already loaded by config_load (faster, no disk I/O); uci_get queries the config files each call. Use config_get when you call config_load once and access multiple options. [2]

References:

  • OpenWrt scripting docs (config/list behavior). [1]
  • Explanation of config_/uci_ differences and implementation details. [2]
  • Notes about list handling and config_list_foreach. [3]

If you want, I can show the exact function implementation lines from your OpenWrt version (need target release or a copy of /lib/functions.sh).


config_get in command substitution drops respawn values.

config_get assigns to a variable and does not output; $(config_get …) leaves respawn_threshold, respawn_timeout, and respawn_retry empty. The values are then always replaced by defaults in lines 51 and 63: "${respawn_threshold:-3600}".

🛠️ Proposed fix
-respawn_threshold=$(config_get http respawn_threshold)
-respawn_timeout=$(config_get http respawn_timeout)
-respawn_retry=$(config_get http respawn_retry)
+config_get respawn_threshold http respawn_threshold
+config_get respawn_timeout http respawn_timeout
+config_get respawn_retry http respawn_retry
🤖 Prompt for AI Agents
In `@openwisp-monitoring/files/monitoring.init` around lines 30 - 32, The three
variables are being set with command substitution which yields nothing because
config_get assigns variables rather than printing them; replace the
"$(config_get ...)" usages with direct calls to config_get so that config_get
assigns respawn_threshold, respawn_timeout, and respawn_retry (i.e., call
config_get http respawn_threshold, config_get http respawn_timeout, config_get
http respawn_retry) and keep the existing default fallbacks
("${respawn_threshold:-3600}", etc.) intact.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In progress

Development

Successfully merging this pull request may close these issues.

[enhancement] Move logger call into subroutine

5 participants