diff --git a/.dockerignore b/.dockerignore index 7a530350..53399a8d 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,2 +1,3 @@ build +gocache Dockerfile diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..8ce1b21c --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,27 @@ +name: Build + +on: + push: + branches: [$default-branch] + pull_request: + branches: [$default-branch] + +jobs: + build: + runs-on: ubuntu-latest + + strategy: + matrix: + debian_packages: [BULLSEYE, BUSTER] + arch: [armhf, amd64] + + steps: + - uses: actions/checkout@v3 + + - name: Build + run: make build DEBIAN_PACKAGES=${{ matrix.debian_packages }} ARCH=${{ matrix.arch }} + + - uses: actions/upload-artifact@v3 + with: + name: deb-${{ matrix.debian_packages }}-${{ matrix.arch }} + path: build/**/*.deb diff --git a/.gitignore b/.gitignore index 988ba6ed..c07b4fd0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ build +gocache/ debian/changelog pkg/ .vscode/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 4faf72ce..d2c99f9c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,19 +1,35 @@ ARG IMAGE FROM ${IMAGE} +SHELL ["/bin/bash", "-c"] + +ARG TARGET_ARCH + +# Note: dh-systemd doesn't exist on bullseye anymore (it's been merged with debhelper) +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + git build-essential \ + debhelper devscripts fakeroot git-buildpackage dh-make dh-golang \ + && \ + (apt-get install -y --no-install-recommends dh-systemd || true) \ + && \ + if [[ `dpkg-architecture -q DEB_BUILD_ARCH` != "${TARGET_ARCH}" ]]; then \ + dpkg --add-architecture ${TARGET_ARCH} && \ + apt-get update && \ + apt-get install -y --no-install-recommends \ + crossbuild-essential-${TARGET_ARCH}; \ + fi && \ + apt-get install -y --no-install-recommends \ + libcairo2-dev:${TARGET_ARCH} \ + libgtk-3-dev:${TARGET_ARCH} + ARG GO_TAGS ENV GO_TAGS=${GO_TAGS} -RUN apt-get update && apt-get install -y --no-install-recommends \ - git build-essential \ - debhelper devscripts fakeroot git-buildpackage dh-make dh-systemd dh-golang \ - libcairo2-dev \ - libgtk-3-dev - # We cache go get gtk, to speed up builds. #RUN go get -tags ${GO_TAGS} -v github.com/gotk3/gotk3/gtk/... -ADD . ${GOPATH}/src/github.com/Z-Bolt/OctoScreen/ +ADD . /OctoScreen/ #RUN go get -tags ${GO_TAGS} -v ./... -WORKDIR ${GOPATH}/src/github.com/Z-Bolt/OctoScreen/ +WORKDIR /OctoScreen/ diff --git a/Gopkg.lock b/Gopkg.lock deleted file mode 100644 index c3ec9e5f..00000000 --- a/Gopkg.lock +++ /dev/null @@ -1,61 +0,0 @@ -memo = "1d6b648d9b1c526dfce34fe8a2dd8a2efad3406a3d4a346852da0ce192f63d30" - -[[projects]] - branch = "master" - name = "github.com/StackExchange/wmi" - packages = ["."] - revision = "ea383cf3ba6ec950874b8486cd72356d007c768f" - -[[projects]] - branch = "master" - name = "github.com/dustin/go-humanize" - packages = ["."] - revision = "bb3d318650d48840a39aa21a027c6630e198e626" - -[[projects]] - name = "github.com/go-ole/go-ole" - packages = [".","oleutil"] - revision = "0e87ea779d9deb219633b828a023b32e1244dd57" - version = "v1.2.0" - -[[projects]] - branch = "master" - name = "github.com/gotk3/gotk3" - packages = ["cairo","gdk","glib","gtk","pango"] - revision = "8364b1c62f2b942c9647d392b2980a60f87037da" - -[[projects]] - branch = "master" - name = "github.com/mcuadros/go-octoprint" - packages = ["."] - revision = "01362f94e21fd2fd43e430358b250cfa89eeab44" - -[[projects]] - name = "github.com/shirou/gopsutil" - packages = ["internal/common","load","mem"] - revision = "7ec06ec280df1dd1f08befc535049d49d63ae18a" - version = "v2.17.12" - -[[projects]] - name = "github.com/sirupsen/logrus" - packages = ["."] - revision = "d682213848ed68c0a260ca37d6dd5ace8423f5ba" - version = "v1.0.4" - -[[projects]] - branch = "master" - name = "golang.org/x/crypto" - packages = ["ssh/terminal"] - revision = "0fcca4842a8d74bfddc2c96a073bd2a4d2a7a2e8" - -[[projects]] - branch = "master" - name = "golang.org/x/sys" - packages = ["unix","windows"] - revision = "a3f2cbd54cf5dfe3fbaccf76375fdb12f67654c8" - -[[projects]] - branch = "v1" - name = "gopkg.in/yaml.v1" - packages = ["."] - revision = "9f9df34309c04878acc86042b16630b0f696e1de" diff --git a/Gopkg.toml b/Gopkg.toml deleted file mode 100644 index 75ece1d9..00000000 --- a/Gopkg.toml +++ /dev/null @@ -1,72 +0,0 @@ - -## Gopkg.toml example (these lines may be deleted) - -## "required" lists a set of packages (not projects) that must be included in -## Gopkg.lock. This list is merged with the set of packages imported by the current -## project. Use it when your project needs a package it doesn't explicitly import - -## including "main" packages. -# required = ["github.com/user/thing/cmd/thing"] - -## "ignored" lists a set of packages (not projects) that are ignored when -## dep statically analyzes source code. Ignored packages can be in this project, -## or in a dependency. -# ignored = ["github.com/user/project/badpkg"] - -## Dependencies define constraints on dependent projects. They are respected by -## dep whether coming from the Gopkg.toml of the current project or a dependency. -# [[dependencies]] -## Required: the root import path of the project being constrained. -# name = "github.com/user/project" -# -## Recommended: the version constraint to enforce for the project. -## Only one of "branch", "version" or "revision" can be specified. -# version = "1.0.0" -# branch = "master" -# revision = "abc123" -# -## Optional: an alternate location (URL or import path) for the project's source. -# source = "https://github.com/myfork/package.git" - -## Overrides have the same structure as [[dependencies]], but supercede all -## [[dependencies]] declarations from all projects. Only the current project's -## [[overrides]] are applied. -## -## Overrides are a sledgehammer. Use them only as a last resort. -# [[overrides]] -## Required: the root import path of the project being constrained. -# name = "github.com/user/project" -# -## Optional: specifying a version constraint override will cause all other -## constraints on this project to be ignored; only the overriden constraint -## need be satisfied. -## Again, only one of "branch", "version" or "revision" can be specified. -# version = "1.0.0" -# branch = "master" -# revision = "abc123" -# -## Optional: specifying an alternate source location as an override will -## enforce that the alternate location is used for that project, regardless of -## what source location any dependent projects specify. -# source = "https://github.com/myfork/package.git" - - - -[[dependencies]] - branch = "master" - name = "github.com/dustin/go-humanize" - -[[dependencies]] - branch = "master" - name = "github.com/gotk3/gotk3" - -[[dependencies]] - branch = "master" - name = "github.com/mcuadros/go-octoprint" - -[[dependencies]] - branch = "master" - name = "github.com/sirupsen/logrus" - -[[dependencies]] - branch = "master" - name = "pifke.org/wpasupplicant" \ No newline at end of file diff --git a/Makefile b/Makefile index fdb4091e..a3ed2b82 100755 --- a/Makefile +++ b/Makefile @@ -13,22 +13,23 @@ GOTEST = $(GOCMD) test -v # Environment WORKDIR := $(shell pwd) BUILD_PATH := $(WORKDIR)/build +GOCACHE_PATH = $(WORKDIR)/gocache DOCKER_IMAGE_BUILD = mcuadros/octoprint-tft-build -DEBIAN_PACKAGES = STRETCH +DEBIAN_PACKAGES = BUSTER +ARCH = armhf +# ARCH = amd64 -BUSTER_NAME := buster -BUSTER_IMAGE := golang:1.15-buster -BUSTER_GO_TAGS := gtk_3_24 - -STRETCH_NAME := stretch -STRETCH_IMAGE := golang:1.9-stretch -STRETCH_GO_TAGS := gtk_3_22 - -JESSIE_NAME := jessie -JESSIE_IMAGE := golang:1.8-jessie -JESSIE_GO_TAGS := gtk_3_14 +BULLSEYE_NAME := bullseye +BULLSEYE_IMAGE := golang:1.20-bullseye +BULLSEYE_GO_TAGS := "gtk_3_24 glib_deprecated glib_2_66" +# Buster's gtk 3.24.5 doesn't work with gtk_3_24 tag +# Using gtk_3_22 produces some deprecation warnings, but it compiles +# More info: https://github.com/gotk3/gotk3/issues/874 +BUSTER_NAME := buster +BUSTER_IMAGE := golang:1.20-buster +BUSTER_GO_TAGS := "gtk_3_22 glib_deprecated glib_2_58 pango_1_42" # Build information #GIT_COMMIT = $(shell git rev-parse HEAD | cut -c1-7) @@ -49,28 +50,32 @@ export build-environment: mkdir -p ${BUILD_PATH} + mkdir -p ${GOCACHE_PATH} build: | build-environment $(DEBIAN_PACKAGES) $(DEBIAN_PACKAGES): docker build \ --build-arg IMAGE=${${@}_IMAGE} \ + --build-arg TARGET_ARCH=${ARCH} \ --build-arg GO_TAGS=${${@}_GO_TAGS} \ - -t ${DOCKER_IMAGE_BUILD}:${${@}_NAME} . \ + -t ${DOCKER_IMAGE_BUILD}:${${@}_NAME}-${ARCH} . \ && \ - docker run -it --rm \ - -v ${BUILD_PATH}/${${@}_NAME}:/build \ - ${DOCKER_IMAGE_BUILD}:${${@}_NAME} \ + docker run --rm \ + -e TARGET_ARCH=${ARCH} \ + -v ${BUILD_PATH}/${${@}_NAME}-${ARCH}:/build \ + -v ${GOCACHE_PATH}/${${@}_NAME}-${ARCH}:/gocache \ + ${DOCKER_IMAGE_BUILD}:${${@}_NAME}-${ARCH} \ make build-internal build-internal: prepare-internal #go build --tags ${GO_TAGS} -v -o /build/bin/${BINARY_NAME} main.go cd $(WORKDIR); \ - debuild --prepend-path=/usr/local/go/bin/ --preserve-env -us -uc; \ - cp ../*.deb /build/; + GOCACHE=/gocache debuild --prepend-path=/usr/local/go/bin/ --preserve-env -us -uc -a${TARGET_ARCH} \ + && cp ../*.deb /build/; prepare-internal: - dch --create -v $(VERSION)-1 --package $(PACKAGE_NAME) empty; \ + dch --create -v $(VERSION)-1 --package $(PACKAGE_NAME) --controlmaint empty; \ cd $(WORKDIR)/..; \ tar -czf octoscreen_$(VERSION).orig.tar.gz --exclude-vcs OctoScreen diff --git a/README.md b/README.md index cc6a6efe..6b2fd979 100755 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ You will also need to set up the video drivers for the display you are using. I ### Install From a .deb Package -There are two ways to install OctoScreen: the recommended and supported way is to install from a .deb package, or you can choose to install from building the sources yourself. The recommended way to install OctoScreen is use the `.deb` packages from the [Releases](https://github.com/Z-Bolt/OctoScreen/releases) page. The packages are available for Debian Stretch based distributions such as Raspbian and OctoPi. +There are two ways to install OctoScreen: the recommended and supported way is to install from a .deb package, or you can choose to install from building the sources yourself. The recommended way to install OctoScreen is use the `.deb` packages from the [Releases](https://github.com/Z-Bolt/OctoScreen/releases) page. The packages are available for Debian based distributions such as Raspbian and OctoPi. For example, to install on a new RaspberryPi with OctoPi: ```sh @@ -115,10 +115,10 @@ make build ls -1 build/ ``` -The default build is for the STRETCH release of debian, but BUSTER and JESSIE are also possible. To build one of these targets, you just have to specify the package during make. -Example for BUSTER: +The default build is for the BUSTER release of debian, but BULLSEYE is also possible. To build one of these targets, you just have to specify the package during make. +Example for BULLSEYE: ```sh -make build DEBIAN_PACKAGES=BUSTER +make build DEBIAN_PACKAGES=BULLSEYE ls -1 build/ ``` diff --git a/debian/control b/debian/control index 6cd5cf6f..3ed9b0ba 100644 --- a/debian/control +++ b/debian/control @@ -3,9 +3,8 @@ Section: devel Priority: optional Maintainer: Debian Go Packaging Team Uploaders: Máximo Cuadros -Build-Depends: debhelper (>= 9), +Build-Depends: debhelper (>= 9.20160709), dh-golang, - dh-systemd, libcairo2-dev (>= 1.14.0), libgtk-3-dev (>= 3.14) Standards-Version: 4.1.1 @@ -22,8 +21,10 @@ Depends: ${shlibs:Depends}, ${misc:Depends}, libcairo2 (>= 1.14.0), libgtk-3-0 (>= 3.14), + librsvg2-common, xserver-xorg, - xinit + xinit, + x11-xserver-utils Provides: x-display-manager Description: A OctoPrint touch interface for TFT touch modules based on GTK+3 OOctoScreen OOctoScreen, a touch interface for TFT touch modules diff --git a/debian/rules b/debian/rules index 55088c60..27de23b1 100755 --- a/debian/rules +++ b/debian/rules @@ -1,21 +1,49 @@ #!/usr/bin/make -f +SHELL := /bin/bash + export DH_VERBOSE := 1 export DH_GOPKG := github.com/Z-Bolt/OctoScreen +export DH_GOLANG_BUILDPKG := github.com/Z-Bolt/OctoScreen export DH_GOLANG_INSTALL_ALL := 1 -export DH_GOLANG_EXCLUDES := vendor -export GOCACHE := $(GOPATH)/pkg + +export GOPROXY := https://proxy.golang.org +export GO111MODULE := on + +# Workaround for dh-golang before https://salsa.debian.org/go-team/packages/dh-golang/-/commit/8b121b42e5597c9d156d2f811810d1d86787d449 +_DH_GOLANG_VERSION := $(shell dpkg-query --show --showformat '$${Version}' dh-golang) +_DH_GOLANG_WITH_CROSSBUILD_SUPPORT := $(shell dpkg --compare-versions $(_DH_GOLANG_VERSION) lt 1.43 2> /dev/null; echo $$?) + +ifeq ($(_DH_GOLANG_WITH_CROSSBUILD_SUPPORT),0) + export GOOS := linux + ifeq ($(DEB_HOST_ARCH),armhf) + export GOARCH := arm + export GOARM := 7 + else + export GOARCH := $(DEB_HOST_ARCH) + endif + + export CGO_ENABLED := 1 + export CC := $(DEB_HOST_MULTIARCH)-gcc + export PKG_CONFIG_PATH := /usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig +endif %: dh $@ --buildsystem=golang --with=golang,systemd override_dh_auto_build: - dh_auto_build -O--buildsystem=golang -O--no-parallel -- \ - --tags $(GO_TAGS) \ + dh_auto_build -O--buildsystem=golang -- \ + --tags "$(GO_TAGS)" \ -ldflags "\ -X $(DH_GOPKG)/ui.Version=$(VERSION) \ -X $(DH_GOPKG)/ui.Build=$(BUILD_DATE)\ " + if [[ $(_DH_GOLANG_WITH_CROSSBUILD_SUPPORT) != 1 ]]; then \ + if [[ "$(DEB_BUILD_ARCH)" != "$(DEB_HOST_ARCH)" ]]; then \ + mv $(CURDIR)/obj-$(DEB_HOST_MULTIARCH)/bin/$(GOOS)_$(GOARCH)/* $(CURDIR)/obj-$(DEB_HOST_MULTIARCH)/bin/; \ + rm -r $(CURDIR)/obj-$(DEB_HOST_MULTIARCH)/bin/$(GOOS)_$(GOARCH); \ + fi; \ + fi override_dh_golang: # The dh_golang is used to add the Built-using field to the deb. This is only for reference. @@ -26,6 +54,7 @@ override_dh_install: mkdir -p $(CURDIR)/debian/octoscreen/opt/octoscreen/ cp -r styles $(CURDIR)/debian/octoscreen/opt/octoscreen/ rm -rf $(CURDIR)/debian/octoscreen/usr/share/gocode + chmod -x "debian/octoscreen.install" # Make sure octoscreen.install isn't executable dh_install -XLICENSE override_dh_auto_test: diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..dc23ceae --- /dev/null +++ b/go.mod @@ -0,0 +1,25 @@ +module github.com/Z-Bolt/OctoScreen + +go 1.20 + +require ( + github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf + github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4 + github.com/golang-collections/collections v0.0.0-20130729185459-604e922904d3 + github.com/gotk3/gotk3 v0.6.2-0.20220628045702-d885f48a5492 + github.com/shirou/gopsutil v2.17.12+incompatible + github.com/sirupsen/logrus v1.9.0 + gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0 + pifke.org/wpasupplicant v0.0.0-20200816231324-12bdf536389f +) + +require ( + github.com/StackExchange/wmi v0.0.0-20170410192909-ea383cf3ba6e // indirect + github.com/go-ole/go-ole v1.2.0 // indirect + github.com/stretchr/testify v1.8.0 // indirect + golang.org/x/crypto v0.0.0-20171231215028-0fcca4842a8d // indirect + golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect + gopkg.in/airbrake/gobrake.v2 v2.0.9 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..1c12313c --- /dev/null +++ b/go.sum @@ -0,0 +1,54 @@ +github.com/StackExchange/wmi v0.0.0-20170410192909-ea383cf3ba6e h1:IHXQQIpxASe3m0Jtcd3XongL+lxHNd5nUmvHxJARUmg= +github.com/StackExchange/wmi v0.0.0-20170410192909-ea383cf3ba6e/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= +github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU= +github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4 h1:qk/FSDDxo05wdJH28W+p5yivv7LuLYLRXPPD8KQCtZs= +github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/go-ole/go-ole v1.2.0 h1:wiiTJjbwlWm5KF3UgZHuU2a2ZKA8MXJaW4vnW0SOwg4= +github.com/go-ole/go-ole v1.2.0/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= +github.com/golang-collections/collections v0.0.0-20130729185459-604e922904d3 h1:zN2lZNZRflqFyxVaTIU61KNKQ9C0055u9CAfpmqUvo4= +github.com/golang-collections/collections v0.0.0-20130729185459-604e922904d3/go.mod h1:nPpo7qLxd6XL3hWJG/O60sR8ZKfMCiIoNap5GvD12KU= +github.com/gotk3/gotk3 v0.6.2-0.20220628045702-d885f48a5492 h1:4Bcs6gb1hgGHtvZ32t7i7JqGnbXkYnRI1Sa+NoldgmU= +github.com/gotk3/gotk3 v0.6.2-0.20220628045702-d885f48a5492/go.mod h1:/hqFpkNa9T3JgNAE2fLvCdov7c5bw//FHNZrZ3Uv9/Q= +github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +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/shirou/gopsutil v2.17.12+incompatible h1:FNbznluSK3DQggqiVw3wK/tFKJrKlLPBuQ+V8XkkCOc= +github.com/shirou/gopsutil v2.17.12+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= +github.com/sirupsen/logrus v1.0.4 h1:gzbtLsZC3Ic5PptoRG+kQj4L60qjK7H7XszrU163JNQ= +github.com/sirupsen/logrus v1.0.4/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= +github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +golang.org/x/crypto v0.0.0-20171231215028-0fcca4842a8d h1:GrqEEc3+MtHKTsZrdIGVoYDgLpbSRzW1EF+nLu0PcHE= +golang.org/x/crypto v0.0.0-20171231215028-0fcca4842a8d/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/sys v0.0.0-20180104162908-a3f2cbd54cf5 h1:6Od77Y9QsEwa/MFtLV5Oyv3/z8z7CSga7Qzdkg8VUKE= +golang.org/x/sys v0.0.0-20180104162908-a3f2cbd54cf5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +gopkg.in/airbrake/gobrake.v2 v2.0.9 h1:7z2uVWwn7oVeeugY1DtlPAy5H+KYgB1KeKTnqjNatLo= +gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/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/gemnasium/logrus-airbrake-hook.v2 v2.1.2 h1:OAj3g0cR6Dx/R07QgQe8wkA9RNjB2u4i700xBkIT4e0= +gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= +gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0 h1:POO/ycCATvegFmVuPpQzZFJ+pGZeX22Ufu6fibxDVjU= +gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +pifke.org/wpasupplicant v0.0.0-20200816231324-12bdf536389f h1:hI2b46+nRc9gwX1zne3kDsCE669yLLBRzCQ1ORDjrX8= +pifke.org/wpasupplicant v0.0.0-20200816231324-12bdf536389f/go.mod h1:76nFyvc1UBvdBKAle/WKulDZK54rmyX59+mX4zqFQMs= diff --git a/ui/PrintStatusPanel.go b/ui/PrintStatusPanel.go index fdbf1baa..f31d7683 100755 --- a/ui/PrintStatusPanel.go +++ b/ui/PrintStatusPanel.go @@ -24,12 +24,12 @@ type printStatusPanel struct { PrintWasCanceled bool // Tools - tool0Button *uiWidgets.ToolPrintingButton - tool1Button *uiWidgets.ToolPrintingButton - tool2Button *uiWidgets.ToolPrintingButton - tool3Button *uiWidgets.ToolPrintingButton + tool0Button *uiWidgets.ToolPrintingButton + tool1Button *uiWidgets.ToolPrintingButton + tool2Button *uiWidgets.ToolPrintingButton + tool3Button *uiWidgets.ToolPrintingButton tool4Button *uiWidgets.ToolPrintingButton - bedButton *uiWidgets.ToolPrintingButton + bedButton *uiWidgets.ToolPrintingButton // Statistics/Info fileLabelWithImage *utils.LabelWithImage @@ -45,7 +45,7 @@ type printStatusPanel struct { progressBar *gtk.ProgressBar // Toolbar buttons - pauseButton *gtk.Button + pauseButton *gtk.Button cancelButton *gtk.Button controlButton *gtk.Button completedButton *gtk.Button @@ -491,7 +491,7 @@ func (this *printStatusPanel) handlePauseClicked() { } logger.TraceLeave("PrintStatusPanel.handlePauseClicked()") -} + } func (this *printStatusPanel) handleCancelClicked() { userResponse := this.confirmCancelDialogBox( @@ -499,14 +499,14 @@ func (this *printStatusPanel) handleCancelClicked() { "Are you sure you want to cancel the current print?", ) - if userResponse == int(gtk.RESPONSE_YES) { + if userResponse == gtk.RESPONSE_YES { this.cancelPrintJob() } } func (this *printStatusPanel) handleControlClicked() { this.UI.GoToPanel(GetPrintMenuPanelInstance(this.UI)) -} + } func (this *printStatusPanel) handleCompleteClicked() { this.UI.WaitingForUserToContinue = false @@ -515,31 +515,31 @@ func (this *printStatusPanel) handleCompleteClicked() { func (this *printStatusPanel) confirmCancelDialogBox( parentWindow *gtk.Window, message string, -) int { - dialogBox := gtk.MessageDialogNewWithMarkup( - parentWindow, - gtk.DIALOG_MODAL, - gtk.MESSAGE_INFO, - gtk.BUTTONS_YES_NO, - "", - ) +) gtk.ResponseType { + dialogBox := gtk.MessageDialogNewWithMarkup( + parentWindow, + gtk.DIALOG_MODAL, + gtk.MESSAGE_INFO, + gtk.BUTTONS_YES_NO, + "", + ) - dialogBox.SetMarkup(utils.CleanHTML(message)) - defer dialogBox.Destroy() + dialogBox.SetMarkup(utils.CleanHTML(message)) + defer dialogBox.Destroy() - box, _ := dialogBox.GetContentArea() - box.SetMarginStart(15) - box.SetMarginEnd(15) - box.SetMarginTop(15) - box.SetMarginBottom(15) + box, _ := dialogBox.GetContentArea() + box.SetMarginStart(15) + box.SetMarginEnd(15) + box.SetMarginTop(15) + box.SetMarginBottom(15) - ctx, _ := dialogBox.GetStyleContext() - ctx.AddClass("dialog") + ctx, _ := dialogBox.GetStyleContext() + ctx.AddClass("dialog") - userResponse := dialogBox.Run() + userResponse := dialogBox.Run() return userResponse -} + } func (this *printStatusPanel) cancelPrintJob() { logger.TraceEnter("PrintStatusPanel.cancelPrintJob()") @@ -551,10 +551,10 @@ func (this *printStatusPanel) cancelPrintJob() { this.controlButton.SetSensitive(false) } else { logger.LogError("PrintStatusPanel.cancelPrintJob()", "Do(CancelRequest)", err) - } + } logger.TraceLeave("PrintStatusPanel.cancelPrintJob()") -} + } func formattedDuration(duration time.Duration) string { hours := duration / time.Hour diff --git a/ui/z_offset_calibration_panel.go b/ui/z_offset_calibration_panel.go index e75b7257..87ee5938 100755 --- a/ui/z_offset_calibration_panel.go +++ b/ui/z_offset_calibration_panel.go @@ -90,11 +90,7 @@ func (this *zOffsetCalibrationPanel) initialize() { // First row func (this *zOffsetCalibrationPanel) CreateSelectToolStepButton() { this.selectHotendStepButton = uiWidgets.CreateSelectHotendStepButton(this.UI.Client, false, 1, nil) - _, err := this.selectHotendStepButton.Connect("clicked", this.selectToolStepButtonHandleClick) - if err != nil { - logger.LogError("PANIC!!! - zOffsetCalibrationPanel.CreateSelectToolStepButton()", "selectHotendStepButton.Connect()", err) - panic(err) - } + this.selectHotendStepButton.Connect("clicked", this.selectToolStepButtonHandleClick) hotendCount := utils.GetHotendCount(this.UI.Client) if hotendCount > 1 { @@ -131,11 +127,7 @@ func (this *zOffsetCalibrationPanel) selectToolStepButtonHandleClick() { func (this *zOffsetCalibrationPanel) CreateDecreaseZOffsetButton() { this.decreaseZOffsetButton = uiWidgets.CreateIncreaseZOffsetButton(false) - _, err := this.decreaseZOffsetButton.Connect("clicked", this.decreaseZOffsetButtonClicked) - if err != nil { - logger.LogError("PANIC!!! - zOffsetCalibrationPanel.CreateDecreaseZOffsetButton()", "decreaseZOffsetButton.Connect()", err) - panic(err) - } + this.decreaseZOffsetButton.Connect("clicked", this.decreaseZOffsetButtonClicked) this.Grid().Attach(this.decreaseZOffsetButton, 1, 0, 1, 1) } @@ -149,11 +141,7 @@ func (this *zOffsetCalibrationPanel) decreaseZOffsetButtonClicked() { func (this *zOffsetCalibrationPanel) CreateIncreaseZOffsetButton() { this.increaseZOffsetButton = uiWidgets.CreateIncreaseZOffsetButton(true) - _, err := this.increaseZOffsetButton.Connect("clicked", this.increaseZOffsetButtonClicked) - if err != nil { - logger.LogError("PANIC!!! - zOffsetCalibrationPanel.CreateIncreaseZOffsetButton()", "increaseZOffsetButton.Connect()", err) - panic(err) - } + this.increaseZOffsetButton.Connect("clicked", this.increaseZOffsetButtonClicked) this.Grid().Attach(this.increaseZOffsetButton, 2, 0, 1, 1) } @@ -182,11 +170,7 @@ func (this *zOffsetCalibrationPanel) CreateZOffsetLabel() *gtk.Label { // Third row func (this *zOffsetCalibrationPanel) CreateManualZCalibrationStepButton() { this.manualZCalibrationStepButton = uiWidgets.CreateManualZCalibrationStepButton(2, nil) - _, err := this.manualZCalibrationStepButton.Connect("clicked", this.manualZCalibrationStepButtonHandleClick) - if err != nil { - logger.LogError("PANIC!!! - zOffsetCalibrationPanel.CreateManualZCalibrationStepButton()", "manualZCalibrationStepButton.Connect()", err) - panic(err) - } + this.manualZCalibrationStepButton.Connect("clicked", this.manualZCalibrationStepButtonHandleClick) this.Grid().Attach(this.manualZCalibrationStepButton, 0, 2, 1, 1) } diff --git a/uiWidgets/AmountToExtrudeStepButton.go b/uiWidgets/AmountToExtrudeStepButton.go index 4f345c43..53a68c5a 100755 --- a/uiWidgets/AmountToExtrudeStepButton.go +++ b/uiWidgets/AmountToExtrudeStepButton.go @@ -1,9 +1,5 @@ package uiWidgets -import ( - "github.com/Z-Bolt/OctoScreen/logger" -) - type AmountToExtrudeStepButton struct { *StepButton } @@ -12,7 +8,7 @@ func CreateAmountToExtrudeStepButton( colorVariation int, clicked func(), ) *AmountToExtrudeStepButton { - base, err := CreateStepButton( + base := CreateStepButton( colorVariation, clicked, Step{" 20mm", "move-step.svg", nil, 20}, @@ -22,10 +18,6 @@ func CreateAmountToExtrudeStepButton( Step{" 5mm", "move-step.svg", nil, 5}, Step{" 10mm", "move-step.svg", nil, 10}, ) - if err != nil { - logger.LogError("PANIC!!! - CreateAmountToExtrudeStepButton()", "CreateStepButton()", err) - panic(err) - } instance := &AmountToExtrudeStepButton { StepButton: base, diff --git a/uiWidgets/AmountToMoveStepButton.go b/uiWidgets/AmountToMoveStepButton.go index 0e90658e..c4190e70 100755 --- a/uiWidgets/AmountToMoveStepButton.go +++ b/uiWidgets/AmountToMoveStepButton.go @@ -1,9 +1,5 @@ package uiWidgets -import ( - "github.com/Z-Bolt/OctoScreen/logger" -) - type AmountToMoveStepButton struct { *StepButton } @@ -12,7 +8,7 @@ func CreateAmountToMoveStepButton( colorVariation int, clicked func(), ) *AmountToMoveStepButton { - base, err := CreateStepButton( + base := CreateStepButton( colorVariation, clicked, Step{"10mm", "move-step.svg", nil, 10.00}, @@ -22,10 +18,6 @@ func CreateAmountToMoveStepButton( Step{"0.1mm", "move-step.svg", nil, 0.10}, Step{" 1mm", "move-step.svg", nil, 1.00}, ) - if err != nil { - logger.LogError("PANIC!!! - CreateAmountToMoveStepButton()", "CreateStepButton()", err) - panic(err) - } instance := &AmountToMoveStepButton{ StepButton: base, diff --git a/uiWidgets/ClickableListBoxRow.go b/uiWidgets/ClickableListBoxRow.go index fa736d83..f54a56cf 100644 --- a/uiWidgets/ClickableListBoxRow.go +++ b/uiWidgets/ClickableListBoxRow.go @@ -2,21 +2,20 @@ package uiWidgets import ( "github.com/gotk3/gotk3/gtk" - // "github.com/Z-Bolt/OctoScreen/utils" ) type ClickableListBoxRow struct { gtk.ListBoxRow - ListItemButton *gtk.Button - RowIndex int + ListItemButton *gtk.Button + RowIndex int } func CreateClickableListBoxRow( - rowIndex int, - padding int, - rowClickHandler func (button *gtk.Button, rowIndex int), + rowIndex int, + padding int, + rowClickHandler func(button *gtk.Button, rowIndex int), ) *ClickableListBoxRow { /* Object hierarchy (for a static, non-clickable list item): @@ -37,10 +36,10 @@ func CreateClickableListBoxRow( listItemButton := createListItemButton(rowIndex, rowClickHandler) base.Add(listItemButton) - instance := &ClickableListBoxRow { - ListBoxRow: *base, - ListItemButton: listItemButton, - RowIndex: rowIndex, + instance := &ClickableListBoxRow{ + ListBoxRow: *base, + ListItemButton: listItemButton, + RowIndex: rowIndex, } return instance @@ -52,23 +51,25 @@ func CreateClickableListBoxRow( // child widget is added to uiWidgets.ListBoxRow, it will actually // be added to contentsBox. // -// Object hierarchy: +// Object hierarchy: // gtk.ListBoxRow (base) func (this *ClickableListBoxRow) Add(widget gtk.IWidget) { this.ListItemButton.Add(widget) } func createListItemButton( - rowIndex int, - rowClickHandler func (button *gtk.Button, rowIndex int), -) *gtk.Button{ + rowIndex int, + rowClickHandler func(button *gtk.Button, rowIndex int), +) *gtk.Button { listItemButton, _ := gtk.ButtonNew() - listItemButton.Connect("clicked", rowClickHandler, rowIndex) + listItemButton.Connect("clicked", func(button *gtk.Button) { + rowClickHandler(button, rowIndex) + }) listItemButtonStyleContext, _ := listItemButton.GetStyleContext() listItemButtonStyleContext.AddClass("list-item-button") - if rowIndex % 2 == 0 { + if rowIndex%2 == 0 { listItemButtonStyleContext.AddClass("list-item-nth-child-odd-background-color") } else { listItemButtonStyleContext.AddClass("list-item-nth-child-even-background-color") diff --git a/uiWidgets/CommandButton.go b/uiWidgets/CommandButton.go index 2ed5dd80..24f185c3 100755 --- a/uiWidgets/CommandButton.go +++ b/uiWidgets/CommandButton.go @@ -38,11 +38,7 @@ func CreateCommandButton( parentWindow: parentWindow, commandDefinition: commandDefinition, } - _, err := instance.Button.Connect("clicked", instance.handleClicked) - if err != nil { - logger.LogError("PANIC!!! - CreateCommandButton()", "instance.Button.Connect()", err) - panic(err) - } + instance.Button.Connect("clicked", instance.handleClicked) return instance } diff --git a/uiWidgets/ControlButton.go b/uiWidgets/ControlButton.go index 575639ed..6717c873 100755 --- a/uiWidgets/ControlButton.go +++ b/uiWidgets/ControlButton.go @@ -38,11 +38,7 @@ func CreateControlButton( parentWindow: parentWindow, controlDefinition: controlDefinition, } - _, err := instance.Button.Connect("clicked", instance.handleClicked) - if err != nil { - logger.LogError("PANIC!!! - CreateControlButton()", "instance.Button.Connect()", err) - panic(err) - } + instance.Button.Connect("clicked", instance.handleClicked) return instance } diff --git a/uiWidgets/CoolDownButton.go b/uiWidgets/CoolDownButton.go index e4a1c675..4620629a 100755 --- a/uiWidgets/CoolDownButton.go +++ b/uiWidgets/CoolDownButton.go @@ -28,11 +28,7 @@ func CreateCoolDownButton( client: client, callback: callback, } - _, err := instance.Button.Connect("clicked", instance.handleClicked) - if err != nil { - logger.LogError("PANIC!!! - CreateCoolDownButton()", "instance.Button.Connect()", err) - panic(err) - } + instance.Button.Connect("clicked", instance.handleClicked) return instance } diff --git a/uiWidgets/FanButton.go b/uiWidgets/FanButton.go index ad5de56d..5036c1d9 100755 --- a/uiWidgets/FanButton.go +++ b/uiWidgets/FanButton.go @@ -40,11 +40,7 @@ func CreateFanButton( client: client, amount: amount, } - _, err := instance.Button.Connect("clicked", instance.handleClicked) - if err != nil { - logger.LogError("PANIC!!! - CreateFanButton()", "instance.Button.Connect()", err) - panic(err) - } + instance.Button.Connect("clicked", instance.handleClicked) return instance } diff --git a/uiWidgets/FilamentExtrudeButton.go b/uiWidgets/FilamentExtrudeButton.go index 858a702e..48cb1cec 100755 --- a/uiWidgets/FilamentExtrudeButton.go +++ b/uiWidgets/FilamentExtrudeButton.go @@ -2,7 +2,6 @@ package uiWidgets import ( "github.com/gotk3/gotk3/gtk" - "github.com/Z-Bolt/OctoScreen/logger" "github.com/Z-Bolt/OctoScreen/octoprintApis" // "github.com/Z-Bolt/OctoScreen/octoprintApis/dataModels" "github.com/Z-Bolt/OctoScreen/utils" @@ -43,11 +42,7 @@ func CreateFilamentExtrudeButton( selectExtruderStepButton: selectExtruderStepButton, isForward: isForward, } - _, err := instance.Button.Connect("clicked", instance.handleClicked) - if err != nil { - logger.LogError("PANIC!!! - CreateFilamentExtrudeButton()", "instance.Button.Connect()", err) - panic(err) - } + instance.Button.Connect("clicked", instance.handleClicked) return instance } diff --git a/uiWidgets/FilamentLoadButton.go b/uiWidgets/FilamentLoadButton.go index 79dfb2cd..d803dbbc 100755 --- a/uiWidgets/FilamentLoadButton.go +++ b/uiWidgets/FilamentLoadButton.go @@ -4,7 +4,6 @@ import ( // "fmt" "github.com/gotk3/gotk3/gtk" - "github.com/Z-Bolt/OctoScreen/logger" "github.com/Z-Bolt/OctoScreen/octoprintApis" // "github.com/Z-Bolt/OctoScreen/octoprintApis/dataModels" "github.com/Z-Bolt/OctoScreen/utils" @@ -46,11 +45,7 @@ func CreateFilamentLoadButton( isForward: isForward, length: length, } - _, err := instance.Button.Connect("clicked", instance.handleClicked) - if err != nil { - logger.LogError("PANIC!!! - CreateFilamentLoadButton()", "instance.Button.Connect()", err) - panic(err) - } + instance.Button.Connect("clicked", instance.handleClicked) return instance } diff --git a/uiWidgets/FlowRateStepButton.go b/uiWidgets/FlowRateStepButton.go index 3bfd05f2..66d69bae 100755 --- a/uiWidgets/FlowRateStepButton.go +++ b/uiWidgets/FlowRateStepButton.go @@ -1,7 +1,6 @@ package uiWidgets import ( - "github.com/Z-Bolt/OctoScreen/logger" "github.com/Z-Bolt/OctoScreen/octoprintApis" // "github.com/Z-Bolt/OctoScreen/octoprintApis/dataModels" "github.com/Z-Bolt/OctoScreen/utils" @@ -13,21 +12,17 @@ type FlowRateStepButton struct { } func CreateFlowRateStepButton( - client *octoprintApis.Client, + client *octoprintApis.Client, colorVariation int, clicked func(), ) *FlowRateStepButton { - base, err := CreateStepButton( + base := CreateStepButton( colorVariation, clicked, Step{"Normal (100%)", "speed-normal.svg", nil, 100}, Step{"Fast (125%)", "speed-fast.svg", nil, 125}, Step{"Slow (75%)", "speed-slow.svg", nil, 75}, ) - if err != nil { - logger.LogError("PANIC!!! - CreateFlowRateStepButton()", "CreateStepButton()", err) - panic(err) - } instance := &FlowRateStepButton{ StepButton: base, diff --git a/uiWidgets/HomeAllButton.go b/uiWidgets/HomeAllButton.go index b36f8489..76728898 100755 --- a/uiWidgets/HomeAllButton.go +++ b/uiWidgets/HomeAllButton.go @@ -23,11 +23,7 @@ func CreateHomeAllButton( Button: base, client: client, } - _, err := instance.Button.Connect("clicked", instance.handleClicked) - if err != nil { - logger.LogError("PANIC!!! - CreateHomeAllButton()", "instance.Button.Connect()", err) - panic(err) - } + instance.Button.Connect("clicked", instance.handleClicked) return instance } diff --git a/uiWidgets/HomeButton.go b/uiWidgets/HomeButton.go index 5733798b..0fe7f56d 100755 --- a/uiWidgets/HomeButton.go +++ b/uiWidgets/HomeButton.go @@ -28,11 +28,7 @@ func CreateHomeButton( client: client, axes: axes, } - _, err := instance.Button.Connect("clicked", instance.handleClicked) - if err != nil { - logger.LogError("PANIC!!! - CreateHomeButton()", "instance.Button.Connect()", err) - panic(err) - } + instance.Button.Connect("clicked", instance.handleClicked) return instance } diff --git a/uiWidgets/ManualZCalibrationStepButton.go b/uiWidgets/ManualZCalibrationStepButton.go index 19b47935..c338d31d 100755 --- a/uiWidgets/ManualZCalibrationStepButton.go +++ b/uiWidgets/ManualZCalibrationStepButton.go @@ -1,9 +1,5 @@ package uiWidgets -import ( - "github.com/Z-Bolt/OctoScreen/logger" -) - type ManualZCalibrationStepButton struct { *StepButton } @@ -12,16 +8,12 @@ func CreateManualZCalibrationStepButton( colorVariation int, clicked func(), ) *ManualZCalibrationStepButton { - base, err := CreateStepButton( + base := CreateStepButton( colorVariation, clicked, Step{"Start Manual\nZ Calibration", "z-calibration.svg", nil, false}, Step{"Stop Manual\nZ Calibration", "z-calibration.svg", nil, true}, ) - if err != nil { - logger.LogError("PANIC!!! - CreateManualZCalibrationStepButton()", "CreateStepButton()", err) - panic(err) - } instance := &ManualZCalibrationStepButton{ StepButton: base, diff --git a/uiWidgets/SelectExtruderStepButton.go b/uiWidgets/SelectExtruderStepButton.go index 93d27d47..2947a7f5 100644 --- a/uiWidgets/SelectExtruderStepButton.go +++ b/uiWidgets/SelectExtruderStepButton.go @@ -5,17 +5,16 @@ import ( // "strconv" // "strings" - "github.com/Z-Bolt/OctoScreen/logger" "github.com/Z-Bolt/OctoScreen/octoprintApis" // "github.com/Z-Bolt/OctoScreen/octoprintApis/dataModels" "github.com/Z-Bolt/OctoScreen/utils" ) func CreateSelectExtruderStepButton( - client *octoprintApis.Client, - includeBed bool, - colorVariation int, - clicked func(), + client *octoprintApis.Client, + includeBed bool, + colorVariation int, + clicked func(), ) *SelectToolStepButton { extruderCount := utils.GetExtruderCount(client) @@ -25,12 +24,12 @@ func CreateSelectExtruderStepButton( if i == 0 && extruderCount == 1 { label = "Extruder" } else { - label = fmt.Sprintf("Extruder %d", i + 1) + label = fmt.Sprintf("Extruder %d", i+1) } - step := Step { + step := Step{ label, - utils.GetExtruderFileName(i + 1, extruderCount), + utils.GetExtruderFileName(i+1, extruderCount), nil, fmt.Sprintf("tool%d", i), } @@ -42,15 +41,11 @@ func CreateSelectExtruderStepButton( steps = append(steps, Step{"Bed", "bed.svg", nil, "bed"}) } - base, err := CreateStepButton( + base := CreateStepButton( colorVariation, clicked, steps..., ) - if err != nil { - logger.LogError("PANIC!!! - CreateSelectExtruderStepButton()", "CreateStepButton()", err) - panic(err) - } instance := &SelectToolStepButton{ StepButton: base, diff --git a/uiWidgets/SelectHotendStepButton.go b/uiWidgets/SelectHotendStepButton.go index cf68d0d1..ad35a0f6 100644 --- a/uiWidgets/SelectHotendStepButton.go +++ b/uiWidgets/SelectHotendStepButton.go @@ -5,18 +5,16 @@ import ( // "strconv" // "strings" - "github.com/Z-Bolt/OctoScreen/logger" "github.com/Z-Bolt/OctoScreen/octoprintApis" // "github.com/Z-Bolt/OctoScreen/octoprintApis/dataModels" "github.com/Z-Bolt/OctoScreen/utils" ) - func CreateSelectHotendStepButton( - client *octoprintApis.Client, - includeBed bool, - colorVariation int, - clicked func(), + client *octoprintApis.Client, + includeBed bool, + colorVariation int, + clicked func(), ) *SelectToolStepButton { hotendCount := utils.GetHotendCount(client) @@ -26,12 +24,12 @@ func CreateSelectHotendStepButton( if i == 0 && hotendCount == 1 { label = "Hotend" } else { - label = fmt.Sprintf("Hotend %d", i + 1) + label = fmt.Sprintf("Hotend %d", i+1) } - step := Step { + step := Step{ label, - utils.GetHotendFileName(i + 1, hotendCount), + utils.GetHotendFileName(i+1, hotendCount), nil, fmt.Sprintf("tool%d", i), } @@ -43,15 +41,11 @@ func CreateSelectHotendStepButton( steps = append(steps, Step{"Bed", "bed.svg", nil, "bed"}) } - base, err := CreateStepButton( + base := CreateStepButton( colorVariation, clicked, steps..., ) - if err != nil { - logger.LogError("PANIC!!! - CreateSelectHotendStepButton()", "CreateStepButton()", err) - panic(err) - } instance := &SelectToolStepButton{ StepButton: base, diff --git a/uiWidgets/SelectToolStepButton.go b/uiWidgets/SelectToolStepButton.go index e2b3b02c..c2937750 100755 --- a/uiWidgets/SelectToolStepButton.go +++ b/uiWidgets/SelectToolStepButton.go @@ -15,11 +15,11 @@ type SelectToolStepButton struct { *StepButton } -func (this *SelectToolStepButton) Value() string { +func (this *SelectToolStepButton) Value() string { return this.StepButton.Value().(string) } -func (this *SelectToolStepButton) Index() int { +func (this *SelectToolStepButton) Index() int { value := strings.Replace(this.Value(), "tool", "", -1) index, _ := strconv.Atoi(value) diff --git a/uiWidgets/StepButton.go b/uiWidgets/StepButton.go index bdb1ce6b..b16f0511 100755 --- a/uiWidgets/StepButton.go +++ b/uiWidgets/StepButton.go @@ -21,7 +21,7 @@ type StepButton struct { *gtk.Button sync.RWMutex - Steps []Step + Steps []Step CurrentStepIndex int clicked func() } @@ -30,7 +30,7 @@ func CreateStepButton( colorVariation int, clicked func(), steps ...Step, -) (*StepButton, error) { +) *StepButton { stepCount := len(steps) if stepCount < 1 { logger.Error("PANIC!!! - CreateStepButton() - len(steps) < 1") @@ -39,14 +39,14 @@ func CreateStepButton( base := utils.MustButtonImageUsingFilePath(steps[0].Label, steps[0].ImageFileName, nil) if stepCount > 1 { - ctx, _ := base.GetStyleContext() - colorClass := fmt.Sprintf("color-dash-%d", colorVariation) - ctx.AddClass(colorClass) + ctx, _ := base.GetStyleContext() + colorClass := fmt.Sprintf("color-dash-%d", colorVariation) + ctx.AddClass(colorClass) } instance := &StepButton{ - Button: base, - Steps: steps, + Button: base, + Steps: steps, CurrentStepIndex: -1, clicked: clicked, } @@ -59,9 +59,9 @@ func CreateStepButton( instance.CurrentStepIndex = 0 } - _, err := instance.Button.Connect("clicked", instance.handleClick) + instance.Button.Connect("clicked", instance.handleClick) - return instance, err + return instance } func (this *StepButton) Value() interface{} { @@ -102,5 +102,5 @@ func (this *StepButton) handleClick() { if this.clicked != nil { this.clicked() - } +} } diff --git a/uiWidgets/TemperatureAmountStepButton.go b/uiWidgets/TemperatureAmountStepButton.go index 62239d51..01d1979d 100755 --- a/uiWidgets/TemperatureAmountStepButton.go +++ b/uiWidgets/TemperatureAmountStepButton.go @@ -1,9 +1,5 @@ package uiWidgets -import ( - "github.com/Z-Bolt/OctoScreen/logger" -) - type TemperatureAmountStepButton struct { *StepButton } @@ -12,7 +8,7 @@ func CreateTemperatureAmountStepButton( colorVariation int, clicked func(), ) *TemperatureAmountStepButton { - base, err := CreateStepButton( + base := CreateStepButton( colorVariation, clicked, Step{"10°C", "move-step.svg", nil, 10.0}, @@ -21,10 +17,6 @@ func CreateTemperatureAmountStepButton( Step{" 1°C", "move-step.svg", nil, 1.0}, Step{" 5°C", "move-step.svg", nil, 5.0}, ) - if err != nil { - logger.LogError("PANIC!!! - CreateTemperatureAmountStepButton()", "CreateStepButton()", err) - panic(err) - } instance := &TemperatureAmountStepButton{ StepButton: base, diff --git a/uiWidgets/TemperatureIncreaseButton.go b/uiWidgets/TemperatureIncreaseButton.go index ba4a1a42..0e1a4e8a 100755 --- a/uiWidgets/TemperatureIncreaseButton.go +++ b/uiWidgets/TemperatureIncreaseButton.go @@ -37,11 +37,7 @@ func CreateTemperatureIncreaseButton( selectHotendStepButton: selectHotendStepButton, isIncrease: isIncrease, } - _, err := instance.Button.Connect("clicked", instance.handleClicked) - if err != nil { - logger.LogError("PANIC!!! - CreateTemperatureIncreaseButton()", "instance.Button.Connect()", err) - panic(err) - } + instance.Button.Connect("clicked", instance.handleClicked) return instance } diff --git a/uiWidgets/TemperaturePresetButton.go b/uiWidgets/TemperaturePresetButton.go index 9a6d4aee..3fe82d51 100755 --- a/uiWidgets/TemperaturePresetButton.go +++ b/uiWidgets/TemperaturePresetButton.go @@ -36,11 +36,7 @@ func CreateTemperaturePresetButton( temperaturePreset: temperaturePreset, callback: callback, } - _, err := instance.Button.Connect("clicked", instance.handleClicked) - if err != nil { - logger.LogError("PANIC!!! - CreateTemperaturePresetButton()", "instance.Button.Connect()", err) - panic(err) - } + instance.Button.Connect("clicked", instance.handleClicked) return instance } diff --git a/uiWidgets/ToolButton.go b/uiWidgets/ToolButton.go index b854e00b..a0a71185 100755 --- a/uiWidgets/ToolButton.go +++ b/uiWidgets/ToolButton.go @@ -60,10 +60,7 @@ func CreateToolButton( printer: printer, } - _, err := instance.Connect("clicked", instance.clicked) - if err != nil { - logger.LogError("ToolButton.CreateToolButton()", "t.Connect('clicked', t.clicked)", err) - } + instance.Connect("clicked", instance.clicked) return instance } diff --git a/utils/BackgroundTask.go b/utils/BackgroundTask.go index 57910d25..8d6c34dd 100755 --- a/utils/BackgroundTask.go +++ b/utils/BackgroundTask.go @@ -73,10 +73,7 @@ func (this *BackgroundTask) loop() { } func (this *BackgroundTask) execute() { - _, err := glib.IdleAdd(this.task) - if err != nil { - logger.LogFatalError("BackgroundTask.execute()", "IdleAdd()", err) - } + glib.IdleAdd(this.task) } diff --git a/utils/ui_utils.go b/utils/ui_utils.go index 5cd91b0b..b89369e9 100755 --- a/utils/ui_utils.go +++ b/utils/ui_utils.go @@ -101,7 +101,7 @@ func MustConfirmDialogBox(parent *gtk.Window, msg string, cb func()) func() { ctx, _ := win.GetStyleContext() ctx.AddClass("dialog") - if win.Run() == int(gtk.RESPONSE_YES) { + if win.Run() == gtk.RESPONSE_YES { cb() } } diff --git a/vendor/github.com/StackExchange/wmi/LICENSE b/vendor/github.com/StackExchange/wmi/LICENSE deleted file mode 100644 index ae80b672..00000000 --- a/vendor/github.com/StackExchange/wmi/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Stack Exchange - -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. diff --git a/vendor/github.com/StackExchange/wmi/README.md b/vendor/github.com/StackExchange/wmi/README.md deleted file mode 100644 index 426d1a46..00000000 --- a/vendor/github.com/StackExchange/wmi/README.md +++ /dev/null @@ -1,6 +0,0 @@ -wmi -=== - -Package wmi provides a WQL interface to Windows WMI. - -Note: It interfaces with WMI on the local machine, therefore it only runs on Windows. diff --git a/vendor/github.com/StackExchange/wmi/swbemservices.go b/vendor/github.com/StackExchange/wmi/swbemservices.go deleted file mode 100644 index 9765a53f..00000000 --- a/vendor/github.com/StackExchange/wmi/swbemservices.go +++ /dev/null @@ -1,260 +0,0 @@ -// +build windows - -package wmi - -import ( - "fmt" - "reflect" - "runtime" - "sync" - - "github.com/go-ole/go-ole" - "github.com/go-ole/go-ole/oleutil" -) - -// SWbemServices is used to access wmi. See https://msdn.microsoft.com/en-us/library/aa393719(v=vs.85).aspx -type SWbemServices struct { - //TODO: track namespace. Not sure if we can re connect to a different namespace using the same instance - cWMIClient *Client //This could also be an embedded struct, but then we would need to branch on Client vs SWbemServices in the Query method - sWbemLocatorIUnknown *ole.IUnknown - sWbemLocatorIDispatch *ole.IDispatch - queries chan *queryRequest - closeError chan error - lQueryorClose sync.Mutex -} - -type queryRequest struct { - query string - dst interface{} - args []interface{} - finished chan error -} - -// InitializeSWbemServices will return a new SWbemServices object that can be used to query WMI -func InitializeSWbemServices(c *Client, connectServerArgs ...interface{}) (*SWbemServices, error) { - //fmt.Println("InitializeSWbemServices: Starting") - //TODO: implement connectServerArgs as optional argument for init with connectServer call - s := new(SWbemServices) - s.cWMIClient = c - s.queries = make(chan *queryRequest) - initError := make(chan error) - go s.process(initError) - - err, ok := <-initError - if ok { - return nil, err //Send error to caller - } - //fmt.Println("InitializeSWbemServices: Finished") - return s, nil -} - -// Close will clear and release all of the SWbemServices resources -func (s *SWbemServices) Close() error { - s.lQueryorClose.Lock() - if s == nil || s.sWbemLocatorIDispatch == nil { - s.lQueryorClose.Unlock() - return fmt.Errorf("SWbemServices is not Initialized") - } - if s.queries == nil { - s.lQueryorClose.Unlock() - return fmt.Errorf("SWbemServices has been closed") - } - //fmt.Println("Close: sending close request") - var result error - ce := make(chan error) - s.closeError = ce //Race condition if multiple callers to close. May need to lock here - close(s.queries) //Tell background to shut things down - s.lQueryorClose.Unlock() - err, ok := <-ce - if ok { - result = err - } - //fmt.Println("Close: finished") - return result -} - -func (s *SWbemServices) process(initError chan error) { - //fmt.Println("process: starting background thread initialization") - //All OLE/WMI calls must happen on the same initialized thead, so lock this goroutine - runtime.LockOSThread() - defer runtime.LockOSThread() - - err := ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED) - if err != nil { - oleCode := err.(*ole.OleError).Code() - if oleCode != ole.S_OK && oleCode != S_FALSE { - initError <- fmt.Errorf("ole.CoInitializeEx error: %v", err) - return - } - } - defer ole.CoUninitialize() - - unknown, err := oleutil.CreateObject("WbemScripting.SWbemLocator") - if err != nil { - initError <- fmt.Errorf("CreateObject SWbemLocator error: %v", err) - return - } else if unknown == nil { - initError <- ErrNilCreateObject - return - } - defer unknown.Release() - s.sWbemLocatorIUnknown = unknown - - dispatch, err := s.sWbemLocatorIUnknown.QueryInterface(ole.IID_IDispatch) - if err != nil { - initError <- fmt.Errorf("SWbemLocator QueryInterface error: %v", err) - return - } - defer dispatch.Release() - s.sWbemLocatorIDispatch = dispatch - - // we can't do the ConnectServer call outside the loop unless we find a way to track and re-init the connectServerArgs - //fmt.Println("process: initialized. closing initError") - close(initError) - //fmt.Println("process: waiting for queries") - for q := range s.queries { - //fmt.Printf("process: new query: len(query)=%d\n", len(q.query)) - errQuery := s.queryBackground(q) - //fmt.Println("process: s.queryBackground finished") - if errQuery != nil { - q.finished <- errQuery - } - close(q.finished) - } - //fmt.Println("process: queries channel closed") - s.queries = nil //set channel to nil so we know it is closed - //TODO: I think the Release/Clear calls can panic if things are in a bad state. - //TODO: May need to recover from panics and send error to method caller instead. - close(s.closeError) -} - -// Query runs the WQL query using a SWbemServices instance and appends the values to dst. -// -// dst must have type *[]S or *[]*S, for some struct type S. Fields selected in -// the query must have the same name in dst. Supported types are all signed and -// unsigned integers, time.Time, string, bool, or a pointer to one of those. -// Array types are not supported. -// -// By default, the local machine and default namespace are used. These can be -// changed using connectServerArgs. See -// http://msdn.microsoft.com/en-us/library/aa393720.aspx for details. -func (s *SWbemServices) Query(query string, dst interface{}, connectServerArgs ...interface{}) error { - s.lQueryorClose.Lock() - if s == nil || s.sWbemLocatorIDispatch == nil { - s.lQueryorClose.Unlock() - return fmt.Errorf("SWbemServices is not Initialized") - } - if s.queries == nil { - s.lQueryorClose.Unlock() - return fmt.Errorf("SWbemServices has been closed") - } - - //fmt.Println("Query: Sending query request") - qr := queryRequest{ - query: query, - dst: dst, - args: connectServerArgs, - finished: make(chan error), - } - s.queries <- &qr - s.lQueryorClose.Unlock() - err, ok := <-qr.finished - if ok { - //fmt.Println("Query: Finished with error") - return err //Send error to caller - } - //fmt.Println("Query: Finished") - return nil -} - -func (s *SWbemServices) queryBackground(q *queryRequest) error { - if s == nil || s.sWbemLocatorIDispatch == nil { - return fmt.Errorf("SWbemServices is not Initialized") - } - wmi := s.sWbemLocatorIDispatch //Should just rename in the code, but this will help as we break things apart - //fmt.Println("queryBackground: Starting") - - dv := reflect.ValueOf(q.dst) - if dv.Kind() != reflect.Ptr || dv.IsNil() { - return ErrInvalidEntityType - } - dv = dv.Elem() - mat, elemType := checkMultiArg(dv) - if mat == multiArgTypeInvalid { - return ErrInvalidEntityType - } - - // service is a SWbemServices - serviceRaw, err := oleutil.CallMethod(wmi, "ConnectServer", q.args...) - if err != nil { - return err - } - service := serviceRaw.ToIDispatch() - defer serviceRaw.Clear() - - // result is a SWBemObjectSet - resultRaw, err := oleutil.CallMethod(service, "ExecQuery", q.query) - if err != nil { - return err - } - result := resultRaw.ToIDispatch() - defer resultRaw.Clear() - - count, err := oleInt64(result, "Count") - if err != nil { - return err - } - - enumProperty, err := result.GetProperty("_NewEnum") - if err != nil { - return err - } - defer enumProperty.Clear() - - enum, err := enumProperty.ToIUnknown().IEnumVARIANT(ole.IID_IEnumVariant) - if err != nil { - return err - } - if enum == nil { - return fmt.Errorf("can't get IEnumVARIANT, enum is nil") - } - defer enum.Release() - - // Initialize a slice with Count capacity - dv.Set(reflect.MakeSlice(dv.Type(), 0, int(count))) - - var errFieldMismatch error - for itemRaw, length, err := enum.Next(1); length > 0; itemRaw, length, err = enum.Next(1) { - if err != nil { - return err - } - - err := func() error { - // item is a SWbemObject, but really a Win32_Process - item := itemRaw.ToIDispatch() - defer item.Release() - - ev := reflect.New(elemType) - if err = s.cWMIClient.loadEntity(ev.Interface(), item); err != nil { - if _, ok := err.(*ErrFieldMismatch); ok { - // We continue loading entities even in the face of field mismatch errors. - // If we encounter any other error, that other error is returned. Otherwise, - // an ErrFieldMismatch is returned. - errFieldMismatch = err - } else { - return err - } - } - if mat != multiArgTypeStructPtr { - ev = ev.Elem() - } - dv.Set(reflect.Append(dv, ev)) - return nil - }() - if err != nil { - return err - } - } - //fmt.Println("queryBackground: Finished") - return errFieldMismatch -} diff --git a/vendor/github.com/StackExchange/wmi/swbemservices_test.go b/vendor/github.com/StackExchange/wmi/swbemservices_test.go deleted file mode 100644 index 1d619af4..00000000 --- a/vendor/github.com/StackExchange/wmi/swbemservices_test.go +++ /dev/null @@ -1,151 +0,0 @@ -// +build windows - -package wmi - -import ( - "fmt" - "runtime" - "testing" - "time" -) - -func TestWbemQuery(t *testing.T) { - s, err := InitializeSWbemServices(DefaultClient) - if err != nil { - t.Fatalf("InitializeSWbemServices: %s", err) - } - - var dst []Win32_Process - q := CreateQuery(&dst, "WHERE name='lsass.exe'") - errQuery := s.Query(q, &dst) - if errQuery != nil { - t.Fatalf("Query1: %s", errQuery) - } - count := len(dst) - if count < 1 { - t.Fatal("Query1: no results found for lsass.exe") - } - //fmt.Printf("dst[0].ProcessID=%d\n", dst[0].ProcessId) - - q2 := CreateQuery(&dst, "WHERE name='svchost.exe'") - errQuery = s.Query(q2, &dst) - if errQuery != nil { - t.Fatalf("Query2: %s", errQuery) - } - count = len(dst) - if count < 1 { - t.Fatal("Query2: no results found for svchost.exe") - } - //for index, item := range dst { - // fmt.Printf("dst[%d].ProcessID=%d\n", index, item.ProcessId) - //} - errClose := s.Close() - if errClose != nil { - t.Fatalf("Close: %s", errClose) - } -} - -func TestWbemQueryNamespace(t *testing.T) { - s, err := InitializeSWbemServices(DefaultClient) - if err != nil { - t.Fatalf("InitializeSWbemServices: %s", err) - } - var dst []MSFT_NetAdapter - q := CreateQuery(&dst, "") - errQuery := s.Query(q, &dst, nil, "root\\StandardCimv2") - if errQuery != nil { - t.Fatalf("Query: %s", errQuery) - } - count := len(dst) - if count < 1 { - t.Fatal("Query: no results found for MSFT_NetAdapter in root\\StandardCimv2") - } - errClose := s.Close() - if errClose != nil { - t.Fatalf("Close: %s", errClose) - } -} - -// Run using: go test -run TestWbemMemory -timeout 60m -func TestWbemMemory(t *testing.T) { - s, err := InitializeSWbemServices(DefaultClient) - if err != nil { - t.Fatalf("InitializeSWbemServices: %s", err) - } - start := time.Now() - limit := 500000 - fmt.Printf("Benchmark Iterations: %d (Memory should stabilize around 7MB after ~3000)\n", limit) - var privateMB, allocMB, allocTotalMB float64 - for i := 0; i < limit; i++ { - privateMB, allocMB, allocTotalMB = WbemGetMemoryUsageMB(s) - if i%100 == 0 { - privateMB, allocMB, allocTotalMB = WbemGetMemoryUsageMB(s) - fmt.Printf("Time: %4ds Count: %5d Private Memory: %5.1fMB MemStats.Alloc: %4.1fMB MemStats.TotalAlloc: %5.1fMB\n", time.Now().Sub(start)/time.Second, i, privateMB, allocMB, allocTotalMB) - } - } - errClose := s.Close() - if errClose != nil { - t.Fatalf("Close: %s", err) - } - fmt.Printf("Final Time: %4ds Private Memory: %5.1fMB MemStats.Alloc: %4.1fMB MemStats.TotalAlloc: %5.1fMB\n", time.Now().Sub(start)/time.Second, privateMB, allocMB, allocTotalMB) -} - -func WbemGetMemoryUsageMB(s *SWbemServices) (float64, float64, float64) { - runtime.ReadMemStats(&mMemoryUsageMB) - errGetMemoryUsageMB = s.Query(qGetMemoryUsageMB, &dstGetMemoryUsageMB) - if errGetMemoryUsageMB != nil { - fmt.Println("ERROR GetMemoryUsage", errGetMemoryUsageMB) - return 0, 0, 0 - } - return float64(dstGetMemoryUsageMB[0].WorkingSetPrivate) / MB, float64(mMemoryUsageMB.Alloc) / MB, float64(mMemoryUsageMB.TotalAlloc) / MB -} - -//Run all benchmarks (should run for at least 60s to get a stable number): -//go test -run=NONE -bench=Version -benchtime=120s - -//Individual benchmarks: -//go test -run=NONE -bench=NewVersion -benchtime=120s -func BenchmarkNewVersion(b *testing.B) { - s, err := InitializeSWbemServices(DefaultClient) - if err != nil { - b.Fatalf("InitializeSWbemServices: %s", err) - } - var dst []Win32_OperatingSystem - q := CreateQuery(&dst, "") - for n := 0; n < b.N; n++ { - errQuery := s.Query(q, &dst) - if errQuery != nil { - b.Fatalf("Query%d: %s", n, errQuery) - } - count := len(dst) - if count < 1 { - b.Fatalf("Query%d: no results found for Win32_OperatingSystem", n) - } - } - errClose := s.Close() - if errClose != nil { - b.Fatalf("Close: %s", errClose) - } -} - -//go test -run=NONE -bench=OldVersion -benchtime=120s -func BenchmarkOldVersion(b *testing.B) { - var dst []Win32_OperatingSystem - q := CreateQuery(&dst, "") - for n := 0; n < b.N; n++ { - errQuery := Query(q, &dst) - if errQuery != nil { - b.Fatalf("Query%d: %s", n, errQuery) - } - count := len(dst) - if count < 1 { - b.Fatalf("Query%d: no results found for Win32_OperatingSystem", n) - } - } -} - -type MSFT_NetAdapter struct { - Name string - InterfaceIndex int - DriverDescription string -} diff --git a/vendor/github.com/StackExchange/wmi/wmi.go b/vendor/github.com/StackExchange/wmi/wmi.go deleted file mode 100644 index 9c688b03..00000000 --- a/vendor/github.com/StackExchange/wmi/wmi.go +++ /dev/null @@ -1,468 +0,0 @@ -// +build windows - -/* -Package wmi provides a WQL interface for WMI on Windows. - -Example code to print names of running processes: - - type Win32_Process struct { - Name string - } - - func main() { - var dst []Win32_Process - q := wmi.CreateQuery(&dst, "") - err := wmi.Query(q, &dst) - if err != nil { - log.Fatal(err) - } - for i, v := range dst { - println(i, v.Name) - } - } - -*/ -package wmi - -import ( - "bytes" - "errors" - "fmt" - "log" - "os" - "reflect" - "runtime" - "strconv" - "strings" - "sync" - "time" - - "github.com/go-ole/go-ole" - "github.com/go-ole/go-ole/oleutil" -) - -var l = log.New(os.Stdout, "", log.LstdFlags) - -var ( - ErrInvalidEntityType = errors.New("wmi: invalid entity type") - // ErrNilCreateObject is the error returned if CreateObject returns nil even - // if the error was nil. - ErrNilCreateObject = errors.New("wmi: create object returned nil") - lock sync.Mutex -) - -// S_FALSE is returned by CoInitializeEx if it was already called on this thread. -const S_FALSE = 0x00000001 - -// QueryNamespace invokes Query with the given namespace on the local machine. -func QueryNamespace(query string, dst interface{}, namespace string) error { - return Query(query, dst, nil, namespace) -} - -// Query runs the WQL query and appends the values to dst. -// -// dst must have type *[]S or *[]*S, for some struct type S. Fields selected in -// the query must have the same name in dst. Supported types are all signed and -// unsigned integers, time.Time, string, bool, or a pointer to one of those. -// Array types are not supported. -// -// By default, the local machine and default namespace are used. These can be -// changed using connectServerArgs. See -// http://msdn.microsoft.com/en-us/library/aa393720.aspx for details. -// -// Query is a wrapper around DefaultClient.Query. -func Query(query string, dst interface{}, connectServerArgs ...interface{}) error { - if DefaultClient.SWbemServicesClient == nil { - return DefaultClient.Query(query, dst, connectServerArgs...) - } - return DefaultClient.SWbemServicesClient.Query(query, dst, connectServerArgs...) -} - -// A Client is an WMI query client. -// -// Its zero value (DefaultClient) is a usable client. -type Client struct { - // NonePtrZero specifies if nil values for fields which aren't pointers - // should be returned as the field types zero value. - // - // Setting this to true allows stucts without pointer fields to be used - // without the risk failure should a nil value returned from WMI. - NonePtrZero bool - - // PtrNil specifies if nil values for pointer fields should be returned - // as nil. - // - // Setting this to true will set pointer fields to nil where WMI - // returned nil, otherwise the types zero value will be returned. - PtrNil bool - - // AllowMissingFields specifies that struct fields not present in the - // query result should not result in an error. - // - // Setting this to true allows custom queries to be used with full - // struct definitions instead of having to define multiple structs. - AllowMissingFields bool - - // SWbemServiceClient is an optional SWbemServices object that can be - // initialized and then reused across multiple queries. If it is null - // then the method will initialize a new temporary client each time. - SWbemServicesClient *SWbemServices -} - -// DefaultClient is the default Client and is used by Query, QueryNamespace -var DefaultClient = &Client{} - -// Query runs the WQL query and appends the values to dst. -// -// dst must have type *[]S or *[]*S, for some struct type S. Fields selected in -// the query must have the same name in dst. Supported types are all signed and -// unsigned integers, time.Time, string, bool, or a pointer to one of those. -// Array types are not supported. -// -// By default, the local machine and default namespace are used. These can be -// changed using connectServerArgs. See -// http://msdn.microsoft.com/en-us/library/aa393720.aspx for details. -func (c *Client) Query(query string, dst interface{}, connectServerArgs ...interface{}) error { - dv := reflect.ValueOf(dst) - if dv.Kind() != reflect.Ptr || dv.IsNil() { - return ErrInvalidEntityType - } - dv = dv.Elem() - mat, elemType := checkMultiArg(dv) - if mat == multiArgTypeInvalid { - return ErrInvalidEntityType - } - - lock.Lock() - defer lock.Unlock() - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - err := ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED) - if err != nil { - oleCode := err.(*ole.OleError).Code() - if oleCode != ole.S_OK && oleCode != S_FALSE { - return err - } - } - defer ole.CoUninitialize() - - unknown, err := oleutil.CreateObject("WbemScripting.SWbemLocator") - if err != nil { - return err - } else if unknown == nil { - return ErrNilCreateObject - } - defer unknown.Release() - - wmi, err := unknown.QueryInterface(ole.IID_IDispatch) - if err != nil { - return err - } - defer wmi.Release() - - // service is a SWbemServices - serviceRaw, err := oleutil.CallMethod(wmi, "ConnectServer", connectServerArgs...) - if err != nil { - return err - } - service := serviceRaw.ToIDispatch() - defer serviceRaw.Clear() - - // result is a SWBemObjectSet - resultRaw, err := oleutil.CallMethod(service, "ExecQuery", query) - if err != nil { - return err - } - result := resultRaw.ToIDispatch() - defer resultRaw.Clear() - - count, err := oleInt64(result, "Count") - if err != nil { - return err - } - - enumProperty, err := result.GetProperty("_NewEnum") - if err != nil { - return err - } - defer enumProperty.Clear() - - enum, err := enumProperty.ToIUnknown().IEnumVARIANT(ole.IID_IEnumVariant) - if err != nil { - return err - } - if enum == nil { - return fmt.Errorf("can't get IEnumVARIANT, enum is nil") - } - defer enum.Release() - - // Initialize a slice with Count capacity - dv.Set(reflect.MakeSlice(dv.Type(), 0, int(count))) - - var errFieldMismatch error - for itemRaw, length, err := enum.Next(1); length > 0; itemRaw, length, err = enum.Next(1) { - if err != nil { - return err - } - - err := func() error { - // item is a SWbemObject, but really a Win32_Process - item := itemRaw.ToIDispatch() - defer item.Release() - - ev := reflect.New(elemType) - if err = c.loadEntity(ev.Interface(), item); err != nil { - if _, ok := err.(*ErrFieldMismatch); ok { - // We continue loading entities even in the face of field mismatch errors. - // If we encounter any other error, that other error is returned. Otherwise, - // an ErrFieldMismatch is returned. - errFieldMismatch = err - } else { - return err - } - } - if mat != multiArgTypeStructPtr { - ev = ev.Elem() - } - dv.Set(reflect.Append(dv, ev)) - return nil - }() - if err != nil { - return err - } - } - return errFieldMismatch -} - -// ErrFieldMismatch is returned when a field is to be loaded into a different -// type than the one it was stored from, or when a field is missing or -// unexported in the destination struct. -// StructType is the type of the struct pointed to by the destination argument. -type ErrFieldMismatch struct { - StructType reflect.Type - FieldName string - Reason string -} - -func (e *ErrFieldMismatch) Error() string { - return fmt.Sprintf("wmi: cannot load field %q into a %q: %s", - e.FieldName, e.StructType, e.Reason) -} - -var timeType = reflect.TypeOf(time.Time{}) - -// loadEntity loads a SWbemObject into a struct pointer. -func (c *Client) loadEntity(dst interface{}, src *ole.IDispatch) (errFieldMismatch error) { - v := reflect.ValueOf(dst).Elem() - for i := 0; i < v.NumField(); i++ { - f := v.Field(i) - of := f - isPtr := f.Kind() == reflect.Ptr - if isPtr { - ptr := reflect.New(f.Type().Elem()) - f.Set(ptr) - f = f.Elem() - } - n := v.Type().Field(i).Name - if !f.CanSet() { - return &ErrFieldMismatch{ - StructType: of.Type(), - FieldName: n, - Reason: "CanSet() is false", - } - } - prop, err := oleutil.GetProperty(src, n) - if err != nil { - if !c.AllowMissingFields { - errFieldMismatch = &ErrFieldMismatch{ - StructType: of.Type(), - FieldName: n, - Reason: "no such struct field", - } - } - continue - } - defer prop.Clear() - - switch val := prop.Value().(type) { - case int8, int16, int32, int64, int: - v := reflect.ValueOf(val).Int() - switch f.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - f.SetInt(v) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - f.SetUint(uint64(v)) - default: - return &ErrFieldMismatch{ - StructType: of.Type(), - FieldName: n, - Reason: "not an integer class", - } - } - case uint8, uint16, uint32, uint64: - v := reflect.ValueOf(val).Uint() - switch f.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - f.SetInt(int64(v)) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - f.SetUint(v) - default: - return &ErrFieldMismatch{ - StructType: of.Type(), - FieldName: n, - Reason: "not an integer class", - } - } - case string: - switch f.Kind() { - case reflect.String: - f.SetString(val) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - iv, err := strconv.ParseInt(val, 10, 64) - if err != nil { - return err - } - f.SetInt(iv) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - uv, err := strconv.ParseUint(val, 10, 64) - if err != nil { - return err - } - f.SetUint(uv) - case reflect.Struct: - switch f.Type() { - case timeType: - if len(val) == 25 { - mins, err := strconv.Atoi(val[22:]) - if err != nil { - return err - } - val = val[:22] + fmt.Sprintf("%02d%02d", mins/60, mins%60) - } - t, err := time.Parse("20060102150405.000000-0700", val) - if err != nil { - return err - } - f.Set(reflect.ValueOf(t)) - } - } - case bool: - switch f.Kind() { - case reflect.Bool: - f.SetBool(val) - default: - return &ErrFieldMismatch{ - StructType: of.Type(), - FieldName: n, - Reason: "not a bool", - } - } - case float32: - switch f.Kind() { - case reflect.Float32: - f.SetFloat(float64(val)) - default: - return &ErrFieldMismatch{ - StructType: of.Type(), - FieldName: n, - Reason: "not a Float32", - } - } - default: - // Only support []string slices for now - if f.Kind() == reflect.Slice && f.Type().Elem().Kind() == reflect.String { - safeArray := prop.ToArray() - if safeArray != nil { - arr := safeArray.ToValueArray() - fArr := reflect.MakeSlice(f.Type(), len(arr), len(arr)) - for i, v := range arr { - s := fArr.Index(i) - s.SetString(v.(string)) - } - f.Set(fArr) - break - } - } - - typeof := reflect.TypeOf(val) - if typeof == nil && (isPtr || c.NonePtrZero) { - if (isPtr && c.PtrNil) || (!isPtr && c.NonePtrZero) { - of.Set(reflect.Zero(of.Type())) - } - break - } - return &ErrFieldMismatch{ - StructType: of.Type(), - FieldName: n, - Reason: fmt.Sprintf("unsupported type (%T)", val), - } - } - } - return errFieldMismatch -} - -type multiArgType int - -const ( - multiArgTypeInvalid multiArgType = iota - multiArgTypeStruct - multiArgTypeStructPtr -) - -// checkMultiArg checks that v has type []S, []*S for some struct type S. -// -// It returns what category the slice's elements are, and the reflect.Type -// that represents S. -func checkMultiArg(v reflect.Value) (m multiArgType, elemType reflect.Type) { - if v.Kind() != reflect.Slice { - return multiArgTypeInvalid, nil - } - elemType = v.Type().Elem() - switch elemType.Kind() { - case reflect.Struct: - return multiArgTypeStruct, elemType - case reflect.Ptr: - elemType = elemType.Elem() - if elemType.Kind() == reflect.Struct { - return multiArgTypeStructPtr, elemType - } - } - return multiArgTypeInvalid, nil -} - -func oleInt64(item *ole.IDispatch, prop string) (int64, error) { - v, err := oleutil.GetProperty(item, prop) - if err != nil { - return 0, err - } - defer v.Clear() - - i := int64(v.Val) - return i, nil -} - -// CreateQuery returns a WQL query string that queries all columns of src. where -// is an optional string that is appended to the query, to be used with WHERE -// clauses. In such a case, the "WHERE" string should appear at the beginning. -func CreateQuery(src interface{}, where string) string { - var b bytes.Buffer - b.WriteString("SELECT ") - s := reflect.Indirect(reflect.ValueOf(src)) - t := s.Type() - if s.Kind() == reflect.Slice { - t = t.Elem() - } - if t.Kind() != reflect.Struct { - return "" - } - var fields []string - for i := 0; i < t.NumField(); i++ { - fields = append(fields, t.Field(i).Name) - } - b.WriteString(strings.Join(fields, ", ")) - b.WriteString(" FROM ") - b.WriteString(t.Name()) - b.WriteString(" " + where) - return b.String() -} diff --git a/vendor/github.com/StackExchange/wmi/wmi_test.go b/vendor/github.com/StackExchange/wmi/wmi_test.go deleted file mode 100644 index 32c4dcda..00000000 --- a/vendor/github.com/StackExchange/wmi/wmi_test.go +++ /dev/null @@ -1,544 +0,0 @@ -// +build windows - -package wmi - -import ( - "encoding/json" - "fmt" - "os" - "reflect" - "runtime" - "runtime/debug" - "sync" - "testing" - "time" - - ole "github.com/go-ole/go-ole" - "github.com/go-ole/go-ole/oleutil" -) - -func TestQuery(t *testing.T) { - var dst []Win32_Process - q := CreateQuery(&dst, "") - err := Query(q, &dst) - if err != nil { - t.Fatal(err) - } -} - -func TestFieldMismatch(t *testing.T) { - type s struct { - Name string - HandleCount uint32 - Blah uint32 - } - var dst []s - err := Query("SELECT Name, HandleCount FROM Win32_Process", &dst) - if err == nil || err.Error() != `wmi: cannot load field "Blah" into a "uint32": no such struct field` { - t.Error("Expected err field mismatch") - } -} - -func TestStrings(t *testing.T) { - printed := false - f := func() { - var dst []Win32_Process - zeros := 0 - q := CreateQuery(&dst, "") - for i := 0; i < 5; i++ { - err := Query(q, &dst) - if err != nil { - t.Fatal(err, q) - } - for _, d := range dst { - v := reflect.ValueOf(d) - for j := 0; j < v.NumField(); j++ { - f := v.Field(j) - if f.Kind() != reflect.String { - continue - } - s := f.Interface().(string) - if len(s) > 0 && s[0] == '\u0000' { - zeros++ - if !printed { - printed = true - j, _ := json.MarshalIndent(&d, "", " ") - t.Log("Example with \\u0000:\n", string(j)) - } - } - } - } - fmt.Println("iter", i, "zeros:", zeros) - } - if zeros > 0 { - t.Error("> 0 zeros") - } - } - - fmt.Println("Disabling GC") - debug.SetGCPercent(-1) - f() - fmt.Println("Enabling GC") - debug.SetGCPercent(100) - f() -} - -func TestNamespace(t *testing.T) { - var dst []Win32_Process - q := CreateQuery(&dst, "") - err := QueryNamespace(q, &dst, `root\CIMV2`) - if err != nil { - t.Fatal(err) - } - dst = nil - err = QueryNamespace(q, &dst, `broken\nothing`) - if err == nil { - t.Fatal("expected error") - } -} - -func TestCreateQuery(t *testing.T) { - type TestStruct struct { - Name string - Count int - } - var dst []TestStruct - output := "SELECT Name, Count FROM TestStruct WHERE Count > 2" - tests := []interface{}{ - &dst, - dst, - TestStruct{}, - &TestStruct{}, - } - for i, test := range tests { - if o := CreateQuery(test, "WHERE Count > 2"); o != output { - t.Error("bad output on", i, o) - } - } - if CreateQuery(3, "") != "" { - t.Error("expected empty string") - } -} - -// Run using: go test -run TestMemoryWMISimple -timeout 60m -func _TestMemoryWMISimple(t *testing.T) { - start := time.Now() - limit := 500000 - fmt.Printf("Benchmark Iterations: %d (Memory should stabilize around 7MB after ~3000)\n", limit) - var privateMB, allocMB, allocTotalMB float64 - //var dst []Win32_PerfRawData_PerfDisk_LogicalDisk - //q := CreateQuery(&dst, "") - for i := 0; i < limit; i++ { - privateMB, allocMB, allocTotalMB = GetMemoryUsageMB() - if i%1000 == 0 { - //privateMB, allocMB, allocTotalMB = GetMemoryUsageMB() - fmt.Printf("Time: %4ds Count: %5d Private Memory: %5.1fMB MemStats.Alloc: %4.1fMB MemStats.TotalAlloc: %5.1fMB\n", time.Now().Sub(start)/time.Second, i, privateMB, allocMB, allocTotalMB) - } - //Query(q, &dst) - } - //privateMB, allocMB, allocTotalMB = GetMemoryUsageMB() - fmt.Printf("Final Time: %4ds Private Memory: %5.1fMB MemStats.Alloc: %4.1fMB MemStats.TotalAlloc: %5.1fMB\n", time.Now().Sub(start)/time.Second, privateMB, allocMB, allocTotalMB) -} - -func _TestMemoryWMIConcurrent(t *testing.T) { - if testing.Short() { - return - } - start := time.Now() - limit := 50000 - fmt.Println("Total Iterations:", limit) - fmt.Println("No panics mean it succeeded. Other errors are OK. Memory should stabilize after ~1500 iterations.") - runtime.GOMAXPROCS(2) - wg := sync.WaitGroup{} - wg.Add(2) - go func() { - for i := 0; i < limit; i++ { - if i%500 == 0 { - privateMB, allocMB, allocTotalMB := GetMemoryUsageMB() - fmt.Printf("Time: %4ds Count: %4d Private Memory: %5.1fMB MemStats.Alloc: %4.1fMB MemStats.TotalAlloc: %5.1fMB\n", time.Now().Sub(start)/time.Second, i, privateMB, allocMB, allocTotalMB) - } - var dst []Win32_PerfRawData_PerfDisk_LogicalDisk - q := CreateQuery(&dst, "") - err := Query(q, &dst) - if err != nil { - fmt.Println("ERROR disk", err) - } - } - wg.Done() - }() - go func() { - for i := 0; i > -limit; i-- { - //if i%500 == 0 { - // fmt.Println(i) - //} - var dst []Win32_OperatingSystem - q := CreateQuery(&dst, "") - err := Query(q, &dst) - if err != nil { - fmt.Println("ERROR OS", err) - } - } - wg.Done() - }() - wg.Wait() - //privateMB, allocMB, allocTotalMB := GetMemoryUsageMB() - //fmt.Printf("Final Private Memory: %5.1fMB MemStats.Alloc: %4.1fMB MemStats.TotalAlloc: %5.1fMB\n", privateMB, allocMB, allocTotalMB) -} - -var lockthread sync.Mutex -var refcount1 int32 -var refcount2 int32 -var refcount3 int32 - -// Test function showing memory leak in unknown.QueryInterface call on Server2016/Windows10 -func getRSS(url string, xmlhttp *ole.IDispatch, MinimalTest bool) (int, error) { - - // call using url,nil to see memory leak - if xmlhttp == nil { - //Initialize inside loop if not passed in from outer section - lockthread.Lock() - defer lockthread.Unlock() - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - err := ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED) - if err != nil { - oleCode := err.(*ole.OleError).Code() - if oleCode != ole.S_OK && oleCode != S_FALSE { - return 0, err - } - } - defer ole.CoUninitialize() - - //fmt.Println("CreateObject Microsoft.XMLHTTP") - unknown, err := oleutil.CreateObject("Microsoft.XMLHTTP") - if err != nil { - return 0, err - } - defer func() { refcount1 += xmlhttp.Release() }() - - //Memory leak occurs here - xmlhttp, err = unknown.QueryInterface(ole.IID_IDispatch) - if err != nil { - return 0, err - } - defer func() { refcount2 += xmlhttp.Release() }() - //Nothing below this really matters. Can be removed if you want a tighter loop - } - - //fmt.Printf("Download %s\n", url) - openRaw, err := oleutil.CallMethod(xmlhttp, "open", "GET", url, false) - if err != nil { - return 0, err - } - defer openRaw.Clear() - - if MinimalTest { - return 1, nil - } - - //Initiate http request - sendRaw, err := oleutil.CallMethod(xmlhttp, "send", nil) - if err != nil { - return 0, err - } - defer sendRaw.Clear() - state := -1 // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState - for state != 4 { - time.Sleep(5 * time.Millisecond) - stateRaw := oleutil.MustGetProperty(xmlhttp, "readyState") - state = int(stateRaw.Val) - stateRaw.Clear() - } - - responseXMLRaw := oleutil.MustGetProperty(xmlhttp, "responseXml") - responseXML := responseXMLRaw.ToIDispatch() - defer responseXMLRaw.Clear() - itemsRaw := oleutil.MustCallMethod(responseXML, "selectNodes", "/rdf:RDF/item") - items := itemsRaw.ToIDispatch() - defer itemsRaw.Clear() - lengthRaw := oleutil.MustGetProperty(items, "length") - defer lengthRaw.Clear() - length := int(lengthRaw.Val) - - /* This just bloats the TotalAlloc and slows the test down. Doesn't effect Private Working Set - for n := 0; n < length; n++ { - itemRaw := oleutil.MustGetProperty(items, "item", n) - item := itemRaw.ToIDispatch() - title := oleutil.MustCallMethod(item, "selectSingleNode", "title").ToIDispatch() - - //fmt.Println(oleutil.MustGetProperty(title, "text").ToString()) - textRaw := oleutil.MustGetProperty(title, "text") - textRaw.ToString() - - link := oleutil.MustCallMethod(item, "selectSingleNode", "link").ToIDispatch() - //fmt.Println(" " + oleutil.MustGetProperty(link, "text").ToString()) - textRaw2 := oleutil.MustGetProperty(link, "text") - textRaw2.ToString() - - textRaw2.Clear() - link.Release() - textRaw.Clear() - title.Release() - itemRaw.Clear() - } - */ - return length, nil -} - -// Testing go-ole/oleutil -// Run using: go test -run TestMemoryOLE -timeout 60m -// Code from https://github.com/go-ole/go-ole/blob/master/example/msxml/rssreader.go -func _TestMemoryOLE(t *testing.T) { - defer func() { - if r := recover(); r != nil { - t.Error(r) - } - }() - - start := time.Now() - limit := 50000000 - url := "http://localhost/slashdot.xml" //http://rss.slashdot.org/Slashdot/slashdot" - fmt.Printf("Benchmark Iterations: %d (Memory should stabilize around 8MB to 12MB after ~2k full or 250k minimal)\n", limit) - - //On Server 2016 or Windows 10 changing leakMemory=true will cause it to leak ~1.5MB per 10000 calls to unknown.QueryInterface - leakMemory := true - - //////////////////////////////////////// - //Start outer section - var unknown *ole.IUnknown - var xmlhttp *ole.IDispatch - if !leakMemory { - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - err := ole.CoInitializeEx(0, ole.COINIT_MULTITHREADED) - if err != nil { - oleCode := err.(*ole.OleError).Code() - if oleCode != ole.S_OK && oleCode != S_FALSE { - t.Fatal(err) - } - } - defer ole.CoUninitialize() - - //fmt.Println("CreateObject Microsoft.XMLHTTP") - unknown, err = oleutil.CreateObject("Microsoft.XMLHTTP") - if err != nil { - t.Fatal(err) - } - defer unknown.Release() - - //Memory leak starts here - xmlhttp, err = unknown.QueryInterface(ole.IID_IDispatch) - if err != nil { - t.Fatal(err) - } - defer xmlhttp.Release() - } - //End outer section - //////////////////////////////////////// - - totalItems := uint64(0) - for i := 0; i < limit; i++ { - if i%2000 == 0 { - privateMB, allocMB, allocTotalMB := GetMemoryUsageMB() - fmt.Printf("Time: %4ds Count: %7d Private Memory: %5.1fMB MemStats.Alloc: %4.1fMB MemStats.TotalAlloc: %5.1fMB %7d/%7d\n", time.Now().Sub(start)/time.Second, i, privateMB, allocMB, allocTotalMB, refcount1, refcount2) - } - //This should use less than 10MB for 1 million iterations if xmlhttp was initialized above - //On Server 2016 or Windows 10 changing leakMemory=true above will cause it to leak ~1.5MB per 10000 calls to unknown.QueryInterface - count, err := getRSS(url, xmlhttp, true) //last argument is for Minimal test. Doesn't effect leak just overall allocations/time - if err != nil { - t.Fatal(err) - } - totalItems += uint64(count) - } - privateMB, allocMB, allocTotalMB := GetMemoryUsageMB() - fmt.Printf("Final totalItems: %d Private Memory: %5.1fMB MemStats.Alloc: %4.1fMB MemStats.TotalAlloc: %5.1fMB\n", totalItems, privateMB, allocMB, allocTotalMB) -} - -const MB = 1024 * 1024 - -var ( - mMemoryUsageMB runtime.MemStats - errGetMemoryUsageMB error - dstGetMemoryUsageMB []Win32_PerfRawData_PerfProc_Process - filterProcessID = fmt.Sprintf("WHERE IDProcess = %d", os.Getpid()) - qGetMemoryUsageMB = CreateQuery(&dstGetMemoryUsageMB, filterProcessID) -) - -func GetMemoryUsageMB() (float64, float64, float64) { - runtime.ReadMemStats(&mMemoryUsageMB) - //errGetMemoryUsageMB = nil //Query(qGetMemoryUsageMB, &dstGetMemoryUsageMB) float64(dstGetMemoryUsageMB[0].WorkingSetPrivate) - errGetMemoryUsageMB = Query(qGetMemoryUsageMB, &dstGetMemoryUsageMB) - if errGetMemoryUsageMB != nil { - fmt.Println("ERROR GetMemoryUsage", errGetMemoryUsageMB) - return 0, 0, 0 - } - return float64(dstGetMemoryUsageMB[0].WorkingSetPrivate) / MB, float64(mMemoryUsageMB.Alloc) / MB, float64(mMemoryUsageMB.TotalAlloc) / MB -} - -type Win32_PerfRawData_PerfProc_Process struct { - IDProcess uint32 - WorkingSetPrivate uint64 -} - -type Win32_Process struct { - CSCreationClassName string - CSName string - Caption *string - CommandLine *string - CreationClassName string - CreationDate *time.Time - Description *string - ExecutablePath *string - ExecutionState *uint16 - Handle string - HandleCount uint32 - InstallDate *time.Time - KernelModeTime uint64 - MaximumWorkingSetSize *uint32 - MinimumWorkingSetSize *uint32 - Name string - OSCreationClassName string - OSName string - OtherOperationCount uint64 - OtherTransferCount uint64 - PageFaults uint32 - PageFileUsage uint32 - ParentProcessId uint32 - PeakPageFileUsage uint32 - PeakVirtualSize uint64 - PeakWorkingSetSize uint32 - Priority uint32 - PrivatePageCount uint64 - ProcessId uint32 - QuotaNonPagedPoolUsage uint32 - QuotaPagedPoolUsage uint32 - QuotaPeakNonPagedPoolUsage uint32 - QuotaPeakPagedPoolUsage uint32 - ReadOperationCount uint64 - ReadTransferCount uint64 - SessionId uint32 - Status *string - TerminationDate *time.Time - ThreadCount uint32 - UserModeTime uint64 - VirtualSize uint64 - WindowsVersion string - WorkingSetSize uint64 - WriteOperationCount uint64 - WriteTransferCount uint64 -} - -type Win32_PerfRawData_PerfDisk_LogicalDisk struct { - AvgDiskBytesPerRead uint64 - AvgDiskBytesPerRead_Base uint32 - AvgDiskBytesPerTransfer uint64 - AvgDiskBytesPerTransfer_Base uint32 - AvgDiskBytesPerWrite uint64 - AvgDiskBytesPerWrite_Base uint32 - AvgDiskQueueLength uint64 - AvgDiskReadQueueLength uint64 - AvgDiskSecPerRead uint32 - AvgDiskSecPerRead_Base uint32 - AvgDiskSecPerTransfer uint32 - AvgDiskSecPerTransfer_Base uint32 - AvgDiskSecPerWrite uint32 - AvgDiskSecPerWrite_Base uint32 - AvgDiskWriteQueueLength uint64 - Caption *string - CurrentDiskQueueLength uint32 - Description *string - DiskBytesPerSec uint64 - DiskReadBytesPerSec uint64 - DiskReadsPerSec uint32 - DiskTransfersPerSec uint32 - DiskWriteBytesPerSec uint64 - DiskWritesPerSec uint32 - FreeMegabytes uint32 - Frequency_Object uint64 - Frequency_PerfTime uint64 - Frequency_Sys100NS uint64 - Name string - PercentDiskReadTime uint64 - PercentDiskReadTime_Base uint64 - PercentDiskTime uint64 - PercentDiskTime_Base uint64 - PercentDiskWriteTime uint64 - PercentDiskWriteTime_Base uint64 - PercentFreeSpace uint32 - PercentFreeSpace_Base uint32 - PercentIdleTime uint64 - PercentIdleTime_Base uint64 - SplitIOPerSec uint32 - Timestamp_Object uint64 - Timestamp_PerfTime uint64 - Timestamp_Sys100NS uint64 -} - -type Win32_OperatingSystem struct { - BootDevice string - BuildNumber string - BuildType string - Caption *string - CodeSet string - CountryCode string - CreationClassName string - CSCreationClassName string - CSDVersion *string - CSName string - CurrentTimeZone int16 - DataExecutionPrevention_Available bool - DataExecutionPrevention_32BitApplications bool - DataExecutionPrevention_Drivers bool - DataExecutionPrevention_SupportPolicy *uint8 - Debug bool - Description *string - Distributed bool - EncryptionLevel uint32 - ForegroundApplicationBoost *uint8 - FreePhysicalMemory uint64 - FreeSpaceInPagingFiles uint64 - FreeVirtualMemory uint64 - InstallDate time.Time - LargeSystemCache *uint32 - LastBootUpTime time.Time - LocalDateTime time.Time - Locale string - Manufacturer string - MaxNumberOfProcesses uint32 - MaxProcessMemorySize uint64 - MUILanguages *[]string - Name string - NumberOfLicensedUsers *uint32 - NumberOfProcesses uint32 - NumberOfUsers uint32 - OperatingSystemSKU uint32 - Organization string - OSArchitecture string - OSLanguage uint32 - OSProductSuite uint32 - OSType uint16 - OtherTypeDescription *string - PAEEnabled *bool - PlusProductID *string - PlusVersionNumber *string - PortableOperatingSystem bool - Primary bool - ProductType uint32 - RegisteredUser string - SerialNumber string - ServicePackMajorVersion uint16 - ServicePackMinorVersion uint16 - SizeStoredInPagingFiles uint64 - Status string - SuiteMask uint32 - SystemDevice string - SystemDirectory string - SystemDrive string - TotalSwapSpaceSize *uint64 - TotalVirtualMemorySize uint64 - TotalVisibleMemorySize uint64 - Version string - WindowsDirectory string -} diff --git a/vendor/github.com/coreos/go-systemd/.travis.yml b/vendor/github.com/coreos/go-systemd/.travis.yml deleted file mode 100644 index cfea999c..00000000 --- a/vendor/github.com/coreos/go-systemd/.travis.yml +++ /dev/null @@ -1,45 +0,0 @@ -dist: trusty -sudo: required -services: - - docker - -language: go -go: - - "1.10.x" - - "1.11.x" -go_import_path: github.com/coreos/go-systemd - -env: - global: - - IMPORTPATH=github.com/coreos/go-systemd - - GOPATH=/opt - - DEP_BINDIR=/tmp - - BUILD_DIR=/opt/src/github.com/coreos/go-systemd - matrix: - - DOCKER_BASE=ubuntu:16.04 - - DOCKER_BASE=ubuntu:18.04 - - DOCKER_BASE=debian:stretch - -before_install: - - sudo apt-get -qq update - - sudo apt-get install -y libsystemd-journal-dev libsystemd-daemon-dev - - curl https://raw.githubusercontent.com/golang/dep/master/install.sh | INSTALL_DIRECTORY=${DEP_BINDIR} sh - - ${DEP_BINDIR}/dep ensure -v - - docker pull ${DOCKER_BASE} - - docker run --privileged -e GOPATH=${GOPATH} --cidfile=/tmp/cidfile ${DOCKER_BASE} /bin/bash -c "apt-get update && apt-get install -y sudo build-essential git golang dbus libsystemd-dev libpam-systemd systemd-container" - - docker commit `cat /tmp/cidfile` go-systemd/container-tests - - rm -f /tmp/cidfile - -install: - - docker run --shm-size=2gb -d --cidfile=/tmp/cidfile --privileged -e GOPATH=${GOPATH} -v ${PWD}:${BUILD_DIR} go-systemd/container-tests /bin/systemd --system - -script: - - ./scripts/travis/pr-test.sh go_fmt - - ./scripts/travis/pr-test.sh build_source - - ./scripts/travis/pr-test.sh build_tests - - docker exec --privileged `cat /tmp/cidfile` /bin/bash -c "cd ${BUILD_DIR} && ./scripts/travis/pr-test.sh run_tests" - - ./scripts/travis/pr-test.sh go_vet - - ./scripts/travis/pr-test.sh license_check - -after_script: - - docker kill `cat /tmp/cidfile` diff --git a/vendor/github.com/coreos/go-systemd/CONTRIBUTING.md b/vendor/github.com/coreos/go-systemd/CONTRIBUTING.md deleted file mode 100644 index 0551ed53..00000000 --- a/vendor/github.com/coreos/go-systemd/CONTRIBUTING.md +++ /dev/null @@ -1,77 +0,0 @@ -# How to Contribute - -CoreOS projects are [Apache 2.0 licensed](LICENSE) and accept contributions via -GitHub pull requests. This document outlines some of the conventions on -development workflow, commit message formatting, contact points and other -resources to make it easier to get your contribution accepted. - -# Certificate of Origin - -By contributing to this project you agree to the Developer Certificate of -Origin (DCO). This document was created by the Linux Kernel community and is a -simple statement that you, as a contributor, have the legal right to make the -contribution. See the [DCO](DCO) file for details. - -# Email and Chat - -The project currently uses the general CoreOS email list and IRC channel: -- Email: [coreos-dev](https://groups.google.com/forum/#!forum/coreos-dev) -- IRC: #[coreos](irc://irc.freenode.org:6667/#coreos) IRC channel on freenode.org - -Please avoid emailing maintainers found in the MAINTAINERS file directly. They -are very busy and read the mailing lists. - -## Getting Started - -- Fork the repository on GitHub -- Read the [README](README.md) for build and test instructions -- Play with the project, submit bugs, submit patches! - -## Contribution Flow - -This is a rough outline of what a contributor's workflow looks like: - -- Create a topic branch from where you want to base your work (usually master). -- Make commits of logical units. -- Make sure your commit messages are in the proper format (see below). -- Push your changes to a topic branch in your fork of the repository. -- Make sure the tests pass, and add any new tests as appropriate. -- Submit a pull request to the original repository. - -Thanks for your contributions! - -### Coding Style - -CoreOS projects written in Go follow a set of style guidelines that we've documented -[here](https://github.com/coreos/docs/tree/master/golang). Please follow them when -working on your contributions. - -### Format of the Commit Message - -We follow a rough convention for commit messages that is designed to answer two -questions: what changed and why. The subject line should feature the what and -the body of the commit should describe the why. - -``` -scripts: add the test-cluster command - -this uses tmux to setup a test cluster that you can easily kill and -start for debugging. - -Fixes #38 -``` - -The format can be described more formally as follows: - -``` -: - - - -