“Could not fetch metrics” error while publishing quality gat

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.

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.

# 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)'

Hey there.

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

Why not instead use the SonarQubeAnalyze step? See the documentation on Analyzing projects with Azure Pipelines

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”

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

Which comes back to the question:

And:

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

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.

Hi Team,

Could not fetch Metrics error while publishing quality gate.