### Start Log Collection Source: https://context7.com/simple-observability/simob-agent/llms.txt This example demonstrates how to set up and start log collection using the `logs` package. It includes discovering log sources, initializing collectors, and initiating continuous tailing of logs until the context is cancelled. ```go package main import ( "context" "fmt" "sync" "time" "agent/internal/exporter" "agent/internal/logs" "agent/internal/logs/nginx" "agent/internal/logs/journalctl" "agent/internal/config" ) func main() { cfg := config.NewConfig("sk-abc123") // Build log collectors collectors := []logs.LogCollector{ nginx.NewNginxLogCollector(), // tails /var/log/nginx/*.log journalctl.NewJournalCTLCollector(), // streams systemd journal } // Discovery: report which log sources exist on this host for _, c := range collectors { sources := c.Discover() for _, s := range sources { fmt.Printf("%s -> %s\n", s.Name, s.Path) // nginx -> /var/log/nginx/*.log } } // Continuous tailing (blocks until ctx cancel) exp, _ := exporter.NewExporter(cfg, false) defer exp.Close() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() var wg sync.WaitGroup wg.Add(1) go logs.StartCollection(collectors, ctx, &wg, exp) wg.Wait() } ``` -------------------------------- ### Install simob Agent with Prebuilt Binaries Source: https://github.com/simple-observability/simob-agent/blob/master/README.md Installs the latest agent binary, sets up a systemd service, and initializes the agent with a server key. Replace `` with your actual key. Optional flags can modify installation behavior. ```bash $ curl -fsSL https://simpleobservability.com/install.sh | sudo bash -s -- [optional flags] ``` -------------------------------- ### Build and Install simob from Source Source: https://context7.com/simple-observability/simob-agent/llms.txt Builds the simob agent from source code using Go and installs it using a custom binary path. Ensure you have the Go toolchain installed. ```bash git clone https://github.com/simple-observability/simob-agent.git cd simob-agent/agent && go build -ldflags "-X agent/internal/version.Version=1.0.0" -o simob . sudo BINARY_PATH=./simob bash ../install.sh ``` -------------------------------- ### Install simob Agent from Source Source: https://github.com/simple-observability/simob-agent/blob/master/README.md Installs the agent using a locally built binary. Ensure `BINARY_PATH` points to your compiled binary and replace `` with your actual key. ```bash $ sudo BINARY_PATH= bash install.sh ``` -------------------------------- ### Install simob Agent Source: https://context7.com/simple-observability/simob-agent/llms.txt Installs the simob agent using a one-command script. Options are available to control journald access and system read permissions. ```bash curl -fsSL https://simpleobservability.com/install.sh | sudo bash -s -- ``` ```bash curl -fsSL https://simpleobservability.com/install.sh | sudo bash -s -- --no-journal-access ``` ```bash curl -fsSL https://simpleobservability.com/install.sh | sudo bash -s -- --no-system-read ``` -------------------------------- ### Collect and Export Metrics Source: https://context7.com/simple-observability/simob-agent/llms.txt Implement `metrics.MetricCollector` to gather system metrics. `metrics.StartCollection` runs a continuous polling loop. This example demonstrates manual collection and setting up a continuous loop with an exporter. ```go package main import ( "context" "fmt" "sync" "time" "agent/internal/exporter" "agent/internal/metrics" "agent/internal/metrics/cpu" "agent/internal/metrics/memory" "agent/internal/metrics/disk" "agent/internal/config" ) func main() { cfg := config.NewConfig("sk-abc123") // Build individual collectors manually collectors := []metrics.MetricCollector{ cpu.NewCPUCollector(), memory.NewMemoryCollector(), disk.NewDiskCollector(), } // Discover what each collector can produce (sent to backend on startup) for _, c := range collectors { available, err := c.Discover() if err != nil { fmt.Printf("discover %s: %v\n", c.Name(), err) continue } fmt.Printf("%s: %d metrics available\n", c.Name(), len(available)) // cpu: 20 (10 states × 2 cores + "total") // mem: 9 (virtual + swap) // disk: 14 (usage + IO per partition) } // One-shot collection example for _, c := range collectors { dps, err := c.CollectAll() if err != nil { fmt.Printf("collect %s: %v\n", c.Name(), err) continue } for _, dp := range dps { fmt.Printf("[%s] %s=%f labels=%v\n", c.Name(), dp.Name, dp.Value, dp.Labels) } } // [cpu] cpu_user_ratio=0.023100 labels=map[cpu:cpu0] // [cpu] cpu_idle_ratio=0.961200 labels=map[cpu:total] // [mem] mem_used_bytes=4294967296 labels=map[] // [mem] mem_used_ratio=0.512000 labels=map[] // [disk] disk_used_ratio=0.670000 labels=map[device:/dev/sda1 mountpoint:/] // Continuous collection loop (60 s interval, stops on ctx cancel) exp, _ := exporter.NewExporter(cfg, false) defer exp.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() var wg sync.WaitGroup wg.Add(1) go metrics.StartCollection(collectors, 60*time.Second, ctx, &wg, exp) wg.Wait() } ``` -------------------------------- ### Start simob Agent Source: https://context7.com/simple-observability/simob-agent/llms.txt Starts the simob agent's metrics and logs collection service. The `--dry-run` flag is useful for testing data collection without remote transmission. ```bash simob start ``` ```bash DEBUG=1 simob start --dry-run ``` -------------------------------- ### Get simob Agent Version Source: https://context7.com/simple-observability/simob-agent/llms.txt Retrieves and displays the version of the currently installed simob agent. The version is set during the build process. ```bash simob version ``` -------------------------------- ### Custom Metric Collector Implementation Source: https://context7.com/simple-observability/simob-agent/llms.txt Provides an example of implementing the `MetricCollector` interface for custom metrics. Remember to register the collector in `agent/internal/metrics/registry/registry.go`. ```go // agent/internal/metrics/myservice/myservice.go package myservice import ( "fmt" "time" "agent/internal/collection" "agent/internal/metrics" ) type MyServiceCollector struct { metrics.BaseCollector // embed for SetIncludedMetrics / IsIncluded helpers } func NewMyServiceCollector() *MyServiceCollector { return &MyServiceCollector{} } func (c *MyServiceCollector) Name() string { return "myservice" } func (c *MyServiceCollector) Discover() ([]collection.Metric, error) { return []collection.Metric{ {Name: "myservice_requests_rate", Type: "gauge", Labels: map[string]string{}}, {Name: "myservice_error_ratio", Type: "gauge", Labels: map[string]string{}}, }, nil } func (c *MyServiceCollector) CollectAll() ([]metrics.DataPoint, error) { ts := time.Now().UnixMilli() // ... fetch stats from your service ... return []metrics.DataPoint{ {Name: "myservice_requests_rate", Timestamp: ts, Value: 42.5, Labels: map[string]string{}}, {Name: "myservice_error_ratio", Timestamp: ts, Value: 0.01, Labels: map[string]string{}}, }, nil } func (c *MyServiceCollector) Collect() ([]metrics.DataPoint, error) { all, err := c.CollectAll() if err != nil { return nil, err } var out []metrics.DataPoint for _, dp := range all { if c.IsIncluded(dp.Name, dp.Labels) { out = append(out, dp) } } return out, nil } // In registry.go, add: // "myservice": myservice.NewMyServiceCollector(), ``` -------------------------------- ### API Client Usage for Backend Interaction Source: https://context7.com/simple-observability/simob-agent/llms.txt Shows how to initialize and use the `api.Client` to validate API keys, fetch collection configurations, and report discovered metrics and log sources. ```go package main import ( "fmt" "agent/internal/api" "agent/internal/collection" "agent/internal/config" ) func main() { cfg := config.NewConfig("sk-abc123") client := api.NewClient(*cfg, false) // dryRun=false sends real requests // Validate the API key against the backend valid, err := client.CheckAPIKeyValidity() fmt.Println(valid, err) // true // Fetch the collection config the UI has configured for this server collCfg, err := client.GetCollectionConfig() if err != nil { panic(err) } fmt.Println(len(collCfg.Metrics)) // e.g. 12 fmt.Println(len(collCfg.LogSources)) // e.g. 2 // Report discovered metrics to the platform (so the UI can display them) err = client.PostAvailableMetrics([]collection.Metric{ {Name: "cpu_user_ratio", Type: "gauge", Labels: map[string]string{"cpu": "total"}}, }) fmt.Println("post metrics:", err) // Report discovered log sources err = client.PostAvailableLogSources([]collection.LogSource{ {Name: "nginx", Path: "/var/log/nginx/*.log"}, }) fmt.Println("post log sources:", err) } ``` -------------------------------- ### Build Metric Collectors with Configuration Source: https://context7.com/simple-observability/simob-agent/llms.txt Demonstrates how to use `metricsRegistry.BuildCollectors` to create a set of active metric collectors. It shows instantiation with a nil config (all collectors enabled) and with a filtered `CollectionConfig` to enable specific metrics. ```go package main import ( "fmt" "agent/internal/collection" metricsRegistry "agent/internal/metrics/registry" ) func main() { // nil config → all collectors enabled (used during capability discovery) allCollectors := metricsRegistry.BuildCollectors(nil) fmt.Println(len(allCollectors)) // 9 // Filtered config from the remote API cfg := &collection.CollectionConfig{ Metrics: []collection.Metric{ {Name: "cpu_user_ratio", Type: "gauge", Labels: map[string]string{"cpu": "total"}}, {Name: "mem_used_ratio", Type: "gauge", Labels: map[string]string{}}, {Name: "nginx_requests_rate", Type: "gauge", Labels: map[string]string{}}, }, } filtered := metricsRegistry.BuildCollectors(cfg) fmt.Println(len(filtered)) // 4 (status always included + cpu + mem + nginx) for _, c := range filtered { fmt.Println(c.Name()) // "status", "cpu", "mem", "nginx" } } ``` -------------------------------- ### Run Agent Lifecycle Source: https://context7.com/simple-observability/simob-agent/llms.txt Initialize and run the agent using the `manager` package. The agent orchestrates sub-systems and reacts to OS signals. Set `DEBUG` environment variable to 1 for verbose logging. ```go package main import ( "agent/internal/config" "agent/internal/logger" "agent/internal/manager" "os" ) func main() { logger.Init(os.Getenv("DEBUG") == "1") cfg := config.NewConfig("sk-abc123") // Construct and run the agent (blocks until SIGTERM / SIGINT) agent := manager.NewAgent(cfg) agent.Run(false) // false = production mode; true = dry-run (stdout, 20 s) // agent.Stop() can be called from another goroutine to trigger a clean shutdown } ``` -------------------------------- ### Build and Cross-Compile the Agent Source: https://context7.com/simple-observability/simob-agent/llms.txt These bash commands illustrate how to clone the repository, run tests, build the agent for the current platform, and cross-compile it for Linux and Windows. The `-ldflags` option is used to set the version information during the build process. ```bash # Clone the repository git clone https://github.com/simple-observability/simob-agent.git cd simob-agent/agent # Run tests go test ./... # Build for the current platform go build -ldflags "-X agent/internal/version.Version=1.0.0" -o simob . # Cross-compile for Linux amd64 GOOS=linux GOARCH=amd64 \ go build -ldflags "-X agent/internal/version.Version=1.0.0" -o simob-linux-amd64 . # Cross-compile for Windows amd64 GOOS=windows GOARCH=amd64 \ go build -ldflags "-X agent/internal/version.Version=1.0.0" -o simob-windows-amd64.exe . ``` -------------------------------- ### Instantiate All Built-in Metric Collectors Source: https://context7.com/simple-observability/simob-agent/llms.txt This code snippet shows how to import and instantiate all available built-in metric collectors. Each collector is initialized and assigned to a blank identifier, indicating they are being prepared for use. ```go import ( "agent/internal/metrics/apache" "agent/internal/metrics/cpu" "agent/internal/metrics/disk" "agent/internal/metrics/memcached" "agent/internal/metrics/memory" "agent/internal/metrics/network" "agent/internal/metrics/nginx" "agent/internal/metrics/phpfpm" "agent/internal/metrics/status" ) // Instantiate all collectors _ = apache.NewApacheCollector() // apache_requests_rate, apache_connections_*, apache_workers_* _ = cpu.NewCPUCollector() // cpu_{user,system,idle,iowait,...}_ratio (per-core + total) _ = disk.NewDiskCollector() // disk_{total,used,free}_bytes, disk_{read,write}_{rate,bps}, disk_busy_ratio _ = memcached.NewMemcachedCollector() // memcached_hits_rate, memcached_misses_rate, memcached_connections_total, ... _ = memory.NewMemoryCollector() // mem_{total,used,available,free}_bytes, mem_used_ratio + swap equivalents _ = network.NewNetworkCollector() // net_{in,out}_bps, net_{in,out}_rate (per interface) _ = nginx.NewNginxCollector() // nginx_connections_{active,reading,writing,waiting}_total, nginx_requests_{total,rate} _ = phpfpm.NewPHPFPMCollector() // phpfpm_active_processes_total, phpfpm_idle_processes_total, ... _ = status.NewStatusCollector() // agent_status (heartbeat gauge, always included) ``` -------------------------------- ### Configure Agent Settings Source: https://context7.com/simple-observability/simob-agent/llms.txt Use the `config` package to create, modify, and persist agent settings. New configurations merge with existing `config.json` files. Ensure to handle potential errors during saving and loading. ```go package main import ( "fmt" "agent/internal/config" ) func main() { // Create a new config with an API key (merges with any existing config.json) cfg := config.NewConfig("sk-abc123") // cfg.APIKey == "sk-abc123" // cfg.APIUrl == "https://api.simpleobservability.com" (default) // cfg.LogsExportUrl == "https://logs.simpleobservability.com" (default) // cfg.MetricsExportUrl == "https://metrics.simpleobservability.com" (default) // Override individual fields cfg.SetAPIUrl("https://api.internal") cfg.SetMetricsExportUrl("https://metrics.internal") // Persist to disk (~/.simob/config.json or /etc/simob/config.json) if err := cfg.Save(); err != nil { panic(err) } // Load back from disk loaded, err := config.Load() if err != nil { panic(err) } fmt.Println(loaded.APIKey) // "sk-abc123" // Resolve the config file path path, _ := config.ConfigPath() fmt.Println(path) // e.g. /etc/simob/config.json } ``` -------------------------------- ### Exporter Usage with Background Flusher Source: https://context7.com/simple-observability/simob-agent/llms.txt Demonstrates how to initialize and use the `exporter.Exporter` for sending metric and log data. Ensure `exp.Close()` is called to flush remaining data. ```go package main import ( "fmt" "agent/internal/config" "agent/internal/exporter" ) func main() { cfg := config.NewConfig("sk-abc123") // Full exporter with background flusher (normal production use) exp, err := exporter.NewExporter(cfg, false) if err != nil { panic(err) } defer exp.Close() // flushes remaining spool entries and shuts down flusher // Export a metric data point err = exp.ExportMetric([]exporter.MetricPayload{ { Timestamp: "1717171717000", Name: "cpu_user_ratio", Value: 0.23, Labels: map[string]string{"cpu": "total"}, }, }) if err != nil { fmt.Println("metric export error:", err) } // Export a log entry err = exp.ExportLog([]exporter.LogPayload{ { Timestamp: "1717171717000", Message: `192.168.1.1 - - [01/Jan/2025:12:00:00 +0000] "GET /health HTTP/1.1" 200 42`, Labels: map[string]string{"source": "nginx"}, Metadata: map[string]string{}, }, ]) if err != nil { fmt.Println("log export error:", err) } // Spool-only exporter (no flusher — another process handles sending) spoolOnly, err := exporter.NewExporterWithoutFlusher() if err != nil { panic(err) } defer spoolOnly.Close() } ``` -------------------------------- ### List Available Log Collectors Source: https://context7.com/simple-observability/simob-agent/llms.txt This snippet shows the available log collectors that can be instantiated. It includes collectors for Apache logs, systemd journal, Nginx logs, and Windows Event Logs. ```go import ( "agent/internal/logs/apache" "agent/internal/logs/journalctl" "agent/internal/logs/nginx" "agent/internal/logs/winevent" ) _ = apache.NewApacheLogCollector() // tails /var/log/apache2/*.log (Combined Log Format) _ = journalctl.NewJournalCTLCollector() // streams systemd journal via journalctl _ = nginx.NewNginxLogCollector() // tails /var/log/nginx/*.log _ = winevent.NewWinEventCollector() // Windows Event Log (Windows only) ``` -------------------------------- ### Perform Self-Update with SHA-256 Verification Source: https://context7.com/simple-observability/simob-agent/llms.txt This Go code snippet demonstrates how to use the `updater.Update()` function to perform an in-place binary replacement. It includes error handling and sets an environment variable for testing the API base URL. On success, a restart signal file is created, which systemd uses to automatically restart the service. ```go package main import ( "fmt" "os" "agent/internal/updater" ) func main() { // Override the API base URL for testing os.Setenv("API_URL", "https://api.simpleobservability.com") if err := updater.Update(); err != nil { fmt.Fprintf(os.Stderr, "update failed: %v\n", err) os.Exit(1) } // On success the running binary has been replaced on disk and a "restart" // signal file has been created. Systemd will restart the service automatically. } ``` -------------------------------- ### Configure simob Agent Source: https://context7.com/simple-observability/simob-agent/llms.txt Manages the agent's local configuration file (`config.json`). Allows viewing and modifying settings like API keys and export URLs. ```bash simob config ``` ```bash simob config api_key=sk-abc123... ``` ```bash simob config api_url=https://api.mycompany.internal ``` ```bash simob config logs_export_url=https://logs.mycompany.internal ``` ```bash simob config metrics_export_url=https://metrics.mycompany.internal ``` -------------------------------- ### Update simob Agent Source: https://context7.com/simple-observability/simob-agent/llms.txt Checks for and applies agent updates. This command downloads a new binary, verifies its integrity, and prepares the system for a restart to use the updated version. ```bash simob update ``` -------------------------------- ### Check simob Agent Status Source: https://context7.com/simple-observability/simob-agent/llms.txt Checks if the simob agent is currently running by examining its process lock file. Provides a clear indication of the agent's operational state. ```bash simob status ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.