123456 |
- "use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[5783],{7462:(e,t,a)=>{a.r(t),a.d(t,{plugin:()=>St});var r=a(43215),s=a(82897),n=a(68404),i=a(69783);let o;!function(e){e.InfluxQL="InfluxQL",e.Flux="Flux"}(o||(o={}));var l,u,d,c,m,p,h,g,f=a(45916);function y(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const{Input:v,SecretFormField:x}=i.LegacyForms,b=[{label:"GET",value:"GET"},{label:"POST",value:"POST"}],S=[{label:"InfluxQL",value:o.InfluxQL,description:"The InfluxDB SQL-like query language."},{label:"Flux",value:o.Flux,description:"Advanced data scripting and query language. Supported in InfluxDB 2.x and 1.8+"}];class j extends n.PureComponent{constructor(e){var t;super(e),y(this,"state",{maxSeries:""}),y(this,"htmlPrefix",void 0),y(this,"onResetPassword",(()=>{(0,r.updateDatasourcePluginResetOption)(this.props,"password")})),y(this,"onResetToken",(()=>{(0,r.updateDatasourcePluginResetOption)(this.props,"token")})),y(this,"onVersionChanged",(e=>{const{options:t,onOptionsChange:a}=this.props,r=Object.assign({},t,{jsonData:Object.assign({},t.jsonData,{version:e.value})});e.value===o.Flux&&(r.access="proxy",r.basicAuth=!0,r.jsonData.httpMode="POST",delete r.user,delete r.database),a(r)})),this.state.maxSeries=(null===(t=e.options.jsonData.maxSeries)||void 0===t?void 0:t.toString())||"",this.htmlPrefix=(0,s.uniqueId)("influxdb-config")}renderInflux2x(){const{options:e}=this.props,{secureJsonFields:t}=e,a=e.secureJsonData||{},{htmlPrefix:s}=this;return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsxs)("div",{className:"gf-form",children:[(0,f.jsx)(i.InlineFormLabel,{htmlFor:`${s}-org`,className:"width-10",children:"Organization"}),(0,f.jsx)("div",{className:"width-10",children:(0,f.jsx)(v,{id:`${s}-org`,className:"width-20",value:e.jsonData.organization||"",onChange:(0,r.onUpdateDatasourceJsonDataOption)(this.props,"organization")})})]})}),(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsx)("div",{className:"gf-form",children:(0,f.jsx)(x,{isConfigured:t&&t.token,value:a.token||"",label:"Token","aria-label":"Token",labelWidth:10,inputWidth:20,onReset:this.onResetToken,onChange:(0,r.onUpdateDatasourceSecureJsonDataOption)(this.props,"token")})})}),(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsxs)("div",{className:"gf-form",children:[l||(l=(0,f.jsx)(i.InlineFormLabel,{className:"width-10",children:"Default Bucket"})),(0,f.jsx)("div",{className:"width-10",children:(0,f.jsx)(v,{className:"width-20",placeholder:"default bucket",value:e.jsonData.defaultBucket||"",onChange:(0,r.onUpdateDatasourceJsonDataOption)(this.props,"defaultBucket")})})]})}),(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsxs)("div",{className:"gf-form",children:[u||(u=(0,f.jsx)(i.InlineFormLabel,{className:"width-10",tooltip:"A lower limit for the auto group by time interval. Recommended to be set to write frequency, for example 1m if your data is written every minute.",children:"Min time interval"})),(0,f.jsx)("div",{className:"width-10",children:(0,f.jsx)(v,{className:"width-10",placeholder:"10s",value:e.jsonData.timeInterval||"",onChange:(0,r.onUpdateDatasourceJsonDataOption)(this.props,"timeInterval")})})]})})]})}renderInflux1x(){const{options:e}=this.props,{secureJsonFields:t}=e,a=e.secureJsonData||{},{htmlPrefix:s}=this;return(0,f.jsxs)(f.Fragment,{children:[d||(d=(0,f.jsxs)(i.InfoBox,{children:[(0,f.jsx)("h5",{children:"Database Access"}),(0,f.jsxs)("p",{children:["Setting the database for this datasource does not deny access to other databases. The InfluxDB query syntax allows switching the database in the query. For example:",(0,f.jsx)("code",{children:"SHOW MEASUREMENTS ON _internal"})," or",(0,f.jsx)("code",{children:'SELECT * FROM "_internal".."database" LIMIT 10'}),(0,f.jsx)("br",{}),(0,f.jsx)("br",{}),"To support data isolation and security, make sure appropriate permissions are configured in InfluxDB."]})]})),(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsxs)("div",{className:"gf-form",children:[(0,f.jsx)(i.InlineFormLabel,{htmlFor:`${s}-db`,className:"width-10",children:"Database"}),(0,f.jsx)("div",{className:"width-20",children:(0,f.jsx)(v,{id:`${s}-db`,className:"width-20",value:e.database||"",onChange:(0,r.onUpdateDatasourceOption)(this.props,"database")})})]})}),(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsxs)("div",{className:"gf-form",children:[(0,f.jsx)(i.InlineFormLabel,{htmlFor:`${s}-user`,className:"width-10",children:"User"}),(0,f.jsx)("div",{className:"width-10",children:(0,f.jsx)(v,{id:`${s}-user`,className:"width-20",value:e.user||"",onChange:(0,r.onUpdateDatasourceOption)(this.props,"user")})})]})}),(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsx)("div",{className:"gf-form",children:(0,f.jsx)(x,{isConfigured:t&&t.password,value:a.password||"",label:"Password","aria-label":"Password",labelWidth:10,inputWidth:20,onReset:this.onResetPassword,onChange:(0,r.onUpdateDatasourceSecureJsonDataOption)(this.props,"password")})})}),(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsxs)("div",{className:"gf-form",children:[(0,f.jsx)(i.InlineFormLabel,{htmlFor:`${s}-http-method`,className:"width-10",tooltip:"You can use either GET or POST HTTP method to query your InfluxDB database. The POST method allows you to perform heavy requests (with a lots of WHERE clause) while the GET method will restrict you and return an error if the query is too large.",children:"HTTP Method"}),(0,f.jsx)(i.Select,{inputId:`${s}-http-method`,className:"width-10",value:b.find((t=>t.value===e.jsonData.httpMode)),options:b,defaultValue:e.jsonData.httpMode,onChange:(0,r.onUpdateDatasourceJsonDataOptionSelect)(this.props,"httpMode")})]})}),(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsxs)("div",{className:"gf-form",children:[c||(c=(0,f.jsx)(i.InlineFormLabel,{className:"width-10",tooltip:"A lower limit for the auto group by time interval. Recommended to be set to write frequency, for example 1m if your data is written every minute.",children:"Min time interval"})),(0,f.jsx)("div",{className:"width-10",children:(0,f.jsx)(v,{className:"width-10",placeholder:"10s",value:e.jsonData.timeInterval||"",onChange:(0,r.onUpdateDatasourceJsonDataOption)(this.props,"timeInterval")})})]})})]})}render(){const{options:e,onOptionsChange:t}=this.props;return(0,f.jsxs)(f.Fragment,{children:[m||(m=(0,f.jsx)("h3",{className:"page-heading",children:"Query Language"})),(0,f.jsx)("div",{className:"gf-form-group",children:(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsx)("div",{className:"gf-form",children:(0,f.jsx)(i.Select,{"aria-label":"Query language",className:"width-30",value:e.jsonData.version===o.Flux?S[1]:S[0],options:S,defaultValue:S[0],onChange:this.onVersionChanged})})})}),e.jsonData.version===o.Flux&&(p||(p=(0,f.jsxs)(i.InfoBox,{children:[(0,f.jsx)("h5",{children:"Support for Flux in Grafana is currently in beta"}),(0,f.jsxs)("p",{children:["Please report any issues to: ",(0,f.jsx)("br",{}),(0,f.jsx)("a",{href:"https://github.com/grafana/grafana/issues/new/choose",children:"https://github.com/grafana/grafana/issues"})]})]}))),"direct"===e.access&&(h||(h=(0,f.jsx)(i.Alert,{title:"Deprecation Notice",severity:"warning",children:"Browser access mode in the InfluxDB datasource is deprecated and will be removed in a future release."}))),(0,f.jsx)(i.DataSourceHttpSettings,{showAccessOptions:!0,dataSourceConfig:e,defaultUrl:"http://localhost:8086",onChange:t}),(0,f.jsxs)("div",{className:"gf-form-group",children:[g||(g=(0,f.jsx)("div",{children:(0,f.jsx)("h3",{className:"page-heading",children:"InfluxDB Details"})})),e.jsonData.version===o.Flux?this.renderInflux2x():this.renderInflux1x(),(0,f.jsx)("div",{className:"gf-form-inline",children:(0,f.jsx)(i.InlineField,{labelWidth:20,label:"Max series",tooltip:"Limit the number of series/tables that Grafana will process. Lower this number to prevent abuse, and increase it if you have lots of small time series and not all are shown. Defaults to 1000.",children:(0,f.jsx)(v,{placeholder:"1000",type:"number",className:"width-10",value:this.state.maxSeries,onChange:e=>{this.setState({maxSeries:e.currentTarget.value});const t=parseInt(e.currentTarget.value,10);(0,r.updateDatasourcePluginJsonDataOption)(this.props,"maxSeries",Number.isFinite(t)?t:void 0)}})})})]})]})}}const w=j;var C;const O=[{title:"Getting started",label:"Start by selecting a measurement and field from the dropdown above. You can then use the tag selector to further narrow your search."}],T=e=>(0,f.jsxs)("div",{children:[C||(C=(0,f.jsx)("h2",{children:"InfluxDB Cheat Sheet"})),O.map((e=>(0,f.jsxs)("div",{className:"cheat-sheet-item",children:[(0,f.jsx)("div",{className:"cheat-sheet-item__title",children:e.title}),(0,f.jsx)("div",{className:"cheat-sheet-item__label",children:e.label})]},e.title)))]});class I extends n.PureComponent{render(){return(0,f.jsx)(T,{onClickExample:this.props.onClickExample})}}var E=a(36636),P=a(39132),D=a(76355);const F=[],N={Aggregations:[],Selectors:[],Transformations:[],Predictors:[],Math:[],Aliasing:[],Fields:[]};function k(e){const t=F[e.type];if(!t)throw{message:"Could not find query part "+e.type};return new D.XN(e,t)}function A(e){F[e.type]=new D.zU(e),e.category.push(F[e.type])}const R=[];function M(e,t){return"*"===e.params[0]?"*":'"'+e.params[0]+'"'}function B(e,t){for(let a=0;a<e.length;a++){const r=e[a];if(r.def.category===N.Aggregations){if(r.def.type===t.def.type)return;if("count"===r.def.type&&"distinct"===t.def.type)break;if("distinct"===r.def.type){const r=e.length>=a+2;if("count"!==t.def.type&&r){e[a+1].def.category===N.Aggregations&&e.splice(a+1,1)}else if("count"===t.def.type)return void(r&&"count"===e[a+1].def.type||e.splice(a+1,0,t))}return void(e[a]=t)}if(r.def.category===N.Selectors)return void(e[a]=t)}e.splice(1,0,t)}function q(e,t){let a;for(a=0;a<e.length;a++){const t=e[a];if(t.def.category===N.Math||t.def.category===N.Aliasing)break}e.splice(a,0,t)}A({type:"field",addStrategy:function(e,t,a){const r=(0,s.map)(e,(e=>k({type:e.def.type,params:(0,s.clone)(e.params)})));a.selectModels.push(r)},category:N.Fields,params:[{type:"field",dynamicLookup:!0}],defaultParams:["value"],renderer:M}),A({type:"count",addStrategy:B,category:N.Aggregations,params:[],defaultParams:[],renderer:D.D}),A({type:"distinct",addStrategy:B,category:N.Aggregations,params:[],defaultParams:[],renderer:D.D}),A({type:"integral",addStrategy:B,category:N.Aggregations,params:[],defaultParams:[],renderer:D.D}),A({type:"mean",addStrategy:B,category:N.Aggregations,params:[],defaultParams:[],renderer:D.D}),A({type:"median",addStrategy:B,category:N.Aggregations,params:[],defaultParams:[],renderer:D.D}),A({type:"mode",addStrategy:B,category:N.Aggregations,params:[],defaultParams:[],renderer:D.D}),A({type:"sum",addStrategy:B,category:N.Aggregations,params:[],defaultParams:[],renderer:D.D}),A({type:"derivative",addStrategy:q,category:N.Transformations,params:[{name:"duration",type:"interval",options:["1s","10s","1m","5m","10m","15m","1h"]}],defaultParams:["10s"],renderer:D.D}),A({type:"spread",addStrategy:q,category:N.Transformations,params:[],defaultParams:[],renderer:D.D}),A({type:"non_negative_derivative",addStrategy:q,category:N.Transformations,params:[{name:"duration",type:"interval",options:["1s","10s","1m","5m","10m","15m","1h"]}],defaultParams:["10s"],renderer:D.D}),A({type:"difference",addStrategy:q,category:N.Transformations,params:[],defaultParams:[],renderer:D.D}),A({type:"non_negative_difference",addStrategy:q,category:N.Transformations,params:[],defaultParams:[],renderer:D.D}),A({type:"moving_average",addStrategy:q,category:N.Transformations,params:[{name:"window",type:"int",options:[5,10,20,30,40]}],defaultParams:[10],renderer:D.D}),A({type:"cumulative_sum",addStrategy:q,category:N.Transformations,params:[],defaultParams:[],renderer:D.D}),A({type:"stddev",addStrategy:q,category:N.Transformations,params:[],defaultParams:[],renderer:D.D}),A({type:"time",category:R,params:[{name:"interval",type:"time",options:["$__interval","1s","10s","1m","5m","10m","15m","1h"]}],defaultParams:["$__interval"],renderer:D.D}),A({type:"fill",category:R,params:[{name:"fill",type:"string",options:["none","null","0","previous","linear"]}],defaultParams:["null"],renderer:D.D}),A({type:"elapsed",addStrategy:q,category:N.Transformations,params:[{name:"duration",type:"interval",options:["1s","10s","1m","5m","10m","15m","1h"]}],defaultParams:["10s"],renderer:D.D}),A({type:"holt_winters",addStrategy:q,category:N.Predictors,params:[{name:"number",type:"int",options:[5,10,20,30,40]},{name:"season",type:"int",options:[0,1,2,5,10]}],defaultParams:[10,2],renderer:D.D}),A({type:"holt_winters_with_fit",addStrategy:q,category:N.Predictors,params:[{name:"number",type:"int",options:[5,10,20,30,40]},{name:"season",type:"int",options:[0,1,2,5,10]}],defaultParams:[10,2],renderer:D.D}),A({type:"bottom",addStrategy:B,category:N.Selectors,params:[{name:"count",type:"int"}],defaultParams:[3],renderer:D.D}),A({type:"first",addStrategy:B,category:N.Selectors,params:[],defaultParams:[],renderer:D.D}),A({type:"last",addStrategy:B,category:N.Selectors,params:[],defaultParams:[],renderer:D.D}),A({type:"max",addStrategy:B,category:N.Selectors,params:[],defaultParams:[],renderer:D.D}),A({type:"min",addStrategy:B,category:N.Selectors,params:[],defaultParams:[],renderer:D.D}),A({type:"percentile",addStrategy:B,category:N.Selectors,params:[{name:"nth",type:"int"}],defaultParams:[95],renderer:D.D}),A({type:"top",addStrategy:B,category:N.Selectors,params:[{name:"count",type:"int"}],defaultParams:[3],renderer:D.D}),A({type:"tag",category:R,params:[{name:"tag",type:"string",dynamicLookup:!0}],defaultParams:["tag"],renderer:M}),A({type:"math",addStrategy:function(e,t){const a=e.length;if(a>0){if("math"===e[a-1].def.type)return void(e[a-1]=t);if(a>1&&"math"===e[a-2].def.type)return void(e[a-2]=t);if("alias"===e[a-1].def.type)return void e.splice(a-1,0,t)}e.push(t)},category:N.Math,params:[{name:"expr",type:"string"}],defaultParams:[" / 100"],renderer:D.C7}),A({type:"alias",addStrategy:function(e,t){const a=e.length;a>0&&"alias"===e[a-1].def.type?e[a-1]=t:e.push(t)},category:N.Aliasing,params:[{name:"name",type:"string",quote:"double"}],defaultParams:["alias"],renderMode:"suffix",renderer:function(e,t){return t+' AS "'+e.params[0]+'"'}});const L={create:k,getCategories:()=>N,replaceAggregationAdd:B};function _(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class Q{constructor(e,t,a){_(this,"target",void 0),_(this,"selectModels",[]),_(this,"queryBuilder",void 0),_(this,"groupByParts",void 0),_(this,"templateSrv",void 0),_(this,"scopedVars",void 0),_(this,"refId",void 0),this.target=e,this.templateSrv=t,this.scopedVars=a,e.policy=e.policy||"default",e.resultFormat=e.resultFormat||"time_series",e.orderByTime=e.orderByTime||"ASC",e.tags=e.tags||[],e.groupBy=e.groupBy||[{type:"time",params:["$__interval"]},{type:"fill",params:["null"]}],e.select=e.select||[[{type:"field",params:["value"]},{type:"mean",params:[]}]],this.updateProjection()}updateProjection(){this.selectModels=(0,s.map)(this.target.select,(e=>(0,s.map)(e,L.create))),this.groupByParts=(0,s.map)(this.target.groupBy,L.create)}updatePersistedParts(){this.target.select=(0,s.map)(this.selectModels,(e=>(0,s.map)(e,(e=>({type:e.def.type,params:e.params})))))}hasGroupByTime(){return(0,s.find)(this.target.groupBy,(e=>"time"===e.type))}hasFill(){return(0,s.find)(this.target.groupBy,(e=>"fill"===e.type))}addGroupBy(e){let t=e.match(/^(\w+)\((.*)\)$/);if(!t||!this.target.groupBy)return;const a=t[1],r=t[2],s=L.create({type:a,params:[r]}),n=this.target.groupBy.length;0===n?this.target.groupBy.push(s.part):"time"===a?this.target.groupBy.splice(0,0,s.part):"tag"===a&&"fill"===this.target.groupBy[n-1].type?this.target.groupBy.splice(n-1,0,s.part):this.target.groupBy.push(s.part),this.updateProjection()}removeGroupByPart(e,t){const a=L.getCategories();"time"===e.def.type&&(this.target.groupBy=(0,s.filter)(this.target.groupBy,(e=>"fill"!==e.type)),this.target.select=(0,s.map)(this.target.select,(e=>(0,s.filter)(e,(e=>{const t=L.create(e);return t.def.category!==a.Aggregations&&t.def.category!==a.Selectors}))))),this.target.groupBy.splice(t,1),this.updateProjection()}removeSelect(e){this.target.select.splice(e,1),this.updateProjection()}removeSelectPart(e,t){if("field"===t.def.type){if(this.selectModels.length>1){const t=(0,s.indexOf)(this.selectModels,e);this.selectModels.splice(t,1)}}else{const a=(0,s.indexOf)(e,t);e.splice(a,1)}this.updatePersistedParts()}addSelectPart(e,t){const a=L.create({type:t});a.def.addStrategy(e,a,this),this.updatePersistedParts()}renderTagCondition(e,t,a){let r="",s=e.operator,n=e.value;return t>0&&(r=(e.condition||"AND")+" "),s||(s=/^\/.*\/$/.test(n)?"=~":"="),"=~"!==s&&"!~"!==s?(a&&(n=this.templateSrv.replace(n,this.scopedVars)),">"!==s&&"<"!==s&&(n="'"+n.replace(/\\/g,"\\\\").replace(/\'/g,"\\'")+"'")):a&&(n=this.templateSrv.replace(n,this.scopedVars,"regex")),r+'"'+e.key+'" '+s+" "+n}getMeasurementAndPolicy(e){let t=this.target.policy,a=this.target.measurement||"measurement";return a.match("^/.*/$")?e&&(a=this.templateSrv.replace(a,this.scopedVars,"regex")):a='"'+a+'"',t="default"!==t?'"'+this.target.policy+'".':"",t+a}interpolateQueryStr(e,t,a){if(!t.multi&&!t.includeAll)return e;if("string"==typeof e)return P.Z.regexEscape(e);return"("+(0,s.map)(e,P.Z.regexEscape).join("|")+")"}render(e){const t=this.target;if(t.rawQuery)return e?this.templateSrv.replace(t.query,this.scopedVars,this.interpolateQueryStr):t.query;let a,r,n="SELECT ";for(a=0;a<this.selectModels.length;a++){const e=this.selectModels[a];let t="";for(r=0;r<e.length;r++){t=e[r].render(t)}a>0&&(n+=", "),n+=t}n+=" FROM "+this.getMeasurementAndPolicy(e)+" WHERE ";const i=(0,s.map)(t.tags,((t,a)=>this.renderTagCondition(t,a,e)));i.length>0&&(n+="("+i.join(" ")+") AND "),n+="$timeFilter";let o="";for(a=0;a<this.groupByParts.length;a++){const e=this.groupByParts[a];a>0&&(o+="fill"===e.def.type?" ":", "),o+=e.render("")}return o.length&&(n+=" GROUP BY "+o),t.fill&&(n+=" fill("+t.fill+")"),"DESC"===t.orderByTime&&(n+=" ORDER BY time DESC"),t.limit&&(n+=" LIMIT "+t.limit),t.slimit&&(n+=" SLIMIT "+t.slimit),t.tz&&(n+=" tz('"+t.tz+"')"),n}renderAdhocFilters(e){const t=(0,s.map)(e,((e,t)=>this.renderTagCondition(e,t,!0)));return t.join(" ")}}function V(e){const t=(0,s.cloneDeep)(e);return new Q(t).render(!1)}Q.$inject=["target","templateSrv","scopedVars"];var $,G,U,z=a(90923);function W(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const H=[{label:"Show buckets",description:"List the available buckets (table)",value:"buckets()"},{label:"Simple query",description:"filter by measurement and field",value:'from(bucket: "db/rp")\n |> range(start: v.timeRangeStart, stop:v.timeRangeStop)\n |> filter(fn: (r) =>\n r._measurement == "example-measurement" and\n r._field == "example-field"\n )'},{label:"Grouped Query",description:"Group by (min/max/sum/median)",value:'// v.windowPeriod is a variable referring to the current optimized window period (currently: $interval)\nfrom(bucket: v.bucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r["_measurement"] == "measurement1" or r["_measurement"] =~ /^.*?regex.*$/)\n |> filter(fn: (r) => r["_field"] == "field2" or r["_field"] =~ /^.*?regex.*$/)\n |> aggregateWindow(every: v.windowPeriod, fn: mean|median|max|count|derivative|sum)\n |> yield(name: "some-name")'},{label:"Filter by value",description:"Results between a min/max",value:'// v.bucket, v.timeRangeStart, and v.timeRange stop are all variables supported by the flux plugin and influxdb\nfrom(bucket: v.bucket)\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r["_value"] >= 10 and r["_value"] <= 20)'},{label:"Schema Exploration: (measurements)",description:"Get a list of measurement using flux",value:'import "influxdata/influxdb/v1"\nv1.measurements(bucket: v.bucket)'},{label:"Schema Exploration: (fields)",description:"Return every possible key in a single table",value:'from(bucket: v.bucket)\n |> range(start: v.timeRangeStart, stop:v.timeRangeStop)\n |> keys()\n |> keep(columns: ["_value"])\n |> group()\n |> distinct()'},{label:"Schema Exploration: (tag keys)",description:"Get a list of tag keys using flux",value:'import "influxdata/influxdb/v1"\nv1.tagKeys(bucket: v.bucket)'},{label:"Schema Exploration: (tag values)",description:"Get a list of tag values using flux",value:'import "influxdata/influxdb/v1"\nv1.tagValues(\n bucket: v.bucket,\n tag: "host",\n predicate: (r) => true,\n start: -1d\n)'}];class K extends n.PureComponent{constructor(){super(...arguments),W(this,"onFluxQueryChange",(e=>{this.props.onChange(Object.assign({},this.props.query,{query:e})),this.props.onRunQuery()})),W(this,"onSampleChange",(e=>{this.props.onChange(Object.assign({},this.props.query,{query:e.value})),this.forceUpdate(),this.props.onRunQuery()})),W(this,"getSuggestions",(()=>{const e=[{label:"v.timeRangeStart",kind:i.CodeEditorSuggestionItemKind.Property,detail:"The start time"},{label:"v.timeRangeStop",kind:i.CodeEditorSuggestionItemKind.Property,detail:"The stop time"},{label:"v.windowPeriod",kind:i.CodeEditorSuggestionItemKind.Property,detail:"based on max data points"},{label:"v.defaultBucket",kind:i.CodeEditorSuggestionItemKind.Property,detail:"bucket configured in the datsource"},{label:"v.organization",kind:i.CodeEditorSuggestionItemKind.Property,detail:"org configured for the datsource"}],t=(0,z.getTemplateSrv)();return t.getVariables().forEach((a=>{const r="${"+a.name+"}";let s=t.replace(r);s===r&&(s=""),e.push({label:r,kind:i.CodeEditorSuggestionItemKind.Text,detail:`(Template Variable) ${s}`})})),e})),W(this,"editorDidMountCallbackHack",(e=>{setTimeout((()=>e.layout()),100)}))}render(){const{query:e}=this.props,t=$||($=(0,f.jsxs)("div",{children:["Type: ",(0,f.jsx)("i",{children:"ctrl+space"})," to show template variable suggestions ",(0,f.jsx)("br",{}),"Many queries can be copied from Chronograf"]}));return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(i.CodeEditor,{height:"200px",language:"sql",value:e.query||"",onBlur:this.onFluxQueryChange,onSave:this.onFluxQueryChange,showMiniMap:!1,showLineNumbers:!0,getSuggestions:this.getSuggestions,onEditorDidMount:this.editorDidMountCallbackHack}),(0,f.jsxs)("div",{className:(0,E.cx)("gf-form-inline",E.css`
- margin-top: 6px;
- `),children:[G||(G=(0,f.jsx)(i.LinkButton,{icon:"external-link-alt",variant:"secondary",target:"blank",href:"https://docs.influxdata.com/influxdb/latest/query-data/get-started/",children:"Flux language syntax"})),(0,f.jsx)(i.Segment,{options:H,value:"Sample Query",onChange:this.onSampleChange}),U||(U=(0,f.jsx)("div",{className:"gf-form gf-form--grow",children:(0,f.jsx)("div",{className:"gf-form-label gf-form-label--grow"})})),(0,f.jsx)(i.InlineFormLabel,{width:5,tooltip:t,children:"Help"})]})]})}}const Y=e=>{let{isRaw:t,onChange:a}=e;const[r,s]=(0,n.useState)(!1);return(0,n.useEffect)((()=>{s(!1)}),[t]),t?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(i.Button,{"aria-label":"Switch to visual editor",icon:"pen",variant:"secondary",type:"button",onClick:()=>{s(!0)}}),(0,f.jsx)(i.ConfirmModal,{isOpen:r,title:"Switch to visual editor mode",body:"Are you sure to switch to visual editor mode? You will lose the changes done in raw query mode.",confirmText:"Yes, switch to editor mode",dismissText:"No, stay in raw query mode",onConfirm:()=>{a(!1)},onDismiss:()=>{s(!1)}})]}):(0,f.jsx)(i.Button,{"aria-label":"Switch to text editor",icon:"pen",variant:"secondary",type:"button",onClick:()=>{a(!0)}})},J=[{label:"Time series",value:"time_series"},{label:"Table",value:"table"},{label:"Logs",value:"logs"}],Z="time_series";var X=a(20002);function ee(e){const[t,a]=(0,n.useState)(e),r=(0,X.Z)(e);return(0,n.useEffect)((()=>{r!==e&&t!==e&&a(e)}),[e,t,r]),[t,a]}var te=a(68366);const ae=e=>{var t;let{query:a,onChange:r,onRunQuery:s}=e;const[n,o]=ee(a.query),[l,u]=ee(a.alias),d=(0,te.L)(),c=(0,te.L)(),m=null!==(t=a.resultFormat)&&void 0!==t?t:Z,p=()=>{r(Object.assign({},a,{query:n,alias:l,resultFormat:m})),s()};return(0,f.jsxs)("div",{children:[(0,f.jsx)(i.TextArea,{"aria-label":"query",rows:3,spellCheck:!1,placeholder:"InfluxDB Query",onBlur:p,onChange:e=>{o(e.currentTarget.value)},value:null!=n?n:""}),(0,f.jsxs)(i.HorizontalGroup,{children:[(0,f.jsx)(i.InlineFormLabel,{htmlFor:c,children:"Format as"}),(0,f.jsx)(i.Select,{inputId:c,onChange:e=>{r(Object.assign({},a,{resultFormat:e.value})),s()},value:m,options:J}),(0,f.jsx)(i.InlineFormLabel,{htmlFor:d,children:"Alias by"}),(0,f.jsx)(i.Input,{id:d,type:"text",spellCheck:!1,placeholder:"Naming pattern",onBlur:p,onChange:e=>{u(e.currentTarget.value)},value:null!=l?l:""})]})]})};class re{constructor(e,t){this.target=e,this.database=t}buildExploreQuery(e,t,a){let r,n,i="";if("TAG_KEYS"===e)i="SHOW TAG KEYS",r=this.target.measurement,n=this.target.policy;else if("TAG_VALUES"===e)i="SHOW TAG VALUES",r=this.target.measurement,n=this.target.policy;else if("MEASUREMENTS"===e)i="SHOW MEASUREMENTS",a&&(i+=" WITH MEASUREMENT =~ /(?i)"+P.Z.regexEscape(a)+"/");else{if("FIELDS"===e)return r=this.target.measurement,n=this.target.policy,r.match("^/.*/")||(r='"'+r+'"',n&&"default"!==n&&(n='"'+n+'"',r=n+"."+r)),"SHOW FIELD KEYS FROM "+r;if("RETENTION POLICIES"===e)return i='SHOW RETENTION POLICIES on "'+this.database+'"',i}if(r&&(r.match("^/.*/")||r.match(/^merge\(.*\)/)||(r='"'+r+'"'),n&&"default"!==n&&(n='"'+n+'"',r=n+"."+r),i+=" FROM "+r),t&&(i+=' WITH KEY = "'+t+'"'),this.target.tags&&this.target.tags.length>0){const e=(0,s.reduce)(this.target.tags,((e,a)=>(a.key===t||">"===a.operator||"<"===a.operator||e.push(function(e,t){let a="",r=e.operator,s=e.value;return t>0&&(a=(e.condition||"AND")+" "),r||(r=/^\/.*\/$/.test(e.value)?"=~":"="),(""===s||"=~"!==r&&"!~"!==r&&isNaN(+s))&&(s="'"+s.replace(/\\/g,"\\\\").replace(/\'/g,"\\'")+"'"),a+'"'+e.key+'" '+r+" "+s}(a,e.length)),e)),[]);e.length>0&&(i+=" WHERE "+e.join(" "))}return"MEASUREMENTS"===e&&(i+=" LIMIT 100"),i}}const se=(e,t,a,r,s)=>{const n=new re(r,s.database).buildExploreQuery(e,t,a);return s.metricFindQuery(n)};async function ne(e,t,a,r){const s={tags:a,measurement:e,policy:t};return(await se("TAG_KEYS",void 0,void 0,s,r)).map((e=>e.text))}const ie=(0,E.css)({paddingRight:"4px"});function oe(e){if(null==e)throw new Error("value must not be nullish");return e}const le=(0,E.cx)("width-8",ie),ue=e=>{let{format:t,inputId:a,onChange:r}=e;return(0,f.jsx)(i.Select,{inputId:a,className:le,onChange:e=>{r(oe(e.value))},value:t,options:J})};var de=a(99151),ce=a.n(de),me=a(42147);const pe=(0,E.css)({minWidth:"160px"}),he=e=>e,ge=e=>{let{loadOptions:t,allowCustomValue:a,onChange:r,onClose:s}=e;const n=ce()(t,1e3,{leading:!0});return(0,f.jsx)("div",{className:pe,children:(0,f.jsx)(i.AsyncSelect,{formatCreateLabel:he,defaultOptions:!0,autoFocus:!0,isOpen:!0,onCloseMenu:s,allowCustomValue:a,loadOptions:n,onChange:r})})},fe=e=>{var t;let{loadOptions:a,allowCustomValue:r,onChange:s,onClose:o}=e;const[l,u]=(0,me.Z)(a,[a]);return(0,n.useEffect)((()=>{u("")}),[u,a]),(0,f.jsx)("div",{className:pe,children:(0,f.jsx)(i.Select,{isLoading:l.loading,formatCreateLabel:he,autoFocus:!0,isOpen:!0,onCloseMenu:o,allowCustomValue:r,options:null!==(t=l.value)&&void 0!==t?t:[],onChange:s})})},ye=e=>{let{loadOptions:t,filterByLoadOptions:a,allowCustomValue:r,onChange:s,onClose:n}=e;return a?(0,f.jsx)(ge,{loadOptions:t,allowCustomValue:r,onChange:s,onClose:n}):(0,f.jsx)(fe,{loadOptions:t,allowCustomValue:r,onChange:s,onClose:n})},ve=e=>{let{initialValue:t,onChange:a,onClose:r}=e;const[s,n]=ee(t);return(0,f.jsx)(i.Input,{autoFocus:!0,type:"text",spellCheck:!1,onBlur:r,onKeyDown:e=>{"Enter"===e.key&&a(s)},onChange:e=>{n(e.currentTarget.value)},value:s})},xe=(0,E.css)({width:"auto",cursor:"pointer"}),be=e=>{let{value:t,buttonClassName:a,loadOptions:r,filterByLoadOptions:s,allowCustomValue:o,onChange:l}=e;const[u,d]=(0,n.useState)(!1);if(u)return void 0!==r?(0,f.jsx)(ye,{loadOptions:r,filterByLoadOptions:null!=s&&s,allowCustomValue:o,onChange:e=>{d(!1),l(e)},onClose:()=>{d(!1)}}):(0,f.jsx)(ve,{initialValue:t,onClose:()=>{d(!1)},onChange:e=>{d(!1),l({value:e,label:e})}});{const e=(0,E.cx)(xe,a);return(0,f.jsx)(i.InlineLabel,{as:"button",className:e,onClick:()=>{d(!0)},children:t})}};function Se(e){return{label:e,value:e}}const je=e=>{let{policy:t,measurement:a,onChange:r,getPolicyOptions:s,getMeasurementOptions:n}=e;return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(be,{allowCustomValue:!0,value:null!=t?t:"using default policy",loadOptions:async()=>{const e=await s();return(e.some((e=>"default"===e))?e:["default",...e]).map(Se)},onChange:e=>{r(e.value,a)}}),(0,f.jsx)(be,{allowCustomValue:!0,value:null!=a?a:"select measurement",loadOptions:async e=>(await n(e)).map(Se),filterByLoadOptions:!0,onChange:e=>{r(t,e.value)}})]})},we=e=>{let{value:t,onChange:a,isWide:r,placeholder:s}=e;const[n,o]=ee(t);return(0,f.jsx)(f.Fragment,{children:(0,f.jsx)(i.Input,{placeholder:s,className:(0,E.cx)(null!=r&&r?"width-14":"width-8",ie),type:"text",spellCheck:!1,onBlur:()=>{a(""===n?void 0:n)},onChange:e=>{o(e.currentTarget.value)},value:null!=n?n:""})})},Ce=[{label:"ascending",value:"ASC"},{label:"descending",value:"DESC"}],Oe=(0,E.cx)("width-9",ie),Te=e=>{let{value:t,onChange:a,inputId:r}=e;return(0,f.jsx)(f.Fragment,{children:(0,f.jsx)(i.Select,{inputId:r,className:Oe,onChange:e=>{a(oe(e.value))},value:t,options:Ce})})},Ie=e=>{let{loadOptions:t,allowCustomValue:a,onAdd:r}=e;return(0,f.jsx)(be,{value:"+",loadOptions:t,allowCustomValue:a,onChange:e=>{r(oe(e.value))}})},Ee=(0,E.css)({paddingRight:"0",marginRight:"0"}),Pe=e=>{let{name:t,onRemove:a}=e;return(0,f.jsx)(i.WithContextMenu,{renderMenuItems:()=>{return e=a,(0,f.jsx)(i.MenuGroup,{label:"",children:(0,f.jsx)(i.MenuItem,{label:"remove",onClick:e})});var e},children:e=>{let{openMenu:a}=e;return(0,f.jsx)("button",{className:(0,E.cx)("gf-form-label",Ee),onClick:a,children:t})}})},De=(0,E.css)({paddingLeft:"0",paddingRight:"0",marginLeft:"0",marginRight:"0"}),Fe=e=>{let{name:t,params:a,onChange:r,onRemove:s}=e;const o=(0,i.useTheme2)(),l=(0,n.useMemo)((()=>(e=>(0,E.cx)("gf-form-label",(0,E.css)({paddingLeft:"0",lineHeight:e.typography.body.lineHeight,fontSize:e.typography.body.fontSize})))(o)),[o]);return(0,f.jsxs)("div",{className:l,children:[(0,f.jsx)(Pe,{name:t,onRemove:s}),"(",a.map(((e,t)=>{const{value:s,options:i}=e,o=t===a.length-1,l=null!==i?()=>i().then((e=>e.map(Se))):void 0;return(0,f.jsxs)(n.Fragment,{children:[(0,f.jsx)(be,{allowCustomValue:!0,value:s,buttonClassName:De,loadOptions:l,onChange:e=>{((e,t)=>{const s=a.map((e=>e.value));s[t]=e,r(s)})(oe(e.value),t)}}),!o&&","]},t)})),")"]})},Ne=e=>{let{parts:t,getNewPartOptions:a,onAddNewPart:r,onRemovePart:s,onChange:n}=e;return(0,f.jsxs)(f.Fragment,{children:[t.map(((e,t)=>(0,f.jsx)(Fe,{name:e.name,params:e.params,onRemove:()=>{s(t)},onChange:e=>{n(t,e)}},t))),(0,f.jsx)(Ie,{loadOptions:a,onAdd:r})]})};function ke(e){return/^\/.*\/$/.test(e)}function Ae(e){var t;return null!==(t=e.operator)&&void 0!==t?t:ke(e.value)?"=~":"="}function Re(e,t){var a;return t?void 0:null!==(a=e.condition)&&void 0!==a?a:"AND"}function Me(e,t){const a="=~"===e||"!~"===e;return ke(t)?a?e:"=~":a?"=":e}const Be=["=","!=","<>","<",">","=~","!~"].map(Se),qe=["AND","OR"].map(Se),Le=()=>Promise.resolve(qe),_e=()=>Promise.resolve(Be),Qe=e=>{let{tag:t,isFirst:a,onRemove:r,onChange:s,getTagKeyOptions:n,getTagValueOptions:i}=e;const o=Ae(t),l=Re(t,a);return(0,f.jsxs)("div",{className:"gf-form",children:[null!=l&&(0,f.jsx)(be,{value:l,loadOptions:Le,onChange:e=>{s(Object.assign({},t,{condition:e.value}))}}),(0,f.jsx)(be,{allowCustomValue:!0,value:t.key,loadOptions:()=>n().catch((e=>(console.error(e),[]))).then((e=>[{label:"-- remove filter --",value:void 0},...e.map(Se)])),onChange:e=>{const{value:a}=e;void 0===a?r():s(Object.assign({},t,{key:null!=a?a:""}))}}),(0,f.jsx)(be,{value:o,loadOptions:_e,onChange:e=>{s(Object.assign({},t,{operator:e.value}))}}),(0,f.jsx)(be,{allowCustomValue:!0,value:t.value,loadOptions:()=>i(t.key).then((e=>e.map(Se))),onChange:e=>{var a;const r=null!==(a=e.value)&&void 0!==a?a:"";s(Object.assign({},t,{value:r,operator:Me(o,r)}))}})]})},Ve=e=>{let{tags:t,onChange:a,getTagKeyOptions:r,getTagValueOptions:s}=e;return(0,f.jsxs)(f.Fragment,{children:[t.map(((e,n)=>(0,f.jsx)(Qe,{tag:e,isFirst:0===n,onChange:e=>{((e,r)=>{const s=t.map(((t,a)=>r===a?e:t));a(s)})(e,n)},onRemove:()=>{(e=>{const r=t.filter(((t,a)=>a!==e));a(r)})(n)},getTagKeyOptions:r,getTagValueOptions:s},n))),(0,f.jsx)(Ie,{allowCustomValue:!0,loadOptions:()=>r().then((e=>e.map(Se))),onAdd:e=>{((e,r)=>{const s={key:e,value:"select tag value"},n={key:s.key,value:s.value,operator:Ae(s),condition:Re(s,r)};a([...t,n])})(e,0===t.length)}})]})};function $e(e,t){var a;const r=L.create(e).def,s=(null!==(a=e.params)&&void 0!==a?a:[]).map((e=>e.toString()));if(s.length!==r.params.length)throw new Error("Invalid query-segment");return s.map(((e,a)=>{const s=r.params[a];return s.dynamicLookup?{value:e,options:oe(t.get(`${r.type}_${a}`))}:null!=s.options?{value:e,options:()=>Promise.resolve(s.options)}:{value:e,options:null}}))}function Ge(e,t){return e.map((e=>({name:e.type,params:$e(e,t)})))}function Ue(e){return e.then((e=>[...(0,z.getTemplateSrv)().getVariables().map((e=>`/^$${e.name}$/`)),...e]))}function ze(e,t){return e.filter((e=>t.has(e.key)))}const We=e=>{var t,a,r,o;const l=(0,te.L)(),u=`influxdb-qe-format-as-${l}`,d=`influxdb-qe-order-by${l}`,c=(0,i.useStyles2)(He),m=function(e){if(void 0!==e.policy&&void 0!==e.resultFormat&&void 0!==e.orderByTime&&void 0!==e.tags&&void 0!==e.groupBy&&void 0!==e.select)return e;const t=(0,s.cloneDeep)(e);return new Q(t).target}(e.query),{datasource:p}=e,{measurement:h,policy:g}=m,y=(0,n.useMemo)((()=>ne(h,g,[],p).then((e=>new Set(e)))),[h,g,p]),v=(0,n.useMemo)((()=>{var e;const t=new Map([["field_0",()=>void 0!==h?async function(e,t,a){const r={tags:[],measurement:e,policy:t};return(await se("FIELDS",void 0,void 0,r,a)).map((e=>e.text))}(h,g,p):Promise.resolve([])]]);return(null!==(e=m.select)&&void 0!==e?e:[]).map((e=>Ge(e,t)))}),[h,g,m.select,p]),x=(0,n.useMemo)((()=>()=>y.then((e=>{var t;return ne(h,g,ze(null!==(t=m.tags)&&void 0!==t?t:[],e),p)}))),[h,g,m.tags,p,y]),b=(0,n.useMemo)((()=>{var e;const t=new Map([["tag_0",x]]);return Ge(null!==(e=m.groupBy)&&void 0!==e?e:[],t)}),[x,m.groupBy]),S=t=>{e.onChange(t),e.onRunQuery()};return(0,f.jsxs)("div",{children:[(0,f.jsxs)(i.SegmentSection,{label:"FROM",fill:!0,children:[(0,f.jsx)(je,{policy:g,measurement:h,getPolicyOptions:()=>async function(e){const t={tags:[],measurement:void 0,policy:void 0};return(await se("RETENTION POLICIES",void 0,void 0,t,e)).map((e=>e.text))}(p),getMeasurementOptions:e=>Ue(y.then((t=>{var a;return async function(e,t,a){const r={tags:t,measurement:void 0,policy:void 0};return(await se("MEASUREMENTS",void 0,e,r,a)).map((e=>e.text))}(""===e?void 0:e,ze(null!==(a=m.tags)&&void 0!==a?a:[],t),p)}))),onChange:(e,t)=>{S(Object.assign({},m,{policy:e,measurement:t}))}}),(0,f.jsx)(i.InlineLabel,{width:"auto",className:c.inlineLabel,children:"WHERE"}),(0,f.jsx)(Ve,{tags:null!==(t=m.tags)&&void 0!==t?t:[],onChange:e=>{S(Object.assign({},m,{tags:0===e.length?void 0:e}))},getTagKeyOptions:x,getTagValueOptions:e=>Ue(y.then((t=>{var a;return async function(e,t,a,r,s){const n={tags:r,measurement:t,policy:a};return(await se("TAG_VALUES",e,void 0,n,s)).map((e=>e.text))}(e,h,g,ze(null!==(a=m.tags)&&void 0!==a?a:[],t),p)})))})]}),v.map(((e,t)=>(0,f.jsx)(i.SegmentSection,{label:0===t?"SELECT":"",fill:!0,children:(0,f.jsx)(Ne,{parts:e,getNewPartOptions:()=>Promise.resolve(function(){const e=L.getCategories(),t=[];return Object.keys(e).forEach((a=>{const r=e[a].map((e=>Se(e.type)));t.push({label:a,options:r})})),t}()),onChange:(e,a)=>{const r=function(e,t,a,r){var s;const n=[...null!==(s=e.select)&&void 0!==s?s:[]];return n[t]=[...n[t]],n[t][a]=Object.assign({},n[t][a],{params:r}),Object.assign({},e,{select:n})}(m,t,e,a);S(r)},onAddNewPart:e=>{S(function(e,t,a){const r=(0,s.cloneDeep)(e),n=new Q(r);return n.addSelectPart(n.selectModels[a],t),n.target}(m,e,t))},onRemovePart:e=>{S(function(e,t,a){const r=(0,s.cloneDeep)(e),n=new Q(r),i=n.selectModels[a];return n.removeSelectPart(i,i[t]),n.target}(m,e,t))}})},t))),(0,f.jsx)(i.SegmentSection,{label:"GROUP BY",fill:!0,children:(0,f.jsx)(Ne,{parts:b,getNewPartOptions:()=>async function(e,t){const a=await t(),r=Object.assign({},e),s=new Q(r),n=[];return s.hasFill()||n.push(Se("fill(null)")),s.hasGroupByTime()||n.push(Se("time($interval)")),a.forEach((e=>{n.push(Se(`tag(${e})`))})),n}(m,x),onChange:(e,t)=>{const a=function(e,t,a){var r;const s=[...null!==(r=e.groupBy)&&void 0!==r?r:[]];return s[t]=Object.assign({},s[t],{params:a}),Object.assign({},e,{groupBy:s})}(m,e,t);S(a)},onAddNewPart:e=>{S(function(e,t){const a=(0,s.cloneDeep)(e),r=new Q(a);return r.addGroupBy(t),r.target}(m,e))},onRemovePart:e=>{S(function(e,t){const a=(0,s.cloneDeep)(e),r=new Q(a);return r.removeGroupByPart(r.groupByParts[t],t),r.target}(m,e))}})}),(0,f.jsxs)(i.SegmentSection,{label:"TIMEZONE",fill:!0,children:[(0,f.jsx)(we,{placeholder:"(optional)",value:m.tz,onChange:e=>{S(Object.assign({},m,{tz:e}))}}),(0,f.jsx)(i.InlineLabel,{htmlFor:d,width:"auto",className:c.inlineLabel,children:"ORDER BY TIME"}),(0,f.jsx)(Te,{inputId:d,value:"DESC"===m.orderByTime?"DESC":"ASC",onChange:e=>{S(Object.assign({},m,{orderByTime:e}))}})]}),(0,f.jsxs)(i.SegmentSection,{label:"LIMIT",fill:!0,children:[(0,f.jsx)(we,{placeholder:"(optional)",value:null===(a=m.limit)||void 0===a?void 0:a.toString(),onChange:e=>{S(Object.assign({},m,{limit:e}))}}),(0,f.jsx)(i.InlineLabel,{width:"auto",className:c.inlineLabel,children:"SLIMIT"}),(0,f.jsx)(we,{placeholder:"(optional)",value:null===(r=m.slimit)||void 0===r?void 0:r.toString(),onChange:e=>{S(Object.assign({},m,{slimit:e}))}})]}),(0,f.jsxs)(i.SegmentSection,{htmlFor:u,label:"FORMAT AS",fill:!0,children:[(0,f.jsx)(ue,{inputId:u,format:null!==(o=m.resultFormat)&&void 0!==o?o:Z,onChange:e=>{S(Object.assign({},m,{resultFormat:e}))}}),"table"!==m.resultFormat&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(i.InlineLabel,{width:"auto",className:c.inlineLabel,children:"ALIAS"}),(0,f.jsx)(we,{isWide:!0,placeholder:"Naming pattern",value:m.alias,onChange:e=>{S(Object.assign({},m,{alias:e}))}})]})]})]})};function He(e){return{inlineLabel:E.css`
- color: ${e.colors.primary.text};
- `}}var Ke;class Ye extends n.PureComponent{constructor(){var e,t,a;super(...arguments),a=()=>{},(t="onRefresh")in(e=this)?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a}render(){let{query:e,datasource:t,onChange:a}=this.props;return t.isFlux?(0,f.jsx)(K,{datasource:t,query:{refId:"A",query:e},onRunQuery:this.onRefresh,onChange:e=>a(e.query)}):(0,f.jsxs)("div",{className:"gf-form-inline",children:[Ke||(Ke=(0,f.jsx)(i.InlineFormLabel,{width:10,children:"Query"})),(0,f.jsx)("div",{className:"gf-form-inline gf-form--grow",children:(0,f.jsx)(i.TextArea,{defaultValue:e||"",placeholder:"metric name or tags query",rows:1,className:"gf-form-input",onBlur:e=>a(e.currentTarget.value)})})]})}}var Je=a(2937),Ze=a(58788),Xe=a(26702),et=a(10010),tt=a(76913),at=a(34110),rt=a(78837),st=a(7166),nt=a(65660);function it(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class ot{constructor(e){it(this,"refId",void 0),it(this,"series",void 0),it(this,"alias",void 0),it(this,"annotation",void 0),it(this,"meta",void 0),this.series=e.series,this.alias=e.alias,this.annotation=e.annotation,this.meta=e.meta,this.refId=e.refId}getTimeSeries(){const e=[];let t,a;return 0===this.series.length||(0,s.each)(this.series,(r=>{const n=r.columns.length,i=(0,s.map)(r.tags,((e,t)=>t+": "+e));for(a=1;a<n;a++){let s=r.name;const n=r.columns[a];"value"!==n&&(s=s+"."+n),this.alias?s=this._getSeriesName(r,a):r.tags&&(s=s+" {"+i.join(", ")+"}");const o=[];if(r.values)for(t=0;t<r.values.length;t++)o[t]=[r.values[t][a],r.values[t][0]];e.push({title:s,target:s,datapoints:o,tags:r.tags,meta:this.meta,refId:this.refId})}})),e}_getSeriesName(e,t){const a=e.name.split(".");return this.alias.replace(/\$(\w+)|\[\[([\s\S]+?)\]\]/g,((r,s,n)=>{const i=s||n,o=parseInt(i,10);if("m"===i||"measurement"===i)return e.name;if("col"===i)return e.columns[t];var l;if(!isNaN(o))return null!==(l=a[o])&&void 0!==l?l:r;if(0!==i.indexOf("tag_"))return r;const u=i.replace("tag_","");return e.tags?e.tags[u]:r}))}getAnnotations(){const e=[];return(0,s.each)(this.series,(t=>{let a=null,r=null,n=null;const i=[];let o=null;(0,s.each)(t.columns,((e,t)=>{"time"!==e?"sequence_number"!==e&&(e!==this.annotation.titleColumn?(0,s.includes)((this.annotation.tagsColumn||"").replace(" ","").split(","),e)?i.push(t):e!==this.annotation.textColumn?e!==this.annotation.timeEndColumn?a||o===t||(a=t):n=t:o=t:a=t):r=t})),(0,s.each)(t.values,(t=>{const l={annotation:this.annotation,time:+new Date(t[r]),title:t[a],timeEnd:t[n],tags:(0,s.flatten)(i.filter((e=>t[e])).map((e=>t[e].split(",")))),text:t[o]};e.push(l)}))})),e}getTable(){const e=new nt.Z;let t,a;return e.refId=this.refId,e.meta=this.meta,0===this.series.length||(0,s.each)(this.series,((n,i)=>{if(0===i){const t=n.columns[0],i="time"===t?{text:"Time",type:r.FieldType.time}:{text:t};for(e.columns.push(i),(0,s.each)((0,s.keys)(n.tags),(t=>{e.columns.push({text:t})})),a=1;a<n.columns.length;a++)e.columns.push({text:n.columns[a]})}if(n.values)for(t=0;t<n.values.length;t++){const r=n.values[t],s=[r[0]];if(n.tags)for(const e in n.tags)n.tags.hasOwnProperty(e)&&s.push(n.tags[e]);for(a=1;a<r.length;a++)s.push(r[a]);e.rows.push(s)}})),e}}class lt{parse(e,t){if(null==t||!t.results||0===t.results.length)return[];const a=t.results[0];if(!a.series)return[];const r=e.toLowerCase(),n=r.indexOf("show field keys")>=0||r.indexOf("show retention policies")>=0,i=new Set;return(0,s.each)(a.series,(e=>{(0,s.each)(e.values,(e=>{(0,s.isArray)(e)?n?ct(i,e[0]):void 0!==e[1]?ct(i,e[1]):ct(i,e[0]):ct(i,e)}))})),Array.from(i).map((e=>({text:e})))}getTable(e,t,a){let n=new nt.Z;var i;if(e.length>0)if(n.meta=Object.assign({},a,{executedQueryString:null===(i=e[0].meta)||void 0===i?void 0:i.executedQueryString}),n.refId=t.refId,n=function(e,t,a){const s=function(e){var t;let a=[];null===(t=e.select)||void 0===t||t.forEach((e=>{const t=e.filter((e=>"field"!==e.type));t.length>0?a.push(t[0].type):e[0]&&e[0].params&&e[0].params[0]&&a.push(e[0].params[0].toString())}));let r=[];return a.forEach((e=>{r.push(dt(e,e,r,0))})),r}(a);e[0].fields.forEach((e=>{"time"===e.name?t.columns.push({text:"Time",type:r.FieldType.time}):"value"===e.name&&e.labels&&Object.keys(e.labels).forEach((e=>{t.columns.push({text:e})}))})),"metricFindQuery"===e[0].refId&&e.forEach((e=>{e.name&&t.columns.push({text:e.name})}));for(let e=0;e<s.length;e++)t.columns.push({text:s[e]});return t}(e,n,t),e[0].fields[1]&&e[0].fields[1].labels){let t=(0,s.groupBy)(e,(e=>e.fields[1].labels?Object.values(e.fields[1].labels):null));const a=Object.keys(t);t=Object.values(t);for(let e=0;e<t.length;e++)n=ut(t[e],n,[...a[e].split(",")])}else n=ut(e,n,[]);return n}async transformAnnotationResponse(e,t,a){const r=(0,z.toDataQueryResponse)(t,[a]);if(r){const t=this.getTable(r.data,a,{}),n=[];let i=null,o=null,l=null;const u=[];let d=null;return(0,s.each)(t.columns,((t,a)=>{"time"!==t.text.toLowerCase()?t.text!==e.annotation.titleColumn?!function(e,t){const a=(t||"").replace(" ","").split(",");for(var r of a)if(e.includes(r))return!0;return!1}(t.text,e.annotation.tagsColumn)?t.text.includes(e.annotation.textColumn)?d=a:t.text!==e.annotation.timeEndColumn?i||d===a||(i=a):l=a:u.push(a):i=a:o=a})),(0,s.each)(t.rows,(t=>{const a={annotation:e.annotation,time:+new Date(t[o]),title:t[i],timeEnd:t[l],tags:(0,s.flatten)(u.filter((e=>t[e])).map((e=>t[e].split(",")))),text:t[d]};n.push(a)})),n}return[]}}function ut(e,t,a){const r=e[0].fields[0].values.toArray();for(let s=0;s<r.length;s++){const n=r[s],i=e.map((e=>e.fields[1]?e.fields[1].values.toArray()[s]:null));i.indexOf(null)<0&&t.rows.push([n,...a,...i])}return t}function dt(e,t,a,r){return a.indexOf(t)>-1?dt(e,e+"_"+ ++r,a,r):t}function ct(e,t){e.add(t.toString())}const mt=["__interval","__interval_ms"];function pt(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function ht(e){const t=e.find((e=>null!==e));if(void 0===t)return r.FieldType.number;const a=typeof t;switch(a){case"string":return r.FieldType.string;case"boolean":return r.FieldType.boolean;case"number":return r.FieldType.number;default:throw new Error(`InfluxQL: invalid value type ${a}`)}}function gt(e){const t=[],a=[],s=e.datapoints;for(const e of s)a.push(e[0]),t.push(e[1]);const n=[{name:r.TIME_SERIES_TIME_FIELD_NAME,type:r.FieldType.time,config:{},values:new r.ArrayVector(t)},{name:r.TIME_SERIES_VALUE_FIELD_NAME,type:ht(a),config:{displayNameFromDS:e.title},values:new r.ArrayVector(a),labels:e.tags}];return{name:e.target,refId:e.refId,meta:e.meta,fields:n,length:a.length}}class ft extends z.DataSourceWithBackend{constructor(e){var t,a,r;let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(0,st.J)();super(e),pt(this,"type",void 0),pt(this,"urls",void 0),pt(this,"username",void 0),pt(this,"password",void 0),pt(this,"name",void 0),pt(this,"database",void 0),pt(this,"basicAuth",void 0),pt(this,"withCredentials",void 0),pt(this,"access",void 0),pt(this,"interval",void 0),pt(this,"responseParser",void 0),pt(this,"httpMode",void 0),pt(this,"isFlux",void 0),this.templateSrv=s,this.type="influxdb",this.urls=(null!==(t=e.url)&&void 0!==t?t:"").split(",").map((e=>e.trim())),this.username=null!==(a=e.username)&&void 0!==a?a:"",this.password=null!==(r=e.password)&&void 0!==r?r:"",this.name=e.name,this.database=e.database,this.basicAuth=e.basicAuth,this.withCredentials=e.withCredentials,this.access=e.access;const n=e.jsonData||{};this.interval=n.timeInterval,this.httpMode=n.httpMode||"GET",this.responseParser=new lt,this.isFlux=n.version===o.Flux,this.isFlux&&(this.annotations={QueryEditor:K})}query(e){const t=Object.assign({},e,{targets:e.targets.filter((e=>!0!==e.hide))});return this.isFlux?super.query(t):this.isMigrationToggleOnAndIsAccessProxy()?super.query(t).pipe((0,et.U)((e=>{if(e.error)throw{message:"InfluxDB Error: "+e.error.message,res:e};const a=[],r=(0,s.groupBy)(e.data,(e=>e.refId));return Object.keys(r).length>0&&t.targets.forEach((e=>{var t;const s=null!==(t=r[e.refId])&&void 0!==t?t:[];switch(e.resultFormat){case"logs":case"table":a.push(this.responseParser.getTable(s,e,{preferredVisualisationType:e.resultFormat}));break;default:for(let e=0;e<s.length;e++)a.push(s[e])}})),{data:a}}))):this.classicQuery(e)}getQueryDisplayText(e){return this.isFlux?e.query:new Q(e).render(!1)}filterQuery(e){return!this.isFlux||!!e.query}applyTemplateVariables(e,t){const a=function(e,t){if(null==e)return{};var a,r,s={},n=Object.keys(e);for(r=0;r<n.length;r++)a=n[r],t.indexOf(a)>=0||(s[a]=e[a]);return s}(t,mt);var r;return this.isFlux?Object.assign({},e,{query:this.templateSrv.replace(null!==(r=e.query)&&void 0!==r?r:"",a)}):(rt.ZP.featureToggles.influxdbBackendMigration&&"proxy"===this.access&&(e=this.applyVariables(e,t,a)),e)}classicQuery(e){let t=this.getTimeFilter(e);const a=e.scopedVars,r=(0,s.cloneDeep)(e.targets),n=[];let i,o,l=(0,s.map)(r,(e=>e.hide?"":(n.push(e),a.interval=a.__interval,new Q(e,this.templateSrv,a).render(!0)))).reduce(((e,t)=>(""!==t&&(e+=";"+t),e)));if(""===l)return(0,Je.of)({data:[]});const u=this.templateSrv.getAdhocFilters(this.name);if(u.length>0){t+=" AND "+new Q({refId:"A"},this.templateSrv,a).renderAdhocFilters(u)}return a.timeFilter={value:t},l=this.templateSrv.replace(l,a),this._seriesQuery(l,e).pipe((0,et.U)((t=>{if(!t||!t.results)return{data:[]};const a=[];for(i=0;i<t.results.length;i++){const r=t.results[i];if(!r||!r.series)continue;const s=n[i];let l=s.alias;l&&(l=this.templateSrv.replace(s.alias,e.scopedVars));const u={executedQueryString:t.executedQueryString},d=new ot({refId:s.refId,series:t.results[i].series,alias:l,meta:u});switch(s.resultFormat){case"logs":u.preferredVisualisationType="logs";case"table":a.push(d.getTable());break;default:{const e=d.getTimeSeries();for(o=0;o<e.length;o++)a.push(gt(e[o]));break}}}return{data:a}})))}async annotationQuery(e){if(this.isFlux)return Promise.reject({message:"Flux requires the standard annotation query"});if(!e.annotation.query)return Promise.reject({message:"Query missing in annotation definition"});if(rt.ZP.featureToggles.influxdbBackendMigration&&"proxy"===this.access){var t;const a={refId:"metricFindQuery",datasource:this.getRef(),query:this.templateSrv.replace(null!==(t=e.annotation.query)&&void 0!==t?t:"",void 0,"regex"),rawQuery:!0};return(0,Ze.n)((0,z.getBackendSrv)().fetch({url:"/api/ds/query",method:"POST",data:{from:e.range.from.valueOf().toString(),to:e.range.to.valueOf().toString(),queries:[a]},requestId:e.annotation.name}).pipe((0,et.U)((async t=>await this.responseParser.transformAnnotationResponse(e,t,a)))))}const a=this.getTimeFilter({rangeRaw:e.rangeRaw,timezone:e.dashboard.timezone});let r=e.annotation.query.replace("$timeFilter",a);return r=this.templateSrv.replace(r,void 0,"regex"),(0,Ze.n)(this._seriesQuery(r,e)).then((t=>{if(!t||!t.results||!t.results[0])throw{message:"No results in response from InfluxDB"};return new ot({series:t.results[0].series,annotation:e.annotation}).getAnnotations()}))}targetContainsTemplate(e){const t=this.isFlux?e.query:V(e);return this.templateSrv.containsTemplate(t)}interpolateVariablesInQueries(e,t){return e&&0!==e.length?e.map((e=>{var a;return this.isFlux?Object.assign({},e,{datasource:this.getRef(),query:this.templateSrv.replace(null!==(a=e.query)&&void 0!==a?a:"",t,"regex")}):Object.assign({},e,{datasource:this.getRef()},this.applyVariables(e,t,t))})):[]}applyVariables(e,t,a){var r,s,n,i,o,l,u,d,c;const m=Object.assign({},e);return e.groupBy&&(m.groupBy=e.groupBy.map((e=>{var t;return Object.assign({},e,{params:null===(t=e.params)||void 0===t?void 0:t.map((e=>this.templateSrv.replace(e.toString(),void 0,"regex")))})}))),e.select&&(m.select=e.select.map((e=>e.map((e=>{var t;return Object.assign({},e,{params:null===(t=e.params)||void 0===t?void 0:t.map((e=>this.templateSrv.replace(e.toString(),void 0,"regex")))})}))))),e.tags&&(m.tags=e.tags.map((e=>Object.assign({},e,{value:this.templateSrv.replace(e.value,void 0,"regex")})))),Object.assign({},m,{query:this.templateSrv.replace(null!==(r=e.query)&&void 0!==r?r:"",a,"regex"),alias:this.templateSrv.replace(null!==(s=e.alias)&&void 0!==s?s:"",t),limit:this.templateSrv.replace(null!==(n=null===(i=e.limit)||void 0===i?void 0:i.toString())&&void 0!==n?n:"",t,"regex"),measurement:this.templateSrv.replace(null!==(o=e.measurement)&&void 0!==o?o:"",t,"regex"),policy:this.templateSrv.replace(null!==(l=e.policy)&&void 0!==l?l:"",t,"regex"),slimit:this.templateSrv.replace(null!==(u=null===(d=e.slimit)||void 0===d?void 0:d.toString())&&void 0!==u?u:"",t,"regex"),tz:this.templateSrv.replace(null!==(c=e.tz)&&void 0!==c?c:"",t)})}async metricFindQuery(e,t){if(this.isFlux||this.isMigrationToggleOnAndIsAccessProxy()){const a={refId:"metricFindQuery",query:e,rawQuery:!0};return(0,Ze.n)(super.query(Object.assign({},t,{targets:[a]}))).then((e=>{var t;return null!==(t=e.data)&&void 0!==t&&t.length?(0,z.frameToMetricFindValue)(e.data[0]):[]}))}const a=this.templateSrv.replace(e,void 0,"regex");return(0,Ze.n)(this._seriesQuery(a,t)).then((t=>this.responseParser.parse(e,t)))}getTagKeys(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=new re({measurement:e.measurement||"",tags:[]},this.database).buildExploreQuery("TAG_KEYS");return this.metricFindQuery(t,e)}getTagValues(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=new re({measurement:e.measurement||"",tags:[]},this.database).buildExploreQuery("TAG_VALUES",e.key);return this.metricFindQuery(t,e)}_seriesQuery(e,t){if(!e)return(0,Je.of)({results:[]});if(t&&t.range){const a=this.getTimeFilter({rangeRaw:t.range,timezone:t.timezone});e=e.replace("$timeFilter",a)}return this._influxRequest(this.httpMode,"/query",{q:e,epoch:"ms"},t)}serializeParams(e){return e?(0,s.reduce)(e,((e,t,a)=>(null==t||e.push(encodeURIComponent(a)+"="+encodeURIComponent(t)),e)),[]).join("&"):""}testDatasource(){if(this.isFlux){const e={targets:[{refId:"test",query:"buckets()"}],requestId:`${this.id}-health-${(0,at.Z)()}`,dashboardId:0,panelId:0,interval:"1m",intervalMs:6e4,maxDataPoints:423,range:{from:(0,r.dateTime)(1e3),to:(0,r.dateTime)(2e3)}};return(0,Ze.n)(super.query(e)).then((e=>{if(!e||!e.data||e.state!==r.LoadingState.Done)return console.error("InfluxDB Error",e),{status:"error",message:"Error reading InfluxDB"};const t=e.data[0];return t&&t.length?{status:"success",message:`${t.length} buckets found`}:(console.error("InfluxDB Error",e),{status:"error",message:"Error reading buckets"})})).catch((e=>(console.error("InfluxDB Error",e),{status:"error",message:e.message})))}if(this.isMigrationToggleOnAndIsAccessProxy()){const e={refId:"metricFindQuery",query:"SHOW TAG KEYS",rawQuery:!0};return(0,Ze.n)(super.query({targets:[e]})).then((e=>{var t;return e&&e.data&&e.state===r.LoadingState.Done?null!==(t=e.data)&&void 0!==t&&t.length?{status:"success",message:"Data source is working."}:{status:"error",message:"Successfully connected to InfluxDB, but no tags found."}:{status:"error",message:"Error reading InfluxDB."}})).catch((e=>({status:"error",message:e.message})))}const e=new re({measurement:"",tags:[]},this.database).buildExploreQuery("RETENTION POLICIES");return(0,Ze.n)(this._seriesQuery(e)).then((e=>{const t=(0,s.get)(e,"results[0].error");return t?{status:"error",message:t}:{status:"success",message:"Data source is working"}})).catch((e=>({status:"error",message:e.message})))}_influxRequest(e,t,a,r){const n=this.urls.shift();this.urls.push(n);const i={};this.username&&(i.u=this.username,i.p=this.password),r&&r.database?i.db=r.database:this.database&&(i.db=this.database);const{q:o}=a;"POST"===e&&(0,s.has)(a,"q")?((0,s.extend)(i,(0,s.omit)(a,["q"])),a=this.serializeParams((0,s.pick)(a,["q"]))):"GET"!==e&&"POST"!==e||((0,s.extend)(i,a),a=null);const l={method:e,url:n+t,params:i,data:a,precision:"ms",inspect:{type:"influxdb"},paramSerializer:this.serializeParams};return l.headers=l.headers||{},(this.basicAuth||this.withCredentials)&&(l.withCredentials=!0),this.basicAuth&&(l.headers.Authorization=this.basicAuth),"POST"===e&&(l.headers["Content-type"]="application/x-www-form-urlencoded"),(0,z.getBackendSrv)().fetch(l).pipe((0,et.U)((e=>{const{data:t}=e;if(t&&(t.executedQueryString=o,t.results)){const a=e.data.results.filter((e=>e.error));if(a.length>0)throw{message:"InfluxDB Error: "+a[0].error,data:t}}return t})),(0,tt.K)((e=>e.cancelled?(0,Je.of)(e):(0,Xe._)(this.handleErrors(e)))))}handleErrors(e){const t={message:e&&e.status||e&&e.message||"Unknown error during query transaction. Please check JS console logs."};return(Number.isInteger(e.status)&&0!==e.status||e.status>=300)&&(e.data&&e.data.error?(t.message="InfluxDB Error: "+e.data.error,t.data=e.data,t.config=e.config):(t.message="Network Error: "+e.statusText+"("+e.status+")",t.data=e.data,t.config=e.config)),t}getTimeFilter(e){return"time >= "+this.getInfluxTime(e.rangeRaw.from,!1,e.timezone)+" and time <= "+this.getInfluxTime(e.rangeRaw.to,!0,e.timezone)}getInfluxTime(e,t,a){if((0,s.isString)(e)){if("now"===e)return"now()";const s=/^now-(\d+)([dhms])$/.exec(e);if(s){return"now() - "+parseInt(s[1],10)+s[2]}e=r.dateMath.parse(e,t,a)}return e.valueOf()+"ms"}isMigrationToggleOnAndIsAccessProxy(){return rt.ZP.featureToggles.influxdbBackendMigration&&"proxy"===this.access}}class yt{}var vt,xt,bt;bt="partials/annotations.editor.html",(xt="templateUrl")in(vt=yt)?Object.defineProperty(vt,xt,{value:bt,enumerable:!0,configurable:!0,writable:!0}):vt[xt]=bt;const St=new r.DataSourcePlugin(ft).setConfigEditor(w).setQueryEditor((e=>{var t;let{query:a,onChange:r,onRunQuery:s,datasource:n,range:i,data:o}=e;return n.isFlux?(0,f.jsx)("div",{className:"gf-form-query-content",children:(0,f.jsx)(K,{query:a,onChange:r,onRunQuery:s,datasource:n})}):(0,f.jsxs)("div",{className:(0,E.css)({display:"flex"}),children:[(0,f.jsx)("div",{className:(0,E.css)({flexGrow:1}),children:a.rawQuery?(0,f.jsx)(ae,{query:a,onChange:r,onRunQuery:s}):(0,f.jsx)(We,{query:a,onChange:r,onRunQuery:s,datasource:n})}),(0,f.jsx)(Y,{isRaw:null!==(t=a.rawQuery)&&void 0!==t&&t,onChange:e=>{r(Object.assign({},a,{query:V(a),rawQuery:e})),s()}})]})})).setAnnotationQueryCtrl(yt).setVariableQueryEditor(Ye).setQueryEditorHelp(I)},20002:(e,t,a)=>{a.d(t,{Z:()=>s});var r=a(68404);function s(e){var t=(0,r.useRef)();return(0,r.useEffect)((function(){t.current=e})),t.current}}}]);
- //# sourceMappingURL=influxdbPlugin.b76d815b7be79e3aa808.js.map
|