Skip to content

Commit

Permalink
Merge pull request #1 from stuartleeks/sl/go
Browse files Browse the repository at this point in the history
Convert to Go implementation,  with the following advantages:

* The application runs as a windowless app so there is no longer the flash of a powershell window when the task runs
* The logic has been updated to test for a running WSL v2 distro before checking whether to reset the clock (rather than _any_ running distro). This removes the potential for spinning up a WSL 2 distro when there wasn't one running (i.e. when there was no need to reset the clock)
* The logic now uses an existing running distro for executing the time checks and reset steps, rather than the default distro. This avoids situations where an extra distro may have been started, as well as avoiding issues when the default distro was configured as WSL v1
  • Loading branch information
stuartleeks authored Aug 13, 2020
2 parents 38c40e6 + beebf3a commit f63a714
Show file tree
Hide file tree
Showing 19 changed files with 707 additions and 57 deletions.
57 changes: 57 additions & 0 deletions .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#-------------------------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
#-------------------------------------------------------------------------------------------------------------

FROM golang:1.14-stretch

# Avoid warnings by switching to noninteractive
ENV DEBIAN_FRONTEND=noninteractive

# Configure apt, install packages and tools
RUN apt-get update \
&& apt-get -y install --no-install-recommends apt-utils dialog nano \
#
# Verify git, process tools, lsb-release (common in install instructions for CLIs) installed
&& apt-get -y install git iproute2 procps lsb-release \
# Install Release Tools
#
# --> RPM used by goreleaser
&& apt install -y rpm \
# Clean up
&& apt-get autoremove -y \
&& apt-get clean -y \
&& rm -rf /var/lib/apt/lists/*

# This Dockerfile adds a non-root user with sudo access. Use the "remoteUser"
# property in devcontainer.json to use it. On Linux, the container user's GID/UIDs
# will be updated to match your local UID/GID (when using the dockerFile property).
# See https://aka.ms/vscode-remote/containers/non-root-user for details.
ARG USERNAME=vscode
ARG USER_UID=1000
ARG USER_GID=$USER_UID

# Set env for tracking that we're running in a devcontainer
ENV DEVCONTAINER=true

# Enable go modules
ENV GO111MODULE=on

# Install Go tools
RUN \
# --> Delve for debugging
go get github.com/go-delve/delve/cmd/[email protected] \
# --> Go language server
&& go get golang.org/x/tools/[email protected] \
# --> Go symbols and outline for go to symbol support and test support
&& go get github.com/acroca/[email protected] && go get github.com/ramya-rao-a/go-outline@7182a932836a71948db4a81991a494751eccfe77 \
# --> GolangCI-lint
&& curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sed 's/tar -/tar --no-same-owner -/g' | sh -s -- -b $(go env GOPATH)/bin \
# --> Go releaser
&& curl -sfL https://install.goreleaser.com/github.com/goreleaser/goreleaser.sh | sh -s -- "v0.132.1"\
# --> Install junit converter
&& go get github.com/jstemmer/[email protected] \
&& rm -rf /go/src/ && rm -rf /go/pkg

# Switch back to dialog for any ad-hoc use of apt-get
ENV DEBIAN_FRONTEND=dialog
62 changes: 62 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// For format details, see https://aka.ms/vscode-remote/devcontainer.json or this file's README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.117.1/containers/go
{
"name": "wsl-clock",
"dockerFile": "Dockerfile",
"runArgs": [
// Uncomment the next line to use a non-root user. On Linux, this will prevent
// new files getting created as root, but you may need to update the USER_UID
// and USER_GID in .devcontainer/Dockerfile to match your user if not 1000.
// "-u", "vscode",
"--cap-add=SYS_PTRACE",
"--security-opt",
"seccomp=unconfined",

// Mount go mod cache
"-v", "wsl-clock-gomodcache:/go/pkg",
// Keep command history
"-v", "wsl-clock-bashhistory:/root/commandhistory",
// Mount docker socket for docker builds
"-v", "/var/run/docker.sock:/var/run/docker.sock",
// Use host network
"--network=host",
// Mount azure, git and docker config
"-v", "${env:HOME}${env:USERPROFILE}/.azure:/root/.azure"
],

// Set *default* container specific settings.json values on container create.
"settings": {
"terminal.integrated.shell.linux": "/bin/bash",
"go.gopath": "/go",
"go.useLanguageServer": true,
"[go]": {
"editor.snippetSuggestions": "none",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true,
}
},
"gopls": {
"usePlaceholders": true, // add parameter placeholders when completing a function
// Experimental settings
"completeUnimported": true, // autocomplete unimported packages
"watchFileChanges": true, // watch file changes outside of the editor
"deepCompletion": true, // enable deep completion
},
"files.eol": "\n", // formatting only supports LF line endings
},

// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"golang.go"
]

// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],

// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "go version",

// Uncomment to connect as a non-root user. See https://aka.ms/vscode-remote/containers/non-root.
// "remoteUser": "vscode"
}
29 changes: 29 additions & 0 deletions .github/workflows/build-and-release.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: build-and-release

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
build:
runs-on: ubuntu-18.04

steps:
- uses: actions/checkout@v2

- name: CI Tooling
run: sudo apt update && sudo apt install build-essential -y

- name: Build devcontainer for tooling
run: sudo -E make devcontainer

- name: Run the release
run: sudo -E make devcontainer-release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BUILD_NUMBER: ${{ github.run_id }}
IS_CI: 1
IS_PR: ${{ github.head_ref }}
BRANCH: ${{ github.ref }}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/wsl-clock
/wsl-clock.exe
/dist
31 changes: 31 additions & 0 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
builds:
- env:
- CGO_ENABLED=0
binary: wsl-clock
goos:
- windows
goarch:
- 386
- amd64
main: .
ldflags:
- -s -w -X main.version={{.Version}} -X main.commit={{.ShortCommit}} -X main.date={{.Date}} -X "main.goversion={{.Env.GOVERSION}}" -H windowsgui

archives:
- id: zip
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
format_overrides:
- goos: windows
format: zip
files:
- README.md
- LICENSE.md
- add-wslclocktask.ps1
- remove-wslclocktask.ps1

changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
35 changes: 35 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${fileDirname}",
"env": {},
"args": []
},
{
"name": "Launch a test",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${file}",
// "args": [
// "-test.v",
// "-test.run",
// "^${selectedText}$"
// ],
"env": {
"GOOS": "windows",
},
"buildFlags": "-v -tags=all",
"showLog": true,
"envFile": "${workspaceFolder}/.env"
}
]
}
27 changes: 27 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
build:
GOOS=windows go build .

lint: build
GOOS=windows golangci-lint run

devcontainer:
docker build -f ./.devcontainer/Dockerfile ./.devcontainer -t wsl-clock

devcontainer-release:
ifdef DEVCONTAINER
$(error This target can only be run outside of the devcontainer as it mounts files and this fails within a devcontainer. Don't worry all it needs is docker)
endif
@docker run -v ${PWD}:${PWD} \
-e BUILD_NUMBER="${BUILD_NUMBER}" \
-e IS_CI="${IS_CI}" \
-e IS_PR="${IS_PR}" \
-e BRANCH="${BRANCH}" \
-e GITHUB_TOKEN="${GITHUB_TOKEN}" \
--entrypoint /bin/bash \
--workdir "${PWD}" \
wsl-clock \
-c "${PWD}/scripts/ci_release.sh"


test:
GOOS=windows go test -v ./...
29 changes: 7 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@

**IMPORTANT: This is not an official solution and whilst it worked on my machine this is an unsupported workaround :-)**

There is an issue with WSL where the clock in WSl isn't updated when the host resumes from sleep/hibernate. E.g. [this issue](https://github.com/microsoft/WSL/issues/4245)
There is an issue with WSL where the clock in WSL isn't updated when the host resumes from sleep/hibernate. E.g. [this issue](https://github.com/microsoft/WSL/issues/4245)

This repo has a workaround that creates a scheduled task that is triggered by Windows Events for resuming from sleep/hibernation. When the scheduled task executes it resets the clock in the WSL VM.

For the background to this repo, see [this blog post](https://stuartleeks.com/posts/fixing-clock-skew-with-wsl-2/)
For the background to this repo, see [this blog post](https://stuartleeks.com/posts/fixing-clock-skew-with-wsl-2/). The implementation discussed in that blog post is based on PowerShell and that implementation is still available [here](https://github.com/stuartleeks/wsl-clock/tree/powershell). The implementation has now been replaced with a program written in Go, with the following advantages:

* The appliation runs as a windowless app so there is no longer the flash of a powershell window when the task runs
* The logic has been updated to test for a running WSL v2 distro before checking whether to reset the clock (rather than _any_ running distro). This removes the potential for spinning up a WSL 2 distro when there wasn't one running (i.e. when there was no need to reset the clock)
* The logic now uses an existing running distro for executing the time checks and reset steps, rather than the default distro. This avoids situations where an extra distro may have been started, as well as avoiding issues when the default distro was configured as WSL v1

## Setup

Expand All @@ -18,23 +22,4 @@ To remove the scheduled task, run `remove-wslclocktask.ps1`

## Logs/Troubleshooting

The script invoked by the scheduled task logs output to `~/.wsl-clock.log`

## Known issues

### Fails if default distribution is configured for WSL 1

The `update-clock.ps1` script executes the `hwclock` against the default distro. If that distro is configured to run under WSL 1 then it will result in the following error as `hwclock` isn't supported on WSL 1 (and WSL 1 isn't executing in the lightweight VM for WSL 2 so this wouldn't have any effect anyway)

```log
hwclock: Cannot access the Hardware Clock via any known method.
hwclock: Use the --debug option to see the details of our search for an access method.
```

See <https://github.com/microsoft/wsl/issues/193>.

Possible workarounds:

* change your default distro to a distro that is configured for WSL 2
* change your default distro to run on WSL 2
* modify your copy of the script to specify a distro via `-d` parameter for `wsl` when it runs `hwclock`
The program invoked by the scheduled task logs output to `~/.wsl-clock.log`
2 changes: 1 addition & 1 deletion add-wslclocktask.ps1
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
$taskCommand = "powershell.exe -noprofile -windowstyle Hidden -Command '" + $PSScriptRoot + "\update-clock.ps1'"
$taskCommand = $PSScriptRoot + "\wsl-clock.exe"

schtasks /Create /TN wsl-clock /TR $taskCommand /SC ONEVENT /EC System /MO "*[System[Provider[@Name='Microsoft-Windows-Kernel-Power'] and (EventID=107 or EventID=507)]]" /F
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/stuartleeks/wsl-clock

go 1.14

require github.com/stretchr/testify v1.6.1
11 changes: 11 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
75 changes: 75 additions & 0 deletions internal/pkg/logging/logging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package logging

import (
"fmt"
"os"
"path/filepath"
"time"
)

var message string

const maxLogFileSize int64 = 5 * 1024 * 1024

func AddMessage(newMessage string, a ...interface{}) {
if message != "" {
message += "\n"
}
timestamp := time.Now().UTC().Format("2006-01-02 15:04:05 ")
message += timestamp + fmt.Sprintf(newMessage, a...)
}
func WriteLog() {
userProfile := os.Getenv("USERPROFILE")
logPath := filepath.Join(userProfile, ".wsl-clock.log")
backupLogPath := filepath.Join(userProfile, ".wsl-clock.old.log")

handleLogFileRotation(logPath, backupLogPath)

file, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("Error opening log file %q: %s", logPath, err)
panic(err)
}
defer file.Close()

_, err = file.WriteString(message + "\n")
if err != nil {
fmt.Printf("Error writing to log file %q: %s", logPath, err)
panic(err)
}
}

func handleLogFileRotation(logPath string, backupLogPath string) {
size, err := getFileSize(logPath)
if err != nil {
if err != nil {
fmt.Printf("Error getting log file size %q: %s", logPath, err)
panic(err)
}
}
if size > maxLogFileSize {
if _, err = os.Stat(backupLogPath); err != nil {
if !os.IsNotExist(err) {
fmt.Printf("Error checking backup log path %q: %s", backupLogPath, err)
panic(err)
}
} else {
os.Remove(backupLogPath)
}
if err = os.Rename(logPath, backupLogPath); err != nil {
fmt.Printf("Error renaming log to backup %q: %s", backupLogPath, err)
panic(err)
}
}
}

func getFileSize(path string) (int64, error) {
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return 0, nil // treat not found as empty for this use-case
}
return 0, err
}
return info.Size(), nil
}
Loading

0 comments on commit f63a714

Please sign in to comment.