1// Copyright 2016 The Prometheus Authors 2// Licensed under the Apache License, Version 2.0 (the "License"); 3// you may not use this file except in compliance with the License. 4// You may obtain a copy of the License at 5// 6// http://www.apache.org/licenses/LICENSE-2.0 7// 8// Unless required by applicable law or agreed to in writing, software 9// distributed under the License is distributed on an "AS IS" BASIS, 10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11// See the License for the specific language governing permissions and 12// limitations under the License. 13 14package version 15 16import ( 17 "bytes" 18 "fmt" 19 "runtime" 20 "strings" 21 "text/template" 22 23 "github.com/prometheus/client_golang/prometheus" 24) 25 26// Build information. Populated at build-time. 27var ( 28 Version string 29 Revision string 30 Branch string 31 BuildUser string 32 BuildDate string 33 GoVersion = runtime.Version() 34) 35 36// NewCollector returns a collector that exports metrics about current version 37// information. 38func NewCollector(program string) prometheus.Collector { 39 return prometheus.NewGaugeFunc( 40 prometheus.GaugeOpts{ 41 Namespace: program, 42 Name: "build_info", 43 Help: fmt.Sprintf( 44 "A metric with a constant '1' value labeled by version, revision, branch, and goversion from which %s was built.", 45 program, 46 ), 47 ConstLabels: prometheus.Labels{ 48 "version": Version, 49 "revision": Revision, 50 "branch": Branch, 51 "goversion": GoVersion, 52 }, 53 }, 54 func() float64 { return 1 }, 55 ) 56} 57 58// versionInfoTmpl contains the template used by Info. 59var versionInfoTmpl = ` 60{{.program}}, version {{.version}} (branch: {{.branch}}, revision: {{.revision}}) 61 build user: {{.buildUser}} 62 build date: {{.buildDate}} 63 go version: {{.goVersion}} 64 platform: {{.platform}} 65` 66 67// Print returns version information. 68func Print(program string) string { 69 m := map[string]string{ 70 "program": program, 71 "version": Version, 72 "revision": Revision, 73 "branch": Branch, 74 "buildUser": BuildUser, 75 "buildDate": BuildDate, 76 "goVersion": GoVersion, 77 "platform": runtime.GOOS + "/" + runtime.GOARCH, 78 } 79 t := template.Must(template.New("version").Parse(versionInfoTmpl)) 80 81 var buf bytes.Buffer 82 if err := t.ExecuteTemplate(&buf, "version", m); err != nil { 83 panic(err) 84 } 85 return strings.TrimSpace(buf.String()) 86} 87 88// Info returns version, branch and revision information. 89func Info() string { 90 return fmt.Sprintf("(version=%s, branch=%s, revision=%s)", Version, Branch, Revision) 91} 92 93// BuildContext returns goVersion, buildUser and buildDate information. 94func BuildContext() string { 95 return fmt.Sprintf("(go=%s, user=%s, date=%s)", GoVersion, BuildUser, BuildDate) 96} 97