Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(logging): reopen on sighup #7140

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

james-d-elliott
Copy link
Member

@james-d-elliott james-d-elliott commented Apr 11, 2024

This implements a method to send Authelia a SIGHUP signal to indicate it should reload the configuration file. This can be used in two ways. If using an external logrotate service you can tell Authelia to reopen the file and create it if it doesn't exist. Secondly if you use the existing time date replacements this will create a brand new log file with the current time.

Closes #4964

@authelia
Copy link

authelia bot commented Apr 11, 2024

Artifacts

These changes are published for testing on Buildkite, DockerHub and GitHub Container Registry.

Docker Container

  • docker pull authelia/authelia:feat-logrotate
  • docker pull ghcr.io/authelia/authelia:feat-logrotate

Copy link
Contributor

coderabbitai bot commented Apr 11, 2024

Walkthrough

The changes introduce a new logging feature that allows the application to reopen its log files upon receiving specific signals. This enhancement includes new methods in the CmdCtx struct, a SignalService for handling signals, and updates to the logging package to support file reopening. These modifications ensure that log rotation can be managed more effectively without losing log entries.

Changes

File Path Change Summary
internal/commands/const.go Added a new constant serviceTypeSignal with the value "signal".
internal/commands/context.go Added methods GetLogger, GetProviders, GetConfiguration to CmdCtx struct.
internal/commands/services.go Added NewSignalService, ServiceCtx interface, SignalService struct, and updated service functions.
internal/logging/const.go Added global variables for stacktrace, file path formatting regex, and file handling.
internal/logging/file.go Introduced file logging functionalities including file creation, reopening, closing, and writing.
internal/logging/logger.go Refactored ConfigureLogger to use new file handling methods and added a Reopen function.
internal/logging/logger_test.go Updated tests to reflect new logging functionalities and removed obsolete test function.
internal/logging/printf.go Added LoggerPrintf and LoggerCtxPrintf functions for creating loggers with specific log levels.
internal/logging/util.go Added utility function FormatFilePath for formatting file paths with timestamps.
internal/logging/util_test.go Introduced tests for the FormatFilePath function.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant User
    participant SignalService
    participant Logger

    User ->> SignalService: Send Signal (e.g., -HUP)
    SignalService ->> Logger: Call Reopen Function
    Logger ->> File: Reopen Log File
    File ->> Logger: Confirm Reopen
    Logger ->> SignalService: Confirm Reopen Success
    SignalService ->> User: Acknowledge Signal Handling

Assessment against linked issues

Objective (Issue #4964) Addressed Explanation
Provide a way to reopen log files after rotation

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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

internal/logging/logger_test.go Outdated Show resolved Hide resolved
Copy link
Contributor

@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

internal/logging/logger.go Show resolved Hide resolved
Copy link

codecov bot commented Apr 12, 2024

Codecov Report

Attention: Patch coverage is 47.41379% with 61 lines in your changes are missing coverage. Please review.

Project coverage is 73.62%. Comparing base (1870378) to head (0d186d4).
Report is 4 commits behind head on master.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #7140      +/-   ##
==========================================
- Coverage   73.68%   73.62%   -0.07%     
==========================================
  Files         346      347       +1     
  Lines       30022    30109      +87     
  Branches      839      839              
==========================================
+ Hits        22123    22169      +46     
- Misses       7026     7069      +43     
+ Partials      873      871       -2     
Flag Coverage Δ
backend 74.49% <47.41%> (-0.08%) ⬇️
frontend 66.00% <ø> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files Coverage Δ
internal/commands/context.go 77.57% <100.00%> (+0.50%) ⬆️
internal/logging/const.go 100.00% <ø> (ø)
internal/logging/logger.go 92.42% <28.57%> (-7.58%) ⬇️
internal/logging/file.go 69.69% <69.69%> (ø)
internal/commands/services.go 40.44% <34.28%> (-4.20%) ⬇️

... and 3 files with indirect coverage changes

Copy link
Contributor

@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

@@ -59,9 +59,9 @@ func ConfigureLogger(config schema.Log, log bool) (err error) {

switch {
case config.FilePath != "":
var file *os.File
file = NewFile(config.FilePath)
Copy link
Contributor

Choose a reason for hiding this comment

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

Declare the file variable before using it to avoid scope issues.

+ var file *FileHandler
  file = NewFile(config.FilePath)

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.

Suggested change
file = NewFile(config.FilePath)
var file *FileHandler
file = NewFile(config.FilePath)

Comment on lines +89 to +96
// Reopen handles safely reopening the log file.
func Reopen() (err error) {
if file == nil {
return fmt.Errorf("error reopening log file: file is not configured")
}

return file.Open()
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider encapsulating the file variable within a struct to manage its scope and lifecycle more effectively.

type Logger struct {
    file *FileHandler
}

func (l *Logger) Reopen() error {
    if l.file == nil {
        return fmt.Errorf("error reopening log file: file is not configured")
    }
    return l.file.Open()
}

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.

Suggested change
// Reopen handles safely reopening the log file.
func Reopen() (err error) {
if file == nil {
return fmt.Errorf("error reopening log file: file is not configured")
}
return file.Open()
}
type Logger struct {
file *FileHandler
}
func (l *Logger) Reopen() error {
if l.file == nil {
return fmt.Errorf("error reopening log file: file is not configured")
}
return l.file.Open()
}

Signed-off-by: James Elliott <[email protected]>
Copy link
Contributor

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 47d049a and 0d186d4.

Files selected for processing (6)
  • internal/commands/const.go (1 hunks)
  • internal/commands/context.go (1 hunks)
  • internal/commands/services.go (7 hunks)
  • internal/logging/const.go (1 hunks)
  • internal/logging/file.go (1 hunks)
  • internal/logging/logger.go (3 hunks)
Files skipped from review due to trivial changes (1)
  • internal/commands/const.go
Additional comments not posted (5)
internal/logging/file.go (1)

9-59: The implementation of file handling methods (Open, Close, Write) correctly uses mutexes to ensure thread safety.

internal/logging/logger.go (2)

62-64: Duplicate comment: Ensure proper scope and lifecycle management for the file variable.


89-96: Duplicate comment: Encapsulate the file variable within a struct to manage its scope and lifecycle more effectively.

internal/commands/services.go (1)

Line range hint 89-375: The implementation of SignalService and its methods (Run, Shutdown) correctly handle signals and actions, demonstrating effective use of Go's concurrency patterns.

internal/commands/context.go (1)

86-97: The addition of getter methods (GetLogger, GetProviders, GetConfiguration) to the CmdCtx struct enhances modularity and maintainability.

@@ -53,4 +53,5 @@ const (
var (
stacktrace sync.Once
reFormatFilePath = regexp.MustCompile(`(%d|\{datetime(:([^}]+))?})`)
file *File
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The search results indicate multiple usages of the file variable within the internal/logging package. However, there is no evidence of synchronization mechanisms around its access, which could lead to potential issues with concurrent access.

  • internal/logging/logger.go: The file variable is used for opening, writing, and reopening the log file.
  • internal/logging/file.go: The file variable is used for managing file operations such as opening, closing, and writing to the file.

To ensure thread-safety, it is crucial to implement synchronization mechanisms (e.g., mutexes) around the access to the file variable.

  • internal/logging/logger.go
  • internal/logging/file.go
Analysis chain

Verify thread-safety for the global file variable.


Narrow down the search to the internal/logging package and check for synchronization mechanisms around the file variable.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Search for all usages of the global `file` variable to ensure it is accessed in a thread-safe manner.

# Test: Search for the variable usage. Expect: Proper synchronization mechanisms around its access.
rg --type go $'file'

Length of output: 142520



Script:

#!/bin/bash
# Description: Search for all usages of the global `file` variable in the `internal/logging` package to ensure it is accessed in a thread-safe manner.

# Test: Search for the variable usage within the `internal/logging` package. Expect: Proper synchronization mechanisms around its access.
rg --type go --glob 'internal/logging/**' $'file'

Length of output: 1333

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

A way to tell authelia to reopen its logfile
1 participant