### Start Testing Sandbox Source: https://github.com/percona/mongodb_exporter/blob/main/CONTRIBUTING.md Run this make command to start the testing sandbox environment, which includes multiple MongoDB instances. ```bash make test-cluster ``` -------------------------------- ### Example GET Requests with collect[] Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/endpoints.md Demonstrates how to use the `collect[]` parameter in GET requests to control which collectors are executed. The first example shows only the `dbstats` collector running. The second example targets a specific host and runs `collstats` and `indexstats`. The third example applies collectors to all instances. ```http GET /metrics?collect[]=dbstats → Only dbstats collector runs ``` ```http GET /scrape?target=localhost:27017&collect[]=collstats&collect[]=indexstats → Only collstats and indexstats collectors run for that target ``` ```http GET /scrapeall?collect[]=diagnosticdata&collect[]=replicasetstatus → Only these collectors for all instances ``` -------------------------------- ### Full MongoDB Exporter Startup Example Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/main-entry-point.md This example demonstrates a complete startup command for the MongoDB exporter, including connection details, collection monitoring, listening address, metrics path, enabled collectors, log level, and timeout offset. ```bash #!/bin/bash mongodb_exporter \ --mongodb.uri=mongodb://user:pass@localhost:27017/admin \ --mongodb.collstats-colls=mydb.users,mydb.orders \ --web.listen-address=:9216 \ --web.telemetry-path=/metrics \ --collector.diagnosticdata \ --collector.dbstats \ --collector.collstats \ --log.level=info \ --web.timeout-offset=2 ``` -------------------------------- ### Install Development Tools Source: https://github.com/percona/mongodb_exporter/blob/main/docs/development-guide.md Run 'make init' to install necessary tools for code checking, linting, formatting, and testing. This command ensures your development environment is set up correctly. ```bash make init ``` -------------------------------- ### Start HTTP Server and Register Handlers Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/exporter.md RunWebServer starts the HTTP server, registers metric handlers for /metrics, /scrape, and /scrapeall, and applies TLS configuration if provided. Ensure the exporters list is not empty to avoid panics. ```go serverOpts := &exporter.ServerOpts{ WebListenAddress: ":9216", Path: "/metrics", } exporter.RunWebServer(serverOpts, []*exporter.Exporter{exp1, exp2}, logger) ``` -------------------------------- ### Provide MongoDB URI Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/main-entry-point.md Ensure at least one MongoDB URI is provided when starting the exporter. This example shows the command-line flag. ```bash mongodb_exporter --mongodb.uri=mongodb://localhost:27017 ``` -------------------------------- ### Start Test Sandbox Source: https://github.com/percona/mongodb_exporter/blob/main/docs/development-guide.md Use this command to create the Docker-based test sandbox for the exporter. ```bash make test-cluster ``` -------------------------------- ### Initialize Development Environment Source: https://github.com/percona/mongodb_exporter/blob/main/CONTRIBUTING.md Installs necessary development tools like goimports, goreleaser, golangci-lint, and reviewdog for formatting, linting, and building the exporter. ```bash make init ``` -------------------------------- ### Start Sandbox with Specific MongoDB Version Source: https://github.com/percona/mongodb_exporter/blob/main/docs/development-guide.md Specify a different MongoDB base image version using the TEST_MONGODB_IMAGE environment variable when starting the sandbox. ```bash TEST_MONGODB_IMAGE=mongo:5.0 make test-cluster ``` -------------------------------- ### Example ServerMap Usage Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/types.md Illustrates how to initialize a ServerMap with specific host:port combinations mapped to exporter handlers. Used for multi-target routing. ```go serverMap := ServerMap{ "localhost:27017": exporter1.Handler(), "localhost:27018": exporter2.Handler(), } ``` -------------------------------- ### Start Exporter with Multiple URIs and Scrape Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/endpoints.md Demonstrates how to start the exporter with multiple MongoDB URIs and then scrape specific instances using curl. Filters can be applied to specific scrapes. ```bash # Start exporter with multiple URIs mongodb_exporter \ --mongodb.uri=mongodb://host1:27017 \ --mongodb.uri=mongodb://host2:27018 # Scrape host1 curl http://exporter:9216/scrape?target=host1:27017 # Scrape host2 with filters curl http://exporter:9216/scrape?target=host2:27018?collect[]=dbstats ``` -------------------------------- ### Counter Metric Examples Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/metrics-nomenclature.md Examples of monotonically increasing counter metrics. Use these for counts that only go up. ```text mongodb_ss_opcounters_insert_total 12345 mongodb_ss_connections_total_created 500 ``` -------------------------------- ### RunWebServer() Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/SUMMARY.txt Starts the web server for the exporter. This function is responsible for listening for HTTP requests and serving metrics. ```APIDOC ## RunWebServer() ### Description Starts the web server for the exporter. ### Method (Function Signature) ### Parameters (Details on parameters for RunWebServer() would be here if available in source) ### Return Value (Details on return values for RunWebServer() would be here if available in source) ### Example (Code example for RunWebServer() would be here if available in source) ``` -------------------------------- ### Response Example for /scrapeall Endpoint Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/endpoints.md Illustrates the Prometheus exposition format with instance labels for aggregated metrics collected by the /scrapeall endpoint. ```text # HELP mongodb_up MongoDB instance is up # TYPE mongodb_up gauge mongodb_up{instance="host1:27015"} 1 mongodb_up{instance="host2:27016"} 1 # HELP mongodb_ss_connections Current connections # TYPE mongodb_ss_connections gauge mongodb_ss_connections{conn_type="current",instance="host1:27015"} 5 mongodb_ss_connections{conn_type="current",instance="host2:27016"} 3 mongodb_ss_connections{conn_type="available",instance="host1:27015"} 819195 mongodb_ss_connections{conn_type="available",instance="host2:27016"} 819197 ``` -------------------------------- ### Gauge Metric Examples Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/metrics-nomenclature.md Examples of gauge metrics that can increase or decrease. Use these for current values or quantities. ```text mongodb_ss_connections_current 5 mongodb_ss_global_lock_active_readers 2 ``` -------------------------------- ### MongoDB Exporter Example Usage Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/main-entry-point.md Demonstrates various ways to run the MongoDB exporter from the command line, including basic usage, enabling specific collectors, configuring multi-target instances, and checking the version. ```bash # Basic usage mongodb_exporter --mongodb.uri=mongodb://localhost:27017/admin ``` ```bash # With collectors mongodb_exporter \ --mongodb.uri=mongodb://localhost:27017/admin \ --collector.diagnosticdata \ --collector.dbstats ``` ```bash # Multi-target mongodb_exporter \ --mongodb.uri=mongodb://host1:27017 \ --mongodb.uri=mongodb://host2:27017 ``` ```bash # With version check mongodb_exporter --version ``` -------------------------------- ### Configuration for /scrapeall Endpoint Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/endpoints.md Example configuration showing how to specify multiple MongoDB URIs for the /scrapeall endpoint to aggregate metrics from. ```bash --mongodb.uri=mongodb://host1:27015 --mongodb.uri=mongodb://host2:27016 ``` -------------------------------- ### Start MongoDB Test Cluster Source: https://github.com/percona/mongodb_exporter/blob/main/CONTRIBUTING.md Starts a MongoDB test cluster for running tests. You can specify the MongoDB image flavor and version using the TEST_MONGODB_IMAGE environment variable. ```bash TEST_MONGODB_IMAGE=mongo:3.6 make test-cluster ``` -------------------------------- ### Go Function Signature Example Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/README.md Illustrates the expected format for function signatures in the documentation, including parameter and return types. This is useful for understanding the API's structure. ```go func Name(param Type) ReturnType ``` -------------------------------- ### Run MongoDB Exporter Source: https://github.com/percona/mongodb_exporter/wiki/Home Start the exporter binary. It connects to mongodb://localhost:27017 by default if no options are provided. Recommended options include -mongodb.uri, -auth.user, -auth.pass, -web.listen-address, and -log_dir. ```bash ./mongodb_exporter ``` -------------------------------- ### RunWebServer Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/exporter.md Starts the HTTP server and registers all metric handlers. This function configures and launches the web server for the exporter, including endpoints for metrics, scraping, and information. ```APIDOC ## RunWebServer ### Description Starts the HTTP server and registers all metric handlers. This function configures and launches the web server for the exporter, including endpoints for metrics, scraping, and information. ### Signature ```go func RunWebServer(opts *ServerOpts, exporters []*Exporter, log *slog.Logger) ``` ### Parameters #### Path Parameters - **opts** (*ServerOpts) - Required - Server configuration options - **exporters** ([*Exporter]) - Required - List of Exporter instances for multiple targets - **log** (*slog.Logger) - Required - Logger instance for errors and debug info ### Behavior - Creates HTTP multiplexer with standard routes - Registers `/metrics` endpoint (first exporter) - Registers `/scrape` endpoint for multi-target scraping - Registers `/scrapeall` endpoint for all targets in one request - Registers root `/` endpoint with HTML info page - Applies TLS configuration if TLSConfigPath provided - Starts listening on WebListenAddress ### Panics - If exporters list is empty ### Request Example ```go serverOpts := &exporter.ServerOpts{ WebListenAddress: ":9216", Path: "/metrics", } exporter.RunWebServer(serverOpts, []*exporter.Exporter{exp1, exp2}, logger) ``` ``` -------------------------------- ### GET / Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/exporter.md The root endpoint serves a simple HTML page with a link to the /metrics endpoint. ```APIDOC ## GET / ### Description Root endpoint serving HTML information page. ### Method GET ### Endpoint / ### Response - Content-Type: `text/html` - Body: Simple HTML with link to `/metrics` ``` -------------------------------- ### Minimal MongoDB Exporter Configuration Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/INDEX.md Use this basic configuration to start the exporter with a single MongoDB instance. Ensure the MongoDB URI is correctly specified. ```bash mongodb_exporter --mongodb.uri=mongodb://localhost:27017/admin ``` -------------------------------- ### Configure Web Server Listen Address Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/configuration.md Set the address and port for the HTTP server. Examples include listening on all interfaces, localhost only, or IPv6 localhost. ```bash --web.listen-address=:9216 ``` ```bash --web.listen-address=127.0.0.1:9216 ``` ```bash --web.listen-address=[::1]:9216 ``` -------------------------------- ### Histogram Metric Examples Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/metrics-nomenclature.md Examples of histogram metrics used for latency distributions. These include bucket counts, total counts, and sums. ```text mongodb_op_latencies_write_bucket{le="10"} 100 mongodb_op_latencies_write_count 1000 mongodb_op_latencies_write_sum 45000 ``` -------------------------------- ### List All MongoDB Metrics Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/metrics-nomenclature.md Use this command to list all unique metric names starting with 'mongodb_'. ```bash curl -s http://localhost:9216/metrics | grep "^mongodb_" | cut -d'{' -f1 | sort -u ``` -------------------------------- ### Prometheus Metrics Endpoint Example Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/endpoints.md This snippet shows the expected output format for the /metrics endpoint, which exposes MongoDB metrics in Prometheus exposition format. ```text # HELP mongodb_up Whether the MongoDB instance is up # TYPE mongodb_up gauge mongodb_up 1 # HELP mongodb_ss_connections Current MongoDB connections # TYPE mongodb_ss_connections gauge mongodb_ss_connections{conn_type="current"} 5 mongodb_ss_connections{conn_type="available"} 819195 # HELP mongodb_dbstats_collections Number of collections in database # TYPE mongodb_dbstats_collections gauge mongodb_dbstats_collections{database="admin"} 0 mongodb_dbstats_collections{database="mydb"} 5 ``` -------------------------------- ### Count All MongoDB Metrics Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/metrics-nomenclature.md Use this command to count the total number of metrics starting with 'mongodb_'. ```bash curl -s http://localhost:9216/metrics | grep "^mongodb_" | wc -l ``` -------------------------------- ### GET / Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/SUMMARY.txt Provides an information page about the MongoDB exporter. This page typically includes build information and status. ```APIDOC ## GET / ### Description Provides an information page about the MongoDB exporter. ### Method GET ### Endpoint / ### Parameters (No parameters documented for this endpoint in the source) ### Request Example (No request body documented for this endpoint in the source) ### Response #### Success Response (200) - **info** (string) - Information about the exporter #### Response Example (Example response body would be here if available in source) ``` -------------------------------- ### Scrape MongoDB Instance with Prometheus Exposition Format Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/endpoints.md A successful scrape returns metrics in the Prometheus exposition format. This example shows sample output for a healthy instance. ```text # HELP mongodb_up MongoDB instance is up # TYPE mongodb_up gauge mongodb_up 1 # HELP mongodb_ss_connections Current connections # TYPE mongodb_ss_connections gauge mongodb_ss_connections{conn_type="current"} 3 ... ``` -------------------------------- ### Descending Index Override Example Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/metrics-nomenclature.md Demonstrates the change in index naming convention when the `--metrics.overridedescendingindex` flag is enabled, making descending indexes more readable. ```text index_name="user_1_created_DESC" ``` -------------------------------- ### Enable Shard Metrics Gathering Source: https://github.com/percona/mongodb_exporter/blob/main/README.md When the `--collector.shards` flag is enabled, the exporter exposes metrics for sharded MongoDB deployments. This example shows chunk counts for collections. ```text # HELP mongodb_shards_collection_chunks_count sharded collection chunks. # TYPE mongodb_shards_collection_chunks_count counter mongodb_shards_collection_chunks_count{collection="system.sessions",database="config",shard="rs1"} 250 mongodb_shards_collection_chunks_count{collection="system.sessions",database="config",shard="rs2"} 250 ``` -------------------------------- ### Create New Exporter Instance Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/exporter.md Creates and initializes a new Exporter instance with the provided options. Connection errors are logged but do not prevent initialization, as retries occur on scrape requests. Configuration errors in opts are logged as warnings. ```go opts := &exporter.Opts{ URI: "mongodb://localhost:27017/admin", Logger: log.New(), EnableDiagnosticData: true, EnableDBStats: true, } exp := exporter.New(opts) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/percona/mongodb_exporter/blob/main/CONTRIBUTING.md Execute this make command to run the project's unit tests. ```bash make test ``` -------------------------------- ### Root Endpoint HTML Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/endpoints.md Serves a simple HTML page with a link to the metrics endpoint. Accessible via GET /. ```html MongoDB Exporter

MongoDB Exporter

Metrics

``` -------------------------------- ### GET /scrapeall Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/SUMMARY.txt Aggregates metrics from all configured MongoDB targets. This endpoint provides a consolidated view of metrics from all targets. ```APIDOC ## GET /scrapeall ### Description Aggregates metrics from all configured MongoDB targets. ### Method GET ### Endpoint /scrapeall ### Parameters (No parameters documented for this endpoint in the source) ### Request Example (No request body documented for this endpoint in the source) ### Response #### Success Response (200) - **metrics** (string) - Prometheus-formatted metrics aggregated from all targets #### Response Example (Example response body would be here if available in source) ``` -------------------------------- ### GET /scrape Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/SUMMARY.txt Enables multi-target scraping of MongoDB instances. This endpoint allows specifying multiple targets for scraping. ```APIDOC ## GET /scrape ### Description Enables multi-target scraping of MongoDB instances. ### Method GET ### Endpoint /scrape ### Parameters (No parameters documented for this endpoint in the source) ### Request Example (No request body documented for this endpoint in the source) ### Response #### Success Response (200) - **metrics** (string) - Prometheus-formatted metrics for specified targets #### Response Example (Example response body would be here if available in source) ``` -------------------------------- ### HTTP Server Configuration Options (ServerOpts) Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/exporter.md Defines the configuration options for the exporter's HTTP server. Use these fields to set the metrics endpoint path, listen address, and TLS settings. ```go type ServerOpts struct { Path string MultiTargetPath string OverallTargetPath string WebListenAddress string TLSConfigPath string DisableDefaultRegistry bool } ``` -------------------------------- ### GET /metrics Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/SUMMARY.txt The main endpoint for scraping MongoDB exporter metrics. This endpoint provides the collected metrics in Prometheus format. ```APIDOC ## GET /metrics ### Description Main endpoint for scraping MongoDB exporter metrics. ### Method GET ### Endpoint /metrics ### Parameters (No parameters documented for this endpoint in the source) ### Request Example (No request body documented for this endpoint in the source) ### Response #### Success Response (200) - **metrics** (string) - Prometheus-formatted metrics #### Response Example (Example response body would be here if available in source) ``` -------------------------------- ### MongoDB Exporter Help Source: https://github.com/percona/mongodb_exporter/wiki/Home View all available command-line options for the exporter by using the -h or --help flags. ```bash ./mongodb_exporter --help ``` -------------------------------- ### New Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/exporter.md Creates and initializes a new Exporter instance. It takes configuration options and attempts an initial asynchronous connection to MongoDB. Connection errors are logged but do not prevent initialization, with retries occurring on subsequent scrape requests. ```APIDOC ## New ### Description Creates and initializes a new Exporter instance. Attempts an initial connection to MongoDB asynchronously. ### Signature ```go func New(opts *Opts) *Exporter ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **opts** (*Opts) - Optional - Configuration options for exporter behavior ### Returns - **`*Exporter`** - Initialized exporter instance ### Error Conditions - Connection errors are logged but do not prevent initialization; connection retry occurs on each scrape request - Configuration errors in opts are logged as warnings ### Example ```go opts := &exporter.Opts{ URI: "mongodb://localhost:27017/admin", Logger: log.New(), EnableDiagnosticData: true, EnableDBStats: true, } exp := exporter.New(opts) ``` ``` -------------------------------- ### Go Main Function Signature Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/main-entry-point.md The entry point for the application. It is responsible for parsing command-line flags and initiating the server. ```go func main() ``` -------------------------------- ### Development and Debugging Configuration Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/configuration.md Enable verbose logging for troubleshooting during development. Use `--log.level=debug` and specify a local listen address. ```bash mongodb_exporter \ --mongodb.uri=mongodb://localhost:27017/admin \ --collector.diagnosticdata \ --log.level=debug \ --web.listen-address=127.0.0.1:9216 ``` -------------------------------- ### Go Error Interface Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/types.md The standard Go error interface, used for reporting errors. Includes examples of custom errors like errCannotHandleType and errUnexpectedDataType. ```go type error interface { Error() string } ``` -------------------------------- ### Connect to mongos on Shard 2 with Authentication Source: https://github.com/percona/mongodb_exporter/blob/main/CONTRIBUTING.md Use this command to connect to the mongos instance on shard 2 when authentication is enabled. Ensure you have the correct credentials. ```bash mongo mongodb://admin:admin@127.0.0.1:17001/admin ``` -------------------------------- ### Format Code Source: https://github.com/percona/mongodb_exporter/blob/main/CONTRIBUTING.md Run this make command to format your code according to the project's standards before submitting a pull request. ```bash make format ``` -------------------------------- ### Connect to mongos on Shard 1 Source: https://github.com/percona/mongodb_exporter/blob/main/CONTRIBUTING.md Use this command to connect to the mongos instance on shard 1 when no authentication is enabled. ```bash mongo mongodb://127.0.0.1:17001/admin ``` -------------------------------- ### Format Source Code Source: https://github.com/percona/mongodb_exporter/blob/main/docs/development-guide.md Use 'make format' to automatically format the source code according to project standards. This ensures code consistency across the project. ```bash make format ``` -------------------------------- ### Get Unique Strings from Slice Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/common-functions.md Removes duplicate strings from a slice, preserving the first occurrence. Note that the order of elements in the returned slice may not be preserved. ```go func unique(slice []string) []string ``` ```go unique := unique([]string{"users", "orders", "users"}) // unique = []string{"users", "orders"} or ["orders", "users"] ``` -------------------------------- ### Build MongoDB Exporter Source: https://github.com/percona/mongodb_exporter/wiki/Home Build the exporter binary using make. Ensure GO_VERSION is set if you need a specific Go version. ```bash export GO_VERSION=1.5.1 # if you wish to use your system version make ``` -------------------------------- ### MongoDB Collection Type Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/types.md Represents a MongoDB collection, providing methods for querying and retrieving statistics. Used for running aggregation pipelines and getting collection stats. ```go type Collection struct { // unexported fields } // Methods Used: // Aggregate(ctx, pipeline, opts) - Run aggregation pipeline // Stats(ctx, opts) - Get collection statistics ``` -------------------------------- ### Version Information Variables Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/main-entry-point.md These variables are injected during the build process and contain version, commit hash, and build date information. They are used for the `--version` flag and startup logs. ```go var ( version string // Semantic version (e.g., "0.40.0") commit string // Git commit hash buildDate string // Build timestamp ) ``` -------------------------------- ### Configure Exporter Options with Filters Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/exporter.md Use GetRequestOpts to create exporter options by specifying a list of collector names to enable. This is useful for customizing metrics exposed via URL query parameters. ```go filters := []string{"dbstats", "collstats"} opts := exporter.GetRequestOpts(filters, defaultOpts) ``` -------------------------------- ### Run MongoDB Exporter with Docker Source: https://github.com/percona/mongodb_exporter/blob/main/README.md Run the MongoDB exporter using Docker or Podman. Ensure the MongoDB URI is correctly specified. ```sh # with podman podman run -d -p 9216:9216 percona/mongodb_exporter:0.40 --mongodb.uri=mongodb://127.0.0.1:17001 # with docker docker run -d -p 9216:9216 percona/mongodb_exporter:0.40 --mongodb.uri=mongodb://127.0.0.1:17001 ``` -------------------------------- ### Run MongoDB Exporter Binary Source: https://github.com/percona/mongodb_exporter/blob/main/README.md Execute the MongoDB exporter binary directly. Ensure the MongoDB URI is correctly specified. ```sh mongodb_exporter_linux_amd64/mongodb_exporter --mongodb.uri=mongodb://127.0.0.1:17001 ``` -------------------------------- ### Specify Collections for IndexStats Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/configuration.md Provide a comma-separated list of databases and collections to monitor using the $indexStats command. ```bash --mongodb.indexstats-colls=db1.col1,db2.col2 ``` -------------------------------- ### Stop Testing Sandbox Source: https://github.com/percona/mongodb_exporter/blob/main/CONTRIBUTING.md Run this make command to clean up and stop the testing sandbox environment. ```bash make test-cluster-clean ``` -------------------------------- ### Recommended MongoDB Exporter Configuration Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/INDEX.md This configuration includes recommended collectors for diagnostic data, database stats, and collection stats, along with info log level. It requires authentication credentials. ```bash mongodb_exporter \ --mongodb.uri=mongodb://user:pass@localhost:27017/admin \ --collector.diagnosticdata \ --collector.dbstats \ --collector.collstats \ --log.level=info ``` -------------------------------- ### Create Percona Backup for MongoDB Collector Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/collectors.md Creates a collector for Percona Backup metrics. Requires context, a MongoDB client, the MongoDB URI, and a logger. ```go func newPbmCollector( ctx context.Context, client *mongo.Client, mongoURI string, logger *slog.Logger, ) *pbmCollector ``` -------------------------------- ### PromQL: Collection Size by Database Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/metrics-nomenclature.md Sum the collection sizes, grouped by database. ```promql sum by (database) (mongodb_collstats_size) ``` -------------------------------- ### PromQL: Cache Eviction Rate Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/metrics-nomenclature.md Calculate the rate of cache evictions per second over a 1-minute window. ```promql rate(mongodb_ss_wt_cache_evicted[1m]) ``` -------------------------------- ### Exporter.New() Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/SUMMARY.txt Initializes a new instance of the MongoDB Exporter. This function is used to set up the exporter with the necessary configuration. ```APIDOC ## Exporter.New() ### Description Initializes a new MongoDB Exporter instance. ### Method (Function Signature) ### Parameters (Details on parameters for New() would be here if available in source) ### Return Value (Details on return values for New() would be here if available in source) ### Example (Code example for Exporter.New() would be here if available in source) ``` -------------------------------- ### Build Multiple MongoDB Exporters Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/main-entry-point.md Use `buildServers` to create exporter instances for each MongoDB URI provided. This function parses the URIs and calls `buildExporter` for each one, returning a slice of configured exporters, one for each MongoDB instance or cluster. ```go opts := GlobalFlags{ URI: []string{"mongodb://host1:27017", "mongodb://host2:27017"}, } exporters := buildServers(opts, logger) // Returns 2 exporter instances ``` -------------------------------- ### buildServers Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/main-entry-point.md Creates Exporter instances for each URI in the provided list. It parses URIs, calls `buildExporter` for each, and returns a slice of initialized exporters, with one exporter per MongoDB instance or cluster. ```APIDOC ## buildServers ### Description Creates Exporter instances for each URI in the list. ### Signature ```go func buildServers(opts GlobalFlags, logger *slog.Logger) []*exporter.Exporter ``` ### Parameters #### Path Parameters - **opts** (GlobalFlags) - Required - Command-line options - **logger** (*slog.Logger) - Required - Structured logger ### Returns - `[]*exporter.Exporter` - List of configured exporters ### Behavior - Parses URI list with parseURIList - For each URI, calls buildExporter - Returns slice of initialized exporters - One exporter per MongoDB instance/cluster ### Example ```go opts := GlobalFlags{ URI: []string{"mongodb://host1:27017", "mongodb://host2:27017"}, } exporters := buildServers(opts, logger) // Returns 2 exporter instances ``` ``` -------------------------------- ### Basic MongoDB Monitoring Configuration Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/configuration.md Monitor a single MongoDB instance with essential metrics. Ensure the MongoDB URI and desired collectors are specified. ```bash mongodb_exporter \ --mongodb.uri=mongodb://user:pass@localhost:27017/admin \ --collector.diagnosticdata \ --collector.dbstats \ --log.level=info ``` -------------------------------- ### Set Valid Web Telemetry Path Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/main-entry-point.md If the Web telemetry path is an empty string, it defaults to '/'. Provide a valid path to specify the metrics endpoint. ```bash # Provide valid path: --web.telemetry-path=/metrics ``` -------------------------------- ### Build MongoDB URI with Credentials Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/main-entry-point.md Constructs a complete MongoDB URI, adding the 'mongodb://' prefix if missing. It does not override existing credentials in the provided URI and handles edge cases by calling buildURIManually. ```go uri := buildURI("localhost:27017", "user", "pass") // Returns: "mongodb://user:pass@localhost:27017" uri := buildURI("mongodb://user:pass@localhost:27017", "", "") // Returns: "mongodb://user:pass@localhost:27017" ``` -------------------------------- ### Run Integration Tests Source: https://github.com/percona/mongodb_exporter/blob/main/docs/development-guide.md Execute the exporter's integration test suite against the running test sandbox. Ensure the sandbox is active before running this command. ```bash make test ``` -------------------------------- ### Create Diagnostic Data Collector Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/collectors.md Initializes a collector specifically for diagnostic data metrics. This collector requires context, a MongoDB client, logger, compatibility flag, topology labels, and build information. ```go func newDiagnosticDataCollector( ctx context.Context, client *mongo.Client, logger *slog.Logger, compatible bool, topology labelsGetter, buildInfo buildInfo, ) *diagnosticDataCollector ``` -------------------------------- ### Create Annotated Git Tag Source: https://github.com/percona/mongodb_exporter/wiki/Release-Overview Use this command to create an annotated tag for a new release. Replace X.Y.Z with the actual version number. ```bash git tag -a vX.Y.Z -m vX.Y.Z ``` -------------------------------- ### Create Base Collector Instance Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/collectors.md Function to create a new instance of the base collector. It initializes the collector with a MongoDB client and a structured logger. ```go func newBaseCollector(client *mongo.Client, logger *slog.Logger) *baseCollector ``` -------------------------------- ### Enable Compatibility Mode for Metrics Source: https://github.com/percona/mongodb_exporter/blob/main/README.md The --compatible-mode flag exposes new metrics in a version 1 compatible format alongside the new schema. This ensures backward compatibility for older monitoring systems. ```text # HELP mongodb_ss_wt_log_log_bytes_written serverStatus.wiredTiger.log. # TYPE mongodb_ss_wt_log_log_bytes_written untyped mongodb_ss_wt_log_log_bytes_written 2.6208e+06 ``` ```text HELP mongodb_mongod_wiredtiger_log_bytes_total mongodb_mongod_wiredtiger_log_bytes_total # TYPE mongodb_mongod_wiredtiger_log_bytes_total untyped mongodb_mongod_wiredtiger_log_bytes_total{type="unwritten"} 2.6208e+06 ``` -------------------------------- ### Create MongoDB Connection Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/common-functions.md Establishes and validates a MongoDB connection using provided options. It handles DSN parsing, sets connection timeouts, and performs an initial ping to ensure the connection is active. The client is closed if the ping fails. ```go ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client, err := connect(ctx, &Opts{ URI: "mongodb://localhost:27017", ConnectTimeoutMS: 5000, }) if err != nil { log.Fatal(err) } deferr client.Disconnect(ctx) ``` -------------------------------- ### Full Monitoring MongoDB Exporter Configuration Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/INDEX.md Enables all collectors and specifies specific collections for detailed monitoring. This is suitable for comprehensive performance analysis. ```bash mongodb_exporter \ --mongodb.uri=mongodb://user:pass@localhost:27017/admin \ --collect-all \ --collector.collstats-colls=mydb.users,mydb.orders \ --log.level=info ``` -------------------------------- ### Configure TLS and Basic Authentication Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/configuration.md Specify the path to a YAML configuration file for TLS settings (HTTPS) and basic authentication. The file should follow the Prometheus exporter-toolkit format. ```yaml tls_server_config: cert_file: /path/to/cert.pem key_file: /path/to/key.pem basic_auth_users: user1: password_hash_1 ``` -------------------------------- ### Compatible Mode Metric Naming Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/metrics-nomenclature.md Illustrates the old and new metric naming conventions when compatible mode is enabled. ```text mongodb_mongod_wiredtiger_log_bytes_total{type="unwritten"} ``` ```text mongodb_ss_wt_log_log_bytes_written ``` -------------------------------- ### Push Git Tag to GitHub Source: https://github.com/percona/mongodb_exporter/wiki/Release-Overview Push the newly created annotated tag to the GitHub repository. Ensure 'origin' is set to your GitHub remote. ```bash git push origin vX.Y.Z ``` -------------------------------- ### GetRequestOpts() Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/SUMMARY.txt Retrieves options for making requests to MongoDB. This utility function helps in configuring database interactions. ```APIDOC ## GetRequestOpts() ### Description Retrieves options for making requests to MongoDB. ### Method (Function Signature) ### Parameters (Details on parameters for GetRequestOpts() would be here if available in source) ### Return Value (Details on return values for GetRequestOpts() would be here if available in source) ### Example (Code example for GetRequestOpts() would be here if available in source) ``` -------------------------------- ### Go Runtime Metrics Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/metrics-nomenclature.md Go runtime metrics collected when exporter-metrics is enabled. These offer details about the Go environment the exporter runs in. ```text go_goroutines go_threads go_memstats_heap_alloc_bytes go_memstats_heap_sys_bytes go_memstats_gc_collections_count ``` -------------------------------- ### Collector Enablement Logic Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/integration-guide.md This Go code demonstrates how collector enablement is determined, prioritizing per-request filters if provided, otherwise falling back to default exporter options. It checks both levels before registering a collector. ```go if len(filters) > 0 { requestOpts = ParseFilters(filters) } else { // Otherwise use defaults from exporter.Opts requestOpts = defaultOpts } // Check both levels before registering collector if exporter.EnableCollStats && requestOpts.EnableCollStats { registry.MustRegister(newCollectionStatsCollector(...)) } ``` -------------------------------- ### Performance-Tuned MongoDB Monitoring Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/configuration.md Configure for high-volume deployments by tuning connection pools and collector limits. Set `--collector.collstats-enable-details=false` to reduce overhead. ```bash mongodb_exporter \ --mongodb.uri=mongodb://user:pass@mongodb.example.com:27017/admin \ --global-conn-pool \ --collector.diagnosticdata \ --collector.dbstats \ --collector.collstats-limit=5000 \ --collector.collstats-enable-details=false \ --log.level=warn ``` -------------------------------- ### Prometheus Registry Type and Constructor Source: https://github.com/percona/mongodb_exporter/blob/main/_autodocs/types.md Represents an in-memory storage and orchestrator for metrics collection. Use NewRegistry to create an instance. ```go type Registry struct { // unexported fields } func NewRegistry() *Registry ```