func buildUpdateDataSourceRequest()

in cmd/datasource-syncer/main.go [213:286]


func buildUpdateDataSourceRequest(dataSource grafana.DataSource, token string) (*grafana.DataSource, error) {
	var (
		minPrometheusVersion     = "2.40.0"
		authorizationHeaderLabel = "Authorization"
		// httpHeader* are the prefixes that are used to store the names and values of custom headers.
		// check https://github.com/grafana/grafana/blob/148e1c1588e9f075b14b72eb87d5463ea5bbb253/pkg/services/datasources/models.go#L34C1-L34C1 for more info.
		httpHeaderName  = "httpHeaderName"
		httpHeaderValue = "httpHeaderValue"
	)
	if dataSource.Type != "prometheus" {
		return nil, errors.New("datasource type is not prometheus")
	}
	if *gcmEndpointOverride != "" {
		dataSource.URL = *gcmEndpointOverride
	} else {
		dataSource.URL = fmt.Sprintf("https://monitoring.googleapis.com/v1/projects/%s/location/global/prometheus/", *projectID)
	}

	// Miscellaneous updates to make Grafana more compatible with GMP.
	jsonData := dataSource.JSONData
	if jsonData["queryTimeout"] == nil {
		jsonData["queryTimeout"] = "2m"
	}

	if jsonData["timeout"] == nil {
		jsonData["timeout"] = "120"
	}

	jsonData["httpMethod"] = http.MethodGet
	if jsonData["prometheusType"] == nil {
		jsonData["prometheusType"] = "Prometheus"
	}

	// Make sure prometheusVersion is set to 2.40.0 or higher.
	if jsonData["prometheusVersion"] == nil {
		jsonData["prometheusVersion"] = minPrometheusVersion
	} else {
		// semver.Compare needs a prefix of v.
		dsPrometheusVersion := fmt.Sprintf("v%s", jsonData["prometheusVersion"].(string))
		if semver.Compare(dsPrometheusVersion, fmt.Sprintf("v%s", minPrometheusVersion)) < 0 {
			jsonData["prometheusVersion"] = minPrometheusVersion
		}
	}

	// Headers are named httpHeaderNameX. Where X is a digit that is based on the number of headers.
	// Try to find httpHeaderNameX equal to Authorization. Keep track of X so we know which header
	// to use for httpHeaderValueX. If it's not found create httpHeaderNameX : Authorization.
	x := 1
	found := false
	for {
		authHeader := fmt.Sprintf("%s%d", httpHeaderName, x)
		value, ok := jsonData[authHeader]
		if !ok {
			break
		}
		if value == authorizationHeaderLabel {
			found = true
			break
		}
		x++
	}

	if !found {
		authHeader := fmt.Sprintf("%s%d", httpHeaderName, x)
		jsonData[authHeader] = authorizationHeaderLabel
	}
	authHeaderValue := fmt.Sprintf("%s%d", httpHeaderValue, x)
	if dataSource.SecureJSONData == nil {
		dataSource.SecureJSONData = map[string]interface{}{}
	}
	// Add token to SecureJSONData e.g. httpHeaderValue1: Bearer 123.
	dataSource.SecureJSONData[authHeaderValue] = fmt.Sprintf("Bearer %s", token)
	return &dataSource, nil
}