### Starting Grafana Server (Linux) Source: https://github.com/oracle/oci-grafana-metrics/blob/master/docs/linuxoci.md This command initiates the Grafana server service on a Linux system using systemctl. Ensure Grafana is installed and configured before running this command. ```Bash sudo systemctl start grafana-server ``` -------------------------------- ### MQL Raw Query Example for OCI Metrics Plugin Source: https://github.com/oracle/oci-grafana-metrics/blob/master/docs/using.md Demonstrates how to use the raw MQL editor in version 5 of the OCI Metrics plugin for Grafana. This editor allows direct input for metric, window, aggregation, and dimensions. The example shows setting a window of 1 minute and applying the max aggregation. ```MQL AllRequests[1m].max() ``` -------------------------------- ### Manual OCI Grafana Plugin Installation (Linux) Source: https://github.com/oracle/oci-grafana-metrics/blob/master/docs/linuxoci.md These commands demonstrate the manual installation process for the OCI Grafana Plugin on Linux systems for Grafana versions prior to 8. It involves navigating to the plugins directory, downloading the plugin tarball, unpacking it, and then removing the tarball. ```Bash cd /usr/local/var/lib/grafana/plugins wget https://github.com/oracle/oci-grafana-plugin/releases/download//plugin.tar mkdir oci && tar -C oci -xvf plugin.tar rm plugin.tar ``` -------------------------------- ### OCI API HTTP Request Examples for Grafana Source: https://context7.com/oracle/oci-grafana-metrics/llms.txt Provides example `curl` commands to interact with the OCI API through a Grafana proxy. These examples cover fetching lists of tenancies, regions, compartments, namespaces, and dimensions, which are crucial for dynamically configuring OCI monitoring in Grafana. ```bash # Get list of tenancies (for multi-tenancy mode) curl -X GET http://localhost:3000/api/datasources/proxy/1/tenancies \ -H "Authorization: Bearer " # Response: # [ # {"name": "Tenancy-A", "ocid": "ocid1.tenancy.oc1..aaa"}, # {"name": "Tenancy-B", "ocid": "ocid1.tenancy.oc1..bbb"} # ] # Get subscribed regions for a tenancy curl -X POST http://localhost:3000/api/datasources/proxy/1/regions \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"tenancy": "ocid1.tenancy.oc1..example"}' # Response: ["us-ashburn-1", "us-phoenix-1", "eu-frankfurt-1"] # Get compartments in a tenancy curl -X POST http://localhost:3000/api/datasources/proxy/1/compartments \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"tenancy": "ocid1.tenancy.oc1..example"}' # Response: # [ # {"name": "root", "ocid": "ocid1.tenancy.oc1..example"}, # {"name": "Production", "ocid": "ocid1.compartment.oc1..prod"}, # {"name": "Development", "ocid": "ocid1.compartment.oc1..dev"} # ] # Get namespaces with metric names curl -X POST http://localhost:3000/api/datasources/proxy/1/namespaces \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "tenancy": "ocid1.tenancy.oc1..example", "compartment": "ocid1.compartment.oc1..example", "region": "us-ashburn-1" }' # Get dimensions for a specific metric curl -X POST http://localhost:3000/api/datasources/proxy/1/dimensions \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "tenancy": "ocid1.tenancy.oc1..example", "compartment": "ocid1.compartment.oc1..example", "region": "us-ashburn-1", "namespace": "oci_computeagent", "metric_name": "CpuUtilization" }' # Response: # [ # { # "key": "resourceId", # "values": ["ocid1.instance.oc1..inst1", "ocid1.instance.oc1..inst2"] # }, # { # "key": "availabilityDomain", # "values": ["AD-1", "AD-2", "AD-3"] # } # ] ``` -------------------------------- ### MQL Raw Query with Variable for Window Source: https://github.com/oracle/oci-grafana-metrics/blob/master/docs/using.md Shows how to use a variable for the window in the raw MQL editor. This allows dynamic configuration of the time window based on Grafana variables, enhancing dashboard flexibility. The example uses '$window' as a placeholder for the variable. ```MQL AllRequests[$window].max() ``` -------------------------------- ### MQL Raw Query with 'auto' for Window Selection Source: https://github.com/oracle/oci-grafana-metrics/blob/master/docs/using.md Illustrates using the 'auto' option for the window in the raw MQL editor. This setting automatically adjusts the window based on the selected time range, simplifying configuration and ensuring optimal data aggregation. The example uses 'auto' for the window and 'count()' for the aggregation. ```MQL AllRequests[auto].count() ``` -------------------------------- ### Grafana Configuration for Unsigned Plugins (Grafana 7) Source: https://github.com/oracle/oci-grafana-metrics/blob/master/docs/linuxoci.md This configuration snippet for the `grafana.ini` file allows Grafana 7 to load unsigned plugins, specifically the 'oci-datasource'. This is a necessary step for manual plugin installations in older Grafana versions. ```INI [plugins] allow_loading_unsigned_plugins = "oci-datasource" ``` -------------------------------- ### General Regex for Shortening Metric Names in Grafana Source: https://github.com/oracle/oci-grafana-metrics/blob/master/docs/using.md This example provides a more general regular expression pattern designed to shorten and reformat various server metric names in Grafana. The 'Match' regex `(\w{3,4}\w*_\w{2}\w*_(\d+)_\w{3}\w*)` aims to capture key parts of the metric name, while the 'Replace' pattern `$1_$2_$3_$4` reconstructs it. This requires careful crafting and testing for specific naming conventions. ```regex (\w{3,4}\w*_\w{2}\w*_(\d+)_\w{3}\w*) ``` ```regex $1_$2_$3_$4 ``` -------------------------------- ### OCI User Principals Configuration Guide (Multi Tenancy) Source: https://github.com/oracle/oci-grafana-metrics/blob/master/docs/datasource_configuration.md This section outlines the parameters required to configure Grafana for OCI metrics datasource using user principals in multi-tenancy mode via the Grafana API. It details settings for 'jsonData' and 'secureJsonData', including environment, tenancy mode, region configurations, and sensitive credentials for multiple tenancies. -------------------------------- ### BigInt64Array Methods Documentation Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt This section provides documentation for common BigInt64Array methods. ```APIDOC ## BigInt64Array Methods Documentation This section provides documentation for common BigInt64Array methods. ### `fill(value: bigint, start?: number, end?: number): this` Fills elements of an array from a `start` to `end` index with a static `value` and returns the modified array. **Parameters:** * `value` (bigint) - The value to fill the array section with. * `start` (number, optional) - The index to start filling the array at. If negative, it's treated as `length + start`. * `end` (number, optional) - The index to stop filling the array at. If negative, it's treated as `length + end`. ### `filter(predicate: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array` Returns the elements of an array that meet the condition specified in a callback function. **Parameters:** * `predicate` (function) - A function that accepts up to three arguments. It's called for each element. * `thisArg` (any, optional) - An object to which the `this` keyword can refer in the predicate function. ### `find(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined` Returns the value of the first element in the array where `predicate` is true, and `undefined` otherwise. **Parameters:** * `predicate` (function) - A function that returns `true` if the element satisfies the condition. * `thisArg` (any, optional) - If provided, used as the `this` value for each invocation of `predicate`. ### `findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number` Returns the index of the first element in the array where `predicate` is true, and -1 otherwise. **Parameters:** * `predicate` (function) - A function that returns `true` if the element satisfies the condition. * `thisArg` (any, optional) - If provided, used as the `this` value for each invocation of `predicate`. ### `forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void` Performs the specified action for each element in an array. **Parameters:** * `callbackfn` (function) - A function that accepts up to three arguments. It's called for each element. * `thisArg` (any, optional) - An object to which the `this` keyword can refer in the `callbackfn` function. ### `includes(searchElement: bigint, fromIndex?: number): boolean` Determines whether an array includes a certain element, returning `true` or `false` as appropriate. **Parameters:** * `searchElement` (bigint) - The element to search for. * `fromIndex` (number, optional) - The position in the array at which to begin searching. ### `indexOf(searchElement: bigint, fromIndex?: number): number` Returns the index of the first occurrence of a value in an array. **Parameters:** * `searchElement` (bigint) - The value to locate in the array. * `fromIndex` (number, optional) - The array index at which to begin the search. Defaults to 0. ### `join(separator?: string): string` Adds all the elements of an array separated by the specified separator string. **Parameters:** * `separator` (string, optional) - A string used to separate one element of an array from the next. Defaults to a comma. ### `keys(): IterableIterator` Yields each index in the array. ### `lastIndexOf(searchElement: bigint, fromIndex?: number): number` Returns the index of the last occurrence of a value in an array. **Parameters:** * `searchElement` (bigint) - The value to locate in the array. * `fromIndex` (number, optional) - The array index at which to begin the search. Defaults to 0. ### `length: number` The length of the array. ### `map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): any[]` Calls a defined callback function on each element of an array, and returns an array that contains the results. **Parameters:** * `callbackfn` (function) - A function that accepts up to three arguments. It's called for each element. * `thisArg` (any, optional) - An object to which the `this` keyword can refer in the `callbackfn` function. ``` -------------------------------- ### Get BigInt64Array Length Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt The `length` property returns the number of elements in the BigInt64Array. This is a read-only property. ```typescript readonly length: number; ``` -------------------------------- ### Terraform Variables for OCI Grafana Installation Source: https://github.com/oracle/oci-grafana-metrics/blob/master/docs/terraform.md This snippet defines the required Terraform variables for setting up the OCI Data Source for Grafana. These variables include OCI credentials, region, compartment details, SSH keys, and network configurations. Ensure these are correctly set for successful deployment. ```hcl variable "tenancy_ocid" {} variable "user_ocid" {} variable "fingerprint" {} variable "private_key_path" {} variable "region" {} variable "compartment_ocid" {} variable "ssh_public_key" {} variable "ssh_private_key" {} variable "subnet_id" {} variable "availability_domain" {} variable "dynamic_group_name" {} ``` -------------------------------- ### WebGL2RenderingContextBase Methods Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt Outlines essential methods for the WebGL2RenderingContextBase interface, including buffer clearing, uniform setting, and attribute configuration. Supports various data types and dimensions for uniforms. ```typescript interface WebGL2RenderingContextBase { clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Iterable, srcOffset?: GLuint): void; clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Iterable, srcOffset?: GLuint): void; clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Iterable, srcOffset?: GLuint): void; drawBuffers(buffers: Iterable): void; getActiveUniforms(program: WebGLProgram, uniformIndices: Iterable, pname: GLenum): any; getUniformIndices(program: WebGLProgram, uniformNames: Iterable): Iterable | null; invalidateFramebuffer(target: GLenum, attachments: Iterable): void; invalidateSubFramebuffer(target: GLenum, attachments: Iterable, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; transformFeedbackVaryings(program: WebGLProgram, varyings: Iterable, bufferMode: GLenum): void; uniform1uiv(location: WebGLUniformLocation | null, data: Iterable, srcOffset?: GLuint, srcLength?: GLuint): void; uniform2uiv(location: WebGLUniformLocation | null, data: Iterable, srcOffset?: GLuint, srcLength?: GLuint): void; uniform3uiv(location: WebGLUniformLocation | null, data: Iterable, srcOffset?: GLuint, srcLength?: GLuint): void; uniform4uiv(location: WebGLUniformLocation | null, data: Iterable, srcOffset?: GLuint, srcLength?: GLuint): void; uniformMatrix2x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable, srcOffset?: GLuint, srcLength?: GLuint): void; uniformMatrix2x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable, srcOffset?: GLuint, srcLength?: GLuint): void; uniformMatrix3x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable, srcOffset?: GLuint, srcLength?: GLuint): void; uniformMatrix3x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable, srcOffset?: GLuint, srcLength?: GLuint): void; uniformMatrix4x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable, srcOffset?: GLuint, srcLength?: GLuint): void; uniformMatrix4x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable, srcOffset?: GLuint, srcLength?: GLuint): void; vertexAttribI4iv(index: GLuint, values: Iterable): void; vertexAttribI4uiv(index: GLuint, values: Iterable): void; } ``` -------------------------------- ### Get BigInt64Array Keys Iterator Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt The `keys` method returns an iterator that yields the indices for each element in the BigInt64Array. ```typescript keys(): IterableIterator; ``` -------------------------------- ### BigUint64Array Constructor Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt Information about the BigUint64Array constructor and its static properties. ```APIDOC ## BigUint64Array Constructor ### `new BigUint64Array(length?: number): BigUint64Array` #### Description Creates a new `BigUint64Array` of the specified length, initialized to all zeros. ### `new BigUint64Array(array: Iterable): BigUint64Array` #### Description Creates a new `BigUint64Array` from an iterable object (like an array). ### `new BigUint64Array(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array` #### Description Creates a new `BigUint64Array` view on the given `ArrayBuffer`. ### `readonly BYTES_PER_ELEMENT: number` #### Description Returns the number of bytes used by each element in the array. For `BigUint64Array`, this is 8. ### `static of(...items: bigint[]): BigUint64Array` #### Description Creates a new `BigUint64Array` with the arguments passed to the method. #### Parameters - **items** (bigint[]) - A list of arguments to be used as elements in the new array. #### Return Value A new `BigUint64Array` instance. ``` -------------------------------- ### JavaScript: Get Enumerable String Keys Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt Returns an array of the names of the enumerable string properties and methods of an object. This is useful for iterating over an object's accessible properties. ```javascript keys(o: {}): string[]; ``` -------------------------------- ### JavaScript Intl.RelativeTimeFormat Constructor and Methods Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt Demonstrates how to instantiate and use the Intl.RelativeTimeFormat object in JavaScript. It covers the constructor for creating formatters based on locales and options, and the format, formatToParts, and resolvedOptions methods for outputting and inspecting formatted relative time strings. ```javascript /** * Creates [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) objects * * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings. * For the general form and interpretation of the locales argument, * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). * * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters) * with some or all of options of `RelativeTimeFormatOptions`. * * @returns [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) object. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat). */ const formatter = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' }); /** * Formats a numeric value into a language-sensitive relative time string. * * @param value - Numeric value to use in the internationalized relative time message * @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit) to use in the relative time internationalized message. * @returns {string} Internationalized relative time message as string * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format). */ formatter.format(5, 'day'); // Example: "in 5 days" /** * Returns an array of objects representing the relative time format in parts. * * @param value - Numeric value to use in the internationalized relative time message * @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit) to use in the relative time internationalized message. * @returns {RelativeTimeFormatPart[]} Array of formatting parts. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts). */ formatter.formatToParts(1, 'hour'); // Example: [ { type: "literal", value: "in " }, { type: "integer", value: "1" }, { type: "unit", value: "hour" } ] /** * Provides access to the locale and options computed during initialization. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions). */ formatter.resolvedOptions(); // Example: { locale: "en-US", numberFormat: { style: "numeric" }, numeric: "auto",ริ: "long" } ``` -------------------------------- ### BigUint64Array: Slice Method Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt The slice method returns a new BigUint64Array view of a portion of the underlying ArrayBuffer. It extracts elements from a start index up to, but not including, an end index. ```typescript slice(start?: number, end?: number): BigUint64Array; ``` -------------------------------- ### Implement Iterable APIs for Window Objects (TypeScript) Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt This snippet demonstrates the implementation of iterable APIs for various Window objects in TypeScript. It includes interfaces for AudioParam, AudioParamMap, BaseAudioContext, CSSRuleList, CSSStyleDeclaration, Cache, CanvasPathDrawingStyles, DOMRectList, DOMStringList, DOMTokenList, DataTransferItemList, FileList, FontFaceSet, FormData, HTMLAllCollection, HTMLCollectionBase, HTMLCollectionOf, HTMLFormElement, HTMLSelectElement, Headers, and IDBDatabase. These implementations allow for easy iteration over collections of objects. ```typescript interface AudioParam { setValueCurveAtTime(values: Iterable, startTime: number, duration: number): AudioParam; } interface AudioParamMap extends ReadonlyMap { } interface BaseAudioContext { createIIRFilter(feedforward: Iterable, feedback: Iterable): IIRFilterNode; createPeriodicWave(real: Iterable, imag: Iterable, constraints?: PeriodicWaveConstraints): PeriodicWave; } interface CSSRuleList { [Symbol.iterator](): IterableIterator; } interface CSSStyleDeclaration { [Symbol.iterator](): IterableIterator; } interface Cache { addAll(requests: Iterable): Promise; } interface CanvasPathDrawingStyles { setLineDash(segments: Iterable): void; } interface DOMRectList { [Symbol.iterator](): IterableIterator; } interface DOMStringList { [Symbol.iterator](): IterableIterator; } interface DOMTokenList { [Symbol.iterator](): IterableIterator; entries(): IterableIterator<[number, string]>; keys(): IterableIterator; values(): IterableIterator; } interface DataTransferItemList { [Symbol.iterator](): IterableIterator; } interface FileList { [Symbol.iterator](): IterableIterator; } interface FontFaceSet extends Set { } interface FormData { [Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>; /** Returns an array of key, value pairs for every entry in the list. */ entries(): IterableIterator<[string, FormDataEntryValue]>; /** Returns a list of keys in the list. */ keys(): IterableIterator; /** Returns a list of values in the list. */ values(): IterableIterator; } interface HTMLAllCollection { [Symbol.iterator](): IterableIterator; } interface HTMLCollectionBase { [Symbol.iterator](): IterableIterator; } interface HTMLCollectionOf { [Symbol.iterator](): IterableIterator; } interface HTMLFormElement { [Symbol.iterator](): IterableIterator; } interface HTMLSelectElement { [Symbol.iterator](): IterableIterator; } interface Headers { [Symbol.iterator](): IterableIterator<[string, string]>; /** Returns an iterator allowing to go through all key/value pairs contained in this object. */ entries(): IterableIterator<[string, string]>; /** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ keys(): IterableIterator; /** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ values(): IterableIterator; } interface IDBDatabase { /** Returns a new transac ``` -------------------------------- ### JavaScript: Get Object Symbol Properties Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt Retrieves all own symbol properties of a given object. Symbols are unique and immutable primitive values, often used for object property keys. ```javascript getOwnPropertySymbols(o: any): symbol[]; ``` -------------------------------- ### Get Array Indices with keys in BigUint64Array Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt The `keys` method returns a new Array Iterator object that contains the keys (indices) for each element in the BigUint64Array. This allows for iteration over the indices of the array. ```typescript /** Yields each index in the array. */ keys(): IterableIterator; ``` -------------------------------- ### Configure OCI Authentication (Go) Source: https://context7.com/oracle/oci-grafana-metrics/llms.txt Configures OCI authentication using either local settings with user principals or OCI instance principals. It handles loading settings, validating keys, creating configuration providers, and initializing OCI monitoring clients with a retry policy. This function is crucial for establishing a connection to OCI services. ```go import ( "crypto/x509/pkix" "encoding/pem" "errors" "github.com/oracle/oci-go-sdk/common" "github.com/oracle/oci-go-sdk/monitoring" "github.com/oracle/oci-go-sdk/auth" "grafana/pkg/components/sqlstore/sqlstoreutils" "grafana/pkg/infra/log" "grafana/pkg/models" "grafana/pkg/services/datasource/backend" "grafana/pkg/tsdb/cloudwatch/models" ) // Placeholder for OCILoadSettings function (implementation not provided in snippet) func OCILoadSettings(req backend.DataSourceInstanceSettings) (*models.OCISettings, error) { // Dummy implementation return &models.OCISettings{ tenancyocid: map[string]string{"key1": "tenancy1"}, user: map[string]string{"key1": "user1"}, region: map[string]string{"key1": "region1"}, fingerprint: map[string]string{"key1": "fingerprint1"}, privkey: map[string]string{ "key1": "-----BEGIN PRIVATE KEY-----\nfakekey\n-----END PRIVATE KEY-----" }, privkeypass: map[string]string{"key1": "pass1"}, }, nil } // Placeholder for clientRetryPolicy function (implementation not provided in snippet) func clientRetryPolicy() common.RetryPolicy { // Dummy implementation return common.NewRetryPolicy(0, 0, 0, 0) } // Placeholder for identityClient (implementation not provided in snippet) var identityClient common.ConfigurationProvider // Placeholder for TenancyAccess struct (implementation not provided in snippet) type TenancyAccess struct { MonitoringClient *monitoring.MonitoringClient IdentityClient common.ConfigurationProvider ConfigProvider common.ConfigurationProvider } const SingleTenancyKey = "_" // OCIDatasource struct definition (implementation not provided in snippet) type OCIDatasource struct { tenancyAccess map[string]*TenancyAccess } // Configure authentication using User Principals func (o *OCIDatasource) getConfigProvider(environment string, tenancymode string, req backend.DataSourceInstanceSettings) error { switch environment { case "local": q, err := OCILoadSettings(req) if err != nil { return errors.New("Error Loading config settings") } for key := range q.tenancyocid { // Validate PEM key block, _ := pem.Decode([]byte(q.privkey[key])) if block == nil { return errors.New("Invalid Private Key in profile " + key) } // Create configuration provider configProvider := common.NewRawConfigurationProvider( q.tenancyocid[key], q.user[key], q.region[key], q.fingerprint[key], q.privkey[key], q.privkeypass[key], ) // Create OCI monitoring client with retry policy mrp := clientRetryPolicy() monitoringClient, err := monitoring.NewMonitoringClientWithConfigurationProvider(configProvider) if err != nil { return errors.New("error with client") } monitoringClient.Configuration.RetryPolicy = &mrp o.tenancyAccess[key] = &TenancyAccess{monitoringClient, identityClient, configProvider} } return nil case "OCI Instance": // Use Instance Principal for authentication configProvider, err := auth.InstancePrincipalConfigurationProvider() if err != nil { return errors.New("error with instance principals") } monitoringClient, err := monitoring.NewMonitoringClientWithConfigurationProvider(configProvider) if err != nil { return errors.New("error with client") } o.tenancyAccess[SingleTenancyKey] = &TenancyAccess{monitoringClient, identityClient, configProvider} return nil } return nil } ``` -------------------------------- ### JavaScript: Get Regular Expression Flags Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt Returns a string representing the flags of a regular expression. The flags are returned in a specific order: global, ignoreCase, multiline, unicode, sticky, dotAll. ```javascript RegExp.prototype.flags; ``` -------------------------------- ### Build MQL Query with QueryModel in TypeScript Source: https://context7.com/oracle/oci-grafana-metrics/llms.txt Demonstrates how to construct an MQL query dynamically using the QueryModel class. It handles default values for query parameters and allows for both raw query input and builder mode, including interval calculation, dimension addition, grouping, and statistic aggregation. It relies on a `getTemplateSrv` function and a `SetAutoInterval` helper function. ```typescript export default class QueryModel { target: OCIQuery; constructor(incomingQuery: OCIQuery, templateSrv?: TemplateSrv, scopedVars?: ScopedVars) { this.target = incomingQuery; this.target.tenancy = incomingQuery.tenancy || 'DEFAULT/'; this.target.compartment = incomingQuery.compartment || ''; this.target.region = incomingQuery.region || 'select region'; this.target.namespace = incomingQuery.namespace || 'select namespace'; this.target.metric = incomingQuery.metric || 'select metric'; this.target.statistic = incomingQuery.statistic || 'avg()'; this.target.interval = incomingQuery.interval || 'auto'; this.target.dimensionValues = incomingQuery.dimensionValues || []; this.target.rawQuery = incomingQuery.rawQuery ?? true; } buildQuery(queryText: string) { if (this.target.rawQuery === false && this.target.queryTextRaw !== '') { // Use raw query mode return String(this.target.queryTextRaw); } // Build query using builder mode let convertedInterval = this.target.interval; if (this.target.interval === "auto" || !this.target.interval) { const timeStart = parseInt(getTemplateSrv().replace("${__from}"), 10); const timeEnd = parseInt(getTemplateSrv().replace("${__to}"), 10); convertedInterval = SetAutoInterval(timeStart, timeEnd); } queryText += convertedInterval; // Add dimensions: metric[interval]{dimension1="value1",dimension2="value2"} if (this.target.dimensionValues && this.target.dimensionValues.length > 0) { let dimensionParams = '{'; dimensionParams += this.target.dimensionValues.join(','); dimensionParams += '}'; queryText += dimensionParams; } // Add groupBy option if specified if (this.target.groupBy && this.target.groupBy !== 'select option (optional)') { queryText += '.groupBy(' + this.target.groupBy + ')'; } // Add aggregation statistic: .avg(), .max(), .sum(), etc. queryText += '.' + (this.target.statistic || 'avg()'); return queryText; } } // Example: Build MQL query const query: OCIQuery = { tenancy: 'ocid1.tenancy.oc1..example', region: 'us-ashburn-1', compartment: 'ocid1.compartment.oc1..example', namespace: 'oci_computeagent', metric: 'CpuUtilization', interval: '[5m]', statistic: 'avg()', dimensionValues: ['resourceId="ocid1.instance.oc1..example"'], rawQuery: true }; const queryModel = new QueryModel(query, getTemplateSrv()); const mqlQuery = queryModel.buildQuery(query.metric); // Result: "CpuUtilization[5m]{resourceId=\"ocid1.instance.oc1..example\"}.avg()" ``` -------------------------------- ### Configure Metric Template Variable (OCI) Source: https://github.com/oracle/oci-grafana-metrics/blob/master/docs/using.md Sets up the 'metric' template variable, dependent on 'tenancy', 'region', 'compartment', 'namespace', and 'resourcegroup'. It queries available OCI metrics using 'metrics($tenancy, $region, $compartment, $namespace, $resourcegroup)'. ```json { "name": "metric", "type": "query", "query": "metrics($tenancy, $region, $compartment, $namespace, $resourcegroup)", "datasource": "OCI" } ``` -------------------------------- ### Check if BigInt64Array Includes Element Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt The `includes` method determines whether a BigInt64Array includes a certain element, returning `true` or `false`. It accepts the element to search for and an optional starting index. ```typescript includes(searchElement: bigint, fromIndex?: number): boolean; ``` -------------------------------- ### Query Model and MQL Builder Source: https://context7.com/oracle/oci-grafana-metrics/llms.txt This section details the `QueryModel` class used for constructing MQL queries from provided parameters. It handles the logic for setting default values, determining query intervals, and appending dimensions, group by options, and statistics to form a complete MQL query. ```APIDOC ## Query Model and MQL Builder ### Description This TypeScript class `QueryModel` is designed to build Monitoring Query Language (MQL) queries based on a given `OCIQuery` object. It supports both raw query mode and a builder mode where query components like interval, dimensions, group by clauses, and statistics are assembled. ### Class `QueryModel` ### Constructor - `constructor(incomingQuery: OCIQuery, templateSrv?: TemplateSrv, scopedVars?: ScopedVars)` - Initializes the `QueryModel` with an `OCIQuery` object and optional Grafana template service and scoped variables. - Sets default values for tenancy, compartment, region, namespace, metric, statistic, interval, dimensionValues, and rawQuery if not provided in `incomingQuery`. ### Methods - `buildQuery(queryText: string): string` - Constructs and returns the MQL query string. - If `rawQuery` is false and `queryTextRaw` is not empty, it returns `queryTextRaw`. - Otherwise, it builds the query using the provided properties: - Appends the interval (auto-calculated or specified). - Appends dimension filters in the format `{dimension1="value1",dimension2="value2"}`. - Appends a `groupBy` clause if specified. - Appends the aggregation statistic (e.g., `.avg()`, `.max()`). ### Request Body (for `OCIQuery` object) - **tenancy** (string) - Required - The OCID of the tenancy. - **compartment** (string) - Optional - The OCID of the compartment. - **region** (string) - Optional - The OCI region (e.g., 'us-ashburn-1'). Defaults to 'select region'. - **namespace** (string) - Optional - The OCI metric namespace (e.g., 'oci_computeagent'). Defaults to 'select namespace'. - **metric** (string) - Optional - The name of the metric (e.g., 'CpuUtilization'). Defaults to 'select metric'. - **interval** (string) - Optional - The monitoring interval (e.g., '[5m]', 'auto'). Defaults to 'auto'. - **statistic** (string) - Optional - The aggregation statistic (e.g., 'avg()'). Defaults to 'avg()'. - **dimensionValues** (array of strings) - Optional - An array of dimension key-value pairs (e.g., `['resourceId="ocid1.instance.oc1..example"']`). - **rawQuery** (boolean) - Optional - Flag to indicate if a raw MQL query should be used. Defaults to `true`. - **queryTextRaw** (string) - Optional - The raw MQL query string, used when `rawQuery` is false. ### Request Example (TypeScript) ```typescript const query: OCIQuery = { tenancy: 'ocid1.tenancy.oc1..example', region: 'us-ashburn-1', compartment: 'ocid1.compartment.oc1..example', namespace: 'oci_computeagent', metric: 'CpuUtilization', interval: '[5m]', statistic: 'avg()', dimensionValues: ['resourceId="ocid1.instance.oc1..example"'], rawQuery: true }; const queryModel = new QueryModel(query, getTemplateSrv()); const mqlQuery = queryModel.buildQuery(query.metric); // Result: "CpuUtilization[5m]{resourceId=\"ocid1.instance.oc1..example\"}.avg()" ``` ``` -------------------------------- ### Find First Occurrence Index with indexOf in BigUint64Array Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt The `indexOf` method returns the first index at which a given element can be found in the BigUint64Array, or -1 if it is not present. The search can optionally start from a specified `fromIndex`. ```typescript /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: bigint, fromIndex?: number): number; ``` -------------------------------- ### Find Last Index of Element in BigInt64Array Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt The `lastIndexOf` method returns the index of the last occurrence of a specified value in the BigInt64Array. It searches backward from an optional starting index. If the element is not found, it returns -1. ```typescript lastIndexOf(searchElement: bigint, fromIndex?: number): number; ``` -------------------------------- ### BigUint64Array Methods Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt This section details various methods available on BigUint64Array instances for manipulating and querying the array. ```APIDOC ## BigUint64Array Methods ### `reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U` #### Description Applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value. #### Method `reduce` #### Parameters ##### Callback Function Parameters - **previousValue** (U) - The value resulting from the previous call to callbackfn. - **currentValue** (bigint) - The value of the current element being processed in the array. - **currentIndex** (number) - The index of the current element being processed in the array. - **array** (BigUint64Array) - The array reduce was called upon. ##### Instance Method Parameters - **callbackfn** (function) - Function to execute on each value in the array, taking four arguments. - **initialValue** (U) - Optional. Value to use as the first argument to the first call of the callbackfn. If not supplied, the first element in the array will be used. ### `reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint` #### Description Applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. #### Method `reduceRight` #### Parameters ##### Callback Function Parameters - **previousValue** (bigint) - The value resulting from the previous call to callbackfn. - **currentValue** (bigint) - The value of the current element being processed in the array. - **currentIndex** (number) - The index of the current element being processed in the array. - **array** (BigUint64Array) - The array reduceRight was called upon. ##### Instance Method Parameters - **callbackfn** (function) - Function to execute on each value in the array, taking four arguments. ### `reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U` #### Description Applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. The `initialValue` parameter allows for a different type for the accumulator. #### Method `reduceRight` #### Parameters ##### Callback Function Parameters - **previousValue** (U) - The value resulting from the previous call to callbackfn. - **currentValue** (bigint) - The value of the current element being processed in the array. - **currentIndex** (number) - The index of the current element being processed in the array. - **array** (BigUint64Array) - The array reduceRight was called upon. ##### Instance Method Parameters - **callbackfn** (function) - Function to execute on each value in the array, taking four arguments. - **initialValue** (U) - Value to use as the first argument to the first call of the callbackfn. ### `reverse(): this` #### Description Reverses the elements in the array in place. #### Method `reverse` #### Return Value `this` - The reversed array. ### `set(array: ArrayLike, offset?: number): void` #### Description Sets values in the array from a given typed or untyped array. #### Method `set` #### Parameters - **array** (ArrayLike) - A typed or untyped array of values to set. - **offset** (number, Optional) - The index in the current array at which the values are to be written. ### `slice(start?: number, end?: number): BigUint64Array` #### Description Returns a new `BigUint64Array` containing a portion of the original array. #### Method `slice` #### Parameters - **start** (number, Optional) - The beginning of the specified portion of the array. Defaults to 0. - **end** (number, Optional) - The end of the specified portion of the array. Defaults to the array length. #### Return Value A new `BigUint64Array` containing the specified section of the original array. ### `some(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean` #### Description Tests whether at least one element in the array passes the test implemented by the provided function. #### Method `some` #### Parameters - **predicate** (function) - Function to test each element. It takes three arguments: `value`, `index`, and `array`. - **thisArg** (any, Optional) - Object to use as `this` when executing the `predicate`. #### Return Value `true` if the callback function returns a truthy value for at least one element in the array; otherwise, `false`. ### `sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this` #### Description Sorts the elements of an array in place. #### Method `sort` #### Parameters - **compareFn** (function, Optional) - Specifies a function that defines the sort order. If omitted, elements are sorted according to string conversion of each element. #### Return Value `this` - The sorted array. ### `subarray(begin?: number, end?: number): BigUint64Array` #### Description Returns a new `BigUint64Array` view of the portion of this array specified by the begin and end indices. #### Method `subarray` #### Parameters - **begin** (number, Optional) - The index of the beginning of the array. Defaults to 0. - **end** (number, Optional) - The index of the end of the array. Defaults to the array length. #### Return Value A new `BigUint64Array` representing the specified subarray. ### `toLocaleString(): string` #### Description Converts the array to a string using the current locale's conventions. #### Method `toLocaleString` #### Return Value A string representation of the array. ### `toString(): string` #### Description Returns a string representation of the array. #### Method `toString` #### Return Value A string representing the array. ### `valueOf(): BigUint64Array` #### Description Returns the primitive value of the specified object. #### Method `valueOf` #### Return Value The primitive value of the `BigUint64Array` object. ### `values(): IterableIterator` #### Description Returns a new iterator object that yields the value for each element in the `BigUint64Array` object in insertion order. #### Method `values` #### Return Value An `IterableIterator` object. ### `[Symbol.iterator](): IterableIterator` #### Description Allows the `BigUint64Array` object to be used in a `for...of` loop. #### Method `[Symbol.iterator]` #### Return Value An `IterableIterator` object. ``` -------------------------------- ### Find First Index of Element in BigInt64Array Source: https://github.com/oracle/oci-grafana-metrics/blob/master/THIRD_PARTY_LICENSES.txt The `indexOf` method returns the first index at which a given element can be found in the BigInt64Array. It accepts the element to search for and an optional starting index. If the element is not found, it returns -1. ```typescript indexOf(searchElement: bigint, fromIndex?: number): number; ```