-
Notifications
You must be signed in to change notification settings - Fork 23
Implement basic varlink API and rhc-server daemon
#366
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
Open
mjcr99
wants to merge
8
commits into
main
Choose a base branch
from
macano/implement-rhc-server-scaffolding
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+550
−1
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a0487c1
feat(varlink api): added preliminary varlink API implementation
mjcr99 7601669
feat(varlink api): implemented simple varlink backend for rhc-server
mjcr99 aa76aed
feat(rhc-server): added rhc-server daemon with varlink support
mjcr99 4cf9bfe
feat(rhc-server): added rhc-server generation in Makefile's build target
mjcr99 d25c3d7
feat(rhc-server): implement PID lock to prevent concurrent instances
mjcr99 a5bd606
feat(rhc-server): add systemd integration and RPM packaging for rhc-s…
mjcr99 34222c9
feat(rhc-server): refactor rhc-server structure and follow varlink na…
mjcr99 a3fa20e
test(rhc-server): add unit tests for backend implementation
mjcr99 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| /rhc | ||
| /rhc-server | ||
| /rhc.1.gz | ||
| /USAGE.md | ||
| rhc.spec | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,261 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "log/slog" | ||
| "net" | ||
| "os" | ||
| "os/signal" | ||
| "path/filepath" | ||
| "syscall" | ||
|
|
||
| "github.com/coreos/go-systemd/v22/activation" | ||
| govarlink "github.com/emersion/go-varlink" | ||
|
|
||
| "github.com/redhatinsights/rhc/varlink/internalapi" | ||
| ) | ||
|
|
||
| const ( | ||
| socketPath = "/run/rhc/com.redhat.rhc" | ||
| pidFilePath = "/run/rhc/rhc-server.pid" | ||
| socketDirPerms = 0755 | ||
| socketPerms = 0660 | ||
| pidFilePerms = 0644 | ||
|
|
||
| // Channel buffer sizes for graceful shutdown | ||
| signalChanBuffer = 1 | ||
| errorChanBuffer = 1 | ||
| ) | ||
|
|
||
| func main() { | ||
| // Acquire PID lock to ensure only one instance runs | ||
| cleanup, err := acquirePIDLock() | ||
| if err != nil { | ||
| slog.Error("Failed to acquire PID lock", "error", err) | ||
| os.Exit(1) | ||
| } | ||
| defer cleanup() | ||
|
|
||
| if err := run(); err != nil { | ||
| slog.Error("rhc-server error", "error", err) | ||
| os.Exit(1) | ||
| } | ||
| } | ||
|
|
||
| func run() error { | ||
| // Create backend | ||
| backend := NewBackend() | ||
|
|
||
| // Create registry and register the internal API | ||
| registry := govarlink.NewRegistry(&govarlink.RegistryOptions{ | ||
| Vendor: "Red Hat", | ||
| Product: "rhc", | ||
| Version: Version, | ||
| URL: "https://github.com/redhatinsights/rhc", | ||
| }) | ||
|
|
||
| // Register internal API | ||
| handler := internalapi.Handler{Backend: backend} | ||
| handler.Register(registry) | ||
|
|
||
| // Create server | ||
| varlinkServer := &govarlink.Server{ | ||
| Handler: registry, | ||
| } | ||
|
|
||
| // Try to get listener from systemd socket activation first | ||
| listener, err := getListener() | ||
| if err != nil { | ||
| return fmt.Errorf("failed to get listener: %w", err) | ||
| } | ||
| defer func() { | ||
| if err := listener.Close(); err != nil { | ||
| slog.Error("Error closing listener", "error", err) | ||
| } | ||
| }() | ||
|
|
||
| slog.Info("rhc-server starting", "version", Version) | ||
| slog.Info("Listening on socket", "address", listener.Addr()) | ||
|
|
||
| // Setup graceful shutdown | ||
| _, cancel := context.WithCancel(context.Background()) | ||
| defer cancel() | ||
|
|
||
| // Setup signal handler for graceful shutdown on SIGINT/SIGTERM | ||
| sigChan := make(chan os.Signal, signalChanBuffer) | ||
| signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) | ||
|
|
||
| // Run the server in a goroutine so we can handle signals concurrently | ||
| errChan := make(chan error, errorChanBuffer) | ||
| go func() { | ||
| errChan <- varlinkServer.Serve(listener) | ||
| }() | ||
|
|
||
| // Block until either: | ||
| // - The server encounters an error (errChan) | ||
| // - We receive a shutdown signal (sigChan) | ||
| select { | ||
| case err := <-errChan: | ||
| if err != nil { | ||
| return fmt.Errorf("server error: %w", err) | ||
| } | ||
| case sig := <-sigChan: | ||
| slog.Info("Received signal, shutting down gracefully", "signal", sig) | ||
| cancel() | ||
| } | ||
|
|
||
| slog.Info("rhc-server stopped") | ||
| return nil | ||
| } | ||
|
|
||
| // acquirePIDLock creates and locks a PID file to ensure only one instance runs. | ||
| // Returns a cleanup function that should be deferred to release the lock. | ||
| func acquirePIDLock() (func(), error) { | ||
| // Ensure the directory exists | ||
| dir := filepath.Dir(pidFilePath) | ||
| if err := os.MkdirAll(dir, socketDirPerms); err != nil { | ||
| return nil, fmt.Errorf("failed to create PID file directory: %w", err) | ||
| } | ||
|
|
||
| // Open or create the PID file | ||
| pidFile, err := os.OpenFile(pidFilePath, os.O_CREATE|os.O_RDWR, pidFilePerms) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to open PID file: %w", err) | ||
| } | ||
|
|
||
| // Try to acquire an exclusive lock (non-blocking) | ||
| if err := syscall.Flock(int(pidFile.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { | ||
| _ = pidFile.Close() | ||
| if errors.Is(err, syscall.EWOULDBLOCK) { | ||
| return nil, fmt.Errorf("another instance of rhc-server is already running") | ||
| } | ||
| return nil, fmt.Errorf("failed to lock PID file: %w", err) | ||
| } | ||
|
|
||
| // release defines a local helper to unlock and close the PID file | ||
| // during error handling or normal shutdown. | ||
| release := func() { | ||
| _ = syscall.Flock(int(pidFile.Fd()), syscall.LOCK_UN) | ||
| _ = pidFile.Close() | ||
| } | ||
|
|
||
| // Reset file content to ensure a clean state before writing the new PID | ||
| if err := pidFile.Truncate(0); err != nil { | ||
| release() | ||
| return nil, fmt.Errorf("failed to truncate PID file: %w", err) | ||
| } | ||
|
|
||
| // Ensure the file cursor is at the beginning | ||
| if _, err := pidFile.Seek(0, 0); err != nil { | ||
| release() | ||
| return nil, fmt.Errorf("failed to seek PID file: %w", err) | ||
| } | ||
|
|
||
| // Save current process ID to the lock file | ||
| pid := os.Getpid() | ||
| if _, err := fmt.Fprintf(pidFile, "%d\n", pid); err != nil { | ||
| release() | ||
| return nil, fmt.Errorf("failed to write PID to file: %w", err) | ||
| } | ||
|
|
||
| // Commit pidFile content to stable storage | ||
| if err := pidFile.Sync(); err != nil { | ||
| release() | ||
| return nil, fmt.Errorf("failed to sync PID file: %w", err) | ||
| } | ||
|
|
||
| slog.Info("PID lock acquired", "pid", pid, "pidFile", pidFilePath) | ||
|
|
||
| // Return cleanup function | ||
| cleanup := func() { | ||
| release() | ||
| if err := os.Remove(pidFilePath); err != nil { | ||
| slog.Warn("Failed to remove PID file", "path", pidFilePath, "error", err) | ||
| } | ||
| slog.Info("PID lock released") | ||
| } | ||
|
|
||
| return cleanup, nil | ||
| } | ||
|
|
||
| // trySystemdActivation attempts to get a listener from systemd socket activation. | ||
| func trySystemdActivation() (net.Listener, error) { | ||
mjcr99 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| listeners, err := activation.Listeners() | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to get systemd listeners: %w", err) | ||
| } | ||
|
|
||
| if len(listeners) == 0 { | ||
mjcr99 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| slog.Debug("Unable to find systemd listeners") | ||
| return nil, nil // No systemd socket available | ||
| } | ||
|
|
||
| // Find the first unix socket listener | ||
| for _, listener := range listeners { | ||
| if listener.Addr().Network() == "unix" { | ||
| slog.Info("Using systemd socket activation", "address", listener.Addr()) | ||
| return listener, nil | ||
| } | ||
| } | ||
|
|
||
| return nil, fmt.Errorf("no unix socket found in systemd listeners") | ||
| } | ||
|
|
||
| // ensureSocketDirectory creates the directory for the socket if it doesn't exist. | ||
| func ensureSocketDirectory(path string) error { | ||
| dir := filepath.Dir(path) | ||
| if err := os.MkdirAll(dir, socketDirPerms); err != nil { | ||
| return fmt.Errorf("failed to create socket directory: %w", err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // createUnixSocket creates a unix socket at the specified path. | ||
| func createUnixSocket(path string) (net.Listener, error) { | ||
| slog.Info("Creating unix socket", "path", path) | ||
|
|
||
| // Ensure the directory exists | ||
| if err := ensureSocketDirectory(path); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // Remove existing socket file if it exists. | ||
| // This is safe because we hold the PID lock, ensuring no other | ||
| // rhc-server instance is running. The socket exists only because | ||
| // a previous instance was terminated abnormally. | ||
| if err := os.RemoveAll(path); err != nil { | ||
mjcr99 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return nil, fmt.Errorf("failed to remove existing socket: %w", err) | ||
| } | ||
|
|
||
| // Create unix socket | ||
| listener, err := net.Listen("unix", path) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create unix socket: %w", err) | ||
| } | ||
|
|
||
| // Set socket permissions | ||
| if err := os.Chmod(path, socketPerms); err != nil { | ||
| _ = listener.Close() | ||
| return nil, fmt.Errorf("failed to set socket permissions: %w", err) | ||
| } | ||
|
|
||
| return listener, nil | ||
| } | ||
|
|
||
| // getListener tries to get a listener from systemd socket activation, | ||
| // falls back to creating a unix socket. | ||
| func getListener() (net.Listener, error) { | ||
| // Try systemd socket activation first | ||
| listener, err := trySystemdActivation() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if listener != nil { | ||
| return listener, nil | ||
| } | ||
|
|
||
| // Fall back to creating our own unix socket | ||
| return createUnixSocket(socketPath) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "fmt" | ||
|
|
||
| "github.com/redhatinsights/rhc/varlink/internalapi" | ||
| ) | ||
|
|
||
| var ( | ||
| // Version is set at build time. | ||
| Version = "dev" | ||
| ) | ||
|
|
||
| // Backend implements the internal API backend. | ||
| type Backend struct{} | ||
|
|
||
| // NewBackend creates a new backend instance. | ||
| func NewBackend() *Backend { | ||
| return &Backend{} | ||
| } | ||
|
|
||
| // Test implements the Test method of the internal API. | ||
| // Simply echoes back the input with a prefix. | ||
| func (b *Backend) Test(in *internalapi.TestIn) (*internalapi.TestOut, error) { | ||
| output := fmt.Sprintf("Echo from rhc-server: %s", in.Input) | ||
| return &internalapi.TestOut{Output: output}, nil | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.