(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[6303],{362:(ae,G,n)=>{"use strict";n.d(G,{ZP:()=>Qe});var p=n(52423),A=n(57706),d=n(68404),g=n(16911),H=n(40400),U=n(41818),L=n(13193),O=n(67660),w=n(39904),$=n(31403),R=n(72648),B=n(59796);function N(x){return typeof x=="object"&&x!==null&&"isCanceled"in x}const re=x=>{let c=!1;return{promise:new Promise((m,u)=>{const E={isCanceled:!0};x.then(T=>c?u(E):m(T)),x.catch(T=>u(c?E:T))}),cancel(){c=!0}}};var k=n(51649),ve=n(75478),q=n(7804),J=n(61744),se=n(52081),ne=n(64353),xe=n(46967),ye=n(85951);const pe="{}",Z="__name__",oe=25;function _(x){let c="";const v=[];for(const m of x)if((m.name===Z||m.selected)&&m.values&&m.values.length>0){const u=m.values.filter(E=>E.selected).map(E=>E.name);u.length>1?v.push(`${m.name}=~"${u.map(k.tU).join("|")}"`):u.length===1&&(m.name===Z?c=u[0]:v.push(`${m.name}="${(0,k.U9)(u[0])}"`))}return[c,"{",v.join(","),"}"].join("")}function De(x,c,v){return x.map(m=>{const u=c[m.name];if(u){let E;if(m.name===v&&m.values)E=m.values;else{const T=new Set(m.values?.filter(f=>f.selected).map(f=>f.name)||[]);E=u.map(f=>({name:f,selected:T.has(f)}))}return{...m,loading:!1,values:E,hidden:!u,facets:E.length}}return{...m,loading:!1,hidden:!u,values:void 0,facets:0}})}const Le=(0,q.B)(x=>({wrapper:p.css`
    background-color: ${x.colors.background.secondary};
    padding: ${x.spacing(1)};
    width: 100%;
  `,list:p.css`
    margin-top: ${x.spacing(1)};
    display: flex;
    flex-wrap: wrap;
    max-height: 200px;
    overflow: auto;
    align-content: flex-start;
  `,section:p.css`
    & + & {
      margin: ${x.spacing(2)} 0;
    }
    position: relative;
  `,selector:p.css`
    font-family: ${x.typography.fontFamilyMonospace};
    margin-bottom: ${x.spacing(1)};
  `,status:p.css`
    padding: ${x.spacing(.5)};
    color: ${x.colors.text.secondary};
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    /* using absolute positioning because flex interferes with ellipsis */
    position: absolute;
    width: 50%;
    right: 0;
    text-align: right;
    transition: opacity 100ms linear;
    opacity: 0;
  `,statusShowing:p.css`
    opacity: 1;
  `,error:p.css`
    color: ${x.colors.error.main};
  `,valueList:p.css`
    margin-right: ${x.spacing(1)};
    resize: horizontal;
  `,valueListWrapper:p.css`
    border-left: 1px solid ${x.colors.border.medium};
    margin: ${x.spacing(1)} 0;
    padding: ${x.spacing(1)} 0 ${x.spacing(1)} ${x.spacing(1)};
  `,valueListArea:p.css`
    display: flex;
    flex-wrap: wrap;
    margin-top: ${x.spacing(1)};
  `,valueTitle:p.css`
    margin-left: -${x.spacing(.5)};
    margin-bottom: ${x.spacing(1)};
  `,validationStatus:p.css`
    padding: ${x.spacing(.5)};
    margin-bottom: ${x.spacing(1)};
    color: ${x.colors.text.maxContrast};
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  `}));class Te extends d.Component{constructor(){super(...arguments),this.valueListsRef=d.createRef(),this.state={labels:[],labelSearchTerm:"",metricSearchTerm:"",status:"Ready",error:"",validationStatus:"",valueSearchTerm:""},this.onChangeLabelSearch=c=>{this.setState({labelSearchTerm:c.target.value})},this.onChangeMetricSearch=c=>{this.setState({metricSearchTerm:c.target.value})},this.onChangeValueSearch=c=>{this.setState({valueSearchTerm:c.target.value})},this.onClickRunQuery=()=>{const c=_(this.state.labels);this.props.onChange(c)},this.onClickRunRateQuery=()=>{const v=`rate(${_(this.state.labels)}[$__interval])`;this.props.onChange(v)},this.onClickClear=()=>{this.setState(c=>({labels:c.labels.map(m=>({...m,values:void 0,selected:!1,loading:!1,hidden:!1,facets:void 0})),labelSearchTerm:"",metricSearchTerm:"",status:"",error:"",validationStatus:"",valueSearchTerm:""})),this.props.deleteLastUsedLabels(),this.fetchValues(Z,pe)},this.onClickLabel=(c,v,m)=>{const u=this.state.labels.find(f=>f.name===c);if(!u)return;const E=!u.selected;let T={selected:E};if(u.values&&!E){const f=u.values.map(D=>({...D,selected:!1}));T={...T,facets:0,values:f}}this.setState({labelSearchTerm:""}),this.updateLabelState(c,T,"",()=>this.doFacettingForLabel(c))},this.onClickValue=(c,v,m)=>{const u=this.state.labels.find(T=>T.name===c);if(!u||!u.values)return;this.setState({labelSearchTerm:""});const E=u.values.map(T=>({...T,selected:T.name===v?!T.selected:T.selected}));this.updateLabelState(c,{values:E},"",()=>this.doFacetting(c))},this.onClickMetric=(c,v,m)=>{const u=this.state.labels.find(f=>f.name===c);if(!u||!u.values)return;this.setState({metricSearchTerm:""});const E=u.values.map(f=>({...f,selected:f.name===v||f.selected?!f.selected:f.selected})),T=E.some(f=>f.selected);this.updateLabelState(c,{selected:T,values:E},"",()=>this.doFacetting(c))},this.onClickValidate=()=>{const c=_(this.state.labels);this.validateSelector(c)},this.doFacetting=c=>{const v=_(this.state.labels);if(v===pe){const m=this.state.labels.map(u=>({...u,facets:0,values:void 0,hidden:!1}));this.setState({labels:m},()=>{this.state.labels.forEach(u=>(u.selected||u.name===Z)&&this.fetchValues(u.name,v))})}else this.fetchSeries(v,c)}}updateLabelState(c,v,m="",u){this.setState(E=>{const T=E.labels.map(D=>D.name===c?{...D,...v}:D),f=m?"":E.error;return{labels:T,status:m,error:f,validationStatus:""}},u)}componentDidMount(){const{languageProvider:c,lastUsedLabels:v}=this.props;if(c){const m=v;c.start().then(()=>{let u=c.getLabelKeys();this.fetchValues(Z,pe);const E=u.map((T,f,D)=>({name:T,selected:m.includes(T),loading:!1}));this.setState({labels:E},()=>{this.state.labels.forEach(T=>{T.selected&&this.fetchValues(T.name,pe)})})})}}doFacettingForLabel(c){const v=this.state.labels.find(u=>u.name===c);if(!v)return;const m=this.state.labels.filter(u=>u.selected).map(u=>u.name);this.props.storeLastUsedLabels(m),v.selected?v.values||this.fetchValues(c,_(this.state.labels)):this.doFacetting()}async fetchValues(c,v){const{languageProvider:m}=this.props;this.updateLabelState(c,{loading:!0},`Fetching values for ${c}`);try{let u=await m.getLabelValues(c);if(v!==_(this.state.labels)){this.updateLabelState(c,{loading:!1});return}const E=[],{metricsMetadata:T}=m;for(const f of u){const D={name:f};if(c===Z&&T){const P=T[f];P&&(D.details=`(${P.type}) ${P.help}`)}E.push(D)}this.updateLabelState(c,{values:E,loading:!1})}catch(u){console.error(u)}}async fetchSeries(c,v){const{languageProvider:m}=this.props;v&&this.updateLabelState(v,{loading:!0},`Facetting labels for ${c}`);try{const u=await m.fetchSeriesLabels(c,!0);if(c!==_(this.state.labels)){v&&this.updateLabelState(v,{loading:!1});return}if(Object.keys(u).length===0){this.setState({error:`Empty results, no matching label for ${c}`});return}const E=De(this.state.labels,u,v);this.setState({labels:E,error:""}),v&&this.updateLabelState(v,{loading:!1})}catch(u){console.error(u)}}async validateSelector(c){const{languageProvider:v}=this.props;this.setState({validationStatus:`Validating selector ${c}`,error:""});const m=await v.fetchSeries(c);this.setState({validationStatus:`Selector is valid (${m.length} series found)`})}render(){const{theme:c}=this.props,{labels:v,labelSearchTerm:m,metricSearchTerm:u,status:E,error:T,validationStatus:f,valueSearchTerm:D}=this.state,P=Le(c);if(v.length===0)return d.createElement("div",{className:P.wrapper},d.createElement(J.u,{text:"Loading labels..."}));let W=v.find(M=>M.name===Z);W&&u&&(W={...W,values:W.values?.filter(M=>M.selected||M.name.includes(u))});let ie=v.filter(M=>!M.hidden&&M.name!==Z);m&&(ie=ie.filter(M=>M.selected||M.name.includes(m)));let fe=ie.filter(M=>M.selected&&M.values);D&&(fe=fe.map(M=>({...M,values:M.values?.filter(ee=>ee.selected||ee.name.includes(D))})));const Ee=_(this.state.labels),ue=Ee===pe,ce=W?.values?.length||0;return d.createElement("div",{className:P.wrapper},d.createElement(se.Lh,{align:"flex-start",spacing:"lg"},d.createElement("div",null,d.createElement("div",{className:P.section},d.createElement(ne._,{description:"Once a metric is selected only possible labels are shown."},"1. Select a metric"),d.createElement("div",null,d.createElement(xe.I,{onChange:this.onChangeMetricSearch,"aria-label":"Filter expression for metric",value:u})),d.createElement("div",{role:"list",className:P.valueListWrapper},d.createElement(ve.t7,{height:Math.min(450,ce*oe),itemCount:ce,itemSize:oe,itemKey:M=>W.values[M].name,width:300,className:P.valueList},({index:M,style:ee})=>{const de=W?.values?.[M];return de?d.createElement("div",{style:ee},d.createElement(ye._,{name:W.name,value:de?.name,title:de.details,active:de?.selected,onClick:this.onClickMetric,searchTerm:u})):null})))),d.createElement("div",null,d.createElement("div",{className:P.section},d.createElement(ne._,{description:"Once label values are selected, only possible label combinations are shown."},"2. Select labels to search in"),d.createElement("div",null,d.createElement(xe.I,{onChange:this.onChangeLabelSearch,"aria-label":"Filter expression for label",value:m})),d.createElement("div",{className:P.list,style:{height:120}},ie.map(M=>d.createElement(ye._,{key:M.name,name:M.name,loading:M.loading,active:M.selected,hidden:M.hidden,facets:M.facets,onClick:this.onClickLabel,searchTerm:m})))),d.createElement("div",{className:P.section},d.createElement(ne._,{description:"Use the search field to find values across selected labels."},"3. Select (multiple) values for your labels"),d.createElement("div",null,d.createElement(xe.I,{onChange:this.onChangeValueSearch,"aria-label":"Filter expression for label values",value:D})),d.createElement("div",{className:P.valueListArea,ref:this.valueListsRef},fe.map(M=>d.createElement("div",{role:"list",key:M.name,"aria-label":`Values for ${M.name}`,className:P.valueListWrapper},d.createElement("div",{className:P.valueTitle},d.createElement(ye._,{name:M.name,loading:M.loading,active:M.selected,hidden:M.hidden,facets:M.facets||M.values?.length,onClick:this.onClickLabel})),d.createElement(ve.t7,{height:Math.min(200,oe*(M.values?.length||0)),itemCount:M.values?.length||0,itemSize:28,itemKey:ee=>M.values[ee].name,width:200,className:P.valueList},({index:ee,style:de})=>{const Ie=M.values?.[ee];return Ie?d.createElement("div",{style:de},d.createElement(ye._,{name:M.name,value:Ie?.name,active:Ie?.selected,onClick:this.onClickValue,searchTerm:D})):null}))))))),d.createElement("div",{className:P.section},d.createElement(ne._,null,"4. Resulting selector"),d.createElement("div",{"aria-label":"selector",className:P.selector},Ee),f&&d.createElement("div",{className:P.validationStatus},f),d.createElement(se.Lh,null,d.createElement($.zx,{"aria-label":"Use selector for query button",disabled:ue,onClick:this.onClickRunQuery},"Use query"),d.createElement($.zx,{"aria-label":"Use selector as metrics button",variant:"secondary",disabled:ue,onClick:this.onClickRunRateQuery},"Use as rate query"),d.createElement($.zx,{"aria-label":"Validate submit button",variant:"secondary",disabled:ue,onClick:this.onClickValidate},"Validate selector"),d.createElement($.zx,{"aria-label":"Selector clear button",variant:"secondary",onClick:this.onClickClear},"Clear"),d.createElement("div",{className:(0,p.cx)(P.status,(E||T)&&P.statusShowing)},d.createElement("span",{className:T?P.error:""},T||E)))))}}const Re=(0,R.HE)(Te),F=d.lazy(()=>n.e(6031).then(n.bind(n,75695))),be=x=>d.createElement(d.Suspense,{fallback:null},d.createElement(F,{...x})),X=x=>{const c=(0,d.useRef)(null),{runQueryOnBlur:v,onRunQuery:m,onChange:u,...E}=x,T=P=>{c.current=P,u(P),m()},f=P=>{v?P!==c.current&&T(P):u(P)},D=P=>{u(P)};return d.createElement(be,{onChange:D,onRunQuery:T,onBlur:f,...E})},Ue="__recording_rules__",Se="grafana.datasources.prometheus.browser.labels";function Ae(x,c,v){return x?"(Disabled)":c?v?"Metrics browser":"(No metrics found)":"Loading metrics..."}function we(x,{typeaheadContext:c,typeaheadText:v}){switch(c){case"context-labels":{const m=DOMUtil.getNextCharacter();(!m||m==="}"||m===",")&&(x+="=");break}case"context-label-values":{v.match(/^(!?=~?"|")/)||(x=`"${x}`),DOMUtil.getNextCharacter()!=='"'&&(x=`${x}"`);break}default:}return x}class Fe extends d.PureComponent{constructor(c,v){super(c,v),this.refreshHint=()=>{const{datasource:m,query:u,data:E}=this.props,T=m.getInitHints(),f=T.length>0?T[0]:null;if(!E||E.series.length===0){this.setState({hint:f});return}const D=(0,g.aY)(E.series[0])?E.series.map(g.Zr):E.series,P=m.getQueryHints(u,D);let W=P.length>0?P[0]:null;this.setState({hint:W??f})},this.refreshMetrics=async()=>{const{datasource:{languageProvider:m}}=this.props;this.languageProviderInitializationPromise=re(m.start());try{const u=await this.languageProviderInitializationPromise.promise;await Promise.all(u),this.onUpdateLanguage()}catch(u){if(!(N(u)&&u.isCanceled))throw u}},this.onChangeLabelBrowser=m=>{this.onChangeQuery(m,!0),this.setState({labelBrowserVisible:!1})},this.onChangeQuery=(m,u)=>{const{query:E,onChange:T,onRunQuery:f}=this.props;if(T){const D={...E,expr:m};T(D),u&&f&&f()}},this.onClickChooserButton=()=>{this.setState(m=>({labelBrowserVisible:!m.labelBrowserVisible})),(0,U.ff)("user_grafana_prometheus_metrics_browser_clicked",{editorMode:this.state.labelBrowserVisible?"metricViewClosed":"metricViewOpen",app:this.props?.app??""})},this.onClickHintFix=()=>{const{datasource:m,query:u,onChange:E,onRunQuery:T}=this.props,{hint:f}=this.state;f?.fix?.action&&E(m.modifyQuery(u,f.fix.action)),T()},this.onUpdateLanguage=()=>{const{datasource:{languageProvider:m}}=this.props,{metrics:u}=m;u&&this.setState({syntaxLoaded:!0})},this.onTypeahead=async m=>{const{datasource:{languageProvider:u}}=this.props;if(!u)return{suggestions:[]};const{history:E}=this.props,{prefix:T,text:f,value:D,wrapperClasses:P,labelKey:W}=m;return await u.provideCompletionItems({text:f,value:D,prefix:T,wrapperClasses:P,labelKey:W},{history:E})},this.plugins=[(0,L.h)(),(0,O.Z)({onlyIn:m=>m.type==="code_block",getSyntax:m=>"promql"},{...A.languages,promql:this.props.datasource.languageProvider.syntax})],this.state={labelBrowserVisible:!1,syntaxLoaded:!1,hint:null}}componentDidMount(){this.props.datasource.languageProvider&&this.refreshMetrics(),this.refreshHint()}componentWillUnmount(){this.languageProviderInitializationPromise&&this.languageProviderInitializationPromise.cancel()}componentDidUpdate(c){const{data:v,datasource:{languageProvider:m},range:u}=this.props;m!==c.datasource.languageProvider&&this.setState({syntaxLoaded:!1});const E=this.rangeChangedToRefresh(u,c.range);(m!==c.datasource.languageProvider||E)&&this.refreshMetrics(),v&&c.data&&c.data.series!==v.series&&this.refreshHint()}rangeChangedToRefresh(c,v){if(c&&v){const m=(0,k.o8)(c.from.valueOf())===(0,k.o8)(v.from.valueOf()),u=(0,k.o8)(c.to.valueOf())===(0,k.o8)(v.to.valueOf());return!(m&&u)}return!1}render(){const{datasource:c,datasource:{languageProvider:v},query:m,ExtraFieldElement:u,history:E=[],theme:T}=this.props,{labelBrowserVisible:f,syntaxLoaded:D,hint:P}=this.state,W=v.metrics.length>0,ie=Ae(c.lookupsDisabled,D,W),fe=!(D&&W);return d.createElement(B.G,{storageKey:Se,defaultValue:[]},(Ee,ue,ce)=>d.createElement(d.Fragment,null,d.createElement("div",{className:"gf-form-inline gf-form-inline--xs-view-flex-column flex-grow-1","data-testid":this.props["data-testid"]},d.createElement("button",{className:"gf-form-label query-keyword pointer",onClick:this.onClickChooserButton,disabled:fe,type:"button"},ie,d.createElement(w.J,{name:f?"angle-down":"angle-right"})),d.createElement("div",{className:"gf-form gf-form--grow flex-shrink-1 min-width-15"},d.createElement(X,{runQueryOnBlur:this.props.app!==H.zj.Explore,languageProvider:v,history:E,onChange:this.onChangeQuery,onRunQuery:this.props.onRunQuery,initialValue:m.expr??"",placeholder:"Enter a PromQL query\u2026"}))),f&&d.createElement("div",{className:"gf-form"},d.createElement(Re,{languageProvider:v,onChange:this.onChangeLabelBrowser,lastUsedLabels:Ee||[],storeLastUsedLabels:ue,deleteLastUsedLabels:ce})),u,P?d.createElement("div",{className:"query-row-break"},d.createElement("div",{className:"prom-query-field-info text-warning"},P.label," ",P.fix?d.createElement("button",{type:"button",className:(0,p.cx)((0,$.gN)(T),"text-link","muted"),onClick:this.onClickHintFix},P.fix.label):null)):null))}}const Qe=(0,R.HE)(Fe)},76303:(ae,G,n)=>{"use strict";n.d(G,{QG:()=>ze,vQ:()=>ct});var p=n(82897),A=n(20707),d=n.n(A),g=n(68404),H=n(37537),U=n(3363),L=n(53786),O=n(21973),w=n(16313),$=n(74687),R=n(2101),B=n(29236),N=n(14542),re=n(94514),k=n(72097),ve=n.n(k),q=n(40400),J=n(33180),se=n(49922),ne=n(46519),xe=n(21053),ye=n(22069),pe=n(32689),Z=n(54899),oe=n(19985),_=n(61860),De=n(55935),Le=n(44737),Te=n(19349),Re=n(98639),F=n(46063),be=n(41564),X=n(26418),Ue=n(68668),Se=n(46967),Ae=n(79969);function we(i){const e=i.annotation,t=i.onAnnotationChange,a={expr:e.expr,refId:e.name,interval:e.step};return g.createElement(g.Fragment,null,g.createElement(X.EditorRows,null,g.createElement(Ae.j,{...i,query:a,showExplain:!1,onChange:s=>{t({...e,expr:s.expr})}}),g.createElement(X.EditorRow,null,g.createElement(X.EditorField,{label:"Min step",tooltip:g.createElement(g.Fragment,null,"An additional lower limit for the step parameter of the Prometheus query and for the"," ",g.createElement("code",null,"$__interval")," and ",g.createElement("code",null,"$__rate_interval")," variables.")},g.createElement(Ue.H,{type:"text","aria-label":"Set lower limit for the step parameter",placeholder:"auto",minWidth:10,onCommitChange:s=>{t({...e,step:s.currentTarget.value})},defaultValue:a.interval})))),g.createElement(X.Space,{v:.5}),g.createElement(X.EditorRow,null,g.createElement(X.EditorField,{label:"Title",tooltip:"Use either the name or a pattern. For example, {{instance}} is replaced with label value for the label instance."},g.createElement(Se.I,{type:"text",placeholder:"{{alertname}}",value:e.titleFormat,onChange:s=>{t({...e,titleFormat:s.currentTarget.value})}})),g.createElement(X.EditorField,{label:"Tags"},g.createElement(Se.I,{type:"text",placeholder:"label1,label2",value:e.tagKeys,onChange:s=>{t({...e,tagKeys:s.currentTarget.value})}})),g.createElement(X.EditorField,{label:"Text",tooltip:"Use either the name or a pattern. For example, {{instance}} is replaced with label value for the label instance."},g.createElement(Se.I,{type:"text",placeholder:"{{instance}}",value:e.textFormat,onChange:s=>{t({...e,textFormat:s.currentTarget.value})}})),g.createElement(X.EditorField,{label:"Series value as timestamp",tooltip:"The unit of timestamp is milliseconds. If the unit of the series value is seconds, multiply its range vector by 1000."},g.createElement(X.EditorSwitch,{value:e.useValueForTime,onChange:s=>{t({...e,useValueForTime:s.currentTarget.value})}}))))}var Fe=n(36784),Qe=n(51649),x=n(44332);class c{constructor(e,t){this.datasource=e,this.query=t,this.datasource=e,this.query=t,this.range=(0,Te.$t)().timeRange()}process(){const e=/^label_names\(\)\s*$/,t=/^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]*)\)\s*$/,a=/^metrics\((.+)\)\s*$/,s=/^query_result\((.+)\)\s*$/;if(this.query.match(e))return this.labelNamesQuery();const l=this.query.match(t);if(l)return l[1]?this.labelValuesQuery(l[2],l[1]):this.labelValuesQuery(l[2]);const o=this.query.match(a);if(o)return this.metricNameQuery(o[1]);const h=this.query.match(s);return h?(0,U.n)(this.queryResultQuery(h[1])):this.metricNameAndLabelsQuery(this.query)}labelNamesQuery(){const e=this.datasource.getPrometheusTime(this.range.from,!1),t=this.datasource.getPrometheusTime(this.range.to,!0),a={start:e.toString(),end:t.toString()},s="/api/v1/labels";return this.datasource.metadataRequest(s,a).then(r=>(0,p.map)(r.data.data,l=>({text:l})))}labelValuesQuery(e,t){const a=this.datasource.getPrometheusTime(this.range.from,!1),s=this.datasource.getPrometheusTime(this.range.to,!0),r={...t&&{"match[]":t},start:a.toString(),end:s.toString()};if(!t||this.datasource.hasLabelsMatchAPISupport()){const l=`/api/v1/label/${e}/values`;return this.datasource.metadataRequest(l,r).then(o=>(0,p.map)(o.data.data,h=>({text:h})))}else{const l="/api/v1/series";return this.datasource.metadataRequest(l,r).then(o=>{const h=(0,p.map)(o.data.data,y=>y[e]||"").filter(y=>y!=="");return(0,p.uniq)(h).map(y=>({text:y,expandable:!0}))})}}metricNameQuery(e){const t=this.datasource.getPrometheusTime(this.range.from,!1),a=this.datasource.getPrometheusTime(this.range.to,!0),s={start:t.toString(),end:a.toString()},r="/api/v1/label/__name__/values";return this.datasource.metadataRequest(r,s).then(l=>(0,p.chain)(l.data.data).filter(o=>new RegExp(e).test(o)).map(o=>({text:o,expandable:!0})).value())}queryResultQuery(e){const t=this.datasource.getPrometheusTime(this.range.to,!0),a={expr:e};return this.datasource.performInstantQuery(a,t).pipe((0,R.U)(s=>{switch(s.data.data.resultType){case"scalar":case"string":return[{text:s.data.data.result[1]||"",expandable:!1}];case"vector":return(0,p.map)(s.data.data.result,r=>{let l=r.metric.__name__||"";return delete r.metric.__name__,l+="{"+(0,p.map)(r.metric,(o,h)=>h+'="'+o+'"').join(",")+"}",l+=" "+r.value[1]+" "+r.value[0]*1e3,{text:l,expandable:!0}});default:throw Error(`Unknown/Unhandled result type: [${s.data.data.resultType}]`)}}))}metricNameAndLabelsQuery(e){const t=this.datasource.getPrometheusTime(this.range.from,!1),a=this.datasource.getPrometheusTime(this.range.to,!0),s={"match[]":e,start:t.toString(),end:a.toString()},r="/api/v1/series",l=this;return this.datasource.metadataRequest(r,s).then(o=>(0,p.map)(o.data.data,h=>({text:l.datasource.getOriginalMetricName(h),expandable:!0})))}}const v=20;function m(i,e,t){const a=[];if(i.trim().match(/^\w+_bucket$|^\w+_bucket{.*}$/)){const r="Selected metric has buckets.";a.push({type:"HISTOGRAM_QUANTILE",label:r,fix:{label:"Consider calculating aggregated quantile by adding histogram_quantile().",action:{type:"ADD_HISTOGRAM_QUANTILE",query:i}}})}if(i.indexOf("rate(")===-1&&i.indexOf("increase(")===-1){const r=i.match(/\b(\w+_(total|sum|count))\b/);let l=r?r[1]:"";const o=t?.languageProvider?.metricsMetadata;let h=!1;if(o&&(l=Array.from(i.matchAll(/\$?[a-zA-Z_:][a-zA-Z0-9_:]*/g)).map(([S])=>S).filter(S=>!S.startsWith("$")).flatMap(S=>S.split(":")).find(S=>{const b=o[S];return b&&b.type.toLowerCase()==="counter"?(h=!0,!0):!1})??""),l){const y=i.trim().match(/^\w+$|^\w+{.*}$/);let b=`Selected metric ${h?"is":"looks like"} a counter.`,C;y?C={label:"Consider calculating rate of counter by adding rate().",action:{type:"ADD_RATE",query:i}}:b=`${b} Consider calculating rate of counter by adding rate().`,a.push({type:"APPLY_RATE",label:b,fix:C})}}if(t&&t.ruleMappings){const r=t.ruleMappings,l=Object.keys(r).reduce((o,h)=>i.search(h)>-1?{...o,[h]:r[h]}:o,{});if((0,p.size)(l)>0){const o="Query contains recording rules.";a.push({type:"EXPAND_RULES",label:o,fix:{label:"Expand rules",action:{type:"EXPAND_RULES",query:i,options:l}}})}}return e&&e.length>=v&&i.trim().match(/^\w+$/)&&a.push({type:"ADD_SUM",label:"Many time series results returned.",fix:{label:"Consider aggregating with sum().",action:{type:"ADD_SUM",query:i,preventSubmit:!0}}}),a}function u(i){const e=[];return i.directUrl.includes("/loki")&&!i.languageProvider.metrics.length&&e.push({label:"Using Loki as a Prometheus data source is no longer supported. You must use the Loki data source for your Loki instance.",type:"INFO"}),i.lookupsDisabled&&e.push({label:"Labels and metrics lookup was disabled in data source settings.",type:"INFO"}),e}var E=n(47700),T=n(62163),f=n(14582),D=n(19695),P=n(71398),W=n(36512),ie=n(15355),fe=n(88432),Ee=n(86647),ue=n(40885),ce=n(37462);const M=/^[+-]?inf(?:inity)?$/i,ee=(i,e)=>e.app===q.zj.Explore&&(i.meta?.custom?.resultType==="vector"||i.meta?.custom?.resultType==="scalar")?!0:e.targets.find(a=>a.refId===i.refId)?.format==="table",de=(i,e)=>e.targets.find(a=>a.refId===i.refId)?.format==="heatmap";function Ie(i,e,t){const[a,s]=(0,p.partition)(i.data,V=>ee(V,e)),r=Ye(a),[l,o]=(0,p.partition)(s,V=>V.meta?.custom?.resultType==="exemplar"),{exemplarTraceIdDestinations:h}=t,y=l.map(V=>{if(h?.length)for(const Y of h){const j=V.fields.find(te=>te.name===Y.name);if(j){const te=We(Y);j.config.links=j.config.links?.length?[...j.config.links,...te]:te}}return{...V,meta:{...V.meta,dataTopic:T.w5.Annotations}}}),[S,b]=(0,p.partition)(o,V=>de(V,e));S.forEach(V=>{if(V.name==null){let Y=V.fields.find(j=>j.name==="Value");if(Y){let j=Y.labels?.le;j&&(V.name=j,Y.config.displayNameFromDS=j)}}});const C=(0,p.groupBy)(S,V=>V.refId);let I=[];for(const V in C){const Y=C[V],j=(0,p.groupBy)(Y,te=>{const he=te.fields.find(ge=>ge.name===f.M5);if(he?.labels&&Ce in he.labels){const{le:ge,...Xe}=he?.labels;return Object.values(Xe).join()}return Object.values(he?.labels??[]).join()});(0,p.forOwn)(j,(te,he)=>{const ge=te.sort(He);I.push(je(Ge(ge)))})}const Q=b.map(V=>({...V,meta:{...V.meta,preferredVisualisationType:"graph"}})),K=(0,p.flatten)(I);return{...i,data:[...Q,...r,...K,...y]}}const Ce="le";function Ye(i){if(i.length===0||i.length===1&&i[0].length===0)return i;const e=(0,p.groupBy)(i,"refId"),t=Object.keys(e);return t.map(s=>{const r=Je(t.length,s),l=Me({data:[],valueName:r}),o=Pe([]),h=[];e[s].forEach(S=>{const C=S.fields[1]?.labels??{};Object.keys(C).sort().forEach(I=>{if(!h.some(Q=>Q.name===I)){const Q=I===Ce;h.push({name:I,config:{filterable:!0},type:Q?f.fS.number:f.fS.string,values:new D.G})}})}),e[s].forEach(S=>{const b=S.fields[0]?.values??new D.G,C=S.fields[1]?.values??new D.G;b.toArray().forEach(I=>o.values.add(I)),C.toArray().forEach(I=>{l.values.add(me(I));const Q=S.fields[1].labels??{};h.forEach(K=>K.values.add(Ve(Q,K.name)))})});const y=[o,...h,l];return{refId:s,fields:y,meta:{...i[0].meta,preferredVisualisationType:"rawPrometheus"},length:o.values.length}})}function Je(i,e=""){return i>1?`Value #${e}`:"Value"}function Be(i,e){const t={format:e.target.format,step:e.query.step,legendFormat:e.target.legendFormat,start:e.query.start,end:e.query.end,query:e.query.expr,responseListLength:e.responseListLength,scopedVars:e.scopedVars,refId:e.target.refId,valueWithRefId:e.target.valueWithRefId,meta:{preferredVisualisationType:e.query.instant?"rawPrometheus":"graph"}},a=i.data.data;if((0,ce.WS)(a)){const r=[];a.forEach(h=>{const y=h.exemplars.map(S=>({[f.Ls]:S.timestamp*1e3,[f.M5]:S.value,...S.labels,...h.seriesLabels}));r.push(...y)});const l=qe(r,t),o=new P.i(l);if(o.meta={dataTopic:T.w5.Annotations},e.exemplarTraceIdDestinations?.length)for(const h of e.exemplarTraceIdDestinations){const y=o.fields.find(S=>S.name===h.name);if(y){const S=We(h);y.config.links=y.config.links?.length?[...y.config.links,...S]:S}}return[o]}if(!a?.result)return[];if(a.resultType==="scalar")return[{meta:t.meta,refId:t.refId,length:1,fields:[Pe([a.result]),Me({data:[a.result]})]}];if(t.format==="table")return[et(a.result,t)];const s=[];return a.result.forEach(r=>s.push(_e(r,t))),t.format==="heatmap"?je(Ge(s.sort(He))):s}function We(i){const e=[];if(i.datasourceUid){const a=(0,Ee.F)().getInstanceSettings(i.datasourceUid);a&&e.push({title:i.urlDisplayLabel||`Query with ${a?.name}`,url:"",internal:{query:{query:"${__value.raw}",queryType:"traceql"},datasourceUid:i.datasourceUid,datasourceName:a?.name??"Data source not found"}})}return i.url&&e.push({title:i.urlDisplayLabel||`Go to ${i.url}`,url:i.url,targetBlank:!0}),e}function qe(i,e){const t=e.step||15,a={},s=[];for(const h of i){const y=String(Math.floor(h[f.Ls]/1e3/t)*t*1e3);a[y]||(a[y]=[]),a[y].push(h),s.push(h[f.M5])}const r=(0,E.deviation)(s),l=Object.keys(a).sort(),o=[];for(const h of l){const y=a[h];if(y.length===1)o.push(y[0]);else{const b=y.map(C=>C[f.M5]).sort(E.descending).reduce((C,I)=>{if(C.length===0)C.push(I);else{const Q=C[C.length-1];r&&Q-I>=2*r&&C.push(I)}return C},[]);o.push(...b.map(C=>y.find(I=>I[f.M5]===C)))}}return o}function _e(i,e){const{name:t,labels:a}=tt(i.metric,e),s=[];if((0,ce.el)(i)){const r=e.step?e.step*1e3:NaN;let l=e.start*1e3;const o=[];for(const y of i.values){let S=me(y[1]);isNaN(S)&&(S=null);const b=y[0]*1e3;for(let C=l;C<b;C+=r)o.push([C,null]);l=b+r,o.push([b,S])}const h=e.end*1e3;for(let y=l;y<=h;y+=r)o.push([y,null]);s.push(Pe(o,!0)),s.push(Me({data:o,parseValue:!1,labels:a,displayNameFromDS:t}))}else s.push(Pe([i.value])),s.push(Me({data:[i.value],labels:a,displayNameFromDS:t}));return{meta:e.meta,refId:e.refId,length:s[0].values.length,fields:s,name:t}}function et(i,e){if(!i||i.length===0)return{meta:e.meta,refId:e.refId,length:0,fields:[]};const t=e.responseListLength>1||e.valueWithRefId?`Value #${e.refId}`:"Value",a=Pe([]),s=Object.keys(i.reduce((l,o)=>({...l,...o.metric}),{})).sort().map(l=>({name:l,config:{filterable:!0},type:l===Ce?f.fS.number:f.fS.string,values:new D.G})),r=Me({data:[],valueName:t});return i.forEach(l=>{(0,ce.el)(l)?l.values.forEach(o=>{a.values.add(o[0]*1e3),s.forEach(h=>h.values.add(Ve(l.metric,h.name))),r.values.add(me(o[1]))}):(a.values.add(l.value[0]*1e3),s.forEach(o=>o.values.add(Ve(l.metric,o.name))),r.values.add(me(l.value[1])))}),{meta:e.meta,refId:e.refId,length:a.values.length,fields:[a,...s,r]}}function Ve(i,e){return i.hasOwnProperty(e)?e===Ce?me(i[e]):i[e]:""}function Pe(i,e=!1){return{name:f.Ls,type:f.fS.time,config:{},values:new D.G(i.map(t=>e?t[0]:t[0]*1e3))}}function Me({data:i,valueName:e=f.M5,parseValue:t=!0,labels:a,displayNameFromDS:s}){return{name:e,type:f.fS.number,display:(0,W.U)(),config:{displayNameFromDS:s},labels:a,values:new D.G(i.map(r=>t?me(r[1]):r[1]))}}function tt(i,e){if(e?.legendFormat)return{name:(0,x.W)((0,ue.J)().replace(e.legendFormat,e?.scopedVars),i),labels:i};const{__name__:t,...a}=i,s=(0,ie.aA)(a);let r=`${t??""}${s}`;return r||(r=e.query),{name:r,labels:a}}function at(i){const e=i.__name__||"";delete i.__name__;const t=Object.entries(i).map(a=>`${a[0]}="${a[1]}"`).join(",");return`${e}{${t}}`}function je(i){if(i.length===0)return[];const e=i[0].fields.find(a=>a.type===f.fS.time),t=i.map(a=>{let s=a.fields.find(r=>r.type===f.fS.number);return{...s,name:s.config.displayNameFromDS}});return[{...i[0],meta:{...i[0].meta,type:fe.P.HeatmapRows},fields:[e,...t]}]}function Ge(i){for(let e=i.length-1;e>0;e--){const t=i[e].fields.find(s=>s.name===f.M5),a=i[e-1].fields.find(s=>s.name===f.M5);if(!t||!a)throw new Error("Prometheus heatmap transform error: data should be a time series");for(let s=0;s<t.values.length;s++){const r=a.values.get(s)||[0];t.values.toArray()[s]-=r}}return i}function He(i,e){let t,a;try{t=me(i.name??""),a=me(e.name??"")}catch(s){return console.error(s),0}return t>a?1:t<a?-1:0}function me(i){return M.test(i)?i[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY:parseFloat(i)}var rt=n(41818),st=n(35645);function nt(i,e,t){const{app:a,targets:s}=e;if(!(a===q.zj.Dashboard||a===q.zj.PanelViewer))for(const r of s)(0,rt.ff)("grafana_prometheus_query_executed",{app:a,grafana_version:st.v.buildInfo.version,has_data:i.data.some(l=>l.length>0),has_error:i.error!==void 0,expr:r.expr,format:r.format,instant:r.instant,range:r.range,exemplar:r.exemplar,hinting:r.hinting,interval:r.interval,intervalFactor:r.intervalFactor,utcOffsetSec:r.utcOffsetSec,legend:r.legendFormat,valueWithRefId:r.valueWithRefId,requestId:r.requestId,showingGraph:r.showingGraph,showingTable:r.showingTable,editor_mode:r.editorMode,simultaneously_sent_query_count:s.length,time_range_from:e?.range?.from?.toISOString(),time_range_to:e?.range?.to?.toISOString(),time_taken:Date.now()-t.getTime()})}var it=n(85526),lt=n(59670);class ot extends lt.v6{constructor(e,t=(0,ue.J)(),a=(0,Te.$t)()){super(),this.datasource=e,this.templateSrv=t,this.timeSrv=a,this.query=this.query.bind(this)}query(e){const t=e.targets[0].expr;if(!t)return(0,L.of)({data:[]});const a={...e.scopedVars,__interval:{text:this.datasource.interval,value:this.datasource.interval},__interval_ms:{text:J.intervalToMs(this.datasource.interval),value:J.intervalToMs(this.datasource.interval)},...this.datasource.getRangeScopedVars(this.timeSrv.timeRange())},s=this.templateSrv.replace(t,a,this.datasource.interpolateQueryExpr),r=new c(this.datasource,s);return(0,it.D)(r.process()).pipe((0,R.U)(o=>({data:o})))}toDataQuery(e){return{refId:"PrometheusDatasource-VariableQuery",expr:e.query}}}const Ke="60s",ut=["api/v1/query","api/v1/query_range","api/v1/series","api/v1/labels"],ze="-Instant";class ct extends ye.CK{constructor(e,t=(0,Re.J)(),a=(0,Te.$t)(),s){super(e),this.templateSrv=t,this.timeSrv=a,this.metricsNameCache=new(d())({max:10}),this.init=async()=>{this.loadRules(),this.exemplarsAvailable=await this.areExemplarsAvailable()},this.prepareTargets=(r,l,o)=>{const h=[],y=[],S=(0,p.cloneDeep)(r.targets);for(const b of S){if(!b.expr||b.hide)continue;b.requestId=r.panelId+b.refId;const C=this.languageProvider.histogramMetrics.find(I=>b.expr.includes(I));if(r.app===q.zj.Explore&&b.range===b.instant){const I=(0,p.cloneDeep)(b);I.format="table",I.instant=!0,I.range=!1,I.valueWithRefId=!0,delete I.maxDataPoints,I.requestId+="_instant";const Q=(0,p.cloneDeep)(b);if(Q.format="time_series",Q.instant=!1,I.range=!0,b.exemplar){if(!C||C&&!y.some(K=>K.expr.includes(C))){const K=(0,p.cloneDeep)(b);K.instant=!1,K.requestId+="_exemplar",h.push(this.createQuery(K,r,l,o)),y.push(K)}I.exemplar=!1,Q.exemplar=!1}y.push(I,Q),h.push(this.createQuery(I,r,l,o),this.createQuery(Q,r,l,o))}else if(b.instant&&r.app===q.zj.Explore){const I=(0,p.cloneDeep)(b);I.format="table",h.push(this.createQuery(I,r,l,o)),y.push(I)}else{if(b.exemplar&&!b.instant){if(!C||C&&!y.some(I=>I.expr.includes(C))){const I=(0,p.cloneDeep)(b);I.requestId+="_exemplar",h.push(this.createQuery(I,r,l,o)),y.push(I)}b.exemplar=!1}h.push(this.createQuery(b,r,l,o)),y.push(b)}}return{queries:h,activeTargets:y}},this.handleErrors=(r,l)=>{const o={message:r&&r.statusText||"Unknown error during query transaction. Please check JS console logs.",refId:l.refId};return r.data?typeof r.data=="string"?o.message=r.data:r.data.error&&(o.message=(0,De.Xh)(r.data.error)):r.message?o.message=r.message:typeof r=="string"&&(o.message=r),o.status=r.status,o.statusText=r.statusText,o},this.processAnnotationResponse=(r,l)=>{const o=(0,pe.z1)({data:l}).data;if(!o||!o.length)return[];const h=r.annotation,{tagKeys:y="",titleFormat:S="",textFormat:b=""}=h,C=J.intervalToSeconds(h.step||Ke)*1e3,I=y.split(","),Q=[];for(const K of o){if(K.fields.length===0)continue;const V=K.fields[0],Y=K.fields[1],j=Y?.labels||{},te=Object.keys(j).filter(z=>I.includes(z)).map(z=>j[z]),he=[];let ge=0;Y.values.toArray().forEach(z=>{let Ne,$e;const ht=V.values.get(ge);r.annotation.useValueForTime?(Ne=Math.floor(parseFloat(z)),$e=1):(Ne=Math.floor(parseFloat(ht)),$e=parseFloat(z)),ge++,he.push([Ne,$e])});const Oe=he.filter(z=>z[1]>0).map(z=>z[0]);let le=null;for(const z of Oe){if(le&&(le.timeEnd??0)+C>=z){le.timeEnd=z;continue}le&&Q.push(le),le={time:z,timeEnd:z,annotation:h,title:(0,x.W)(S,j),tags:te,text:(0,x.W)(b,j)}}le&&(le.timeEnd=Oe[Oe.length-1],Q.push(le))}return Q},this.type="prometheus",this.subType=F.T8.Prometheus,this.rulerEnabled=!1,this.editorSrc="app/features/prometheus/partials/query.editor.html",this.id=e.id,this.url=e.url,this.access=e.access,this.basicAuth=e.basicAuth,this.withCredentials=e.withCredentials,this.interval=e.jsonData.timeInterval||"15s",this.queryTimeout=e.jsonData.queryTimeout,this.httpMethod=e.jsonData.httpMethod||"GET",this.directUrl=e.jsonData.directUrl??this.url,this.exemplarTraceIdDestinations=e.jsonData.exemplarTraceIdDestinations,this.ruleMappings={},this.languageProvider=s??new Fe.ZP(this),this.lookupsDisabled=e.jsonData.disableMetricsLookup??!1,this.customQueryParameters=new URLSearchParams(e.jsonData.customQueryParameters),this.datasourceConfigurationPrometheusFlavor=e.jsonData.prometheusType,this.datasourceConfigurationPrometheusVersion=e.jsonData.prometheusVersion,this.defaultEditor=e.jsonData.defaultEditor,this.variables=new ot(this,this.templateSrv,this.timeSrv),this.exemplarsAvailable=!0,this.annotations={QueryEditor:we}}getQueryDisplayText(e){return e.expr}hasLabelsMatchAPISupport(){return this._isDatasourceVersionGreaterOrEqualTo("2.24.0",F.T8.Prometheus)||this._isDatasourceVersionGreaterOrEqualTo("2.0.0",F.T8.Mimir)||this._isDatasourceVersionGreaterOrEqualTo("1.11.0",F.T8.Cortex)||this._isDatasourceVersionGreaterOrEqualTo("0.18.0",F.T8.Thanos)}_isDatasourceVersionGreaterOrEqualTo(e,t){return!this.datasourceConfigurationPrometheusVersion||!this.datasourceConfigurationPrometheusFlavor||t!==this.datasourceConfigurationPrometheusFlavor?!1:ve().gte(this.datasourceConfigurationPrometheusVersion,e)}_addTracingHeaders(e,t){e.headers={},this.access==="proxy"&&(e.headers["X-Dashboard-Id"]=t.dashboardId,e.headers["X-Dashboard-UID"]=t.dashboardUID,e.headers["X-Panel-Id"]=t.panelId)}_request(e,t,a={}){if(this.access==="direct"){const l=new Error("Browser access mode in the Prometheus datasource is no longer available. Switch to server access mode.");return(0,H._)(()=>l)}t=t||{};for(const[l,o]of this.customQueryParameters)t[l]==null&&(t[l]=o);let s=this.url+e;e.startsWith(`/api/datasources/uid/${this.uid}`)&&(s=e);const r=(0,p.defaults)(a,{url:s,method:this.httpMethod,headers:{}});return r.method==="GET"?t&&Object.keys(t).length&&(r.url=r.url+(r.url.search(/\?/)>=0?"&":"?")+Object.entries(t).map(([l,o])=>`${encodeURIComponent(l)}=${encodeURIComponent(o)}`).join("&")):(r.headers["Content-Type"]="application/x-www-form-urlencoded",r.data=t),(this.basicAuth||this.withCredentials)&&(r.withCredentials=!0),this.basicAuth&&(r.headers.Authorization=this.basicAuth),(0,Z.i)().fetch(r)}async importFromAbstractQueries(e){return e.map(t=>this.languageProvider.importFromAbstractQuery(t))}async exportToAbstractQueries(e){return e.map(t=>this.languageProvider.exportToAbstractQuery(t))}async metadataRequest(e,t={},a){if(ut.some(s=>e.includes(s)))try{return await(0,U.n)(this._request(`/api/datasources/uid/${this.uid}/resources${e}`,t,{method:this.httpMethod,hideFromInspector:!0,showErrorAlert:!1,...a}))}catch(s){if(this.httpMethod==="POST"&&(0,Z.kW)(s)&&(s.status===405||s.status===400))console.warn("Couldn't use configured POST HTTP method for this request. Trying to use GET method instead.");else throw s}return await(0,U.n)(this._request(`/api/datasources/uid/${this.uid}/resources${e}`,t,{method:"GET",hideFromInspector:!0,...a}))}interpolateQueryExpr(e=[],t){if(!t.multi&&!t.includeAll)return ke(e);if(typeof e=="string")return Ze(e);const a=e.map(s=>Ze(s));return a.length===1?a[0]:"("+a.join("|")+")"}targetContainsTemplate(e){return this.templateSrv.containsTemplate(e.expr)}shouldRunExemplarQuery(e,t){if(e.exemplar){const a=this.languageProvider.histogramMetrics.find(l=>e.expr.includes(l)),s=t.targets.findIndex(l=>l.refId===e.refId),r=t.targets.slice(0,s).filter(l=>!l.hide);return!!(!a||a&&!r.some(l=>l.expr.includes(a)))}return!1}processTargetV2(e,t){const a=[],s={...e,exemplar:this.shouldRunExemplarQuery(e,t),requestId:t.panelId+e.refId,utcOffsetSec:this.timeSrv.timeRange().to.utcOffset()*60};return e.instant&&e.range?a.push({...s,refId:s.refId,instant:!1},{...s,refId:s.refId+ze,range:!1}):a.push(s),a}query(e){if(this.access==="proxy"){const t=e.targets.map(s=>this.processTargetV2(s,e)),a=new Date;return super.query({...e,targets:t.flat()}).pipe((0,R.U)(s=>Ie(s,e,{exemplarTraceIdDestinations:this.exemplarTraceIdDestinations})),(0,B.b)(s=>{nt(s,e,a)}))}else{const t=this.getPrometheusTime(e.range.from,!1),a=this.getPrometheusTime(e.range.to,!0),{queries:s,activeTargets:r}=this.prepareTargets(e,t,a);return!s||!s.length?(0,L.of)({data:[],state:se.Gu.Done}):e.app===q.zj.Explore?this.exploreQuery(s,r,a):this.panelsQuery(s,r,a,e.requestId,e.scopedVars)}}exploreQuery(e,t,a){let s=e.length;const r=e.map((l,o)=>{const h=t[o],y=(0,O.z)((0,B.b)(()=>s--),(0,N.h)(S=>!S.cancelled),(0,R.U)(S=>({data:Be(S,{query:l,target:h,responseListLength:e.length,exemplarTraceIdDestinations:this.exemplarTraceIdDestinations}),key:l.requestId,state:s===0?se.Gu.Done:se.Gu.Loading})));return this.runQuery(l,a,y)});return(0,w.T)(...r)}panelsQuery(e,t,a,s,r){const l=e.map((o,h)=>{const y=t[h],S=(0,O.z)((0,N.h)(b=>!b.cancelled),(0,R.U)(b=>Be(b,{query:o,target:y,responseListLength:e.length,scopedVars:r,exemplarTraceIdDestinations:this.exemplarTraceIdDestinations})));return this.runQuery(o,a,S)});return(0,$.D)(l).pipe((0,R.U)(o=>({data:o.reduce((y,S)=>[...y,...S],[]),key:s,state:se.Gu.Done})))}runQuery(e,t,a){return e.instant?this.performInstantQuery(e,t).pipe(a):e.exemplar?this.getExemplars(e).pipe((0,re.K)(()=>(0,L.of)({data:[],state:se.Gu.Done})),a):this.performTimeSeriesQuery(e,e.start,e.end).pipe(a)}createQuery(e,t,a,s){const r={hinting:e.hinting,instant:e.instant,exemplar:e.exemplar,step:0,expr:"",requestId:e.requestId,refId:e.refId,start:0,end:0},l=Math.ceil(s-a);let o=J.intervalToSeconds(t.interval);const h=J.intervalToSeconds(this.templateSrv.replace(e.interval||t.interval,t.scopedVars)),y=e.interval?J.intervalToSeconds(this.templateSrv.replace(e.interval,t.scopedVars)):J.intervalToSeconds(this.interval),S=e.intervalFactor||1,b=this.adjustInterval(o,h,l,S);let C={...t.scopedVars,...this.getRangeScopedVars(t.range),...this.getRateIntervalScopedVariable(b,y)};o!==b&&(o=b,C=Object.assign({},t.scopedVars,{__interval:{text:o+"s",value:o+"s"},__interval_ms:{text:o*1e3,value:o*1e3},...this.getRateIntervalScopedVariable(o,y),...this.getRangeScopedVars(t.range)})),r.step=o;let I=e.expr;I=this.enhanceExprWithAdHocFilters(I),r.expr=this.templateSrv.replace(I,C,this.interpolateQueryExpr);const Q=dt(a,s,r.step,this.timeSrv.timeRange().to.utcOffset()*60);return r.start=Q.start,r.end=Q.end,this._addTracingHeaders(r,t),r}getRateIntervalScopedVariable(e,t){t===0&&(t=15);const a=Math.max(e+t,4*t);return{__rate_interval:{text:a+"s",value:a+"s"}}}adjustInterval(e,t,a,s){let r=a/11e3;return r>1&&(r=Math.ceil(r)),Math.max(e*s,t,r)}performTimeSeriesQuery(e,t,a){if(t>a)throw{message:"Invalid time range"};const s="/api/v1/query_range",r={query:e.expr,start:t,end:a,step:e.step};return this.queryTimeout&&(r.timeout=this.queryTimeout),this._request(s,r,{requestId:e.requestId,headers:e.headers}).pipe((0,re.K)(l=>l.cancelled?(0,L.of)(l):(0,H._)(this.handleErrors(l,e))))}performInstantQuery(e,t){const a="/api/v1/query",s={query:e.expr,time:t};return this.queryTimeout&&(s.timeout=this.queryTimeout),this._request(`/api/datasources/uid/${this.uid}/resources${a}`,s,{requestId:e.requestId,headers:e.headers}).pipe((0,re.K)(r=>r.cancelled?(0,L.of)(r):(0,H._)(this.handleErrors(r,e))))}metricFindQuery(e){if(!e)return Promise.resolve([]);const t={__interval:{text:this.interval,value:this.interval},__interval_ms:{text:J.intervalToMs(this.interval),value:J.intervalToMs(this.interval)},...this.getRangeScopedVars(this.timeSrv.timeRange())},a=this.templateSrv.replace(e,t,this.interpolateQueryExpr);return new c(this,a).process()}getRangeScopedVars(e=this.timeSrv.timeRange()){const t=e.to.diff(e.from),a=Math.round(t/1e3);return{__range_ms:{text:t,value:t},__range_s:{text:a,value:a},__range:{text:a+"s",value:a+"s"}}}async annotationQuery(e){if(this.access==="direct"){const l=new Error("Browser access mode in the Prometheus datasource is no longer available. Switch to server access mode.");return Promise.reject(l)}const t=e.annotation,{expr:a=""}=t;if(!a)return Promise.resolve([]);const s=e.annotation.step||Ke,r={expr:a,range:!0,instant:!1,exemplar:!1,interval:s,refId:"X",datasource:this.getRef()};return await(0,U.n)((0,Z.i)().fetch({url:"/api/ds/query",method:"POST",headers:this.getRequestHeaders(),data:{from:(this.getPrometheusTime(e.range.from,!1)*1e3).toString(),to:(this.getPrometheusTime(e.range.to,!0)*1e3).toString(),queries:[this.applyTemplateVariables(r,{})]},requestId:`prom-query-${t.name}`}).pipe((0,R.U)(l=>this.processAnnotationResponse(e,l.data))))}getExemplars(e){const t="/api/v1/query_exemplars";return this._request(t,{query:e.expr,start:e.start.toString(),end:e.end.toString()},{requestId:e.requestId,headers:e.headers})}async getTagKeys(e){if(e?.series){const t=await Promise.all(e.series.map(r=>this.languageProvider.fetchSeriesLabels(r)));let a=[];return t.map(r=>a=a.concat(Object.keys(r))),[...new Set(a)].map(r=>({text:r}))}else{const t=this.getTimeRangeParams();return(await this.metadataRequest("/api/v1/labels",t))?.data?.data?.map(s=>({text:s}))??[]}}async getTagValues(e={}){const t=this.getTimeRangeParams();return(await this.metadataRequest(`/api/v1/label/${e.key}/values`,t))?.data?.data?.map(s=>({text:s}))??[]}async getBuildInfo(){try{return await(0,Le.WG)({url:this.url,name:this.name,type:"prometheus"})}catch{return}}getBuildInfoMessage(e){const t=g.createElement(oe.C,{color:"green",icon:"check",text:"Ruler API enabled"}),a=g.createElement(oe.C,{color:"orange",icon:"exclamation-triangle",text:"Ruler API not enabled"}),s=g.createElement(_.u,{placement:"top",content:"Prometheus does not allow editing rules, connect to either a Mimir or Cortex datasource to manage alerts via Grafana."},g.createElement("div",null,g.createElement(oe.C,{color:"red",icon:"exclamation-triangle",text:"Ruler API not supported"}))),r={[F.T8.Cortex]:"/public/app/plugins/datasource/prometheus/img/cortex_logo.svg",[F.T8.Mimir]:"/public/app/plugins/datasource/prometheus/img/mimir_logo.svg",[F.T8.Prometheus]:"/public/app/plugins/datasource/prometheus/img/prometheus_logo.svg",[F.T8.Thanos]:"/public/app/plugins/datasource/prometheus/img/thanos_logo.svg"},l={[F.T8.Cortex]:"blue",[F.T8.Mimir]:"orange",[F.T8.Prometheus]:"red",[F.T8.Thanos]:"purple"},o={[F.T8.Cortex]:"Cortex",[F.T8.Mimir]:"Mimir",[F.T8.Prometheus]:"Prometheus",[F.T8.Thanos]:"Thanos"},h=this.datasourceConfigurationPrometheusFlavor??e.application,y=g.createElement(oe.C,{text:g.createElement("span",null,g.createElement("img",{style:{width:14,height:14,verticalAlign:"text-bottom"},src:r[h??F.T8.Prometheus],alt:""})," ",h?o[h]:"Unknown"),color:l[h??F.T8.Prometheus]});return g.createElement("div",{style:{display:"grid",gridTemplateColumns:"max-content max-content",rowGap:"0.5rem",columnGap:"2rem",marginTop:"1rem"}},g.createElement("div",null,"Type"),g.createElement("div",null,y),g.createElement(g.Fragment,null,g.createElement("div",null,"Ruler API"),e.application===F.T8.Prometheus&&g.createElement("div",null,s),e.application!==F.T8.Prometheus&&g.createElement("div",null,e.features.rulerApiEnabled?t:a)))}async testDatasource(){const e=new Date().getTime(),t={targets:[{refId:"test",expr:"1+1",instant:!0}],requestId:`${this.id}-health`,scopedVars:{},dashboardId:0,panelId:0,interval:"1m",intervalMs:6e4,maxDataPoints:1,range:{from:(0,ne.CQ)(e-1e3),to:(0,ne.CQ)(e)}},a=await this.getBuildInfo();return(0,U.n)(this.query(t)).then(s=>!s||!s.data||s.state!==se.Gu.Done?{status:"error",message:`Error reading Prometheus: ${s?.error?.message}`}:{status:"success",message:"Data source is working",details:a&&{verboseMessage:this.getBuildInfoMessage(a)}}).catch(s=>(console.error("Prometheus Error",s),{status:"error",message:s.message}))}interpolateVariablesInQueries(e,t){let a=e;return e&&e.length&&(a=e.map(s=>({...s,datasource:this.getRef(),expr:this.enhanceExprWithAdHocFilters(this.templateSrv.replace(s.expr,t,this.interpolateQueryExpr)),interval:this.templateSrv.replace(s.interval,t)}))),a}getQueryHints(e,t){return m(e.expr??"",t,this)}getInitHints(){return u(this)}async loadRules(){try{const t=(await this.metadataRequest("/api/v1/rules",{},{showErrorAlert:!1})).data?.data?.groups;t&&(this.ruleMappings=mt(t))}catch(e){console.log("Rules API is experimental. Ignore next error."),console.error(e)}}async areExemplarsAvailable(){try{return(await this.metadataRequest("/api/v1/query_exemplars",{query:"test",start:(0,ne.CQ)().subtract(30,"minutes").valueOf().toString(),end:(0,ne.CQ)().valueOf().toString()},{showErrorAlert:!1})).data.status==="success"}catch{return!1}}modifyQuery(e,t){let a=e.expr??"";switch(t.type){case"ADD_FILTER":{const{key:s,value:r}=t.options??{};s&&r&&(a=(0,be.F)(a,s,r));break}case"ADD_FILTER_OUT":{const{key:s,value:r}=t.options??{};s&&r&&(a=(0,be.F)(a,s,r,"!="));break}case"ADD_HISTOGRAM_QUANTILE":{a=`histogram_quantile(0.95, sum(rate(${a}[$__rate_interval])) by (le))`;break}case"ADD_RATE":{a=`rate(${a}[$__rate_interval])`;break}case"ADD_SUM":{a=`sum(${a.trim()}) by ($1)`;break}case"EXPAND_RULES":{t.options&&(a=(0,Qe.ll)(a,t.options));break}default:break}return{...e,expr:a}}getPrometheusTime(e,t){return typeof e=="string"&&(e=xe.parse(e,t)),Math.ceil(e.valueOf()/1e3)}getTimeRangeParams(){const e=this.timeSrv.timeRange();return{start:this.getPrometheusTime(e.from,!1).toString(),end:this.getPrometheusTime(e.to,!0).toString()}}getOriginalMetricName(e){return at(e)}enhanceExprWithAdHocFilters(e){return this.templateSrv.getAdhocFilters(this.name).reduce((s,r)=>{const{key:l,operator:o}=r;let{value:h}=r;return(o==="=~"||o==="!~")&&(h=ke(h)),(0,be.F)(s,l,h,o)},e)}filterQuery(e){return!(e.hide||!e.expr)}applyTemplateVariables(e,t){const a=(0,p.cloneDeep)(t);delete a.__interval,delete a.__interval_ms;const s=this.enhanceExprWithAdHocFilters(e.expr);return{...e,legendFormat:this.templateSrv.replace(e.legendFormat,a),expr:this.templateSrv.replace(s,a,this.interpolateQueryExpr),interval:this.templateSrv.replace(e.interval,a)}}getVariables(){return this.templateSrv.getVariables().map(e=>`$${e.name}`)}interpolateString(e){return this.templateSrv.replace(e,void 0,this.interpolateQueryExpr)}}function dt(i,e,t,a){const s=Math.floor((e+a)/t)*t-a,r=Math.floor((i+a)/t)*t-a;return{end:s,start:r}}function mt(i){return i.reduce((e,t)=>t.rules.filter(a=>a.type==="recording").reduce((a,s)=>({...a,[s.name]:s.query}),e),{})}function ke(i){return typeof i=="string"?i.replace(/\\/g,"\\\\").replace(/'/g,"\\\\'"):i}function Ze(i){return typeof i=="string"?i.replace(/\\/g,"\\\\\\\\").replace(/[$^*{}\[\]\'+?.()|]/g,"\\\\$&"):i}},37285:(ae,G,n)=>{"use strict";n.d(G,{A:()=>w,n:()=>$});var p=n(68404),A=n(26418),d=n(21899),g=n(4252),H=n(74852),U=n(58439),L=n(19023),O=n(45204);const w="Fetch all series matching metric name and label filters.",$=p.memo(({query:R})=>{const B=(0,H._)(R||"").query,N={grammar:d.ZP,name:"promql"};return p.createElement(A.Stack,{gap:.5,direction:"column"},p.createElement(U.B,{stepNumber:1,title:p.createElement(O.U,{query:`${B.metric} ${g.Z.renderLabels(B.labels)}`,lang:N})},w),p.createElement(L.V,{stepNumber:2,queryModeller:g.Z,query:B,lang:N}))});$.displayName="PromQueryBuilderExplained"},79969:(ae,G,n)=>{"use strict";n.d(G,{j:()=>U});var p=n(52423),A=n(68404),d=n(72648),g=n(362),H=n(37285);function U(O){const{query:w,datasource:$,range:R,onRunQuery:B,onChange:N,data:re,app:k,showExplain:ve}=O,q=(0,d.wW)(L);return A.createElement("div",{className:q.wrapper},A.createElement(g.ZP,{datasource:$,query:w,range:R,onRunQuery:B,onChange:N,history:[],data:re,app:k}),ve&&A.createElement(H.n,{query:w.expr}))}const L=O=>({wrapper:p.css`
      .gf-form {
        margin-bottom: 0;
      }
    `})},58439:(ae,G,n)=>{"use strict";n.d(G,{B:()=>H});var p=n(52423),A=n(68404),d=n(41959),g=n(72648);function H({title:L,stepNumber:O,markdown:w,children:$}){const R=(0,g.wW)(U);return A.createElement("div",{className:R.box},O!==void 0&&A.createElement("div",{className:R.stepNumber},O),A.createElement("div",{className:R.boxInner},L&&A.createElement("div",{className:R.header},A.createElement("span",null,L)),A.createElement("div",{className:R.body},w&&A.createElement("div",{dangerouslySetInnerHTML:{__html:(0,d.a)(w)}}),$)))}const U=L=>({box:(0,p.css)({background:L.colors.background.secondary,padding:L.spacing(1),borderRadius:L.shape.borderRadius(),position:"relative"}),boxInner:(0,p.css)({marginLeft:L.spacing(4)}),stepNumber:(0,p.css)({fontWeight:L.typography.fontWeightMedium,background:L.colors.secondary.main,width:"20px",height:"20px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",top:"10px",left:"11px",fontSize:L.typography.bodySmall.fontSize}),header:(0,p.css)({paddingBottom:L.spacing(.5),display:"flex",alignItems:"center",fontFamily:L.typography.fontFamilyMonospace}),body:(0,p.css)({color:L.colors.text.secondary,"p:last-child":{margin:0},a:{color:L.colors.text.link,textDecoration:"underline"}})})},19023:(ae,G,n)=>{"use strict";n.d(G,{V:()=>g});var p=n(68404),A=n(58439),d=n(45204);function g({query:H,queryModeller:U,stepNumber:L,lang:O,onMouseEnter:w,onMouseLeave:$}){return p.createElement(p.Fragment,null,H.operations.map((R,B)=>{const N=U.getOperationDef(R.id);if(!N)return`Operation ${R.id} not found`;const re=N.renderer(R,N,"<expr>"),k=N.explainHandler?N.explainHandler(R,N):N.documentation??"no docs";return p.createElement("div",{key:B,onMouseEnter:()=>w?.(R,B),onMouseLeave:()=>$?.(R,B)},p.createElement(A.B,{stepNumber:B+L,title:p.createElement(d.U,{query:re,lang:O}),markdown:k}))}))}},45204:(ae,G,n)=>{"use strict";n.d(G,{U:()=>U});var p=n(52423),A=n(57706),d=n.n(A),g=n(68404),H=n(72648);function U({query:O,lang:w,className:$}){const R=(0,H.l4)(),B=L(R),N=d().highlight(O,w.grammar,w.name);return g.createElement("div",{className:(0,p.cx)(B.editorField,"prism-syntax-highlight",$),"aria-label":"selector",dangerouslySetInnerHTML:{__html:N}})}const L=O=>({editorField:(0,p.css)({fontFamily:O.typography.fontFamilyMonospace,fontSize:O.typography.bodySmall.fontSize})})},37462:(ae,G,n)=>{"use strict";n.d(G,{WS:()=>A,el:()=>p,pD:()=>d});function p(g){return"values"in g}function A(g){return g==null||!Array.isArray(g)?!1:g.length?"exemplars"in g[0]:!1}var d=(g=>(g.Auto="__auto",g.Verbose="__verbose",g.Custom="__custom",g))(d||{})},72097:(ae,G,n)=>{ae.exports=n(5048)}}]);

//# sourceMappingURL=6303.162b46605b5c56043489.js.map