(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[3988],{12850:(ge,Z,l)=>{"use strict";l.d(Z,{ZP:()=>d});var x=l(60234),Q=l(6570),r=l(65237),_=l(21886),W=l(28704),L=l(96229),C=l(25204),w=l(6335),j=l(48389),$=l(93048),V=l(69749);function K(m){return typeof m=="object"&&m!==null&&"isCanceled"in m}const B=m=>{let s=!1;return{promise:new Promise((o,c)=>{const h={isCanceled:!0};m.then(y=>s?c(h):o(y)),m.catch(y=>c(s?h:y))}),cancel(){s=!0}}};var te=l(78007),se=l(16202),ie=l(48954),Y=l(16693),oe=l(6741),ce=l(42505),pe=l(96682),Ee=l(36858);const ue="{}",J="__name__",be=25;function ne(m){let s="";const u=[];for(const o of m)if((o.name===J||o.selected)&&o.values&&o.values.length>0){const c=o.values.filter(h=>h.selected).map(h=>h.name);c.length>1?u.push(`${o.name}=~"${c.map(te.tU).join("|")}"`):c.length===1&&(o.name===J?s=c[0]:u.push(`${o.name}="${(0,te.U9)(c[0])}"`))}return[s,"{",u.join(","),"}"].join("")}function Le(m,s,u){return m.map(o=>{const c=s[o.name];if(c){let h;if(o.name===u&&o.values)h=o.values;else{const y=new Set(o.values?.filter(E=>E.selected).map(E=>E.name)||[]);h=c.map(E=>({name:E,selected:y.has(E)}))}return{...o,loading:!1,values:h,hidden:!c,facets:h.length}}return{...o,loading:!1,hidden:!c,values:void 0,facets:0}})}const xe=(0,ie.B)(m=>({wrapper:x.css`
    background-color: ${m.colors.background.secondary};
    padding: ${m.spacing(1)};
    width: 100%;
  `,list:x.css`
    margin-top: ${m.spacing(1)};
    display: flex;
    flex-wrap: wrap;
    max-height: 200px;
    overflow: auto;
    align-content: flex-start;
  `,section:x.css`
    & + & {
      margin: ${m.spacing(2)} 0;
    }
    position: relative;
  `,selector:x.css`
    font-family: ${m.typography.fontFamilyMonospace};
    margin-bottom: ${m.spacing(1)};
  `,status:x.css`
    padding: ${m.spacing(.5)};
    color: ${m.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:x.css`
    opacity: 1;
  `,error:x.css`
    color: ${m.colors.error.main};
  `,valueList:x.css`
    margin-right: ${m.spacing(1)};
    resize: horizontal;
  `,valueListWrapper:x.css`
    border-left: 1px solid ${m.colors.border.medium};
    margin: ${m.spacing(1)} 0;
    padding: ${m.spacing(1)} 0 ${m.spacing(1)} ${m.spacing(1)};
  `,valueListArea:x.css`
    display: flex;
    flex-wrap: wrap;
    margin-top: ${m.spacing(1)};
  `,valueTitle:x.css`
    margin-left: -${m.spacing(.5)};
    margin-bottom: ${m.spacing(1)};
  `,validationStatus:x.css`
    padding: ${m.spacing(.5)};
    margin-bottom: ${m.spacing(1)};
    color: ${m.colors.text.maxContrast};
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  `}));class Te extends r.Component{constructor(){super(...arguments),this.valueListsRef=r.createRef(),this.state={labels:[],labelSearchTerm:"",metricSearchTerm:"",status:"Ready",error:"",validationStatus:"",valueSearchTerm:""},this.onChangeLabelSearch=s=>{this.setState({labelSearchTerm:s.target.value})},this.onChangeMetricSearch=s=>{this.setState({metricSearchTerm:s.target.value})},this.onChangeValueSearch=s=>{this.setState({valueSearchTerm:s.target.value})},this.onClickRunQuery=()=>{const s=ne(this.state.labels);this.props.onChange(s)},this.onClickRunRateQuery=()=>{const u=`rate(${ne(this.state.labels)}[$__rate_interval])`;this.props.onChange(u)},this.onClickClear=()=>{this.setState(s=>({labels:s.labels.map(o=>({...o,values:void 0,selected:!1,loading:!1,hidden:!1,facets:void 0})),labelSearchTerm:"",metricSearchTerm:"",status:"",error:"",validationStatus:"",valueSearchTerm:""})),this.props.deleteLastUsedLabels(),this.fetchValues(J,ue)},this.onClickLabel=(s,u,o)=>{const c=this.state.labels.find(E=>E.name===s);if(!c)return;const h=!c.selected;let y={selected:h};if(c.values&&!h){const E=c.values.map(S=>({...S,selected:!1}));y={...y,facets:0,values:E}}this.setState({labelSearchTerm:""}),this.updateLabelState(s,y,"",()=>this.doFacettingForLabel(s))},this.onClickValue=(s,u,o)=>{const c=this.state.labels.find(y=>y.name===s);if(!c||!c.values)return;this.setState({labelSearchTerm:""});const h=c.values.map(y=>({...y,selected:y.name===u?!y.selected:y.selected}));this.updateLabelState(s,{values:h},"",()=>this.doFacetting(s))},this.onClickMetric=(s,u,o)=>{const c=this.state.labels.find(E=>E.name===s);if(!c||!c.values)return;this.setState({metricSearchTerm:""});const h=c.values.map(E=>({...E,selected:E.name===u||E.selected?!E.selected:E.selected})),y=h.some(E=>E.selected);this.updateLabelState(s,{selected:y,values:h},"",()=>this.doFacetting(s))},this.onClickValidate=()=>{const s=ne(this.state.labels);this.validateSelector(s)},this.doFacetting=s=>{const u=ne(this.state.labels);if(u===ue){const o=this.state.labels.map(c=>({...c,facets:0,values:void 0,hidden:!1}));this.setState({labels:o},()=>{this.state.labels.forEach(c=>(c.selected||c.name===J)&&this.fetchValues(c.name,u))})}else this.fetchSeries(u,s)}}updateLabelState(s,u,o="",c){this.setState(h=>{const y=h.labels.map(S=>S.name===s?{...S,...u}:S),E=o?"":h.error;return{labels:y,status:o,error:E,validationStatus:""}},c)}componentDidMount(){const{languageProvider:s,lastUsedLabels:u}=this.props;if(s){const o=u;s.start().then(()=>{let c=s.getLabelKeys();this.fetchValues(J,ue);const h=c.map((y,E,S)=>({name:y,selected:o.includes(y),loading:!1}));this.setState({labels:h},()=>{this.state.labels.forEach(y=>{y.selected&&this.fetchValues(y.name,ue)})})})}}doFacettingForLabel(s){const u=this.state.labels.find(c=>c.name===s);if(!u)return;const o=this.state.labels.filter(c=>c.selected).map(c=>c.name);this.props.storeLastUsedLabels(o),u.selected?u.values||this.fetchValues(s,ne(this.state.labels)):this.doFacetting()}async fetchValues(s,u){const{languageProvider:o}=this.props;this.updateLabelState(s,{loading:!0},`Fetching values for ${s}`);try{let c=await o.getLabelValues(s);if(u!==ne(this.state.labels)){this.updateLabelState(s,{loading:!1});return}const h=[],{metricsMetadata:y}=o;for(const E of c){const S={name:E};if(s===J&&y){const v=y[E];v&&(S.details=`(${v.type}) ${v.help}`)}h.push(S)}this.updateLabelState(s,{values:h,loading:!1})}catch(c){console.error(c)}}async fetchSeries(s,u){const{languageProvider:o}=this.props;u&&this.updateLabelState(u,{loading:!0},`Facetting labels for ${s}`);try{const c=await o.fetchSeriesLabels(s,!0);if(s!==ne(this.state.labels)){u&&this.updateLabelState(u,{loading:!1});return}if(Object.keys(c).length===0){this.setState({error:`Empty results, no matching label for ${s}`});return}const h=Le(this.state.labels,c,u);this.setState({labels:h,error:""}),u&&this.updateLabelState(u,{loading:!1})}catch(c){console.error(c)}}async validateSelector(s){const{languageProvider:u}=this.props;this.setState({validationStatus:`Validating selector ${s}`,error:""});const o=await u.fetchSeries(s);this.setState({validationStatus:`Selector is valid (${o.length} series found)`})}render(){const{theme:s}=this.props,{labels:u,labelSearchTerm:o,metricSearchTerm:c,status:h,error:y,validationStatus:E,valueSearchTerm:S}=this.state,v=xe(s);if(u.length===0)return r.createElement("div",{className:v.wrapper},r.createElement(Y.u,{text:"Loading labels..."}));let P=u.find(T=>T.name===J);P&&c&&(P={...P,values:P.values?.filter(T=>T.selected||T.name.includes(c))});let F=u.filter(T=>!T.hidden&&T.name!==J);o&&(F=F.filter(T=>T.selected||T.name.includes(o)));let z=F.filter(T=>T.selected&&T.values);S&&(z=z.map(T=>({...T,values:T.values?.filter(H=>H.selected||H.name.includes(S))})));const me=ne(this.state.labels),D=me===ue,k=P?.values?.length||0;return r.createElement("div",{className:v.wrapper},r.createElement(oe.Lh,{align:"flex-start",spacing:"lg"},r.createElement("div",null,r.createElement("div",{className:v.section},r.createElement(ce._,{description:"Once a metric is selected only possible labels are shown."},"1. Select a metric"),r.createElement("div",null,r.createElement(pe.I,{onChange:this.onChangeMetricSearch,"aria-label":"Filter expression for metric",value:c})),r.createElement("div",{role:"list",className:v.valueListWrapper},r.createElement(se.t7,{height:Math.min(450,k*be),itemCount:k,itemSize:be,itemKey:T=>P.values[T].name,width:300,className:v.valueList},({index:T,style:H})=>{const re=P?.values?.[T];return re?r.createElement("div",{style:H},r.createElement(Ee._,{name:P.name,value:re?.name,title:re.details,active:re?.selected,onClick:this.onClickMetric,searchTerm:c})):null})))),r.createElement("div",null,r.createElement("div",{className:v.section},r.createElement(ce._,{description:"Once label values are selected, only possible label combinations are shown."},"2. Select labels to search in"),r.createElement("div",null,r.createElement(pe.I,{onChange:this.onChangeLabelSearch,"aria-label":"Filter expression for label",value:o})),r.createElement("div",{className:v.list,style:{height:120}},F.map(T=>r.createElement(Ee._,{key:T.name,name:T.name,loading:T.loading,active:T.selected,hidden:T.hidden,facets:T.facets,onClick:this.onClickLabel,searchTerm:o})))),r.createElement("div",{className:v.section},r.createElement(ce._,{description:"Use the search field to find values across selected labels."},"3. Select (multiple) values for your labels"),r.createElement("div",null,r.createElement(pe.I,{onChange:this.onChangeValueSearch,"aria-label":"Filter expression for label values",value:S})),r.createElement("div",{className:v.valueListArea,ref:this.valueListsRef},z.map(T=>r.createElement("div",{role:"list",key:T.name,"aria-label":`Values for ${T.name}`,className:v.valueListWrapper},r.createElement("div",{className:v.valueTitle},r.createElement(Ee._,{name:T.name,loading:T.loading,active:T.selected,hidden:T.hidden,facets:T.facets||T.values?.length,onClick:this.onClickLabel})),r.createElement(se.t7,{height:Math.min(200,be*(T.values?.length||0)),itemCount:T.values?.length||0,itemSize:28,itemKey:H=>T.values[H].name,width:200,className:v.valueList},({index:H,style:re})=>{const fe=T.values?.[H];return fe?r.createElement("div",{style:re},r.createElement(Ee._,{name:T.name,value:fe?.name,active:fe?.selected,onClick:this.onClickValue,searchTerm:S})):null}))))))),r.createElement("div",{className:v.section},r.createElement(ce._,null,"4. Resulting selector"),r.createElement("div",{"aria-label":"selector",className:v.selector},me),E&&r.createElement("div",{className:v.validationStatus},E),r.createElement(oe.Lh,null,r.createElement(j.zx,{"aria-label":"Use selector for query button",disabled:D,onClick:this.onClickRunQuery},"Use query"),r.createElement(j.zx,{"aria-label":"Use selector as metrics button",variant:"secondary",disabled:D,onClick:this.onClickRunRateQuery},"Use as rate query"),r.createElement(j.zx,{"aria-label":"Validate submit button",variant:"secondary",disabled:D,onClick:this.onClickValidate},"Validate selector"),r.createElement(j.zx,{"aria-label":"Selector clear button",variant:"secondary",onClick:this.onClickClear},"Clear"),r.createElement("div",{className:(0,x.cx)(v.status,(h||y)&&v.statusShowing)},r.createElement("span",{className:y?v.error:""},y||h)))))}}const A=(0,$.HE)(Te),ve=r.lazy(()=>l.e(6031).then(l.bind(l,87753))),Se=m=>r.createElement(r.Suspense,{fallback:null},r.createElement(ve,{...m})),ae=m=>{const s=(0,r.useRef)(null),{onRunQuery:u,onChange:o,...c}=m,h=S=>{s.current=S,o(S),u()},y=S=>{o(S)},E=S=>{o(S)};return r.createElement(Se,{onChange:E,onRunQuery:h,onBlur:y,...c})},Re="__recording_rules__",de="grafana.datasources.prometheus.browser.labels";function Ie(m,s,u){return m?"(Disabled)":s?u?"Metrics browser":"(No metrics found)":"Loading metrics..."}function le(m,{typeaheadContext:s,typeaheadText:u}){switch(s){case"context-labels":{const o=DOMUtil.getNextCharacter();(!o||o==="}"||o===",")&&(m+="=");break}case"context-label-values":{u.match(/^(!?=~?"|")/)||(m=`"${m}`),DOMUtil.getNextCharacter()!=='"'&&(m=`${m}"`);break}default:}return m}class p extends r.PureComponent{constructor(s,u){super(s,u),this.refreshHint=()=>{const{datasource:o,query:c,data:h}=this.props,y=o.getInitHints(),E=y.length>0?y[0]:null;if(!h||h.series.length===0){this.setState({hint:E});return}const S=(0,_.aY)(h.series[0])?h.series.map(_.Zr):h.series,v=o.getQueryHints(c,S);let P=v.length>0?v[0]:null;this.setState({hint:P??E})},this.refreshMetrics=async()=>{const{datasource:{languageProvider:o}}=this.props;this.languageProviderInitializationPromise=B(o.start());try{const c=await this.languageProviderInitializationPromise.promise;await Promise.all(c),this.onUpdateLanguage()}catch(c){if(!(K(c)&&c.isCanceled))throw c}},this.onChangeLabelBrowser=o=>{this.onChangeQuery(o,!0),this.setState({labelBrowserVisible:!1})},this.onChangeQuery=(o,c)=>{const{query:h,onChange:y,onRunQuery:E}=this.props;if(y){const S={...h,expr:o};y(S),c&&E&&E()}},this.onClickChooserButton=()=>{this.setState(o=>({labelBrowserVisible:!o.labelBrowserVisible})),(0,W.ff)("user_grafana_prometheus_metrics_browser_clicked",{editorMode:this.state.labelBrowserVisible?"metricViewClosed":"metricViewOpen",app:this.props?.app??""})},this.onClickHintFix=()=>{const{datasource:o,query:c,onChange:h,onRunQuery:y}=this.props,{hint:E}=this.state;E?.fix?.action&&h(o.modifyQuery(c,E.fix.action)),y()},this.onUpdateLanguage=()=>{const{datasource:{languageProvider:o}}=this.props,{metrics:c}=o;c&&this.setState({syntaxLoaded:!0})},this.onTypeahead=async o=>{const{datasource:{languageProvider:c}}=this.props;if(!c)return{suggestions:[]};const{history:h}=this.props,{prefix:y,text:E,value:S,wrapperClasses:v,labelKey:P}=o;return await c.provideCompletionItems({text:E,value:S,prefix:y,wrapperClasses:v,labelKey:P},{history:h})},this.plugins=[(0,L.h)(),(0,C.Z)({onlyIn:o=>o.type==="code_block",getSyntax:o=>"promql"},{...Q.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(s){const{data:u,datasource:{languageProvider:o},range:c}=this.props;o!==s.datasource.languageProvider&&this.setState({syntaxLoaded:!1});const h=this.rangeChangedToRefresh(c,s.range);(o!==s.datasource.languageProvider||h)&&this.refreshMetrics(),u&&s.data&&s.data.series!==u.series&&this.refreshHint()}rangeChangedToRefresh(s,u){if(s&&u){const o=(0,te.o8)(s.from.valueOf())===(0,te.o8)(u.from.valueOf()),c=(0,te.o8)(s.to.valueOf())===(0,te.o8)(u.to.valueOf());return!(o&&c)}return!1}render(){const{datasource:s,datasource:{languageProvider:u},query:o,ExtraFieldElement:c,history:h=[],theme:y}=this.props,{labelBrowserVisible:E,syntaxLoaded:S,hint:v}=this.state,P=u.metrics.length>0,F=Ie(s.lookupsDisabled,S,P),z=!(S&&P);return r.createElement(V.G,{storageKey:de,defaultValue:[]},(me,D,k)=>r.createElement(r.Fragment,null,r.createElement("div",{className:"gf-form-inline gf-form-inline--xs-view-flex-column flex-grow-1","data-testid":this.props["data-testid"]},r.createElement("button",{className:"gf-form-label query-keyword pointer",onClick:this.onClickChooserButton,disabled:z,type:"button"},F,r.createElement(w.J,{name:E?"angle-down":"angle-right"})),r.createElement("div",{className:"gf-form gf-form--grow flex-shrink-1 min-width-15"},r.createElement(ae,{languageProvider:u,history:h,onChange:this.onChangeQuery,onRunQuery:this.props.onRunQuery,initialValue:o.expr??"",placeholder:"Enter a PromQL query\u2026"}))),E&&r.createElement("div",{className:"gf-form"},r.createElement(A,{languageProvider:u,onChange:this.onChangeLabelBrowser,lastUsedLabels:me||[],storeLastUsedLabels:D,deleteLastUsedLabels:k})),c,v?r.createElement("div",{className:"query-row-break"},r.createElement("div",{className:"prom-query-field-info text-warning"},v.label," ",v.fix?r.createElement("button",{type:"button",className:(0,x.cx)((0,j.gN)(y),"text-link","muted"),onClick:this.onClickHintFix},v.fix.label):null)):null))}}const d=(0,$.HE)(p)},53988:(ge,Z,l)=>{"use strict";l.d(Z,{QG:()=>je,vQ:()=>Ze});var x=l(89949),Q=l(15285),r=l(65237),_=l(91826),W=l(78209),L=l(45383),C=l(15084),w=l(6857),j=l(87872),$=l(39343),V=l(76970),K=l(56361),B=l(56469),te=l(62870),se=l.n(te),ie=l(71534),Y=l(65996),oe=l(81859),ce=l(79432),pe=l(88657),Ee=l(96891),ue=l(55041),J=l(66434),be=l(89050),ne=l(86447),Le=l(36203),xe=l(15993),Te=l(94332),A=l(70176),ve=l(18819),Se=l(25287),ae=l(66917),Re=l(43326),de=l(96682),Ie=l(55601);function le(b){const e=b.annotation,t=b.onAnnotationChange,a={expr:e.expr,refId:e.name,interval:e.step};return r.createElement(r.Fragment,null,r.createElement(ae.EditorRows,null,r.createElement(Ie.j,{...b,query:a,showExplain:!1,onChange:i=>{t({...e,expr:i.expr})}}),r.createElement(ae.EditorRow,null,r.createElement(ae.EditorField,{label:"Min step",tooltip:r.createElement(r.Fragment,null,"An additional lower limit for the step parameter of the Prometheus query and for the"," ",r.createElement("code",null,"$__interval")," and ",r.createElement("code",null,"$__rate_interval")," variables.")},r.createElement(Re.H,{type:"text","aria-label":"Set lower limit for the step parameter",placeholder:"auto",minWidth:10,onCommitChange:i=>{t({...e,step:i.currentTarget.value})},defaultValue:a.interval})))),r.createElement(ae.Space,{v:.5}),r.createElement(ae.EditorRow,null,r.createElement(ae.EditorField,{label:"Title",tooltip:"Use either the name or a pattern. For example, {{instance}} is replaced with label value for the label instance."},r.createElement(de.I,{type:"text",placeholder:"{{alertname}}",value:e.titleFormat,onChange:i=>{t({...e,titleFormat:i.currentTarget.value})}})),r.createElement(ae.EditorField,{label:"Tags"},r.createElement(de.I,{type:"text",placeholder:"label1,label2",value:e.tagKeys,onChange:i=>{t({...e,tagKeys:i.currentTarget.value})}})),r.createElement(ae.EditorField,{label:"Text",tooltip:"Use either the name or a pattern. For example, {{instance}} is replaced with label value for the label instance."},r.createElement(de.I,{type:"text",placeholder:"{{instance}}",value:e.textFormat,onChange:i=>{t({...e,textFormat:i.currentTarget.value})}})),r.createElement(ae.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."},r.createElement(ae.EditorSwitch,{value:e.useValueForTime,onChange:i=>{t({...e,useValueForTime:i.currentTarget.value})}}))))}var p=l(9111),d=l(78007),m=l(53632);class s{constructor(e,t){this.datasource=e,this.query=t,this.datasource=e,this.query=t,this.range=(0,xe.$t)().timeRange()}process(){const e=/^label_names\(\)\s*$/,t=/^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]*)\)\s*$/,a=/^metrics\((.+)\)\s*$/,i=/^query_result\((.+)\)\s*$/;if(this.query.match(e))return this.datasource.getTagKeys();const f=this.query.match(t);if(f)return f[1]?this.labelValuesQuery(f[2],f[1]):this.labelValuesQuery(f[2]);const g=this.query.match(a);if(g)return this.metricNameQuery(g[1]);const I=this.query.match(i);return I?(0,W.n)(this.queryResultQuery(I[1])):["label_values()","metrics()","query_result()"].includes(this.query)?Promise.resolve([]):this.metricNameAndLabelsQuery(this.query)}labelValuesQuery(e,t){const a=(0,d.jj)(this.range.from,!1),i=(0,d.jj)(this.range.to,!0),n={...t&&{"match[]":t},start:a.toString(),end:i.toString()};if(!t||this.datasource.hasLabelsMatchAPISupport()){const f=`/api/v1/label/${e}/values`;return this.datasource.metadataRequest(f,n).then(g=>(0,x.map)(g.data.data,I=>({text:I})))}else{const f="/api/v1/series";return this.datasource.metadataRequest(f,n).then(g=>{const I=(0,x.map)(g.data.data,R=>R[e]||"").filter(R=>R!=="");return(0,x.uniq)(I).map(R=>({text:R,expandable:!0}))})}}metricNameQuery(e){const t=(0,d.jj)(this.range.from,!1),a=(0,d.jj)(this.range.to,!0),i={start:t.toString(),end:a.toString()},n="/api/v1/label/__name__/values";return this.datasource.metadataRequest(n,i).then(f=>(0,x.chain)(f.data.data).filter(g=>new RegExp(e).test(g)).map(g=>({text:g,expandable:!0})).value())}queryResultQuery(e){const t=(0,d.jj)(this.range.to,!0),a={expr:e};return this.datasource.performInstantQuery(a,t).pipe((0,$.U)(i=>{switch(i.data.data.resultType){case"scalar":case"string":return[{text:i.data.data.result[1]||"",expandable:!1}];case"vector":return(0,x.map)(i.data.data.result,n=>{let f=n.metric.__name__||"";return delete n.metric.__name__,f+="{"+(0,x.map)(n.metric,(g,I)=>I+'="'+g+'"').join(",")+"}",f+=" "+n.value[1]+" "+n.value[0]*1e3,{text:f,expandable:!0}});default:throw Error(`Unknown/Unhandled result type: [${i.data.data.resultType}]`)}}))}metricNameAndLabelsQuery(e){const t=(0,d.jj)(this.range.from,!1),a=(0,d.jj)(this.range.to,!0),i={"match[]":e,start:t.toString(),end:a.toString()},n="/api/v1/series",f=this;return this.datasource.metadataRequest(n,i).then(g=>(0,x.map)(g.data.data,I=>({text:f.datasource.getOriginalMetricName(I),expandable:!0})))}}const u=20;function o(b,e,t){const a=[];if(b.trim().match(/^\w+_bucket$|^\w+_bucket{.*}$/)){const n="Selected metric has buckets.";a.push({type:"HISTOGRAM_QUANTILE",label:n,fix:{label:"Consider calculating aggregated quantile by adding histogram_quantile().",action:{type:"ADD_HISTOGRAM_QUANTILE",query:b}}})}if(b.indexOf("rate(")===-1&&b.indexOf("increase(")===-1){const n=b.match(/\b(\w+_(total|sum|count))\b/);let f=n?n[1]:"";const g=t?.languageProvider?.metricsMetadata;let I=!1;if(g&&(f=Array.from(b.matchAll(/\$?[a-zA-Z_:][a-zA-Z0-9_:]*/g)).map(([N])=>N).filter(N=>!N.startsWith("$")).flatMap(N=>N.split(":")).find(N=>{const M=g[N];return M&&M.type.toLowerCase()==="counter"?(I=!0,!0):!1})??""),f){const R=b.trim().match(/^\w+$|^\w+{.*}$/);let M=`Selected metric ${I?"is":"looks like"} a counter.`,G;R?G={label:"Consider calculating rate of counter by adding rate().",action:{type:"ADD_RATE",query:b}}:M=`${M} Consider calculating rate of counter by adding rate().`,a.push({type:"APPLY_RATE",label:M,fix:G})}}if(t&&t.ruleMappings){const n=t.ruleMappings,f=Object.keys(n).reduce((g,I)=>b.search(I)>-1?{...g,[I]:n[I]}:g,{});if((0,x.size)(f)>0){const g="Query contains recording rules.";a.push({type:"EXPAND_RULES",label:g,fix:{label:"Expand rules",action:{type:"EXPAND_RULES",query:b,options:f}}})}}return e&&e.length>=u&&b.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:b,preventSubmit:!0}}}),a}function c(b){const e=[];return b.directUrl.includes("/loki")&&!b.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"}),b.lookupsDisabled&&e.push({label:"Labels and metrics lookup was disabled in data source settings.",type:"INFO"}),e}var h=l(97341),y=l(28704),E=l(49784);function S(b,e,t){const{app:a,targets:i}=e;if(!(a===ie.zj.Dashboard||a===ie.zj.PanelViewer))for(const n of i)(0,y.ff)("grafana_prometheus_query_executed",{app:a,grafana_version:E.v.buildInfo.version,has_data:b.data.some(f=>f.length>0),has_error:b.error!==void 0,expr:n.expr,format:n.format,instant:n.instant,range:n.range,exemplar:n.exemplar,hinting:n.hinting,interval:n.interval,intervalFactor:n.intervalFactor,utcOffsetSec:n.utcOffsetSec,legend:n.legendFormat,valueWithRefId:n.valueWithRefId,requestId:e.requestId,showingGraph:n.showingGraph,showingTable:n.showingTable,editor_mode:n.editorMode,simultaneously_sent_query_count:i.length,time_range_from:e?.range?.from?.toISOString(),time_range_to:e?.range?.to?.toISOString(),time_taken:Date.now()-t.getTime()})}var v=l(57625),P=l(91053),F=l(29832),z=l(10808),me=l(54805),D=l(1163),k=l(94795),T=l(15446);const H=/^label_names\(\)\s*$/,re=/^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]*)\)\s*$/,fe=/^metrics\((.+)\)\s*$/,Qe=/^query_result\((.+)\)\s*$/;function Ne(b){if(typeof b!="string")return b;const e={refId:"PrometheusDatasource-VariableQuery",qryType:v.jo.LabelNames},t=b.match(H);if(t)return{...e,qryType:v.jo.LabelNames};const a=b.match(re);if(a){const f=a[2],g=a[1];return g?{...e,qryType:v.jo.LabelValues,label:f,metric:g}:{...e,qryType:v.jo.LabelValues,label:f}}const i=b.match(fe);if(i)return{...e,qryType:v.jo.MetricNames,metric:i[1]};const n=b.match(Qe);return n?{...e,qryType:v.jo.VarQueryResult,varQuery:n[1]}:!t&&!a&&!i&&!n?{...e,qryType:v.jo.SeriesQuery,seriesQuery:b}:e}function We(b){switch(b.qryType){case v.jo.LabelNames:return"label_names()";case v.jo.LabelValues:return b.metric?`label_values(${b.metric},${b.label})`:`label_values(${b.label})`;case v.jo.MetricNames:return`metrics(${b.metric})`;case v.jo.VarQueryResult:return`query_result(${we(b.varQuery)})`;case v.jo.SeriesQuery:return""+b.seriesQuery}return""}function we(b){return b?b.replace(/[\r\n]+/gm,""):""}const _e=[{label:"Label names",value:v.jo.LabelNames},{label:"Label values",value:v.jo.LabelValues},{label:"Metrics",value:v.jo.MetricNames},{label:"Query result",value:v.jo.VarQueryResult},{label:"Series query",value:v.jo.SeriesQuery}],Ke="PrometheusVariableQueryEditor-VariableQuery",He=({onChange:b,query:e,datasource:t})=>{const[a,i]=(0,r.useState)(void 0),[n,f]=(0,r.useState)(""),[g,I]=(0,r.useState)(""),[R,N]=(0,r.useState)(""),[M,G]=(0,r.useState)(""),[O,q]=(0,r.useState)([]);(0,r.useEffect)(()=>{if(!e)return;const U=Ge(e);i(U.qryType),f(U.label??""),I(U.metric??""),N(U.varQuery??""),G(U.seriesQuery??""),U.label&&q([{label:U.label,value:U.label}])},[e]),(0,r.useEffect)(()=>{a===v.jo.LabelValues&&t.getTagKeys().then(U=>{q(U.map(({text:Me})=>({label:Me,value:Me})))})},[t,a]);const X=U=>{const he=We({qryType:U,label:n,metric:g,varQuery:R,seriesQuery:M,refId:"PrometheusVariableQueryEditor-VariableQuery"});b({query:he,refId:Ke})},Ae=U=>{i(U.value),U.value===v.jo.LabelNames&&X(U.value)},Ce=U=>{f(U.value??"")},Pe=U=>{I(U.currentTarget.value)},Oe=U=>{N(U.currentTarget.value)},De=U=>{G(U.currentTarget.value)},ye=()=>{(a===v.jo.LabelNames||a===v.jo.LabelValues&&n||a===v.jo.MetricNames&&g||a===v.jo.VarQueryResult&&R||a===v.jo.SeriesQuery&&M)&&X(a)};return r.createElement(me.Z,null,r.createElement(D._,{label:"Query Type",labelWidth:20,tooltip:r.createElement("div",null,"The Prometheus data source plugin provides the following query types for template variables.")},r.createElement(k.Ph,{placeholder:"Select query type","aria-label":"Query type",onChange:Ae,onBlur:ye,value:a,options:_e,width:25})),a===v.jo.LabelValues&&r.createElement(r.Fragment,null,r.createElement(D._,{label:"Label",labelWidth:20,required:!0,tooltip:r.createElement("div",null,"Returns a list of label values for the label name in all metrics unless the metric is specified.")},r.createElement(k.Ph,{"aria-label":"label-select",onChange:Ce,onBlur:ye,value:n,options:O,width:25,allowCustomValue:!0})),r.createElement(D._,{label:"Metric",labelWidth:20,tooltip:r.createElement("div",null,"Optional: returns a list of label values for the label name in the specified metric.")},r.createElement(de.I,{type:"text","aria-label":"Metric selector",placeholder:"Optional metric selector",value:g,onChange:Pe,onBlur:ye,width:25}))),a===v.jo.MetricNames&&r.createElement(r.Fragment,null,r.createElement(D._,{label:"Metric Regex",labelWidth:20,tooltip:r.createElement("div",null,"Returns a list of metrics matching the specified metric regex.")},r.createElement(de.I,{type:"text","aria-label":"Metric selector",placeholder:"Metric Regex",value:g,onChange:Pe,onBlur:ye,width:25}))),a===v.jo.VarQueryResult&&r.createElement(r.Fragment,null,r.createElement(D._,{label:"Query",labelWidth:20,tooltip:r.createElement("div",null,"Returns a list of Prometheus query results for the query. This can include Prometheus functions, i.e. sum(go_goroutines).")},r.createElement(T.K,{type:"text","aria-label":"Prometheus Query",placeholder:"Prometheus Query",value:R,onChange:Oe,onBlur:ye,cols:100}))),a===v.jo.SeriesQuery&&r.createElement(r.Fragment,null,r.createElement(D._,{label:"Series Query",labelWidth:20,tooltip:r.createElement("div",null,'Enter enter a metric with labels, only a metric or only labels, i.e. go_goroutines{instance="localhost:9090"}, go_goroutines, or {instance="localhost:9090"}. Returns a list of time series associated with the entered data.')},r.createElement(de.I,{type:"text","aria-label":"Series Query",placeholder:"Series Query",value:M,onChange:De,onBlur:ye,width:100}))))};function Ge(b){return typeof b=="string"?Ne(b):b.query?Ne(b.query):b}class ze extends F.Mg{constructor(e,t=(0,z.J)(),a=(0,xe.$t)()){super(),this.datasource=e,this.templateSrv=t,this.timeSrv=a,this.editor=He,this.query=this.query.bind(this)}query(e){let t;if(typeof e.targets[0]=="string"?t=e.targets[0]:t=e.targets[0].query,!t)return(0,L.of)({data:[]});const a={...e.scopedVars,__interval:{text:this.datasource.interval,value:this.datasource.interval},__interval_ms:{text:Y.intervalToMs(this.datasource.interval),value:Y.intervalToMs(this.datasource.interval)},...this.datasource.getRangeScopedVars(this.timeSrv.timeRange())},i=this.templateSrv.replace(t,a,this.datasource.interpolateQueryExpr),n=new s(this.datasource,i);return(0,P.D)(n.process()).pipe((0,$.U)(g=>({data:g})))}}const Ue="60s",ke=["api/v1/query","api/v1/query_range","api/v1/series","api/v1/labels"],je="-Instant";class Ze extends pe.CK{constructor(e,t=(0,Te.J)(),a=(0,xe.$t)(),i){super(e),this.templateSrv=t,this.timeSrv=a,this.metricsNameCache=new Q.Z({max:10}),this.init=async()=>{this.loadRules(),this.exemplarsAvailable=await this.areExemplarsAvailable()},this.prepareTargets=(n,f,g)=>{const I=[],R=[],N=(0,x.cloneDeep)(n.targets);for(const M of N){if(!M.expr||M.hide)continue;const G=this.languageProvider.histogramMetrics.find(O=>M.expr.includes(O));if(n.app===ie.zj.Explore&&M.range===M.instant){const O=(0,x.cloneDeep)(M);O.format="table",O.instant=!0,O.range=!1,O.valueWithRefId=!0,delete O.maxDataPoints;const q=(0,x.cloneDeep)(M);if(q.format="time_series",q.instant=!1,O.range=!0,M.exemplar){if(!G||G&&!R.some(X=>X.expr.includes(G))){const X=(0,x.cloneDeep)(M);X.instant=!1,I.push(this.createQuery(X,n,f,g)),R.push(X)}O.exemplar=!1,q.exemplar=!1}R.push(O,q),I.push(this.createQuery(O,n,f,g),this.createQuery(q,n,f,g))}else if(M.instant&&n.app===ie.zj.Explore){const O=(0,x.cloneDeep)(M);O.format="table",I.push(this.createQuery(O,n,f,g)),R.push(O)}else{if(M.exemplar&&!M.instant){if(!G||G&&!R.some(O=>O.expr.includes(G))){const O=(0,x.cloneDeep)(M);I.push(this.createQuery(O,n,f,g)),R.push(O)}M.exemplar=!1}I.push(this.createQuery(M,n,f,g)),R.push(M)}}return{queries:I,activeTargets:R}},this.handleErrors=(n,f)=>{const g={message:n&&n.statusText||"Unknown error during query transaction. Please check JS console logs.",refId:f.refId};return n.data?typeof n.data=="string"?g.message=n.data:n.data.error&&(g.message=(0,ne.Xh)(n.data.error)):n.message?g.message=n.message:typeof n=="string"&&(g.message=n),g.status=n.status,g.statusText=n.statusText,g},this.processAnnotationResponse=(n,f)=>{const g=(0,Ee.z1)({data:f}).data;if(!g||!g.length)return[];const I=n.annotation,{tagKeys:R="",titleFormat:N="",textFormat:M=""}=I,G=Y.intervalToSeconds(I.step||Ue)*1e3,O=R.split(","),q=[];for(const X of g){if(X.fields.length===0)continue;const Ae=X.fields[0],Ce=X.fields[1],Pe=Ce?.labels||{},Oe=Object.keys(Pe).filter(ee=>O.includes(ee)).map(ee=>Pe[ee]),De=[];let ye=0;Ce.values.toArray().forEach(ee=>{let Fe,Ve;const Je=Ae.values.get(ye);n.annotation.useValueForTime?(Fe=Math.floor(parseFloat(ee)),Ve=1):(Fe=Math.floor(parseFloat(Je)),Ve=parseFloat(ee)),ye++,De.push([Fe,Ve])});const Me=De.filter(ee=>ee[1]>0).map(ee=>ee[0]);let he=null;for(const ee of Me){if(he&&(he.timeEnd??0)+G>=ee){he.timeEnd=ee;continue}he&&q.push(he),he={time:ee,timeEnd:ee,annotation:I,title:(0,m.W)(N,Pe),tags:Oe,text:(0,m.W)(M,Pe)}}he&&(he.timeEnd=Me[Me.length-1],q.push(he))}return q},this.type="prometheus",this.subType=A.T8.Prometheus,this.rulerEnabled=!1,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=i??new p.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 ze(this,this.templateSrv,this.timeSrv),this.exemplarsAvailable=!0,this.cacheLevel=e.jsonData.cacheLevel??v.x3.Low,this.annotations={QueryEditor:le}}getQueryDisplayText(e){return e.expr}hasLabelsMatchAPISupport(){return this._isDatasourceVersionGreaterOrEqualTo("2.24.0",A.T8.Prometheus)||this._isDatasourceVersionGreaterOrEqualTo("2.0.0",A.T8.Mimir)||this._isDatasourceVersionGreaterOrEqualTo("1.11.0",A.T8.Cortex)||this._isDatasourceVersionGreaterOrEqualTo("0.18.0",A.T8.Thanos)}_isDatasourceVersionGreaterOrEqualTo(e,t){return!this.datasourceConfigurationPrometheusVersion||!this.datasourceConfigurationPrometheusFlavor||t!==this.datasourceConfigurationPrometheusFlavor?!1:se().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 f=new Error("Browser access mode in the Prometheus datasource is no longer available. Switch to server access mode.");return(0,_._)(()=>f)}t=t||{};for(const[f,g]of this.customQueryParameters)t[f]==null&&(t[f]=g);let i=this.url+e;e.startsWith(`/api/datasources/uid/${this.uid}`)&&(i=e);const n=(0,x.defaults)(a,{url:i,method:this.httpMethod,headers:{}});return n.method==="GET"?t&&Object.keys(t).length&&(n.url=n.url+(n.url.search(/\?/)>=0?"&":"?")+Object.entries(t).map(([f,g])=>`${encodeURIComponent(f)}=${encodeURIComponent(g)}`).join("&")):(n.headers["Content-Type"]="application/x-www-form-urlencoded",n.data=t),(this.basicAuth||this.withCredentials)&&(n.withCredentials=!0),this.basicAuth&&(n.headers.Authorization=this.basicAuth),(0,ue.i)().fetch(n)}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(ke.some(i=>e.includes(i)))try{return await(0,W.n)(this._request(`/api/datasources/uid/${this.uid}/resources${e}`,t,{method:this.httpMethod,hideFromInspector:!0,showErrorAlert:!1,...a}))}catch(i){if(this.httpMethod==="POST"&&(0,ue.kW)(i)&&(i.status===405||i.status===400))console.warn("Couldn't use configured POST HTTP method for this request. Trying to use GET method instead.");else throw i}return await(0,W.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 $e(e);if(typeof e=="string")return Be(e);const a=e.map(i=>Be(i));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(f=>e.expr.includes(f)),i=t.targets.findIndex(f=>f.refId===e.refId),n=t.targets.slice(0,i).filter(f=>!f.hide);return!!(!a||a&&!n.some(f=>f.expr.includes(a)))}return!1}processTargetV2(e,t){const a=[],i={...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({...i,refId:i.refId,instant:!1},{...i,refId:i.refId+je,range:!1}):a.push(i),a}query(e){if(this.access==="proxy"){const t=e.targets.map(i=>this.processTargetV2(i,e)),a=new Date;return super.query({...e,targets:t.flat()}).pipe((0,$.U)(i=>(0,h.n)(i,e,{exemplarTraceIdDestinations:this.exemplarTraceIdDestinations})),(0,V.b)(i=>{S(i,e,a)}))}else{const t=(0,d.jj)(e.range.from,!1),a=(0,d.jj)(e.range.to,!0),{queries:i,activeTargets:n}=this.prepareTargets(e,t,a);return!i||!i.length?(0,L.of)({data:[],state:oe.Gu.Done}):e.app===ie.zj.Explore?this.exploreQuery(i,n,a):this.panelsQuery(i,n,a,e.requestId,e.scopedVars)}}exploreQuery(e,t,a){let i=e.length;const n=e.map((f,g)=>{const I=t[g],R=(0,C.z)((0,V.b)(()=>i--),(0,K.h)(N=>!N.cancelled),(0,$.U)(N=>({data:(0,h.vs)(N,{query:f,target:I,responseListLength:e.length,exemplarTraceIdDestinations:this.exemplarTraceIdDestinations}),key:f.requestId,state:i===0?oe.Gu.Done:oe.Gu.Loading})));return this.runQuery(f,a,R)});return(0,w.T)(...n)}panelsQuery(e,t,a,i,n){const f=e.map((g,I)=>{const R=t[I],N=(0,C.z)((0,K.h)(M=>!M.cancelled),(0,$.U)(M=>(0,h.vs)(M,{query:g,target:R,responseListLength:e.length,scopedVars:n,exemplarTraceIdDestinations:this.exemplarTraceIdDestinations})));return this.runQuery(g,a,N)});return(0,j.D)(f).pipe((0,$.U)(g=>({data:g.reduce((R,N)=>[...R,...N],[]),key:i,state:oe.Gu.Done})))}runQuery(e,t,a){return e.instant?this.performInstantQuery(e,t).pipe(a):e.exemplar?this.getExemplars(e).pipe((0,B.K)(()=>(0,L.of)({data:[],state:oe.Gu.Done})),a):this.performTimeSeriesQuery(e,e.start,e.end).pipe(a)}createQuery(e,t,a,i){const n={hinting:e.hinting,instant:e.instant,exemplar:e.exemplar,step:0,expr:"",refId:e.refId,start:0,end:0},f=Math.ceil(i-a);let g=Y.intervalToSeconds(t.interval);const I=Y.intervalToSeconds(this.templateSrv.replace(e.interval||t.interval,t.scopedVars)),R=e.interval?Y.intervalToSeconds(this.templateSrv.replace(e.interval,t.scopedVars)):Y.intervalToSeconds(this.interval),N=e.intervalFactor||1,M=this.adjustInterval(g,I,f,N);let G={...t.scopedVars,...this.getRangeScopedVars(t.range),...this.getRateIntervalScopedVariable(M,R)};g!==M&&(g=M,G=Object.assign({},t.scopedVars,{__interval:{text:g+"s",value:g+"s"},__interval_ms:{text:g*1e3,value:g*1e3},...this.getRateIntervalScopedVariable(g,R),...this.getRangeScopedVars(t.range)})),n.step=g;let O=e.expr;O=this.enhanceExprWithAdHocFilters(O),n.expr=this.templateSrv.replace(O,G,this.interpolateQueryExpr);const q=Xe(a,i,n.step,this.timeSrv.timeRange().to.utcOffset()*60);return n.start=q.start,n.end=q.end,this._addTracingHeaders(n,t),n}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,i){let n=a/11e3;return n>1&&(n=Math.ceil(n)),Math.max(e*i,t,n)}performTimeSeriesQuery(e,t,a){if(t>a)throw{message:"Invalid time range"};const i="/api/v1/query_range",n={query:e.expr,start:t,end:a,step:e.step};return this.queryTimeout&&(n.timeout=this.queryTimeout),this._request(i,n,{requestId:e.requestId,headers:e.headers}).pipe((0,B.K)(f=>f.cancelled?(0,L.of)(f):(0,_._)(this.handleErrors(f,e))))}performInstantQuery(e,t){const a="/api/v1/query",i={query:e.expr,time:t};return this.queryTimeout&&(i.timeout=this.queryTimeout),this._request(`/api/datasources/uid/${this.uid}/resources${a}`,i,{requestId:e.requestId,headers:e.headers}).pipe((0,B.K)(n=>n.cancelled?(0,L.of)(n):(0,_._)(this.handleErrors(n,e))))}metricFindQuery(e){if(!e)return Promise.resolve([]);const t={__interval:{text:this.interval,value:this.interval},__interval_ms:{text:Y.intervalToMs(this.interval),value:Y.intervalToMs(this.interval)},...this.getRangeScopedVars(this.timeSrv.timeRange())},a=this.templateSrv.replace(e,t,this.interpolateQueryExpr);return new s(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 f=new Error("Browser access mode in the Prometheus datasource is no longer available. Switch to server access mode.");return Promise.reject(f)}const t=e.annotation,{expr:a=""}=t;if(!a)return Promise.resolve([]);const i=e.annotation.step||Ue,n={expr:a,range:!0,instant:!1,exemplar:!1,interval:i,refId:"X",datasource:this.getRef()};return await(0,W.n)((0,ue.i)().fetch({url:"/api/ds/query",method:"POST",headers:this.getRequestHeaders(),data:{from:((0,d.jj)(e.range.from,!1)*1e3).toString(),to:((0,d.jj)(e.range.to,!0)*1e3).toString(),queries:[this.applyTemplateVariables(n,{})]},requestId:`prom-query-${t.name}`}).pipe((0,$.U)(f=>this.processAnnotationResponse(e,f.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(n=>this.languageProvider.fetchSeriesLabels(n)));let a=[];return t.map(n=>a=a.concat(Object.keys(n))),[...new Set(a)].map(n=>({text:n}))}else{const t=this.getTimeRangeParams();return(await this.metadataRequest("/api/v1/labels",t))?.data?.data?.map(i=>({text:i}))??[]}}async getTagValues(e={}){const t=this.getTimeRangeParams();return(await this.metadataRequest(`/api/v1/label/${e.key}/values`,t))?.data?.data?.map(i=>({text:i}))??[]}async getBuildInfo(){try{return await(0,Le.WG)({url:this.url,name:this.name,type:"prometheus"})}catch{return}}getBuildInfoMessage(e){const t=r.createElement(J.C,{color:"green",icon:"check",text:"Ruler API enabled"}),a=r.createElement(J.C,{color:"orange",icon:"exclamation-triangle",text:"Ruler API not enabled"}),i=r.createElement(be.u,{placement:"top",content:"Prometheus does not allow editing rules, connect to either a Mimir or Cortex datasource to manage alerts via Grafana."},r.createElement("div",null,r.createElement(J.C,{color:"red",icon:"exclamation-triangle",text:"Ruler API not supported"}))),n={[A.T8.Cortex]:"/public/app/plugins/datasource/prometheus/img/cortex_logo.svg",[A.T8.Mimir]:"/public/app/plugins/datasource/prometheus/img/mimir_logo.svg",[A.T8.Prometheus]:"/public/app/plugins/datasource/prometheus/img/prometheus_logo.svg",[A.T8.Thanos]:"/public/app/plugins/datasource/prometheus/img/thanos_logo.svg"},f={[A.T8.Cortex]:"blue",[A.T8.Mimir]:"orange",[A.T8.Prometheus]:"red",[A.T8.Thanos]:"purple"},g={[A.T8.Cortex]:"Cortex",[A.T8.Mimir]:"Mimir",[A.T8.Prometheus]:"Prometheus",[A.T8.Thanos]:"Thanos"},I=this.datasourceConfigurationPrometheusFlavor??e.application,R=r.createElement(J.C,{text:r.createElement("span",null,r.createElement("img",{style:{width:14,height:14,verticalAlign:"text-bottom"},src:n[I??A.T8.Prometheus],alt:""})," ",I?g[I]:"Unknown"),color:f[I??A.T8.Prometheus]});return r.createElement("div",{style:{display:"grid",gridTemplateColumns:"max-content max-content",rowGap:"0.5rem",columnGap:"2rem",marginTop:"1rem"}},r.createElement("div",null,"Type"),r.createElement("div",null,R),r.createElement(r.Fragment,null,r.createElement("div",null,"Ruler API"),e.application===A.T8.Prometheus&&r.createElement("div",null,i),e.application!==A.T8.Prometheus&&r.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,ce.CQ)(e-1e3),to:(0,ce.CQ)(e)}},a=await this.getBuildInfo();return(0,W.n)(this.query(t)).then(i=>!i||!i.data||i.state!==oe.Gu.Done?{status:"error",message:`Error reading Prometheus: ${i?.error?.message}`}:{status:"success",message:"Data source is working",details:a&&{verboseMessage:this.getBuildInfoMessage(a)}}).catch(i=>(console.error("Prometheus Error",i),{status:"error",message:i.message}))}interpolateVariablesInQueries(e,t){let a=e;return e&&e.length&&(a=e.map(i=>({...i,datasource:this.getRef(),expr:this.enhanceExprWithAdHocFilters(this.templateSrv.replace(i.expr,t,this.interpolateQueryExpr)),interval:this.templateSrv.replace(i.interval,t)}))),a}getQueryHints(e,t){return o(e.expr??"",t,this)}getInitHints(){return c(this)}async loadRules(){try{const t=(await this.metadataRequest("/api/v1/rules",{},{showErrorAlert:!1})).data?.data?.groups;t&&(this.ruleMappings=Ye(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,ce.CQ)().subtract(30,"minutes").valueOf().toString(),end:(0,ce.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:i,value:n}=t.options??{};i&&n&&(a=(0,Se.F)(a,i,n));break}case"ADD_FILTER_OUT":{const{key:i,value:n}=t.options??{};i&&n&&(a=(0,Se.F)(a,i,n,"!="));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,d.ll)(a,t.options));break}default:break}return{...e,expr:a}}getAdjustedInterval(){if(!ve.ZP.featureToggles.prometheusResourceBrowserCache)return this.getTimeRangeParams();const e=this.timeSrv.timeRange();return(0,d.wY)(this.cacheLevel,e)}getTimeRangeParams(){const e=this.timeSrv.timeRange();return{start:(0,d.jj)(e.from,!1).toString(),end:(0,d.jj)(e.to,!0).toString()}}getOriginalMetricName(e){return(0,h.nM)(e)}enhanceExprWithAdHocFilters(e){return this.templateSrv.getAdhocFilters(this.name).reduce((i,n)=>{const{key:f,operator:g}=n;let{value:I}=n;return(g==="=~"||g==="!~")&&(I=$e(I)),(0,Se.F)(i,f,I,g)},e)}filterQuery(e){return!(e.hide||!e.expr)}applyTemplateVariables(e,t){const a=(0,x.cloneDeep)(t);delete a.__interval,delete a.__interval_ms;const i=this.enhanceExprWithAdHocFilters(e.expr);return{...e,legendFormat:this.templateSrv.replace(e.legendFormat,a),expr:this.templateSrv.replace(i,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)}getDebounceTimeInMilliseconds(){switch(this.cacheLevel){case v.x3.Medium:return 600;case v.x3.High:return 1200;default:return 350}}getDaysToCacheMetadata(){switch(this.cacheLevel){case v.x3.Medium:return 7;case v.x3.High:return 30;default:return 1}}getCacheDurationInMinutes(){return(0,d.l3)(this.cacheLevel)}}function Xe(b,e,t,a){const i=Math.floor((e+a)/t)*t-a,n=Math.floor((b+a)/t)*t-a;return{end:i,start:n}}function Ye(b){return b.reduce((e,t)=>t.rules.filter(a=>a.type==="recording").reduce((a,i)=>({...a,[i.name]:i.query}),e),{})}function $e(b){return typeof b=="string"?b.replace(/\\/g,"\\\\").replace(/'/g,"\\\\'"):b}function Be(b){return typeof b=="string"?b.replace(/\\/g,"\\\\\\\\").replace(/[$^*{}\[\]\'+?.()|]/g,"\\\\$&"):b}},91182:(ge,Z,l)=>{"use strict";l.d(Z,{A:()=>j,n:()=>$});var x=l(65237),Q=l(66917),r=l(35560),_=l(9140),W=l(14253),L=l(30130),C=l(43153),w=l(7642);const j="Fetch all series matching metric name and label filters.",$=x.memo(({query:V})=>{const K=(0,W._)(V||"").query,B={grammar:r.ZP,name:"promql"};return x.createElement(Q.Stack,{gap:.5,direction:"column"},x.createElement(L.B,{stepNumber:1,title:x.createElement(w.U,{query:`${K.metric} ${_.Z.renderLabels(K.labels)}`,lang:B})},j),x.createElement(C.V,{stepNumber:2,queryModeller:_.Z,query:K,lang:B}))});$.displayName="PromQueryBuilderExplained"},55601:(ge,Z,l)=>{"use strict";l.d(Z,{j:()=>L});var x=l(60234),Q=l(65237),r=l(93048),_=l(12850),W=l(91182);function L(w){const{query:j,datasource:$,range:V,onRunQuery:K,onChange:B,data:te,app:se,showExplain:ie}=w,Y=(0,r.wW)(C);return Q.createElement("div",{className:Y.wrapper},Q.createElement(_.ZP,{datasource:$,query:j,range:V,onRunQuery:K,onChange:B,history:[],data:te,app:se}),ie&&Q.createElement(W.n,{query:j.expr}))}const C=w=>({wrapper:x.css`
      .gf-form {
        margin-bottom: 0;
      }
    `})},30130:(ge,Z,l)=>{"use strict";l.d(Z,{B:()=>W});var x=l(60234),Q=l(65237),r=l(80088),_=l(93048);function W({title:C,stepNumber:w,markdown:j,children:$}){const V=(0,_.wW)(L);return Q.createElement("div",{className:V.box},w!==void 0&&Q.createElement("div",{className:V.stepNumber},w),Q.createElement("div",{className:V.boxInner},C&&Q.createElement("div",{className:V.header},Q.createElement("span",null,C)),Q.createElement("div",{className:V.body},j&&Q.createElement("div",{dangerouslySetInnerHTML:{__html:(0,r.a)(j)}}),$)))}const L=C=>({box:(0,x.css)({background:C.colors.background.secondary,padding:C.spacing(1),borderRadius:C.shape.borderRadius(),position:"relative"}),boxInner:(0,x.css)({marginLeft:C.spacing(4)}),stepNumber:(0,x.css)({fontWeight:C.typography.fontWeightMedium,background:C.colors.secondary.main,width:"20px",height:"20px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",top:"10px",left:"11px",fontSize:C.typography.bodySmall.fontSize}),header:(0,x.css)({paddingBottom:C.spacing(.5),display:"flex",alignItems:"center",fontFamily:C.typography.fontFamilyMonospace}),body:(0,x.css)({color:C.colors.text.secondary,"p:last-child":{margin:0},a:{color:C.colors.text.link,textDecoration:"underline"}})})},43153:(ge,Z,l)=>{"use strict";l.d(Z,{V:()=>_});var x=l(65237),Q=l(30130),r=l(7642);function _({query:W,queryModeller:L,stepNumber:C,lang:w,onMouseEnter:j,onMouseLeave:$}){return x.createElement(x.Fragment,null,W.operations.map((V,K)=>{const B=L.getOperationDef(V.id);if(!B)return`Operation ${V.id} not found`;const te=B.renderer(V,B,"<expr>"),se=B.explainHandler?B.explainHandler(V,B):B.documentation??"no docs";return x.createElement("div",{key:K,onMouseEnter:()=>j?.(V,K),onMouseLeave:()=>$?.(V,K)},x.createElement(Q.B,{stepNumber:K+C,title:x.createElement(r.U,{query:te,lang:w}),markdown:se}))}))}},7642:(ge,Z,l)=>{"use strict";l.d(Z,{U:()=>L});var x=l(60234),Q=l(6570),r=l.n(Q),_=l(65237),W=l(93048);function L({query:w,lang:j,className:$}){const V=(0,W.l4)(),K=C(V),B=r().highlight(w,j.grammar,j.name);return _.createElement("div",{className:(0,x.cx)(K.editorField,"prism-syntax-highlight",$),"aria-label":"selector",dangerouslySetInnerHTML:{__html:B}})}const C=w=>({editorField:(0,x.css)({fontFamily:w.typography.fontFamilyMonospace,fontSize:w.typography.bodySmall.fontSize})})},97341:(ge,Z,l)=>{"use strict";l.d(Z,{Ky:()=>le,n:()=>ce,nM:()=>ae,nf:()=>Ie,vs:()=>J});var x=l(81367),Q=l(89949),r=l.n(Q),_=l(71534),W=l(19135),L=l(12554),C=l(36669),w=l(82352),j=l(37344),$=l(73570),V=l(34311),K=l(51031),B=l(10808),te=l(53632),se=l(57625);const ie=/^[+-]?inf(?:inity)?$/i,Y=(p,d)=>d.app===_.zj.Explore&&(p.meta?.custom?.resultType==="vector"||p.meta?.custom?.resultType==="scalar")?!0:d.targets.find(s=>s.refId===p.refId)?.format==="table",oe=(p,d)=>d.targets.find(s=>s.refId===p.refId)?.format==="heatmap";function ce(p,d,m){const[s,u]=(0,Q.partition)(p.data,D=>Y(D,d)),o=Ee(s),[c,h]=(0,Q.partition)(u,D=>D.meta?.custom?.resultType==="exemplar"),{exemplarTraceIdDestinations:y}=m,E=c.map(D=>{if(y?.length)for(const k of y){const T=D.fields.find(H=>H.name===k.name);if(T){const H=be(k);T.config.links=T.config.links?.length?[...T.config.links,...H]:H}}return{...D,meta:{...D.meta,dataTopic:W.w5.Annotations}}}),[S,v]=(0,Q.partition)(h,D=>oe(D,d));S.forEach(D=>{if(D.name==null){let k=D.fields.find(T=>T.name==="Value");if(k){let T=k.labels?.le;T&&(D.name=T,k.config.displayNameFromDS=T)}}});const P=(0,Q.groupBy)(S,D=>D.refId);let F=[];for(const D in P){const k=P[D],T=(0,Q.groupBy)(k,H=>{const re=H.fields.find(fe=>fe.name===L.M5);if(re?.labels&&pe in re.labels){const{le:fe,...Qe}=re?.labels;return Object.values(Qe).join()}return Object.values(re?.labels??[]).join()});(0,Q.forOwn)(T,(H,re)=>{const fe=H.sort(Ie);F.push(Re(de(fe)))})}const z=v.map(D=>({...D,meta:{...D.meta,preferredVisualisationType:"graph"}})),me=(0,Q.flatten)(F);return{...p,data:[...z,...o,...me,...E]}}const pe="le";function Ee(p){if(p.length===0||p.length===1&&p[0].length===0)return p;const d=(0,Q.groupBy)(p,"refId"),m=Object.keys(d);return m.map(u=>{const o=ue(m.length,u),c=ve({data:[],valueName:o}),h=A([]),y=[];d[u].forEach(S=>{const P=S.fields[1]?.labels??{};Object.keys(P).sort().forEach(F=>{if(!y.some(z=>z.name===F)){const z=F===pe;y.push({name:F,config:{filterable:!0},type:z?L.fS.number:L.fS.string,values:new C.G})}})}),d[u].forEach(S=>{const v=S.fields[0]?.values??new C.G,P=S.fields[1]?.values??new C.G;v.toArray().forEach(F=>h.values.add(F)),P.toArray().forEach(F=>{c.values.add(le(F));const z=S.fields[1].labels??{};y.forEach(me=>me.values.add(Te(z,me.name)))})});const E=[h,...y,c];return{refId:u,fields:E,meta:{...d[u][0].meta,preferredVisualisationType:"rawPrometheus"},length:h.values.length}})}function ue(p,d=""){return p>1?`Value #${d}`:"Value"}function J(p,d){const m={format:d.target.format,step:d.query.step,legendFormat:d.target.legendFormat,start:d.query.start,end:d.query.end,query:d.query.expr,responseListLength:d.responseListLength,scopedVars:d.scopedVars,refId:d.target.refId,valueWithRefId:d.target.valueWithRefId,meta:{preferredVisualisationType:d.query.instant?"rawPrometheus":"graph"}},s=p.data.data;if((0,se.WS)(s)){const o=[];s.forEach(y=>{const E=y.exemplars.map(S=>({[L.Ls]:S.timestamp*1e3,[L.M5]:S.value,...S.labels,...y.seriesLabels}));o.push(...E)});const c=ne(o,m),h=new w.i(c);if(h.meta={dataTopic:W.w5.Annotations},d.exemplarTraceIdDestinations?.length)for(const y of d.exemplarTraceIdDestinations){const E=h.fields.find(S=>S.name===y.name);if(E){const S=be(y);E.config.links=E.config.links?.length?[...E.config.links,...S]:S}}return[h]}if(!s?.result)return[];if(s.resultType==="scalar")return[{meta:m.meta,refId:m.refId,length:1,fields:[A([s.result]),ve({data:[s.result]})]}];if(m.format==="table")return[xe(s.result,m)];const u=[];return s.result.forEach(o=>u.push(Le(o,m))),m.format==="heatmap"?Re(de(u.sort(Ie))):u}function be(p){const d=[];if(p.datasourceUid){const s=(0,K.F)().getInstanceSettings(p.datasourceUid);s&&d.push({title:p.urlDisplayLabel||`Query with ${s?.name}`,url:"",internal:{query:{query:"${__value.raw}",queryType:"traceql"},datasourceUid:p.datasourceUid,datasourceName:s?.name??"Data source not found"}})}return p.url&&d.push({title:p.urlDisplayLabel||`Go to ${p.url}`,url:p.url,targetBlank:!0}),d}function ne(p,d){const m=d.step||15,s={},u=[];for(const y of p){const E=String(Math.floor(y[L.Ls]/1e3/m)*m*1e3);s[E]||(s[E]=[]),s[E].push(y),u.push(y[L.M5])}const o=(0,x.deviation)(u),c=Object.keys(s).sort(),h=[];for(const y of c){const E=s[y];if(E.length===1)h.push(E[0]);else{const v=E.map(P=>P[L.M5]).sort(x.descending).reduce((P,F)=>{if(P.length===0)P.push(F);else{const z=P[P.length-1];o&&z-F>=2*o&&P.push(F)}return P},[]);h.push(...v.map(P=>E.find(F=>F[L.M5]===P)))}}return h}function Le(p,d){const{name:m,labels:s}=Se(p.metric,d),u=[];if((0,se.el)(p)){const o=d.step?d.step*1e3:NaN;let c=d.start*1e3;const h=[];for(const E of p.values){let S=le(E[1]);isNaN(S)&&(S=null);const v=E[0]*1e3;for(let P=c;P<v;P+=o)h.push([P,null]);c=v+o,h.push([v,S])}const y=d.end*1e3;for(let E=c;E<=y;E+=o)h.push([E,null]);u.push(A(h,!0)),u.push(ve({data:h,parseValue:!1,labels:s,displayNameFromDS:m}))}else u.push(A([p.value])),u.push(ve({data:[p.value],labels:s,displayNameFromDS:m}));return{meta:d.meta,refId:d.refId,length:u[0].values.length,fields:u,name:m}}function xe(p,d){if(!p||p.length===0)return{meta:d.meta,refId:d.refId,length:0,fields:[]};const m=d.responseListLength>1||d.valueWithRefId?`Value #${d.refId}`:"Value",s=A([]),u=Object.keys(p.reduce((c,h)=>({...c,...h.metric}),{})).sort().map(c=>({name:c,config:{filterable:!0},type:c===pe?L.fS.number:L.fS.string,values:new C.G})),o=ve({data:[],valueName:m});return p.forEach(c=>{(0,se.el)(c)?c.values.forEach(h=>{s.values.add(h[0]*1e3),u.forEach(y=>y.values.add(Te(c.metric,y.name))),o.values.add(le(h[1]))}):(s.values.add(c.value[0]*1e3),u.forEach(h=>h.values.add(Te(c.metric,h.name))),o.values.add(le(c.value[1])))}),{meta:d.meta,refId:d.refId,length:s.values.length,fields:[s,...u,o]}}function Te(p,d){return p.hasOwnProperty(d)?d===pe?le(p[d]):p[d]:""}function A(p,d=!1){return{name:L.Ls,type:L.fS.time,config:{},values:new C.G(p.map(m=>d?m[0]:m[0]*1e3))}}function ve({data:p,valueName:d=L.M5,parseValue:m=!0,labels:s,displayNameFromDS:u}){return{name:d,type:L.fS.number,display:(0,j.U_)(),config:{displayNameFromDS:u},labels:s,values:new C.G(p.map(o=>m?le(o[1]):o[1]))}}function Se(p,d){if(d?.legendFormat)return{name:(0,te.W)((0,B.J)().replace(d.legendFormat,d?.scopedVars),p),labels:p};const{__name__:m,...s}=p,u=(0,$.aA)(s);let o=`${m??""}${u}`;return o||(o=d.query),{name:o,labels:s}}function ae(p){const d=p.__name__||"";delete p.__name__;const m=Object.entries(p).map(s=>`${s[0]}="${s[1]}"`).join(",");return`${d}{${m}}`}function Re(p){if(p.length===0||p.length===1&&p[0].length===0)return[];const d=p[0].fields.find(s=>s.type===L.fS.time),m=p.map(s=>{let u=s.fields.find(o=>o.type===L.fS.number);return{...u,name:u.config.displayNameFromDS}});return[{...p[0],meta:{...p[0].meta,type:V.P.HeatmapRows},fields:[d,...m]}]}function de(p){for(let d=p.length-1;d>0;d--){const m=p[d].fields.find(u=>u.name===L.M5),s=p[d-1].fields.find(u=>u.name===L.M5);if(!m||!s)throw new Error("Prometheus heatmap transform error: data should be a time series");for(let u=0;u<m.values.length;u++){const o=s.values.get(u)||[0];m.values.toArray()[u]-=o}}return p}function Ie(p,d){let m,s;try{m=le(p.name??p.fields[1].name),s=le(d.name??d.fields[1].name)}catch(u){return console.error(u),0}return m>s?1:m<s?-1:0}function le(p){return ie.test(p)?p[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY:parseFloat(p)}},62870:(ge,Z,l)=>{ge.exports=l(16211)}}]);

//# sourceMappingURL=3988.d3321fa31f7414790ff0.js.map