From 134e74d60f924c761d6d5b7cc46c04b77b1081a0 Mon Sep 17 00:00:00 2001 From: Jamie Phillips Date: Fri, 22 Jul 2022 09:44:04 -0400 Subject: [PATCH] Migrating the build to mage and fixing the binary location issue. --- .drone.yml | 68 ++-- .gitignore | 2 + Dockerfile | 71 +--- README.md | 18 +- go.mod | 6 +- go.sum | 10 +- magefiles/magefile.go | 153 ++++++++ magetools/gotool.go | 38 ++ magetools/helpers.go | 34 ++ make.ps1 | 99 ------ package/windows/Dockerfile | 17 - package/windows/install.ps1 | 672 ------------------------------------ package/windows/run.ps1 | 136 -------- scripts/build.ps1 | 57 --- scripts/ci.ps1 | 61 ---- scripts/package.ps1 | 18 - scripts/release.ps1 | 0 scripts/test.ps1 | 22 -- scripts/utils.psm1 | 52 --- scripts/validate.ps1 | 22 -- scripts/version.ps1 | 54 --- 21 files changed, 276 insertions(+), 1334 deletions(-) create mode 100644 magefiles/magefile.go create mode 100644 magetools/gotool.go create mode 100644 magetools/helpers.go delete mode 100644 make.ps1 delete mode 100644 package/windows/Dockerfile delete mode 100644 package/windows/install.ps1 delete mode 100644 package/windows/run.ps1 delete mode 100644 scripts/build.ps1 delete mode 100644 scripts/ci.ps1 delete mode 100644 scripts/package.ps1 delete mode 100644 scripts/release.ps1 delete mode 100644 scripts/test.ps1 delete mode 100644 scripts/utils.psm1 delete mode 100644 scripts/validate.ps1 delete mode 100644 scripts/version.ps1 diff --git a/.drone.yml b/.drone.yml index ce56f321..d4864bec 100644 --- a/.drone.yml +++ b/.drone.yml @@ -10,23 +10,19 @@ platform: steps: - name: build - image: plugins/docker - pull: always - settings: - dry_run: true - purge: true - build_args: - - SERVERCORE_VERSION=1809 - - ARCH=amd64 - - ACTION=ci - - MAINTAINERS=ross.kirkpatrick@suse.com jamie.phillips@suse.com - - REPO=https://github.com/rancher/wins - custom_dns: 1.1.1.1 - dockerfile: Dockerfile - repo: rancher/wins - volumes: - - name: docker_pipe - path: \\\\.\\pipe\\docker_engine + image: golang:1.18-windowsservercore + environment: + MAGEFILE_CACHE: C:/Drone/.magefile + commands: + - go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.44.0 + - go install github.com/onsi/ginkgo/ginkgo@latest + - go get -u github.com/onsi/gomega/... + - cd .. + - git clone https://github.com/magefile/mage.git + - cd mage + - go run bootstrap.go install + - cd C:/Drone/src + - mage ci - name: publish image: plugins/docker @@ -35,8 +31,6 @@ steps: build_args: - SERVERCORE_VERSION=1809 - ARCH=amd64 - - VERSION=${DRONE_TAG} - - ACTION=ci - MAINTAINERS=ross.kirkpatrick@suse.com jamie.phillips@suse.com - REPO=https://github.com/rancher/wins custom_dns: 1.1.1.1 @@ -68,9 +62,12 @@ steps: - sha256 - sha512 files: - - C:\\wins.exe + - C:/wins.exe file_exists: - fail + volumes: + - name: root + path: C:/ when: instance: - drone-publish.rancher.io @@ -109,22 +106,19 @@ steps: image: rancher/drone-images:git-amd64-ltsc2022 - name: build - image: rancher/drone-images:docker-amd64-ltsc2022 - settings: - dry_run: true - purge: true - build_args: - - SERVERCORE_VERSION=ltsc2022 - - ARCH=amd64 - - ACTION=ci - - MAINTAINERS=ross.kirkpatrick@suse.com jamie.phillips@suse.com - - REPO=https://github.com/rancher/wins - custom_dns: 1.1.1.1 - dockerfile: Dockerfile - repo: rancher/wins - volumes: - - name: docker_pipe - path: \\\\.\\pipe\\docker_engine + image: golang:1.18-windowsservercore + environment: + MAGEFILE_CACHE: C:/Drone/.magefile + commands: + - go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.44.0 + - go install github.com/onsi/ginkgo/ginkgo@latest + - go get -u github.com/onsi/gomega/... + - cd .. + - git clone https://github.com/magefile/mage.git + - cd mage + - go run bootstrap.go install + - cd C:/Drone/src + - mage ci - name: publish @@ -134,8 +128,6 @@ steps: build_args: - SERVERCORE_VERSION=ltsc2022 - ARCH=amd64 - - VERSION=${DRONE_TAG} - - ACTION=ci - MAINTAINERS=ross.kirkpatrick@suse.com jamie.phillips@suse.com - REPO=https://github.com/rancher/wins custom_dns: 1.1.1.1 diff --git a/.gitignore b/.gitignore index b0ae061f..a0a0af68 100644 --- a/.gitignore +++ b/.gitignore @@ -35,3 +35,5 @@ Dockerfile.dapper[0-9]* dist/ *.tgz + +artifacts/ diff --git a/Dockerfile b/Dockerfile index 45035c87..9eb35a84 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,73 +1,4 @@ ARG SERVERCORE_VERSION -FROM library/golang:1.17.7 as base -SHELL ["powershell", "-NoLogo", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"] - -RUN pushd c:\; \ - $URL = 'https://github.com/StefanScherer/docker-cli-builder/releases/download/20.10.5/docker.exe'; \ - Write-Host ('Downloading docker from {0} ...' -f $URL); \ - curl.exe -sfL $URL -o c:\Windows\docker.exe; \ - Write-Host 'docker install complete.'; \ - popd; - -RUN pushd c:\ ; \ - $URL = 'https://github.com/cli/cli/releases/download/v2.14.2/gh_2.14.2_windows_amd64.zip' ; \ - Write-Host ('Downloading github cli from {0} ...' -f $URL); \ - curl.exe -sfL $URL -o c:\gh.zip; \ - Write-Host 'Expanding ...'; \ - Expand-Archive -Path c:\gh.zip -DestinationPath c:\gh_2.14.2_windows_amd64; \ - Write-Host 'Cleaning ...'; \ - Remove-Item -Force -Recurse -Path c:\gh.zip; \ - Write-Host 'Updating PATH ...'; \ - [Environment]::SetEnvironmentVariable('PATH', ('c:\gh_2.14.2_windows_amd64\bin\;{0}' -f $env:PATH), [EnvironmentVariableTarget]::Machine); \ - Write-Host 'github cli install complete.'; \ - popd - -RUN pushd c:\; \ - $URL = 'https://github.com/golangci/golangci-lint/releases/download/v1.44.0/golangci-lint-1.44.0-windows-amd64.zip'; \ - Write-Host ('Downloading golangci from {0} ...' -f $URL); \ - curl.exe -sfL $URL -o c:\golangci-lint.zip; \ - Write-Host 'Expanding ...'; \ - Expand-Archive -Path c:\golangci-lint.zip -DestinationPath c:\; \ - Write-Host 'Cleaning ...'; \ - Remove-Item -Force -Recurse -Path c:\golangci-lint.zip; \ - Write-Host 'Updating PATH ...'; \ - [Environment]::SetEnvironmentVariable('PATH', ('c:\golangci-lint-1.44.0-windows-amd64\;{0}' -f $env:PATH), [EnvironmentVariableTarget]::Machine); \ - Write-Host 'golangci-lint install complete.'; \ - popd; - -# upgrade git -RUN pushd c:\; \ - $URL = 'https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/MinGit-2.33.0.2-64-bit.zip'; \ - Write-Host ('Downloading git from {0} ...' -f $URL); \ - [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; \ - Invoke-WebRequest -UseBasicParsing -OutFile c:\git.zip -Uri $URL; \ - Write-Host 'Expanding ...'; \ - Expand-Archive -Force -Path c:\git.zip -DestinationPath c:\git\.; \ - Write-Host 'Cleaning ...'; \ - Remove-Item -Force -Recurse -Path c:\git.zip; \ - Write-Host 'git install complete.'; \ - popd; - -# install ginkgo -RUN pushd c:\; \ - Write-Host ('Updating ginkgo ...'); \ - go install github.com/onsi/ginkgo/ginkgo@latest; \ - go get -u github.com/onsi/gomega/...; \ - Write-Host 'Ginkgo install complete.'; \ - popd; - -COPY . /go/wins/ -WORKDIR C:/ - -ARG ACTION -ARG DRONE_TAG -ENV DRONE_TAG ${DRONE_TAG} - -ENV ACTION ${ACTION} -RUN Write-Host "Starting CI Action ($env:ACTION) for wins"; \ - Set-Location C:/go/wins/ ; \ - ./scripts/ci.ps1 "$env:ACTION" - FROM mcr.microsoft.com/windows/servercore:${SERVERCORE_VERSION} as wins ARG VERSION ARG MAINTAINERS @@ -88,7 +19,7 @@ LABEL org.opencontainers.image.vendor="Rancher Labs" LABEL org.opencontainers.image.version=${VERSION} WORKDIR C:/ -COPY --from=base C:/package/ C:/ +COPY ./artifacts C:/ # staging for backwards compatibility # Create a symbolic link pwsh.exe that points to powershell.exe for consistency RUN New-Item -ItemType SymbolicLink -Target "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Path "C:\Windows\System32\WindowsPowerShell\v1.0\pwsh.exe" ; \ diff --git a/README.md b/README.md index 84277f6c..ed29e79e 100644 --- a/README.md +++ b/README.md @@ -214,18 +214,10 @@ tls-config: ## Build -``` powershell -# Build inside a Docker container - -> .\make.ps1 build - -# Build using Powershell scripts only +This project uses magefile to build. The default target is build. -> .\make.ps1 no-docker build - -# Build locally using drone (Docker-In-Docker) - -> drone.exe exec --trusted --pipeline=windows-1809 --include=build --event=pull_request --ref="$(git rev-parse --short HEAD)" --sha="$(git show -s --format=%H)" .drone.yml +``` powershell +> go run mage.go ``` ## Testing @@ -236,13 +228,13 @@ and integration test. For validation test, which could be embedded into a containerized CI flow, please run the below command in `PowerShell`: ``` powershell -> .\make.ps1 validate +> go run mage.go validate ``` For integration test, please run the below command in `PowerShell`: ``` powershell -> .\make.ps1 integration +> go run mage.go integration ``` > Note: Don't use `bin/wins.exe` after integration testing. Please `.\make.ps1 build` again. diff --git a/go.mod b/go.mod index df01bd43..84fb8fa2 100644 --- a/go.mod +++ b/go.mod @@ -61,6 +61,8 @@ require ( ) +require github.com/magefile/mage v1.13.0 + require ( github.com/PuerkitoBio/purell v1.1.1 // indirect github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect @@ -98,6 +100,7 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/onsi/gomega v1.20.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.0.3-0.20220114050600-8b9d41f48198 // indirect github.com/pierrec/lz4 v2.6.1+incompatible // indirect @@ -113,7 +116,7 @@ require ( github.com/urfave/cli v1.22.9 // indirect github.com/vbatts/tar-split v0.11.2 // indirect go.opencensus.io v0.23.0 // indirect - golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e // indirect + golang.org/x/net v0.0.0-20220722155237-a158d28d115b // indirect golang.org/x/oauth2 v0.0.0-20220628200809-02e64fa58f26 // indirect golang.org/x/term v0.0.0-20220526004731-065cf7ba2467 // indirect golang.org/x/text v0.3.7 // indirect @@ -122,6 +125,7 @@ require ( google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20220421151946-72621c1f0bd3 // indirect google.golang.org/protobuf v1.28.0 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index 9425e35f..9d730668 100644 --- a/go.sum +++ b/go.sum @@ -606,6 +606,8 @@ github.com/lithammer/dedent v1.1.0/go.mod h1:jrXYCQtgg0nJiN+StA2KgR7w6CiQNv9Fd/Z github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= github.com/lpabon/godbc v0.1.1/go.mod h1:Jo9QV0cf3U6jZABgiJ2skINAXb9j8m51r07g4KI92ZA= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= +github.com/magefile/mage v1.13.0 h1:XtLJl8bcCM7EFoO8FyH8XK3t7G5hQAeK+i4tq+veT9M= +github.com/magefile/mage v1.13.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= @@ -701,7 +703,6 @@ github.com/mwitkow/go-proto-validators v0.2.0/go.mod h1:ZfA1hW+UH/2ZHOWvQ3HnQaU0 github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= github.com/nakabonne/nestif v0.3.1/go.mod h1:9EtoZochLn5iUprVDmDjqGKPofoUEBL8U4Ngq6aY7OE= github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354/go.mod h1:KSVJerMDfblTH7p5MZaTt+8zaT2iEk3AkVb9PQdZuE8= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nishanths/exhaustive v0.2.3/go.mod h1:bhIX678Nx8inLM9PbpvK1yv6oGtoP8BfaIeMzgBNKvc= github.com/nishanths/predeclared v0.0.0-20190419143655-18a43bb90ffc/go.mod h1:62PewwiQTlm/7Rj+cxVYqZvDIUc+JjZq6GHAC1fsObQ= @@ -732,6 +733,8 @@ github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1y github.com/onsi/gomega v1.15.0/go.mod h1:cIuvLEne0aoVhAgh/O6ac0Op8WWw9H6eYCriF+tEHG0= github.com/onsi/gomega v1.16.0 h1:6gjqkI8iiRHMvdccRJM8rVKjCWk6ZIm6FTm3ddIe4/c= github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/onsi/gomega v1.20.0 h1:8W0cWlwFkflGPLltQvLRB7ZVD5HuP6ng320w2IS245Q= +github.com/onsi/gomega v1.20.0/go.mod h1:DtrZpjmvpn2mPm4YWQa0/ALMDj9v4YxLgojwPeREyVo= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= @@ -1147,6 +1150,8 @@ golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e h1:TsQ7F31D3bUCLeqPT0u+yjp1guoArKaNKmCr22PYgTQ= golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b h1:PxfKdU9lEEDYjdIzOtC4qFWgkU2rGHdKlKowJSMN9h0= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/oauth2 v0.0.0-20220524215830-622c5d57e401 h1:zwrSfklXn0gxyLRX/aR+q6cgHbV/ItVyzbPlbA+dkAw= golang.org/x/oauth2 v0.0.0-20220524215830-622c5d57e401/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= golang.org/x/sync v0.0.0-20220513210516-0976fa681c29 h1:w8s32wxx3sY+OjLlv9qltkLU5yvJzxjjgiHWLjdIcw4= @@ -1558,8 +1563,9 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/cheggaaa/pb.v1 v1.0.28/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= diff --git a/magefiles/magefile.go b/magefiles/magefile.go new file mode 100644 index 00000000..7e04eb35 --- /dev/null +++ b/magefiles/magefile.go @@ -0,0 +1,153 @@ +//go:build mage + +package main + +import ( + "errors" + "fmt" + "log" + "os" + "path/filepath" + "strings" + + "github.com/magefile/mage/mg" + "github.com/magefile/mage/sh" + "github.com/rancher/wins/magetools" +) + +var Default = Build +var g *magetools.Go +var version string +var commit string +var artifactOutput = filepath.Join("artifacts") + +func Clean() error { + if err := sh.Rm(artifactOutput); err != nil { + return err + } + return sh.Rm("bin") +} + +func Version() error { + c, err := magetools.GetCommit() + if err != nil { + return err + } + commit = c + + dt := os.Getenv("DRONE_TAG") + isClean, err := magetools.IsGitClean() + if err != nil { + return err + } + if dt != "" && isClean { + version = dt + return nil + } + + tag, err := magetools.GetLatestTag() + if err != nil { + return err + } + if tag != "" && isClean { + version = tag + return nil + } + + version = commit + "-dirty" + return nil +} + +func Setup() { + mg.Deps(Version) + g = magetools.NewGo("amd64", "windows", version, commit, "0") +} + +func Dependencies() error { + mg.Deps(Setup) + return g.Mod("download") +} + +func Validate() error { + envs := map[string]string{"GOOS": "windows", "ARCH": "amd64", "CGO_ENABLED": "0"} + + log.Printf("[build] Running: golangci-lint \n") + if err := sh.RunWithV(envs, "golangci-lint", "run"); err != nil { + return err + } + + log.Printf("[build] Running: go fmt \n") + if err := sh.RunWithV(envs, "go", "fmt", "./..."); err != nil { + return err + } + + log.Printf("validate has completed successfully \n") + return nil +} + +func Build() error { + mg.Deps(Clean, Dependencies, Validate) + + winsOutput := filepath.Join("bin", "wins.exe") + + log.Printf("[build] Building wins version %s \n", version) + log.Printf("[build] Output: %s \n", winsOutput) + if err := g.Build(flags, "cmd/main.go", winsOutput); err != nil { + return err + } + log.Printf("[build] successfully built wins version version %s \n", version) + + log.Printf("[build] now staging build artifacts \n") + if err := os.MkdirAll(artifactOutput, os.ModePerm); err != nil { + return err + } + + if err := sh.Copy(filepath.Join(artifactOutput, "install.ps1"), "install.ps1"); err != nil { + return err + } + + if err := sh.Copy(filepath.Join(artifactOutput, "wins.exe"), winsOutput); err != nil { + return err + } + + if err := sh.Copy(filepath.Join(artifactOutput, "run.ps1"), filepath.Join("suc", "run.ps1")); err != nil { + return err + } + + log.Printf("[build] all required build artifacts have been staged \n") + files, err := os.ReadDir(artifactOutput) + if err != nil { + return err + } + + if len(files) != 3 { + return errors.New("[package] a required build artifact is missing, exiting now \n") + } + + var artifacts strings.Builder + for _, file := range files { + artifacts.WriteString(file.Name() + " ,") + } + + log.Printf("[build] artifacts copied: %s \n", artifacts.String()) + + return nil +} + +func Test() error { + mg.Deps(Build) + log.Printf("[build] Testing wins version %s \n", version) + if err := g.Test(flags, "./..."); err != nil { + return err + } + log.Printf("[build] successfully tested wins version version %s \n", version) + return nil +} + +func CI() { + mg.Deps(Test) +} + +func flags(version string, commit string) string { + return fmt.Sprintf(`-s -w -X github.com/rancher/wins/pkg/defaults.AppVersion=%s -X github.com/rancher/wins/pkg/defaults.AppCommit=%s -extldflags "-static"`, version, commit) +} diff --git a/magetools/gotool.go b/magetools/gotool.go new file mode 100644 index 00000000..d4e1b781 --- /dev/null +++ b/magetools/gotool.go @@ -0,0 +1,38 @@ +package magetools + +import ( + "github.com/magefile/mage/sh" +) + +type Go struct { + Arch string + OS string + Version string + Commit string + CGoEnabled string +} + +func NewGo(arch, goos, version, commit, cgoEnabled string) *Go { + return &Go{ + Arch: arch, + OS: goos, + Version: version, + Commit: commit, + CGoEnabled: cgoEnabled, + } +} + +func (g *Go) Build(flags func(string, string) string, target, output string) error { + envs := map[string]string{"GOOS": g.OS, "ARCH": g.Arch, "CGO_ENABLED": g.CGoEnabled} + return sh.RunWithV(envs, "go", "build", "-o", output, "--ldflags="+flags(g.Version, g.Commit), target) +} + +func (g *Go) Test(flags func(string, string) string, target string) error { + envs := map[string]string{"GOOS": g.OS, "ARCH": g.Arch, "CGO_ENABLED": g.CGoEnabled} + return sh.RunWithV(envs, "go", "test", "-v", "-cover", "--ldflags="+flags(g.Version, g.Commit), target) +} + +func (g *Go) Mod(cmd string) error { + envs := map[string]string{"GOOS": g.OS, "ARCH": g.Arch} + return sh.RunWithV(envs, "go", "mod", cmd) +} diff --git a/magetools/helpers.go b/magetools/helpers.go new file mode 100644 index 00000000..91bd70ae --- /dev/null +++ b/magetools/helpers.go @@ -0,0 +1,34 @@ +package magetools + +import ( + "strings" + + "github.com/magefile/mage/sh" +) + +func IsGitClean() (bool, error) { + result, err := sh.Output("git", "status", "--porcelain", "--untracked-files=no") + if err != nil { + return false, err + } + if result != "" { + return false, nil + } + return true, nil +} + +func GetLatestTag() (string, error) { + result, err := sh.Output("git", "tag", "-l", "--contains", "HEAD") + if err != nil { + return "", err + } + return strings.TrimSpace(result), nil +} + +func GetCommit() (string, error) { + result, err := sh.Output("git", "rev-parse", "--short", "HEAD") + if err != nil { + return "", err + } + return strings.TrimSpace(result), nil +} diff --git a/make.ps1 b/make.ps1 deleted file mode 100644 index cce62f61..00000000 --- a/make.ps1 +++ /dev/null @@ -1,99 +0,0 @@ -#Requires -Version 5.0 - -$ErrorActionPreference = 'Stop' - -Import-Module -WarningAction Ignore -Name "$PSScriptRoot\scripts\utils.psm1" - -function WinsCIAction() { - param ( - [parameter(Mandatory = $true, ValueFromPipeline = $true)] [string]$Action - ) - Invoke-Expression -Command "$PSScriptRoot\scripts\version.ps1" - - $IMAGE = ('{0}/wins:{1}-windows-{2}' -f $env:REPO, $env:TAG, $env:SERVERCORE_VERSION) - Write-Host -ForegroundColor Yellow "Starting docker build of $IMAGE`n" - Write-Host "CI Action: $Action" - Write-Host "VERSION = $env:TAG" - - docker build ` - --build-arg SERVERCORE_VERSION=$env:SERVERCORE_VERSION ` - --build-arg ACTION=$Action ` - --build-arg VERSION=$env:VERSION ` - --build-arg DRONE_TAG=$env:DRONE_TAG ` - --build-arg MAINTAINERS=$env:MAINTAINERS ` - --build-arg REPO=https://github.com/rancher/wins ` - --tag $IMAGE ` - -f Dockerfile . - - if ($LASTEXITCODE -ne 0) { - $env:TAG="" - $env:VERSION="" - $env:SERVERCORE_VERSION="" - exit $LASTEXITCODE - } - Write-Host -ForegroundColor Green "Successfully built $IMAGE`n" - Write-Host -ForegroundColor Green "Attempting to stage wins binary for $env:VERSION`n" - docker cp $IMAGE:C:\\wins.exe C:\\wins.exe - Write-Host -ForegroundColor Green "Successfully staged wins binary from $IMAGE`n" -} - -trap { - Write-Host -NoNewline -ForegroundColor Red "[ERROR]: " - Write-Host -ForegroundColor Red "$_" - - Pop-Location - exit 1 -} - -if ($args[0] -eq "integration") { - Write-Host "Running Integration Tests" - WinsCIAction -Action "integration" - exit -} - -if ($args[0] -eq "build" -or $args[0] -eq "package") { - Write-Host "Building wins" - WinsCIAction -Action "build" - exit -} - -if ($args[0] -eq "package") { - Write-Host "Building and Packaging wins" - WinsCIAction -Action "build" - WinsCIAction -Action "package" - exit -} - -if ($args[0] -eq "all" -or $args.Count -eq 0 -or $args[0] -eq "ci") { - Write-Host "Running CI and Integration Tests" - WinsCIAction -Action "ci" - exit -} - -if ($args[0] -eq "no-docker") { - if ($args[1] -eq "") { - Write-Host "Running CI without Docker" - Invoke-Expression -Command "scripts\ci.ps1 ci" - } else { - Write-Host ('Running {0}.ps1 without Docker' -f $($args[1])) - Invoke-Expression -Command "scripts\ci.ps1 $($args[1])" - } - exit -} - -if ($args[0] -eq "clean") { - Remove-Item .dapper.exe - Remove-Item Dockerfile.dapper* -Exclude "Dockerfile.dapper" -} - -if ($args[0] -eq "build") { - Write-Host "Building" - .dapper.exe -f Dockerfile.dapper build - exit -} - -if (Test-Path scripts\$($args[0]).ps1) { - WinsCIAction -Action "$($args[0])" - exit -} - diff --git a/package/windows/Dockerfile b/package/windows/Dockerfile deleted file mode 100644 index 4ef03b1d..00000000 --- a/package/windows/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -ARG SERVERCORE_VERSION - -FROM mcr.microsoft.com/windows/servercore:${SERVERCORE_VERSION} as download -ENV ARCH=amd64 - -SHELL ["powershell", "-NoLogo", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"] - -# Create a symbolic link pwsh.exe that points to powershell.exe for consistency -RUN New-Item -ItemType SymbolicLink -Target "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Path "C:\Windows\System32\WindowsPowerShell\v1.0\pwsh.exe" - -COPY ./wins.exe /Windows/ -COPY ./wins.exe wins.exe -COPY ./install.ps1 install.ps1 -COPY ./run.ps1 run.ps1 -#USER ContainerAdministrator - -ENTRYPOINT [ "powershell", "-Command", "./run.ps1"] diff --git a/package/windows/install.ps1 b/package/windows/install.ps1 deleted file mode 100644 index e4aeb23a..00000000 --- a/package/windows/install.ps1 +++ /dev/null @@ -1,672 +0,0 @@ -<# -.SYNOPSIS - Installs Rancher Wins to create Windows Worker Nodes. -.DESCRIPTION - Run the script to install all Rancher Wins related needs. -.NOTES - Environment variables: - System Agent Variables - - CATTLE_AGENT_LOGLEVEL (default: debug) - - CATTLE_AGENT_CONFIG_DIR (default: C:/etc/rancher/agent) - - CATTLE_AGENT_VAR_DIR (default: C:/var/lib/rancher/agent) - Rancher 2.6+ Variables - - CATTLE_SERVER - - CATTLE_TOKEN - - CATTLE_CA_CHECKSUM - - CATTLE_ROLE_CONTROLPLANE=false - - CATTLE_ROLE_ETCD=false - - CATTLE_ROLE_WORKER=false - - CATTLE_LABELS - - CATTLE_TAINTS - Advanced Environment Variables - - CATTLE_AGENT_BINARY_URL (default: latest GitHub release) - - CATTLE_PRESERVE_WORKDIR (default: false) - - CATTLE_REMOTE_ENABLED (default: true) - - CATTLE_ID (default: autogenerate) - - CATTLE_AGENT_BINARY_LOCAL (default: false) - - CATTLE_AGENT_BINARY_LOCAL_LOCATION (default: ) - - CSI_PROXY_URL (default: ) - - CSI_PROXY_VERSION (default: ) - - CSI_PROXY_KUBELET_PATH (default: ) -.EXAMPLE - -#> -#Make sure this params matches the CmdletBinding below -param ( - [Parameter()] - [String] - $Address, - [Parameter()] - [String] - $CaChecksum, - [Parameter()] - [String] - $InternalAddress, - [Parameter()] - [String] - $Label, - [Parameter()] - [String] - $NodeName, - [Parameter()] - [String] - $Server, - [Parameter()] - [String] - $Taint, - [Parameter()] - [String] - $Token, - [Parameter()] - [Switch] - $Worker -) -$ErrorActionPreference = 'Stop' -Set-StrictMode -Version Latest - -$FALLBACK = "v0.1.1" - -function Invoke-WinsInstaller { - [CmdletBinding()] - param ( - [Parameter()] - [String] - $Address, - [Parameter()] - [String] - $CaChecksum, - [Parameter()] - [String] - $InternalAddress, - [Parameter()] - [String] - $Label, - [Parameter()] - [String] - $NodeName, - [Parameter()] - [String] - $Server, - [Parameter()] - [String] - $Taint, - [Parameter()] - [String] - $Token, - [Parameter()] - [Switch] - $Worker - ) - - [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12 - - function Write-LogInfo { - Write-Host -NoNewline -ForegroundColor Blue "INFO: " - Write-Host -ForegroundColor Gray ("{0,-44}" -f ($args -join " ")) - } - function Write-LogWarn { - Write-Host -NoNewline -ForegroundColor DarkYellow "WARN: " - Write-Host -ForegroundColor Gray ("{0,-44}" -f ($args -join " ")) - } - function Write-LogError { - Write-Host -NoNewline -ForegroundColor DarkRed "ERROR: " - Write-Host -ForegroundColor Gray ("{0,-44}" -f ($args -join " ")) - } - function Write-LogFatal { - Write-Host -NoNewline -ForegroundColor DarkRed "FATA: " - Write-Host -ForegroundColor Gray ("{0,-44}" -f ($args -join " ")) - exit 255 - } - - function Get-StringHash { - [CmdletBinding()] - param ( - [Parameter()] - [string] - $Value - ) - $stringAsStream = [System.IO.MemoryStream]::new() - $writer = [System.IO.StreamWriter]::new($stringAsStream) - $writer.write($Value) - $writer.Flush() - $stringAsStream.Position = 0 - return (Get-FileHash -InputStream $stringAsStream -Algorithm SHA256).Hash.ToLower() - } - - function Get-Args { - if ($Address) { - $env:CATTLE_ADDRESS = $Address - } - - if ($CaChecksum) { - $env:CATTLE_CA_CHECKSUM = $CaChecksum - } - - if ($InternalAddress) { - $env:CATTLE_INTERNAL_ADDRESS = $InternalAddress - } - - if ($Label) { - if ($env:CATTLE_LABELS) { - $env:CATTLE_LABELS += ",$Label" - } - else { - $env:CATTLE_LABELS = $Label - } - } - - if ($NodeName) { - $env:CATTLE_NODE_NAME = $NodeName - } - - if ($Server) { - $env:CATTLE_SERVER = $Server - } - - if ($Taint) { - if ($env:CATTLE_TAINTS) { - $env:CATTLE_TAINTS += ",$Taint" - } - else { - $env:CATTLE_TAINTS = $Taint - } - } - - if ($Token) { - $env:CATTLE_TOKEN = $Token - } - - if ($Worker) { - $env:CATTLE_ROLE_WORKER = "true" - } - } - - function Set-Path { - $env:PATH += ";C:\var\lib\rancher\rke2\bin;C:\usr\local\bin" - $environment = [System.Environment]::GetEnvironmentVariable("Path", "Machine") - $environment = $environment.Insert($environment.Length, ";C:\var\lib\rancher\rke2\bin;C:\usr\local\bin") - [System.Environment]::SetEnvironmentVariable("Path", $environment, "Machine") - } - - function Set-Environment { - $env:CURL_CAFLAG = "--ssl-no-revoke" - - if (-Not $env:CATTLE_ROLE_CONTROLPLANE) { - $env:CATTLE_ROLE_CONTROLPLANE = "false" - } - - if (-Not $env:CATTLE_ROLE_ETCD) { - $env:CATTLE_ROLE_ETCD = "false" - } - - if (-Not $env:CATTLE_ROLE_WORKER) { - $env:CATTLE_ROLE_WORKER = "false" - } - - if (-Not $env:CATTLE_REMOTE_ENABLED) { - $env:CATTLE_REMOTE_ENABLED = "true" - } - else { - $env:CATTLE_REMOTE_ENABLED = $env:CATTLE_REMOTE_ENABLED.ToLower() - } - - if (-Not $env:CATTLE_PRESERVE_WORKDIR) { - $env:CATTLE_PRESERVE_WORKDIR = "false" - } - else { - $env:CATTLE_PRESERVE_WORKDIR = $env:CATTLE_PRESERVE_WORKDIR.ToLower() - } - - if (-Not $env:CATTLE_AGENT_LOGLEVEL) { - $env:CATTLE_AGENT_LOGLEVEL = "debug" - } - else { - $env:CATTLE_AGENT_LOGLEVEL = $env:CATTLE_AGENT_LOGLEVEL.ToLower() - } - - if ($env:CATTLE_AGENT_BINARY_LOCAL -eq "true") { - if (-Not $env:CATTLE_AGENT_BINARY_LOCAL_LOCATION) { - Write-LogFatal "No local binary location was specified" - } - $env:BINARY_SOURCE = "local" - } - else { - $env:BINARY_SOURCE = "remote" - if (-Not $env:CATTLE_AGENT_BINARY_URL -and $env:CATTLE_AGENT_BINARY_BASE_URL) { - $env:CATTLE_AGENT_BINARY_URL = "$env:CATTLE_AGENT_BINARY_BASE_URL/wins.exe" - } - - if (-Not $env:CATTLE_AGENT_BINARY_URL) { - $rateLimit = $(curl.exe --connect-timeout 60 --max-time 300 $env:CURL_CAFLAG -sfL "https://api.github.com/rate_limit") | ConvertFrom-Json - - if ($rateLimit.rate.remaining -eq 0) { - Write-LogInfo "Error contacting GitHub to retrieve the latest version, falling back to version: $FALLBACK" - $env:VERSION = $FALLBACK - } - else { - try { - $env:VERSION = $(curl.exe --connect-timeout 60 $env:CURL_CAFLAG -sfL "https://api.github.com/repos/rancher/wins/releases/latest" | ConvertFrom-Json).tag_name - } - catch { - Write-LogInfo "Error contacting GitHub to retrieve the latest version, falling back to version: $FALLBACK" - $env:VERSION = $FALLBACK - } - } - - $env:CATTLE_AGENT_BINARY_URL = "https://github.com/rancher/wins/releases/download/$env:VERSION/wins.exe" - $env:BINARY_SOURCE = "upstream" - } - } - - if ($env:CATTLE_REMOTE_ENABLED -eq "true") { - if (-Not $env:CATTLE_TOKEN) { - Write-LogFatal "Environment variable CATTLE_TOKEN was not set. Will not retrieve a remote connection configuration from Rancher2" - } - if (-Not $env:CATTLE_SERVER) { - Write-LogFatal "Environment variable CATTLE_SERVER was not set" - } - } - - if (-Not $env:CATTLE_AGENT_CONFIG_DIR) { - $env:CATTLE_AGENT_CONFIG_DIR = "C:/etc/rancher/wins" - Write-LogInfo "Using default agent configuration directory $( $env:CATTLE_AGENT_CONFIG_DIR )" - } - if (-Not (Test-Path $env:CATTLE_AGENT_CONFIG_DIR)) { - New-Item -Path $env:CATTLE_AGENT_CONFIG_DIR -ItemType Directory -Force | Out-Null - } - - # copy powershell for wins - Copy-Item $($(Get-Command powershell).Source) "$env:CATTLE_AGENT_CONFIG_DIR/powershell.exe" - - if (-Not $env:CATTLE_AGENT_VAR_DIR) { - $env:CATTLE_AGENT_VAR_DIR = "C:/var/lib/rancher/agent" - Write-LogInfo "Using default agent var directory $( $env:CATTLE_AGENT_VAR_DIR )" - } - if (-Not (Test-Path $env:CATTLE_AGENT_VAR_DIR)) { - New-Item -Path $env:CATTLE_AGENT_VAR_DIR -ItemType Directory -Force | Out-Null - } - - if (-Not $env:CATTLE_AGENT_BIN_PREFIX) { - $env:CATTLE_AGENT_BIN_PREFIX = "c:/usr/local" - } - if (-Not (Test-Path $env:CATTLE_AGENT_BIN_PREFIX)) { - New-Item -Path $env:CATTLE_AGENT_BIN_PREFIX -ItemType Directory -Force | Out-Null - } - - $env:CATTLE_ADDRESS = Get-Address -Value $env:CATTLE_ADDRESS - $env:CATTLE_INTERNAL_ADDRESS = Get-Address -Value $env:CATTLE_INTERNAL_ADDRESS - } - - function Test-Architecture() { - if ($env:PROCESSOR_ARCHITECTURE -ne "AMD64") { - Write-LogFatal "Unsupported architecture $( $env:PROCESSOR_ARCHITECTUR )" - } - } - - function Invoke-WinsAgentDownload() { - if (-Not (Test-Path "$env:CATTLE_AGENT_BIN_PREFIX/bin")) { - New-Item -Path "$env:CATTLE_AGENT_BIN_PREFIX/bin" -ItemType Directory -Force | Out-Null - } - - if ($env:CATTLE_AGENT_BINARY_LOCAL -eq "true") { - Write-LogInfo "Using local Wins installer from $($env:CATTLE_AGENT_BINARY_LOCAL_LOCATION)" - Copy-Item -Path $env:CATTLE_AGENT_BINARY_LOCAL_LOCATION -Destination "$env:CATTLE_AGENT_BIN_PREFIX/bin/wins.exe" - } - else { - Write-LogInfo "Downloading Wins from $($env:CATTLE_AGENT_BINARY_URL)" - if ($env:BINARY_SOURCE -ne "upstream") { - $env:CURL_BIN_CAFLAG = $env:CURL_CAFLAG - } - else { - $env:CURL_BIN_CAFLAG = "" - } - - $retries = 0 - while ($retries -lt 6) { - $responseCode = $(curl.exe --connect-timeout 60 --max-time 300 --write-out "%{http_code}\n" $env:CURL_BIN_CAFLAG -sfL "$($env:CATTLE_AGENT_BINARY_URL)" -o "$env:CATTLE_AGENT_BIN_PREFIX/bin/wins.exe") - - switch ( $responseCode ) { - { "ok200", 200 } { - Write-LogInfo "Successfully downloaded the wins binary." - $retries = 99 - break - } - default { - Write-LogError "$responseCode received while downloading the wins binary. Sleeping for 5 seconds and trying again." - Start-Sleep -Seconds 5 - $retries++ - continue - } - } - } - } - if (-Not (Test-Path "$env:CATTLE_AGENT_BIN_PREFIX/bin/wins.exe")) { - Write-LogFatal "Wins.exe doesn't appear to have been installed." - } - } - - function Test-CaCheckSum() { - $caCertsPath = "cacerts" - $env:RANCHER_CERT = Join-Path -Path $env:CATTLE_AGENT_CONFIG_DIR -ChildPath "ranchercert" - if (-Not $env:CATTLE_CA_CHECKSUM) { - return - } - - curl.exe --insecure -sfL $env:CATTLE_SERVER/$caCertsPath -o $env:RANCHER_CERT - if (-Not(Test-Path -Path $env:RANCHER_CERT)) { - Write-Error "The environment variable CATTLE_CA_CHECKSUM is set but there is no CA certificate configured at $( $env:CATTLE_SERVER )/$( $caCertsPath )) " - exit 1 - } - - if ($LASTEXITCODE -ne 0) { - Write-Error "Value from $( $env:CATTLE_SERVER )/$( $caCertsPath ) does not look like an x509 certificate, exited with $( $LASTEXITCODE ) " - Write-Error "Retrieved cacerts:" - Get-Content $env:RANCHER_CERT - exit 1 - } - else { - Write-LogInfo "Value from $( $env:CATTLE_SERVER )/$( $caCertsPath ) is an x509 certificate" - } - $env:CATTLE_SERVER_CHECKSUM = (Get-FileHash -Path $env:RANCHER_CERT -Algorithm SHA256).Hash.ToLower() - if ($env:CATTLE_SERVER_CHECKSUM -ne $env:CATTLE_CA_CHECKSUM) { - Remove-Item -Path $env:RANCHER_CERT -Force - Write-LogError "Configured cacerts checksum $( $env:CATTLE_SERVER_CHECKSUM ) does not match given -CaCheckSum $( $env:CATTLE_CA_CHECKSUM ) " - Write-LogError "Please check if the correct certificate is configured at $( $env:CATTLE_SERVER )/$( $caCertsPath ) ." - exit 1 - } - Import-Certificate -FilePath $env:RANCHER_CERT -CertStoreLocation Cert:\LocalMachine\Root | Out-Null - } - - function Test-RancherConnection { - $env:RANCHER_SUCCESS = $false - if ($env:CATTLE_SERVER -and ($env:CATTLE_REMOTE_ENABLED -eq "true")) { - $retries = 0 - while ($retries -lt 6) { - $responseCode = $(curl.exe --connect-timeout 60 --max-time 60 --write-out "%{http_code}\n" $env:CURL_CAFLAG -sfL "$env:CATTLE_SERVER/healthz") - switch ( $responseCode ) { - { $_ -in "ok200", 200 } { - Write-LogInfo "Successfully tested Rancher connection." - $env:RANCHER_SUCCESS = $true - $retries = 99 - break - } - default { - Write-LogError "$responseCode received while testing Rancher connection. Sleeping for 5 seconds and trying again." - Start-Sleep -Seconds 5 - $retries++ - continue - } - } - } - if (!$env:RANCHER_SUCCESS) { - Write-LogFatal "Error connecting to Rancher. Perhaps -CaCheckSum needs to be set?" - } - } - } - - function Test-CaRequired { - $env:CA_REQUIRED = $false - if ($env:CATTLE_SERVER -and ($env:CATTLE_REMOTE_ENABLED -eq "true")) { - $retries = 0 - while ($retries -lt 6) { - curl.exe --connect-timeout 60 --max-time 60 -sfL "$env:CATTLE_SERVER/healthz" - switch ($LASTEXITCODE) { - 0 { - Write-LogInfo "Determined CA is not necessary to connect to Rancher." - $env:CATTLE_CA_CHECKSUM = "" - $retries = 99 - break - } - { $_ -in 60, 77 } { - Write-LogInfo "Determined CA is necessary to connect to Rancher." - $env:CA_REQUIRED = $true - $retries = 99 - break - } - default { - Write-LogError "Error while connecting to Rancher to verify CA necessity. Sleeping for 5 seconds and trying again." - Start-Sleep -Seconds 5 - $retries++ - continue - } - } - } - } - } - - function Get-RancherConnectionInfo() { - if ($env:CATTLE_REMOTE_ENABLED -eq "true") { - $retries = 0 - while ($retries -lt 6) { - $responseCode = $(curl.exe --connect-timeout 60 --max-time 60 --write-out "%{http_code}\n" $env:CURL_CAFLAG -sfL "$env:CATTLE_SERVER/v3/connect/agent" -o $env:CATTLE_AGENT_VAR_DIR/rancher2_connection_info.json -H "Authorization: Bearer $($env:CATTLE_TOKEN)" -H "X-Cattle-Id: $($env:CATTLE_ID)" -H "X-Cattle-Role-Worker: $($env:CATTLE_ROLE_WORKER)" -H "X-Cattle-Labels: $($env:CATTLE_LABELS)" -H "X-Cattle-Taints: $($env:CATTLE_TAINTS)" -H "X-Cattle-Address: $($env:CATTLE_ADDRESS)" -H "X-Cattle-Internal-Address: $($env:CATTLE_INTERNAL_ADDRESS)" -H "Content-Type: application/json") - switch ( $responseCode ) { - { $_ -in "ok200", 200 } { - Write-LogInfo "Successfully downloaded Rancher connection information." - $retries = 99 - break - } - default { - Write-LogError "$responseCode received while downloading Rancher connection information. Sleeping for 5 seconds and trying again." - Start-Sleep -Seconds 5 - $retries++ - continue - } - } - } - } - } - - function Set-WinsConfig() { - $winsConfig = - @" -white_list: - processPaths: - - $($env:CATTLE_AGENT_CONFIG_DIR)/powershell.exe - - $($env:CATTLE_AGENT_CONFIG_DIR)/wins-upgrade.exe - - C:/etc/wmi-exporter/wmi-exporter.exe - - C:/etc/windows-exporter/windows-exporter.exe - proxyPorts: - - 9796 -"@ - Add-Content -Path $env:CATTLE_AGENT_CONFIG_DIR/config -Value $winsConfig - - $agentConfig = - @" -systemagent: - workDirectory: $($env:CATTLE_AGENT_VAR_DIR)/work - appliedPlanDirectory: $($env:CATTLE_AGENT_VAR_DIR)/applied - remoteEnabled: $($env:CATTLE_REMOTE_ENABLED) - preserveWorkDirectory: $($env:CATTLE_PRESERVE_WORKDIR) -"@ - Add-Content -Path $env:CATTLE_AGENT_CONFIG_DIR/config -Value $agentConfig - if ($env:CATTLE_REMOTE_ENABLED -eq "true") { - Add-Content -Path $env:CATTLE_AGENT_CONFIG_DIR/config -Value " connectionInfoFile: $env:CATTLE_AGENT_VAR_DIR/rancher2_connection_info.json" - } - if ((Test-Path -Path $env:RANCHER_CERT) -and ($env:CA_REQUIRED -eq "true")) { - $tlsConfig = - @" - tls-config: - certFilePath: $($($env:RANCHER_CERT).Replace("\\","/")) -"@ - Add-Content -Path $env:CATTLE_AGENT_CONFIG_DIR/config -Value $tlsConfig - } - } - - function Set-CsiProxyConfig() { - $proxyConfig = - @" -csi-proxy: - url: $($env:CSI_PROXY_URL) - version: $($env:CSI_PROXY_VERSION) - kubeletPath: $($env:CSI_PROXY_KUBELET_PATH) -"@ - Add-Content -Path $env:CATTLE_AGENT_CONFIG_DIR/config -Value $proxyConfig - } - - function Stop-Agent() { - [CmdletBinding()] - param ( - [Parameter()] - [string] - $ServiceName - ) - Write-LogInfo "Checking if $ServiceName service exists" - if ((Get-Service -Name $ServiceName -ErrorAction SilentlyContinue)) { - Write-LogInfo "$ServiceName service found, stopping now" - Stop-Service -Name $ServiceName - while ((Get-Service -Name $ServiceName).Status -ne 'Stopped') { - Write-LogInfo "Waiting for $ServiceName service to stop" - Start-Sleep -s 5 - } - } - else { - Write-LogInfo "$ServiceName isn't installed, continuing" - } - } - - function New-CattleId() { - if (-Not $env:CATTLE_ID) { - Write-LogInfo "Generating Cattle ID" - - if (Test-Path -Path "$($env:CATTLE_AGENT_CONFIG_DIR)/cattle-id") { - $env:CATTLE_ID = Get-Content -Path "$($env:CATTLE_AGENT_CONFIG_DIR)/cattle-id" - Write-LogInfo "Cattle ID was already detected as $($env:CATTLE_ID). Not generating a new one." - return - } - $stream = [IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes($env:COMPUTERNAME)) - $env:CATTLE_ID = (Get-FileHash -InputStream $stream -Algorithm SHA256).Hash.ToLower().Substring(0, 62) - Set-Content -Path "$($env:CATTLE_AGENT_CONFIG_DIR)/cattle-id" -Value $env:CATTLE_ID - return - } - Write-LogInfo "Not generating Cattle ID" - } - - function Get-Address() { - [CmdletBinding()] - param ( - [Parameter()] - [String] - $Value - ) - if (!$Value) { - # If nothing is given, return empty (it will be automatically determined later if empty) - return "" - } - # If given address is a network interface on the system, retrieve configured IP on that interface (only the first configured IP is taken) - elseif (Get-NetAdapter -Name $Value -ErrorAction SilentlyContinue) { - return $(Get-NetIpConfiguration | Where-Object { $null -ne $_.IPv4DefaultGateway -and $_.NetAdapter.Status -ne "Disconnected" }).IPv4Address.IPAddress - } - # Loop through cloud provider options to get IP from metadata, if not found return given value - else { - switch ($Value) { - awslocal { return curl.exe --connect-timeout 60 --max-time 60 -s http://169.254.169.254/latest/meta-data/local-ipv4 } - awspublic { return curl.exe --connect-timeout 60 --max-time 60 -s http://169.254.169.254/latest/meta-data/public-ipv4 } - doprivate { return curl.exe --connect-timeout 60 --max-time 60 -s http://169.254.169.254/metadata/v1/interfaces/private/0/ipv4/address } - dopublic { return curl.exe --connect-timeout 60 --max-time 60 -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address } - azprivate { return curl.exe --connect-timeout 60 --max-time 60 -s -H Metadata:true "http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/privateIpAddress?api-version=2017-08-01&format=text" } - azpublic { return curl.exe --connect-timeout 60 --max-time 60 -s -H Metadata:true "http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-08-01&format=text" } - gceinternal { return curl.exe --connect-timeout 60 --max-time 60 -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/ip } - gceexternal { return curl.exe --connect-timeout 60 --max-time 60 -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip } - packetlocal { return curl.exe --connect-timeout 60 --max-time 60 -s https://metadata.packet.net/2009-04-04/meta-data/local-ipv4 } - packetpublic { return curl.exe --connect-timeout 60 --max-time 60 -s https://metadata.packet.net/2009-04-04/meta-data/public-ipv4 } - ipify { return curl.exe --connect-timeout 60 --max-time 60 -s https://api.ipify.org } - default { - return $Value - } - } - } - } - - function Copy-WinsForCharts() { - $winsForChartsPath = "c:/windows" - if (-Not (Test-Path $winsForChartsPath)) { - New-Item $winsForChartsPath -ItemType Directory - } - Copy-Item -Path "$env:CATTLE_AGENT_BIN_PREFIX/bin/wins.exe" -Destination "$winsForChartsPath/wins.exe" -Force - } - - function Confirm-WindowsFeatures { - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [String[]] - $RequiredFeatures - ) - foreach ($feature in $RequiredFeatures) { - $f = Get-WindowsFeature -Name $feature - if (-not $f.Installed) { - Write-LogFatal "Windows feature: '$feature' is not installed. Please run: Install-WindowsFeature -Name $feature" - } - else { - Write-LogInfo "Windows feature: '$feature' is installed. Installation will proceed." - } - } - } - - function Invoke-WinsAgentInstall() { - $serviceName = "rancher-wins" - Get-Args - Set-Environment - Set-Path - Test-CaCheckSum - - if ($env:CATTLE_CA_CHECKSUM) { - Test-CaRequired - } - - Test-RancherConnection - Stop-Agent -ServiceName $serviceName - Invoke-WinsAgentDownload - Copy-WinsForCharts - Set-WinsConfig - - if($env:CSI_PROXY_URL -and $env:CSI_PROXY_VERSION -and $env:CSI_PROXY_KUBELET_PATH) { - Set-CsiProxyConfig - } - - if ($env:CATTLE_TOKEN) { - New-CattleId - Get-RancherConnectionInfo - } - - $newEnv = @() - $PROXY_ENV_INFO = Get-ChildItem env: | Where-Object { $_.Name -Match "^(NO|HTTP|HTTPS)_PROXY" } | ForEach-Object { "$($_.Name)=$($_.Value)" } - if ($PROXY_ENV_INFO) { - netsh winhttp set proxy $env:HTTPS_PROXY - Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" ProxyEnable -value 1 - Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" ProxyServer -value "https=$env:HTTPS_PROXY;http=$env:HTTP_PROXY" - Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" ProxyOverride -value $env:NO_PROXY.Replace(',',';') - - $newEnv += $PROXY_ENV_INFO - if(Test-Path -Path HKLM:SYSTEM\CurrentControlSet\Services\$serviceName) { - Set-ItemProperty HKLM:SYSTEM\CurrentControlSet\Services\$serviceName -Name Environment -Value $([string]$newEnv) - } - else { - New-Item HKLM:SYSTEM\CurrentControlSet\Services\$serviceName - New-ItemProperty HKLM:SYSTEM\CurrentControlSet\Services\$serviceName -Name Environment -PropertyType MultiString -Value $([string]$newEnv) - } - } - - try { - Write-LogInfo "Checking if $serviceName service exists." - Get-Service -Name $serviceName - } - catch { - Write-LogInfo "$serviceName service not found, enabling agent service." - Push-Location c:\usr\local\bin - wins.exe srv app run --register - Pop-Location - Start-Sleep -s 5 - } - - Write-LogInfo "Starting $serviceName service." - Start-Service -Name $serviceName - while ((Get-Service $serviceName).Status -ne 'Running') { - Write-LogInfo "Waiting for $serviceName service to start." - Start-Sleep -s 5 - } - } - - Confirm-WindowsFeatures -RequiredFeatures @("Containers") - Invoke-WinsAgentInstall -} diff --git a/package/windows/run.ps1 b/package/windows/run.ps1 deleted file mode 100644 index b1735f5a..00000000 --- a/package/windows/run.ps1 +++ /dev/null @@ -1,136 +0,0 @@ -<# -.SYNOPSIS - Upgrades Rancher Wins. -.DESCRIPTION - Run the script to upgrade all Rancher Wins related needs. -.NOTES - -.EXAMPLE - -#> -param ( - [Parameter()] - [Switch] - $HostProcess -) - -$ErrorActionPreference = 'Stop' - -function New-Directory { - param ( - [parameter(Mandatory = $false, ValueFromPipeline = $true)] [string]$Path - ) - - if (Test-Path -Path $Path) { - if (-not (Test-Path -Path $Path -PathType Container)) { - # clean the same path file - Remove-Item -Recurse -Force -Path $Path -ErrorAction Ignore | Out-Null - } - return - } - - New-Item -Force -ItemType Directory -Path $Path | Out-Null -} - -function Invoke-Cleanup { - param ( - [parameter(Mandatory = $false, ValueFromPipeline = $true)] [string]$Path - ) - - if (Test-Path -Path $Path) { - Remove-Item -Recurse -Force -Path $Path -ErrorAction Ignore | Out-Null - } -} - -function Start-TransferFile { - param ( - [parameter(Mandatory = $true)] [string]$Source, - [parameter(Mandatory = $true)] [string]$Destination - ) - - if (Test-Path -PathType leaf -Path $Destination) { - $destinationHasher = Get-FileHash -Path $Destination - $sourceHasher = Get-FileHash -Path $Source - if ($destinationHasher.Hash -eq $sourceHasher.Hash) { - return - } - } - - Copy-Item -Force -Path $Source -Destination $Destination | Out-Null -} - -function Invoke-WinsHostProcessUpgrade { - $tmpdirbase = "/etc/rancher/agent" - $tmpdir = Join-Path "C:\host\" -ChildPath $tmpdirbase - - New-Directory -Path $tmpdir - - Start-TransferFile -Source "C:\wins.exe" -Destination $tmpdir - Start-TransferFile -Source "C:\install.ps1" -Destination $tmpdir - - if (-Not $env:CATTLE_ROLE_WORKER) { - $env:CATTLE_ROLE_WORKER = "true" - } - - $env:CATTLE_AGENT_BINARY_LOCAL = "true" - $env:CATTLE_AGENT_BINARY_LOCAL_LOCATION = Join-Path -Path $tmpdir -ChildPath "wins.exe" - - Set-Location -Path $tmpdir - - ./install.ps1 - - Pop-Location - - Remove-Item -Path $tmpdir\wins.exe - Remove-Item -Path $tmpdir\install.ps1 - exit 0 -} - -function Invoke-WinsWinsUpgrade { - $tmpdirbase = "/etc/rancher/wins" - $tmpdir = Join-Path "C:\host\" -ChildPath $tmpdirbase - $tmpdirLocal = Join-Path "C:\" -ChildPath $tmpdirbase - $winsUpgradePath = Join-Path -Path $tmpdir -ChildPath "wins-upgrade.exe" - $winsUpgradePathLocal = Join-Path -Path $tmpdirLocal -ChildPath "wins-upgrade.exe" - - New-Directory -Path $tmpdirLocal - Copy-Item -Force -Path "C:\wins.exe" -Destination $winsUpgradePathLocal | Out-Null - - Write-Host "Transferring file to host..." - Start-TransferFile -Source "C:\wins.exe" -Destination $winsUpgradePath - - Write-Host "Checking if $($winsUpgradePath) exists" - if(Test-Path $winsUpgradePath) { - Write-Host "$($winsUpgradePath) exists..." - } - else { - Write-Host "$($winsUpgradePath) was not copied to host..." - exit 1 - } - - $winsOut = wins.exe cli prc run --path=$winsUpgradePathLocal --args="up" - - Remove-Item -Path $winsUpgradePath - - if ($winsOut -match ".* rpc error: code = Unavailable desc = transport is closing") { - Write-Host "Successfully upgraded" - exit 0 - } - elseif ($LastExitCode -ne 0) { - Write-Host "Returned exit $LastExitCode" - Write-Host $winsOut - exit $LastExitCode - } - else { - Write-Host "Returned exit 0, but did not receive expected output from .\wins up" - Write-Host $winsOut - exit 1 - } -} - -if($HostProcess) { - Invoke-WinsHostProcessUpgrade -} -else { - Invoke-WinsWinsUpgrade -} diff --git a/scripts/build.ps1 b/scripts/build.ps1 deleted file mode 100644 index 12fbc504..00000000 --- a/scripts/build.ps1 +++ /dev/null @@ -1,57 +0,0 @@ -#Requires -Version 5.0 - -$ErrorActionPreference = 'Stop' - -Import-Module -WarningAction Ignore -Name "$PSScriptRoot\utils.psm1" - -function Build { - param ( - [parameter(Mandatory = $true)] [string]$Version, - [parameter(Mandatory = $true)] [string]$Commit, - [parameter(Mandatory = $true)] [string]$Output - ) - - $linkFlags = ('-s -w -X github.com/rancher/wins/pkg/defaults.AppVersion={0} -X github.com/rancher/wins/pkg/defaults.AppCommit={1} -extldflags "-static"' -f $Version, $Commit) - go build -ldflags $linkFlags -o $Output cmd/main.go - if (-not $?) { - Log-Fatal "[build] go build failed!" - } -} - -Invoke-Script -File "$PSScriptRoot\version.ps1" - -$SRC_PATH = (Resolve-Path "$PSScriptRoot\..").Path -Push-Location $SRC_PATH - -Remove-Item -Path "$SRC_PATH\bin\*" -Force -ErrorAction Ignore -$null = New-Item -Type Directory -Path bin -ErrorAction Ignore -$env:GOARCH = $env:ARCH -$env:GOOS = 'windows' -$env:CGO_ENABLED = 0 -Write-Host "[build] Building wins version ($env:VERSION) for $env:GOOS/$env:GOARCH" -Build -Version $env:VERSION -Commit $env:COMMIT -Output "$SRC_PATH\bin\wins.exe" -Write-Host "[build] successfully built wins version $env:VERSION for $env:GOOS/$env:GOARCH" - -$PACKAGE_DIR = "C:\package" -$ASSETS = @("install.ps1", "bin\wins.exe", "suc\run.ps1") -Write-Host -ForegroundColor Yellow "[build] now staging build artifacts [$ASSETS] from $SRC_PATH" -$null = New-Item -Type Directory -Path C:\package -ErrorAction Ignore -foreach ($item in $ASSETS) { - if ("$SRC_PATH\$item") { - if ($item.Contains('\')) { - $i = $item -replace "^.*?\\" - Copy-Item -Force -Path $SRC_PATH\$item -Destination "$PACKAGE_DIR\$i" - Write-Host ('[build] new artifact ({0}\{1})' -f $PACKAGE_DIR, $i) - } else { - Copy-Item -Force -Path $SRC_PATH\$item -Destination "$PACKAGE_DIR\$item" - Write-Host ('[build] new artifact ({0}\{1})' -f $PACKAGE_DIR, $item) - } - } else { - Log-Fatal "[build] build artifact $SRC_PATH\$item is missing" - } -} -Write-Host -ForegroundColor Green "[build] all required build artifacts have been staged" -Write-Host -ForegroundColor Blue ('[build] Artifacts List in ({0}): {1}' -f $PACKAGE_DIR, (Get-ChildItem $PACKAGE_DIR)) -Write-Host -ForegroundColor Green "build.ps1 has completed successfully" -Write-Host "[build] invoking package.ps1 to validate build artifacts" -Invoke-Script -File "$PSScriptRoot\package.ps1" diff --git a/scripts/ci.ps1 b/scripts/ci.ps1 deleted file mode 100644 index 037f5e02..00000000 --- a/scripts/ci.ps1 +++ /dev/null @@ -1,61 +0,0 @@ -#Requires -Version 5.0 - -$ErrorActionPreference = 'Stop' - -Import-Module -WarningAction Ignore -Name "$PSScriptRoot\utils.psm1" - -try { - - if (($args[0] -eq "all") -or ($args[0] -eq "ci") -or ($args[0] -eq "")) { - Write-Host "Invoking validate.ps1" - Invoke-Script -File "$PSScriptRoot\validate.ps1" - - Write-Host "Invoking test.ps1" - Invoke-Script -File "$PSScriptRoot\test.ps1" - - Write-Host "Invoking build.ps1" - Invoke-Script -File "$PSScriptRoot\build.ps1" - - Write-Host "Invoking integration.ps1" - Invoke-Script -File "$PSScriptRoot\integration.ps1" - - Write-Host "Invoking package.ps1 to validate build artifacts" - Invoke-Script -File "$PSScriptRoot\package.ps1" - } - - if ($args[0] -eq "package") { - Write-Host "Invoking build.ps1" - Invoke-Script -File "$PSScriptRoot\build.ps1" - Write-Host "Invoking package.ps1" - Invoke-Script -File "$PSScriptRoot\package.ps1" - } - - if ($args[0] -eq "integration") { - Write-Host "Invoking build.ps1" - Invoke-Script -File "$PSScriptRoot\build.ps1" - - Write-Host "Invoking integration.ps1" - Invoke-Script -File "$PSScriptRoot\integration.ps1" - } - - if ($args[0] -eq "validate") { - Write-Host "Invoking validate.ps1" - Invoke-Script -File "$PSScriptRoot\validate.ps1" - } - - if ($args[0] -eq "test") { - Write-Host "Invoking test.ps1" - Invoke-Script -File "$PSScriptRoot\test.ps1" - } - - if ($args[0] -eq "build") { - Write-Host "Invoking build.ps1" - Invoke-Script -File "$PSScriptRoot\build.ps1" - } - - -} catch { - Write-Host -NoNewline -ForegroundColor Red "[ERROR]: " - Write-Host -ForegroundColor Red "Failed running $_" - exit 1 -} diff --git a/scripts/package.ps1 b/scripts/package.ps1 deleted file mode 100644 index 0c1ce38e..00000000 --- a/scripts/package.ps1 +++ /dev/null @@ -1,18 +0,0 @@ -#Requires -Version 5.0 -$ErrorActionPreference = "Stop" - -Invoke-Expression -Command "$PSScriptRoot\version.ps1" - -$DIR_PATH = Split-Path -Parent $MyInvocation.MyCommand.Definition -$SRC_PATH = (Resolve-Path "$DIR_PATH\..").Path -$PACKAGE_DIR = "C:\package" - -$ASSETS = @("install.ps1", "wins.exe", "run.ps1") -Write-Host -ForegroundColor Yellow "[package] verifying build artifacts [$ASSETS] are present in ($PACKAGE_DIR)" -foreach ($item in $ASSETS) { - if (-not("$PACKAGE_DIR\$item")) { - Log-Fatal "[package] required build artifact $PACKAGE_DIR\$item is missing, exiting now" - } -} -Write-Host -ForegroundColor Green "[package] all required build artifacts are present" -Write-Host -ForegroundColor Green "package.ps1 has completed successfully" diff --git a/scripts/release.ps1 b/scripts/release.ps1 deleted file mode 100644 index e69de29b..00000000 diff --git a/scripts/test.ps1 b/scripts/test.ps1 deleted file mode 100644 index c867f0e1..00000000 --- a/scripts/test.ps1 +++ /dev/null @@ -1,22 +0,0 @@ -#Requires -Version 5.0 - -$ErrorActionPreference = 'Stop' - -Import-Module -WarningAction Ignore -Name "$PSScriptRoot\utils.psm1" - -Invoke-Script -File "$PSScriptRoot\version.ps1" - -$SRC_PATH = (Resolve-Path "$PSScriptRoot\..").Path -Push-Location $SRC_PATH - -$env:GOARCH = $env:ARCH -$env:GOOS = 'windows' -$env:CGO_ENABLED = 0 -$LINKFLAGS = ('-X github.com/rancher/wins/pkg/defaults.AppVersion={0} -X github.com/rancher/wins/pkg/defaults.AppCommit={1}' -f $env:VERSION, $env:COMMIT) -go test --ldflags $LINKFLAGS -v -cover ./... -if (-not $?) -{ - Log-Fatal "validation test failed" -} - -Pop-Location diff --git a/scripts/utils.psm1 b/scripts/utils.psm1 deleted file mode 100644 index c404f979..00000000 --- a/scripts/utils.psm1 +++ /dev/null @@ -1,52 +0,0 @@ -#Requires -Version 5.0 - -$ErrorActionPreference = 'Stop' -$WarningPreference = 'SilentlyContinue' -$VerbosePreference = 'SilentlyContinue' -$DebugPreference = 'SilentlyContinue' -$InformationPreference = 'SilentlyContinue' - -function Log-Info { - Write-Host -NoNewline -ForegroundColor Blue "INFO: " - Write-Host -ForegroundColor Gray ("{0,-44}" -f ($Args -join " ")) -} - -function Log-Warn { - Write-Host -NoNewline -ForegroundColor DarkYellow "WARN: " - Write-Host -ForegroundColor Gray ("{0,-44}" -f ($args -join " ")) -} - -function Log-Error { - Write-Host -NoNewline -ForegroundColor DarkRed "ERRO " - Write-Host -ForegroundColor Gray ("{0,-44}" -f ($args -join " ")) -} - - -function Log-Fatal { - Write-Host -NoNewline -ForegroundColor DarkRed "FATA: " - Write-Host -ForegroundColor Gray ("{0,-44}" -f ($args -join " ")) - - exit 255 -} - -function Invoke-Script { - param ( - [parameter(Mandatory = $true)] [string]$File - ) - - try { - Invoke-Expression -Command $File - if (-not $?) { - Log-Fatal "Failed to invoke $File" - } - } - catch { - Log-Fatal "Could not invoke $File, $($_.Exception.Message)" - } -} - -Export-ModuleMember -Function Log-Info -Export-ModuleMember -Function Log-Warn -Export-ModuleMember -Function Log-Error -Export-ModuleMember -Function Log-Fatal -Export-ModuleMember -Function Invoke-Script diff --git a/scripts/validate.ps1 b/scripts/validate.ps1 deleted file mode 100644 index f7625374..00000000 --- a/scripts/validate.ps1 +++ /dev/null @@ -1,22 +0,0 @@ -#Requires -Version 5.0 - -$ErrorActionPreference = 'Stop' -Import-Module -WarningAction Ignore -Name "$PSScriptRoot\utils.psm1" - -$SRC_PATH = (Resolve-Path "$PSScriptRoot\..").Path -Push-Location $SRC_PATH - -Log-Info "Running validation" -Get-Command -ErrorAction Ignore -Name @("golangci-lint.exe") | Out-Null -if (-not $?) { - Log-Info "Skipping validation: no golangci-lint available" - exit 1 -} - -Log-Info "Running: golangci-lint" -golangci-lint run - -Log-Info "Running: go fmt" -go fmt ./... - -Write-Host -ForegroundColor Green "validate.ps1 has completed successfully." diff --git a/scripts/version.ps1 b/scripts/version.ps1 deleted file mode 100644 index 5bc5d40d..00000000 --- a/scripts/version.ps1 +++ /dev/null @@ -1,54 +0,0 @@ -#Requires -Version 5.0 -$ErrorActionPreference = 'Stop' - -Import-Module -WarningAction Ignore -Name "$PSScriptRoot\utils.psm1" - -$DIRTY = "" -if ("$(git status --porcelain --untracked-files=no)") { - $DIRTY = "-dirty" -} - -$COMMIT = $(git rev-parse --short HEAD) -$GIT_TAG = $env:DRONE_TAG -if (-not $GIT_TAG) { - $GIT_TAG = $(git tag -l --contains HEAD | Select-Object -First 1) -} -$env:COMMIT = $COMMIT - -$VERSION = "${env:COMMIT}${DIRTY}" -if ((-not $DIRTY) -and ($GIT_TAG)) { - $VERSION = "${GIT_TAG}" -} -$env:VERSION = $VERSION - -$TAG = ('{0}{1}' -f $env:VERSION, $env:SUFFIX) -if ($TAG | Select-String -Pattern 'dirty') { - $TAG = "dev" -} - -if (-not $env:REPO) { - $env:REPO = "rancher" -} - -if (($env:DRONE_TAG) -and (-Not ($TAG).Contains("dev") -or -Not ($TAG).Contains("dirty"))){ - $TAG = $env:DRONE_TAG - $env:TAG = $TAG -} else { - $env:TAG = $TAG -} - -if (-not $env:ARCH) { - $env:ARCH = "amd64" -} - -$buildTags = @{ "17763" = "1809"; "20348" = "ltsc2022";} -$buildNumber = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\' -ErrorAction Ignore).CurrentBuildNumber -$env:SERVERCORE_VERSION = $buildTags[$buildNumber] -if (-not $env:SERVERCORE_VERSION) { - $env:SERVERCORE_VERSION = "1809" -} - -Write-Host "ARCH: $env:ARCH" -Write-Host "VERSION: $env:VERSION" -Write-Host "TAG: $env:TAG" -Write-Host "SERVERCORE_VERSION: $env:SERVERCORE_VERSION"