Skip to content

Commit

Permalink
Add metadata to Windows exe files (#16048)
Browse files Browse the repository at this point in the history
This adds metadata to the Windows .exe files that the build produces. This makes our binaries a little more friendly to automation on Windows because you can check the version programmatically with ease. It also makes is easy for end user to inspect some details about the file from the file properties dialog in Windows.

Closes #15232

For example:

```
PS C:\vagrant\winlogbeat > (Get-Info .\winlogbeat.exe).VersionInfo | Format-List

OriginalFilename  : winlogbeat.exe
FileDescription   : Winlogbeat ships Windows event logs to Elasticsearch or Logstash.
ProductName       : Winlogbeat
Comments          : commit=8d6cf58f347579188d707421da6b70b2f66701ea
CompanyName       : Elastic
FileName          : C:\vagrant\winlogbeat\winlogbeat.exe
FileVersion       : 8.0.0
ProductVersion    : 8.0.0
IsDebug           : False
IsPatched         : False
IsPreRelease      : False
IsPrivateBuild    : False
IsSpecialBuild    : False
Language          : Language Neutral
LegalCopyright    : Copyright Elastic, License ASL 2.0
LegalTrademarks   :
PrivateBuild      :
SpecialBuild      :
FileVersionRaw    : 8.0.0.0
ProductVersionRaw : 8.0.0.0
```
  • Loading branch information
andrewkroh authored Feb 26, 2020
1 parent 2743d51 commit 695b167
Show file tree
Hide file tree
Showing 19 changed files with 1,991 additions and 9 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.next.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ https://github.com/elastic/beats/compare/v7.0.0-alpha2...master[Check the HEAD d
- Add `aws_ec2` provider for autodiscover. {issue}12518[12518] {pull}14823[14823]
- Add monitoring variable `libbeat.config.scans` to distinguish scans of the configuration directory from actual reloads of its contents. {pull}16440[16440]
- Add support for multiple password in redis output. {issue}16058[16058] {pull}16206[16206]
- Windows .exe files now have embedded file version info. {issue}15232[15232]t
- Remove experimental flag from `setup.template.append_fields` {pull}16576[16576]

*Auditbeat*
Expand Down
56 changes: 56 additions & 0 deletions NOTICE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,34 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

--------------------------------------------------------------------
Dependency: github.com/akavel/rsrc
Revision: b9f6b78f792dc3dddaf295854d968f5b6fdcdba1
License type (autodetected): MIT
./vendor/github.com/akavel/rsrc/LICENSE.txt:
--------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2013-2017 The rsrc Authors.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

--------------------------------------------------------------------
Dependency: github.com/andrewkroh/sys
Revision: 287798fe3e430efeb9318b95ff52353aaa2b59b1
Expand Down Expand Up @@ -4695,6 +4723,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

--------------------------------------------------------------------
Dependency: github.com/josephspurrier/goversioninfo
Revision: 63e6d1acd3dd857ec6b8c54fbf52e10ce24a8786
License type (autodetected): MIT
./vendor/github.com/josephspurrier/goversioninfo/LICENSE:
--------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2016 Joseph Spurrier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

--------------------------------------------------------------------
Dependency: github.com/jpillora/backoff
Revision: d80867952dff4e2fbfb4280ded4ff94d67790457
Expand Down
79 changes: 70 additions & 9 deletions dev-tools/mage/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,24 @@ import (
"path/filepath"
"strings"

"github.com/josephspurrier/goversioninfo"
"github.com/magefile/mage/sh"
"github.com/pkg/errors"
)

// BuildArgs are the arguments used for the "build" target and they define how
// "go build" is invoked.
type BuildArgs struct {
Name string // Name of binary. (On Windows '.exe' is appended.)
InputFiles []string
OutputDir string
CGO bool
Static bool
Env map[string]string
LDFlags []string
Vars map[string]string // Vars that are passed as -X key=value with the ldflags.
ExtraFlags []string
Name string // Name of binary. (On Windows '.exe' is appended.)
InputFiles []string
OutputDir string
CGO bool
Static bool
Env map[string]string
LDFlags []string
Vars map[string]string // Vars that are passed as -X key=value with the ldflags.
ExtraFlags []string
WinMetadata bool // Add resource metadata to Windows binaries (like add the version number to the .exe properties).
}

// DefaultBuildArgs returns the default BuildArgs for use in builds.
Expand All @@ -55,6 +57,7 @@ func DefaultBuildArgs() BuildArgs {
"github.com/elastic/beats/libbeat/version.buildTime": "{{ date }}",
"github.com/elastic/beats/libbeat/version.commit": "{{ commit }}",
},
WinMetadata: true,
}

if versionQualified {
Expand Down Expand Up @@ -157,6 +160,64 @@ func Build(params BuildArgs) error {
args = append(args, params.InputFiles...)
}

if GOOS == "windows" && params.WinMetadata {
log.Println("Generating a .syso containing Windows file metadata.")
syso, err := MakeWindowsSysoFile()
if err != nil {
return errors.Wrap(err, "failed generating Windows .syso metadata file")
}
defer os.Remove(syso)
}

log.Println("Adding build environment vars:", env)
return sh.RunWith(env, "go", args...)
}

// MakeWindowsSysoFile generates a .syso file containing metadata about the
// executable file like vendor, version, copyright. The linker automatically
// discovers the .syso file and incorporates it into the Windows exe. This
// allows users to view metadata about the exe in the Details tab of the file
// properties viewer.
func MakeWindowsSysoFile() (string, error) {
version, err := BeatQualifiedVersion()
if err != nil {
return "", err
}

commit, err := CommitHash()
if err != nil {
return "", err
}

major, minor, patch, err := ParseVersion(version)
if err != nil {
return "", err
}
fileVersion := goversioninfo.FileVersion{Major: major, Minor: minor, Patch: patch}

vi := &goversioninfo.VersionInfo{
FixedFileInfo: goversioninfo.FixedFileInfo{
FileVersion: fileVersion,
ProductVersion: fileVersion,
FileType: "01", // Application
},
StringFileInfo: goversioninfo.StringFileInfo{
CompanyName: BeatVendor,
ProductName: strings.Title(BeatName),
ProductVersion: version,
FileVersion: version,
FileDescription: BeatDescription,
OriginalFilename: BeatName + ".exe",
LegalCopyright: "Copyright " + BeatVendor + ", License " + BeatLicense,
Comments: "commit=" + commit,
},
}

vi.Build()
vi.Walk()
sysoFile := BeatName + "_windows_" + GOARCH + ".syso"
if err = vi.WriteSyso(sysoFile, GOARCH); err != nil {
return "", errors.Wrap(err, "failed to generate syso file with Windows metadata")
}
return sysoFile, nil
}
22 changes: 22 additions & 0 deletions dev-tools/mage/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -761,3 +761,25 @@ func binaryExtension(goos string) string {
}
return ""
}

var parseVersionRegex = regexp.MustCompile(`(?m)^[^\d]*(?P<major>\d)+\.(?P<minor>\d)+(?:\.(?P<patch>\d)+.*)?$`)

// ParseVersion extracts the major, minor, and optional patch number from a
// version string.
func ParseVersion(version string) (major, minor, patch int, err error) {
names := parseVersionRegex.SubexpNames()
matches := parseVersionRegex.FindStringSubmatch(version)
if len(matches) == 0 {
err = errors.Errorf("failed to parse version '%v'", version)
return
}

data := map[string]string{}
for i, match := range matches {
data[names[i]] = match
}
major, _ = strconv.Atoi(data["major"])
minor, _ = strconv.Atoi(data["minor"])
patch, _ = strconv.Atoi(data["patch"])
return
}
47 changes: 47 additions & 0 deletions dev-tools/mage/common_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package mage

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestParseVersion(t *testing.T) {
var tests = []struct {
Version string
Major, Minor, Patch int
}{
{"v1.2.3", 1, 2, 3},
{"1.2.3", 1, 2, 3},
{"1.2.3-SNAPSHOT", 1, 2, 3},
{"1.2.3rc1", 1, 2, 3},
{"1.2", 1, 2, 0},
}

for _, tc := range tests {
major, minor, patch, err := ParseVersion(tc.Version)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, tc.Major, major)
assert.Equal(t, tc.Minor, minor)
assert.Equal(t, tc.Patch, patch)
}
}
21 changes: 21 additions & 0 deletions vendor/github.com/akavel/rsrc/LICENSE.txt

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions vendor/github.com/akavel/rsrc/binutil/plain.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 35 additions & 0 deletions vendor/github.com/akavel/rsrc/binutil/sizedfile.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

63 changes: 63 additions & 0 deletions vendor/github.com/akavel/rsrc/binutil/walk.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 695b167

Please sign in to comment.