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 which exports metrics about current version information. 37func NewCollector(program string) *prometheus.GaugeVec { 38 buildInfo := prometheus.NewGaugeVec( 39 prometheus.GaugeOpts{ 40 Namespace: program, 41 Name: "build_info", 42 Help: fmt.Sprintf( 43 "A metric with a constant '1' value labeled by version, revision, branch, and goversion from which %s was built.", 44 program, 45 ), 46 }, 47 []string{"version", "revision", "branch", "goversion"}, 48 ) 49 buildInfo.WithLabelValues(Version, Revision, Branch, GoVersion).Set(1) 50 return buildInfo 51} 52 53// versionInfoTmpl contains the template used by Info. 54var versionInfoTmpl = ` 55{{.program}}, version {{.version}} (branch: {{.branch}}, revision: {{.revision}}) 56 build user: {{.buildUser}} 57 build date: {{.buildDate}} 58 go version: {{.goVersion}} 59` 60 61// Print returns version information. 62func Print(program string) string { 63 m := map[string]string{ 64 "program": program, 65 "version": Version, 66 "revision": Revision, 67 "branch": Branch, 68 "buildUser": BuildUser, 69 "buildDate": BuildDate, 70 "goVersion": GoVersion, 71 } 72 t := template.Must(template.New("version").Parse(versionInfoTmpl)) 73 74 var buf bytes.Buffer 75 if err := t.ExecuteTemplate(&buf, "version", m); err != nil { 76 panic(err) 77 } 78 return strings.TrimSpace(buf.String()) 79} 80 81// Info returns version, branch and revision information. 82func Info() string { 83 return fmt.Sprintf("(version=%s, branch=%s, revision=%s)", Version, Branch, Revision) 84} 85 86// BuildContext returns goVersion, buildUser and buildDate information. 87func BuildContext() string { 88 return fmt.Sprintf("(go=%s, user=%s, date=%s)", GoVersion, BuildUser, BuildDate) 89} 90