### Komari Server Examples Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md Demonstrates starting the Komari server with different configurations for listening address and database. ```bash # Listen on all interfaces, port 8080 komari server -l 0.0.0.0:8080 ``` ```bash # Use custom SQLite database komari server -d ./my_komari.db ``` ```bash # Via environment variables KOMARI_DB_TYPE=sqlite KOMARI_DB_FILE=./data/metrics.db komari server ``` -------------------------------- ### Clone, Install, Build, and Copy Frontend Assets Source: https://github.com/komari-monitor/komari/blob/main/web/public/readme.md This sequence of commands clones the frontend repository, installs dependencies, builds the static files, and copies them into the backend's public directory. Ensure the target paths for copying are correct for your backend setup. ```bash # Clone frontend repository / 克隆前端仓库 / フロントエンドリポジトリをクローン git clone https://github.com/komari-monitor/komari-web cd komari-web # Install dependencies and build / 安装依赖并构建 / 依存関係をインストールしてビルド npm install npm run build # Copy frontend assets into the backend embed directory / 复制到后端 embed 目录 / バックエンドの embed ディレクトリにコピー mkdir -p /path/to/komari/web/public/defaultTheme/dist cp -r dist/* /path/to/komari/web/public/defaultTheme/dist/ cp komari-theme.json /path/to/komari/web/public/defaultTheme/ ``` -------------------------------- ### Install Komari with One-Click Script Source: https://github.com/komari-monitor/komari/blob/main/README.md Use this script for distributions using systemd like Ubuntu and Debian. Ensure you have curl installed. ```bash curl -fsSL https://raw.githubusercontent.com/komari-monitor/komari/main/install-komari.sh -o install-komari.sh chmod +x install-komari.sh sudo ./install-komari.sh ``` -------------------------------- ### Start Komari Server with SQLite Database Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md Use this command to start the Komari server and specify the path for the SQLite database file. The data directory will be created if it does not exist. ```bash mkdir -p ./data komari server -d ./data/komari.db ``` -------------------------------- ### WS /ws Client Command Example Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Example of a client command to restart a specific client, sent over the WebSocket connection. The connection uses JSON-RPC 2.0. ```json { "jsonrpc": "2.0", "id": 1, "method": "client.restart", "params": {"client_uuid": "..."} } ``` -------------------------------- ### Get and Set API Key Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md Demonstrates how to retrieve the current API key and set a new one using the configuration package. ```go // Get current API key apiKey, _ := config.GetAs[string](config.ApiKeyKey, "") // Set new API key config.Set(config.ApiKeyKey, "newSecretKey12345") ``` -------------------------------- ### Get All Configuration Items Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-config.md Retrieves all configuration items currently stored in the database as a map of key-value pairs. ```go allConfig, err := config.GetAll() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Client Token Authentication Examples Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md Demonstrates two ways to authenticate using a client token: as a query parameter or within a JSON request body. ```bash curl "http://localhost:8080/api/client/data?token=myClientToken" ``` ```bash curl -X POST http://localhost:8080/api/client/data \ -H "Content-Type: application/json" \ -d '{"token":"myClientToken"}' ``` -------------------------------- ### Initialize PostgreSQL Store Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-metric-store.md Example of initializing a Metric Store with PostgreSQL. Configures the driver, DSN, and default retention days. An optional dedicated read pool can be provided. ```go cfg := metric.Config{ Driver: metric.DriverPostgreSQL, DSN: "postgres://user:password@localhost:5432/metrics?sslmode=disable", DefaultRetentionDays: 180, ReadDB: readPool, // Optional dedicated read pool } store, err := metric.Open(context.Background(), cfg) ``` -------------------------------- ### Initialize MySQL Store Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-metric-store.md Example of initializing a Metric Store with MySQL. Specifies the driver, DSN, and default retention days. Ensure the DSN is correctly formatted for MySQL connections. ```go cfg := metric.Config{ Driver: metric.DriverMySQL, DSN: "user:password@tcp(localhost:3306)/metrics", DefaultRetentionDays: 180, } store, err := metric.Open(context.Background(), cfg) ``` -------------------------------- ### Manage Komari with Systemd Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md Commands to start, enable, and check the status of the Komari service managed by systemd. ```bash sudo systemctl start komari sudo systemctl enable komari sudo systemctl status komari ``` -------------------------------- ### Verify Two-Factor Authentication Setup Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Confirm the two-factor authentication setup by providing the verification code generated by your authenticator app. This completes the 2FA enablement process. ```json { "code": "123456" } ``` ```json { "status": "success" } ``` -------------------------------- ### Initialize SQLite Store Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-metric-store.md Example of initializing a Metric Store using SQLite. Sets the driver, DSN, default retention, and table prefix. Ensures the store is closed when done. ```go cfg := metric.Config{ Driver: metric.DriverSQLite, DSN: "file:./data/metrics.db?cache=shared&mode=rwc", DefaultRetentionDays: 90, TablePrefix: "metric_", } store, err := metric.Open(context.Background(), cfg) if err != nil { log.Fatal(err) } defer store.Close() ``` -------------------------------- ### Register RPC Handler Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/README.md Illustrates how to register a new handler for an RPC endpoint. This example registers a handler for 'system.status' and requires importing the 'pkg/rpc' package. ```go import "github.com/komari-monitor/komari/pkg/rpc" rpc.MustRegister("system.status", func(ctx context.Context, req *rpc.JsonRpcRequest) (any, *rpc.JsonRpcError) { return map[string]any{"online": true}, nil }) ``` -------------------------------- ### POST /api/admin/2fa/verify Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Verifies the two-factor authentication (2FA) setup. This endpoint confirms the 2FA setup using a provided verification code. ```APIDOC ## POST /api/admin/2fa/verify ### Description Confirms 2FA setup with verification code. ### Method POST ### Endpoint /api/admin/2fa/verify ### Parameters #### Request Body - **code** (string) - Required - The verification code from the 2FA app. ### Request Example ```json { "code": "123456" } ``` ### Response #### Success Response (200) Indicates the 2FA verification was successful. ``` -------------------------------- ### WS /ws Server Event Example Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Example of a system status event sent by the server over the WebSocket connection. The connection uses JSON-RPC 2.0. ```json { "jsonrpc": "2.0", "method": "system.status", "params": {"online": true} } ``` -------------------------------- ### Configure SQLite Database via Command-Line Arguments Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md Alternatively, configure the SQLite database type and path directly using command-line flags when starting the Komari server. ```bash komari server -t sqlite -d /var/lib/komari/komari.db ``` -------------------------------- ### Build Komari Frontend Source: https://github.com/komari-monitor/komari/blob/main/README.md Build the static frontend files for Komari. Requires Node.js 20+. Clone the repository and run npm install and build. ```bash git clone https://github.com/komari-monitor/komari-web cd komari-web npm install npm run build ``` -------------------------------- ### Set Initial Admin Credentials on First Startup Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md Provide initial administrator username and password via environment variables when starting the Komari server for the first time. This is used to create the initial admin user if the database is empty. ```bash ADMIN_USERNAME=admin ADMIN_PASSWORD=password123 komari server ``` -------------------------------- ### Komari Server Command Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md Starts the Komari monitoring server. Flags can be used to customize listen address and database type/path. ```bash komari server [flags] ``` -------------------------------- ### GET /api/version Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Returns Komari version information. ```APIDOC ## GET /api/version ### Description Returns Komari version information. ### Method GET ### Endpoint /api/version ### Response #### Success Response (200) - **status** (string) - Indicates the status of the service. - **data** (object) - Contains version details. - **version** (string) - The current version of Komari. - **hash** (string) - The git commit hash. ### Response Example ```json { "status": "success", "data": { "version": "0.x.x", "hash": "abc123def456" } } ``` ``` -------------------------------- ### API Key Authentication Example Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md Use this cURL command to authenticate with an API key. Ensure the key meets the minimum length requirement and is prefixed with 'Bearer '. ```bash curl -H "Authorization: Bearer mySecretKey12345" http://localhost:8080/api/admin ``` -------------------------------- ### GET /api/admin/config Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Retrieves the current system configuration. This endpoint returns all active configuration settings for the Komari system. ```APIDOC ## GET /api/admin/config ### Description Returns current configuration. ### Method GET ### Endpoint /api/admin/config ### Response #### Success Response (200) - **api_key** (string) - The API key used by the system. - **private_site** (boolean) - Indicates if the site is private. - **...** (any) - Other configuration fields. #### Response Example ```json { "status": "success", "data": { "api_key": "...", "private_site": false, "...": "..." } } ``` ``` -------------------------------- ### Enable Two-Factor Authentication Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Generate and retrieve the necessary secret and QR code for setting up two-factor authentication. This should be done before verifying the setup. ```json { "status": "success", "data": { "secret": "JBSWY3DPEBLW64TMMQ......", "qr_code": "data:image/png;base64,..." } } ``` -------------------------------- ### Setup Global Logger Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/utilities-reference.md Initializes the global structured logger using Go's slog package. Call this during application initialization. Supported levels include Debug, Info, Warn, and Error. ```go import logutil "github.com/komari-monitor/komari/utils/log" logutil.SetupGlobalLogger(slog.LevelInfo) ``` -------------------------------- ### WebSocket Connection Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Example of establishing a WebSocket connection for real-time communication, including sending RPC requests and handling responses. ```APIDOC ## WebSocket Connection ### Description This example illustrates how to establish a WebSocket connection for real-time communication, including sending JSON-RPC requests and processing responses. ### Endpoint ws://localhost:25774/ws ### Request Example ```javascript const ws = new WebSocket('ws://localhost:25774/ws'); ws.onopen = () => { // Send RPC request ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "system.getStatus", params: {} })); }; ws.onmessage = (event) => { const response = JSON.parse(event.data); console.log(response); }; ``` ``` -------------------------------- ### Session Authentication Example (Client-Side) Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md This JavaScript snippet demonstrates how a client can send session cookies to the server for authentication. The 'credentials: 'include'' option is crucial for this. ```javascript fetch('/api/data', { credentials: 'include' // Sends cookies }) ``` -------------------------------- ### Handling RPC Errors with ResponseWithID Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-rpc.md Example demonstrating how to use ResponseWithID to return an error response when a request validation fails. ```go if err := request.Validate(); err != nil { return err.ResponseWithID(request.ID) } ``` -------------------------------- ### Authenticated Request using Session Token Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Example of making a request to the admin configuration endpoint using a session token for authentication. ```bash curl -b "session_token=SESSION_TOKEN" \ http://localhost:25774/api/admin/config ``` -------------------------------- ### Batch Get Configuration Values Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-config.md Retrieves multiple configuration values in a single batch operation. Missing keys with non-nil defaults specified in the input map will be written to the database. ```go result, err := config.GetMany(map[string]any{ "port": 8080, "host": "localhost", "timeout": nil, // Not written if missing }) // result["port"] = 8080 (or database value if exists) // result["timeout"] = (zero value, not in db) ``` -------------------------------- ### Authenticated Request (Session) Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Example of how to make an authenticated request using a session token. This is useful for accessing administrative configurations. ```APIDOC ## Authenticated Request (Session) ### Description This example demonstrates how to authenticate requests using a session token, typically for accessing administrative configurations. ### Method GET ### Endpoint http://localhost:25774/api/admin/config ### Request Example ```bash curl -b "session_token=SESSION_TOKEN" \ http://localhost:25774/api/admin/config ``` ``` -------------------------------- ### Identity Middleware Setup Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md Applies the IdentityMiddleware to a Gin router to identify the request's identity using API Key, Session Token, or Client Token. ```go router.Use(IdentityMiddleware()) router.GET("/api/data", handler) ``` -------------------------------- ### Call HTTP API Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/README.md Provides an example of how to call an HTTP API endpoint using curl, including setting an Authorization header. ```bash curl -H "Authorization: Bearer API_KEY" \ http://localhost:25774/api/admin/config ``` -------------------------------- ### Get Current Configuration Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Retrieve the current system configuration settings. This includes sensitive information like API keys and private site status. ```json { "status": "success", "data": { "api_key": "...", "private_site": false, "...": "..." } } ``` -------------------------------- ### POST /api/admin/update/download Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Initiates the download of the latest system update. This endpoint starts the process of downloading the most recent version of the Komari system. ```APIDOC ## POST /api/admin/update/download ### Description Starts downloading latest update. ### Method POST ### Endpoint /api/admin/update/download ### Response #### Success Response (200) - **download_url** (string) - The URL from which the update can be downloaded. #### Response Example ```json { "status": "success", "data": { "download_url": "https://github.com/..." } } ``` ``` -------------------------------- ### Configure SQLite Database via Environment Variables Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md Set environment variables to configure the SQLite database type and file path before starting the Komari server. This is the default database configuration. ```bash export KOMARI_DB_TYPE=sqlite export KOMARI_DB_FILE=./data/komari.db komari server ``` -------------------------------- ### Multi-Role Endpoint Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md Example of an endpoint accessible by multiple roles (Admin and Client), with behavior dynamically adjusting based on the authenticated user's role. ```APIDOC ## Multi-Role Endpoint ### Description This endpoint provides system status information and can be accessed by both 'admin' and 'client' roles. The response content varies based on the user's role. ### Method `GET` ### Endpoint `/api/status` ### Behavior - Requires `RoleAdmin` or `RoleClient`. - If role is 'admin', returns full system status. - If role is 'client', returns the specific client's status. ### Response #### Success Response (200) - (Response varies based on role. Admin receives full system status, Client receives their own status.) ``` -------------------------------- ### Generate 2FA Secret and QR Code Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Generates a TOTP secret and a QR code image for Two-Factor Authentication setup. Requires handling the returned error. ```go secret, img, err := accounts.Generate2Fa() if err != nil { return err } // Display img to user, have them scan it, then verify secret ``` -------------------------------- ### Authenticated Request using Client Token and POST Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Example of sending a POST request with a JSON payload to the client report endpoint, authenticated by a client token. ```bash curl "http://localhost:25774/api/client/report?token=CLIENT_TOKEN" \ -X POST \ -H "Content-Type: application/json" \ -d '{"cpu": 45.5}' ``` -------------------------------- ### Get Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-config.md Retrieves a configuration value by key. An optional default value can be provided if the key is not found. Errors occur if the key is not found and no default is given, or if there's a JSON unmarshalling failure. ```APIDOC ## Get ### Description Retrieves a configuration value by key and deserializes it as `interface{}`. An optional default value can be provided if the key is not found. Errors occur if the key is not found and no default is given, or if there's a JSON unmarshalling failure. ### Function Signature ```go func Get(key string, defaul ...any) (any, error) ``` ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - **key** (string) - Required - Configuration key to retrieve - **defaul** (...any) - Optional - Optional default value if key not found ### Returns - **any** - Deserialized value or default - **error** - Error if retrieval fails ### Example ```go val, err := config.Get("mykey", "default_value") if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Initialize Configuration System Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/README.md Demonstrates how to initialize the configuration system by setting a database connection and retrieving/setting configuration values. Requires importing the 'pkg/config' package. ```go import "github.com/komari-monitor/komari/pkg/config" config.SetDb(gormDB) value, _ := config.GetAs[string]("api_key", "") config.Set("new_key", "value") ``` -------------------------------- ### Deploy Komari Binary Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md Steps to download, make executable, and run the Komari binary for deployment. ```bash # Download from GitHub releases wget https://github.com/komari-monitor/komari/releases/download/v0.x.x/komari-linux-amd64 # Make executable chmod +x komari-linux-amd64 # Run ./komari-linux-amd64 server -l 0.0.0.0:25774 ``` -------------------------------- ### GET /api/me Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Returns current authenticated user info. ```APIDOC ## GET /api/me ### Description Returns current authenticated user info. ### Method GET ### Endpoint /api/me ### Authentication Auth Required: Yes (Admin) ### Response #### Success Response (200) - **status** (string) - Indicates the status of the service. - **data** (object) - Contains user information. - **uuid** (string) - The unique identifier of the user. - **username** (string) - The username of the authenticated user. - **has_2fa** (boolean) - Indicates if two-factor authentication is enabled for the user. ### Response Example ```json { "status": "success", "data": { "uuid": "user-uuid", "username": "admin", "has_2fa": true } } ``` ``` -------------------------------- ### GET /api/recent Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Returns recent activity/status (public view). ```APIDOC ## GET /api/recent ### Description Returns recent activity/status (public view). ### Method GET ### Endpoint /api/recent ### Response #### Success Response (200) - **status** (string) - Indicates the status of the service. - **data** (object) - Contains recent activity data. - **clients** (array) - List of recent clients. - **recent_records** (array) - List of recent records. ### Response Example ```json { "status": "success", "data": { "clients": [...], "recent_records": [...] } } ``` ``` -------------------------------- ### Open Store Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-metric-store.md Initializes a Store from a Config, creates connection pools, and runs auto-migrations. It validates the configuration, creates database connection pools, and auto-migrates the schema. For SQLite, it also creates the parent directory if needed. ```APIDOC ## Open ### Description Initializes a Store from a Config, creates connection pools, and runs auto-migrations. ### Function Signature ```go func Open(ctx context.Context, cfg Config) (*Store, error) ``` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters Table | Parameter | Type | Description | |-----------|-----------------|--------------------------| | ctx | context.Context | Context for connection timeout | | cfg | Config | Store configuration | ### Returns - *Store: Initialized Store pointer - error: error on failure ### Example ```go store, err := metric.Open(context.Background(), metric.Config{ Driver: metric.DriverSQLite, DSN: "file:metrics.db", DefaultRetentionDays: 90, }) if err != nil { log.Fatal(err) } defer store.Close() ``` ``` -------------------------------- ### GET /api/ping Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Health check endpoint. Always accessible. ```APIDOC ## GET /api/ping ### Description Health check endpoint. Always accessible. ### Method GET ### Endpoint /api/ping ### Response #### Success Response (200) - **status** (string) - Indicates the status of the service. ### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Unauthorized Error Response Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md Example of an unauthorized error response when no authentication is provided. ```json { "status": "error", "message": "Unauthorized." } ``` -------------------------------- ### Get Client UUID by Token Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Resolves a client's UUID using its authentication token. ```go func GetClientUUIDByToken(token string) (string, error) ``` -------------------------------- ### Open Metric Store Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-metric-store.md Initializes a Metric Store from configuration. It handles connection pooling and auto-migrations. Ensure context is provided for connection timeouts. ```go func Open(ctx context.Context, cfg Config) (*Store, error) ``` ```go store, err := metric.Open(context.Background(), metric.Config{ Driver: metric.DriverSQLite, DSN: "file:metrics.db", DefaultRetentionDays: 90, }) if err != nil { log.Fatal(err) } defer store.Close() ``` -------------------------------- ### Build Komari Backend Source: https://github.com/komari-monitor/komari/blob/main/README.md Build the Komari backend binary. Requires Go 1.18+. Copy frontend static files and theme assets before building. ```bash git clone https://github.com/komari-monitor/komari cd komari go build -o komari ``` -------------------------------- ### GET /api/client/basicinfo Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Retrieves the basic information for the authenticated client. This includes its unique identifier, name, and region. ```APIDOC ## GET /api/client/basicinfo ### Description Retrieves basic client information. ### Method GET ### Endpoint /api/client/basicinfo ### Response #### Success Response (200) - **status** (string) - Indicates the status of the operation, expected to be "success". - **data** (object) - Contains the client's basic information. - **uuid** (string) - The unique identifier of the client. - **name** (string) - The name of the client. - **region** (string) - The region where the client is located. #### Response Example ```json { "status": "success", "data": { "uuid": "client-uuid", "name": "Server 1", "region": "US-East" } } ``` ``` -------------------------------- ### SetDb Initialization Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-config.md Initializes the configuration system by setting the global database instance and performing schema auto-migration. ```APIDOC ## SetDb Initialization ### Description Must be called once at startup to initialize the config system with a GORM database instance. ### Method Signature ```go var SetDb = func(gdb *gorm.DB) { // Sets global database instance and auto-migrates schema } ``` ### Parameters #### Path Parameters - **gdb** (*gorm.DB) - Required - The GORM database instance. ### Example ```go db, _ := gorm.Open(sqlite.Open("data.db")) config.SetDb(db) ``` ``` -------------------------------- ### Private Site Blocked Error Response Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md Example of an error response when a private site is enabled and access is blocked. ```json { "status": "error", "message": "Private site is enabled, please login first." } ``` -------------------------------- ### GetAll Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-config.md Retrieves all configuration items currently stored in the database. ```APIDOC ## GetAll ### Description Retrieves all configuration items in the database. ### Function Signature ```go func GetAll() (map[string]any, error) ``` ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Returns - **map[string]any** - Map containing all keys and their corresponding values ### Example ```go allItems, err := config.GetAll() if err != nil { log.Fatal(err) } // Process allItems map ``` ``` -------------------------------- ### Get All Active Sessions Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Retrieves a list of all currently active user sessions. Returns a slice of models.Session or an error. ```go func GetAllSessions() (sessions []models.Session, err error) ``` -------------------------------- ### GET /api/client/basicinfo Response Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Retrieve basic client information including UUID, name, and region. Authentication is required. ```json { "status": "success", "data": { "uuid": "client-uuid", "name": "Server 1", "region": "US-East" } } ``` -------------------------------- ### Check and Enable Private Site Mode Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md Shows how to check the status of private site mode and enable it using the configuration package. ```go // Check if private site enabled isPrivate, _ := config.GetAs[bool](config.PrivateSiteKey, false) // Enable private site config.Set(config.PrivateSiteKey, true) ``` -------------------------------- ### GET /api/admin/update/check Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Checks for available system updates. This endpoint queries the system to see if a newer version is available. ```APIDOC ## GET /api/admin/update/check ### Description Checks for available updates. ### Method GET ### Endpoint /api/admin/update/check ### Response #### Success Response (200) - **current_version** (string) - The currently installed version of the system. - **latest_version** (string) - The latest available version of the system. - **update_available** (boolean) - True if an update is available, false otherwise. #### Response Example ```json { "status": "success", "data": { "current_version": "0.x.x", "latest_version": "0.y.y", "update_available": true } } ``` ``` -------------------------------- ### Initialize Database Connection Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Initializes the global database connection with the specified driver and data source name (DSN). Supported drivers include 'sqlite', 'mysql', and 'postgresql'. ```Go err := dbcore.InitDB("sqlite", "file:test.db?cache=shared&mode=rwc") ``` -------------------------------- ### Deploy Komari with Docker Source: https://github.com/komari-monitor/komari/blob/main/README.md Run Komari as a Docker container. Mount a local directory for data persistence. View logs for default credentials. ```bash mkdir -p ./data ``` ```bash docker run -d \ -p 25774:25774 \ -v $(pwd)/data:/app/data \ --name komari \ ghcr.io/komari-monitor/komari:latest ``` ```bash docker logs komari ``` -------------------------------- ### InitDB Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Initializes the global database connection using the specified driver and data source name. ```APIDOC ## InitDB ### Description Initializes the global database connection. ### Signature ```go func InitDB(driver string, dsn string) error ``` ### Parameters #### Path Parameters - **driver** (string) - Required - Specifies the database driver: "sqlite", "mysql", or "postgresql". - **dsn** (string) - Required - The connection string for the database. ``` -------------------------------- ### Protected Admin Endpoint Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md Example of an endpoint that requires admin privileges to access. It demonstrates how to protect routes and access user information. ```APIDOC ## Protected Admin Endpoint ### Description This endpoint is protected and only accessible by users with the 'admin' role. It demonstrates how to enforce role-based access control and perform administrative actions. ### Method `POST` ### Endpoint `/api/admin/restart` ### Behavior - Requires `RoleAdmin`. - Accesses the admin's UUID from the context. - Executes a server restart function. ### Request Example (See general API Key Authentication example for setting the Authorization header) ### Response #### Success Response (200) - `status` (string) - Indicates the server is restarting. ``` -------------------------------- ### Run Komari Binary Source: https://github.com/komari-monitor/komari/blob/main/README.md Execute the Komari binary directly. Ensure it has execute permissions. Data is saved in the 'data' folder. ```bash ./komari server -l 0.0.0.0:25774 ``` -------------------------------- ### Authenticated Request (API Key) Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Example of how to make an authenticated request using an API key. This is a common method for server-to-server authentication. ```APIDOC ## Authenticated Request (API Key) ### Description This example shows how to authenticate requests using an API key, commonly employed for server-to-server interactions. ### Method GET ### Endpoint http://localhost:25774/api/admin/config ### Request Example ```bash curl -H "Authorization: Bearer API_KEY" \ http://localhost:25774/api/admin/config ``` ``` -------------------------------- ### Initialize Komari Config with Database Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-config.md Call this function once at application startup to set the global GORM database instance for the configuration system. This is required before any configuration operations that interact with the database. ```go var SetDb = func(gdb *gorm.DB) { // Sets global database instance and auto-migrates schema } ``` ```go db, _ := gorm.Open(sqlite.Open("data.db")) config.SetDb(db) ``` -------------------------------- ### Create User Session After Login Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Handles user authentication, including optional two-factor authentication (2FA), and creates a session token. Sets a session cookie upon successful authentication. ```Go // 1. Verify credentials uuid, success := accounts.CheckPassword(username, password) if !success { return errors.New("invalid credentials") } // 2. Verify 2FA if enabled if has2FA(uuid) { // Get 2FA code from user if !accounts.Verify2Fa(uuid, code) { return errors.New("invalid 2FA code") } } // 3. Create session token, err := accounts.CreateSession(uuid, 86400, userAgent, clientIP, "password") if err != nil { return err } // 4. Set session cookie c.SetCookie("session_token", token, 86400, "/", "", false, true) ``` -------------------------------- ### Get Global GORM DB Instance Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Retrieves the globally managed GORM database instance. Ensure the database is initialized before calling this function. ```Go db := dbcore.GetDBInstance() var users []models.User db.Find(&users) ``` -------------------------------- ### Save Client Metrics Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/README.md Shows how to save client-specific reports using the 'SaveClientReport' function. Requires importing the 'database/clients' package. ```go import "github.com/komari-monitor/komari/database/clients" clients.SaveClientReport(clientUUID, &report) ``` -------------------------------- ### GET /api/admin/themes Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Lists all available dashboard themes. This endpoint retrieves a list of themes, including their IDs, names, and preview image paths. ```APIDOC ## GET /api/admin/themes ### Description Lists available dashboard themes. ### Method GET ### Endpoint /api/admin/themes ### Response #### Success Response (200) - **id** (string) - The unique identifier for the theme. - **name** (string) - The display name of the theme. - **preview** (string) - The path to the theme's preview image. #### Response Example ```json { "status": "success", "data": [ { "id": "defaultTheme", "name": "Default", "preview": "preview.png" } ] } ``` ``` -------------------------------- ### Subscribe to Configuration Change Events Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-config.md Register a callback function using `Subscribe` to receive notifications for all configuration changes. Subscribers are invoked asynchronously. ```go config.Subscribe(func(event config.ConfigEvent) { if event.IsChanged("debug_mode") { fmt.Println("Debug mode changed!") } }) ``` -------------------------------- ### Access API with Bearer Token Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md Demonstrates how to authenticate API requests using a Bearer token. ```bash curl -H "Authorization: Bearer mySecretKey12345" \ http://localhost:25774/api/clients ``` -------------------------------- ### Run Komari with Docker Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md Deploys Komari using Docker, mapping ports, persisting data, and setting admin credentials. ```bash docker run -d \ -p 25774:25774 \ -v $(pwd)/data:/app/data \ -e ADMIN_USERNAME=admin \ -e ADMIN_PASSWORD=mypassword \ ghcr.io/komari-monitor/komari:latest ``` -------------------------------- ### Create User Session Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Creates a new authenticated session for a user. Requires user UUID, expiration time, User-Agent, client IP, and login method. Returns the session token or an error. ```go token, err := accounts.CreateSession(userUUID, 86400, userAgent, clientIP, "password") if err != nil { log.Fatal(err) } // Set session_token cookie ``` -------------------------------- ### Export Database to ZIP Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Exports the entire database content into a ZIP archive at the specified destination path. This is useful for creating backups. ```Go err := dbcore.ExportDatabaseAsZip("./backup.zip") ``` -------------------------------- ### Get User UUID from Session Token Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Retrieves the user's UUID associated with a given session token. Returns the UUID and any error encountered. ```go func GetSession(sessionToken string) (uuid string, err error) ``` -------------------------------- ### SetupGlobalLogger Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/utilities-reference.md Initializes the global structured logger for the application. This function configures the logging level, which can be set to Debug, Info, Warn, or Error. ```APIDOC ## SetupGlobalLogger ### Description Initializes global structured logger using Go's slog package. ### Method ```go func SetupGlobalLogger(level slog.Level) ``` ### Parameters #### Path Parameters - **level** (slog.Level) - Required - Log level (Debug, Info, Warn, Error) ### Request Example ```go import logutil "github.com/komari-monitor/komari/utils/log" logutil.SetupGlobalLogger(slog.LevelInfo) ``` ### Response This function does not return any value. ``` -------------------------------- ### Client Access Endpoint Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md Example of an endpoint designed for client access, allowing clients to submit reports. It demonstrates role enforcement and request body parsing. ```APIDOC ## Client Access Endpoint ### Description This endpoint allows clients to submit reports. It requires the 'client' role and processes a JSON payload containing report data. ### Method `POST` ### Endpoint `/api/client/report` ### Parameters #### Request Body - `ReportData` (object) - Contains the data for the client report. - Example structure: `{"field1": "value1", "field2": 123}` ### Behavior - Requires `RoleClient`. - Retrieves the client's UUID from the context. - Parses the incoming JSON report data. - Saves the client report. ### Request Example ```json { "field1": "some data", "field2": 42 } ``` ### Response #### Success Response (200) - (No specific fields returned on success, indicates successful report submission) ``` -------------------------------- ### Filtering and Sorting Clients Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/utilities-reference.md Provides utilities to filter clients by tags and sort them by priority. Useful for managing and displaying client lists. ```Go import "github.com/komari-monitor/komari/utils/item" // Filter by tags webClients := item.FilterByTags(allClients, []string{"web"}) // Sort by priority item.SortByWeight(webClients) // Display in order for _, client := range webClients { fmt.Println(client.Name) } ``` -------------------------------- ### Metric Store Driver Types Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-metric-store.md Defines the available database backends for the metric store. Use these constants when configuring the store. ```go type Driver string const ( DriverSQLite Driver = "sqlite" DriverMySQL Driver = "mysql" DriverPostgreSQL Driver = "postgresql" ) ``` -------------------------------- ### Get Cloudflare Tunnel Status Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/utilities-reference.md Checks if Cloudflare Tunnel is active and retrieves its public URL. Returns a boolean indicating activity, the tunnel URL, and an error if any. ```Go func GetTunnelStatus() (active bool, url string, err error) ``` ```Go active, url, err := cloudflared.GetTunnelStatus() if active { fmt.Println("Tunnel URL:", url) } ``` -------------------------------- ### Client Access Endpoint Implementation Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-web-auth.md This Go code snippet demonstrates an endpoint for client access, requiring the 'Client' role. It binds JSON data, saves a client report, and handles potential errors. ```go router.POST("/api/client/report", RequireRole(RoleClient), func(c *gin.Context) { clientUUID := c.GetString("client_uuid") var report ReportData if err := c.BindJSON(&report); err != nil { api.RespondError(c, http.StatusBadRequest, "Invalid report format") return } if err := saveClientReport(clientUUID, report); err != nil { api.RespondError(c, http.StatusInternalServerError, "Failed to save report") return } api.RespondSuccess(c, nil) }) ``` -------------------------------- ### Authenticated Request (Client Token) Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/http-endpoints.md Example of making an authenticated POST request using a client token, often used for sending client-side data like reports. ```APIDOC ## Authenticated Request (Client Token) ### Description This example demonstrates how to make an authenticated POST request using a client token, typically for submitting client reports. ### Method POST ### Endpoint http://localhost:25774/api/client/report ### Parameters #### Query Parameters - **token** (string) - Required - The client token for authentication. #### Request Body - **cpu** (number) - Required - The CPU usage percentage. ### Request Example ```bash curl "http://localhost:25774/api/client/report?token=CLIENT_TOKEN" \ -X POST \ -H "Content-Type: application/json" \ -d '{"cpu": 45.5}' ``` ``` -------------------------------- ### User Login Flow Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/architecture-overview.md Outlines the process for user authentication, including password verification, optional 2FA, session creation, and token handling. ```text 1. POST /api/login {"username": "admin", "password": "..."} ↓ 2. accounts.CheckPassword(username, passwd) ↓ 3. Verify bcrypt hash in database ↓ 4. If 2FA enabled: a. Prompt for code b. accounts.Verify2Fa(uuid, code) ↓ 5. accounts.CreateSession(uuid, expires, ua, ip, method) ↓ 6. Generate random session token ↓ 7. Store Session record in database ↓ 8. Return token in response ↓ 9. Client sets session_token cookie ↓ 10. Future requests: IdentityMiddleware validates token ``` -------------------------------- ### Metric Store Configuration Structure Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-metric-store.md Defines the structure for configuring a new metric store instance. Includes database connection details, retention policies, and table naming conventions. ```go type Config struct { Driver Driver DSN string DB *sql.DB // Optional: use existing connection ReadDB *sql.DB // Optional: dedicated read pool DefaultRetentionDays int // Data retention (days) TablePrefix string // Metric table prefix ConnectTimeout time.Duration } ``` -------------------------------- ### GetDBInstance Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/database-access.md Retrieves the global GORM database instance. This function should be called after the database has been initialized. ```APIDOC ## GetDBInstance ### Description Returns the global GORM database instance. Must be initialized before use. ### Signature ```go func GetDBInstance() *gorm.DB ``` ### Example ```go db := dbcore.GetDBInstance() var users []models.User db.Find(&users) ``` ``` -------------------------------- ### Set Configuration from Struct using JSON Tags Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/api-reference-config.md Use `SetManyAs` to set multiple configuration items from a struct. The struct fields should be tagged with `json` to map to configuration keys. ```go type AppSettings struct { Port int `json:"port"` Host string `json:"host"` } err := config.SetManyAs[AppSettings](AppSettings{Port: 9000, Host: "0.0.0.0"}) ``` -------------------------------- ### Sending Notifications Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/utilities-reference.md Sends a message to a list of clients. Requires importing the messageSender utility and client models. ```Go import ( "github.com/komari-monitor/komari/utils/messageSender" "github.com/komari-monitor/komari/database/models" ) clients := []models.Client{client1, client2} err := messageSender.SendMessage( "offline", clients, "Server went offline - please investigate", ) ``` -------------------------------- ### Komari Root Command Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/cli-and-configuration.md The main entry point for Komari commands. Default behavior is to run the server. ```bash komari [flags] ``` -------------------------------- ### Get Client Renewal Status Source: https://github.com/komari-monitor/komari/blob/main/_autodocs/utilities-reference.md Determines the renewal status for a given client, checking if it's expired, expiring soon, active, or never set to expire. Used for dashboard alerts and reports. ```Go func GetRenewalStatus(client models.Client) (status string, daysUntilExpiry int) ```