Getting statistical history from TeamCity API

2019-03-28 19:01发布

问题:

From looking at the TeamCity REST API Documentation, the request for statistical data is:

http://teamcity:8111/httpAuth/app/rest/builds/<buildLocator>/statistics/ 

Which works, however, it only gives statistics for the current build (tests passed, code coverage, number of duplicates, etc.), I am looking to build a graph for my build radiator showing trends, therefore I want the historical data for the past month.

Is there a way to get this historical statistic data from the TeamCity API?

回答1:

Rather than hit the DB directly, you can get at the data via the exportchart endpoint on TeamCity. This is not a documented API (at least to my knowledge) but I found that altering the "type" query string param to json gives you json data (rather than the default CSV). You can learn more about this endpoint by messing around with the drop-downs on the Build Configuration -> Statistics tab and then checking out the URL used for the "Download data as CSV" download icon/button.

e.g.

http://teamcity/exportchart.html?type=json&buildTypeId=bt2&%40f_range=MONTH&%40filter.status=WARNING&showBranches=true&_graphKey=g&valueType=CodeCoverage&id=CodeCoveragebt2

From what I can tell, there are no custom date ranges allowed.

(note that "bt2" is a build configuration id from my system)



回答2:

To get statistics values for a set of builds, since TeamCity 8.1 use the request as in the TeamCity REST doc:

 http://teamcity:8111/app/rest/builds?locator=BUILDS_LOCATOR&fields=build(id,number,status,buildType(id,name,projectName),statistics(property(name,value)))

This basically returns build nodes matching BUILDS_LOCATOR and "expands" statistics in each. e.g. use "buildType:(id:BUILD_CONFIG_ID)" as "BUILDS_LOCATOR" to get the builds form the build configuration with the UI-configured id "BUILD_CONFIG_ID".



回答3:

Unfortunately, I was unable to get this data solely from the TeamCity API, so the solution was to go against the database instead.

select 
    build_data_storage.build_id, 
    build_type_mapping.ext_id as 'build_type_id',
    data_storage_dict.value_type_key as 'metric_name', 
    build_data_storage.metric_value,
    history.build_number,
    history.build_finish_time_server
from 
    build_data_storage
join 
    data_storage_dict on build_data_storage.metric_id = data_storage_dict.metric_id
join
    history on build_data_storage.build_id = history.build_id
join
    build_type_mapping on history.build_type_id = build_type_mapping.int_id