2020-03-21 20:31:29 +00:00
|
|
|
// Copyright 2020 Matthew Holt
|
|
|
|
//
|
|
|
|
// Licensed 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.
|
|
|
|
|
2020-04-02 15:35:27 +01:00
|
|
|
package xcaddy
|
2020-03-21 20:31:29 +00:00
|
|
|
|
|
|
|
import (
|
2020-04-13 19:22:23 +01:00
|
|
|
"context"
|
2020-03-21 20:31:29 +00:00
|
|
|
"fmt"
|
|
|
|
"log"
|
2020-03-25 06:01:44 +00:00
|
|
|
"os"
|
2020-03-21 20:31:29 +00:00
|
|
|
"path"
|
|
|
|
"path/filepath"
|
|
|
|
"regexp"
|
|
|
|
"runtime"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/Masterminds/semver/v3"
|
2024-05-10 02:12:15 +01:00
|
|
|
"github.com/caddyserver/xcaddy/internal/utils"
|
2020-03-21 20:31:29 +00:00
|
|
|
)
|
|
|
|
|
2020-04-04 16:56:37 +01:00
|
|
|
// Builder can produce a custom Caddy build with the
|
|
|
|
// configuration it represents.
|
|
|
|
type Builder struct {
|
2020-04-23 21:34:29 +01:00
|
|
|
Compile
|
2020-05-07 17:21:12 +01:00
|
|
|
CaddyVersion string `json:"caddy_version,omitempty"`
|
|
|
|
Plugins []Dependency `json:"plugins,omitempty"`
|
|
|
|
Replacements []Replace `json:"replacements,omitempty"`
|
|
|
|
TimeoutGet time.Duration `json:"timeout_get,omitempty"`
|
|
|
|
TimeoutBuild time.Duration `json:"timeout_build,omitempty"`
|
2020-05-10 01:59:18 +01:00
|
|
|
RaceDetector bool `json:"race_detector,omitempty"`
|
2020-07-16 00:44:06 +01:00
|
|
|
SkipCleanup bool `json:"skip_cleanup,omitempty"`
|
2021-02-05 23:34:51 +00:00
|
|
|
SkipBuild bool `json:"skip_build,omitempty"`
|
2021-07-04 00:57:17 +01:00
|
|
|
Debug bool `json:"debug,omitempty"`
|
2022-06-20 20:20:05 +01:00
|
|
|
BuildFlags string `json:"build_flags,omitempty"`
|
2022-08-16 22:27:48 +01:00
|
|
|
ModFlags string `json:"mod_flags,omitempty"`
|
2023-12-18 20:22:47 +00:00
|
|
|
|
|
|
|
// Experimental: subject to change
|
|
|
|
EmbedDirs []struct {
|
|
|
|
Dir string `json:"dir,omitempty"`
|
|
|
|
Name string `json:"name,omitempty"`
|
|
|
|
} `json:"embed_dir,omitempty"`
|
2020-04-04 16:56:37 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Build builds Caddy at the configured version with the
|
|
|
|
// configured plugins and plops down a binary at outputFile.
|
2020-04-13 19:22:23 +01:00
|
|
|
func (b Builder) Build(ctx context.Context, outputFile string) error {
|
2023-03-03 11:19:04 +00:00
|
|
|
var cancel context.CancelFunc
|
|
|
|
if b.TimeoutBuild > 0 {
|
|
|
|
ctx, cancel = context.WithTimeout(ctx, b.TimeoutBuild)
|
|
|
|
defer cancel()
|
|
|
|
}
|
2020-03-21 20:31:29 +00:00
|
|
|
if outputFile == "" {
|
|
|
|
return fmt.Errorf("output file path is required")
|
|
|
|
}
|
|
|
|
// the user's specified output file might be relative, and
|
|
|
|
// because the `go build` command is executed in a different,
|
|
|
|
// temporary folder, we convert the user's input to an
|
|
|
|
// absolute path so it goes the expected place
|
|
|
|
absOutputFile, err := filepath.Abs(outputFile)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-12-18 20:22:47 +00:00
|
|
|
log.Printf("[INFO] absolute output file path: %s", absOutputFile)
|
2020-03-21 20:31:29 +00:00
|
|
|
|
2020-04-23 21:34:29 +01:00
|
|
|
// set some defaults from the environment, if applicable
|
|
|
|
if b.OS == "" {
|
2024-05-10 02:12:15 +01:00
|
|
|
b.OS = utils.GetGOOS()
|
2020-04-23 21:34:29 +01:00
|
|
|
}
|
|
|
|
if b.Arch == "" {
|
2024-05-10 02:12:15 +01:00
|
|
|
b.Arch = utils.GetGOARCH()
|
2020-04-23 21:34:29 +01:00
|
|
|
}
|
|
|
|
if b.ARM == "" {
|
|
|
|
b.ARM = os.Getenv("GOARM")
|
|
|
|
}
|
|
|
|
|
|
|
|
// prepare the build environment
|
|
|
|
buildEnv, err := b.newEnvironment(ctx)
|
2020-03-21 20:31:29 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-04-23 21:34:29 +01:00
|
|
|
defer buildEnv.Close()
|
|
|
|
|
2021-02-05 23:34:51 +00:00
|
|
|
if b.SkipBuild {
|
|
|
|
log.Printf("[INFO] Skipping build as requested")
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-05-03 00:32:37 +01:00
|
|
|
// prepare the environment for the go command; for
|
2020-04-23 21:34:29 +01:00
|
|
|
// the most part we want it to inherit our current
|
|
|
|
// environment, with a few customizations
|
|
|
|
env := os.Environ()
|
|
|
|
env = setEnv(env, "GOOS="+b.OS)
|
|
|
|
env = setEnv(env, "GOARCH="+b.Arch)
|
|
|
|
env = setEnv(env, "GOARM="+b.ARM)
|
2020-07-16 00:44:06 +01:00
|
|
|
if b.RaceDetector && !b.Compile.Cgo {
|
|
|
|
log.Println("[WARNING] Enabling cgo because it is required by the race detector")
|
|
|
|
b.Compile.Cgo = true
|
|
|
|
}
|
2020-05-22 17:31:34 +01:00
|
|
|
env = setEnv(env, fmt.Sprintf("CGO_ENABLED=%s", b.Compile.CgoEnabled()))
|
2020-03-21 20:31:29 +00:00
|
|
|
|
|
|
|
log.Println("[INFO] Building Caddy")
|
|
|
|
|
2021-02-05 17:49:17 +00:00
|
|
|
// tidy the module to ensure go.mod and go.sum are consistent with the module prereq
|
2023-05-09 18:58:48 +01:00
|
|
|
tidyCmd := buildEnv.newGoModCommand(ctx, "tidy", "-e")
|
2023-03-03 11:19:04 +00:00
|
|
|
if err := buildEnv.runCommand(ctx, tidyCmd); err != nil {
|
2021-02-05 17:49:17 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-04-23 21:34:29 +01:00
|
|
|
// compile
|
2023-03-03 11:19:04 +00:00
|
|
|
cmd := buildEnv.newGoBuildCommand(ctx, "build",
|
2020-03-21 20:31:29 +00:00
|
|
|
"-o", absOutputFile,
|
|
|
|
)
|
2022-02-16 20:26:25 +00:00
|
|
|
if b.Debug {
|
|
|
|
// support dlv
|
|
|
|
cmd.Args = append(cmd.Args, "-gcflags", "all=-N -l")
|
|
|
|
} else {
|
2022-08-16 20:19:15 +01:00
|
|
|
if buildEnv.buildFlags == "" {
|
2022-06-20 20:20:05 +01:00
|
|
|
cmd.Args = append(cmd.Args,
|
|
|
|
"-ldflags", "-w -s", // trim debug symbols
|
|
|
|
"-trimpath",
|
2024-05-06 17:12:23 +01:00
|
|
|
"-tags", "nobadger",
|
2022-06-20 20:20:05 +01:00
|
|
|
)
|
|
|
|
}
|
2021-07-04 00:57:17 +01:00
|
|
|
}
|
|
|
|
|
2020-05-10 01:59:18 +01:00
|
|
|
if b.RaceDetector {
|
|
|
|
cmd.Args = append(cmd.Args, "-race")
|
|
|
|
}
|
2020-04-28 18:07:25 +01:00
|
|
|
cmd.Env = env
|
2023-03-03 11:19:04 +00:00
|
|
|
err = buildEnv.runCommand(ctx, cmd)
|
2020-03-21 20:31:29 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("[INFO] Build complete: %s", outputFile)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-04-23 21:34:29 +01:00
|
|
|
// setEnv sets an environment variable-value pair in
|
|
|
|
// env, overriding an existing variable if it already
|
|
|
|
// exists. The env slice is one such as is returned
|
|
|
|
// by os.Environ(), and set must also have the form
|
|
|
|
// of key=value.
|
|
|
|
func setEnv(env []string, set string) []string {
|
|
|
|
parts := strings.SplitN(set, "=", 2)
|
|
|
|
key := parts[0]
|
|
|
|
for i := 0; i < len(env); i++ {
|
|
|
|
if strings.HasPrefix(env[i], key+"=") {
|
|
|
|
env[i] = set
|
|
|
|
return env
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return append(env, set)
|
|
|
|
}
|
|
|
|
|
2020-03-25 06:01:44 +00:00
|
|
|
// Dependency pairs a Go module path with a version.
|
|
|
|
type Dependency struct {
|
2020-07-16 00:45:32 +01:00
|
|
|
// The name (import path) of the Go package. If at a version > 1,
|
|
|
|
// it should contain semantic import version (i.e. "/v2").
|
|
|
|
// Used with `go get`.
|
|
|
|
PackagePath string `json:"module_path,omitempty"`
|
2020-04-04 16:56:37 +01:00
|
|
|
|
2020-07-16 00:45:32 +01:00
|
|
|
// The version of the Go module, as used with `go get`.
|
2020-04-23 21:34:29 +01:00
|
|
|
Version string `json:"version,omitempty"`
|
2020-04-13 19:22:23 +01:00
|
|
|
}
|
|
|
|
|
2020-08-10 19:27:38 +01:00
|
|
|
// ReplacementPath represents an old or new path component
|
|
|
|
// within a Go module replacement directive.
|
|
|
|
type ReplacementPath string
|
|
|
|
|
|
|
|
// Param reformats a go.mod replace directive to be
|
|
|
|
// compatible with the `go mod edit` command.
|
|
|
|
func (r ReplacementPath) Param() string {
|
|
|
|
return strings.Replace(string(r), " ", "@", 1)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r ReplacementPath) String() string { return string(r) }
|
|
|
|
|
2020-04-13 19:22:23 +01:00
|
|
|
// Replace represents a Go module replacement.
|
|
|
|
type Replace struct {
|
|
|
|
// The import path of the module being replaced.
|
2020-08-10 19:27:38 +01:00
|
|
|
Old ReplacementPath `json:"old,omitempty"`
|
2020-04-04 16:56:37 +01:00
|
|
|
|
2020-04-13 19:22:23 +01:00
|
|
|
// The path to the replacement module.
|
2020-08-10 19:27:38 +01:00
|
|
|
New ReplacementPath `json:"new,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewReplace creates a new instance of Replace provided old and
|
|
|
|
// new Go module paths
|
|
|
|
func NewReplace(old, new string) Replace {
|
|
|
|
return Replace{
|
|
|
|
Old: ReplacementPath(old),
|
|
|
|
New: ReplacementPath(new),
|
|
|
|
}
|
2020-03-21 20:31:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// newTempFolder creates a new folder in a temporary location.
|
|
|
|
// It is the caller's responsibility to remove the folder when finished.
|
|
|
|
func newTempFolder() (string, error) {
|
|
|
|
var parentDir string
|
|
|
|
if runtime.GOOS == "darwin" {
|
|
|
|
// After upgrading to macOS High Sierra, Caddy builds mysteriously
|
|
|
|
// started missing the embedded version information that -ldflags
|
|
|
|
// was supposed to produce. But it only happened on macOS after
|
|
|
|
// upgrading to High Sierra, and it didn't happen with the usual
|
|
|
|
// `go run build.go` -- only when using a buildenv. Bug in git?
|
|
|
|
// Nope. Not a bug in Go 1.10 either. Turns out it's a breaking
|
|
|
|
// change in macOS High Sierra. When the GOPATH of the buildenv
|
|
|
|
// was set to some other folder, like in the $HOME dir, it worked
|
|
|
|
// fine. Only within $TMPDIR it broke. The $TMPDIR folder is inside
|
|
|
|
// /var, which is symlinked to /private/var, which is mounted
|
|
|
|
// with noexec. I don't understand why, but evidently that
|
|
|
|
// makes -ldflags of `go build` not work. Bizarre.
|
|
|
|
// The solution, I guess, is to just use our own "temp" dir
|
|
|
|
// outside of /var. Sigh... as long as it still gets cleaned up,
|
|
|
|
// I guess it doesn't matter too much.
|
|
|
|
// See: https://github.com/caddyserver/caddy/issues/2036
|
|
|
|
// and https://twitter.com/mholt6/status/978345803365273600 (thread)
|
|
|
|
// (using an absolute path prevents problems later when removing this
|
|
|
|
// folder if the CWD changes)
|
|
|
|
var err error
|
|
|
|
parentDir, err = filepath.Abs(".")
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
2020-03-21 22:27:26 +00:00
|
|
|
ts := time.Now().Format(yearMonthDayHourMin)
|
2022-09-30 18:26:26 +01:00
|
|
|
return os.MkdirTemp(parentDir, fmt.Sprintf("buildenv_%s.", ts))
|
2020-03-21 20:31:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// versionedModulePath helps enforce Go Module's Semantic Import Versioning (SIV) by
|
|
|
|
// returning the form of modulePath with the major component of moduleVersion added,
|
|
|
|
// if > 1. For example, inputs of "foo" and "v1.0.0" will return "foo", but inputs
|
|
|
|
// of "foo" and "v2.0.0" will return "foo/v2", for use in Go imports and go commands.
|
|
|
|
// Inputs that conflict, like "foo/v2" and "v3.1.0" are an error. This function
|
|
|
|
// returns the input if the moduleVersion is not a valid semantic version string.
|
2020-04-22 23:29:57 +01:00
|
|
|
// If moduleVersion is empty string, the input modulePath is returned without error.
|
2020-03-21 20:31:29 +00:00
|
|
|
func versionedModulePath(modulePath, moduleVersion string) (string, error) {
|
2020-04-22 23:29:57 +01:00
|
|
|
if moduleVersion == "" {
|
|
|
|
return modulePath, nil
|
|
|
|
}
|
2020-03-21 20:31:29 +00:00
|
|
|
ver, err := semver.StrictNewVersion(strings.TrimPrefix(moduleVersion, "v"))
|
|
|
|
if err != nil {
|
|
|
|
// only return the error if we know they were trying to use a semantic version
|
|
|
|
// (could have been a commit SHA or something)
|
|
|
|
if strings.HasPrefix(moduleVersion, "v") {
|
2020-04-23 21:34:29 +01:00
|
|
|
return "", fmt.Errorf("%s: %v", moduleVersion, err)
|
2020-03-21 20:31:29 +00:00
|
|
|
}
|
|
|
|
return modulePath, nil
|
|
|
|
}
|
|
|
|
major := ver.Major()
|
|
|
|
|
|
|
|
// see if the module path has a major version at the end (SIV)
|
|
|
|
matches := moduleVersionRegexp.FindStringSubmatch(modulePath)
|
|
|
|
if len(matches) == 2 {
|
|
|
|
modPathVer, err := strconv.Atoi(matches[1])
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("this error should be impossible, but module path %s has bad version: %v", modulePath, err)
|
|
|
|
}
|
|
|
|
if modPathVer != int(major) {
|
|
|
|
return "", fmt.Errorf("versioned module path (%s) and requested module major version (%d) diverge", modulePath, major)
|
|
|
|
}
|
|
|
|
} else if major > 1 {
|
|
|
|
modulePath += fmt.Sprintf("/v%d", major)
|
|
|
|
}
|
|
|
|
|
|
|
|
return path.Clean(modulePath), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var moduleVersionRegexp = regexp.MustCompile(`.+/v(\d+)$`)
|
|
|
|
|
|
|
|
const (
|
2020-03-21 22:27:26 +00:00
|
|
|
// yearMonthDayHourMin is the date format
|
2020-03-21 20:31:29 +00:00
|
|
|
// used for temporary folder paths.
|
2020-03-21 22:27:26 +00:00
|
|
|
yearMonthDayHourMin = "2006-01-02-1504"
|
2020-03-21 20:31:29 +00:00
|
|
|
|
|
|
|
defaultCaddyModulePath = "github.com/caddyserver/caddy"
|
|
|
|
)
|