fix(windows-build): Remove free space check for archives (#4485)

This commit is contained in:
Boris Melnik 2023-12-20 21:21:02 +03:00 committed by GitHub
parent b6f2aced08
commit 6d77fb771a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 285 additions and 110 deletions

6
go.mod
View File

@ -103,7 +103,6 @@ require (
github.com/BurntSushi/toml v1.2.1 // indirect github.com/BurntSushi/toml v1.2.1 // indirect
github.com/PuerkitoBio/goquery v1.6.1 // indirect github.com/PuerkitoBio/goquery v1.6.1 // indirect
github.com/RoaringBitmap/roaring v0.9.4 // indirect github.com/RoaringBitmap/roaring v0.9.4 // indirect
github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46 // indirect
github.com/VictoriaMetrics/fastcache v1.6.0 // indirect github.com/VictoriaMetrics/fastcache v1.6.0 // indirect
github.com/anacrolix/chansync v0.3.0 // indirect github.com/anacrolix/chansync v0.3.0 // indirect
github.com/anacrolix/confluence v1.9.0 // indirect github.com/anacrolix/confluence v1.9.0 // indirect
@ -146,7 +145,7 @@ require (
github.com/flynn/noise v1.0.0 // indirect github.com/flynn/noise v1.0.0 // indirect
github.com/francoispqt/gojay v1.2.13 // indirect github.com/francoispqt/gojay v1.2.13 // indirect
github.com/gballet/go-libpcsclite v0.0.0-20191108122812-4678299bea08 // indirect github.com/gballet/go-libpcsclite v0.0.0-20191108122812-4678299bea08 // indirect
github.com/go-ole/go-ole v1.2.5 // indirect github.com/go-ole/go-ole v1.2.6 // indirect
github.com/go-playground/locales v0.14.0 // indirect github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-stack/stack v1.8.1 // indirect github.com/go-stack/stack v1.8.1 // indirect
@ -248,7 +247,7 @@ require (
github.com/russolsen/ohyeah v0.0.0-20160324131710-f4938c005315 // indirect github.com/russolsen/ohyeah v0.0.0-20160324131710-f4938c005315 // indirect
github.com/russolsen/same v0.0.0-20160222130632-f089df61f51d // indirect github.com/russolsen/same v0.0.0-20160222130632-f089df61f51d // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/shirou/gopsutil v3.21.5+incompatible // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect
github.com/shopspring/decimal v1.2.0 // indirect github.com/shopspring/decimal v1.2.0 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/status-im/go-multiaddr-ethv4 v1.2.5 // indirect github.com/status-im/go-multiaddr-ethv4 v1.2.5 // indirect
@ -269,6 +268,7 @@ require (
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
github.com/yeqown/reedsolomon v1.0.0 // indirect github.com/yeqown/reedsolomon v1.0.0 // indirect
github.com/yusufpapurcu/wmi v1.2.3 // indirect
go.etcd.io/bbolt v1.3.6 // indirect go.etcd.io/bbolt v1.3.6 // indirect
go.uber.org/atomic v1.11.0 // indirect go.uber.org/atomic v1.11.0 // indirect
go.uber.org/dig v1.17.0 // indirect go.uber.org/dig v1.17.0 // indirect

9
go.sum
View File

@ -158,7 +158,6 @@ github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d/go.mod h1:H
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46 h1:5sXbqlSomvdjlRbWyNqkPsJ3Fg+tQZCbgeX1VGljbQY=
github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
github.com/VictoriaMetrics/fastcache v1.6.0 h1:C/3Oi3EiBCqufydp1neRZkqcwmEiuRT9c3fqvvgKm5o= github.com/VictoriaMetrics/fastcache v1.6.0 h1:C/3Oi3EiBCqufydp1neRZkqcwmEiuRT9c3fqvvgKm5o=
github.com/VictoriaMetrics/fastcache v1.6.0/go.mod h1:0qHz5QP0GMX4pfmMA/zt5RgfNuXJrTP0zS7DqpHGGTw= github.com/VictoriaMetrics/fastcache v1.6.0/go.mod h1:0qHz5QP0GMX4pfmMA/zt5RgfNuXJrTP0zS7DqpHGGTw=
@ -828,8 +827,9 @@ github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ=
github.com/go-logr/stdr v1.2.0/go.mod h1:YkVgnZu1ZjjL7xTxrfm/LLZBfkhTqSR1ydtm6jTKKwI= github.com/go-logr/stdr v1.2.0/go.mod h1:YkVgnZu1ZjjL7xTxrfm/LLZBfkhTqSR1ydtm6jTKKwI=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8=
github.com/go-ole/go-ole v1.2.5 h1:t4MGB5xEDZvXI+0rMjjsfBsD7yAgp/s9ZDkL1JndXwY=
github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0= github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0=
github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg= github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg=
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
@ -1901,8 +1901,9 @@ github.com/segmentio/kafka-go v0.1.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfP
github.com/segmentio/kafka-go v0.2.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= github.com/segmentio/kafka-go v0.2.0/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/shirou/gopsutil v3.21.5+incompatible h1:OloQyEerMi7JUrXiNzy8wQ5XN+baemxSl12QgIzt0jc=
github.com/shirou/gopsutil v3.21.5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shirou/gopsutil v3.21.5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
github.com/shopspring/decimal v0.0.0-20200227202807-02e2044944cc/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shopspring/decimal v0.0.0-20200227202807-02e2044944cc/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
@ -2153,6 +2154,8 @@ github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw=
github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
github.com/yvasiyarov/go-metrics v0.0.0-20140926110328-57bccd1ccd43/go.mod h1:aX5oPXxHm3bOH+xeAttToC8pqch2ScQN/JoXYupl6xs= github.com/yvasiyarov/go-metrics v0.0.0-20140926110328-57bccd1ccd43/go.mod h1:aX5oPXxHm3bOH+xeAttToC8pqch2ScQN/JoXYupl6xs=
github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50/go.mod h1:NUSPSUX/bi6SeDMUh6brw0nXpxHnc96TguQh0+r/ssA= github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50/go.mod h1:NUSPSUX/bi6SeDMUh6brw0nXpxHnc96TguQh0+r/ssA=
github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f/go.mod h1:GlGEuHIJweS1mbCqG+7vt2nvWLzLLnRHbXz5JKd/Qbg= github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f/go.mod h1:GlGEuHIJweS1mbCqG+7vt2nvWLzLLnRHbXz5JKd/Qbg=

View File

@ -11,7 +11,6 @@ import (
"sort" "sort"
"strings" "strings"
"sync" "sync"
"syscall"
"time" "time"
"github.com/anacrolix/torrent" "github.com/anacrolix/torrent"
@ -3984,21 +3983,6 @@ func (m *Manager) SeedHistoryArchiveTorrent(communityID types.HexBytes) error {
return err return err
} }
var stat syscall.Statfs_t
wd, _ := os.Getwd()
err = syscall.Statfs(wd, &stat)
if err != nil {
return err
}
// Available blocks * size per block = available space in bytes
freeSpace := stat.Bavail * uint64(stat.Bsize)
if freeSpace <= uint64(torrent.Length()) {
return ErrNoFreeSpaceForHistoryArchives
}
torrent.DownloadAll() torrent.DownloadAll()
m.publish(&Subscription{ m.publish(&Subscription{

View File

@ -185,7 +185,9 @@ func invoke(disp *IDispatch, dispid int32, dispatch int16, params ...interface{}
uintptr(unsafe.Pointer(&excepInfo)), uintptr(unsafe.Pointer(&excepInfo)),
0) 0)
if hr != 0 { if hr != 0 {
err = NewErrorWithSubError(hr, BstrToString(excepInfo.bstrDescription), excepInfo) excepInfo.renderStrings()
excepInfo.Clear()
err = NewErrorWithSubError(hr, excepInfo.description, excepInfo)
} }
for i, varg := range vargs { for i, varg := range vargs {
n := len(params) - i - 1 n := len(params) - i - 1

View File

@ -3,6 +3,7 @@ package ole
import ( import (
"fmt" "fmt"
"strings" "strings"
"unsafe"
) )
// DISPPARAMS are the arguments that passed to methods or property. // DISPPARAMS are the arguments that passed to methods or property.
@ -24,6 +25,56 @@ type EXCEPINFO struct {
pvReserved uintptr pvReserved uintptr
pfnDeferredFillIn uintptr pfnDeferredFillIn uintptr
scode uint32 scode uint32
// Go-specific part. Don't move upper cos it'll break structure layout for native code.
rendered bool
source string
description string
helpFile string
}
// renderStrings translates BSTR strings to Go ones so `.Error` and `.String`
// could be safely called after `.Clear`. We need this when we can't rely on
// a caller to call `.Clear`.
func (e *EXCEPINFO) renderStrings() {
e.rendered = true
if e.bstrSource == nil {
e.source = "<nil>"
} else {
e.source = BstrToString(e.bstrSource)
}
if e.bstrDescription == nil {
e.description = "<nil>"
} else {
e.description = BstrToString(e.bstrDescription)
}
if e.bstrHelpFile == nil {
e.helpFile = "<nil>"
} else {
e.helpFile = BstrToString(e.bstrHelpFile)
}
}
// Clear frees BSTR strings inside an EXCEPINFO and set it to NULL.
func (e *EXCEPINFO) Clear() {
freeBSTR := func(s *uint16) {
// SysFreeString don't return errors and is safe for call's on NULL.
// https://docs.microsoft.com/en-us/windows/win32/api/oleauto/nf-oleauto-sysfreestring
_ = SysFreeString((*int16)(unsafe.Pointer(s)))
}
if e.bstrSource != nil {
freeBSTR(e.bstrSource)
e.bstrSource = nil
}
if e.bstrDescription != nil {
freeBSTR(e.bstrDescription)
e.bstrDescription = nil
}
if e.bstrHelpFile != nil {
freeBSTR(e.bstrHelpFile)
e.bstrHelpFile = nil
}
} }
// WCode return wCode in EXCEPINFO. // WCode return wCode in EXCEPINFO.
@ -38,48 +89,30 @@ func (e EXCEPINFO) SCODE() uint32 {
// String convert EXCEPINFO to string. // String convert EXCEPINFO to string.
func (e EXCEPINFO) String() string { func (e EXCEPINFO) String() string {
var src, desc, hlp string if !e.rendered {
if e.bstrSource == nil { e.renderStrings()
src = "<nil>"
} else {
src = BstrToString(e.bstrSource)
} }
if e.bstrDescription == nil {
desc = "<nil>"
} else {
desc = BstrToString(e.bstrDescription)
}
if e.bstrHelpFile == nil {
hlp = "<nil>"
} else {
hlp = BstrToString(e.bstrHelpFile)
}
return fmt.Sprintf( return fmt.Sprintf(
"wCode: %#x, bstrSource: %v, bstrDescription: %v, bstrHelpFile: %v, dwHelpContext: %#x, scode: %#x", "wCode: %#x, bstrSource: %v, bstrDescription: %v, bstrHelpFile: %v, dwHelpContext: %#x, scode: %#x",
e.wCode, src, desc, hlp, e.dwHelpContext, e.scode, e.wCode, e.source, e.description, e.helpFile, e.dwHelpContext, e.scode,
) )
} }
// Error implements error interface and returns error string. // Error implements error interface and returns error string.
func (e EXCEPINFO) Error() string { func (e EXCEPINFO) Error() string {
if e.bstrDescription != nil { if !e.rendered {
return strings.TrimSpace(BstrToString(e.bstrDescription)) e.renderStrings()
} }
src := "Unknown" if e.description != "<nil>" {
if e.bstrSource != nil { return strings.TrimSpace(e.description)
src = BstrToString(e.bstrSource)
} }
code := e.scode code := e.scode
if e.wCode != 0 { if e.wCode != 0 {
code = uint32(e.wCode) code = uint32(e.wCode)
} }
return fmt.Sprintf("%v: %#x", e.source, code)
return fmt.Sprintf("%v: %#x", src, code)
} }
// PARAMDATA defines parameter data type. // PARAMDATA defines parameter data type.

View File

@ -84,13 +84,13 @@ func (sac *SafeArrayConversion) ToValueArray() (values []interface{}) {
safeArrayGetElement(sac.Array, i, unsafe.Pointer(&v)) safeArrayGetElement(sac.Array, i, unsafe.Pointer(&v))
values[i] = v values[i] = v
case VT_BSTR: case VT_BSTR:
var v string v , _ := safeArrayGetElementString(sac.Array, i)
safeArrayGetElement(sac.Array, i, unsafe.Pointer(&v))
values[i] = v values[i] = v
case VT_VARIANT: case VT_VARIANT:
var v VARIANT var v VARIANT
safeArrayGetElement(sac.Array, i, unsafe.Pointer(&v)) safeArrayGetElement(sac.Array, i, unsafe.Pointer(&v))
values[i] = v.Value() values[i] = v.Value()
v.Clear()
default: default:
// TODO // TODO
} }

11
vendor/github.com/go-ole/go-ole/variant_arm.go generated vendored Normal file
View File

@ -0,0 +1,11 @@
// +build arm
package ole
type VARIANT struct {
VT VT // 2
wReserved1 uint16 // 4
wReserved2 uint16 // 6
wReserved3 uint16 // 8
Val int64 // 16
}

13
vendor/github.com/go-ole/go-ole/variant_arm64.go generated vendored Normal file
View File

@ -0,0 +1,13 @@
//go:build arm64
// +build arm64
package ole
type VARIANT struct {
VT VT // 2
wReserved1 uint16 // 4
wReserved2 uint16 // 6
wReserved3 uint16 // 8
Val int64 // 16
_ [8]byte // 24
}

22
vendor/github.com/go-ole/go-ole/variant_date_arm.go generated vendored Normal file
View File

@ -0,0 +1,22 @@
// +build windows,arm
package ole
import (
"errors"
"syscall"
"time"
"unsafe"
)
// GetVariantDate converts COM Variant Time value to Go time.Time.
func GetVariantDate(value uint64) (time.Time, error) {
var st syscall.Systemtime
v1 := uint32(value)
v2 := uint32(value >> 32)
r, _, _ := procVariantTimeToSystemTime.Call(uintptr(v1), uintptr(v2), uintptr(unsafe.Pointer(&st)))
if r != 0 {
return time.Date(int(st.Year), time.Month(st.Month), int(st.Day), int(st.Hour), int(st.Minute), int(st.Second), int(st.Milliseconds/1000), time.UTC), nil
}
return time.Now(), errors.New("Could not convert to time, passing current time.")
}

23
vendor/github.com/go-ole/go-ole/variant_date_arm64.go generated vendored Normal file
View File

@ -0,0 +1,23 @@
//go:build windows && arm64
// +build windows,arm64
package ole
import (
"errors"
"syscall"
"time"
"unsafe"
)
// GetVariantDate converts COM Variant Time value to Go time.Time.
func GetVariantDate(value uint64) (time.Time, error) {
var st syscall.Systemtime
v1 := uint32(value)
v2 := uint32(value >> 32)
r, _, _ := procVariantTimeToSystemTime.Call(uintptr(v1), uintptr(v2), uintptr(unsafe.Pointer(&st)))
if r != 0 {
return time.Date(int(st.Year), time.Month(st.Month), int(st.Day), int(st.Hour), int(st.Minute), int(st.Second), int(st.Milliseconds/1000), time.UTC), nil
}
return time.Now(), errors.New("Could not convert to time, passing current time.")
}

View File

@ -5,9 +5,10 @@ package cpu
import ( import (
"context" "context"
"fmt" "fmt"
"strings"
"unsafe" "unsafe"
"github.com/StackExchange/wmi" "github.com/yusufpapurcu/wmi"
"github.com/shirou/gopsutil/internal/common" "github.com/shirou/gopsutil/internal/common"
"golang.org/x/sys/windows" "golang.org/x/sys/windows"
) )
@ -18,7 +19,14 @@ var (
) )
type Win32_Processor struct { type Win32_Processor struct {
LoadPercentage *uint16 Win32_ProcessorWithoutLoadPct
LoadPercentage *uint16
}
// LoadPercentage takes a linearly more time as the number of sockets increases.
// For vSphere by default corespersocket = 1, meaning for a 40 vCPU VM Get Processor Info
// could take more than half a minute.
type Win32_ProcessorWithoutLoadPct struct {
Family uint16 Family uint16
Manufacturer string Manufacturer string
Name string Name string
@ -104,8 +112,9 @@ func Info() ([]InfoStat, error) {
func InfoWithContext(ctx context.Context) ([]InfoStat, error) { func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
var ret []InfoStat var ret []InfoStat
var dst []Win32_Processor var dst []Win32_ProcessorWithoutLoadPct
q := wmi.CreateQuery(&dst, "") q := wmi.CreateQuery(&dst, "")
q = strings.ReplaceAll(q, "Win32_ProcessorWithoutLoadPct", "Win32_Processor")
if err := common.WMIQueryWithContext(ctx, q, &dst); err != nil { if err := common.WMIQueryWithContext(ctx, q, &dst); err != nil {
return ret, err return ret, err
} }
@ -242,8 +251,9 @@ func CountsWithContext(ctx context.Context, logical bool) (int, error) {
} }
// physical cores https://github.com/giampaolo/psutil/blob/d01a9eaa35a8aadf6c519839e987a49d8be2d891/psutil/_psutil_windows.c#L499 // physical cores https://github.com/giampaolo/psutil/blob/d01a9eaa35a8aadf6c519839e987a49d8be2d891/psutil/_psutil_windows.c#L499
// for the time being, try with unreliable and slow WMI call… // for the time being, try with unreliable and slow WMI call…
var dst []Win32_Processor var dst []Win32_ProcessorWithoutLoadPct
q := wmi.CreateQuery(&dst, "") q := wmi.CreateQuery(&dst, "")
q = strings.ReplaceAll(q, "Win32_ProcessorWithoutLoadPct", "Win32_Processor")
if err := common.WMIQueryWithContext(ctx, q, &dst); err != nil { if err := common.WMIQueryWithContext(ctx, q, &dst); err != nil {
return 0, err return 0, err
} }

View File

@ -253,7 +253,7 @@ func Write(w io.Writer, order ByteOrder, data interface{}) error {
b[0] = *v b[0] = *v
case uint8: case uint8:
bs = b[:1] bs = b[:1]
b[0] = byte(v) b[0] = v
case []uint8: case []uint8:
bs = v bs = v
case *int16: case *int16:

View File

@ -94,7 +94,7 @@ func (i FakeInvoke) CommandWithContext(ctx context.Context, name string, arg ...
var ErrNotImplementedError = errors.New("not implemented yet") var ErrNotImplementedError = errors.New("not implemented yet")
// ReadFile reads contents from a file // ReadFile reads contents from a file.
func ReadFile(filename string) (string, error) { func ReadFile(filename string) (string, error) {
content, err := ioutil.ReadFile(filename) content, err := ioutil.ReadFile(filename)
@ -111,7 +111,7 @@ func ReadLines(filename string) ([]string, error) {
return ReadLinesOffsetN(filename, 0, -1) return ReadLinesOffsetN(filename, 0, -1)
} }
// ReadLines reads contents from file and splits them by new line. // ReadLinesOffsetN reads contents from file and splits them by new line.
// The offset tells at which line number to start. // The offset tells at which line number to start.
// The count determines the number of lines to read (starting from offset): // The count determines the number of lines to read (starting from offset):
// n >= 0: at most n lines // n >= 0: at most n lines
@ -165,7 +165,7 @@ func UintToString(orig []uint8) string {
size = i size = i
break break
} }
ret[i] = byte(o) ret[i] = o
} }
if size == -1 { if size == -1 {
size = len(orig) size = len(orig)
@ -224,31 +224,31 @@ func ReadInts(filename string) ([]int64, error) {
return ret, nil return ret, nil
} }
// Parse Hex to uint32 without error // HexToUint32 parses Hex to uint32 without error.
func HexToUint32(hex string) uint32 { func HexToUint32(hex string) uint32 {
vv, _ := strconv.ParseUint(hex, 16, 32) vv, _ := strconv.ParseUint(hex, 16, 32)
return uint32(vv) return uint32(vv)
} }
// Parse to int32 without error // mustParseInt32 parses to int32 without error.
func mustParseInt32(val string) int32 { func mustParseInt32(val string) int32 {
vv, _ := strconv.ParseInt(val, 10, 32) vv, _ := strconv.ParseInt(val, 10, 32)
return int32(vv) return int32(vv)
} }
// Parse to uint64 without error // mustParseUint64 parses to uint64 without error.
func mustParseUint64(val string) uint64 { func mustParseUint64(val string) uint64 {
vv, _ := strconv.ParseInt(val, 10, 64) vv, _ := strconv.ParseInt(val, 10, 64)
return uint64(vv) return uint64(vv)
} }
// Parse to Float64 without error // mustParseFloat64 parses to Float64 without error.
func mustParseFloat64(val string) float64 { func mustParseFloat64(val string) float64 {
vv, _ := strconv.ParseFloat(val, 64) vv, _ := strconv.ParseFloat(val, 64)
return vv return vv
} }
// StringsHas checks the target string slice contains src or not // StringsHas checks the target string slice contains src or not.
func StringsHas(target []string, src string) bool { func StringsHas(target []string, src string) bool {
for _, t := range target { for _, t := range target {
if strings.TrimSpace(t) == src { if strings.TrimSpace(t) == src {
@ -258,7 +258,7 @@ func StringsHas(target []string, src string) bool {
return false return false
} }
// StringsContains checks the src in any string of the target string slice // StringsContains checks the src in any string of the target string slice.
func StringsContains(target []string, src string) bool { func StringsContains(target []string, src string) bool {
for _, t := range target { for _, t := range target {
if strings.Contains(t, src) { if strings.Contains(t, src) {
@ -308,7 +308,7 @@ func PathExists(filename string) bool {
return false return false
} }
//GetEnv retrieves the environment variable key. If it does not exist it returns the default. // GetEnv retrieves the environment variable key. If it does not exist it returns the default.
func GetEnv(key string, dfault string, combineWith ...string) string { func GetEnv(key string, dfault string, combineWith ...string) string {
value := os.Getenv(key) value := os.Getenv(key)
if value == "" { if value == "" {

View File

@ -26,8 +26,8 @@ func DoSysctrl(mib string) ([]string, error) {
return []string{}, err return []string{}, err
} }
v := strings.Replace(string(out), "{ ", "", 1) v := strings.Replace(string(out), "{ ", "", 1)
v = strings.Replace(string(v), " }", "", 1) v = strings.Replace(v, " }", "", 1)
values := strings.Fields(string(v)) values := strings.Fields(v)
return values, nil return values, nil
} }
@ -55,7 +55,6 @@ func NumProcs() (uint64, error) {
} }
func BootTimeWithContext(ctx context.Context) (uint64, error) { func BootTimeWithContext(ctx context.Context) (uint64, error) {
system, role, err := Virtualization() system, role, err := Virtualization()
if err != nil { if err != nil {
return 0, err return 0, err
@ -76,6 +75,18 @@ func BootTimeWithContext(ctx context.Context) (uint64, error) {
return 0, err return 0, err
} }
if statFile == "uptime" {
if len(lines) != 1 {
return 0, fmt.Errorf("wrong uptime format")
}
f := strings.Fields(lines[0])
b, err := strconv.ParseFloat(f[0], 64)
if err != nil {
return 0, err
}
t := uint64(time.Now().Unix()) - uint64(b)
return t, nil
}
if statFile == "stat" { if statFile == "stat" {
for _, line := range lines { for _, line := range lines {
if strings.HasPrefix(line, "btime") { if strings.HasPrefix(line, "btime") {
@ -91,17 +102,6 @@ func BootTimeWithContext(ctx context.Context) (uint64, error) {
return t, nil return t, nil
} }
} }
} else if statFile == "uptime" {
if len(lines) != 1 {
return 0, fmt.Errorf("wrong uptime format")
}
f := strings.Fields(lines[0])
b, err := strconv.ParseFloat(f[0], 64)
if err != nil {
return 0, err
}
t := uint64(time.Now().Unix()) - uint64(b)
return t, nil
} }
return 0, fmt.Errorf("could not find btime") return 0, fmt.Errorf("could not find btime")
@ -111,7 +111,7 @@ func Virtualization() (string, string, error) {
return VirtualizationWithContext(context.Background()) return VirtualizationWithContext(context.Background())
} }
// required variables for concurrency safe virtualization caching // required variables for concurrency safe virtualization caching.
var ( var (
cachedVirtMap map[string]string cachedVirtMap map[string]string
cachedVirtMutex sync.RWMutex cachedVirtMutex sync.RWMutex
@ -137,10 +137,8 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filepath.Join(filename, "capabilities")) { if PathExists(filepath.Join(filename, "capabilities")) {
contents, err := ReadLines(filepath.Join(filename, "capabilities")) contents, err := ReadLines(filepath.Join(filename, "capabilities"))
if err == nil { if err == nil && StringsContains(contents, "control_d") {
if StringsContains(contents, "control_d") { role = "host"
role = "host"
}
} }
} }
} }
@ -149,16 +147,17 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filename) { if PathExists(filename) {
contents, err := ReadLines(filename) contents, err := ReadLines(filename)
if err == nil { if err == nil {
if StringsContains(contents, "kvm") { switch {
case StringsContains(contents, "kvm"):
system = "kvm" system = "kvm"
role = "host" role = "host"
} else if StringsContains(contents, "vboxdrv") { case StringsContains(contents, "vboxdrv"):
system = "vbox" system = "vbox"
role = "host" role = "host"
} else if StringsContains(contents, "vboxguest") { case StringsContains(contents, "vboxguest"):
system = "vbox" system = "vbox"
role = "guest" role = "guest"
} else if StringsContains(contents, "vmware") { case StringsContains(contents, "vmware"):
system = "vmware" system = "vmware"
role = "guest" role = "guest"
} }
@ -201,7 +200,6 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filepath.Join(filename, "self", "status")) { if PathExists(filepath.Join(filename, "self", "status")) {
contents, err := ReadLines(filepath.Join(filename, "self", "status")) contents, err := ReadLines(filepath.Join(filename, "self", "status"))
if err == nil { if err == nil {
if StringsContains(contents, "s_context:") || if StringsContains(contents, "s_context:") ||
StringsContains(contents, "VxID:") { StringsContains(contents, "VxID:") {
system = "linux-vserver" system = "linux-vserver"
@ -224,16 +222,17 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filepath.Join(filename, "self", "cgroup")) { if PathExists(filepath.Join(filename, "self", "cgroup")) {
contents, err := ReadLines(filepath.Join(filename, "self", "cgroup")) contents, err := ReadLines(filepath.Join(filename, "self", "cgroup"))
if err == nil { if err == nil {
if StringsContains(contents, "lxc") { switch {
case StringsContains(contents, "lxc"):
system = "lxc" system = "lxc"
role = "guest" role = "guest"
} else if StringsContains(contents, "docker") { case StringsContains(contents, "docker"):
system = "docker" system = "docker"
role = "guest" role = "guest"
} else if StringsContains(contents, "machine-rkt") { case StringsContains(contents, "machine-rkt"):
system = "rkt" system = "rkt"
role = "guest" role = "guest"
} else if PathExists("/usr/bin/lxc-version") { case PathExists("/usr/bin/lxc-version"):
system = "lxc" system = "lxc"
role = "host" role = "host"
} }
@ -281,7 +280,7 @@ func GetOSRelease() (platform string, version string, err error) {
return platform, version, nil return platform, version, nil
} }
// Remove quotes of the source string // trimQuotes removes quotes in the source string.
func trimQuotes(s string) string { func trimQuotes(s string) string {
if len(s) >= 2 { if len(s) >= 2 {
if s[0] == '"' && s[len(s)-1] == '"' { if s[0] == '"' && s[len(s)-1] == '"' {

View File

@ -41,8 +41,7 @@ func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args ..
} }
func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int32, error) { func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int32, error) {
var cmd []string cmd := []string{"-P", strconv.Itoa(int(pid))}
cmd = []string{"-P", strconv.Itoa(int(pid))}
pgrep, err := exec.LookPath("pgrep") pgrep, err := exec.LookPath("pgrep")
if err != nil { if err != nil {
return []int32{}, err return []int32{}, err

View File

@ -6,11 +6,12 @@ import (
"context" "context"
"fmt" "fmt"
"path/filepath" "path/filepath"
"reflect"
"strings" "strings"
"syscall" "syscall"
"unsafe" "unsafe"
"github.com/StackExchange/wmi" "github.com/yusufpapurcu/wmi"
"golang.org/x/sys/windows" "golang.org/x/sys/windows"
) )
@ -48,11 +49,18 @@ const (
PDH_INVALID_DATA = 0xc0000bc6 PDH_INVALID_DATA = 0xc0000bc6
PDH_INVALID_HANDLE = 0xC0000bbc PDH_INVALID_HANDLE = 0xC0000bbc
PDH_NO_DATA = 0x800007d5 PDH_NO_DATA = 0x800007d5
STATUS_BUFFER_OVERFLOW = 0x80000005
STATUS_BUFFER_TOO_SMALL = 0xC0000023
STATUS_INFO_LENGTH_MISMATCH = 0xC0000004
) )
const ( const (
ProcessBasicInformation = 0 ProcessBasicInformation = 0
ProcessWow64Information = 26 ProcessWow64Information = 26
ProcessQueryInformation = windows.PROCESS_DUP_HANDLE | windows.PROCESS_QUERY_INFORMATION
SystemExtendedHandleInformationClass = 64
) )
var ( var (
@ -227,3 +235,66 @@ func ConvertDOSPath(p string) string {
} }
return p return p
} }
type NtStatus uint32
func (s NtStatus) Error() error {
if s == 0 {
return nil
}
return fmt.Errorf("NtStatus 0x%08x", uint32(s))
}
func (s NtStatus) IsError() bool {
return s>>30 == 3
}
type SystemExtendedHandleTableEntryInformation struct {
Object uintptr
UniqueProcessId uintptr
HandleValue uintptr
GrantedAccess uint32
CreatorBackTraceIndex uint16
ObjectTypeIndex uint16
HandleAttributes uint32
Reserved uint32
}
type SystemExtendedHandleInformation struct {
NumberOfHandles uintptr
Reserved uintptr
Handles [1]SystemExtendedHandleTableEntryInformation
}
// CallWithExpandingBuffer https://github.com/hillu/go-ntdll
func CallWithExpandingBuffer(fn func() NtStatus, buf *[]byte, resultLength *uint32) NtStatus {
for {
if st := fn(); st == STATUS_BUFFER_OVERFLOW || st == STATUS_BUFFER_TOO_SMALL || st == STATUS_INFO_LENGTH_MISMATCH {
if int(*resultLength) <= cap(*buf) {
(*reflect.SliceHeader)(unsafe.Pointer(buf)).Len = int(*resultLength)
} else {
*buf = make([]byte, int(*resultLength))
}
continue
} else {
if !st.IsError() {
*buf = (*buf)[:int(*resultLength)]
}
return st
}
}
}
func NtQuerySystemInformation(
SystemInformationClass uint32,
SystemInformation *byte,
SystemInformationLength uint32,
ReturnLength *uint32,
) NtStatus {
r0, _, _ := ProcNtQuerySystemInformation.Call(
uintptr(SystemInformationClass),
uintptr(unsafe.Pointer(SystemInformation)),
uintptr(SystemInformationLength),
uintptr(unsafe.Pointer(ReturnLength)))
return NtStatus(r0)
}

View File

@ -1,3 +1,4 @@
//go:build windows
// +build windows // +build windows
package wmi package wmi

View File

@ -1,3 +1,4 @@
//go:build windows
// +build windows // +build windows
/* /*
@ -20,7 +21,6 @@ Example code to print names of running processes:
println(i, v.Name) println(i, v.Name)
} }
} }
*/ */
package wmi package wmi
@ -338,12 +338,10 @@ func (c *Client) loadEntity(dst interface{}, src *ole.IDispatch) (errFieldMismat
f := v.Field(i) f := v.Field(i)
of := f of := f
isPtr := f.Kind() == reflect.Ptr 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 n := v.Type().Field(i).Name
if n[0] < 'A' || n[0] > 'Z' {
continue
}
if !f.CanSet() { if !f.CanSet() {
return &ErrFieldMismatch{ return &ErrFieldMismatch{
StructType: of.Type(), StructType: of.Type(),
@ -364,6 +362,12 @@ func (c *Client) loadEntity(dst interface{}, src *ole.IDispatch) (errFieldMismat
} }
defer prop.Clear() defer prop.Clear()
if isPtr && !(c.PtrNil && prop.VT == 0x1) {
ptr := reflect.New(f.Type().Elem())
f.Set(ptr)
f = f.Elem()
}
if prop.VT == 0x1 { //VT_NULL if prop.VT == 0x1 { //VT_NULL
continue continue
} }
@ -577,7 +581,7 @@ func CreateQuery(src interface{}, where string, class ...string) string {
} }
b.WriteString(strings.Join(fields, ", ")) b.WriteString(strings.Join(fields, ", "))
b.WriteString(" FROM ") b.WriteString(" FROM ")
if len(class) > 0{ if len(class) > 0 {
b.WriteString(class[0]) b.WriteString(class[0])
} else { } else {
b.WriteString(t.Name()) b.WriteString(t.Name())

10
vendor/modules.txt vendored
View File

@ -10,9 +10,6 @@ github.com/PuerkitoBio/goquery
github.com/RoaringBitmap/roaring github.com/RoaringBitmap/roaring
github.com/RoaringBitmap/roaring/BitSliceIndexing github.com/RoaringBitmap/roaring/BitSliceIndexing
github.com/RoaringBitmap/roaring/internal github.com/RoaringBitmap/roaring/internal
# github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46
## explicit
github.com/StackExchange/wmi
# github.com/VictoriaMetrics/fastcache v1.6.0 # github.com/VictoriaMetrics/fastcache v1.6.0
## explicit; go 1.13 ## explicit; go 1.13
github.com/VictoriaMetrics/fastcache github.com/VictoriaMetrics/fastcache
@ -298,7 +295,7 @@ github.com/francoispqt/gojay
# github.com/gballet/go-libpcsclite v0.0.0-20191108122812-4678299bea08 # github.com/gballet/go-libpcsclite v0.0.0-20191108122812-4678299bea08
## explicit ## explicit
github.com/gballet/go-libpcsclite github.com/gballet/go-libpcsclite
# github.com/go-ole/go-ole v1.2.5 # github.com/go-ole/go-ole v1.2.6
## explicit; go 1.12 ## explicit; go 1.12
github.com/go-ole/go-ole github.com/go-ole/go-ole
github.com/go-ole/go-ole/oleutil github.com/go-ole/go-ole/oleutil
@ -893,7 +890,7 @@ github.com/russross/blackfriday/v2
# github.com/schollz/peerdiscovery v1.7.0 # github.com/schollz/peerdiscovery v1.7.0
## explicit; go 1.13 ## explicit; go 1.13
github.com/schollz/peerdiscovery github.com/schollz/peerdiscovery
# github.com/shirou/gopsutil v3.21.5+incompatible # github.com/shirou/gopsutil v3.21.11+incompatible
## explicit ## explicit
github.com/shirou/gopsutil/cpu github.com/shirou/gopsutil/cpu
github.com/shirou/gopsutil/internal/common github.com/shirou/gopsutil/internal/common
@ -1123,6 +1120,9 @@ github.com/yeqown/go-qrcode/writer/standard/imgkit
## explicit ## explicit
github.com/yeqown/reedsolomon github.com/yeqown/reedsolomon
github.com/yeqown/reedsolomon/binary github.com/yeqown/reedsolomon/binary
# github.com/yusufpapurcu/wmi v1.2.3
## explicit; go 1.16
github.com/yusufpapurcu/wmi
# github.com/zenthangplus/goccm v0.0.0-20211005163543-2f2e522aca15 # github.com/zenthangplus/goccm v0.0.0-20211005163543-2f2e522aca15
## explicit; go 1.14 ## explicit; go 1.14
github.com/zenthangplus/goccm github.com/zenthangplus/goccm