# “Could not fetch metrics” error while publishing quality gat

**URL:** <https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gat/98757>\
**Category:** SonarQube Server / Community Build\
**Tags:** azuredevops, quality-gate, sonarqube\
**Created:** [September 6, 2023, 12:23pm UTC](https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gat/98757 "2023-09-06T12:23:25Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jtxrls](https://dub1.discourse-cdn.com/sonarsource/user_avatar/community.sonarsource.com/jtxrls/32/46760_2.png) [@Jtxrls](https://community.sonarsource.com/u/Jtxrls)\
**Post date:** [September 6, 2023, 12:23pm UTC](https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gat/98757/1 "2023-09-06T12:23:26Z")

</div>

Good morning.

I created an old topic with this problem, I was asked to perform the update as suggested but the error still persists, I would like to know if there is another solution or approach to perform. Attached is the error.

 ![sonar](https://europe1.discourse-cdn.com/sonarsource/uploads/sonarcommunity/original/3X/9/7/97413e0bdb178fe8a07396c28861e26e9ddcfe0c.png)

> [@"Could not fetch metrics” error while publishing quality gate result](https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gate-result/94968/1):
>
> Hello!! I’m getting the message on my agent when I’m going to publish the result, until last week it was normal.

---

<div class="post-metadata">

**Author:** ![Colin](https://dub1.discourse-cdn.com/sonarsource/user_avatar/community.sonarsource.com/colin/32/55255_2.png) [@Colin](https://community.sonarsource.com/u/Colin)\
**Post date:** [September 7, 2023, 5:16pm UTC](https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gat/98757/2 "2023-09-07T17:16:43Z")

</div>

Hey again!

Can you publish how your Azure Pipelines is configured? It would be best if you can share a full _azure-pipelines.yml_ file here.

---

<div class="post-metadata">

**Author:** ![Jtxrls](https://dub1.discourse-cdn.com/sonarsource/user_avatar/community.sonarsource.com/jtxrls/32/46760_2.png) [@Jtxrls](https://community.sonarsource.com/u/Jtxrls)\
**Post date:** [September 11, 2023, 11:45am UTC](https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gat/98757/4 "2023-09-11T11:45:30Z")

</div>

```auto
# Setting parameters
parameters:
# Etapas do pipeline
- name: stepList
  type: stepList 
  default: []
# Main folder 
- name: rootFolder
  type: string
  default: ""
# Deploy folder  
- name: deployFolder
  type: string  
  default: ""
# Default type of generated artifact
- name: packageExtension
  type: string  
  default: "war"
# Declaration of global variables
variables:
  # Valida se a branch é a master
  isMaster: $[eq(variables['Build.SourceBranch'], 'refs/heads/master')]
  # Linux image used in the pipeline. Padrão ubuntu-18.04.    
  vmImage: $(vmImage)
# Pipeline steps
stages:
  # Perform software quality testing using sonarQube
  - stage: Quality
    dependsOn: []
    # Validates whether the test is done using sonar
    condition: and(succeeded(), and(eq(variables['sonar.scan'], 'true'),eq(variables['sonar_scan_global'], 'true')))
    # actions that must be performed with sonar
    jobs:
      # Call sonarQube
      - job: JobSonarQube
        pool:
          # agent name
          name: 'POOL_SONAR_CPCS'
        # execution steps
        steps:
          # sonarQube preparation
          - task: SonarQubePrepare@5
            displayName: 'SonarQube - Preparing analysis configuration'
            # Inputs for execution. Name, type and mode of execution
            inputs:
              SonarQube: 'Sonar Tubarão'
              scannerMode: 'CLI'
              configMode: 'file'
          # Sonar execution script.      
          - script: |
              set
              echo "SonarToken:"
              echo %SONAR_TOKEN%
              echo "BUILD_SOURCEBRANCHNAME:"
              echo %BUILD_SOURCEBRANCHNAME%
              echo "BUILD_VERSION"
              echo "%BUILD_VERSION%"
              echo "BUILD_REASON"
              echo "%BUILD_REASON%"
              echo "System.PullRequest.PullRequestId:"
              echo $(System.PullRequest.PullRequestId)
              echo "System.PullRequest.SourceBranch:"
              echo $(System.PullRequest.SourceBranch)
              echo "System.PullRequest.TargetBranch:"
              echo $(System.PullRequest.TargetBranch)
              SET PATH=%SONAR_HOME%\bin;%PATH%
              SET SONAR_SCANNER_OPTS=-Xmx512m
              if not exist exec mkdir exec
              SET SOURCE_BRANCH=$(System.PullRequest.SourceBranch)
              SET SOURCE_BRANCH=%SOURCE_BRANCH:refs/heads/=%
              echo "SOURCE_BRANCH:"
              echo %SOURCE_BRANCH%
              SET TARGET_BRANCH=$(System.PullRequest.TargetBranch)
              SET TARGET_BRANCH=%TARGET_BRANCH:refs/heads/=%
              echo "TARGET_BRANCH:"
              echo %TARGET_BRANCH%
              SET SONAR_METADATAFILEPATH="%AGENT_TEMPDIRECTORY%\sonar\%BUILD_BUILDNUMBER%\report-task.txt"
              ECHO %SONAR_METADATAFILEPATH%             
              IF "%BUILD_REASON%" == "PullRequest" sonar-scanner -X -Dsonar.pullrequest.key=$(System.PullRequest.PullRequestId) -Dsonar.pullrequest.branch=%SOURCE_BRANCH% -Dsonar.pullrequest.base=%TARGET_BRANCH% -Dsonar.projectVersion=%BUILD_VERSION% -Dsonar.scanner.metadataFilePath=%SONAR_METADATAFILEPATH% -Dsonar.qualitygate=cpcs_java -Dsonar.login=$(SONAR_TOKEN)
              IF NOT "%BUILD_REASON%" == "PullRequest" sonar-scanner -X -Dsonar.branch.name=%BUILD_SOURCEBRANCHNAME% -Dsonar.projectVersion=%BUILD_VERSION% -Dsonar.scanner.metadataFilePath=%SONAR_METADATAFILEPATH% -Dsonar.qualitygate=cpcs_java -Dsonar.login=$(SONAR_TOKEN)
            displayName: 'SonarQube - Executando análise de código'
            # USE token created for SONAR
            env:
              SONAR_TOKEN: $(SONAR_TOKEN)
          # Results publication phase
          - task: SonarQubePublish@5
            displayName: 'SonarQube - Publishing Quality Gate results'
            # Waiting time for execution
            inputs:
              pollingTimeoutSec: '300'
          # Presents execution. Reads file generated by sonar and presents it in the build process  
          - template: steps/azure-ci-sonar-status-result.yml
  # Application build phase
  - stage: CI
    dependsOn: []
    # Checks if it is a build created by pull request or updating a branch  
    condition: and(succeeded(),ne(variables['Build.Reason'], 'PullRequest'))
    # Build actions
    jobs:
      - job: JobBuild
        # Uses standard Linux image or received through pipeline variables
        pool:
          vmImage: $(vmImage)
        # Execution steps
        steps:
        # Removes .git files and directories from the project and compresses project sources
        - bash: rm -rf .git
          displayName: 'Remover diretório(.git)'
        - task: ArchiveFiles@2
          displayName: 'Compactar Fontes do Projeto(src.zip)'
          # Appetizer
          inputs:
            # Points to project folder
            rootFolderOrFile: '$(Agent.BuildDirectory)/s${{parameters.rootFolder}}' 
            # Whether or not to include main folder
            includeRootFolder: false 
            # Type of compression to be done
            archiveType: 'zip' 
            # Compressed file name
            archiveFile: '$(Build.ArtifactStagingDirectory)/src.zip'
        # Run Linux bash
        - task: JavaToolInstaller@0
          inputs:
            versionSpec: '8'
            jdkArchitectureOption: 'x64'
            jdkSourceOption: 'PreInstalled'
        - task: Bash@3
          # Text with action to be performed
          displayName: 'Gerar Arquivo com os Comentários do Check-in(conteudo.txt)'
          # Appetizer
          inputs:
            # bash writing method. 
            targetType: 'inline'
            # Command to be executed 
            script: 'cd $(Build.ArtifactStagingDirectory) && mkdir _doc && printf "%s" "$(build.sourceversionmessage)" >> _doc/conteudo.txt'
        # Download maven 2.0.9
        - script: 'wget http://archive.apache.org/dist/maven/binaries/apache-maven-2.0.9-bin.zip'
          displayName: 'Download Maven(apache-maven-2.0.9)'
        # Extract Maven file   
        - task: ExtractFiles@1
          displayName: 'Descompactar Maven(apache-maven-2.0.9)'
          # input commands 
          inputs:
            # maven file name 
            archiveFilePatterns: 'apache-maven-2.0.9-bin.zip'
            # Destination folder 
            destinationFolder: '$(build.sourcesdirectory)/maven'
        # Give any user execution permission to the maven folder
        - script: 'sudo chmod 777 -R $(build.sourcesdirectory)/maven/apache-maven-2.0.9/*'
          displayName: 'Conceder Permisão de Execução Maven(apache-maven-2.0.9)'
        # List sources and run application build
        - script: 'ls -fla $(Build.SourcesDirectory)'
          displayName: 'Listar os fontes'
        - bash: echo "Executando passos do build da aplicação"
          displayName: 'Executando passos do build da aplicação'
        # cycles through steplist parameters and executes the application file.
        - ${{ each step in parameters.stepList }}:
          - ${{ each pair in step }}:
              ${{ pair.key }}: ${{ pair.value }}  
        # Final Success Messages
        - bash: echo "Finalizando passos do build da Aplicação" 
          displayName: 'Finalizando passos do build da Aplicação'
        # Copy build file to azure artifacts folder
        - task: CopyFiles@1
          displayName: 'Copiando os Arquivos para: $(build.artifactstagingdirectory)'
          # Input Actions
          inputs:
            # Folder where the build file was generated
            SourceFolder: '$(system.defaultworkingdirectory)${{parameters.rootFolder}}${{parameters.deployFolder}}'
            # Parameter-based content packageExtension
            Contents: '**/*.${{parameters.packageExtension}}'
            # Folder that will receive the build file
            TargetFolder: '$(build.artifactstagingdirectory)'
        # Copy file to folder
        - task: PublishPipelineArtifact@1
          displayName: 'Copiando os Arquivos para pasta Drop'
          inputs:
            artifactType: 'pipeline'
            artifactName: 'drop'
            targetPath: '$(build.artifactstagingdirectory)'

```

---

<div class="post-metadata">

**Author:** ![Colin](https://dub1.discourse-cdn.com/sonarsource/user_avatar/community.sonarsource.com/colin/32/55255_2.png) [@Colin](https://community.sonarsource.com/u/Colin)\
**Post date:** [September 12, 2023, 8:53am UTC](https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gat/98757/5 "2023-09-12T08:53:53Z")

</div>

Hey there.

This looks remarkably complicated. Why are you trying to set these things manually?

> [@Jtxrls](#):
>
> ```auto
> # Sonar execution script.      
> - script: |
> set
> echo "SonarToken:"
> echo %SONAR_TOKEN%
> echo "BUILD_SOURCEBRANCHNAME:"
> echo %BUILD_SOURCEBRANCHNAME%
> echo "BUILD_VERSION"
> echo "%BUILD_VERSION%"
> echo "BUILD_REASON"
> echo "%BUILD_REASON%"
> echo "System.PullRequest.PullRequestId:"
> echo $(System.PullRequest.PullRequestId)
> echo "System.PullRequest.SourceBranch:"
> echo $(System.PullRequest.SourceBranch)
> echo "System.PullRequest.TargetBranch:"
> echo $(System.PullRequest.TargetBranch)
> SET PATH=%SONAR_HOME%\bin;%PATH%
> SET SONAR_SCANNER_OPTS=-Xmx512m
> if not exist exec mkdir exec
> SET SOURCE_BRANCH=$(System.PullRequest.SourceBranch)
> SET SOURCE_BRANCH=%SOURCE_BRANCH:refs/heads/=%
> echo "SOURCE_BRANCH:"
> echo %SOURCE_BRANCH%
> SET TARGET_BRANCH=$(System.PullRequest.TargetBranch)
> SET TARGET_BRANCH=%TARGET_BRANCH:refs/heads/=%
> echo "TARGET_BRANCH:"
> echo %TARGET_BRANCH%
> SET SONAR_METADATAFILEPATH="%AGENT_TEMPDIRECTORY%\sonar\%BUILD_BUILDNUMBER%\report-task.txt"
> ECHO %SONAR_METADATAFILEPATH%             
> IF "%BUILD_REASON%" == "PullRequest" sonar-scanner -X -Dsonar.pullrequest.key=$(System.PullRequest.PullRequestId) -Dsonar.pullrequest.branch=%SOURCE_BRANCH% -Dsonar.pullrequest.base=%TARGET_BRANCH% -Dsonar.projectVersion=%BUILD_VERSION% -Dsonar.scanner.metadataFilePath=%SONAR_METADATAFILEPATH% -Dsonar.qualitygate=cpcs_java -Dsonar.login=$(SONAR_TOKEN)
> IF NOT "%BUILD_REASON%" == "PullRequest" sonar-scanner -X -Dsonar.branch.name=%BUILD_SOURCEBRANCHNAME% -Dsonar.projectVersion=%BUILD_VERSION% -Dsonar.scanner.metadataFilePath=%SONAR_METADATAFILEPATH% -Dsonar.qualitygate=cpcs_java -Dsonar.login=$(SONAR_TOKEN)
> 
> ```

Why not instead use the `SonarQubeAnalyze` step? See the documentation on [Analyzing projects with Azure Pipelines](https://docs.sonarsource.com/sonarqube/latest/devops-platform-integration/azure-devops-integration/?_gl=1*18yu3kz*_up*MQ..&gclid=Cj0KCQjwmICoBhDxARIsABXkXlJw3ShXHJeZX_6fBAqoZh8admlwEUk5Zfd3U0D4g4mkP8fs1ujON3AaAtPLEALw_wcB#analyzing-projects-with-azure-pipelines)

---

<div class="post-metadata">

**Author:** ![Jtxrls](https://dub1.discourse-cdn.com/sonarsource/user_avatar/community.sonarsource.com/jtxrls/32/46760_2.png) [@Jtxrls](https://community.sonarsource.com/u/Jtxrls)\
**Post date:** [September 12, 2023, 11:28am UTC](https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gat/98757/6 "2023-09-12T11:28:57Z")

</div>

Some systems we use detect these variables manually… and the problem above?

debug:

2023-09-12T11:55:50.7747816Z ##[debug]SONARQUBE\_ENDPOINT=\*\*\*  
2023-09-12T11:55:50.7749438Z ##[debug][SQ] API GET: ‘/api/metrics/search’ with query “{“f”:“name”,“ps”:500}”  
2023-09-12T11:55:50.8112429Z ##[debug]Response: 401 Body: “undefined”  
2023-09-12T11:55:50.8116640Z ##[debug][SQ] API GET ‘/api/metrics/search’ failed, status code was: 401  
2023-09-12T11:55:50.8154563Z ##[error][SQ] Could not fetch metrics  
2023-09-12T11:55:50.8164402Z ##[debug]Processed: ##vso[task.issue type=error;][SQ] Could not fetch metrics  
2023-09-12T11:55:50.8169986Z ##[error][SQ] API GET ‘/api/metrics/search’ failed, status code was: 401  
2023-09-12T11:55:50.8170497Z ##[debug]Processed: ##vso[task.issue type=error;][SQ] API GET ‘/api/metrics/search’ failed, status code was: 401  
2023-09-12T11:55:50.8252517Z ##[debug]pollingTimeoutSec=300  
2023-09-12T11:55:50.8253933Z ##[debug][SQ] API GET: ‘/api/server/version’ with query “undefined”  
2023-09-12T11:55:50.8291540Z ##[debug]Response: 200 Body: “9.0.1.46107”

---

<div class="post-metadata">

**Author:** ![Colin](https://dub1.discourse-cdn.com/sonarsource/user_avatar/community.sonarsource.com/colin/32/55255_2.png) [@Colin](https://community.sonarsource.com/u/Colin)\
**Post date:** [September 13, 2023, 1:17am UTC](https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gat/98757/7 "2023-09-13T01:17:05Z")

</div>

The `SonarCloudPublish` task is only meant to be used after the `SonarCloudAnalyze` step.

Which comes back to the question:

> [@Colin](#):
>
> Why not instead use the `SonarQubeAnalyze` step?

And:

> [@Jtxrls](#):
>
> 2023-09-12T11:55:50.8253933Z ##[debug][SQ] API GET: ‘/api/server/version’ with query “undefined”  
> 2023-09-12T11:55:50.8291540Z ##[debug]Response: 200 Body: “9.0.1.46107”

It looks like you didn’t perform the upgrade you said you did. 😕

> [@Jtxrls](#):
>
> I was asked to perform the update as suggested but the error still persists, I would like to know if there is another solution or approach to perform.

---

<div class="post-metadata">

**Author:** ![Jtxrls](https://dub1.discourse-cdn.com/sonarsource/user_avatar/community.sonarsource.com/jtxrls/32/46760_2.png) [@Jtxrls](https://community.sonarsource.com/u/Jtxrls)\
**Post date:** [October 2, 2023, 12:35pm UTC](https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gat/98757/8 "2023-10-02T12:35:28Z")

</div>

I don’t need to update, I have other systems that use this same version and work correctly, but some are stopping working, so continue this topic, I tried running an agent on my machine and still the error continues, should I take a different approach, and regarding the other question, some systems need to be configured to be able to run manually.

---

<div class="post-metadata">

**Author:** ![Sujith\_Rai](https://dub1.discourse-cdn.com/sonarsource/user_avatar/community.sonarsource.com/sujith_rai/32/65208_2.png) [@Sujith\_Rai](https://community.sonarsource.com/u/Sujith_Rai)\
**Post date:** [December 18, 2024, 6:15am UTC](https://community.sonarsource.com/t/could-not-fetch-metrics-error-while-publishing-quality-gat/98757/9 "2024-12-18T06:15:14Z")

</div>

Hi Team,

Could not fetch Metrics error while publishing quality gate.

 ![image](https://europe1.discourse-cdn.com/sonarsource/uploads/sonarcommunity/original/3X/b/c/bc641dc0b6793491c176ff93719e70520cc33789.png)
