Compare commits

...
Author SHA1 Message Date
Roman Perekhod a6e857f4ea fix: [draft] fix the default roles assigment 2026-09-14 10:04:19 +02:00
238 changed files with 7635 additions and 13862 deletions

No files matched your search

+29 -32
View File
@@ -1,6 +1,6 @@
module github.com/owncloud/ocis/v2
go 1.26
go 1.26.0
require (
dario.cat/mergo v1.0.2
@@ -10,11 +10,11 @@ require (
github.com/MicahParks/keyfunc/v2 v2.1.0
github.com/Nerzal/gocloak/v13 v13.9.0
github.com/bbalet/stopwords v1.0.0
github.com/beevik/etree v1.7.0
github.com/beevik/etree v1.7.1
github.com/blevesearch/bleve/v2 v2.6.0
github.com/cenkalti/backoff v2.2.1+incompatible
github.com/cenkalti/backoff/v5 v5.0.3
github.com/coreos/go-oidc/v3 v3.20.0
github.com/coreos/go-oidc/v3 v3.21.0
github.com/cs3org/go-cs3apis v0.0.0-20241105092511-3ad35d174fc1
github.com/davidbyttow/govips/v2 v2.18.0
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
@@ -22,7 +22,7 @@ require (
github.com/egirna/icap-client v0.1.1
github.com/gabriel-vasile/mimetype v1.4.15
github.com/ggwhite/go-masker v1.1.0
github.com/go-chi/chi/v5 v5.3.1
github.com/go-chi/chi/v5 v5.3.2
github.com/go-chi/httprate v0.16.0
github.com/go-chi/render v1.0.3
github.com/go-ldap/ldap/v3 v3.4.14
@@ -35,7 +35,7 @@ require (
github.com/go-micro/plugins/v4/store/nats-js-kv v0.0.0-20240726082623-6831adfdcdc4
github.com/go-micro/plugins/v4/wrapper/monitoring/prometheus v1.2.0
github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry v1.2.0
github.com/go-playground/validator/v10 v10.30.3
github.com/go-playground/validator/v10 v10.30.4
github.com/gofrs/uuid v4.4.0+incompatible
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/golang/protobuf v1.5.4
@@ -58,16 +58,16 @@ require (
github.com/mitchellh/mapstructure v1.5.0
github.com/mna/pigeon v1.3.0
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826
github.com/nats-io/nats-server/v2 v2.14.5
github.com/nats-io/nats-server/v2 v2.14.6
github.com/nats-io/nats.go v1.53.1
github.com/olekukonko/tablewriter v1.1.4
github.com/onsi/ginkgo v1.16.5
github.com/onsi/ginkgo/v2 v2.32.1
github.com/onsi/gomega v1.42.1
github.com/onsi/gomega v1.43.0
github.com/open-policy-agent/opa v1.19.0
github.com/orcaman/concurrent-map v1.0.0
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
github.com/owncloud/reva/v2 v2.0.0-20260813121157-d386075a0421
github.com/owncloud/reva/v2 v2.0.0-20260911153821-68e8cf7deba4
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.24.1
@@ -75,11 +75,11 @@ require (
github.com/rogpeppe/go-internal v1.16.0
github.com/rs/cors v1.11.1
github.com/rs/zerolog v1.35.1
github.com/shamaton/msgpack/v2 v2.4.1
github.com/shamaton/msgpack/v2 v2.4.2
github.com/sirupsen/logrus v1.10.0
github.com/spf13/afero v1.15.0
github.com/spf13/cobra v1.10.2
github.com/stretchr/testify v1.11.1
github.com/stretchr/testify v1.12.1
github.com/test-go/testify v1.1.4
github.com/thejerf/suture/v4 v4.0.6
github.com/tidwall/gjson v1.19.0
@@ -89,15 +89,15 @@ require (
github.com/xhit/go-simple-mail/v2 v2.16.0
go-micro.dev/v4 v4.11.0
go.etcd.io/bbolt v1.5.0
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0
go.opentelemetry.io/contrib/zpages v0.70.0
go.opentelemetry.io/otel v1.45.0
go.opentelemetry.io/otel v1.46.0
go.opentelemetry.io/otel/exporters/jaeger v1.17.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0
go.opentelemetry.io/otel/sdk v1.45.0
go.opentelemetry.io/otel/trace v1.45.0
golang.org/x/crypto v0.55.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0
go.opentelemetry.io/otel/sdk v1.46.0
go.opentelemetry.io/otel/trace v1.46.0
golang.org/x/crypto v0.56.0
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
golang.org/x/image v0.45.0
golang.org/x/net v0.58.0
@@ -105,7 +105,7 @@ require (
golang.org/x/sync v0.22.0
golang.org/x/term v0.45.0
golang.org/x/text v0.41.0
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d
google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688
google.golang.org/grpc v1.83.2
google.golang.org/protobuf v1.36.12
gopkg.in/yaml.v2 v2.4.0
@@ -155,7 +155,7 @@ require (
github.com/blevesearch/zapx/v17 v17.1.2 // indirect
github.com/bluele/gcache v0.0.2 // indirect
github.com/bombsimon/logrusr/v3 v3.1.0 // indirect
github.com/ceph/go-ceph v0.40.0 // indirect
github.com/ceph/go-ceph v0.41.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cevaris/ordered_map v0.0.0-20190319150403-3adeae072e73 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
@@ -168,7 +168,6 @@ require (
github.com/crewjam/httperr v0.2.0 // indirect
github.com/crewjam/saml v0.4.14 // indirect
github.com/cyphar/filepath-securejoin v0.6.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/deckarep/golang-set v1.8.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 // indirect
github.com/desertbit/timer v1.0.1 // indirect
@@ -203,7 +202,7 @@ require (
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-redis/redis/v8 v8.11.5 // indirect
github.com/go-resty/resty/v2 v2.17.2 // indirect
github.com/go-sql-driver/mysql v1.10.0 // indirect
github.com/go-sql-driver/mysql v1.10.1 // indirect
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
github.com/go-test/deep v1.1.0 // indirect
@@ -214,7 +213,7 @@ require (
github.com/gobwas/ws v1.2.1 // indirect
github.com/goccy/go-json v0.10.6 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/gofrs/flock v0.13.0 // indirect
github.com/gofrs/flock v0.13.1 // indirect
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/golang/snappy v1.0.0 // indirect
@@ -240,11 +239,11 @@ require (
github.com/juliangruber/go-intersect v1.1.0 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/klauspost/compress v1.19.2 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
github.com/klauspost/crc32 v1.3.0 // indirect
github.com/kovidgoyal/go-parallel v1.1.1 // indirect
github.com/kovidgoyal/go-shm v1.0.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/lestrrat-go/blackmagic v1.0.4 // indirect
github.com/lestrrat-go/dsig v1.2.1 // indirect
github.com/lestrrat-go/dsig-secp256k1 v1.0.0 // indirect
@@ -259,7 +258,7 @@ require (
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.21 // indirect
github.com/mattn/go-runewidth v0.0.23 // indirect
github.com/mattn/go-sqlite3 v1.14.49 // indirect
github.com/mattn/go-sqlite3 v1.14.50 // indirect
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b // indirect
github.com/mendsley/gojwk v0.0.0-20141217222730-4d5ec6e58103 // indirect
github.com/miekg/dns v1.1.72 // indirect
@@ -267,7 +266,7 @@ require (
github.com/minio/crc64nvme v1.1.1 // indirect
github.com/minio/highwayhash v1.0.4 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/minio/minio-go/v7 v7.2.1 // indirect
github.com/minio/minio-go/v7 v7.3.0 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
@@ -290,9 +289,8 @@ require (
github.com/philhofer/fwd v1.2.0 // indirect
github.com/pierrec/lz4/v4 v4.1.26 // indirect
github.com/pjbgf/sha1cd v0.6.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/pquerna/cachecontrol v0.2.0 // indirect
github.com/prometheus/alertmanager v0.33.1 // indirect
github.com/prometheus/alertmanager v0.34.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.70.1 // indirect
github.com/prometheus/procfs v0.21.1 // indirect
@@ -316,7 +314,7 @@ require (
github.com/tchap/go-patricia/v2 v2.3.3 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tinylib/msgp v1.6.1 // indirect
github.com/tinylib/msgp v1.6.4 // indirect
github.com/toorop/go-dkim v0.0.0-20201103131630-e1cd1a0a5208 // indirect
github.com/trustelem/zxcvbn v1.0.1 // indirect
github.com/valyala/fastjson v1.6.10 // indirect
@@ -333,8 +331,8 @@ require (
go.etcd.io/etcd/client/v3 v3.7.1 // indirect
go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 // indirect
go.opentelemetry.io/otel/metric v1.45.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect
go.opentelemetry.io/otel/metric v1.46.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.1 // indirect
@@ -345,12 +343,11 @@ require (
golang.org/x/time v0.15.0 // indirect
golang.org/x/tools v0.49.0 // indirect
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
gopkg.in/ini.v1 v1.67.3 // indirect
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
sigs.k8s.io/yaml v1.6.0 // indirect
)
+60 -59
View File
@@ -104,8 +104,8 @@ github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
github.com/bbalet/stopwords v1.0.0 h1:0TnGycCtY0zZi4ltKoOGRFIlZHv0WqpoIGUsObjztfo=
github.com/bbalet/stopwords v1.0.0/go.mod h1:sAWrQoDMfqARGIn4s6dp7OW7ISrshUD8IP2q3KoqPjc=
github.com/beevik/etree v1.7.0 h1:xjBk9O4p4x7D1YajePjfLzdaFC4/uYUENA7P0pv6gXA=
github.com/beevik/etree v1.7.0/go.mod h1:bh4zJxiIr62SOf9pRzN7UUYaEDa9HEKafK25+sLc0Gc=
github.com/beevik/etree v1.7.1 h1:xBlSFAjlMfZkrCNKCEdZ2MSN9pfQYeRBaISDnAVi4Ek=
github.com/beevik/etree v1.7.1/go.mod h1:bh4zJxiIr62SOf9pRzN7UUYaEDa9HEKafK25+sLc0Gc=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
@@ -167,8 +167,8 @@ github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QH
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/ceph/go-ceph v0.40.0 h1:Wz9WOX6i73Hz74mpwhTO9S6IyX3eFPv88VUc7FRMPRk=
github.com/ceph/go-ceph v0.40.0/go.mod h1:1oFtT/x/4y+teLsNiogdd/Kj81Gmrw6JM5w1bWnZoc4=
github.com/ceph/go-ceph v0.41.0 h1:uATh5+zR1KWOQCoBYj4uEfuAPsSccajOGXWW8u8UTgA=
github.com/ceph/go-ceph v0.41.0/go.mod h1:8tvljRxQ65aEtRt7aCxzuPpN7tiwPHCPPSuAqQ5teCY=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
@@ -186,8 +186,8 @@ github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJ
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/coreos/go-oidc/v3 v3.20.0 h1:EtE0WIBHk03N+DqGkY4+UONzzZHk7amKt6IyNd7OsZE=
github.com/coreos/go-oidc/v3 v3.20.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4=
github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec=
github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA=
@@ -286,8 +286,8 @@ github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkPro
github.com/go-asn1-ber/asn1-ber v1.4.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ=
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-chi/httprate v0.16.0 h1:8V5DH9j6pSK6UQoBsTpvMyFxycqaKEIToyPKzHJjUa8=
github.com/go-chi/httprate v0.16.0/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
@@ -359,14 +359,14 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8=
github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc=
github.com/go-playground/validator/v10 v10.30.4 h1:9Rcod2ZPO6mOEG6b4GqyoHE/H6//Ze0RuhOo1hT1x0w=
github.com/go-playground/validator/v10 v10.30.4/go.mod h1:numpT+RPLE91R9oYWMY/R9zRgJBewr3IXHko4OISPpk=
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI=
@@ -389,12 +389,12 @@ github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU=
github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw=
github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0=
github.com/gofrs/flock v0.13.1 h1:jjREztyBeSKBZYAC+mgc1laB+xsgy4kYMf3FbKF2UBo=
github.com/gofrs/flock v0.13.1/go.mod h1:sf4BFiHwnvgxa25DlQoDqXQnwRMEOwqxRq37P6MzzmE=
github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA=
github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
github.com/gofrs/uuid/v5 v5.4.0 h1:EfbpCTjqMuGyq5ZJwxqzn3Cbr2d0rUZU7v5ycAk/e/0=
github.com/gofrs/uuid/v5 v5.4.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/gofrs/uuid/v5 v5.5.0 h1:FkPv6jYQRbZtH3bD8yC7106u+CedTCLF8+t7CLHSZNo=
github.com/gofrs/uuid/v5 v5.5.0/go.mod h1:bbAA98EoIlxyRHIVg6ektCSsZ5n8mSbwgEhvhMYlZgg=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
@@ -576,8 +576,8 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
github.com/kobergj/go-micro/v4 v4.0.0-20250610135441-d0b187215699 h1:3TOdtI6WPyvBB+uCykapjRtQX8vTHMlyhINzR+58B4k=
@@ -607,8 +607,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/leonelquinteros/gotext v1.7.2 h1:bDPndU8nt+/kRo1m4l/1OXiiy2v7Z7dfPQ9+YP7G1Mc=
github.com/leonelquinteros/gotext v1.7.2/go.mod h1:9/haCkm5P7Jay1sxKDGJ5WIg4zkz8oZKw4ekNpALob8=
github.com/lestrrat-go/blackmagic v1.0.4 h1:IwQibdnf8l2KoO+qC3uT4OaTWsW7tuRQXy9TRN9QanA=
@@ -649,8 +649,8 @@ github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLG
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/go-sqlite3 v1.14.49 h1:B8jBHC3xhxZgxztrgruTuLucebnULQnx4W7cF7SAE9w=
github.com/mattn/go-sqlite3 v1.14.49/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
github.com/mattn/go-sqlite3 v1.14.50 h1:dmdFvo1XG4MPzA4IkAmE9upVz/Nj31uRoM5+jC8hYbY=
github.com/mattn/go-sqlite3 v1.14.50/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b h1:Q53idHrTuQDDHyXaxZ6pUl0I9uyD6Z6uKFK3ocX6LzI=
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b/go.mod h1:KirJrATYGbTyUwVR26xIkaipRqRcMRXBf8N5dacvGus=
@@ -668,8 +668,8 @@ github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clg
github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.2.1 h1:PfBfwvKB/MmqyN8Vb1G9voWisaM9OrLv+WwOvMwS9Dw=
github.com/minio/minio-go/v7 v7.2.1/go.mod h1:EU9hENAStx/xXduNdrGO5e4X5vk19NtgB+RIPjZO8o0=
github.com/minio/minio-go/v7 v7.3.0 h1:HM4pFCSQq/TK+j0/zmorSh5ddh81iDgRgU0BG0Vz/YU=
github.com/minio/minio-go/v7 v7.3.0/go.mod h1:KUPWdecEO1LWyUz+sTGXAuf2jZHrPh5fCsRH86QbPfk=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
@@ -696,8 +696,8 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
github.com/nats-io/nats-server/v2 v2.14.5 h1:M6yeo/Xb7khi97RSEVELof3DForDqmYza3P4tHCPFWw=
github.com/nats-io/nats-server/v2 v2.14.5/go.mod h1:1D3iocrisKvWaD1B/imqarTqmaGrWMqALMLbEDo3v7Q=
github.com/nats-io/nats-server/v2 v2.14.6 h1:dHjEHa49lUTxIb5jrsk5kz/AmOyOQ4T9ti8djcBumDQ=
github.com/nats-io/nats-server/v2 v2.14.6/go.mod h1:u/0bNBzN/m5orQGz7q2NNzxCQ6PWdwaOSwPNDADZn/A=
github.com/nats-io/nats.go v1.53.1 h1:Otsq3uLc/kLdjmkNHkXH0jBqwUquwdKFoe3fq6/3/Xo=
github.com/nats-io/nats.go v1.53.1/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno=
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
@@ -725,8 +725,8 @@ github.com/onsi/ginkgo/v2 v2.32.1 h1:6tlvcDm/3sE8lGJbZ4+d4mO3RLy24/tQWOFzVSQNIfw
github.com/onsi/ginkgo/v2 v2.32.1/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I=
github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg=
github.com/onsi/gomega v1.43.0 h1:VlG/1FxqNxhSO+lq/OHBNaaqwiBK/mO8JbVkX9Y+FeU=
github.com/onsi/gomega v1.43.0/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg=
github.com/open-policy-agent/opa v1.19.0 h1:+j2OCsjMezZEML2T1lI9giJdGJS/PL1XFKgkHPGIhpo=
github.com/open-policy-agent/opa v1.19.0/go.mod h1:pb6Y6klyf7X7X8uXNDflruA9dQC2gMqWROXI5w/kvv0=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
@@ -736,8 +736,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
github.com/owncloud/reva/v2 v2.0.0-20260813121157-d386075a0421 h1:orjzG6JMpulTJvkeg//KwgeqdrOMGXAO0K6GaH4XCxI=
github.com/owncloud/reva/v2 v2.0.0-20260813121157-d386075a0421/go.mod h1:f4ymc4PUG6a3QSOHXq7Q9Ck5udiSNU6Lv2Im2Q0jvRc=
github.com/owncloud/reva/v2 v2.0.0-20260911153821-68e8cf7deba4 h1:j78upHa0iJaww1yZftXPeClhAigvaq5rQuxSEqg/uFQ=
github.com/owncloud/reva/v2 v2.0.0-20260911153821-68e8cf7deba4/go.mod h1:VohDRQV33rVDiofWNngHqQK7tsgtYJpQBNWsn41j/LM=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
@@ -767,8 +767,8 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pquerna/cachecontrol v0.2.0 h1:vBXSNuE5MYP9IJ5kjsdo8uq+w41jSPgvba2DEnkRx9k=
github.com/pquerna/cachecontrol v0.2.0/go.mod h1:NrUG3Z7Rdu85UNR3vm7SOsl1nFIeSiQnrHV5K9mBcUI=
github.com/prometheus/alertmanager v0.33.1 h1:PJHGvTdb8Q0ZEpJnWff120WxB2kxIScLa707AaIudTo=
github.com/prometheus/alertmanager v0.33.1/go.mod h1:V06Uc8EZ5X5wLOJRGhtXx+EE2LgrinFIADbKWMVm1RY=
github.com/prometheus/alertmanager v0.34.0 h1:z75n0NoypggESmt3HD4JlTXOaOZj1EBz1ACHO4Z6EUk=
github.com/prometheus/alertmanager v0.34.0/go.mod h1:/qF39A6Vb1MMoDM1SxcySobb7wmpBZha8COwULiKUUo=
github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
@@ -838,8 +838,8 @@ github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sethvargo/go-password v0.4.0 h1:eSidVKQw5C7CmTDAtH3RipBTSjdU1ZRxQaynD2GWLVU=
github.com/sethvargo/go-password v0.4.0/go.mod h1:PO3nYHwUpcHPR0F9woy7a4abZPvzRuqJr0GaeIYTm3k=
github.com/shamaton/msgpack/v2 v2.4.1 h1:JtJ141QoQ3NqgPDsjq2v9VXlaON8SiQOwEaoNLEK/MQ=
github.com/shamaton/msgpack/v2 v2.4.1/go.mod h1:6khjYnkx73f7VQU7wjcFS9DFjs+59naVWJv1TB7qdOI=
github.com/shamaton/msgpack/v2 v2.4.2 h1:ukiqiwF8rIb8EG6hD8iPha3g85AC7EdCxFyobDj6oHk=
github.com/shamaton/msgpack/v2 v2.4.2/go.mod h1:6khjYnkx73f7VQU7wjcFS9DFjs+59naVWJv1TB7qdOI=
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/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
@@ -877,8 +877,9 @@ github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1F
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/stvp/go-udp-testing v0.0.0-20201019212854-469649b16807/go.mod h1:7jxmlfBCDBXRzr0eAQJ48XC1hBu1np4CS5+cHEYfwpc=
github.com/tchap/go-patricia/v2 v2.3.3 h1:xfNEsODumaEcCcY3gI0hYPZ/PcpVv5ju6RMAhgwZDDc=
github.com/tchap/go-patricia/v2 v2.3.3/go.mod h1:VZRHKAb53DLaG+nA9EaYYiaEx6YztwDlLElMsnSHD4k=
@@ -898,8 +899,8 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/tinylib/msgp v1.6.1 h1:ESRv8eL3u+DNHUoSAAQRE50Hm162zqAnBoGv9PzScPY=
github.com/tinylib/msgp v1.6.1/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ=
github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU=
github.com/tklauser/go-sysconf v0.3.14/go.mod h1:1ym4lWMLUOhuBOPGtRcJm7tEGX4SCYNEEEtghGG/8uY=
github.com/tklauser/numcpus v0.8.0 h1:Mx4Wwe/FjZLeQsK/6kt2EOepwwSl7SmJrK5bV/dXYgY=
@@ -965,28 +966,28 @@ go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0 h1:oECp5f+hN7nkwjU/8BxQ/q23bGPb8FIrD839owX222E=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0/go.mod h1:DqEFwLumhzMBDQv9PcWbyoDxHI/4lAk6CM4nJBH39sc=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 h1:B2h3uqicet1CT2N5TOFhS+Gq++9i0/CLmaxvhmhtP5s=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0/go.mod h1:dylvB+ZiiwMvsDij9O84Uy7SijLgHMX4mbkncds+4Sw=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04=
go.opentelemetry.io/contrib/zpages v0.70.0 h1:uBcclHekIrCRLO4KZfXiebDcWB52QQXaHGgvhUJ1K5I=
go.opentelemetry.io/contrib/zpages v0.70.0/go.mod h1:Nz9A1+68HVoJrk+cg92zJbcbHFAa+Jbl1uINwAlcK94=
go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
go.opentelemetry.io/otel/exporters/jaeger v1.17.0 h1:D7UpUy2Xc2wsi1Ras6V40q806WM07rqoCWzXu7Sqy+4=
go.opentelemetry.io/otel/exporters/jaeger v1.17.0/go.mod h1:nPCqOnEH9rNLKqH/+rrUjiMzHJdV1BlpKcTwRTyKkKI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI=
go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0 h1:w53CDeOA/Kurp7yRsegSr6pbbr759dOvJ+yNmWM6Hxs=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0/go.mod h1:BOmGMCbAtvcJiSJ+hLuhgPLdDbimnraSl8irz3iY8sY=
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
@@ -1015,8 +1016,8 @@ golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -1326,10 +1327,10 @@ google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6D
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0=
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I=
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc=
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688 h1:ax2KzoSRIZU/M0cIxri3pKxy99vniH1PVxWC6si/eZI=
google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688/go.mod h1:1RJ9BQGyNdZwkGc1eTqkErfRZ6RJyYPHZo73BZ1vQqI=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
+6 -1
View File
@@ -1,8 +1,13 @@
Release 1.7.0
Release 1.7.1
=============
**Changes**
* Improve efficiency of `Element.Text` and `Element.Tail`.
Release 1.7.0
=============
**Breaking changes**
* To address a security issue, it was necessary to add a `MaxDepth` option to
+20 -4
View File
@@ -635,13 +635,17 @@ func (e *Element) Text() string {
return ""
}
text := ""
var text string
var b strings.Builder
for _, ch := range e.Child {
if cd, ok := ch.(*CharData); ok {
if text == "" {
text = cd.Data
} else {
text += cd.Data
if b.Len() == 0 {
b.WriteString(text)
}
b.WriteString(cd.Data)
}
} else if _, ok := ch.(*Comment); ok {
// ignore
@@ -649,6 +653,10 @@ func (e *Element) Text() string {
break
}
}
if b.Len() > 0 {
return b.String()
}
return text
}
@@ -674,18 +682,26 @@ func (e *Element) Tail() string {
p := e.Parent()
i := e.Index()
text := ""
var text string
var b strings.Builder
for _, ch := range p.Child[i+1:] {
if cd, ok := ch.(*CharData); ok {
if text == "" {
text = cd.Data
} else {
text += cd.Data
if b.Len() == 0 {
b.WriteString(text)
}
b.WriteString(cd.Data)
}
} else {
break
}
}
if b.Len() > 0 {
return b.String()
}
return text
}
+1 -1
View File
@@ -24,7 +24,7 @@ func (fsa *FSAdmin) PinSubVolume(volume, subvolume, pintype, pinsetting string)
return parsePathResponse(fsa.marshalMgrCommand(m))
}
// PinSubVolumeGroup pins subvolume to ranks according to policies. A valid pin
// PinSubVolumeGroup pins subvolume group to ranks according to policies. A valid pin
// setting value depends on the type of pin as described in the docs from
// https://docs.ceph.com/en/latest/cephfs/multimds/#cephfs-pinning and
// https://docs.ceph.com/en/latest/cephfs/multimds/#setting-subtree-partitioning-policies
+28
View File
@@ -0,0 +1,28 @@
//go:build !nautilus && ceph_preview
package admin
// PinSubVolumeInGroup pins a subvolume in a volume and optional subvolume group
// to ranks according to policies. A valid pin setting value depends on the type
// of pin as described in the docs from
// https://docs.ceph.com/en/latest/cephfs/multimds/#cephfs-pinning and
// https://docs.ceph.com/en/latest/cephfs/multimds/#setting-subtree-partitioning-policies
//
// Similar To:
//
// ceph fs subvolume pin <vol_name> <sub_name> <pin_type> <pin_setting> [--group_name=<group>]
func (fsa *FSAdmin) PinSubVolumeInGroup(volume, group, subvolume, pintype, pinsetting string) (string, error) {
m := map[string]string{
"prefix": "fs subvolume pin",
"format": "json",
"vol_name": volume,
"sub_name": subvolume,
"pin_type": pintype,
"pin_setting": pinsetting,
}
if group != NoGroup {
m["group_name"] = group
}
return parsePathResponse(fsa.marshalMgrCommand(m))
}
+14
View File
@@ -278,6 +278,20 @@ func (j *jwkJSON) UnmarshalJSON(data []byte) error {
}
var jwk jose.JSONWebKey
if err := json.Unmarshal(key, &jwk); err != nil {
// Ignore keys with types that go-jose doesn't support, such as
// OKP keys with Ed448 or X448 curves. Some providers include
// them in their key sets without an "alg" value, so the check
// above doesn't catch them.
//
// https://datatracker.ietf.org/doc/html/rfc7517#section-5
//
// Implementations SHOULD ignore JWKs within a JWK Set that use
// "kty" (key type) values that are not understood by them, that
// are missing required members, or for which values are out of
// the supported ranges.
if errors.Is(err, jose.ErrUnsupportedKeyType) {
continue
}
return err
}
j.Keys = append(j.Keys, jwk)
+5
View File
@@ -465,6 +465,11 @@ is folded to plain IPv4, and IPv6 zone identifiers carried in headers are
stripped, so one logical client maps to a single canonical key for logs,
rate limits, and ACLs.
For `ClientIPFromXFFTrustedProxies`, `numTrustedProxies` is the total proxy
hops between client and server. Prefer `ClientIPFromXFF` with explicit CIDRs
when you can — CIDR-based trust cannot off-by-one. See the godoc for a
deployment recipe and a verify checklist.
See the per-function godoc for the full semantics of each middleware, and
[adam-p's "The perils of the 'real' client IP"](https://adam-p.ca/blog/2022/03/x-forwarded-for/)
for the underlying threat model.
+32 -21
View File
@@ -62,7 +62,14 @@ func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
// set (fail-closed) — we can't safely trust anything left of garbage.
//
// Use this when you sit behind one or more reverse proxies whose IP ranges
// you can enumerate as CIDRs:
// you can enumerate as CIDRs. Most CDNs publish their IPs:
//
// Cloudflare: https://www.cloudflare.com/ips/
// AWS: https://ip-ranges.amazonaws.com/ip-ranges.json
// Fastly: https://api.fastly.com/public-ip-list
// Google Cloud: https://www.gstatic.com/ipranges/cloud.json
//
// Example (CloudFront):
//
// r.Use(middleware.ClientIPFromXFF(
// "13.32.0.0/15", // CloudFront IPv4
@@ -109,30 +116,34 @@ func ClientIPFromXFF(trustedIPPrefixes ...string) func(http.Handler) http.Handle
}
}
// ClientIPFromXFFTrustedProxies stores the client IP read from the
// X-Forwarded-For header, given the exact number of trusted reverse proxies
// between this server and the public internet. It returns the IP at position
// len(xff) - numTrustedProxies in the merged X-Forwarded-For list — the IP
// added by the outermost of your trusted proxies, the only IP in the chain
// that none of your proxies have allowed an attacker to forge. Read it with
// [GetClientIP].
// ClientIPFromXFFTrustedProxies stores the client IP read from
// X-Forwarded-For, given the exact number of trusted reverse proxies
// between this server and the public internet. Read it with [GetClientIP].
//
// Use this when:
// - You know exactly how many proxies you sit behind, AND
// - Their IP addresses are dynamic (autoscaling proxy pools, ephemeral
// containers, dynamic CDN edges) so listing CIDRs with [ClientIPFromXFF]
// is impractical.
// PREFER [ClientIPFromXFF] with explicit CIDRs whenever you can — it
// cannot off-by-one and is robust to architecture changes. Most CDNs
// publish their IP ranges (Cloudflare, AWS, Fastly, Google Cloud). Use
// this counting variant only when proxy IPs are dynamic and unpublishable.
//
// WARNING: This variant is brittle to network architecture changes. If you
// add or remove a proxy level, numTrustedProxies silently becomes wrong and
// you may start trusting an attacker-supplied IP. Prefer [ClientIPFromXFF]
// with explicit trusted CIDRs whenever you can.
// numTrustedProxies = total proxy hops between the client and this server.
// Count every hop in the request path:
//
// If the XFF chain has fewer than numTrustedProxies entries (header missing
// or architecture changed), no client IP is set and [GetClientIP] returns "".
// Single proxy (one LB / nginx / Heroku / Fly.io / Render) ....... 1
// Two proxies (Cloudflare → ALB, CloudFront → ALB) .............. 2
// Three proxies (CDN → API gateway → LB) ......................... 3
//
// Like [ClientIPFromXFF], v4-mapped IPv6 folds to plain v4 and IPv6 zones
// are stripped before storage.
// VERIFY BEFORE GOING LIVE: send a request from a known IP and confirm
// [GetClientIP] returns that IP. If it returns a proxy IP, your count is
// too LOW — a client can spoof their IP, fix immediately. If it returns
// "", your count is too HIGH — no leak, but no client IP either.
//
// This middleware reads ONLY X-Forwarded-For; it does not inspect
// r.RemoteAddr. Guarantee at the network layer (security group / firewall)
// that only your proxies can reach this server.
//
// If the XFF chain has fewer than numTrustedProxies entries, no client IP
// is set (fail-closed). Like [ClientIPFromXFF], v4-mapped IPv6 folds to v4
// and IPv6 zones are stripped before storage.
//
// Panics at startup if numTrustedProxies < 1.
func ClientIPFromXFFTrustedProxies(numTrustedProxies int) func(http.Handler) http.Handler {
+11 -1
View File
@@ -18,6 +18,9 @@ var defaultCompressibleContentTypes = []string{
"text/css",
"text/plain",
"text/javascript",
"text/markdown",
"text/csv",
"text/vtt",
"application/javascript",
"application/x-javascript",
"application/json",
@@ -62,6 +65,10 @@ type Compressor struct {
//
// The level should be one of the ones defined in the flate package.
// The types are the content types that are allowed to be compressed.
//
// Catch-all wildcards ("*/*", "/*") are rejected: compressing every response
// wastes CPU on already-compressed types like zip, jpeg or png. Pass explicit
// types instead, e.g. "text/html" or "application/*".
func NewCompressor(level int, types ...string) *Compressor {
// If types are provided, set those as the allowed types. If none are
// provided, use the default list.
@@ -70,9 +77,12 @@ func NewCompressor(level int, types ...string) *Compressor {
if len(types) > 0 {
for _, t := range types {
if strings.Contains(strings.TrimSuffix(t, "/*"), "*") {
panic(fmt.Sprintf("middleware/compress: Unsupported content-type wildcard pattern '%s'. Only '/*' supported", t))
panic(fmt.Sprintf("middleware/compress: Unsupported content-type wildcard pattern '%s'. Only '<type>/*' supported", t))
}
if before, ok := strings.CutSuffix(t, "/*"); ok {
if before == "" {
panic(fmt.Sprintf("middleware/compress: Unsupported content-type wildcard pattern '%s'. Only '<type>/*' supported", t))
}
allowedWildcards[before] = struct{}{}
} else {
allowedTypes[t] = struct{}{}
+46 -6
View File
@@ -7,6 +7,7 @@ package chi
import (
"fmt"
"net/http"
"reflect"
"regexp"
"slices"
"sort"
@@ -478,7 +479,9 @@ func (n *node) findRoute(rctx *Context, method methodTyp, path string) *node {
if endpoints == mALL || endpoints == mSTUB {
continue
}
rctx.methodsAllowed = append(rctx.methodsAllowed, endpoints)
if !slices.Contains(rctx.methodsAllowed, endpoints) {
rctx.methodsAllowed = append(rctx.methodsAllowed, endpoints)
}
}
// flag that the routing context found a route, but not a corresponding
@@ -524,7 +527,9 @@ func (n *node) findRoute(rctx *Context, method methodTyp, path string) *node {
if endpoints == mALL || endpoints == mSTUB {
continue
}
rctx.methodsAllowed = append(rctx.methodsAllowed, endpoints)
if !slices.Contains(rctx.methodsAllowed, endpoints) {
rctx.methodsAllowed = append(rctx.methodsAllowed, endpoints)
}
}
// flag that the routing context found a route, but not a corresponding
@@ -629,8 +634,10 @@ func (n *node) routes() []Route {
rts := []Route{}
n.walk(func(eps endpoints, subroutes Routes) bool {
if eps[mSTUB] != nil && eps[mSTUB].handler != nil && subroutes == nil {
return false
// Hide Mount()'s stub handler, but not a real handler sharing its pattern.
var stubHandler http.Handler
if eps[mSTUB] != nil {
stubHandler = eps[mSTUB].handler
}
// Group methodHandlers by unique patterns
@@ -650,12 +657,17 @@ func (n *node) routes() []Route {
for p, mh := range pats {
hs := make(map[string]http.Handler)
// Walk() reads Handlers["*"] for With() middleware when recursing
// into a subroute, so keep it there even if it's also the stub.
if mh[mALL] != nil && mh[mALL].handler != nil {
hs["*"] = mh[mALL].handler
if subroutes != nil || !equalHandlers(mh[mALL].handler, stubHandler) {
hs["*"] = mh[mALL].handler
}
}
for mt, h := range mh {
if h.handler == nil {
if h.handler == nil || equalHandlers(h.handler, stubHandler) {
continue
}
if m, ok := reverseMethodMap[mt]; ok {
@@ -663,6 +675,11 @@ func (n *node) routes() []Route {
}
}
// Keep subroute nodes so Walk() can recurse; a stub-only leaf has nothing to report.
if len(hs) == 0 && subroutes == nil {
continue
}
rt := Route{subroutes, hs, p}
rts = append(rts, rt)
}
@@ -673,6 +690,29 @@ func (n *node) routes() []Route {
return rts
}
// equalHandlers reports whether a and b are the same handler value. Handlers
// are commonly funcs (e.g. http.HandlerFunc), and a direct == on those
// panics at runtime, so funcs are compared by pointer instead.
func equalHandlers(a, b http.Handler) bool {
if a == nil || b == nil {
return a == b
}
av := reflect.ValueOf(a)
bv := reflect.ValueOf(b)
if av.Type() != bv.Type() {
return false
}
if av.Kind() == reflect.Func {
return av.Pointer() == bv.Pointer()
}
if av.Type().Comparable() {
return a == b
}
return false
}
func (n *node) walk(fn func(eps endpoints, subroutes Routes) bool) bool {
// Visit the leaf values if any
if (n.endpoints != nil || n.subroutes != nil) && fn(n.endpoints, n.subroutes) {
@@ -7,6 +7,8 @@
_obj
_test
bin
.gocache/
.gomodcache/
# Architecture specific extensions/prefixes
*.[568vq]
+1
View File
@@ -14,6 +14,7 @@ linters:
- errorlint
- exhaustive
- exhaustruct
- exhaustruct_v5
- forbidigo
- forcetypeassert
- funlen
+1 -1
View File
@@ -3,7 +3,7 @@ GOCMD=go
linters-install:
@golangci-lint --version >/dev/null 2>&1 || { \
echo "installing linting tools..."; \
curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v2.0.2; \
curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v2.13.1; \
}
lint: linters-install
+2 -1
View File
@@ -85,7 +85,7 @@ validate := validator.New(validator.WithRequiredStructEnabled())
| eqcsfield | Field Equals Another Field (relative)|
| eqfield | Field Equals Another Field |
| fieldcontains | Check the indicated characters are present in the Field |
| fieldexcludes | Check the indicated characters are not present in the field |
| fieldexcludes | Current field does not contain another field's value |
| gtcsfield | Field Greater Than Another Relative Field |
| gtecsfield | Field Greater Than or Equal To Another Relative Field |
| gtefield | Field Greater Than or Equal To Another Field |
@@ -132,6 +132,7 @@ validate := validator.New(validator.WithRequiredStructEnabled())
| origin | Web origin (URL with HTTP(S) scheme and host, but no path/query/fragment) |
| url_encoded | URL Encoded |
| urn_rfc2141 | Urn RFC 2141 String |
| urn_rfc8141 | Urn RFC 8141 String |
### Strings:
+22 -2
View File
@@ -143,6 +143,7 @@ var (
"https_url": isHttpsURL,
"uri": isURI,
"origin": isOrigin,
"urn_rfc8141": isUrnRFC8141, // RFC 8141
"urn_rfc2141": isUrnRFC2141, // RFC 2141
"file": isFile,
"filepath": isFilePath,
@@ -1695,6 +1696,26 @@ func isHttpsURL(fl FieldLevel) bool {
panic(fmt.Sprintf("Bad field type %s", field.Type()))
}
// isUrnRFC8141 is the validation function for validating if the current field's value is a valid URN as per RFC 8141.
func isUrnRFC8141(fl FieldLevel) bool {
field := fl.Field()
switch field.Kind() {
case reflect.String:
str := field.String()
if str == "" {
return false
}
_, match := urn.Parse([]byte(str), urn.WithParsingMode(urn.RFC8141Only))
return match
}
panic(fmt.Sprintf("Bad field type %T", field.Interface()))
}
// isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141.
func isUrnRFC2141(fl FieldLevel) bool {
field := fl.Field()
@@ -2896,7 +2917,7 @@ func isHostnameRFC1123(fl FieldLevel) bool {
func isFQDN(fl FieldLevel) bool {
val := fl.Field().String()
if val == "" {
if val == "" || len(strings.TrimSuffix(val, ".")) > 253 {
return false
}
@@ -3510,4 +3531,3 @@ var (
errMethodReturnNoValues = errors.New(`method return o values (void)`)
errMethodReturnInvalidType = errors.New(`method should return invalid type`)
)
+13 -5
View File
@@ -803,13 +803,14 @@ other types.
Usage: containsfield=InnerStructField.Field
# Field Excludes Another Field
# Field Excludes Another Field's Value
This does the same as excludes except for struct fields. It should only be used
with string types. See the behavior of reflect.Value.String() for behavior on
other types.
This validates that the current field's string value does not contain the
string value of the field named by the parameter. It should only be used with
string types. If the referenced field cannot be resolved, validation succeeds.
See the behavior of reflect.Value.String() for behavior on other types.
Usage: excludesfield=InnerStructField.Field
Usage: fieldexcludes=InnerStructField.Field
# Unique
@@ -1026,6 +1027,13 @@ This will accept any uri the golang request uri accepts
Usage: uri
# Urn RFC 8141 String
This validataes that a string value contains a valid URN
according to the RFC 8141 spec.
Usage: urn_rfc8141
# Urn RFC 2141 String
This validates that a string value contains a valid URN
+59 -3
View File
@@ -310,7 +310,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
return
}
if err = ut.Add("max-items", "{0} must contain at maximum {1}", false); err != nil {
if err = ut.Add("max-items", "{0} must contain at most {1}", false); err != nil {
return
}
if err = ut.AddCardinal("max-items-item", "{0} item", locales.PluralRuleOne, false); err != nil {
@@ -548,7 +548,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
{
tag: "lte",
customRegisFunc: func(ut ut.Translator) (err error) {
if err = ut.Add("lte-string", "{0} must be at maximum {1} in length", false); err != nil {
if err = ut.Add("lte-string", "{0} must be at most {1} in length", false); err != nil {
return
}
@@ -564,7 +564,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
return
}
if err = ut.Add("lte-items", "{0} must contain at maximum {1}", false); err != nil {
if err = ut.Add("lte-items", "{0} must contain at most {1}", false); err != nil {
return
}
@@ -1187,6 +1187,62 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
return t
},
},
{
tag: "startswith",
translation: "{0} must start with '{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "endswith",
translation: "{0} must end with '{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "startsnotwith",
translation: "{0} must not start with '{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "endsnotwith",
translation: "{0} must not end with '{1}'",
override: false,
customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field(), fe.Param())
if err != nil {
log.Printf("warning: error translating FieldError: %#v", fe)
return fe.(error).Error()
}
return t
},
},
{
tag: "excludes",
translation: "{0} cannot contain the text '{1}'",
+1
View File
@@ -129,6 +129,7 @@ Xiangyu Hu <xiangyu.hu at outlook.com>
Xiaobing Jiang <s7v7nislands at gmail.com>
Xiuming Chen <cc at cxm.cc>
Xuehong Chan <chanxuehong at gmail.com>
Yoshito Ohata <yoshito.dev at gmail.com>
Zhang Xiang <angwerzx at 126.com>
Zhenye Xie <xiezhenye at gmail.com>
Zhixin Wen <john.wenzhixin at gmail.com>
+10
View File
@@ -1,5 +1,15 @@
# Changelog
## v1.10.1 (2026-09-02)
* Fix `Config.FormatDSN()` dropping `Addr` when `Net` is empty.
It now uses the default `tcp` network so configs with only `Addr` round-trip correctly. (#1770)
* Fix typed-nil `json.RawMessage` with `interpolateParams=true` being interpolated as an empty string.
It is now interpolated as SQL `NULL`, matching server-side prepared statements. (#1782)
* Add MariaDB 11.8 and 12.3 to the test matrix. (#1774)
## v1.10.0 (2026-04-28)
* Fix `getSystemVar("max_allowed_packet")` potentially returned wrong value. (#1754)
+4 -1
View File
@@ -314,7 +314,10 @@ Type: duration
Default: 0
```
[Truncate time values](https://pkg.go.dev/time#Duration.Truncate) to the specified duration. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*.
[Truncate time values](https://pkg.go.dev/time#Duration.Truncate) in query arguments to the specified duration. The value must be a decimal number with a unit suffix (*"ns"*, *"us"*, *"ms"*, etc...), such as "1us", "1ms", or "10ns".
> [!NOTE]
> `time.Time` arguments are sent with up to nanosecond precision, so a value from `time.Now()` usually has more fractional-second digits than a `DATETIME(N)` or `TIMESTAMP(N)` column stores. On MariaDB, comparing such a value against an indexed column can prevent an index range scan, turning it into a full index scan. Truncating to the column's precision (`1us` for `DATETIME(6)`) avoids this. Only arguments sent to the server are truncated; values read from the server are not affected.
##### `maxAllowedPacket`
```
+3 -1
View File
@@ -384,7 +384,9 @@ func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (strin
buf = append(buf, '\'')
}
case json.RawMessage:
if noBackslashEscapes {
if v == nil {
buf = append(buf, "NULL"...)
} else if noBackslashEscapes {
buf = escapeBytesQuotes(buf, v, false)
} else {
buf = escapeBytesBackslash(buf, v, false)
+12 -6
View File
@@ -264,13 +264,19 @@ func (cfg *Config) FormatDSN() string {
}
// [protocol[(address)]]
if len(cfg.Net) > 0 {
buf.WriteString(cfg.Net)
if len(cfg.Addr) > 0 {
buf.WriteByte('(')
buf.WriteString(cfg.Addr)
buf.WriteByte(')')
if len(cfg.Addr) > 0 {
net := cfg.Net
if net == "" {
net = "tcp"
}
buf.WriteString(net)
buf.WriteByte('(')
buf.WriteString(cfg.Addr)
buf.WriteByte(')')
} else if cfg.Net != "" && cfg.Net != "tcp" {
// Preserve an explicit non-default protocol when there's no
// address, so e.g. Net="unix" still round-trips.
buf.WriteString(cfg.Net)
}
// /dbname
+3 -1
View File
@@ -6,7 +6,9 @@ formatters:
- goimports
settings:
gofumpt:
extra-rules: true
extra:
clothe-returns: true
group-params: true
linters:
enable:
+2 -2
View File
@@ -1,5 +1,5 @@
// Copyright 2015 Tim Heckman. All rights reserved.
// Copyright 2018-2025 The Gofrs. All rights reserved.
// Copyright 2018-2026 The Gofrs. All rights reserved.
// Use of this source code is governed by the BSD 3-Clause
// license that can be found in the LICENSE file.
@@ -100,7 +100,7 @@ func (f *Flock) Close() error {
return f.Unlock()
}
// Path returns the path as provided in NewFlock().
// Path returns the path as provided in New().
func (f *Flock) Path() string {
return f.path
}
+1 -1
View File
@@ -1,5 +1,5 @@
// Copyright 2015 Tim Heckman. All rights reserved.
// Copyright 2018-2025 The Gofrs. All rights reserved.
// Copyright 2018-2026 The Gofrs. All rights reserved.
// Use of this source code is governed by the BSD 3-Clause
// license that can be found in the LICENSE file.
+1 -1
View File
@@ -1,5 +1,5 @@
// Copyright 2015 Tim Heckman. All rights reserved.
// Copyright 2018-2025 The Gofrs. All rights reserved.
// Copyright 2018-2026 The Gofrs. All rights reserved.
// Use of this source code is governed by the BSD 3-Clause
// license that can be found in the LICENSE file.
+1 -1
View File
@@ -1,5 +1,5 @@
// Copyright 2015 Tim Heckman. All rights reserved.
// Copyright 2018-2025 The Gofrs. All rights reserved.
// Copyright 2018-2026 The Gofrs. All rights reserved.
// Use of this source code is governed by the BSD 3-Clause
// license that can be found in the LICENSE file.
+1 -1
View File
@@ -1,5 +1,5 @@
// Copyright 2015 Tim Heckman. All rights reserved.
// Copyright 2018-2025 The Gofrs. All rights reserved.
// Copyright 2018-2026 The Gofrs. All rights reserved.
// Use of this source code is governed by the BSD 3-Clause
// license that can be found in the LICENSE file.
+3
View File
@@ -0,0 +1,3 @@
rules:
secrets-outside-env:
disable: true
+1 -1
View File
@@ -29,7 +29,7 @@ archives:
name_template: "cpuid-{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
format_overrides:
- goos: windows
format: zip
formats: [ 'zip' ]
files:
- LICENSE
checksum:
+69 -1
View File
@@ -2,7 +2,7 @@
Package cpuid provides information about the CPU running the current program.
CPU features are detected on startup, and kept for fast access through the life of the application.
Currently x86 / x64 (AMD64/i386) and ARM (ARM64) is supported, and no external C (cgo) code is used, which should make the library very easy to use.
Currently x86 / x64 (AMD64/i386), ARM (ARM64), and RISC-V (RV64) are supported, and no external C (cgo) code is used, which should make the library very easy to use.
You can access the CPU information by accessing the shared CPU variable of the cpuid library.
@@ -506,6 +506,74 @@ Exit Code 1
| SM3 | SM3 instructions |
| SM4 | SM4 instructions |
| SVE | Scalable Vector Extension |
| SVE2 | Scalable Vector Extension 2 |
| SB | Speculation barrier (SB instruction) |
| SSBS | Speculative Store Bypass Safe (PSTATE.SSBS) |
| BTI | Branch Target Identification |
| FLAGM2 | Condition flag manipulation version 2 (AXFLAG, XAFLAG) |
| FRINTTS | Floating-point to integer rounding (FRINT32Z, FRINT64Z, etc) |
| DCPODP | Data cache clean to Point of Deep Persistence (DC CVADP) |
| BF16 | BFloat16 instructions (BFDOT, BFMMLA, etc) |
| I8MM | Int8 matrix multiplication (SMMLA, UMMLA, USMMLA) |
| WFXT | WFE/WFI with timeout (WFET, WFIT) |
| MOPS | Memory copy and set instructions (CPYF, SETP, etc) |
| HBC | Hinted conditional branches (BC.cond) |
| CSSC | Common short sequence compression (ABS, SMAX, UMAX, etc) |
## riscv64 feature detection
On `riscv64/linux`, CPU features are detected using the `riscv_hwprobe` syscall (Linux 6.4+).
For older kernels, detection falls back to parsing `/proc/cpuinfo` for the ISA string.
Cache line size is detected via `riscv_hwprobe` (Zicbom block size) or sysfs fallback.
Other cache and topology information is not yet available.
# RISC-V features:
| Feature Flag | Description |
|----------------|----------------------------------------------------|
| RV_IMA | IMA base (Integer, Multiply, Atomic) |
| RV_C | Compressed instructions |
| RV_F | Single-precision FP |
| RV_D | Double-precision FP |
| RV_V | Vector extension (V) |
| RV_ZBA | Address generation |
| RV_ZBB | Basic bit manipulation |
| RV_ZBC | Carry-less multiplication |
| RV_ZBS | Single-bit manipulation |
| RV_ZICOND | Integer conditional operations |
| RV_ZIHINTPAUSE | Pause hint |
| RV_ZICBOM | Cache block management operations |
| RV_ZICBOZ | Cache block zero |
| RV_ZICBOP | Cache block prefetch |
| RV_ZFA | Additional floating-point |
| RV_ZFH | Half-precision FP |
| RV_ZFHMIN | Minimal half-precision FP |
| RV_ZTSO | Total store ordering |
| RV_ZACAS | Atomic CAS |
| RV_ZBKB | Bit-manipulation for crypto |
| RV_ZBKC | Carry-less multiply for crypto |
| RV_ZBKX | Crossbar permutations |
| RV_ZKND | NIST Suite: AES decrypt |
| RV_ZKNE | NIST Suite: AES encrypt |
| RV_ZKNH | NIST Suite: SHA-2 (SHA-256/SHA-512) |
| RV_ZKSED | ShangMi Suite: SM4 block cipher |
| RV_ZKSH | ShangMi Suite: SM3 hash |
| RV_ZKT | Data-independent execution latency (Crypto) |
| RV_ZKN | NIST Algorithm Suite (combined from individual) |
| RV_ZKS | ShangMi Algorithm Suite (combined from individual) |
| RV_ZVBB | Vector Basic Bit-manipulation |
| RV_ZVBC | Vector Carry-less multiply |
| RV_ZVKB | Vector Bit-manipulation for crypto |
| RV_ZVKG | Vector GCM/GMAC |
| RV_ZVKNED | NIST Suite: Vector AES encrypt+decrypt |
| RV_ZVKNHA | NIST Suite: Vector SHA-2 (SHA-256) |
| RV_ZVKNHB | NIST Suite: Vector SHA-2 (SHA-512) |
| RV_ZVKSED | ShangMi Suite: Vector SM4 |
| RV_ZVKSH | ShangMi Suite: Vector SM3 hash |
| RV_ZVKT | Vector Data-independent execution latency |
| RV_ZVKNG | NIST Suite with GCM (combined from individual) |
| RV_ZVKSG | ShangMi Suite with GCM (combined from individual) |
# license
+200 -13
View File
@@ -3,7 +3,7 @@
// Package cpuid provides information about the CPU running the current program.
//
// CPU features are detected on startup, and kept for fast access through the life of the application.
// Currently x86 / x64 (AMD64) as well as arm64 is supported.
// Currently x86 / x64 (AMD64), arm64, and riscv64 are supported.
//
// You can access the CPU information by accessing the shared CPU variable of the cpuid library.
//
@@ -17,6 +17,7 @@ import (
"math/bits"
"os"
"runtime"
"slices"
"strings"
)
@@ -61,6 +62,13 @@ const (
SRE
Apple
// RISC-V vendors
SiFive
StarFive
THead
Andes
SpacemiT
lastVendor
)
@@ -95,6 +103,7 @@ const (
AVX2 // AVX2 functions
AVX512BF16 // AVX-512 BFLOAT16 Instructions
AVX512BITALG // AVX-512 Bit Algorithms
AVX512BMM // AVX-512 Bit Manipulation Instructions
AVX512BW // AVX-512 Byte and Word Instructions
AVX512CD // AVX-512 Conflict Detection Instructions
AVX512DQ // AVX-512 Doubleword and Quadword Instructions
@@ -139,6 +148,7 @@ const (
FMA4 // Bulldozer FMA4 functions
FP128 // AMD: When set, the internal FP/SIMD execution datapath is no more than 128-bits wide
FP256 // AMD: When set, the internal FP/SIMD execution datapath is no more than 256-bits wide
FRED // Flexible Return and Event Delivery
FSRM // Fast Short Rep Mov
FXSR // FXSAVE, FXRESTOR instructions, CR4 bit 9
FXSROPT // FXSAVE/FXRSTOR optimizations
@@ -308,6 +318,19 @@ const (
SM3 // SM3 instructions
SM4 // SM4 instructions
SVE // Scalable Vector Extension
SVE2 // Scalable Vector Extension 2
SB // Speculation barrier (SB instruction)
SSBS // Speculative Store Bypass Safe (PSTATE.SSBS)
BTI // Branch Target Identification
FLAGM2 // Condition flag manipulation version 2 (AXFLAG, XAFLAG)
FRINTTS // Floating-point to integer rounding (FRINT32Z, FRINT64Z, etc)
DCPODP // Data cache clean to Point of Deep Persistence (DC CVADP)
BF16 // BFloat16 instructions (BFDOT, BFMMLA, etc)
I8MM // Int8 matrix multiplication (SMMLA, UMMLA, USMMLA)
WFXT // WFE/WFI with timeout (WFET, WFIT)
MOPS // Memory copy and set instructions (CPYF, SETP, etc)
HBC // Hinted conditional branches (BC.cond)
CSSC // Common short sequence compression (ABS, SMAX, UMAX, etc)
// PMU
PMU_FIXEDCOUNTER_CYCLES
@@ -315,6 +338,57 @@ const (
PMU_FIXEDCOUNTER_INSTRUCTIONS
PMU_FIXEDCOUNTER_TOPDOWN_SLOTS
// RISC-V features
RV_IMA // IMA base (Integer, Multiply, Atomic)
RV_C // Compressed instructions
RV_F // Single-precision FP
RV_D // Double-precision FP
RV_V // Vector extension (V)
RV_ZBA // Address generation
RV_ZBB // Basic bit manipulation
RV_ZBC // Carry-less multiplication
RV_ZBS // Single-bit manipulation
RV_ZICOND // Integer conditional operations
RV_ZIHINTPAUSE // Pause hint
RV_ZICBOM // Cache block management operations
RV_ZICBOZ // Cache block zero
RV_ZICBOP // Cache block prefetch
RV_ZFA // Additional floating-point
RV_ZFH // Half-precision FP
RV_ZFHMIN // Minimal half-precision FP
RV_ZTSO // Total store ordering
RV_ZACAS // Atomic CAS
// Scalar cryptography
RV_ZBKB // Bit-manipulation for crypto
RV_ZBKC // Carry-less multiply for crypto
RV_ZBKX // Crossbar permutations
RV_ZKND // NIST Suite: AES decrypt
RV_ZKNE // NIST Suite: AES encrypt
RV_ZKNH // NIST Suite: SHA-2 (SHA-256/SHA-512)
RV_ZKSED // ShangMi Suite: SM4 block cipher
RV_ZKSH // ShangMi Suite: SM3 hash
RV_ZKT // Data-independent execution latency (Crypto)
// Scalar crypto suites (combined from individual extensions)
RV_ZKN // NIST Algorithm Suite (Zknd+Zkne+Zknh+Zbkb+Zbkc+Zbkx+Zkt)
RV_ZKS // ShangMi Algorithm Suite (Zksed+Zksh+Zbkb+Zbkc+Zbkx+Zkt)
// Vector cryptography
RV_ZVBB // Vector Basic Bit-manipulation
RV_ZVBC // Vector Carry-less multiply
RV_ZVKB // Vector Bit-manipulation for crypto
RV_ZVKG // Vector GCM/GMAC
RV_ZVKNED // NIST Suite: Vector AES encrypt+decrypt
RV_ZVKNHA // NIST Suite: Vector SHA-2 (SHA-256)
RV_ZVKNHB // NIST Suite: Vector SHA-2 (SHA-512)
RV_ZVKSED // ShangMi Suite: Vector SM4
RV_ZVKSH // ShangMi Suite: Vector SM3 hash
RV_ZVKT // Vector Data-independent execution latency
// Vector crypto suites (combined from individual extensions)
RV_ZVKNG // NIST Suite with GCM (Zvkned+Zvknhb+Zvkg+Zvkb+Zvkt)
RV_ZVKSG // ShangMi Suite with GCM (Zvksed+Zvksh+Zvkg+Zvkb+Zvkt)
// Keep it last. It automatically defines the size of []flagSet
lastID
@@ -419,8 +493,8 @@ func Detect() {
os.Exit(1)
}
if disableFlag != nil {
s := strings.Split(*disableFlag, ",")
for _, feat := range s {
s := strings.SplitSeq(*disableFlag, ",")
for feat := range s {
feat := ParseFeature(strings.TrimSpace(feat))
if feat != UNKNOWN {
CPU.featureSet.unset(feat)
@@ -471,12 +545,7 @@ func (c *CPUInfo) Has(id FeatureID) bool {
// AnyOf returns whether the CPU supports one or more of the requested features.
func (c CPUInfo) AnyOf(ids ...FeatureID) bool {
for _, id := range ids {
if c.featureSet.inSet(id) {
return true
}
}
return false
return slices.ContainsFunc(ids, c.featureSet.inSet)
}
// Features contains several features combined for a fast check using
@@ -496,6 +565,11 @@ func (c *CPUInfo) HasAll(f Features) bool {
return c.featureSet.hasSetP(f)
}
// HasOneOf returns whether the CPU supports one or more of the requested features.
func (c *CPUInfo) HasOneOf(f Features) bool {
return c.featureSet.hasOneOf(f)
}
// https://en.wikipedia.org/wiki/X86-64#Microarchitecture_levels
var oneOfLevel = CombineFeatures(SYSEE, SYSCALL)
var level1Features = CombineFeatures(CMOV, CMPXCHG8, X87, FXSR, MMX, SSE, SSE2)
@@ -503,6 +577,56 @@ var level2Features = CombineFeatures(CMOV, CMPXCHG8, X87, FXSR, MMX, SSE, SSE2,
var level3Features = CombineFeatures(CMOV, CMPXCHG8, X87, FXSR, MMX, SSE, SSE2, CX16, LAHF, POPCNT, SSE3, SSE4, SSE42, SSSE3, AVX, AVX2, BMI1, BMI2, F16C, FMA3, LZCNT, MOVBE, OSXSAVE)
var level4Features = CombineFeatures(CMOV, CMPXCHG8, X87, FXSR, MMX, SSE, SSE2, CX16, LAHF, POPCNT, SSE3, SSE4, SSE42, SSSE3, AVX, AVX2, BMI1, BMI2, F16C, FMA3, LZCNT, MOVBE, OSXSAVE, AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL)
// RV_CRYPTO_FEATS contains all RISC-V scalar cryptography instruction extensions (excludes Zkt since it is a timing guarantee, not a computational instruction).
var RV_CRYPTO_FEATS = CombineFeatures(RV_ZBKB, RV_ZBKC, RV_ZBKX, RV_ZKND, RV_ZKNE, RV_ZKNH, RV_ZKSED, RV_ZKSH)
// RV_VECTOR_CRYPTO_FEATS contains all RISC-V vector cryptography extensions.
var RV_VECTOR_CRYPTO_FEATS = CombineFeatures(RV_ZVBB, RV_ZVBC, RV_ZVKB, RV_ZVKG, RV_ZVKNED, RV_ZVKNHA, RV_ZVKNHB, RV_ZVKSED, RV_ZVKSH)
// RISC-V application profile feature sets.
// https://github.com/riscv/riscv-profiles
var rvProfile20Features = CombineFeatures(RV_IMA, RV_C, RV_F, RV_D)
var rvProfile22Features = CombineFeatures(RV_IMA, RV_C, RV_F, RV_D, RV_ZBA, RV_ZBB, RV_ZBS, RV_ZFHMIN, RV_ZICBOM, RV_ZICBOP, RV_ZICBOZ, RV_ZIHINTPAUSE)
var rvProfile23Features = CombineFeatures(RV_IMA, RV_C, RV_F, RV_D, RV_ZBA, RV_ZBB, RV_ZBS, RV_ZFHMIN, RV_ZICBOM, RV_ZICBOP, RV_ZICBOZ, RV_ZIHINTPAUSE, RV_V, RV_ZFA, RV_ZICOND, RV_ZVBB, RV_ZVKB)
// RISC-V crypto suites — combined from individual extensions.
var rvZKNFeatures = CombineFeatures(RV_ZKND, RV_ZKNE, RV_ZKNH, RV_ZBKB, RV_ZBKC, RV_ZBKX, RV_ZKT)
var rvZKSFeatures = CombineFeatures(RV_ZKSED, RV_ZKSH, RV_ZBKB, RV_ZBKC, RV_ZBKX, RV_ZKT)
var rvZVKNFeatures = CombineFeatures(RV_ZVKNED, RV_ZVKNHB, RV_ZVKG, RV_ZVKB, RV_ZVKT)
var rvZVKSFeatures = CombineFeatures(RV_ZVKSED, RV_ZVKSH, RV_ZVKG, RV_ZVKB, RV_ZVKT)
// ARM64 architecture levels. armV8Levels[m] is the cumulative set of mandatory
// user-space instruction features added up to and including ARMv8.m that this
// package can detect. EL1/system-only features (PAN, VHE, CSV2/CSV3, ECV, ...)
// are excluded since they are irrelevant to user-space code generation, exactly
// as X64Level ignores non-instruction features.
//
// FEAT_SSBS and FEAT_BTI, although mandatory from ARMv8.5, are intentionally NOT
// required. Both are OS-policy-gated security features (speculative store bypass
// safety and branch-target identification) that Go code generation never depends
// on: their HWCAP/sysctl bits are set only when the OS or hypervisor enables the
// protection, not purely from CPU capability, so they are routinely hidden even
// on capable silicon (neither a Neoverse N2 Linux guest nor Apple Silicon reports
// them). Requiring them would cap such CPUs at v8.4. Both are still detected and
// reported through FeatureSet when present.
// https://go.dev/wiki/MinimumRequirements#arm64
var armV8Levels = [...]Features{
CombineFeatures(FP, ASIMD), // v8.0
CombineFeatures(FP, ASIMD, ATOMICS, CRC32, ASIMDRDM), // v8.1
CombineFeatures(FP, ASIMD, ATOMICS, CRC32, ASIMDRDM, DCPOP), // v8.2
CombineFeatures(FP, ASIMD, ATOMICS, CRC32, ASIMDRDM, DCPOP, JSCVT, FCMA, LRCPC), // v8.3
CombineFeatures(FP, ASIMD, ATOMICS, CRC32, ASIMDRDM, DCPOP, JSCVT, FCMA, LRCPC, TS), // v8.4
CombineFeatures(FP, ASIMD, ATOMICS, CRC32, ASIMDRDM, DCPOP, JSCVT, FCMA, LRCPC, TS, SB, FRINTTS, FLAGM2, DCPODP), // v8.5
CombineFeatures(FP, ASIMD, ATOMICS, CRC32, ASIMDRDM, DCPOP, JSCVT, FCMA, LRCPC, TS, SB, FRINTTS, FLAGM2, DCPODP, BF16, I8MM), // v8.6
CombineFeatures(FP, ASIMD, ATOMICS, CRC32, ASIMDRDM, DCPOP, JSCVT, FCMA, LRCPC, TS, SB, FRINTTS, FLAGM2, DCPODP, BF16, I8MM, WFXT), // v8.7
CombineFeatures(FP, ASIMD, ATOMICS, CRC32, ASIMDRDM, DCPOP, JSCVT, FCMA, LRCPC, TS, SB, FRINTTS, FLAGM2, DCPODP, BF16, I8MM, WFXT, MOPS, HBC), // v8.8
CombineFeatures(FP, ASIMD, ATOMICS, CRC32, ASIMDRDM, DCPOP, JSCVT, FCMA, LRCPC, TS, SB, FRINTTS, FLAGM2, DCPODP, BF16, I8MM, WFXT, MOPS, HBC, CSSC), // v8.9
}
// armCrypto matches the GOARM64 ",crypto" option: FEAT_AES, FEAT_PMULL,
// FEAT_SHA1 and FEAT_SHA256.
var armCrypto = CombineFeatures(AESARM, PMULL, SHA1, SHA2)
// X64Level returns the microarchitecture level detected on the CPU.
// If features are lacking or non x64 mode, 0 is returned.
// See https://en.wikipedia.org/wiki/X86-64#Microarchitecture_levels
@@ -525,6 +649,67 @@ func (c CPUInfo) X64Level() int {
return 0
}
// RVProfile returns the RISC-V application profile level.
// 0 = unknown / base ISA only, 20 = RVA20, 22 = RVA22, 23 = RVA23.
// Returns 0 on non-RISC-V architectures or if not detected.
// https://github.com/riscv/riscv-profiles
func (c CPUInfo) RVProfile() int {
switch {
case c.featureSet.hasSetP(rvProfile23Features):
return 23
case c.featureSet.hasSetP(rvProfile22Features):
return 22
case c.featureSet.hasSetP(rvProfile20Features):
return 20
default:
return 0
}
}
// ARM64Level returns the ARMv8/ARMv9 architecture version supported by the CPU
// as (major, minor), e.g. 8, 4 for ARMv8.4-A or 9, 0 for ARMv9.0-A.
// Only mandatory user-space instruction features are considered, so the result
// is the highest level whose required instructions are all present.
// Returns 0, 0 on non-arm64 CPUs or when feature detection was unavailable.
func (c CPUInfo) ARM64Level() (major, minor int) {
if !c.featureSet.hasSetP(armV8Levels[0]) {
return 0, 0
}
m8 := 0
for m := len(armV8Levels) - 1; m >= 1; m-- {
if c.featureSet.hasSetP(armV8Levels[m]) {
m8 = m
break
}
}
// ARMv9.x mandates everything in ARMv8.(x+5) plus SVE2.
if m8 >= 5 && c.featureSet.inSet(SVE2) {
return 9, m8 - 5
}
return 8, m8
}
// GOARM64 returns a value usable as the GOARM64 build setting for the detected
// CPU, e.g. "v8.4" or "v9.0,crypto". The ",crypto" suffix is appended when AES,
// PMULL, SHA1 and SHA256 are all present; the ",lse" suffix is appended in the
// rare case LSE is present without the rest of the ARMv8.1 feature set.
// Returns "" on non-arm64 CPUs or when feature detection was unavailable.
// See https://go.dev/wiki/MinimumRequirements#arm64
func (c CPUInfo) GOARM64() string {
major, minor := c.ARM64Level()
if major == 0 {
return ""
}
v := fmt.Sprintf("v%d.%d", major, minor)
if major == 8 && minor == 0 && c.featureSet.inSet(ATOMICS) {
v += ",lse"
}
if c.featureSet.hasSetP(armCrypto) {
v += ",crypto"
}
return v
}
// Disable will disable one or several features.
func (c *CPUInfo) Disable(ids ...FeatureID) bool {
for _, id := range ids {
@@ -771,7 +956,7 @@ func flagSetWith(feat ...FeatureID) flagSet {
// Will return UNKNOWN if not found.
func ParseFeature(s string) FeatureID {
s = strings.ToUpper(s)
for i := firstID; i < lastID; i++ {
for i := range lastID {
if i.String() == s {
return i
}
@@ -785,7 +970,7 @@ func (s flagSet) Strings() []string {
return []string{""}
}
r := make([]string, 0)
for i := firstID; i < lastID; i++ {
for i := range lastID {
if s.inSet(i) {
r = append(r, i.String())
}
@@ -806,7 +991,7 @@ func maxFunctionID() uint32 {
func brandName() string {
if maxExtendedFunction() >= 0x80000004 {
v := make([]uint32, 0, 48)
for i := uint32(0); i < 3; i++ {
for i := range uint32(3) {
a, b, c, d := cpuid(0x80000002 + i)
v = append(v, a, b, c, d)
}
@@ -1075,7 +1260,7 @@ func (c *CPUInfo) cacheSize() {
// Hack: When we encounter the same entry 100 times we break.
nSame := 0
var last uint32
for i := uint32(0); i < math.MaxUint32; i++ {
for i := range uint32(math.MaxUint32) {
eax, ebx, ecx, _ := cpuidex(0x8000001D, i)
level := (eax >> 5) & 7
@@ -1329,6 +1514,7 @@ func support() flagSet {
fs.setIf(eax1&(1<<10) != 0, MOVSB_ZL)
fs.setIf(eax1&(1<<11) != 0, STOSB_SHORT)
fs.setIf(eax1&(1<<12) != 0, CMPSB_SCADBS_SHORT)
fs.setIf(eax1&(1<<17) != 0, FRED)
fs.setIf(eax1&(1<<22) != 0, HRESET)
fs.setIf(eax1&(1<<23) != 0, AVXIFMA)
fs.setIf(eax1&(1<<26) != 0, LAM)
@@ -1562,6 +1748,7 @@ func support() flagSet {
fs.setIf((a>>29)&1 == 1, SRSO_NO)
fs.setIf((a>>28)&1 == 1, IBPB_BRTYPE)
fs.setIf((a>>27)&1 == 1, SBPB)
fs.setIf((a>>23)&1 == 1, AVX512BMM)
fs.setIf((c>>1)&1 == 1, TSA_L1_NO)
fs.setIf((c>>2)&1 == 1, TSA_SQ_NO)
fs.setIf((a>>5)&1 == 1, TSA_VERW_CLEAR)
+8 -1
View File
@@ -1,7 +1,6 @@
// Copyright (c) 2015 Klaus Post, released under MIT License. See LICENSE file.
//go:build arm64 && !gccgo && !noasm && !appengine
// +build arm64,!gccgo,!noasm,!appengine
package cpuid
@@ -189,6 +188,7 @@ func addInfo(c *CPUInfo, safe bool) {
f.setIf(instAttrReg0&(0xf<<60) != 0, RNDR)
f.setIf(instAttrReg0&(0xf<<56) != 0, TLB)
f.setIf(instAttrReg0&(0xf<<52) != 0, TS)
f.setIf(instAttrReg0&(0xf<<52) == 2<<52, FLAGM2) // TS == 0b0010 (FEAT_FlagM2)
f.setIf(instAttrReg0&(0xf<<48) != 0, FHM)
f.setIf(instAttrReg0&(0xf<<44) != 0, ASIMDDP)
f.setIf(instAttrReg0&(0xf<<40) != 0, SM4)
@@ -244,6 +244,13 @@ func addInfo(c *CPUInfo, safe bool) {
// fmt.Println("APA")
// }
f.setIf(instAttrReg1&(0xf<<0) != 0, DCPOP)
f.setIf(instAttrReg1&(0xf<<0) == 2<<0, DCPODP) // DPB == 0b0010 (FEAT_DPB2)
// Upper ID_AA64ISAR1_EL1 fields, not in the table above.
f.setIf(instAttrReg1&(0xf<<32) != 0, FRINTTS) // bits [35:32]
f.setIf(instAttrReg1&(0xf<<36) != 0, SB) // bits [39:36]
f.setIf(instAttrReg1&(0xf<<44) != 0, BF16) // bits [47:44]
f.setIf(instAttrReg1&(0xf<<52) != 0, I8MM) // bits [55:52]
// Store
c.featureSet.or(f)
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright (c) 2015 Klaus Post, released under MIT License. See LICENSE file.
//go:build (!amd64 && !386 && !arm64) || gccgo || noasm || appengine
// +build !amd64,!386,!arm64 gccgo noasm appengine
//go:build (!amd64 && !386 && !arm64 && !riscv64) || ((amd64 || 386) && (gccgo || noasm || appengine))
package cpuid
+19
View File
@@ -0,0 +1,19 @@
// Copyright (c) 2015 Klaus Post, released under MIT License. See LICENSE file.
//go:build arm64 && (gccgo || noasm || appengine)
package cpuid
func initCPU() {
cpuid = func(uint32) (a, b, c, d uint32) { return 0, 0, 0, 0 }
cpuidex = func(x, y uint32) (a, b, c, d uint32) { return 0, 0, 0, 0 }
xgetbv = func(uint32) (a, b uint32) { return 0, 0 }
rdtscpAsm = func() (a, b, c, d uint32) { return 0, 0, 0, 0 }
}
func addInfo(c *CPUInfo, safe bool) {
c.CacheLine = 64
detectOS(c)
}
func getVectorLength() (vl, pl uint64) { return 0, 0 }
+16
View File
@@ -0,0 +1,16 @@
// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file.
package cpuid
func getVectorLength() (vl, pl uint64) { return 0, 0 }
func initCPU() {
cpuid = func(uint32) (a, b, c, d uint32) { return 0, 0, 0, 0 }
cpuidex = func(x, y uint32) (a, b, c, d uint32) { return 0, 0, 0, 0 }
xgetbv = func(uint32) (a, b uint32) { return 0, 0 }
rdtscpAsm = func() (a, b, c, d uint32) { return 0, 0, 0, 0 }
}
func addInfo(c *CPUInfo, safe bool) {
detectOS(c)
}
-1
View File
@@ -1,7 +1,6 @@
// Copyright (c) 2015 Klaus Post, released under MIT License. See LICENSE file.
//go:build (386 && !gccgo && !noasm && !appengine) || (amd64 && !gccgo && !noasm && !appengine)
// +build 386,!gccgo,!noasm,!appengine amd64,!gccgo,!noasm,!appengine
package cpuid
+289 -225
View File
@@ -29,234 +29,292 @@ func _() {
_ = x[AVX2-19]
_ = x[AVX512BF16-20]
_ = x[AVX512BITALG-21]
_ = x[AVX512BW-22]
_ = x[AVX512CD-23]
_ = x[AVX512DQ-24]
_ = x[AVX512ER-25]
_ = x[AVX512F-26]
_ = x[AVX512FP16-27]
_ = x[AVX512IFMA-28]
_ = x[AVX512PF-29]
_ = x[AVX512VBMI-30]
_ = x[AVX512VBMI2-31]
_ = x[AVX512VL-32]
_ = x[AVX512VNNI-33]
_ = x[AVX512VP2INTERSECT-34]
_ = x[AVX512VPOPCNTDQ-35]
_ = x[AVXIFMA-36]
_ = x[AVXNECONVERT-37]
_ = x[AVXSLOW-38]
_ = x[AVXVNNI-39]
_ = x[AVXVNNIINT8-40]
_ = x[AVXVNNIINT16-41]
_ = x[BHI_CTRL-42]
_ = x[BMI1-43]
_ = x[BMI2-44]
_ = x[CETIBT-45]
_ = x[CETSS-46]
_ = x[CLDEMOTE-47]
_ = x[CLMUL-48]
_ = x[CLZERO-49]
_ = x[CMOV-50]
_ = x[CMPCCXADD-51]
_ = x[CMPSB_SCADBS_SHORT-52]
_ = x[CMPXCHG8-53]
_ = x[CPBOOST-54]
_ = x[CPPC-55]
_ = x[CX16-56]
_ = x[EFER_LMSLE_UNS-57]
_ = x[ENQCMD-58]
_ = x[ERMS-59]
_ = x[F16C-60]
_ = x[FLUSH_L1D-61]
_ = x[FMA3-62]
_ = x[FMA4-63]
_ = x[FP128-64]
_ = x[FP256-65]
_ = x[FSRM-66]
_ = x[FXSR-67]
_ = x[FXSROPT-68]
_ = x[GFNI-69]
_ = x[HLE-70]
_ = x[HRESET-71]
_ = x[HTT-72]
_ = x[HWA-73]
_ = x[HYBRID_CPU-74]
_ = x[HYPERVISOR-75]
_ = x[IA32_ARCH_CAP-76]
_ = x[IA32_CORE_CAP-77]
_ = x[IBPB-78]
_ = x[IBPB_BRTYPE-79]
_ = x[IBRS-80]
_ = x[IBRS_PREFERRED-81]
_ = x[IBRS_PROVIDES_SMP-82]
_ = x[IBS-83]
_ = x[IBSBRNTRGT-84]
_ = x[IBSFETCHSAM-85]
_ = x[IBSFFV-86]
_ = x[IBSOPCNT-87]
_ = x[IBSOPCNTEXT-88]
_ = x[IBSOPSAM-89]
_ = x[IBSRDWROPCNT-90]
_ = x[IBSRIPINVALIDCHK-91]
_ = x[IBS_FETCH_CTLX-92]
_ = x[IBS_OPDATA4-93]
_ = x[IBS_OPFUSE-94]
_ = x[IBS_PREVENTHOST-95]
_ = x[IBS_ZEN4-96]
_ = x[IDPRED_CTRL-97]
_ = x[INT_WBINVD-98]
_ = x[INVLPGB-99]
_ = x[KEYLOCKER-100]
_ = x[KEYLOCKERW-101]
_ = x[LAHF-102]
_ = x[LAM-103]
_ = x[LBRVIRT-104]
_ = x[LZCNT-105]
_ = x[MCAOVERFLOW-106]
_ = x[MCDT_NO-107]
_ = x[MCOMMIT-108]
_ = x[MD_CLEAR-109]
_ = x[MMX-110]
_ = x[MMXEXT-111]
_ = x[MOVBE-112]
_ = x[MOVDIR64B-113]
_ = x[MOVDIRI-114]
_ = x[MOVSB_ZL-115]
_ = x[MOVU-116]
_ = x[MPX-117]
_ = x[MSRIRC-118]
_ = x[MSRLIST-119]
_ = x[MSR_PAGEFLUSH-120]
_ = x[NRIPS-121]
_ = x[NX-122]
_ = x[OSXSAVE-123]
_ = x[PCONFIG-124]
_ = x[POPCNT-125]
_ = x[PPIN-126]
_ = x[PREFETCHI-127]
_ = x[PSFD-128]
_ = x[RDPRU-129]
_ = x[RDRAND-130]
_ = x[RDSEED-131]
_ = x[RDTSCP-132]
_ = x[RRSBA_CTRL-133]
_ = x[RTM-134]
_ = x[RTM_ALWAYS_ABORT-135]
_ = x[SBPB-136]
_ = x[SERIALIZE-137]
_ = x[SEV-138]
_ = x[SEV_64BIT-139]
_ = x[SEV_ALTERNATIVE-140]
_ = x[SEV_DEBUGSWAP-141]
_ = x[SEV_ES-142]
_ = x[SEV_RESTRICTED-143]
_ = x[SEV_SNP-144]
_ = x[SGX-145]
_ = x[SGXLC-146]
_ = x[SGXPQC-147]
_ = x[SHA-148]
_ = x[SME-149]
_ = x[SME_COHERENT-150]
_ = x[SM3_X86-151]
_ = x[SM4_X86-152]
_ = x[SPEC_CTRL_SSBD-153]
_ = x[SRBDS_CTRL-154]
_ = x[SRSO_MSR_FIX-155]
_ = x[SRSO_NO-156]
_ = x[SRSO_USER_KERNEL_NO-157]
_ = x[SSE-158]
_ = x[SSE2-159]
_ = x[SSE3-160]
_ = x[SSE4-161]
_ = x[SSE42-162]
_ = x[SSE4A-163]
_ = x[SSSE3-164]
_ = x[STIBP-165]
_ = x[STIBP_ALWAYSON-166]
_ = x[STOSB_SHORT-167]
_ = x[SUCCOR-168]
_ = x[SVM-169]
_ = x[SVMDA-170]
_ = x[SVMFBASID-171]
_ = x[SVML-172]
_ = x[SVMNP-173]
_ = x[SVMPF-174]
_ = x[SVMPFT-175]
_ = x[SYSCALL-176]
_ = x[SYSEE-177]
_ = x[TBM-178]
_ = x[TDX_GUEST-179]
_ = x[TLB_FLUSH_NESTED-180]
_ = x[TME-181]
_ = x[TOPEXT-182]
_ = x[TSA_L1_NO-183]
_ = x[TSA_SQ_NO-184]
_ = x[TSA_VERW_CLEAR-185]
_ = x[TSCRATEMSR-186]
_ = x[TSXLDTRK-187]
_ = x[VAES-188]
_ = x[VMCBCLEAN-189]
_ = x[VMPL-190]
_ = x[VMSA_REGPROT-191]
_ = x[VMX-192]
_ = x[VPCLMULQDQ-193]
_ = x[VTE-194]
_ = x[WAITPKG-195]
_ = x[WBNOINVD-196]
_ = x[WRMSRNS-197]
_ = x[X87-198]
_ = x[XGETBV1-199]
_ = x[XOP-200]
_ = x[XSAVE-201]
_ = x[XSAVEC-202]
_ = x[XSAVEOPT-203]
_ = x[XSAVES-204]
_ = x[AESARM-205]
_ = x[ARMCPUID-206]
_ = x[ASIMD-207]
_ = x[ASIMDDP-208]
_ = x[ASIMDHP-209]
_ = x[ASIMDRDM-210]
_ = x[ATOMICS-211]
_ = x[CRC32-212]
_ = x[DCPOP-213]
_ = x[EVTSTRM-214]
_ = x[FCMA-215]
_ = x[FHM-216]
_ = x[FP-217]
_ = x[FPHP-218]
_ = x[GPA-219]
_ = x[JSCVT-220]
_ = x[LRCPC-221]
_ = x[PMULL-222]
_ = x[RNDR-223]
_ = x[TLB-224]
_ = x[TS-225]
_ = x[SHA1-226]
_ = x[SHA2-227]
_ = x[SHA3-228]
_ = x[SHA512-229]
_ = x[SM3-230]
_ = x[SM4-231]
_ = x[SVE-232]
_ = x[PMU_FIXEDCOUNTER_CYCLES-233]
_ = x[PMU_FIXEDCOUNTER_REFCYCLES-234]
_ = x[PMU_FIXEDCOUNTER_INSTRUCTIONS-235]
_ = x[PMU_FIXEDCOUNTER_TOPDOWN_SLOTS-236]
_ = x[lastID-237]
_ = x[AVX512BMM-22]
_ = x[AVX512BW-23]
_ = x[AVX512CD-24]
_ = x[AVX512DQ-25]
_ = x[AVX512ER-26]
_ = x[AVX512F-27]
_ = x[AVX512FP16-28]
_ = x[AVX512IFMA-29]
_ = x[AVX512PF-30]
_ = x[AVX512VBMI-31]
_ = x[AVX512VBMI2-32]
_ = x[AVX512VL-33]
_ = x[AVX512VNNI-34]
_ = x[AVX512VP2INTERSECT-35]
_ = x[AVX512VPOPCNTDQ-36]
_ = x[AVXIFMA-37]
_ = x[AVXNECONVERT-38]
_ = x[AVXSLOW-39]
_ = x[AVXVNNI-40]
_ = x[AVXVNNIINT8-41]
_ = x[AVXVNNIINT16-42]
_ = x[BHI_CTRL-43]
_ = x[BMI1-44]
_ = x[BMI2-45]
_ = x[CETIBT-46]
_ = x[CETSS-47]
_ = x[CLDEMOTE-48]
_ = x[CLMUL-49]
_ = x[CLZERO-50]
_ = x[CMOV-51]
_ = x[CMPCCXADD-52]
_ = x[CMPSB_SCADBS_SHORT-53]
_ = x[CMPXCHG8-54]
_ = x[CPBOOST-55]
_ = x[CPPC-56]
_ = x[CX16-57]
_ = x[EFER_LMSLE_UNS-58]
_ = x[ENQCMD-59]
_ = x[ERMS-60]
_ = x[F16C-61]
_ = x[FLUSH_L1D-62]
_ = x[FMA3-63]
_ = x[FMA4-64]
_ = x[FP128-65]
_ = x[FP256-66]
_ = x[FRED-67]
_ = x[FSRM-68]
_ = x[FXSR-69]
_ = x[FXSROPT-70]
_ = x[GFNI-71]
_ = x[HLE-72]
_ = x[HRESET-73]
_ = x[HTT-74]
_ = x[HWA-75]
_ = x[HYBRID_CPU-76]
_ = x[HYPERVISOR-77]
_ = x[IA32_ARCH_CAP-78]
_ = x[IA32_CORE_CAP-79]
_ = x[IBPB-80]
_ = x[IBPB_BRTYPE-81]
_ = x[IBRS-82]
_ = x[IBRS_PREFERRED-83]
_ = x[IBRS_PROVIDES_SMP-84]
_ = x[IBS-85]
_ = x[IBSBRNTRGT-86]
_ = x[IBSFETCHSAM-87]
_ = x[IBSFFV-88]
_ = x[IBSOPCNT-89]
_ = x[IBSOPCNTEXT-90]
_ = x[IBSOPSAM-91]
_ = x[IBSRDWROPCNT-92]
_ = x[IBSRIPINVALIDCHK-93]
_ = x[IBS_FETCH_CTLX-94]
_ = x[IBS_OPDATA4-95]
_ = x[IBS_OPFUSE-96]
_ = x[IBS_PREVENTHOST-97]
_ = x[IBS_ZEN4-98]
_ = x[IDPRED_CTRL-99]
_ = x[INT_WBINVD-100]
_ = x[INVLPGB-101]
_ = x[KEYLOCKER-102]
_ = x[KEYLOCKERW-103]
_ = x[LAHF-104]
_ = x[LAM-105]
_ = x[LBRVIRT-106]
_ = x[LZCNT-107]
_ = x[MCAOVERFLOW-108]
_ = x[MCDT_NO-109]
_ = x[MCOMMIT-110]
_ = x[MD_CLEAR-111]
_ = x[MMX-112]
_ = x[MMXEXT-113]
_ = x[MOVBE-114]
_ = x[MOVDIR64B-115]
_ = x[MOVDIRI-116]
_ = x[MOVSB_ZL-117]
_ = x[MOVU-118]
_ = x[MPX-119]
_ = x[MSRIRC-120]
_ = x[MSRLIST-121]
_ = x[MSR_PAGEFLUSH-122]
_ = x[NRIPS-123]
_ = x[NX-124]
_ = x[OSXSAVE-125]
_ = x[PCONFIG-126]
_ = x[POPCNT-127]
_ = x[PPIN-128]
_ = x[PREFETCHI-129]
_ = x[PSFD-130]
_ = x[RDPRU-131]
_ = x[RDRAND-132]
_ = x[RDSEED-133]
_ = x[RDTSCP-134]
_ = x[RRSBA_CTRL-135]
_ = x[RTM-136]
_ = x[RTM_ALWAYS_ABORT-137]
_ = x[SBPB-138]
_ = x[SERIALIZE-139]
_ = x[SEV-140]
_ = x[SEV_64BIT-141]
_ = x[SEV_ALTERNATIVE-142]
_ = x[SEV_DEBUGSWAP-143]
_ = x[SEV_ES-144]
_ = x[SEV_RESTRICTED-145]
_ = x[SEV_SNP-146]
_ = x[SGX-147]
_ = x[SGXLC-148]
_ = x[SGXPQC-149]
_ = x[SHA-150]
_ = x[SME-151]
_ = x[SME_COHERENT-152]
_ = x[SM3_X86-153]
_ = x[SM4_X86-154]
_ = x[SPEC_CTRL_SSBD-155]
_ = x[SRBDS_CTRL-156]
_ = x[SRSO_MSR_FIX-157]
_ = x[SRSO_NO-158]
_ = x[SRSO_USER_KERNEL_NO-159]
_ = x[SSE-160]
_ = x[SSE2-161]
_ = x[SSE3-162]
_ = x[SSE4-163]
_ = x[SSE42-164]
_ = x[SSE4A-165]
_ = x[SSSE3-166]
_ = x[STIBP-167]
_ = x[STIBP_ALWAYSON-168]
_ = x[STOSB_SHORT-169]
_ = x[SUCCOR-170]
_ = x[SVM-171]
_ = x[SVMDA-172]
_ = x[SVMFBASID-173]
_ = x[SVML-174]
_ = x[SVMNP-175]
_ = x[SVMPF-176]
_ = x[SVMPFT-177]
_ = x[SYSCALL-178]
_ = x[SYSEE-179]
_ = x[TBM-180]
_ = x[TDX_GUEST-181]
_ = x[TLB_FLUSH_NESTED-182]
_ = x[TME-183]
_ = x[TOPEXT-184]
_ = x[TSA_L1_NO-185]
_ = x[TSA_SQ_NO-186]
_ = x[TSA_VERW_CLEAR-187]
_ = x[TSCRATEMSR-188]
_ = x[TSXLDTRK-189]
_ = x[VAES-190]
_ = x[VMCBCLEAN-191]
_ = x[VMPL-192]
_ = x[VMSA_REGPROT-193]
_ = x[VMX-194]
_ = x[VPCLMULQDQ-195]
_ = x[VTE-196]
_ = x[WAITPKG-197]
_ = x[WBNOINVD-198]
_ = x[WRMSRNS-199]
_ = x[X87-200]
_ = x[XGETBV1-201]
_ = x[XOP-202]
_ = x[XSAVE-203]
_ = x[XSAVEC-204]
_ = x[XSAVEOPT-205]
_ = x[XSAVES-206]
_ = x[AESARM-207]
_ = x[ARMCPUID-208]
_ = x[ASIMD-209]
_ = x[ASIMDDP-210]
_ = x[ASIMDHP-211]
_ = x[ASIMDRDM-212]
_ = x[ATOMICS-213]
_ = x[CRC32-214]
_ = x[DCPOP-215]
_ = x[EVTSTRM-216]
_ = x[FCMA-217]
_ = x[FHM-218]
_ = x[FP-219]
_ = x[FPHP-220]
_ = x[GPA-221]
_ = x[JSCVT-222]
_ = x[LRCPC-223]
_ = x[PMULL-224]
_ = x[RNDR-225]
_ = x[TLB-226]
_ = x[TS-227]
_ = x[SHA1-228]
_ = x[SHA2-229]
_ = x[SHA3-230]
_ = x[SHA512-231]
_ = x[SM3-232]
_ = x[SM4-233]
_ = x[SVE-234]
_ = x[SVE2-235]
_ = x[SB-236]
_ = x[SSBS-237]
_ = x[BTI-238]
_ = x[FLAGM2-239]
_ = x[FRINTTS-240]
_ = x[DCPODP-241]
_ = x[BF16-242]
_ = x[I8MM-243]
_ = x[WFXT-244]
_ = x[MOPS-245]
_ = x[HBC-246]
_ = x[CSSC-247]
_ = x[PMU_FIXEDCOUNTER_CYCLES-248]
_ = x[PMU_FIXEDCOUNTER_REFCYCLES-249]
_ = x[PMU_FIXEDCOUNTER_INSTRUCTIONS-250]
_ = x[PMU_FIXEDCOUNTER_TOPDOWN_SLOTS-251]
_ = x[RV_IMA-252]
_ = x[RV_C-253]
_ = x[RV_F-254]
_ = x[RV_D-255]
_ = x[RV_V-256]
_ = x[RV_ZBA-257]
_ = x[RV_ZBB-258]
_ = x[RV_ZBC-259]
_ = x[RV_ZBS-260]
_ = x[RV_ZICOND-261]
_ = x[RV_ZIHINTPAUSE-262]
_ = x[RV_ZICBOM-263]
_ = x[RV_ZICBOZ-264]
_ = x[RV_ZICBOP-265]
_ = x[RV_ZFA-266]
_ = x[RV_ZFH-267]
_ = x[RV_ZFHMIN-268]
_ = x[RV_ZTSO-269]
_ = x[RV_ZACAS-270]
_ = x[RV_ZBKB-271]
_ = x[RV_ZBKC-272]
_ = x[RV_ZBKX-273]
_ = x[RV_ZKND-274]
_ = x[RV_ZKNE-275]
_ = x[RV_ZKNH-276]
_ = x[RV_ZKSED-277]
_ = x[RV_ZKSH-278]
_ = x[RV_ZKT-279]
_ = x[RV_ZKN-280]
_ = x[RV_ZKS-281]
_ = x[RV_ZVBB-282]
_ = x[RV_ZVBC-283]
_ = x[RV_ZVKB-284]
_ = x[RV_ZVKG-285]
_ = x[RV_ZVKNED-286]
_ = x[RV_ZVKNHA-287]
_ = x[RV_ZVKNHB-288]
_ = x[RV_ZVKSED-289]
_ = x[RV_ZVKSH-290]
_ = x[RV_ZVKT-291]
_ = x[RV_ZVKNG-292]
_ = x[RV_ZVKSG-293]
_ = x[lastID-294]
_ = x[firstID-0]
}
const _FeatureID_name = "firstIDADXAESNIAMD3DNOWAMD3DNOWEXTAMXBF16AMXFP16AMXINT8AMXFP8AMXTILEAMXTF32AMXCOMPLEXAMXTRANSPOSEAPX_FAVXAVX10AVX10_128AVX10_256AVX10_512AVX2AVX512BF16AVX512BITALGAVX512BWAVX512CDAVX512DQAVX512ERAVX512FAVX512FP16AVX512IFMAAVX512PFAVX512VBMIAVX512VBMI2AVX512VLAVX512VNNIAVX512VP2INTERSECTAVX512VPOPCNTDQAVXIFMAAVXNECONVERTAVXSLOWAVXVNNIAVXVNNIINT8AVXVNNIINT16BHI_CTRLBMI1BMI2CETIBTCETSSCLDEMOTECLMULCLZEROCMOVCMPCCXADDCMPSB_SCADBS_SHORTCMPXCHG8CPBOOSTCPPCCX16EFER_LMSLE_UNSENQCMDERMSF16CFLUSH_L1DFMA3FMA4FP128FP256FSRMFXSRFXSROPTGFNIHLEHRESETHTTHWAHYBRID_CPUHYPERVISORIA32_ARCH_CAPIA32_CORE_CAPIBPBIBPB_BRTYPEIBRSIBRS_PREFERREDIBRS_PROVIDES_SMPIBSIBSBRNTRGTIBSFETCHSAMIBSFFVIBSOPCNTIBSOPCNTEXTIBSOPSAMIBSRDWROPCNTIBSRIPINVALIDCHKIBS_FETCH_CTLXIBS_OPDATA4IBS_OPFUSEIBS_PREVENTHOSTIBS_ZEN4IDPRED_CTRLINT_WBINVDINVLPGBKEYLOCKERKEYLOCKERWLAHFLAMLBRVIRTLZCNTMCAOVERFLOWMCDT_NOMCOMMITMD_CLEARMMXMMXEXTMOVBEMOVDIR64BMOVDIRIMOVSB_ZLMOVUMPXMSRIRCMSRLISTMSR_PAGEFLUSHNRIPSNXOSXSAVEPCONFIGPOPCNTPPINPREFETCHIPSFDRDPRURDRANDRDSEEDRDTSCPRRSBA_CTRLRTMRTM_ALWAYS_ABORTSBPBSERIALIZESEVSEV_64BITSEV_ALTERNATIVESEV_DEBUGSWAPSEV_ESSEV_RESTRICTEDSEV_SNPSGXSGXLCSGXPQCSHASMESME_COHERENTSM3_X86SM4_X86SPEC_CTRL_SSBDSRBDS_CTRLSRSO_MSR_FIXSRSO_NOSRSO_USER_KERNEL_NOSSESSE2SSE3SSE4SSE42SSE4ASSSE3STIBPSTIBP_ALWAYSONSTOSB_SHORTSUCCORSVMSVMDASVMFBASIDSVMLSVMNPSVMPFSVMPFTSYSCALLSYSEETBMTDX_GUESTTLB_FLUSH_NESTEDTMETOPEXTTSA_L1_NOTSA_SQ_NOTSA_VERW_CLEARTSCRATEMSRTSXLDTRKVAESVMCBCLEANVMPLVMSA_REGPROTVMXVPCLMULQDQVTEWAITPKGWBNOINVDWRMSRNSX87XGETBV1XOPXSAVEXSAVECXSAVEOPTXSAVESAESARMARMCPUIDASIMDASIMDDPASIMDHPASIMDRDMATOMICSCRC32DCPOPEVTSTRMFCMAFHMFPFPHPGPAJSCVTLRCPCPMULLRNDRTLBTSSHA1SHA2SHA3SHA512SM3SM4SVEPMU_FIXEDCOUNTER_CYCLESPMU_FIXEDCOUNTER_REFCYCLESPMU_FIXEDCOUNTER_INSTRUCTIONSPMU_FIXEDCOUNTER_TOPDOWN_SLOTSlastID"
const _FeatureID_name = "firstIDADXAESNIAMD3DNOWAMD3DNOWEXTAMXBF16AMXFP16AMXINT8AMXFP8AMXTILEAMXTF32AMXCOMPLEXAMXTRANSPOSEAPX_FAVXAVX10AVX10_128AVX10_256AVX10_512AVX2AVX512BF16AVX512BITALGAVX512BMMAVX512BWAVX512CDAVX512DQAVX512ERAVX512FAVX512FP16AVX512IFMAAVX512PFAVX512VBMIAVX512VBMI2AVX512VLAVX512VNNIAVX512VP2INTERSECTAVX512VPOPCNTDQAVXIFMAAVXNECONVERTAVXSLOWAVXVNNIAVXVNNIINT8AVXVNNIINT16BHI_CTRLBMI1BMI2CETIBTCETSSCLDEMOTECLMULCLZEROCMOVCMPCCXADDCMPSB_SCADBS_SHORTCMPXCHG8CPBOOSTCPPCCX16EFER_LMSLE_UNSENQCMDERMSF16CFLUSH_L1DFMA3FMA4FP128FP256FREDFSRMFXSRFXSROPTGFNIHLEHRESETHTTHWAHYBRID_CPUHYPERVISORIA32_ARCH_CAPIA32_CORE_CAPIBPBIBPB_BRTYPEIBRSIBRS_PREFERREDIBRS_PROVIDES_SMPIBSIBSBRNTRGTIBSFETCHSAMIBSFFVIBSOPCNTIBSOPCNTEXTIBSOPSAMIBSRDWROPCNTIBSRIPINVALIDCHKIBS_FETCH_CTLXIBS_OPDATA4IBS_OPFUSEIBS_PREVENTHOSTIBS_ZEN4IDPRED_CTRLINT_WBINVDINVLPGBKEYLOCKERKEYLOCKERWLAHFLAMLBRVIRTLZCNTMCAOVERFLOWMCDT_NOMCOMMITMD_CLEARMMXMMXEXTMOVBEMOVDIR64BMOVDIRIMOVSB_ZLMOVUMPXMSRIRCMSRLISTMSR_PAGEFLUSHNRIPSNXOSXSAVEPCONFIGPOPCNTPPINPREFETCHIPSFDRDPRURDRANDRDSEEDRDTSCPRRSBA_CTRLRTMRTM_ALWAYS_ABORTSBPBSERIALIZESEVSEV_64BITSEV_ALTERNATIVESEV_DEBUGSWAPSEV_ESSEV_RESTRICTEDSEV_SNPSGXSGXLCSGXPQCSHASMESME_COHERENTSM3_X86SM4_X86SPEC_CTRL_SSBDSRBDS_CTRLSRSO_MSR_FIXSRSO_NOSRSO_USER_KERNEL_NOSSESSE2SSE3SSE4SSE42SSE4ASSSE3STIBPSTIBP_ALWAYSONSTOSB_SHORTSUCCORSVMSVMDASVMFBASIDSVMLSVMNPSVMPFSVMPFTSYSCALLSYSEETBMTDX_GUESTTLB_FLUSH_NESTEDTMETOPEXTTSA_L1_NOTSA_SQ_NOTSA_VERW_CLEARTSCRATEMSRTSXLDTRKVAESVMCBCLEANVMPLVMSA_REGPROTVMXVPCLMULQDQVTEWAITPKGWBNOINVDWRMSRNSX87XGETBV1XOPXSAVEXSAVECXSAVEOPTXSAVESAESARMARMCPUIDASIMDASIMDDPASIMDHPASIMDRDMATOMICSCRC32DCPOPEVTSTRMFCMAFHMFPFPHPGPAJSCVTLRCPCPMULLRNDRTLBTSSHA1SHA2SHA3SHA512SM3SM4SVESVE2SBSSBSBTIFLAGM2FRINTTSDCPODPBF16I8MMWFXTMOPSHBCCSSCPMU_FIXEDCOUNTER_CYCLESPMU_FIXEDCOUNTER_REFCYCLESPMU_FIXEDCOUNTER_INSTRUCTIONSPMU_FIXEDCOUNTER_TOPDOWN_SLOTSRV_IMARV_CRV_FRV_DRV_VRV_ZBARV_ZBBRV_ZBCRV_ZBSRV_ZICONDRV_ZIHINTPAUSERV_ZICBOMRV_ZICBOZRV_ZICBOPRV_ZFARV_ZFHRV_ZFHMINRV_ZTSORV_ZACASRV_ZBKBRV_ZBKCRV_ZBKXRV_ZKNDRV_ZKNERV_ZKNHRV_ZKSEDRV_ZKSHRV_ZKTRV_ZKNRV_ZKSRV_ZVBBRV_ZVBCRV_ZVKBRV_ZVKGRV_ZVKNEDRV_ZVKNHARV_ZVKNHBRV_ZVKSEDRV_ZVKSHRV_ZVKTRV_ZVKNGRV_ZVKSGlastID"
var _FeatureID_index = [...]uint16{0, 7, 10, 15, 23, 34, 41, 48, 55, 61, 68, 75, 85, 97, 102, 105, 110, 119, 128, 137, 141, 151, 163, 171, 179, 187, 195, 202, 212, 222, 230, 240, 251, 259, 269, 287, 302, 309, 321, 328, 335, 346, 358, 366, 370, 374, 380, 385, 393, 398, 404, 408, 417, 435, 443, 450, 454, 458, 472, 478, 482, 486, 495, 499, 503, 508, 513, 517, 521, 528, 532, 535, 541, 544, 547, 557, 567, 580, 593, 597, 608, 612, 626, 643, 646, 656, 667, 673, 681, 692, 700, 712, 728, 742, 753, 763, 778, 786, 797, 807, 814, 823, 833, 837, 840, 847, 852, 863, 870, 877, 885, 888, 894, 899, 908, 915, 923, 927, 930, 936, 943, 956, 961, 963, 970, 977, 983, 987, 996, 1000, 1005, 1011, 1017, 1023, 1033, 1036, 1052, 1056, 1065, 1068, 1077, 1092, 1105, 1111, 1125, 1132, 1135, 1140, 1146, 1149, 1152, 1164, 1171, 1178, 1192, 1202, 1214, 1221, 1240, 1243, 1247, 1251, 1255, 1260, 1265, 1270, 1275, 1289, 1300, 1306, 1309, 1314, 1323, 1327, 1332, 1337, 1343, 1350, 1355, 1358, 1367, 1383, 1386, 1392, 1401, 1410, 1424, 1434, 1442, 1446, 1455, 1459, 1471, 1474, 1484, 1487, 1494, 1502, 1509, 1512, 1519, 1522, 1527, 1533, 1541, 1547, 1553, 1561, 1566, 1573, 1580, 1588, 1595, 1600, 1605, 1612, 1616, 1619, 1621, 1625, 1628, 1633, 1638, 1643, 1647, 1650, 1652, 1656, 1660, 1664, 1670, 1673, 1676, 1679, 1702, 1728, 1757, 1787, 1793}
var _FeatureID_index = [...]uint16{0, 7, 10, 15, 23, 34, 41, 48, 55, 61, 68, 75, 85, 97, 102, 105, 110, 119, 128, 137, 141, 151, 163, 172, 180, 188, 196, 204, 211, 221, 231, 239, 249, 260, 268, 278, 296, 311, 318, 330, 337, 344, 355, 367, 375, 379, 383, 389, 394, 402, 407, 413, 417, 426, 444, 452, 459, 463, 467, 481, 487, 491, 495, 504, 508, 512, 517, 522, 526, 530, 534, 541, 545, 548, 554, 557, 560, 570, 580, 593, 606, 610, 621, 625, 639, 656, 659, 669, 680, 686, 694, 705, 713, 725, 741, 755, 766, 776, 791, 799, 810, 820, 827, 836, 846, 850, 853, 860, 865, 876, 883, 890, 898, 901, 907, 912, 921, 928, 936, 940, 943, 949, 956, 969, 974, 976, 983, 990, 996, 1000, 1009, 1013, 1018, 1024, 1030, 1036, 1046, 1049, 1065, 1069, 1078, 1081, 1090, 1105, 1118, 1124, 1138, 1145, 1148, 1153, 1159, 1162, 1165, 1177, 1184, 1191, 1205, 1215, 1227, 1234, 1253, 1256, 1260, 1264, 1268, 1273, 1278, 1283, 1288, 1302, 1313, 1319, 1322, 1327, 1336, 1340, 1345, 1350, 1356, 1363, 1368, 1371, 1380, 1396, 1399, 1405, 1414, 1423, 1437, 1447, 1455, 1459, 1468, 1472, 1484, 1487, 1497, 1500, 1507, 1515, 1522, 1525, 1532, 1535, 1540, 1546, 1554, 1560, 1566, 1574, 1579, 1586, 1593, 1601, 1608, 1613, 1618, 1625, 1629, 1632, 1634, 1638, 1641, 1646, 1651, 1656, 1660, 1663, 1665, 1669, 1673, 1677, 1683, 1686, 1689, 1692, 1696, 1698, 1702, 1705, 1711, 1718, 1724, 1728, 1732, 1736, 1740, 1743, 1747, 1770, 1796, 1825, 1855, 1861, 1865, 1869, 1873, 1877, 1883, 1889, 1895, 1901, 1910, 1924, 1933, 1942, 1951, 1957, 1963, 1972, 1979, 1987, 1994, 2001, 2008, 2015, 2022, 2029, 2037, 2044, 2050, 2056, 2062, 2069, 2076, 2083, 2090, 2099, 2108, 2117, 2126, 2134, 2141, 2149, 2157, 2163}
func (i FeatureID) String() string {
if i < 0 || i >= FeatureID(len(_FeatureID_index)-1) {
idx := int(i) - 0
if i < 0 || idx >= len(_FeatureID_index)-1 {
return "FeatureID(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _FeatureID_name[_FeatureID_index[i]:_FeatureID_index[i+1]]
return _FeatureID_name[_FeatureID_index[idx]:_FeatureID_index[idx+1]]
}
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
@@ -293,16 +351,22 @@ func _() {
_ = x[ACRN-28]
_ = x[SRE-29]
_ = x[Apple-30]
_ = x[lastVendor-31]
_ = x[SiFive-31]
_ = x[StarFive-32]
_ = x[THead-33]
_ = x[Andes-34]
_ = x[SpacemiT-35]
_ = x[lastVendor-36]
}
const _Vendor_name = "VendorUnknownIntelAMDVIATransmetaNSCKVMMSVMVMwareXenHVMBhyveHygonSiSRDCAmpereARMBroadcomCaviumDECFujitsuInfineonMotorolaNVIDIAAMCCQualcommMarvellQEMUQNXACRNSREApplelastVendor"
const _Vendor_name = "VendorUnknownIntelAMDVIATransmetaNSCKVMMSVMVMwareXenHVMBhyveHygonSiSRDCAmpereARMBroadcomCaviumDECFujitsuInfineonMotorolaNVIDIAAMCCQualcommMarvellQEMUQNXACRNSREAppleSiFiveStarFiveTHeadAndesSpacemiTlastVendor"
var _Vendor_index = [...]uint8{0, 13, 18, 21, 24, 33, 36, 39, 43, 49, 55, 60, 65, 68, 71, 77, 80, 88, 94, 97, 104, 112, 120, 126, 130, 138, 145, 149, 152, 156, 159, 164, 174}
var _Vendor_index = [...]uint8{0, 13, 18, 21, 24, 33, 36, 39, 43, 49, 55, 60, 65, 68, 71, 77, 80, 88, 94, 97, 104, 112, 120, 126, 130, 138, 145, 149, 152, 156, 159, 164, 170, 178, 183, 188, 196, 206}
func (i Vendor) String() string {
if i < 0 || i >= Vendor(len(_Vendor_index)-1) {
idx := int(i) - 0
if i < 0 || idx >= len(_Vendor_index)-1 {
return "Vendor(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Vendor_name[_Vendor_index[i]:_Vendor_index[i+1]]
return _Vendor_name[_Vendor_index[idx]:_Vendor_index[idx+1]]
}
+13
View File
@@ -126,4 +126,17 @@ func tryToFillCPUInfoFomSysctl(c *CPUInfo) {
setFeature(c, SM3, "hw.optional.arm.FEAT_SM3") // SM3 instructions
setFeature(c, SM4, "hw.optional.arm.FEAT_SM4") // SM4 instructions
setFeature(c, SVE, "hw.optional.arm.FEAT_SVE") // Scalable Vector Extension
setFeature(c, SVE2, "hw.optional.arm.FEAT_SVE2") // Scalable Vector Extension 2
setFeature(c, SB, "hw.optional.arm.FEAT_SB") // Speculation barrier
setFeature(c, SSBS, "hw.optional.arm.FEAT_SSBS") // Speculative Store Bypass Safe
setFeature(c, BTI, "hw.optional.arm.FEAT_BTI") // Branch Target Identification
setFeature(c, FLAGM2, "hw.optional.arm.FEAT_FlagM2") // Condition flag manipulation version 2
setFeature(c, FRINTTS, "hw.optional.arm.FEAT_FRINTTS") // Floating-point to integer rounding
setFeature(c, DCPODP, "hw.optional.arm.FEAT_DPB2") // Data cache clean to Point of Deep Persistence
setFeature(c, BF16, "hw.optional.arm.FEAT_BF16") // BFloat16 instructions
setFeature(c, I8MM, "hw.optional.arm.FEAT_I8MM") // Int8 matrix multiplication
setFeature(c, WFXT, "hw.optional.arm.FEAT_WFxT") // WFE/WFI with timeout
setFeature(c, MOPS, "hw.optional.arm.FEAT_MOPS") // Memory copy and set instructions
setFeature(c, HBC, "hw.optional.arm.FEAT_HBC") // Hinted conditional branches
setFeature(c, CSSC, "hw.optional.arm.FEAT_CSSC") // Common short sequence compression
}
+52 -36
View File
@@ -115,15 +115,19 @@ const (
hwcap2_POE = 1 << 63
)
// hwcap2 holds AT_HWCAP2. Unlike hwcap, the arm64 runtime does not expose it
// through internal/cpu, so detectOS reads it from the auxiliary vector.
var hwcap2 uint
func detectOS(c *CPUInfo) bool {
// For now assuming no hyperthreading is reasonable.
c.LogicalCores = runtime.NumCPU()
c.PhysicalCores = c.LogicalCores
c.ThreadsPerCore = 1
if hwcap == 0 {
// We did not get values from the runtime.
// Try reading /proc/self/auxv
// hwcap is provided by the runtime through the internal/cpu.HWCap linkname,
// but the runtime does not expose HWCAP2 on arm64. Read the auxiliary vector
// directly to obtain hwcap2 (and hwcap when the linkname is unavailable).
if hwcap == 0 || hwcap2 == 0 {
// From https://github.com/golang/sys
const (
_AT_HWCAP = 16
@@ -132,37 +136,34 @@ func detectOS(c *CPUInfo) bool {
uintSize = int(32 << (^uint(0) >> 63))
)
buf, err := ioutil.ReadFile("/proc/self/auxv")
if err != nil {
// e.g. on android /proc/self/auxv is not accessible, so silently
// ignore the error and leave Initialized = false. On some
// architectures (e.g. arm64) doinit() implements a fallback
// readout and will set Initialized = true again.
return false
}
bo := binary.LittleEndian
for len(buf) >= 2*(uintSize/8) {
var tag, val uint
switch uintSize {
case 32:
tag = uint(bo.Uint32(buf[0:]))
val = uint(bo.Uint32(buf[4:]))
buf = buf[8:]
case 64:
tag = uint(bo.Uint64(buf[0:]))
val = uint(bo.Uint64(buf[8:]))
buf = buf[16:]
}
switch tag {
case _AT_HWCAP:
hwcap = val
case _AT_HWCAP2:
// Not used
// e.g. on android /proc/self/auxv is not accessible, so silently ignore
// the error and fall back to whatever the runtime provided.
if buf, err := ioutil.ReadFile("/proc/self/auxv"); err == nil {
bo := binary.LittleEndian
for len(buf) >= 2*(uintSize/8) {
var tag, val uint
switch uintSize {
case 32:
tag = uint(bo.Uint32(buf[0:]))
val = uint(bo.Uint32(buf[4:]))
buf = buf[8:]
case 64:
tag = uint(bo.Uint64(buf[0:]))
val = uint(bo.Uint64(buf[8:]))
buf = buf[16:]
}
switch tag {
case _AT_HWCAP:
hwcap = val
case _AT_HWCAP2:
hwcap2 = val
}
}
}
if hwcap == 0 {
return false
}
}
if hwcap == 0 {
// Nothing detected, e.g. on android or a restricted environment.
return false
}
// HWCap was populated by the runtime from the auxiliary vector.
@@ -184,9 +185,9 @@ func detectOS(c *CPUInfo) bool {
c.featureSet.setIf(isSet(hwcap, hwcap_JSCVT), JSCVT)
c.featureSet.setIf(isSet(hwcap, hwcap_LRCPC), LRCPC)
c.featureSet.setIf(isSet(hwcap, hwcap_PMULL), PMULL)
c.featureSet.setIf(isSet(hwcap, hwcap2_RNG), RNDR)
// c.featureSet.setIf(isSet(hwcap, hwcap_), TLB)
// c.featureSet.setIf(isSet(hwcap, hwcap_), TS)
c.featureSet.setIf(isSet(hwcap2, hwcap2_RNG), RNDR)
// TLB (FEAT_TLBIOS/TLBIRANGE) has no HWCAP bit; only detectable via ID registers.
c.featureSet.setIf(isSet(hwcap, hwcap_FLAGM), TS)
c.featureSet.setIf(isSet(hwcap, hwcap_SHA1), SHA1)
c.featureSet.setIf(isSet(hwcap, hwcap_SHA2), SHA2)
c.featureSet.setIf(isSet(hwcap, hwcap_SHA3), SHA3)
@@ -194,6 +195,21 @@ func detectOS(c *CPUInfo) bool {
c.featureSet.setIf(isSet(hwcap, hwcap_SM3), SM3)
c.featureSet.setIf(isSet(hwcap, hwcap_SM4), SM4)
c.featureSet.setIf(isSet(hwcap, hwcap_SVE), SVE)
c.featureSet.setIf(isSet(hwcap, hwcap_SB), SB)
c.featureSet.setIf(isSet(hwcap, hwcap_SSBS), SSBS)
// Features reported through the second hardware capability word (HWCAP2).
c.featureSet.setIf(isSet(hwcap2, hwcap2_SVE2), SVE2)
c.featureSet.setIf(isSet(hwcap2, hwcap2_BTI), BTI)
c.featureSet.setIf(isSet(hwcap2, hwcap2_FLAGM2), FLAGM2)
c.featureSet.setIf(isSet(hwcap2, hwcap2_FRINT), FRINTTS)
c.featureSet.setIf(isSet(hwcap2, hwcap2_DCPODP), DCPODP)
c.featureSet.setIf(isSet(hwcap2, hwcap2_BF16), BF16)
c.featureSet.setIf(isSet(hwcap2, hwcap2_I8MM), I8MM)
c.featureSet.setIf(isSet(hwcap2, hwcap2_WFXT), WFXT)
c.featureSet.setIf(isSet(hwcap2, hwcap2_MOPS), MOPS)
c.featureSet.setIf(isSet(hwcap2, hwcap2_HBC), HBC)
c.featureSet.setIf(isSet(hwcap2, hwcap2_CSSC), CSSC)
// The Samsung S9+ kernel reports support for atomics, but not all cores
// actually support them, resulting in SIGILL. See issue #28431.
+225
View File
@@ -0,0 +1,225 @@
// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file.
package cpuid
import (
"bufio"
"os"
"runtime"
"strconv"
"strings"
"unsafe"
"golang.org/x/sys/unix"
)
const __NR_riscv_hwprobe = 258
type riscvHWProbePair struct {
key int64
value uint64
}
// Keys from linux/include/uapi/asm/hwprobe.h
const (
riscv_hwprobe_key_mvendorid = 0
riscv_hwprobe_key_marchid = 1
riscv_hwprobe_key_mimpid = 2
riscv_hwprobe_key_base_behavior = 3
riscv_hwprobe_key_ima_ext_0 = 4
riscv_hwprobe_key_cpuperf_0 = 5
riscv_hwprobe_key_zicbom_block_size = 12
)
// Bits from linux/arch/riscv/include/uapi/asm/hwprobe.h
const (
riscv_hwprobe_ima_fd = 1 << 0
riscv_hwprobe_ima_c = 1 << 1
riscv_hwprobe_ima_v = 1 << 2
riscv_hwprobe_ext_zba = 1 << 3
riscv_hwprobe_ext_zbb = 1 << 4
riscv_hwprobe_ext_zbs = 1 << 5
riscv_hwprobe_ext_zicboz = 1 << 6
riscv_hwprobe_ext_zbc = 1 << 7
riscv_hwprobe_ext_zbkb = 1 << 8
riscv_hwprobe_ext_zbkc = 1 << 9
riscv_hwprobe_ext_zbkx = 1 << 10
riscv_hwprobe_ext_zknd = 1 << 11
riscv_hwprobe_ext_zkne = 1 << 12
riscv_hwprobe_ext_zknh = 1 << 13
riscv_hwprobe_ext_zksed = 1 << 14
riscv_hwprobe_ext_zksh = 1 << 15
riscv_hwprobe_ext_zkt = 1 << 16
riscv_hwprobe_ext_zvbb = 1 << 17
riscv_hwprobe_ext_zvbc = 1 << 18
riscv_hwprobe_ext_zvkb = 1 << 19
riscv_hwprobe_ext_zvkg = 1 << 20
riscv_hwprobe_ext_zvkned = 1 << 21
riscv_hwprobe_ext_zvknha = 1 << 22
riscv_hwprobe_ext_zvknhb = 1 << 23
riscv_hwprobe_ext_zvksed = 1 << 24
riscv_hwprobe_ext_zvksh = 1 << 25
riscv_hwprobe_ext_zvkt = 1 << 26
riscv_hwprobe_ext_zfh = 1 << 27
riscv_hwprobe_ext_zfhmin = 1 << 28
riscv_hwprobe_ext_zihintntl = 1 << 29
riscv_hwprobe_ext_zvfh = 1 << 30
riscv_hwprobe_ext_zvfhmin = 1 << 31
riscv_hwprobe_ext_zfa = 1 << 32
riscv_hwprobe_ext_ztso = 1 << 33
riscv_hwprobe_ext_zacas = 1 << 34
riscv_hwprobe_ext_zicond = 1 << 35
riscv_hwprobe_ext_zihintpause = 1 << 36
riscv_hwprobe_ext_zicbom = 1 << 55
riscv_hwprobe_ext_zicbop = 1 << 60
)
func riscvHWProbe(pairs []riscvHWProbePair) int64 {
if len(pairs) == 0 {
return -1
}
ret, _, _ := unix.Syscall6(__NR_riscv_hwprobe,
uintptr(unsafe.Pointer(&pairs[0])),
uintptr(len(pairs)),
0, 0, 0, 0)
return int64(ret)
}
func detectOS(c *CPUInfo) bool {
c.LogicalCores = runtime.NumCPU()
c.PhysicalCores = c.LogicalCores
c.ThreadsPerCore = 1
pairs := []riscvHWProbePair{
{key: riscv_hwprobe_key_mvendorid},
{key: riscv_hwprobe_key_marchid},
{key: riscv_hwprobe_key_mimpid},
{key: riscv_hwprobe_key_ima_ext_0},
{key: riscv_hwprobe_key_zicbom_block_size},
}
ret := riscvHWProbe(pairs)
if ret == 0 && pairs[3].value != ^uint64(0) {
detectFromHWProbe(c, pairs)
if pairs[4].value != ^uint64(0) && pairs[4].value > 0 {
c.CacheLine = int(pairs[4].value)
}
return true
}
c.CacheLine = detectCacheLine()
return detectFromCPUInfo(c)
}
func detectFromHWProbe(c *CPUInfo, pairs []riscvHWProbePair) {
if pairs[0].value != ^uint64(0) {
c.VendorID = riscvVendorID(pairs[0].value)
c.VendorString = c.VendorID.String()
}
if pairs[1].value != ^uint64(0) {
c.Model = int(pairs[1].value)
}
if pairs[2].value != ^uint64(0) {
c.Family = int(pairs[2].value)
}
imaExt := pairs[3].value
if imaExt&riscv_hwprobe_ima_fd != 0 {
c.featureSet.set(RV_D)
c.featureSet.set(RV_F)
}
c.featureSet.setIf(imaExt&riscv_hwprobe_ima_c != 0, RV_C)
c.featureSet.setIf(imaExt&riscv_hwprobe_ima_v != 0, RV_V)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zba != 0, RV_ZBA)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zbb != 0, RV_ZBB)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zbc != 0, RV_ZBC)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zbs != 0, RV_ZBS)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zicbom != 0, RV_ZICBOM)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zicboz != 0, RV_ZICBOZ)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zicbop != 0, RV_ZICBOP)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zicond != 0, RV_ZICOND)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zihintpause != 0, RV_ZIHINTPAUSE)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zfa != 0, RV_ZFA)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zfh != 0, RV_ZFH)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zfhmin != 0, RV_ZFHMIN)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_ztso != 0, RV_ZTSO)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zacas != 0, RV_ZACAS)
// Scalar cryptography
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zbkb != 0, RV_ZBKB)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zbkc != 0, RV_ZBKC)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zbkx != 0, RV_ZBKX)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zknd != 0, RV_ZKND)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zkne != 0, RV_ZKNE)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zknh != 0, RV_ZKNH)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zksed != 0, RV_ZKSED)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zksh != 0, RV_ZKSH)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zkt != 0, RV_ZKT)
// Vector cryptography
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zvbb != 0, RV_ZVBB)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zvbc != 0, RV_ZVBC)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zvkb != 0, RV_ZVKB)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zvkg != 0, RV_ZVKG)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zvkned != 0, RV_ZVKNED)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zvknha != 0, RV_ZVKNHA)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zvknhb != 0, RV_ZVKNHB)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zvksed != 0, RV_ZVKSED)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zvksh != 0, RV_ZVKSH)
c.featureSet.setIf(imaExt&riscv_hwprobe_ext_zvkt != 0, RV_ZVKT)
// Crypto suites (combined from individual features)
c.featureSet.setIf(c.featureSet.hasSetP(rvZKNFeatures), RV_ZKN)
c.featureSet.setIf(c.featureSet.hasSetP(rvZKSFeatures), RV_ZKS)
c.featureSet.setIf(c.featureSet.hasSetP(rvZVKNFeatures), RV_ZVKNG)
c.featureSet.setIf(c.featureSet.hasSetP(rvZVKSFeatures), RV_ZVKSG)
// Every Linux-capable riscv64 core has I, M, A base.
c.featureSet.set(RV_IMA)
}
func detectFromCPUInfo(c *CPUInfo) bool {
f, err := os.Open("/proc/cpuinfo")
if err != nil {
return false
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
fields := strings.SplitN(line, ":", 2)
if len(fields) < 2 {
continue
}
key := strings.TrimSpace(fields[0])
value := strings.TrimSpace(fields[1])
switch key {
case "isa":
parseISAString(c, value)
case "mvendorid":
if vid, err := strconv.ParseUint(value, 0, 64); err == nil {
c.VendorID = riscvVendorID(vid)
c.VendorString = c.VendorID.String()
}
case "uarch":
c.BrandName = value
}
}
return scanner.Err() == nil
}
func detectCacheLine() int {
data, err := os.ReadFile("/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size")
if err != nil {
return 0
}
if n, err := strconv.Atoi(strings.TrimSpace(string(data))); err == nil && n > 0 {
return n
}
return 0
}
-1
View File
@@ -1,7 +1,6 @@
// Copyright (c) 2020 Klaus Post, released under MIT License. See LICENSE file.
//go:build arm64 && !linux && !darwin
// +build arm64,!linux,!darwin
package cpuid
+14
View File
@@ -0,0 +1,14 @@
// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file.
//go:build riscv64 && !linux
package cpuid
import "runtime"
func detectOS(c *CPUInfo) bool {
c.PhysicalCores = runtime.NumCPU()
c.ThreadsPerCore = 1
c.LogicalCores = c.PhysicalCores
return false
}
-1
View File
@@ -1,7 +1,6 @@
// Copyright (c) 2021 Klaus Post, released under MIT License. See LICENSE file.
//go:build nounsafe
// +build nounsafe
package cpuid
-1
View File
@@ -1,7 +1,6 @@
// Copyright (c) 2021 Klaus Post, released under MIT License. See LICENSE file.
//go:build !nounsafe
// +build !nounsafe
package cpuid
+93
View File
@@ -0,0 +1,93 @@
// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file.
package cpuid
import "strings"
func parseISAString(c *CPUInfo, isa string) {
isa = strings.ToLower(isa)
extMap := make(map[string]bool)
for ext := range strings.SplitSeq(isa, "_") {
ext = strings.TrimSpace(ext)
if strings.HasPrefix(ext, "rv64") {
extMap["i"] = true
for _, ch := range ext[4:] {
extMap[string(ch)] = true
}
} else if ext != "" {
extMap[ext] = true
}
}
if extMap["g"] {
extMap["i"] = true
extMap["m"] = true
extMap["a"] = true
extMap["f"] = true
extMap["d"] = true
}
c.featureSet.setIf(extMap["i"] && extMap["m"] && extMap["a"], RV_IMA)
c.featureSet.setIf(extMap["c"], RV_C)
c.featureSet.setIf(extMap["f"], RV_F)
c.featureSet.setIf(extMap["d"], RV_D)
c.featureSet.setIf(extMap["v"], RV_V)
c.featureSet.setIf(extMap["zihintpause"], RV_ZIHINTPAUSE)
c.featureSet.setIf(extMap["zba"], RV_ZBA)
c.featureSet.setIf(extMap["zbb"], RV_ZBB)
c.featureSet.setIf(extMap["zbc"], RV_ZBC)
c.featureSet.setIf(extMap["zbs"], RV_ZBS)
c.featureSet.setIf(extMap["zicond"], RV_ZICOND)
c.featureSet.setIf(extMap["zicbom"], RV_ZICBOM)
c.featureSet.setIf(extMap["zicboz"], RV_ZICBOZ)
c.featureSet.setIf(extMap["zicbop"], RV_ZICBOP)
c.featureSet.setIf(extMap["zfa"], RV_ZFA)
c.featureSet.setIf(extMap["zfh"], RV_ZFH)
c.featureSet.setIf(extMap["zfhmin"], RV_ZFHMIN)
c.featureSet.setIf(extMap["ztso"], RV_ZTSO)
c.featureSet.setIf(extMap["zacas"], RV_ZACAS)
// Scalar cryptography
c.featureSet.setIf(extMap["zbkb"], RV_ZBKB)
c.featureSet.setIf(extMap["zbkc"], RV_ZBKC)
c.featureSet.setIf(extMap["zbkx"], RV_ZBKX)
c.featureSet.setIf(extMap["zknd"], RV_ZKND)
c.featureSet.setIf(extMap["zkne"], RV_ZKNE)
c.featureSet.setIf(extMap["zknh"], RV_ZKNH)
c.featureSet.setIf(extMap["zksed"], RV_ZKSED)
c.featureSet.setIf(extMap["zksh"], RV_ZKSH)
c.featureSet.setIf(extMap["zkt"], RV_ZKT)
// Vector cryptography
c.featureSet.setIf(extMap["zvbb"], RV_ZVBB)
c.featureSet.setIf(extMap["zvbc"], RV_ZVBC)
c.featureSet.setIf(extMap["zvkb"], RV_ZVKB)
c.featureSet.setIf(extMap["zvkg"], RV_ZVKG)
c.featureSet.setIf(extMap["zvkned"], RV_ZVKNED)
c.featureSet.setIf(extMap["zvknha"], RV_ZVKNHA)
c.featureSet.setIf(extMap["zvknhb"], RV_ZVKNHB)
c.featureSet.setIf(extMap["zvksed"], RV_ZVKSED)
c.featureSet.setIf(extMap["zvksh"], RV_ZVKSH)
c.featureSet.setIf(extMap["zvkt"], RV_ZVKT)
// Crypto suites (combined from individual features or bundle tokens)
c.featureSet.setIf(extMap["zkn"] || c.featureSet.hasSetP(rvZKNFeatures), RV_ZKN)
c.featureSet.setIf(extMap["zks"] || c.featureSet.hasSetP(rvZKSFeatures), RV_ZKS)
c.featureSet.setIf(extMap["zvkng"] || c.featureSet.hasSetP(rvZVKNFeatures), RV_ZVKNG)
c.featureSet.setIf(extMap["zvksg"] || c.featureSet.hasSetP(rvZVKSFeatures), RV_ZVKSG)
}
var riscvVendorMap = map[uint64]Vendor{
0x489: SiFive,
0x5b7: StarFive,
0x5b1: THead,
0x31e: Andes,
0x710: SpacemiT,
}
func riscvVendorID(mvendorid uint64) Vendor {
if v, ok := riscvVendorMap[mvendorid]; ok {
return v
}
return VendorUnknown
}
+5 -1
View File
@@ -24,6 +24,7 @@ var (
err8141QComponentStart = "expecting only one q-component (starting with the ?= sequence) [col %d]"
err8141MalformedRComp = "expecting a non-empty r-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]"
err8141MalformedQComp = "expecting a non-empty q-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]"
errInvalidSyntax = "invalid URN syntax [col %d]"
)
var _toStateActions []byte = []byte{
0, 0, 0, 0, 0, 0, 0, 0,
@@ -4358,7 +4359,7 @@ func (m *machine) Parse(input []byte) (*URN, error) {
if m.parsingMode != RFC8141Only {
// Throw an error when:
// - we are entering here matching the the prefix in the namespace identifier part
// - we are entering here matching the prefix in the namespace identifier part
// - looking ahead (3 chars) we find a colon
if pos := m.p + 3; pos < m.pe && m.data[pos] == 58 && output.prefix != "" {
m.err = fmt.Errorf(errNoUrnWithinID, pos)
@@ -5026,6 +5027,9 @@ func (m *machine) Parse(input []byte) (*URN, error) {
}
if m.cs < firstFinal || m.cs == enFail {
if m.err == nil {
m.err = fmt.Errorf(errInvalidSyntax, m.p)
}
return nil, m.err
}
+6 -2
View File
@@ -24,6 +24,7 @@ var (
err8141QComponentStart = "expecting only one q-component (starting with the ?= sequence) [col %d]"
err8141MalformedRComp = "expecting a non-empty r-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]"
err8141MalformedQComp = "expecting a non-empty q-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]"
errInvalidSyntax = "invalid URN syntax [col %d]"
)
%%{
@@ -48,7 +49,7 @@ action set_pre {
action throw_pre_urn_err {
if m.parsingMode != RFC8141Only {
// Throw an error when:
// - we are entering here matching the the prefix in the namespace identifier part
// - we are entering here matching the prefix in the namespace identifier part
// - looking ahead (3 chars) we find a colon
if pos := m.p + 3; pos < m.pe && m.data[pos] == 58 && output.prefix != "" {
m.err = fmt.Errorf(errNoUrnWithinID, pos)
@@ -366,6 +367,9 @@ func (m *machine) Parse(input []byte) (*URN, error) {
%% write exec;
if m.cs < first_final || m.cs == en_fail {
if m.err == nil {
m.err = fmt.Errorf(errInvalidSyntax, m.p)
}
return nil, m.err
}
@@ -383,4 +387,4 @@ func (m *machine) WithParsingMode(x ParsingMode) {
m.startParsingAt = en_scim_only
}
m.parsingModeSet = true
}
}
+4 -4
View File
@@ -8,7 +8,7 @@ import (
const errInvalidURN = "invalid URN: %s"
// URN represents an Uniform Resource Name.
// URN represents a Uniform Resource Name.
//
// The general form represented is:
//
@@ -32,7 +32,7 @@ type URN struct {
// Normalize turns the receiving URN into its norm version.
//
// Which means: lowercase prefix, lowercase namespace identifier, and immutate namespace specific string chars (except <hex> tokens which are lowercased).
// Which means: lowercase prefix, lowercase namespace identifier, and leave namespace-specific string chars unchanged (except <hex> tokens which are lowercased).
func (u *URN) Normalize() *URN {
return &URN{
prefix: "urn",
@@ -82,10 +82,10 @@ func (u *URN) String() string {
return res
}
// Parse is responsible to create an URN instance from a byte array matching the correct URN syntax (RFC 2141).
// Parse is responsible for creating a URN instance from a byte array matching the correct URN syntax (RFC 2141).
func Parse(u []byte, options ...Option) (*URN, bool) {
urn, err := NewMachine(options...).Parse(u)
if err != nil {
if err != nil || urn == nil {
return nil, false
}
+9 -2
View File
@@ -423,8 +423,15 @@ func goVRelease(pVTab unsafe.Pointer, isDestroy C.int) *C.char {
} else {
err = vt.vTab.Disconnect()
}
// The vtab is gone as far as SQLite is concerned regardless of the
// callback result, so release the handle either way.
if err != nil && isDestroy == 1 {
// SQLite retains p->pVtab when xDestroy fails and later calls
// xDisconnect on the same object; keep the handle registered so
// that call can resolve it (a missing handle panics above).
return mPrintf("%s", err.Error())
}
// On xDisconnect (success or error) SQLite discards the vtab object,
// and on successful xDestroy it clears p->pVtab; release the handle
// in both cases.
deleteHandle(pVTab)
if err != nil {
return mPrintf("%s", err.Error())
+1
View File
@@ -5,3 +5,4 @@ golangci-lint
functional_tests
.idea
vendor/
.branch-validate/
+31 -1
View File
@@ -1,6 +1,6 @@
/*
* MinIO Go Library for Amazon S3 Compatible Cloud Storage
* Copyright 2020 MinIO, Inc.
* Copyright 2026 MinIO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -18,14 +18,44 @@ package minio
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/minio/minio-go/v7/pkg/policy"
"github.com/minio/minio-go/v7/pkg/s3utils"
)
// SetCannedBucketPolicy sets a canned (predefined) access policy on a bucket.
// This is a convenience method that translates predefined access levels
// (readonly, writeonly, readwrite) into the corresponding bucket policy.
// If access is empty or results in no policy statements, the existing bucket policy will be removed.
//
// Parameters:
// - ctx: Context for request cancellation and timeout
// - bucketName: Name of the bucket
// - access: Canned access level (policy.BucketPolicyNone, policy.BucketPolicyReadOnly, policy.BucketPolicyWriteOnly, policy.BucketPolicyReadWrite)
//
// Returns an error if the operation fails.
func (c *Client) SetCannedBucketPolicy(ctx context.Context, bucketName string, bucketPolicy policy.BucketPolicy) error {
if !bucketPolicy.IsValidBucketPolicy() {
return fmt.Errorf("invalid bucket policy %q", bucketPolicy)
}
p := policy.BucketAccessPolicy{Version: "2012-10-17"}
p.Statements = policy.SetPolicy(p.Statements, bucketPolicy, bucketName, "")
if len(p.Statements) == 0 {
return c.SetBucketPolicy(ctx, bucketName, "")
}
policyB, e := json.Marshal(p)
if e != nil {
return e
}
return c.SetBucketPolicy(ctx, bucketName, string(policyB))
}
// SetBucketPolicy sets the access permissions policy on an existing bucket.
// The policy should be a valid JSON string that conforms to the IAM policy format.
// If policy is an empty string, the existing bucket policy will be removed.
+15
View File
@@ -386,6 +386,7 @@ func (c *Client) copyObjectPartDo(ctx context.Context, srcBucket, srcObject, des
return p, err
}
p.PartNumber, p.ETag = partID, cpObjRes.ETag
cpObjRes.setChecksums(&p)
return p, nil
}
@@ -424,6 +425,7 @@ func (c *Client) uploadPartCopy(ctx context.Context, bucket, object, uploadID st
return p, err
}
p.PartNumber, p.ETag = partNumber, cpObjRes.ETag
cpObjRes.setChecksums(&p)
return p, nil
}
@@ -531,6 +533,19 @@ func (c *Client) ComposeObject(ctx context.Context, dst CopyDestOptions, srcs ..
userTags = srcObjectInfos[0].UserTags
}
// Set the requested checksum algorithm on the multipart upload.
if dst.ChecksumType.IsSet() {
meta := make(map[string]string, len(userMeta)+2)
for k, v := range userMeta {
meta[k] = v
}
meta[amzChecksumAlgo] = dst.ChecksumType.String()
if dst.ChecksumType.FullObjectRequested() {
meta[amzChecksumMode] = ChecksumFullObjectMode.String()
}
userMeta = meta
}
uploadID, err := c.newUploadID(ctx, dst.Bucket, dst.Object, PutObjectOptions{
ServerSideEncryption: dst.Encryption,
UserMetadata: userMeta,
+21 -1
View File
@@ -184,10 +184,30 @@ type ObjectInfo struct {
// eg: x-amz-meta-*, content-encoding etc.
Metadata http.Header `json:"metadata" xml:"-"`
// x-amz-meta-* headers stripped "x-amz-meta-" prefix containing the first value.
// Headers is the unfiltered set of response headers from the
// HEAD or GET request that produced this ObjectInfo, e.g.
// Content-Range for ranged requests. RFC 2047-encoded
// x-amz-meta-*/x-minio-meta-* values appear MIME-decoded, matching
// Metadata. Set only when the object info is parsed from an HTTP
// object response (StatObject, GetObject); nil elsewhere, e.g. in
// ListObjects results, on error paths, or for RDMA-backed GetObject.
// It aliases the response headers and must be treated as read-only.
Headers http.Header `json:"rawHeaders,omitempty" xml:"-"`
// UserMetadata contains x-amz-meta-* user metadata.
// StatObject and GetObject return it with the "X-Amz-Meta-" prefix
// stripped; list results with WithMetadata keep the exact values stored
// on the object (prefixed keys plus system entries such as content-type).
// Only returned by MinIO servers.
UserMetadata StringMap `json:"userMetadata,omitempty"`
// UserMetadataStripped is the user metadata from list results in the
// keyed form StatObject and GetObject return in UserMetadata:
// x-amz-meta-* entries with the "X-Amz-Meta-" prefix stripped and
// values passed through verbatim.
// Only populated by MinIO servers when listing with WithMetadata.
UserMetadataStripped StringMap `json:"userMetadataStripped,omitempty" xml:"-"`
// x-amz-tagging values in their k/v values.
// Only returned by MinIO servers.
UserTags URLMap `json:"userTags,omitempty" xml:"UserTags"`
+23 -1
View File
@@ -72,7 +72,7 @@ func (c *Client) FGetObject(ctx context.Context, bucketName, objectName, filePat
filePartPath := filepath.Join(filepath.Dir(filePath), sum256Hex([]byte(filepath.Base(filePath)+objectStat.ETag))+".part.minio")
// If exists, open in append mode. If not create it as a part file.
filePart, err := os.OpenFile(filePartPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
filePart, err := os.OpenFile(filePartPath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0o600)
if err != nil {
return err
}
@@ -98,19 +98,41 @@ func (c *Client) FGetObject(ctx context.Context, bucketName, objectName, filePat
// appropriate range offsets to read from.
if st.Size() > 0 {
opts.SetRange(st.Size(), 0)
if opts.Checksum && objectStat.ChecksumMode == ChecksumFullObjectMode.String() {
if hasherReader := c.newChecksumVerifyingReader(objectStat); hasherReader != nil {
// Read existing file data into hash.
if _, err = io.CopyN(hasherReader.Hash, filePart, st.Size()); err != nil {
_ = hasherReader.Close()
return err
}
opts.checkSumReader = hasherReader
}
}
}
// Seek to current position for incoming reader.
objectReader, objectStat, _, err := c.getObject(ctx, bucketName, objectName, opts)
if err != nil {
if opts.checkSumReader != nil {
_ = opts.checkSumReader.Close()
}
return err
}
defer objectReader.Close()
// Write to the part file.
if _, err = io.CopyN(filePart, objectReader, objectStat.Size); err != nil {
return err
}
// Verify the checksum of the downloaded object before committing the file.
if cr, ok := objectReader.(*checksumVerifyingReader); ok {
if err = cr.VerifyChecksum(); err != nil {
return err
}
}
// Close the file before rename, this is specifically needed for Windows users.
closeAndRemove = false
if err = filePart.Close(); err != nil {
+153 -38
View File
@@ -81,6 +81,8 @@ func (c *Client) GetObject(ctx context.Context, bucketName, objectName string, o
reqCh := make(chan getRequest)
// Create response channel.
resCh := make(chan getResponse)
// record original range header for stat operation.
originalRangeHeader := opts.Header().Get("Range")
// This routine feeds partial object data as and when the caller reads.
go func() {
@@ -115,6 +117,12 @@ func (c *Client) GetObject(ctx context.Context, bucketName, objectName string, o
httpReader, objectInfo, _, err = c.getObject(gctx, bucketName, objectName, opts)
if err != nil {
resCh <- getResponse{Error: err}
// An unsatisfiable range is recoverable: the caller
// may Seek or ReadAt within bounds next, so keep
// serving requests instead of ending the stream.
if ToErrorResponse(err).Code == InvalidRange {
continue
}
return
}
etag = objectInfo.ETag
@@ -141,19 +149,35 @@ func (c *Client) GetObject(ctx context.Context, bucketName, objectName string, o
// it to io.EOF - return unexpected EOF.
err = io.ErrUnexpectedEOF
}
// when doing a readAt, we can't reuse the httpReader for next read action.
if req.isReadAt {
httpReader.Close()
httpReader = nil
}
objectSize := int64(0)
// case for ReadFull with range request
if !req.isReadAt && req.Offset == 0 {
objectSize = objectInfo.Size
}
// Send back the first response.
resCh <- getResponse{
ObjectSize: objectSize,
objectInfo: objectInfo,
Size: size,
Error: err,
didRead: true,
}
} else {
// First request is a Stat or Seek call.
// Only need to run a StatObject until an actual Read or ReadAt request comes through.
if originalRangeHeader == "" {
// First request is a Seek call.
// Only need to run a StatObject until an actual Read request comes through.
// Remove range header if already set, for stat Operations to get original file size.
delete(opts.headers, "Range")
// Remove range header if already set, for stat Operations to get original file size.
delete(opts.headers, "Range")
} else {
opts.headers["Range"] = originalRangeHeader
}
objectInfo, err = c.StatObject(gctx, bucketName, objectName, StatObjectOptions(opts))
if err != nil {
resCh <- getResponse{
@@ -165,12 +189,17 @@ func (c *Client) GetObject(ctx context.Context, bucketName, objectName string, o
etag = objectInfo.ETag
// Send back the first response.
resCh <- getResponse{
ObjectSize: objectInfo.Size,
objectInfo: objectInfo,
}
}
} else if req.settingObjectInfo { // Request is just to get objectInfo.
// Remove range header if already set, for stat Operations to get original file size.
delete(opts.headers, "Range")
if originalRangeHeader == "" {
delete(opts.headers, "Range")
} else {
opts.headers["Range"] = originalRangeHeader
}
// Check whether this is snowball
// if yes do not use If-Match feature
// it doesn't work.
@@ -187,16 +216,22 @@ func (c *Client) GetObject(ctx context.Context, bucketName, objectName string, o
}
// Send back the objectInfo.
resCh <- getResponse{
ObjectSize: objectInfo.Size,
objectInfo: objectInfo,
}
} else {
objectSize := int64(0)
renewReader := false
// Offset changes fetch the new object at an Offset.
// Because the httpReader may not be set by the first
// request if it was a stat or seek it must be checked
// if the object has been read or not to only initialize
// new ones when they haven't been already.
// All readAt requests are new requests.
if req.DidOffsetChange || !req.beenRead {
// A nil httpReader means the previous fetch failed and
// left no stream, so a new one must be established
// regardless of the offset bookkeeping.
if req.DidOffsetChange || !req.beenRead || httpReader == nil {
// Check whether this is snowball
// if yes do not use If-Match feature
// it doesn't work.
@@ -214,16 +249,30 @@ func (c *Client) GetObject(ctx context.Context, bucketName, objectName string, o
} else if req.Offset > 0 { // Range is set with respect to the offset.
opts.SetRange(req.Offset, 0)
} else {
// Remove range header if already set
delete(opts.headers, "Range")
if originalRangeHeader == "" {
delete(opts.headers, "Range")
} else {
opts.headers["Range"] = originalRangeHeader
}
}
httpReader, objectInfo, _, err = c.getObject(gctx, bucketName, objectName, opts)
if err != nil {
resCh <- getResponse{
Error: err,
}
// An unsatisfiable range is recoverable: the caller
// may Seek or ReadAt within bounds next, so keep
// serving requests instead of ending the stream.
if ToErrorResponse(err).Code == InvalidRange {
continue
}
return
}
// case for ReadFull with range request
if !req.isReadAt && req.Offset == 0 {
objectSize = objectInfo.Size
}
renewReader = true
totalRead = 0
}
@@ -250,9 +299,13 @@ func (c *Client) GetObject(ctx context.Context, bucketName, objectName string, o
// it to io.EOF - return unexpected EOF.
err = io.ErrUnexpectedEOF
}
if renewReader && req.isReadAt {
httpReader.Close()
httpReader = nil
}
// Reply back how much was read.
resCh <- getResponse{
ObjectSize: objectSize,
Size: size,
Error: err,
didRead: true,
@@ -281,6 +334,7 @@ type getRequest struct {
// get response message container to reply back for the request.
type getResponse struct {
ObjectSize int64
Size int
Error error
didRead bool // Lets subsequent calls know whether or not httpReader has been initiated.
@@ -299,6 +353,7 @@ type Object struct {
ctx context.Context
cancel context.CancelFunc
currOffset int64
totalSize int64
objectInfo ObjectInfo
// Ask lower level to initiate data fetching based on currOffset
@@ -356,6 +411,10 @@ func (o *Object) doGetRequest(request getRequest) (getResponse, error) {
// Data are ready on the wire, no need to reinitiate connection in lower level
o.seekData = false
if response.ObjectSize != 0 {
o.totalSize = response.ObjectSize
}
return response, response.Error
}
@@ -365,7 +424,7 @@ func (o *Object) setOffset(bytesRead int64) error {
// Update the currentOffset.
o.currOffset += bytesRead
if o.objectInfo.Size > -1 && o.currOffset >= o.objectInfo.Size {
if o.totalSize > -1 && o.currOffset >= o.totalSize {
return io.EOF
}
return nil
@@ -387,6 +446,13 @@ func (o *Object) Read(b []byte) (n int, err error) {
if o.prevErr != nil || o.isClosed {
return 0, o.prevErr
}
// If the current offset is at or beyond the known object size, there is
// nothing more to read. Return io.EOF directly instead of issuing a range
// request from EOF (which the server rejects as an unsatisfiable range).
if o.objectInfoSet && o.objectInfo.Size > -1 && o.currOffset >= o.objectInfo.Size {
o.prevErr = io.EOF
return 0, io.EOF
}
// Create a new request.
readReq := getRequest{
@@ -407,6 +473,14 @@ func (o *Object) Read(b []byte) (n int, err error) {
// Send and receive from the first request.
response, err := o.doGetRequest(readReq)
if err != nil && err != io.EOF {
// An InvalidRange response to a range generated from a non-zero
// read offset means the position is at or past EOF for the object
// as it currently exists. Offset zero sends only a caller-supplied
// range, whose InvalidRange must surface untranslated.
if o.currOffset > 0 && ToErrorResponse(err).Code == InvalidRange {
o.prevErr = io.EOF
return 0, io.EOF
}
// Save the error for future calls.
o.prevErr = err
return response.Size, err
@@ -428,6 +502,8 @@ func (o *Object) Read(b []byte) (n int, err error) {
}
// Stat returns the ObjectInfo structure describing Object.
// When requesting a partial object or reading has started,
// the size returned will reflect the remaining size.
func (o *Object) Stat() (ObjectInfo, error) {
if o == nil {
return ObjectInfo{}, errInvalidArgument("Object is nil")
@@ -436,7 +512,24 @@ func (o *Object) Stat() (ObjectInfo, error) {
o.mutex.Lock()
defer o.mutex.Unlock()
if o.prevErr != nil && o.prevErr != io.EOF || o.isClosed {
if o.prevErr != nil && o.prevErr != io.EOF {
return ObjectInfo{}, o.prevErr
}
// When the object info is already known (e.g. the RDMA GET path, whose
// payload is delivered out-of-band so the object is created closed, or a
// previously completed request) report it, even for a closed object.
if o.objectInfoSet {
if o.currOffset > o.totalSize {
return ObjectInfo{}, io.EOF
}
if o.currOffset <= o.totalSize {
o.objectInfo.Size = o.totalSize - o.currOffset
}
return o.objectInfo, nil
}
if o.isClosed {
return ObjectInfo{}, o.prevErr
}
@@ -452,7 +545,12 @@ func (o *Object) Stat() (ObjectInfo, error) {
return ObjectInfo{}, err
}
}
if o.currOffset > o.totalSize {
return ObjectInfo{}, io.EOF
}
if o.currOffset <= o.totalSize {
o.objectInfo.Size = o.totalSize - o.currOffset
}
return o.objectInfo, nil
}
@@ -488,7 +586,7 @@ func (o *Object) ReadAt(b []byte, offset int64) (n int, err error) {
if o.objectInfoSet {
// If offset is negative than we return io.EOF.
// If offset is greater than or equal to object size we return io.EOF.
if (o.objectInfo.Size > -1 && offset >= o.objectInfo.Size) || offset < 0 {
if (o.totalSize > -1 && offset >= o.totalSize) || offset < 0 {
return 0, io.EOF
}
}
@@ -511,6 +609,12 @@ func (o *Object) ReadAt(b []byte, offset int64) (n int, err error) {
// Send and receive from the first request.
response, err := o.doGetRequest(readAtReq)
if err != nil && err != io.EOF {
// Reading at an offset at or beyond the object size yields
// InvalidRange from the server: report io.EOF, matching the
// io.ReaderAt contract for reads past the end.
if ToErrorResponse(err).Code == InvalidRange {
return 0, io.EOF
}
// Save the error.
o.prevErr = err
return response.Size, err
@@ -541,9 +645,10 @@ func (o *Object) ReadAt(b []byte, offset int64) (n int, err error) {
// and 2 means relative to the end.
// Seek returns the new offset and an error, if any.
//
// Seeking to a negative offset is an error. Seeking to any positive
// offset is legal, subsequent io operations succeed until the
// underlying object is not closed.
// Seeking to a position before the start of the object is an error.
// Seeking to the end of the object is legal; the subsequent Read reports
// io.EOF. When the object size is known, seeking past the end returns
// io.EOF from Seek itself and leaves the offset unchanged.
func (o *Object) Seek(offset int64, whence int) (n int64, err error) {
if o == nil {
return 0, errInvalidArgument("Object is nil")
@@ -558,9 +663,11 @@ func (o *Object) Seek(offset int64, whence int) (n int64, err error) {
return 0, o.prevErr
}
// Negative offset is valid for whence of '2'.
if offset < 0 && whence != 2 {
return 0, errInvalidArgument(fmt.Sprintf("Negative position not allowed for %d", whence))
// Negative absolute offsets are invalid for SeekStart. Negative offsets
// for SeekCurrent/SeekEnd are valid as long as the computed position is
// not before the start of the object (checked after applying whence).
if offset < 0 && whence == 0 {
return 0, errInvalidArgument("Negative position not allowed for 0")
}
// This is the first request. So before anything else
@@ -588,31 +695,26 @@ func (o *Object) Seek(offset int64, whence int) (n int64, err error) {
default:
return 0, errInvalidArgument(fmt.Sprintf("Invalid whence %d", whence))
case 0:
if o.objectInfo.Size > -1 && offset > o.objectInfo.Size {
return 0, io.EOF
}
newOffset = offset
case 1:
if o.objectInfo.Size > -1 && o.currOffset+offset > o.objectInfo.Size {
return 0, io.EOF
}
newOffset += offset
case 2:
// If we don't know the object size return an error for io.SeekEnd
if o.objectInfo.Size < 0 {
if o.totalSize < 0 {
return 0, errInvalidArgument("Whence END is not supported when the object size is unknown")
}
// Seeking to positive offset is valid for whence '2', but
// since we are backing a Reader we have reached 'EOF' if
// offset is positive.
if offset > 0 {
return 0, io.EOF
}
// Seeking to negative position not allowed for whence.
if o.objectInfo.Size+offset < 0 {
return 0, errInvalidArgument(fmt.Sprintf("Seeking at negative offset not allowed for %d", whence))
}
newOffset = o.objectInfo.Size + offset
newOffset = o.totalSize + offset
}
// Seeking to a position before the start of the object is not allowed for
// any whence.
if newOffset < 0 {
return 0, errInvalidArgument(fmt.Sprintf("Seeking at negative offset not allowed for %d", whence))
}
// Seeking past the end of the object is rejected with io.EOF, preserving
// long-standing behavior. Seeking to exactly the end is legal and the
// subsequent Read reports io.EOF.
if o.objectInfo.Size > -1 && newOffset > o.objectInfo.Size {
return 0, io.EOF
}
// Reset the saved error since we successfully seeked, let the Read
// and ReadAt decide.
@@ -717,6 +819,19 @@ func (c *Client) getObject(ctx context.Context, bucketName, objectName string, o
return nil, ObjectInfo{}, nil, err
}
body := resp.Body
if opts.Checksum {
if opts.checkSumReader != nil {
opts.checkSumReader.SetReader(resp.Body)
body = opts.checkSumReader
} else if objectStat.ChecksumMode == ChecksumFullObjectMode.String() && opts.headers["Range"] == "" {
if hasherReader := c.newChecksumVerifyingReader(objectStat); hasherReader != nil {
hasherReader.SetReader(resp.Body)
body = hasherReader
}
}
}
// do not close body here, caller will close
return resp.Body, objectStat, resp.Header, nil
return body, objectStat, resp.Header, nil
}
+6 -1
View File
@@ -44,10 +44,15 @@ type GetObjectOptions struct {
VersionID string
PartNumber int
// Include any checksums, if object was uploaded with checksum.
// For multipart objects this is a checksum of part checksums.
// https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html
// When the response advertises a full-object checksum, un-ranged
// downloads are verified against it: reads through *Object fail with a
// checksum mismatch error at EOF, and FGetObject fails before renaming
// the file into place. Reads that stop before EOF are not verified.
Checksum bool
// If not nil, continue checksum hash verification on the existing data.
checkSumReader *checksumVerifyingReader
// RDMABuffer, when non-nil and Options.EnableRDMA=true, downloads directly
// into a contiguous buffer via libminiocpp.so. The returned *Object's
+35 -25
View File
@@ -127,6 +127,9 @@ func (c *Client) listObjectsV2(ctx context.Context, bucketName string, opts List
// Return object owner information by default
fetchOwner := true
if opts.FetchOwner != nil {
fetchOwner = *opts.FetchOwner
}
return func(yield func(ObjectInfo) bool) {
if contextCanceled(ctx) {
@@ -296,6 +299,7 @@ func (c *Client) listObjectsV2Query(ctx context.Context, bucketName, objectPrefi
return listBucketResult, err
}
listBucketResult.Contents[i].LastModified = listBucketResult.Contents[i].LastModified.Truncate(time.Millisecond)
listBucketResult.Contents[i].UserMetadataStripped = stripUserMetadata(obj.UserMetadata)
}
for i, obj := range listBucketResult.CommonPrefixes {
@@ -419,31 +423,32 @@ func (c *Client) listObjectVersions(ctx context.Context, bucketName string, opts
}
for _, version := range vers {
info := ObjectInfo{
ETag: trimEtag(version.ETag),
Key: version.Key,
LastModified: version.LastModified.Truncate(time.Millisecond),
Size: version.Size,
Owner: version.Owner,
StorageClass: version.StorageClass,
IsLatest: version.IsLatest,
VersionID: version.VersionID,
IsDeleteMarker: version.isDeleteMarker,
UserTags: version.UserTags,
UserMetadata: version.UserMetadata,
Internal: version.Internal,
NumVersions: numVersions,
ChecksumAlgorithm: version.ChecksumAlgorithm,
ChecksumMode: version.ChecksumType,
ChecksumCRC32: version.ChecksumCRC32,
ChecksumCRC32C: version.ChecksumCRC32C,
ChecksumSHA1: version.ChecksumSHA1,
ChecksumSHA256: version.ChecksumSHA256,
ChecksumCRC64NVME: version.ChecksumCRC64NVME,
ChecksumMD5: version.ChecksumMD5,
ChecksumSHA512: version.ChecksumSHA512,
ChecksumXXHash64: version.ChecksumXXHash64,
ChecksumXXHash3: version.ChecksumXXHash3,
ChecksumXXHash128: version.ChecksumXXHash128,
ETag: trimEtag(version.ETag),
Key: version.Key,
LastModified: version.LastModified.Truncate(time.Millisecond),
Size: version.Size,
Owner: version.Owner,
StorageClass: version.StorageClass,
IsLatest: version.IsLatest,
VersionID: version.VersionID,
IsDeleteMarker: version.isDeleteMarker,
UserTags: version.UserTags,
UserMetadata: version.UserMetadata,
UserMetadataStripped: version.UserMetadataStripped,
Internal: version.Internal,
NumVersions: numVersions,
ChecksumAlgorithm: version.ChecksumAlgorithm,
ChecksumMode: version.ChecksumType,
ChecksumCRC32: version.ChecksumCRC32,
ChecksumCRC32C: version.ChecksumCRC32C,
ChecksumSHA1: version.ChecksumSHA1,
ChecksumSHA256: version.ChecksumSHA256,
ChecksumCRC64NVME: version.ChecksumCRC64NVME,
ChecksumMD5: version.ChecksumMD5,
ChecksumSHA512: version.ChecksumSHA512,
ChecksumXXHash64: version.ChecksumXXHash64,
ChecksumXXHash3: version.ChecksumXXHash3,
ChecksumXXHash128: version.ChecksumXXHash128,
}
if !yield(info) {
return false
@@ -606,6 +611,7 @@ func (c *Client) listObjectVersionsQuery(ctx context.Context, bucketName string,
if err != nil {
return listObjectVersionsOutput, err
}
listObjectVersionsOutput.Versions[i].UserMetadataStripped = stripUserMetadata(obj.UserMetadata)
}
for i, obj := range listObjectVersionsOutput.CommonPrefixes {
@@ -738,6 +744,10 @@ type ListObjectsOptions struct {
// Use the deprecated list objects V1 API
UseV1 bool
// FetchOwner indicates whether to return object owner information.
// It defaults to true when unset.
FetchOwner *bool
headers http.Header
}
+1 -1
View File
@@ -140,7 +140,7 @@ func (c *Client) PresignedPostPolicy(ctx context.Context, p *PostPolicy) (u *url
}
// Get credentials from the configured credentials provider.
credValues, err := c.credsProvider.GetWithContext(c.CredContext())
credValues, err := c.credsProvider.GetWithContext(c.credContext(ctx))
if err != nil {
return nil, nil, err
}
+2
View File
@@ -69,6 +69,8 @@ type PutObjectFanOutResponse struct {
// stream multiple objects are written, defined via a list of PutObjectFanOutRequests. Each entry
// in PutObjectFanOutRequest carries an object keyname and its relevant metadata if any. `Key` is
// mandatory, rest of the other options in PutObjectFanOutRequest are optional.
//
// Deprecated: Use PutObject instead.
func (c *Client) PutObjectFanOut(ctx context.Context, bucket string, fanOutData io.Reader, fanOutReq PutObjectFanOutRequest) ([]PutObjectFanOutResponse, error) {
if len(fanOutReq.Entries) == 0 {
return nil, errInvalidArgument("fan out requests cannot be empty")
+34 -2
View File
@@ -94,10 +94,16 @@ type Version struct {
StorageClass string
VersionID string `xml:"VersionId"`
// x-amz-meta-* headers stripped "x-amz-meta-" prefix containing the first value.
// Only returned by MinIO servers.
// UserMetadata contains the exact stored object metadata: x-amz-meta-*
// entries with their prefixed keys plus system entries such as
// content-type. Only returned by MinIO servers.
UserMetadata StringMap `json:"userMetadata,omitempty"`
// UserMetadataStripped is UserMetadata in the keyed form StatObject and
// GetObject return in ObjectInfo.UserMetadata. See
// ObjectInfo.UserMetadataStripped.
UserMetadataStripped StringMap `json:"userMetadataStripped,omitempty" xml:"-"`
// x-amz-tagging values in their k/v values.
// Only returned by MinIO servers.
UserTags URLMap `json:"userTags,omitempty" xml:"UserTags"`
@@ -280,6 +286,32 @@ type initiator struct {
type copyObjectResult struct {
ETag string
LastModified time.Time // time string format "2006-01-02T15:04:05.000Z"
// Checksum values returned in CopyObjectResult / CopyPartResult.
ChecksumCRC32 string `xml:"ChecksumCRC32,omitempty"`
ChecksumCRC32C string `xml:"ChecksumCRC32C,omitempty"`
ChecksumSHA1 string `xml:"ChecksumSHA1,omitempty"`
ChecksumSHA256 string `xml:"ChecksumSHA256,omitempty"`
ChecksumCRC64NVME string `xml:",omitempty"`
ChecksumMD5 string `xml:",omitempty"`
ChecksumSHA512 string `xml:",omitempty"`
ChecksumXXHash64 string `xml:"ChecksumXXHASH64,omitempty"`
ChecksumXXHash3 string `xml:"ChecksumXXHASH3,omitempty"`
ChecksumXXHash128 string `xml:"ChecksumXXHASH128,omitempty"`
}
// setChecksums copies the copied part's checksums onto a CompletePart.
func (r *copyObjectResult) setChecksums(p *CompletePart) {
p.ChecksumCRC32 = r.ChecksumCRC32
p.ChecksumCRC32C = r.ChecksumCRC32C
p.ChecksumSHA1 = r.ChecksumSHA1
p.ChecksumSHA256 = r.ChecksumSHA256
p.ChecksumCRC64NVME = r.ChecksumCRC64NVME
p.ChecksumMD5 = r.ChecksumMD5
p.ChecksumSHA512 = r.ChecksumSHA512
p.ChecksumXXHash64 = r.ChecksumXXHash64
p.ChecksumXXHash3 = r.ChecksumXXHash3
p.ChecksumXXHash128 = r.ChecksumXXHash128
}
// ObjectPart container for particular part of an object.
+27 -22
View File
@@ -57,7 +57,12 @@ func (c *Client) BucketExists(ctx context.Context, bucketName string) (bool, err
}
// StatObject verifies if object exists, you have permission to access it
// and returns information about the object.
// and returns information about the object. When the returned error is
// non-nil but a response was received, the ObjectInfo still carries the
// VersionID and IsDeleteMarker values parsed from the response headers,
// plus ReplicationReady on every error path except the versioned
// delete-marker 405 (an asymmetry preserved from the pre-v7.0.93
// behavior, which populated ReplicationReady on the generic branch only).
func (c *Client) StatObject(ctx context.Context, bucketName, objectName string, opts StatObjectOptions) (ObjectInfo, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
@@ -92,32 +97,32 @@ func (c *Client) StatObject(ctx context.Context, bucketName, objectName string,
})
defer closeResponse(resp)
if err != nil {
return ObjectInfo{}, err
}
if resp != nil {
// executeMethod returns a non-nil error for every non-success
// status. When a response exists, its headers still carry the
// version and delete-marker fields — surface them with the error.
if resp == nil {
return ObjectInfo{}, err
}
deleteMarker := resp.Header.Get(amzDeleteMarker) == "true"
replicationReady := resp.Header.Get(minioTgtReplicationReady) == "true"
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
if resp.StatusCode == http.StatusMethodNotAllowed && opts.VersionID != "" && deleteMarker {
errResp := ErrorResponse{
StatusCode: resp.StatusCode,
Code: MethodNotAllowed,
Message: s3ErrorResponseMap[MethodNotAllowed],
BucketName: bucketName,
Key: objectName,
}
return ObjectInfo{
VersionID: resp.Header.Get(amzVersionID),
IsDeleteMarker: deleteMarker,
}, errResp
if resp.StatusCode == http.StatusMethodNotAllowed && opts.VersionID != "" && deleteMarker {
errResp := ErrorResponse{
StatusCode: resp.StatusCode,
Code: MethodNotAllowed,
Message: s3ErrorResponseMap[MethodNotAllowed],
BucketName: bucketName,
Key: objectName,
}
return ObjectInfo{
VersionID: resp.Header.Get(amzVersionID),
IsDeleteMarker: deleteMarker,
ReplicationReady: replicationReady, // whether delete marker can be replicated
}, httpRespToErrorResponse(resp, bucketName, objectName)
VersionID: resp.Header.Get(amzVersionID),
IsDeleteMarker: deleteMarker,
}, errResp
}
return ObjectInfo{
VersionID: resp.Header.Get(amzVersionID),
IsDeleteMarker: deleteMarker,
ReplicationReady: replicationReady, // whether delete marker can be replicated
}, err
}
return ToObjectInfo(bucketName, objectName, resp.Header)
+136 -32
View File
@@ -175,7 +175,7 @@ type Options struct {
// Global constants.
const (
libraryName = "minio-go"
libraryVersion = "v7.0.98"
libraryVersion = "v7.3.0"
)
// User Agent should always following the below style.
@@ -403,7 +403,7 @@ func (c *Client) TraceOff() {
// SetS3TransferAccelerate - turns s3 accelerated endpoint on or off for all your
// requests. This feature is only specific to S3 for all other endpoints this
// function does nothing. To read further details on s3 transfer acceleration
// please vist -
// please visit -
// http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html
func (c *Client) SetS3TransferAccelerate(accelerateEndpoint string) {
if s3utils.IsAmazonEndpoint(*c.endpointURL) {
@@ -554,7 +554,7 @@ type requestMetadata struct {
}
// dumpHTTP - dump HTTP request and response.
func (c *Client) dumpHTTP(req *http.Request, resp *http.Response) error {
func (c *Client) dumpHTTP(req *http.Request, resp *http.Response, doErr error) error {
// Starts http dump.
_, err := fmt.Fprintln(c.traceOutput, "---------START-HTTP---------")
if err != nil {
@@ -568,6 +568,9 @@ func (c *Client) dumpHTTP(req *http.Request, resp *http.Response) error {
}
// Only display request header.
if req.Body != nil {
req.Body = http.NoBody
}
reqTrace, err := httputil.DumpRequestOut(req, false)
if err != nil {
return err
@@ -579,28 +582,36 @@ func (c *Client) dumpHTTP(req *http.Request, resp *http.Response) error {
return err
}
// Only display response header.
var respTrace []byte
if resp != nil {
// Only display response header.
var respTrace []byte
// For errors we make sure to dump response body as well.
if resp.StatusCode != http.StatusOK &&
resp.StatusCode != http.StatusPartialContent &&
resp.StatusCode != http.StatusNoContent {
respTrace, err = httputil.DumpResponse(resp, true)
if err != nil {
return err
// For errors we make sure to dump response body as well.
if !successStatus.Contains(resp.StatusCode) {
respTrace, err = httputil.DumpResponse(resp, true)
if err != nil {
return err
}
} else {
respTrace, err = httputil.DumpResponse(resp, false)
if err != nil {
return err
}
}
} else {
respTrace, err = httputil.DumpResponse(resp, false)
// Write response to trace output.
_, err = fmt.Fprint(c.traceOutput, strings.TrimSuffix(string(respTrace), "\r\n"))
if err != nil {
return err
}
}
// Write response to trace output.
_, err = fmt.Fprint(c.traceOutput, strings.TrimSuffix(string(respTrace), "\r\n"))
if err != nil {
return err
if doErr != nil {
// Write error to trace output.
_, err = fmt.Fprintln(c.traceOutput, strings.TrimSuffix(string(doErr.Error()), "\r\n"))
if err != nil {
return err
}
}
// Ends the http dump.
@@ -623,6 +634,9 @@ func (c *Client) do(req *http.Request) (resp *http.Response, err error) {
resp, err = c.httpClient.Do(req)
if err != nil {
if c.isTraceEnabled {
_ = c.dumpHTTP(req, nil, err)
}
// Handle this specifically for now until future Golang versions fix this issue properly.
if urlErr, ok := err.(*url.Error); ok {
if strings.Contains(urlErr.Err.Error(), "EOF") {
@@ -643,9 +657,9 @@ func (c *Client) do(req *http.Request) (resp *http.Response, err error) {
}
// If trace is enabled, dump http request and response,
// except when the traceErrorsOnly enabled and the response's status code is ok
if c.isTraceEnabled && (!c.traceErrorsOnly || resp.StatusCode != http.StatusOK) {
err = c.dumpHTTP(req, resp)
// except when traceErrorsOnly is enabled and the response has a success status code
if c.isTraceEnabled && (!c.traceErrorsOnly || !successStatus.Contains(resp.StatusCode)) {
err = c.dumpHTTP(req, resp, nil)
if err != nil {
return nil, err
}
@@ -657,6 +671,7 @@ func (c *Client) do(req *http.Request) (resp *http.Response, err error) {
// List of success status.
var successStatus = set.CreateIntSet(
http.StatusOK,
http.StatusAccepted,
http.StatusNoContent,
http.StatusPartialContent,
)
@@ -833,8 +848,24 @@ func (c *Client) executeMethod(ctx context.Context, method string, metadata requ
return res, err
}
// credsRetrievalPanic carries a panic value out of the de-duplicated
// credential retrieval goroutine so newRequest can resume it on each
// caller's goroutine. The value is re-raised verbatim, as if the provider
// had panicked on the caller's goroutine; the retrieval goroutine's stack
// is not carried along.
type credsRetrievalPanic struct{ value any }
func (p credsRetrievalPanic) Error() string {
return fmt.Sprintf("credentials retrieval panicked: %v", p.value)
}
// newRequest - instantiate a new HTTP request for a given method.
func (c *Client) newRequest(ctx context.Context, method string, metadata requestMetadata) (req *http.Request, err error) {
if ctx == nil {
// A nil context would be dereferenced below — by the bucket
// location lookup, the waiter select, and context.WithoutCancel.
return nil, errInvalidArgument("context cannot be nil")
}
// If no method is supplied default to 'POST'.
if method == "" {
method = http.MethodPost
@@ -867,23 +898,88 @@ func (c *Client) newRequest(ctx context.Context, method string, metadata request
return nil, err
}
if c.httpTrace != nil {
ctx = httptrace.WithClientTrace(ctx, c.httpTrace)
// Cached, unexpired credentials (or an absent provider — anonymous
// access) are served inline; a retrieval that races expiry runs
// inline too, with the caller's live context, serialized by the
// Credentials mutex. A still-fresh cached S3 Express session is
// served inline as well; actual retrievals go through the de-dup
// group.
express := s3utils.IsS3ExpressBucket(metadata.bucketName) && s3utils.IsAmazonEndpoint(*c.endpointURL)
var value credentials.Value
var served bool
if express {
value, served = c.sessionFromCache(metadata.bucketName)
} else if c.credsProvider == nil || !c.credsProvider.IsExpired() {
value, err = c.credsProvider.GetWithContext(c.credContext(ctx))
served = true
}
// make sure to de-dup calls to credential services, this reduces
// the overall load to the endpoint generating credential service.
value, err, _ := c.credsGroup.Do(metadata.bucketName, func() (credentials.Value, error) {
if s3utils.IsS3ExpressBucket(metadata.bucketName) && s3utils.IsAmazonEndpoint(*c.endpointURL) {
return c.CreateSession(ctx, metadata.bucketName, SessionReadWrite)
if !served {
// The provider retrieval is detached (context.WithoutCancel) so
// one caller's cancellation cannot fail concurrent waiters; each
// waiter stops waiting when its own context ends, though a
// caller arriving mid-retrieval blocks in IsExpired on the
// Credentials mutex until the retrieval completes. Detachment
// strips the caller's deadline along with its cancellation: on
// this path the caller context governs only the wait, and reaches
// the credential request itself only outside the group — on the
// inline not-expired path above and the direct call sites
// (presign, bucket location, express CreateSession). The S3
// Express session request keeps the caller context: a full S3
// operation's retries must stay cancellable, so its waiters
// share the winner's fate, and its trace for the same reason:
// the round trip was traced before this change.
// A retrieval panic resumes on each waiting caller's goroutine
// (credsRetrievalPanic); a runtime.Goexit reaches waiters as a
// terminal error from the de-dup group, since the retrieval
// goroutine cannot return one itself.
retrieveCtx := ctx
if express {
if c.httpTrace != nil {
retrieveCtx = httptrace.WithClientTrace(retrieveCtx, c.httpTrace)
}
} else {
retrieveCtx = context.WithoutCancel(ctx)
}
// Get credentials from the configured credentials provider.
return c.credsProvider.GetWithContext(c.CredContext())
})
resCh := c.credsGroup.DoChan(metadata.bucketName, func() (v credentials.Value, rerr error) {
defer func() {
if r := recover(); r != nil {
rerr = credsRetrievalPanic{value: r}
}
}()
if express {
return c.CreateSession(retrieveCtx, metadata.bucketName, SessionReadWrite)
}
// Get credentials from the configured credentials provider.
return c.credsProvider.GetWithContext(c.credContext(retrieveCtx))
})
var res singleflight.Result[credentials.Value]
select {
case res = <-resCh:
case <-ctx.Done():
// A result already delivered when the cancellation fires is
// preferred over the caller's context error.
select {
case res = <-resCh:
default:
return nil, ctx.Err()
}
}
var cp credsRetrievalPanic
if errors.As(res.Err, &cp) {
panic(cp.value)
}
value, err = res.Val, res.Err
}
if err != nil {
return nil, err
}
// Attach the trace after retrieval: provider credential requests were
// never traced. The express session request is traced above.
if c.httpTrace != nil {
ctx = httptrace.WithClientTrace(ctx, c.httpTrace)
}
// Initialize a new HTTP request for the method.
req, err = http.NewRequestWithContext(ctx, method, targetURL.String(), nil)
if err != nil {
@@ -1157,6 +1253,14 @@ func (c *Client) CredContext() *credentials.CredContext {
}
}
// credContext returns the client's CredContext with ctx attached as the
// caller context for credential retrieval.
func (c *Client) credContext(ctx context.Context) *credentials.CredContext {
cc := c.CredContext()
cc.Context = ctx
return cc
}
// GetCreds returns the access creds for the client
func (c *Client) GetCreds() (credentials.Value, error) {
if c.credsProvider == nil {
+28 -26
View File
@@ -76,33 +76,35 @@ func (c *Client) getBucketLocation(ctx context.Context, bucketName string) (stri
// processes the getBucketLocation http response from the server.
func processBucketLocationResponse(resp *http.Response, bucketName string) (bucketLocation string, err error) {
if resp != nil {
if resp.StatusCode != http.StatusOK {
err = httpRespToErrorResponse(resp, bucketName, "")
errResp := ToErrorResponse(err)
// For access denied error, it could be an anonymous
// request. Move forward and let the top level callers
// succeed if possible based on their policy.
switch errResp.Code {
case NotImplemented:
switch errResp.Server {
case "AmazonSnowball":
return "snowball", nil
case "cloudflare":
return "us-east-1", nil
}
case AuthorizationHeaderMalformed:
fallthrough
case InvalidRegion:
fallthrough
case AccessDenied:
if errResp.Region == "" {
return "us-east-1", nil
}
return errResp.Region, nil
if resp == nil {
return "", errInvalidArgument("Empty http response. " + reportIssue)
}
if resp.StatusCode != http.StatusOK {
err = httpRespToErrorResponse(resp, bucketName, "")
errResp := ToErrorResponse(err)
// For access denied error, it could be an anonymous
// request. Move forward and let the top level callers
// succeed if possible based on their policy.
switch errResp.Code {
case NotImplemented:
switch errResp.Server {
case "AmazonSnowball":
return "snowball", nil
case "cloudflare":
return "us-east-1", nil
}
return "", err
case AuthorizationHeaderMalformed:
fallthrough
case InvalidRegion:
fallthrough
case AccessDenied:
if errResp.Region == "" {
return "us-east-1", nil
}
return errResp.Region, nil
}
return "", err
}
// Extract location.
@@ -170,7 +172,7 @@ func (c *Client) getBucketLocationRequest(ctx context.Context, bucketName string
c.setUserAgent(req)
// Get credentials from the configured credentials provider.
value, err := c.credsProvider.GetWithContext(c.CredContext())
value, err := c.credsProvider.GetWithContext(c.credContext(ctx))
if err != nil {
return nil, err
}
+81
View File
@@ -25,6 +25,7 @@ import (
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"hash"
"io"
"math/bits"
@@ -316,6 +317,86 @@ func (c ChecksumType) String() string {
return "<invalid>"
}
// checksumVerifyingReader verifies the checksum of data as it is read.
type checksumVerifyingReader struct {
io.ReadCloser
hash.Hash
expectChecksum string
}
// newChecksumVerifyingReader returns a checksum-verifying reader for obj,
// wrapping the given response body, or nil if obj carries no usable checksum.
func (c *Client) newChecksumVerifyingReader(obj ObjectInfo) *checksumVerifyingReader {
switch {
case obj.ChecksumCRC32 != "":
return &checksumVerifyingReader{Hash: ChecksumCRC32.Hasher(), expectChecksum: obj.ChecksumCRC32}
case obj.ChecksumCRC32C != "":
return &checksumVerifyingReader{Hash: ChecksumCRC32C.Hasher(), expectChecksum: obj.ChecksumCRC32C}
case obj.ChecksumSHA1 != "":
return &checksumVerifyingReader{Hash: ChecksumSHA1.Hasher(), expectChecksum: obj.ChecksumSHA1}
case obj.ChecksumSHA256 != "":
return &checksumVerifyingReader{Hash: c.sha256Hasher(), expectChecksum: obj.ChecksumSHA256}
case obj.ChecksumCRC64NVME != "":
return &checksumVerifyingReader{Hash: ChecksumCRC64NVME.Hasher(), expectChecksum: obj.ChecksumCRC64NVME}
case obj.ChecksumMD5 != "":
return &checksumVerifyingReader{Hash: c.md5Hasher(), expectChecksum: obj.ChecksumMD5}
case obj.ChecksumSHA512 != "":
return &checksumVerifyingReader{Hash: ChecksumSHA512.Hasher(), expectChecksum: obj.ChecksumSHA512}
case obj.ChecksumXXHash64 != "":
return &checksumVerifyingReader{Hash: ChecksumXXHash64.Hasher(), expectChecksum: obj.ChecksumXXHash64}
case obj.ChecksumXXHash3 != "":
return &checksumVerifyingReader{Hash: ChecksumXXHash3.Hasher(), expectChecksum: obj.ChecksumXXHash3}
case obj.ChecksumXXHash128 != "":
return &checksumVerifyingReader{Hash: ChecksumXXHash128.Hasher(), expectChecksum: obj.ChecksumXXHash128}
default:
return nil
}
}
func (c *checksumVerifyingReader) SetReader(r io.ReadCloser) {
c.ReadCloser = r
}
// Close returns any pooled hasher and closes the underlying reader if one is set.
func (c *checksumVerifyingReader) Close() error {
if closer, ok := c.Hash.(interface{ Close() }); ok {
closer.Close()
}
if c.ReadCloser == nil {
return nil
}
return c.ReadCloser.Close()
}
// Read reads data and hashes it. At EOF the checksum is verified; on
// mismatch the mismatch error is returned in place of io.EOF.
func (c *checksumVerifyingReader) Read(p []byte) (int, error) {
n, err := c.ReadCloser.Read(p)
if n > 0 {
n2, werr := c.Write(p[:n])
if werr != nil {
return n, werr
}
if n2 != n {
return n, io.ErrShortWrite
}
}
if err == io.EOF {
if verr := c.VerifyChecksum(); verr != nil {
return n, verr
}
}
return n, err
}
// VerifyChecksum returns an error if the computed checksum does not match.
func (c *checksumVerifyingReader) VerifyChecksum() error {
if got := base64.StdEncoding.EncodeToString(c.Sum(nil)); got != c.expectChecksum {
return fmt.Errorf("checksum mismatch, expected %s, got %s", c.expectChecksum, got)
}
return nil
}
// ChecksumReader reads all of r and returns a checksum of type c.
// Returns any error that may have occurred while reading.
func (c ChecksumType) ChecksumReader(r io.Reader) (Checksum, error) {
+18 -7
View File
@@ -51,19 +51,30 @@ type createSessionResult struct {
} `xml:",omitempty"`
}
// expressSessionRenewalLeeway is how long before its expiration a cached
// S3 Express session stops being served, leaving room for renewal.
const expressSessionRenewalLeeway = 10 * time.Second
// sessionFromCache returns the cached S3 Express session credentials for
// bucketName while they remain outside the renewal leeway.
func (c *Client) sessionFromCache(bucketName string) (credentials.Value, bool) {
v, ok := c.bucketSessionCache.Get(bucketName)
if !ok || !v.Expiration.After(time.Now().Add(expressSessionRenewalLeeway)) {
return credentials.Value{}, false
}
return v, true
}
// CreateSession - https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateSession.html
// the returning credentials may be cached depending on the expiration of the original
// credential, credentials will get renewed 10 secs earlier than when its gonna expire
// allowing for some leeway in the renewal process.
// credential; a cached session stops being served expressSessionRenewalLeeway before
// it expires, allowing for some leeway in the renewal process.
func (c *Client) CreateSession(ctx context.Context, bucketName string, sessionMode SessionMode) (cred credentials.Value, err error) {
if err := s3utils.CheckValidBucketNameS3Express(bucketName); err != nil {
return credentials.Value{}, err
}
v, ok := c.bucketSessionCache.Get(bucketName)
if ok && v.Expiration.After(time.Now().Add(10*time.Second)) {
// Verify if the credentials will not expire
// in another 10 seconds, if not we renew it again.
if v, ok := c.sessionFromCache(bucketName); ok {
return v, nil
}
@@ -143,7 +154,7 @@ func (c *Client) createSessionRequest(ctx context.Context, bucketName string, se
c.setUserAgent(req)
// Get credentials from the configured credentials provider.
value, err := c.credsProvider.GetWithContext(c.CredContext())
value, err := c.credsProvider.GetWithContext(c.credContext(ctx))
if err != nil {
return nil, err
}
+511 -38
View File
@@ -172,9 +172,12 @@ func logError(testName, function string, args map[string]interface{}, startTime
// If server returns NotImplemented we assume it is gateway mode and hence log it as info and move on to next tests
// Special case for ComposeObject API as it is implemented on client side and adds specific error details like `Error in upload-part-copy` in
// addition to NotImplemented error returned from server
if isErrNotImplemented(err) {
switch {
case isErrNotImplemented(err):
logIgnored(testName, function, args, startTime, message)
} else {
case isErrFreeTierLicense(err):
logNotAvailable(testName, function, args, startTime, message)
default:
logFailure(testName, function, args, startTime, alert, message, err)
if !isRunOnFail() {
panic(fmt.Sprintf("Test failed with message: %s, err: %v", message, err))
@@ -206,6 +209,15 @@ func logIgnored(testName, function string, args map[string]interface{}, startTim
).Info("")
}
// log not applicable test runs for license-gated features
func logNotAvailable(testName, function string, args map[string]interface{}, startTime time.Time, alert string) {
baseLogger(testName, function, args, startTime).
With(
"status", "NA",
"alert", strings.Split(alert, " ")[0]+" requires a paid-tier license",
).Info("")
}
// Delete objects in given bucket, recursively
func cleanupBucket(bucketName string, c *minio.Client) error {
// Create a done channel to control 'ListObjectsV2' go routine.
@@ -279,6 +291,11 @@ func isErrNotImplemented(err error) bool {
return minio.ToErrorResponse(err).Code == minio.NotImplemented
}
// isErrFreeTierLicense reports whether the server rejected the request because it requires a paid-tier license.
func isErrFreeTierLicense(err error) bool {
return minio.ToErrorResponse(err).Code == minio.XMinioPaidTierLicenseRequired
}
func isRunOnFail() bool {
return os.Getenv("RUN_ON_FAIL") == "1"
}
@@ -795,6 +812,125 @@ func testListObjectVersions() {
logSuccess(testName, function, args, startTime)
}
func testStatObjectResponseHeaders() {
// initialize logging params
startTime := time.Now()
testName := getFuncName()
function := "StatObject(bucketName, objectName, opts)"
args := map[string]interface{}{}
c, err := NewClient(ClientConfig{})
if err != nil {
logError(testName, function, args, startTime, "", "MinIO client object creation failed", err)
return
}
// Generate a new random bucket name.
bucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "minio-go-test-")
args["bucketName"] = bucketName
// Make a new bucket.
err = c.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{Region: "us-east-1"})
if err != nil {
logError(testName, function, args, startTime, "", "MakeBucket failed", err)
return
}
defer cleanupBucket(bucketName, c)
bufSize := dataFileMap["datafile-33-kB"]
reader := getDataReader("datafile-33-kB")
defer reader.Close()
objectName := randString(60, rand.NewSource(time.Now().UnixNano()), "")
args["objectName"] = objectName
_, err = c.PutObject(context.Background(), bucketName, objectName, reader, int64(bufSize), minio.PutObjectOptions{ContentType: "binary/octet-stream"})
if err != nil {
logError(testName, function, args, startTime, "", "PutObject failed", err)
return
}
opts := minio.StatObjectOptions{}
err = opts.SetRange(0, 99)
if err != nil {
logError(testName, function, args, startTime, "", "SetRange failed", err)
return
}
args["range"] = "0-99"
st, err := c.StatObject(context.Background(), bucketName, objectName, opts)
if err != nil {
logError(testName, function, args, startTime, "", "StatObject failed", err)
return
}
if st.Size != 100 {
logError(testName, function, args, startTime, "", "StatObject ranged size mismatch", fmt.Errorf("got %d, want 100", st.Size))
return
}
wantContentRange := fmt.Sprintf("bytes 0-99/%d", bufSize)
gotContentRange := st.Headers.Get("Content-Range")
if gotContentRange != wantContentRange {
logError(testName, function, args, startTime, "", "StatObject response headers Content-Range mismatch", fmt.Errorf("got %q, want %q", gotContentRange, wantContentRange))
return
}
if st.Headers.Get("ETag") == "" {
logError(testName, function, args, startTime, "", "StatObject response headers missing ETag", errors.New("empty ETag header"))
return
}
gopts := minio.GetObjectOptions{}
err = gopts.SetRange(0, 99)
if err != nil {
logError(testName, function, args, startTime, "", "SetRange failed", err)
return
}
obj, err := c.GetObject(context.Background(), bucketName, objectName, gopts)
if err != nil {
logError(testName, function, args, startTime, "", "GetObject failed", err)
return
}
defer obj.Close()
// Read first: a first-op Stat issues an un-ranged StatObject by design,
// so the ranged GET response headers are observable only after a read.
buf := make([]byte, 100)
if _, err = io.ReadFull(obj, buf); err != nil {
logError(testName, function, args, startTime, "", "GetObject ranged read failed", err)
return
}
gst, err := obj.Stat()
if err != nil {
logError(testName, function, args, startTime, "", "GetObject Stat failed", err)
return
}
if got := gst.Headers.Get("Content-Range"); got != wantContentRange {
logError(testName, function, args, startTime, "", "GetObject response headers Content-Range mismatch", fmt.Errorf("got %q, want %q", got, wantContentRange))
return
}
sawObject := false
for listInfo := range c.ListObjects(context.Background(), bucketName, minio.ListObjectsOptions{}) {
if listInfo.Err != nil {
logError(testName, function, args, startTime, "", "ListObjects failed", listInfo.Err)
return
}
if listInfo.Key == objectName {
sawObject = true
}
if listInfo.Headers != nil {
logError(testName, function, args, startTime, "", "ListObjects ObjectInfo.Headers expected nil", fmt.Errorf("got %v", listInfo.Headers))
return
}
}
if !sawObject {
logError(testName, function, args, startTime, "", "ListObjects did not list the uploaded object", errors.New("uploaded object missing from listing"))
return
}
logSuccess(testName, function, args, startTime)
}
func testStatObjectWithVersioning() {
// initialize logging params
startTime := time.Now()
@@ -5379,7 +5515,7 @@ func testGetObjectReadSeekFunctional() {
}
if st.Size != int64(bufSize) {
logError(testName, function, args, startTime, "", "Number of bytes does not match, expected "+string(int64(bufSize))+", got "+string(st.Size), err)
logError(testName, function, args, startTime, "", "Number of bytes does not match, expected "+strconv.Itoa(bufSize)+", got "+strconv.FormatInt(st.Size, 10), err)
return
}
@@ -5418,50 +5554,77 @@ func testGetObjectReadSeekFunctional() {
{0, 0, 0, nil, true, 0, 0},
// Start from offset 2048, fetch data and compare
{2048, 0, 2048, nil, true, 2048, bufSize},
// Start from offset larger than possible
{int64(bufSize) + 1024, 0, 0, seekErr, false, 0, 0},
// Start from offset larger than possible: Seek rejects it with io.EOF
// and keeps the offset unchanged.
{int64(bufSize) + 1024, 0, 0, io.EOF, false, 0, 0},
// Move to offset 0 without comparing
{0, 0, 0, nil, false, 0, 0},
// Move one step forward and compare
{1, 1, 1, nil, true, 1, bufSize},
// Move larger than possible
{int64(bufSize), 1, 0, seekErr, false, 0, 0},
// Provide negative offset with CUR_SEEK
{int64(-1), 1, 0, seekErr, false, 0, 0},
// Test with whence SEEK_END and with positive offset
{1024, 2, int64(bufSize) - 1024, io.EOF, true, 0, 0},
// Move larger than possible: Seek returns io.EOF.
{int64(bufSize), 1, 0, io.EOF, false, 0, 0},
// Provide negative offset with CUR_SEEK: valid since the resulting
// absolute position is within the object.
{int64(-1), 1, int64(bufSize) - 1, nil, false, 0, 0},
// Test with whence SEEK_END and with positive offset: Seek returns
// io.EOF.
{1024, 2, 0, io.EOF, false, 0, 0},
// Test with whence SEEK_END and with negative offset
{-1024, 2, int64(bufSize) - 1024, nil, true, bufSize - 1024, bufSize},
// Test with whence SEEK_END and with large negative offset
{-int64(bufSize) * 2, 2, 0, seekErr, true, 0, 0},
// Seek to exactly the object end; the subsequent read reports io.EOF.
{0, 2, int64(bufSize), nil, false, 0, 0},
}
for i, testCase := range testCases {
// Snapshot the cursor so rejected seeks can be asserted side-effect
// free.
prevPos, err := r.Seek(0, io.SeekCurrent)
if err != nil {
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, reading the current position failed", i+1), err)
return
}
// Perform seek operation
n, err := r.Seek(testCase.offset, testCase.whence)
// We expect an error
if testCase.err == seekErr && err == nil {
logError(testName, function, args, startTime, "", "Test "+string(i+1)+", unexpected err value: expected: "+testCase.err.Error()+", found: "+err.Error(), err)
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, unexpected err value: expected: %v, found: %v", i+1, testCase.err, err), err)
return
}
// We expect a specific error
if testCase.err != seekErr && testCase.err != err {
logError(testName, function, args, startTime, "", "Test "+string(i+1)+", unexpected err value: expected: "+testCase.err.Error()+", found: "+err.Error(), err)
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, unexpected err value: expected: %v, found: %v", i+1, testCase.err, err), err)
return
}
// If we expect an error go to the next loop
if testCase.err != nil {
// A rejected seek must leave the cursor unchanged.
curPos, cerr := r.Seek(0, io.SeekCurrent)
if cerr != nil || curPos != prevPos {
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, cursor after rejected seek: expected %d, got %d", i+1, prevPos, curPos), cerr)
return
}
continue
}
// Check the returned seek pos
if n != testCase.pos {
logError(testName, function, args, startTime, "", "Test "+string(i+1)+", number of bytes seeked does not match, expected "+string(testCase.pos)+", got "+string(n), err)
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, number of bytes seeked does not match, expected %d, got %d", i+1, testCase.pos, n), err)
return
}
// Compare only if shouldCmp is activated
if testCase.shouldCmp {
cmpData(r, testCase.start, testCase.end)
}
// A successful seek to the object end must defer io.EOF to the
// subsequent read.
if !testCase.shouldCmp && testCase.err == nil && testCase.pos >= int64(bufSize) {
readN, readErr := r.Read(make([]byte, 1))
if readN != 0 || readErr != io.EOF {
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, read after seek to object end expected zero bytes and io.EOF, got %d bytes and %v", i+1, readN, readErr), readErr)
return
}
}
}
logSuccess(testName, function, args, startTime)
}
@@ -5569,8 +5732,8 @@ func testGetObjectReadAtFunctional() {
return
}
if st.Size != int64(bufSize) {
logError(testName, function, args, startTime, "", "Number of bytes in stat does not match, expected "+string(int64(bufSize))+", got "+string(st.Size), err)
if st.Size != (int64(bufSize) - int64(len(bufRead))) {
logError(testName, function, args, startTime, "", "Number of bytes in stat does not match, expected "+strconv.Itoa(bufSize)+", got "+strconv.Itoa(bufSize-len(bufRead)), err)
return
}
@@ -5665,6 +5828,228 @@ func testGetObjectReadAtFunctional() {
logSuccess(testName, function, args, startTime)
}
// testGetObjectWithRange - get object with range
func testGetObjectWithRange() {
// initialize logging params
startTime := time.Now()
testName := getFuncName()
function := "GetObject(bucketName, objectName)"
args := map[string]interface{}{}
c, err := NewClient(ClientConfig{})
if err != nil {
logError(testName, function, args, startTime, "", "MinIO client object creation failed", err)
return
}
// Generate a new random bucket name.
bucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "minio-go-test-")
args["bucketName"] = bucketName
// Make a new bucket.
err = c.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{Region: "us-east-1"})
if err != nil {
logError(testName, function, args, startTime, "", "MakeBucket failed", err)
return
}
defer cleanupBucket(bucketName, c)
// Generate 33K of data.
bufSize := dataFileMap["datafile-33-kB"]
reader := getDataReader("datafile-33-kB")
defer reader.Close()
objectName := randString(60, rand.NewSource(time.Now().UnixNano()), "")
args["objectName"] = objectName
buf, err := io.ReadAll(reader)
if err != nil {
logError(testName, function, args, startTime, "", "ReadAll failed", err)
return
}
// Save the data
_, err = c.PutObject(context.Background(), bucketName, objectName, bytes.NewReader(buf), int64(len(buf)), minio.PutObjectOptions{ContentType: "binary/octet-stream"})
if err != nil {
logError(testName, function, args, startTime, "", "PutObject failed", err)
return
}
var r *minio.Object
testIndex := 0
baseSize := 0
New := func() {
opts := minio.GetObjectOptions{}
switch testIndex {
case 0:
baseSize = bufSize
case 1:
opts.SetRange(100, 1000)
baseSize = 1000 - 100 + 1
case 2:
opts.SetRange(100, 0)
baseSize = bufSize - 100
case 3:
opts.SetRange(0, 1000)
baseSize = 1000 + 1
}
r, err = c.GetObject(context.Background(), bucketName, objectName, opts)
if err != nil {
logError(testName, function, args, startTime, "", "Failed to create MinIO client object", err)
}
}
Size := func(size int) {
st, err := r.Stat()
if err != nil {
logError(testName, function, args, startTime, "", "Failed to get object stat", err)
}
if int(st.Size) != size {
logError(testName, function, args, startTime, "", "Incorrect size returned", fmt.Errorf("Test index %d Expected size %d, got %d", testIndex, size, int(st.Size)))
}
}
Read := func(size int) {
b := make([]byte, size)
_, err := r.Read(b)
if err != nil {
logError(testName, function, args, startTime, "", "Failed to read from object", err)
}
}
ReadFull := func(size int) {
b := make([]byte, size)
_, err := r.Read(b)
if err != nil {
logError(testName, function, args, startTime, "", "Failed to read from object", err)
}
}
ReadAll := func() {
_, err := io.ReadAll(r)
if err != nil {
logError(testName, function, args, startTime, "", "Failed to read from object", err)
}
}
Seek := func(offset int64, whence int) {
_, err := r.Seek(offset, whence)
if err != nil {
logError(testName, function, args, startTime, "", "Failed to seek in object", err)
}
}
ReadAt := func(offset int64, size int64) {
b := make([]byte, size)
_, err := r.ReadAt(b, offset)
if err != nil {
logError(testName, function, args, startTime, "", "Failed to read from object", err)
}
}
for index := range 4 {
testIndex = index
// case 1: stat first and then read 100 bytes for per read
{
New()
Size(baseSize)
Read(100)
Size(baseSize - 100)
Read(100)
Size(baseSize - 200)
Read(100)
Size(baseSize - 300)
ReadFull(100)
Size(baseSize - 400)
}
// case 2: read 100 bytes for per read
{
New()
Read(100)
Size(baseSize - 100)
Read(100)
Size(baseSize - 200)
Read(100)
Size(baseSize - 300)
ReadFull(100)
Size(baseSize - 400)
}
// case 3: Stat -> Read -> ReadAt -> Read
{
New()
Size(baseSize)
Read(100)
Size(baseSize - 100)
// should not move the offset, so next stat is not changed
ReadAt(100, 100)
Size(baseSize - 100)
Read(100)
Size(baseSize - 200)
}
// case 4: Read -> ReadAt -> Read
{
New()
Read(100)
Size(baseSize - 100)
// should not move the offset, so next stat is not changed
ReadAt(100, 100)
Size(baseSize - 100)
Read(100)
Size(baseSize - 200)
}
// case 5: Stat -> Read -> ReadAt -> Read -> Seek -> Read
{
New()
Size(baseSize)
Read(100)
Size(baseSize - 100)
// should not move the offset, so next stat is not changed
ReadAt(100, 100)
Size(baseSize - 100)
Read(100)
Size(baseSize - 200)
Seek(100, io.SeekCurrent)
Size(baseSize - 300)
Read(100)
Size(baseSize - 400)
}
// case 6: Read -> ReadAt -> Read -> Seek -> Read
{
New()
Read(100)
Size(baseSize - 100)
// should not move the offset, so next stat is not changed
ReadAt(100, 100)
Size(baseSize - 100)
Read(100)
Size(baseSize - 200)
Seek(100, io.SeekCurrent)
Size(baseSize - 300)
Read(100)
Size(baseSize - 400)
}
// case 7: Stat -> ReadAll -> ReadAt
{
New()
Size(baseSize)
ReadAll()
ReadAt(100, 100)
}
// case 8: ReadAll -> ReadAt
{
New()
ReadAll()
ReadAt(100, 100)
}
// case9: Seek first
{
New()
Seek(100, io.SeekCurrent)
Size(baseSize - 100)
Read(100)
Size(baseSize - 200)
}
}
}
// Reproduces issue https://github.com/minio/minio-go/issues/1137
func testGetObjectReadAtWhenEOFWasReached() {
// initialize logging params
@@ -5746,7 +6131,7 @@ func testGetObjectReadAtWhenEOFWasReached() {
return
}
if st.Size != int64(bufSize) {
if st.Size != (int64(bufSize) - int64(len(buf1))) {
logError(testName, function, args, startTime, "", "Number of bytes in stat does not match, expected "+string(int64(bufSize))+", got "+string(st.Size), err)
return
}
@@ -6527,7 +6912,7 @@ func testSSECEncryptedGetObjectReadSeekFunctional() {
}
if st.Size != int64(bufSize) {
logError(testName, function, args, startTime, "", "Number of bytes does not match, expected "+string(int64(bufSize))+", got "+string(st.Size), err)
logError(testName, function, args, startTime, "", "Number of bytes does not match, expected "+strconv.Itoa(bufSize)+", got "+strconv.FormatInt(st.Size, 10), err)
return
}
@@ -6563,17 +6948,20 @@ func testSSECEncryptedGetObjectReadSeekFunctional() {
{0, 0, 0, nil, true, 0, 0},
// Start from offset 2048, fetch data and compare
{2048, 0, 2048, nil, true, 2048, bufSize},
// Start from offset larger than possible
// Start from offset larger than possible: Seek rejects it with io.EOF
// and keeps the offset unchanged.
{int64(bufSize) + 1024, 0, 0, io.EOF, false, 0, 0},
// Move to offset 0 without comparing
{0, 0, 0, nil, false, 0, 0},
// Move one step forward and compare
{1, 1, 1, nil, true, 1, bufSize},
// Move larger than possible
// Move larger than possible: Seek returns io.EOF.
{int64(bufSize), 1, 0, io.EOF, false, 0, 0},
// Provide negative offset with CUR_SEEK
{int64(-1), 1, 0, fmt.Errorf("Negative position not allowed for 1"), false, 0, 0},
// Test with whence SEEK_END and with positive offset
// Provide negative offset with CUR_SEEK: valid since the resulting
// absolute position is within the object.
{int64(-1), 1, int64(bufSize) - 1, nil, false, 0, 0},
// Test with whence SEEK_END and with positive offset: Seek returns
// io.EOF.
{1024, 2, 0, io.EOF, false, 0, 0},
// Test with whence SEEK_END and with negative offset
{-1024, 2, int64(bufSize) - 1024, nil, true, bufSize - 1024, bufSize},
@@ -6581,9 +6969,18 @@ func testSSECEncryptedGetObjectReadSeekFunctional() {
{-int64(bufSize) * 2, 2, 0, fmt.Errorf("Seeking at negative offset not allowed for 2"), false, 0, 0},
// Test with invalid whence
{0, 3, 0, fmt.Errorf("Invalid whence 3"), false, 0, 0},
// Seek to exactly the object end; the subsequent read reports io.EOF.
{0, 2, int64(bufSize), nil, false, 0, 0},
}
for i, testCase := range testCases {
// Snapshot the cursor so rejected seeks can be asserted side-effect
// free.
prevPos, err := r.Seek(0, io.SeekCurrent)
if err != nil {
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, reading the current position failed", i+1), err)
return
}
// Perform seek operation
n, err := r.Seek(testCase.offset, testCase.whence)
if err != nil && testCase.err == nil {
@@ -6605,6 +7002,12 @@ func testSSECEncryptedGetObjectReadSeekFunctional() {
fmt.Sprintf("Test %d, unexpected err value: expected: %s, found: %s", i+1, testCase.err, err), err)
return
}
// A rejected seek must leave the cursor unchanged.
curPos, cerr := r.Seek(0, io.SeekCurrent)
if cerr != nil || curPos != prevPos {
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, cursor after rejected seek: expected %d, got %d", i+1, prevPos, curPos), cerr)
return
}
}
// Check the returned seek pos
if n != testCase.pos {
@@ -6616,6 +7019,15 @@ func testSSECEncryptedGetObjectReadSeekFunctional() {
if testCase.shouldCmp {
cmpData(r, testCase.start, testCase.end)
}
// A successful seek to the object end must defer io.EOF to the
// subsequent read.
if !testCase.shouldCmp && testCase.err == nil && testCase.pos >= int64(bufSize) {
readN, readErr := r.Read(make([]byte, 1))
if readN != 0 || readErr != io.EOF {
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, read after seek to object end expected zero bytes and io.EOF, got %d bytes and %v", i+1, readN, readErr), readErr)
return
}
}
}
logSuccess(testName, function, args, startTime)
@@ -6693,7 +7105,7 @@ func testSSES3EncryptedGetObjectReadSeekFunctional() {
}
if st.Size != int64(bufSize) {
logError(testName, function, args, startTime, "", "Number of bytes does not match, expected "+string(int64(bufSize))+", got "+string(st.Size), err)
logError(testName, function, args, startTime, "", "Number of bytes does not match, expected "+strconv.Itoa(bufSize)+", got "+strconv.FormatInt(st.Size, 10), err)
return
}
@@ -6729,17 +7141,20 @@ func testSSES3EncryptedGetObjectReadSeekFunctional() {
{0, 0, 0, nil, true, 0, 0},
// Start from offset 2048, fetch data and compare
{2048, 0, 2048, nil, true, 2048, bufSize},
// Start from offset larger than possible
// Start from offset larger than possible: Seek rejects it with io.EOF
// and keeps the offset unchanged.
{int64(bufSize) + 1024, 0, 0, io.EOF, false, 0, 0},
// Move to offset 0 without comparing
{0, 0, 0, nil, false, 0, 0},
// Move one step forward and compare
{1, 1, 1, nil, true, 1, bufSize},
// Move larger than possible
// Move larger than possible: Seek returns io.EOF.
{int64(bufSize), 1, 0, io.EOF, false, 0, 0},
// Provide negative offset with CUR_SEEK
{int64(-1), 1, 0, fmt.Errorf("Negative position not allowed for 1"), false, 0, 0},
// Test with whence SEEK_END and with positive offset
// Provide negative offset with CUR_SEEK: valid since the resulting
// absolute position is within the object.
{int64(-1), 1, int64(bufSize) - 1, nil, false, 0, 0},
// Test with whence SEEK_END and with positive offset: Seek returns
// io.EOF.
{1024, 2, 0, io.EOF, false, 0, 0},
// Test with whence SEEK_END and with negative offset
{-1024, 2, int64(bufSize) - 1024, nil, true, bufSize - 1024, bufSize},
@@ -6747,9 +7162,18 @@ func testSSES3EncryptedGetObjectReadSeekFunctional() {
{-int64(bufSize) * 2, 2, 0, fmt.Errorf("Seeking at negative offset not allowed for 2"), false, 0, 0},
// Test with invalid whence
{0, 3, 0, fmt.Errorf("Invalid whence 3"), false, 0, 0},
// Seek to exactly the object end; the subsequent read reports io.EOF.
{0, 2, int64(bufSize), nil, false, 0, 0},
}
for i, testCase := range testCases {
// Snapshot the cursor so rejected seeks can be asserted side-effect
// free.
prevPos, err := r.Seek(0, io.SeekCurrent)
if err != nil {
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, reading the current position failed", i+1), err)
return
}
// Perform seek operation
n, err := r.Seek(testCase.offset, testCase.whence)
if err != nil && testCase.err == nil {
@@ -6771,6 +7195,12 @@ func testSSES3EncryptedGetObjectReadSeekFunctional() {
fmt.Sprintf("Test %d, unexpected err value: expected: %s, found: %s", i+1, testCase.err, err), err)
return
}
// A rejected seek must leave the cursor unchanged.
curPos, cerr := r.Seek(0, io.SeekCurrent)
if cerr != nil || curPos != prevPos {
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, cursor after rejected seek: expected %d, got %d", i+1, prevPos, curPos), cerr)
return
}
}
// Check the returned seek pos
if n != testCase.pos {
@@ -6782,6 +7212,15 @@ func testSSES3EncryptedGetObjectReadSeekFunctional() {
if testCase.shouldCmp {
cmpData(r, testCase.start, testCase.end)
}
// A successful seek to the object end must defer io.EOF to the
// subsequent read.
if !testCase.shouldCmp && testCase.err == nil && testCase.pos >= int64(bufSize) {
readN, readErr := r.Read(make([]byte, 1))
if readN != 0 || readErr != io.EOF {
logError(testName, function, args, startTime, "", fmt.Sprintf("Test %d, read after seek to object end expected zero bytes and io.EOF, got %d bytes and %v", i+1, readN, readErr), readErr)
return
}
}
}
logSuccess(testName, function, args, startTime)
@@ -6879,7 +7318,7 @@ func testSSECEncryptedGetObjectReadAtFunctional() {
}
if st.Size != int64(bufSize) {
logError(testName, function, args, startTime, "", "Number of bytes in stat does not match, expected "+string(int64(bufSize))+", got "+string(st.Size), err)
logError(testName, function, args, startTime, "", "Number of bytes in stat does not match, expected "+strconv.Itoa(bufSize)+", got "+strconv.Itoa(int(st.Size)), err)
return
}
@@ -8856,7 +9295,7 @@ func testGetObjectReadSeekFunctionalV2() {
}
if st.Size != int64(bufSize) {
logError(testName, function, args, startTime, "", "Number of bytes in stat does not match, expected "+string(int64(bufSize))+" got "+string(st.Size), err)
logError(testName, function, args, startTime, "", "Number of bytes in stat does not match, expected "+strconv.Itoa(bufSize)+" got "+strconv.FormatInt(st.Size, 10), err)
return
}
@@ -8867,7 +9306,7 @@ func testGetObjectReadSeekFunctionalV2() {
return
}
if n != offset {
logError(testName, function, args, startTime, "", "Number of seeked bytes does not match, expected "+string(offset)+" got "+string(n), err)
logError(testName, function, args, startTime, "", "Number of seeked bytes does not match, expected "+strconv.FormatInt(offset, 10)+" got "+strconv.FormatInt(n, 10), err)
return
}
n, err = r.Seek(0, 1)
@@ -8876,12 +9315,44 @@ func testGetObjectReadSeekFunctionalV2() {
return
}
if n != offset {
logError(testName, function, args, startTime, "", "Number of seeked bytes does not match, expected "+string(offset)+" got "+string(n), err)
logError(testName, function, args, startTime, "", "Number of seeked bytes does not match, expected "+strconv.FormatInt(offset, 10)+" got "+strconv.FormatInt(n, 10), err)
return
}
_, err = r.Seek(offset, 2)
if err == nil {
logError(testName, function, args, startTime, "", "Seek on positive offset for whence '2' should error out", err)
// Seeking past the object end with SEEK_END is rejected with io.EOF and
// leaves the offset unchanged.
n, err = r.Seek(offset, 2)
if err != io.EOF {
logError(testName, function, args, startTime, "", "Seek past object end should return io.EOF", err)
return
}
if n != 0 {
logError(testName, function, args, startTime, "", "Seek past object end should return offset 0, got "+strconv.FormatInt(n, 10), err)
return
}
// A rejected seek must leave the cursor unchanged.
n, err = r.Seek(0, 1)
if err != nil {
logError(testName, function, args, startTime, "", "Seek failed", err)
return
}
if n != offset {
logError(testName, function, args, startTime, "", "Cursor moved after rejected seek, expected "+strconv.FormatInt(offset, 10)+" got "+strconv.FormatInt(n, 10), err)
return
}
// Seeking to exactly the object end succeeds; the subsequent read reports
// io.EOF.
n, err = r.Seek(0, 2)
if err != nil {
logError(testName, function, args, startTime, "", "Seek failed", err)
return
}
if n != st.Size {
logError(testName, function, args, startTime, "", "Number of seeked bytes does not match, expected "+strconv.FormatInt(st.Size, 10)+" got "+strconv.FormatInt(n, 10), err)
return
}
readN, readErr := r.Read(make([]byte, 1))
if readN != 0 || readErr != io.EOF {
logError(testName, function, args, startTime, "", "Read after seeking to object end should return zero bytes and EOF", readErr)
return
}
n, err = r.Seek(-offset, 2)
@@ -8890,7 +9361,7 @@ func testGetObjectReadSeekFunctionalV2() {
return
}
if n != st.Size-offset {
logError(testName, function, args, startTime, "", "Number of seeked bytes does not match, expected "+string(st.Size-offset)+" got "+string(n), err)
logError(testName, function, args, startTime, "", "Number of seeked bytes does not match, expected "+strconv.FormatInt(st.Size-offset, 10)+" got "+strconv.FormatInt(n, 10), err)
return
}
@@ -8913,7 +9384,7 @@ func testGetObjectReadSeekFunctionalV2() {
return
}
if n != (offset - 1) {
logError(testName, function, args, startTime, "", "Number of seeked bytes does not match, expected "+string(offset-1)+" got "+string(n), err)
logError(testName, function, args, startTime, "", "Number of seeked bytes does not match, expected "+strconv.FormatInt(offset-1, 10)+" got "+strconv.FormatInt(n, 10), err)
return
}
@@ -15084,6 +15555,7 @@ func main() {
testMakeBucketError()
testMakeBucketRegions()
testPutObjectWithMetadata()
testGetObjectWithRange()
testPutObjectReadAt()
testPutObjectStreaming()
testPutObjectPreconditionOnNonExistent()
@@ -15122,6 +15594,7 @@ func main() {
testRemoveObjects()
testRemoveObjectsIter()
testListObjectVersions()
testStatObjectResponseHeaders()
testStatObjectWithVersioning()
testGetObjectWithVersioning()
testCopyObjectWithVersioning()
+26 -18
View File
@@ -25,22 +25,31 @@ import (
// hookReader hooks additional reader in the source stream. It is
// useful for making progress bars. Second reader is appropriately
// notified about the exact number of bytes read from the primary
// source on each Read operation.
// source on each Read operation. It deliberately implements neither
// io.Seeker nor io.Closer: retry logic treats a seekable body as
// rewindable, and executeMethod closes request bodies that implement
// io.Closer — a caller-supplied reader must be shielded from both.
type hookReader struct {
source io.Reader
hook io.Reader
}
// hookReadSeeker extends hookReader with seeking support. It is
// constructed only when the source implements io.Seeker, so a wrapped
// reader exposes Seek if and only if it can actually rewind. This lets
// retry logic disable retries for non-seekable bodies instead of
// retrying over a drained reader.
type hookReadSeeker struct {
hookReader
seeker io.Seeker
}
// Seek implements io.Seeker. Seeks source first, and if necessary
// seeks hook if Seek method is appropriately found.
func (hr *hookReader) Seek(offset int64, whence int) (n int64, err error) {
// Verify for source has embedded Seeker, use it.
sourceSeeker, ok := hr.source.(io.Seeker)
if ok {
n, err = sourceSeeker.Seek(offset, whence)
if err != nil {
return 0, err
}
func (hr *hookReadSeeker) Seek(offset int64, whence int) (n int64, err error) {
n, err = hr.seeker.Seek(offset, whence)
if err != nil {
return 0, err
}
if hr.hook != nil {
@@ -53,7 +62,7 @@ func (hr *hookReader) Seek(offset int64, whence int) (n int64, err error) {
return 0, err
}
if n != m {
return 0, fmt.Errorf("hook seeker seeked %d bytes, expected source %d bytes", m, n)
return 0, fmt.Errorf("hook seeker sought to offset %d, expected source offset %d", m, n)
}
}
}
@@ -80,14 +89,13 @@ func (hr *hookReader) Read(b []byte) (n int, err error) {
return n, err
}
// newHook returns a io.ReadSeeker which implements hookReader that
// reports the data read from the source to the hook.
// newHook returns an io.Reader that reports the data read from the
// source to the hook. The returned reader implements io.Seeker only
// when the source does.
func newHook(source, hook io.Reader) io.Reader {
if hook == nil {
return &hookReader{source: source}
}
return &hookReader{
source: source,
hook: hook,
hr := hookReader{source: source, hook: hook}
if seeker, ok := source.(io.Seeker); ok {
return &hookReadSeeker{hookReader: hr, seeker: seeker}
}
return &hr
}
+4 -3
View File
@@ -19,6 +19,7 @@ package credentials
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/xml"
@@ -142,7 +143,7 @@ func closeResponse(resp *http.Response) {
}
}
func getAssumeRoleCredentials(clnt *http.Client, endpoint string, opts STSAssumeRoleOptions) (AssumeRoleResponse, error) {
func getAssumeRoleCredentials(ctx context.Context, clnt *http.Client, endpoint string, opts STSAssumeRoleOptions) (AssumeRoleResponse, error) {
v := url.Values{}
v.Set("Action", "AssumeRole")
v.Set("Version", STSVersion)
@@ -180,7 +181,7 @@ func getAssumeRoleCredentials(clnt *http.Client, endpoint string, opts STSAssume
}
postBody.Seek(0, 0)
req, err := http.NewRequest(http.MethodPost, u.String(), postBody)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), postBody)
if err != nil {
return AssumeRoleResponse{}, err
}
@@ -245,7 +246,7 @@ func (m *STSAssumeRole) RetrieveWithCredContext(cc *CredContext) (Value, error)
return Value{}, errors.New("STS endpoint unknown")
}
a, err := getAssumeRoleCredentials(client, stsEndpoint, m.Options)
a, err := getAssumeRoleCredentials(cc.requestContext(), client, stsEndpoint, m.Options)
if err != nil {
return Value{}, err
}
@@ -0,0 +1,57 @@
[profile p1]
sso_session = main
sso_account_id = 123456789
sso_role_name = myrole
[sso-session main]
sso_region = us-test-2
sso_start_url = https://testacct.awsapps.com/start
[profile p2-legacy]
sso_start_url = https://legacy.awsapps.com/start
sso_region = us-test-1
sso_account_id = 987654321
sso_role_name = legacyrole
[profile p3-broken]
sso_account_id = 111111111
sso_role_name = brokenrole
[profile p4-noregion]
sso_start_url = https://noregion.awsapps.com/start
sso_account_id = 222222222
sso_role_name = noregionrole
[profile p5-ghost-session]
sso_session = ghost
sso_account_id = 333333333
sso_role_name = ghostrole
[profile p6-norole]
sso_start_url = https://norole.awsapps.com/start
sso_region = us-test-1
sso_account_id = 444444444
[profile p7-noaccount]
sso_session = main
sso_role_name = noaccountrole
[profile p8-mixed]
sso_start_url = https://mixed.awsapps.com/start
aws_access_key_id = mixedAccessKey
aws_secret_access_key = mixedSecret
[profile p9-mixed-complete]
sso_session = main
sso_account_id = 555555555
sso_role_name = mixedcompleterole
aws_access_key_id = completeAccessKey
aws_secret_access_key = completeSecret
[profile p10-partial-key]
sso_start_url = https://partial.awsapps.com/start
aws_access_key_id = partialAccessKey
[profile p11-partial-secret]
sso_session = main
aws_secret_access_key = partialSecret
+16
View File
@@ -18,6 +18,7 @@
package credentials
import (
"context"
"net/http"
"sync"
"time"
@@ -85,6 +86,21 @@ type CredContext struct {
// Endpoint specifies the MinIO endpoint that will be used if no
// explicit endpoint is provided.
Endpoint string
// Context is the optional caller context. Cancellation and deadlines
// on it propagate to the HTTP requests the built-in providers make
// to fetch credentials, in addition to any provider-level timeout
// bound. A nil Context means no caller cancellation applies.
Context context.Context
}
// requestContext returns the caller context carried by cc, or
// context.Background() when no Context is set.
func (cc *CredContext) requestContext() context.Context {
if cc.Context == nil {
return context.Background()
}
return cc.Context
}
// A Expiry provides shared expiration logic to be used by credentials
+419 -33
View File
@@ -18,8 +18,15 @@
package credentials
import (
"context"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"os/exec"
"path/filepath"
@@ -29,7 +36,10 @@ import (
"gopkg.in/ini.v1"
)
// A externalProcessCredentials stores the output of a credential_process
// ssoPortalRequestTimeout bounds the AWS SSO portal role-credentials request.
const ssoPortalRequestTimeout = time.Minute
// An externalProcessCredentials stores the output of a credential_process
type externalProcessCredentials struct {
Version int
SessionToken string
@@ -38,6 +48,34 @@ type externalProcessCredentials struct {
Expiration time.Time
}
// An ssoCredentials stores the response of fetching role credentials for
// an AWS SSO role from the SSO portal.
type ssoCredentials struct {
RoleCredentials ssoRoleCredentials `json:"roleCredentials"`
}
// An ssoRoleCredentials stores the role-specific credentials portion of
// an SSO role credentials response. Expiration is milliseconds since
// the Unix epoch.
type ssoRoleCredentials struct {
AccessKeyID string `json:"accessKeyId"`
Expiration int64 `json:"expiration"`
SecretAccessKey string `json:"secretAccessKey"`
SessionToken string `json:"sessionToken"`
}
func (s ssoRoleCredentials) expirationTime() time.Time {
return time.Unix(0, s.Expiration*int64(time.Millisecond))
}
// ssoCachedToken is the subset of the cached token file written by
// `aws sso login` under ~/.aws/sso/cache/ that we need.
type ssoCachedToken struct {
AccessToken string `json:"accessToken"`
ExpiresAt time.Time `json:"expiresAt"`
Region string `json:"region"`
}
// A FileAWSCredentials retrieves credentials from the current user's home
// directory, and keeps track if those credentials are expired.
//
@@ -47,10 +85,15 @@ type FileAWSCredentials struct {
// Path to the shared credentials file.
//
// If empty will look for "AWS_SHARED_CREDENTIALS_FILE" env variable. If the
// env value is empty will default to current user's home directory.
// Linux/OSX: "$HOME/.aws/credentials"
// Windows: "%USERPROFILE%\.aws\credentials"
// If empty, the default AWS files are merged instead: the AWS config
// file ("AWS_CONFIG_FILE" env variable or "$HOME/.aws/config") loaded
// first, then the shared credentials file
// ("AWS_SHARED_CREDENTIALS_FILE" env variable or
// "$HOME/.aws/credentials") overriding matching keys, the same
// resolution the AWS SDK uses. Profiles written by `aws configure sso`
// live in the config file and are discovered this way.
//
// If set, only this one file is read.
Filename string
// AWS Profile to extract credentials from the shared credentials file. If empty
@@ -60,6 +103,14 @@ type FileAWSCredentials struct {
// retrieved states if the credentials have been successfully retrieved.
retrieved bool
// overrideSSOCacheDir overrides, for tests, the directory holding the
// cached SSO tokens (defaults to ~/.aws/sso/cache).
overrideSSOCacheDir string
// overrideSSOPortalURL overrides, for tests, the AWS SSO portal URL
// serving role credentials.
overrideSSOPortalURL string
}
// NewFileAWSCredentials returns a pointer to a new Credentials object
@@ -71,27 +122,27 @@ func NewFileAWSCredentials(filename, profile string) *Credentials {
})
}
func (p *FileAWSCredentials) retrieve() (Value, error) {
if p.Filename == "" {
p.Filename = os.Getenv("AWS_SHARED_CREDENTIALS_FILE")
if p.Filename == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
return Value{}, err
}
p.Filename = filepath.Join(homeDir, ".aws", "credentials")
}
}
if p.Profile == "" {
p.Profile = os.Getenv("AWS_PROFILE")
if p.Profile == "" {
p.Profile = "default"
func (p *FileAWSCredentials) retrieve(cc *CredContext) (Value, error) {
profile := p.Profile
if profile == "" {
profile = os.Getenv("AWS_PROFILE")
if profile == "" {
profile = "default"
}
}
p.retrieved = false
iniProfile, err := loadProfile(p.Filename, p.Profile)
var (
iniConfig *ini.File
iniProfile *ini.Section
err error
)
if p.Filename != "" {
iniConfig, iniProfile, err = loadProfile(p.Filename, profile)
} else {
iniConfig, iniProfile, err = loadDefaultProfiles(profile)
}
if err != nil {
return Value{}, err
}
@@ -103,10 +154,53 @@ func (p *FileAWSCredentials) retrieve() (Value, error) {
// Default to empty string if not found.
token := iniProfile.Key("aws_session_token")
// If credential_process is defined, obtain credentials by executing
// the external process
// A complete static key pair takes precedence over SSO configuration
// and credential_process in the same profile, matching aws-sdk-go-v2's
// resolution order: static credentials, then SSO, then
// credential_process.
hasStaticKeys := id.String() != "" && secret.String() != ""
// Exactly one half of a static key pair is never usable and poisons
// downstream consumers — Chain accepts a Value when either field is
// set — so it is rejected before any resolution, matching
// aws-sdk-go-v2's partial-credentials validation.
if !hasStaticKeys && (id.String() != "" || secret.String() != "") {
return Value{}, errors.New("profile has partial static credentials: aws_access_key_id and aws_secret_access_key must both be set")
}
// If the profile is configured for AWS SSO, obtain credentials from the
// token cached by `aws sso login`.
if !hasStaticKeys && iniProfile.Key("sso_role_name").String() != "" {
ssoCreds, err := p.getSSOCredentials(cc, iniConfig, iniProfile)
if err != nil {
return Value{}, err
}
expiration := ssoCreds.RoleCredentials.expirationTime()
p.retrieved = true
p.SetExpiration(expiration, DefaultExpiryWindow)
return Value{
AccessKeyID: ssoCreds.RoleCredentials.AccessKeyID,
SecretAccessKey: ssoCreds.RoleCredentials.SecretAccessKey,
SessionToken: ssoCreds.RoleCredentials.SessionToken,
Expiration: expiration,
SignerType: SignatureV4,
}, nil
}
// A profile carrying SSO configuration without sso_role_name cannot
// engage the SSO flow above; without a complete static key pair the
// values below would be anonymous.
if !hasStaticKeys &&
(iniProfile.Key("sso_session").String() != "" || iniProfile.Key("sso_start_url").String() != "" ||
iniProfile.Key("sso_account_id").String() != "" || iniProfile.Key("sso_region").String() != "") {
return Value{}, errors.New("profile has SSO configuration but no sso_role_name, and no complete static credentials")
}
// If credential_process is defined, obtain credentials by executing the
// external process. Static credentials and SSO in the same profile both
// take precedence over it, matching aws-sdk-go-v2.
credentialProcess := strings.TrimSpace(iniProfile.Key("credential_process").String())
if credentialProcess != "" {
if !hasStaticKeys && credentialProcess != "" {
args := strings.Fields(credentialProcess)
if len(args) <= 1 {
return Value{}, errors.New("invalid credential process args")
@@ -131,6 +225,7 @@ func (p *FileAWSCredentials) retrieve() (Value, error) {
SignerType: SignatureV4,
}, nil
}
p.retrieved = true
return Value{
AccessKeyID: id.String(),
@@ -140,28 +235,319 @@ func (p *FileAWSCredentials) retrieve() (Value, error) {
}, nil
}
// getSSOCredentials fetches role credentials for an SSO-configured profile
// from the AWS SSO portal, using the access token cached by `aws sso login`.
func (p *FileAWSCredentials) getSSOCredentials(cc *CredContext, iniConfig *ini.File, iniProfile *ini.Section) (ssoCredentials, error) {
ssoAccountID := iniProfile.Key("sso_account_id").String()
ssoRoleName := iniProfile.Key("sso_role_name").String()
if ssoAccountID == "" {
return ssoCredentials{}, errors.New("profile defines sso_role_name but no sso_account_id")
}
// Modern config: the profile references an [sso-session <name>] section
// and the cached token file is named after the SHA1 of the session name.
// Legacy config: sso_start_url/sso_region live directly on the profile
// and the cached token file is named after the SHA1 of the start URL.
ssoSessionName := iniProfile.Key("sso_session").String()
cacheKey := ssoSessionName
ssoRegion := iniProfile.Key("sso_region").String()
if ssoSessionName != "" {
if sessionSection, err := iniConfig.GetSection("sso-session " + ssoSessionName); err == nil {
// aws-sdk-go-v2 rejects profile sso_region/sso_start_url
// values that contradict the sso-session; guessing between
// the two could silently query the wrong portal.
if region := sessionSection.Key("sso_region").String(); region != "" {
if ssoRegion != "" && ssoRegion != region {
return ssoCredentials{}, fmt.Errorf("sso_region %q in profile must match sso_region %q in sso-session %q", ssoRegion, region, ssoSessionName)
}
ssoRegion = region
}
if sessionStartURL := sessionSection.Key("sso_start_url").String(); sessionStartURL != "" {
if profileStartURL := iniProfile.Key("sso_start_url").String(); profileStartURL != "" && profileStartURL != sessionStartURL {
return ssoCredentials{}, fmt.Errorf("sso_start_url %q in profile must match sso_start_url %q in sso-session %q", profileStartURL, sessionStartURL, ssoSessionName)
}
}
}
} else {
startURL := iniProfile.Key("sso_start_url").String()
if startURL == "" {
return ssoCredentials{}, errors.New("profile defines sso_role_name but neither sso_session nor sso_start_url")
}
cacheKey = startURL
}
hash := sha1.Sum([]byte(cacheKey))
cachedTokenFilename := hex.EncodeToString(hash[:]) + ".json"
cacheDir := p.overrideSSOCacheDir
if cacheDir == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
return ssoCredentials{}, fmt.Errorf("getting home dir: %w", err)
}
cacheDir = filepath.Join(homeDir, ".aws", "sso", "cache")
}
cachedTokenPath := filepath.Join(cacheDir, cachedTokenFilename)
cachedTokenRaw, err := os.ReadFile(cachedTokenPath)
if err != nil {
return ssoCredentials{}, fmt.Errorf("reading cached SSO token %q (try `aws sso login`): %w", cachedTokenPath, err)
}
var cachedToken ssoCachedToken
if err := json.Unmarshal(cachedTokenRaw, &cachedToken); err != nil {
return ssoCredentials{}, fmt.Errorf("parsing cached SSO token %q: %w", cachedTokenPath, err)
}
now := time.Now
if p.CurrentTime != nil {
now = p.CurrentTime
}
if cachedToken.ExpiresAt.Before(now()) {
return ssoCredentials{}, errors.New("cached SSO token is expired, refresh it with `aws sso login`")
}
if ssoRegion == "" {
ssoRegion = cachedToken.Region
}
if ssoRegion == "" {
return ssoCredentials{}, errors.New("unable to determine AWS SSO region from profile, sso-session or cached token")
}
portalURL := p.overrideSSOPortalURL
if portalURL == "" {
portalURL = ssoPortalBaseURL(ssoRegion)
}
if cc == nil {
cc = defaultCredContext
}
ctx, cancel := context.WithTimeout(cc.requestContext(), ssoPortalRequestTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, portalURL+"/federation/credentials", nil)
if err != nil {
return ssoCredentials{}, fmt.Errorf("creating SSO role credentials request: %w", err)
}
req.Header.Set("x-amz-sso_bearer_token", cachedToken.AccessToken)
query := req.URL.Query()
query.Add("account_id", ssoAccountID)
query.Add("role_name", ssoRoleName)
req.URL.RawQuery = query.Encode()
client := cc.Client
if client == nil {
client = defaultCredContext.Client
}
resp, err := client.Do(req)
if err != nil {
return ssoCredentials{}, fmt.Errorf("fetching SSO role credentials: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
return ssoCredentials{}, fmt.Errorf("fetching SSO role credentials: %s: %s", resp.Status, strings.TrimSpace(string(body)))
}
var ssoCreds ssoCredentials
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&ssoCreds); err != nil {
return ssoCredentials{}, fmt.Errorf("parsing SSO role credentials response: %w", err)
}
if ssoCreds.RoleCredentials.AccessKeyID == "" || ssoCreds.RoleCredentials.SecretAccessKey == "" {
return ssoCredentials{}, errors.New("SSO portal returned empty role credentials")
}
return ssoCreds, nil
}
// ssoPortalBaseURL returns the AWS SSO portal endpoint for region. The DNS
// suffix follows the region's AWS partition per aws-sdk-go-v2 endpoint
// metadata; regions of unlisted partitions, including aws-us-gov, use the
// standard amazonaws.com suffix.
func ssoPortalBaseURL(region string) string {
suffix := "amazonaws.com"
switch {
case strings.HasPrefix(region, "cn-"):
suffix = "amazonaws.com.cn"
case strings.HasPrefix(region, "us-iso-"):
suffix = "c2s.ic.gov"
case strings.HasPrefix(region, "us-isob-"):
suffix = "sc2s.sgov.gov"
case strings.HasPrefix(region, "eu-isoe-"):
suffix = "cloud.adc-e.uk"
case strings.HasPrefix(region, "us-isof-"):
suffix = "csp.hci.ic.gov"
case strings.HasPrefix(region, "eusc-"):
suffix = "amazonaws.eu"
}
return fmt.Sprintf("https://portal.sso.%s.%s", region, suffix)
}
// Retrieve reads and extracts the shared credentials from the current
// users home directory.
//
// Deprecated: Retrieve() exists for historical compatibility and should not
// be used. To get new credentials use the RetrieveWithCredContext function.
func (p *FileAWSCredentials) Retrieve() (Value, error) {
return p.retrieve()
return p.retrieve(nil)
}
// RetrieveWithCredContext is like Retrieve(), cred context is no-op for File credentials
func (p *FileAWSCredentials) RetrieveWithCredContext(_ *CredContext) (Value, error) {
return p.retrieve()
// RetrieveWithCredContext retrieves credentials from the file like Retrieve,
// using the context's HTTP client for any SSO portal call.
func (p *FileAWSCredentials) RetrieveWithCredContext(cc *CredContext) (Value, error) {
return p.retrieve(cc)
}
// loadProfiles loads from the file pointed to by shared credentials filename for profile.
// loadProfile loads from the file pointed to by shared credentials filename for profile.
// The credentials retrieved from the profile will be returned or error. Error will be
// returned if it fails to read from the file, or the data is invalid.
func loadProfile(filename, profile string) (*ini.Section, error) {
func loadProfile(filename, profile string) (*ini.File, *ini.Section, error) {
config, err := ini.Load(filename)
if err != nil {
return nil, err
return nil, nil, err
}
iniProfile, err := config.GetSection(profile)
if err != nil {
return nil, err
// AWS config files (~/.aws/config) name non-default profile
// sections "profile <name>".
var sectionErr error
iniProfile, sectionErr = config.GetSection("profile " + profile)
if sectionErr != nil {
return nil, nil, err
}
}
return config, iniProfile, nil
}
// loadDefaultProfiles loads profile from the default AWS files, mirroring
// the AWS SDK's shared-config resolution: the config file (AWS_CONFIG_FILE
// or ~/.aws/config) is loaded first and the shared credentials file
// (AWS_SHARED_CREDENTIALS_FILE or ~/.aws/credentials) overrides matching
// keys. A missing file is tolerated as long as the other one loads; a file
// that exists but fails to parse aborts resolution, like aws-sdk-go-v2,
// because silently skipping it could resolve credentials from the wrong
// (lower-precedence) source.
func loadDefaultProfiles(profile string) (*ini.File, *ini.Section, error) {
configFilename := os.Getenv("AWS_CONFIG_FILE")
credsFilename := os.Getenv("AWS_SHARED_CREDENTIALS_FILE")
var loadErrs []error
if configFilename == "" || credsFilename == "" {
// A home-dir failure only rules out the files defaulted under it;
// a file named via env var must still load.
homeDir, err := os.UserHomeDir()
if err != nil {
loadErrs = append(loadErrs, err)
} else {
if configFilename == "" {
configFilename = filepath.Join(homeDir, ".aws", "config")
}
if credsFilename == "" {
credsFilename = filepath.Join(homeDir, ".aws", "credentials")
}
}
}
merged := ini.Empty()
loaded := false
if configFilename != "" {
config, err := ini.Load(configFilename)
switch {
case err == nil:
loaded = true
mergeAWSConfigSections(merged, config)
case errors.Is(err, fs.ErrNotExist):
loadErrs = append(loadErrs, err)
default:
return nil, nil, err
}
}
if credsFilename != "" {
config, err := ini.Load(credsFilename)
switch {
case err == nil:
loaded = true
mergeAWSCredentialsSections(merged, config)
case errors.Is(err, fs.ErrNotExist):
loadErrs = append(loadErrs, err)
default:
return nil, nil, err
}
}
if !loaded {
// Prefer the home-dir error when there is one (the informative
// failure); otherwise return the last not-exist error bare so the
// legacy os.IsNotExist probe on a missing-files result keeps working.
err := loadErrs[len(loadErrs)-1]
for _, e := range loadErrs {
if !errors.Is(e, fs.ErrNotExist) {
err = e
break
}
}
return nil, nil, err
}
iniProfile, err := merged.GetSection(profile)
if err != nil {
return nil, nil, err
}
return merged, iniProfile, nil
}
// mergeAWSConfigSections copies the AWS config file's sections into dst
// under the SDK's config-file rules: bare sections other than "default" and
// "sso-session <name>" are invalid profile names and ignored, and a
// "profile <name>" section is renamed to <name>, replacing a bare
// same-named section wholesale rather than merging with it.
func mergeAWSConfigSections(dst, src *ini.File) {
for _, section := range src.Sections() {
name := section.Name()
if name == ini.DefaultSection || strings.HasPrefix(name, "profile ") ||
(!strings.EqualFold(name, "default") && !strings.HasPrefix(name, "sso-session ")) {
continue
}
copySectionKeys(dst.Section(name), section)
}
for _, section := range src.Sections() {
name := section.Name()
if !strings.HasPrefix(name, "profile ") {
continue
}
dstSection := dst.Section(strings.TrimPrefix(name, "profile "))
for _, key := range dstSection.Keys() {
dstSection.DeleteKey(key.Name())
}
copySectionKeys(dstSection, section)
}
}
// mergeAWSCredentialsSections copies the shared credentials file's sections
// into dst, overriding matching keys; "profile "-prefixed section names are
// invalid in the credentials file and ignored. When a section overrides an
// existing profile, the static credentials move atomically:
// aws_access_key_id, aws_secret_access_key and aws_session_token are only
// taken from an overriding section carrying the complete key pair, so a
// partial pair cannot clobber half of an existing one. A section new to
// the merge is copied as-is; a partial pair it carries is rejected at
// resolution time, matching aws-sdk-go-v2's partial-credentials error.
func mergeAWSCredentialsSections(dst, src *ini.File) {
for _, section := range src.Sections() {
name := section.Name()
if name == ini.DefaultSection || strings.HasPrefix(name, "profile ") {
continue
}
_, err := dst.GetSection(name)
newSection := err != nil
hasPair := section.HasKey("aws_access_key_id") && section.HasKey("aws_secret_access_key")
dstSection := dst.Section(name)
for _, key := range section.Keys() {
switch key.Name() {
case "aws_access_key_id", "aws_secret_access_key", "aws_session_token":
if !newSection && !hasPair {
continue
}
}
dstSection.Key(key.Name()).SetValue(key.Value())
}
}
}
func copySectionKeys(dst, src *ini.Section) {
for _, key := range src.Keys() {
dst.Key(key.Name()).SetValue(key.Value())
}
return iniProfile, nil
}
+48 -19
View File
@@ -58,6 +58,17 @@ type IAM struct {
// Region configurable custom region for STS
Region string
// ExpiryWindow configures how long before the actual credential
// expiration the credentials are considered expired and refreshed.
// The zero value keeps the default behavior of refreshing once 80%
// of the credential lifetime has elapsed. A positive value refreshes
// that long before the actual expiration; a value that meets or
// exceeds the credential lifetime places the effective expiration at
// or before the moment of retrieval, so the credentials are refreshed
// on every subsequent retrieval. A negative value behaves like the
// default.
ExpiryWindow time.Duration
// Support for container authorization token https://docs.aws.amazon.com/sdkref/latest/guide/feature-container-credentials.html
Container struct {
AuthorizationToken string
@@ -94,6 +105,15 @@ func NewIAM(endpoint string) *Credentials {
})
}
// expiryWindow returns the configured ExpiryWindow, falling back to
// DefaultExpiryWindow when unset or negative.
func (m *IAM) expiryWindow() time.Duration {
if m.ExpiryWindow <= 0 {
return DefaultExpiryWindow
}
return m.ExpiryWindow
}
// RetrieveWithCredContext is like Retrieve with Cred Context
func (m *IAM) RetrieveWithCredContext(cc *CredContext) (Value, error) {
if cc == nil {
@@ -151,6 +171,8 @@ func (m *IAM) RetrieveWithCredContext(cc *CredContext) (Value, error) {
client = defaultCredContext.Client
}
ctx := cc.requestContext()
endpoint := m.Endpoint
switch {
@@ -184,7 +206,11 @@ func (m *IAM) RetrieveWithCredContext(cc *CredContext) (Value, error) {
stsWebIdentityCreds, err := creds.RetrieveWithCredContext(cc)
if err == nil {
m.SetExpiration(creds.Expiration(), DefaultExpiryWindow)
// Use the raw credential expiration, not creds.Expiration():
// the inner provider has already reduced its own expiration by
// DefaultExpiryWindow, and applying a window to the reduced
// value would compound the two.
m.SetExpiration(stsWebIdentityCreds.Expiration, m.expiryWindow())
}
return stsWebIdentityCreds, err
@@ -193,11 +219,11 @@ func (m *IAM) RetrieveWithCredContext(cc *CredContext) (Value, error) {
endpoint = fmt.Sprintf("%s%s", DefaultECSRoleEndpoint, relativeURI)
}
roleCreds, err = getEcsTaskCredentials(client, endpoint, token)
roleCreds, err = getEcsTaskCredentials(ctx, client, endpoint, token)
case tokenFile != "" && fullURI != "":
endpoint = fullURI
roleCreds, err = getEKSPodIdentityCredentials(client, endpoint, tokenFile)
roleCreds, err = getEKSPodIdentityCredentials(ctx, client, endpoint, tokenFile)
case fullURI != "":
if len(endpoint) == 0 {
@@ -211,17 +237,16 @@ func (m *IAM) RetrieveWithCredContext(cc *CredContext) (Value, error) {
}
}
roleCreds, err = getEcsTaskCredentials(client, endpoint, token)
roleCreds, err = getEcsTaskCredentials(ctx, client, endpoint, token)
default:
roleCreds, err = getCredentials(client, endpoint)
roleCreds, err = getCredentials(ctx, client, endpoint)
}
if err != nil {
return Value{}, err
}
// Expiry window is set to 10secs.
m.SetExpiration(roleCreds.Expiration, DefaultExpiryWindow)
m.SetExpiration(roleCreds.Expiration, m.expiryWindow())
return Value{
AccessKeyID: roleCreds.AccessKeyID,
@@ -273,8 +298,8 @@ func getIAMRoleURL(endpoint string) (*url.URL, error) {
// with the current EC2 service. If there are no credentials,
// or there is an error making or receiving the request.
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
func listRoleNames(client *http.Client, u *url.URL, token string) ([]string, error) {
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
func listRoleNames(ctx context.Context, client *http.Client, u *url.URL, token string) ([]string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
@@ -303,8 +328,8 @@ func listRoleNames(client *http.Client, u *url.URL, token string) ([]string, err
return credsList, nil
}
func getEcsTaskCredentials(client *http.Client, endpoint, token string) (ec2RoleCredRespBody, error) {
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
func getEcsTaskCredentials(ctx context.Context, client *http.Client, endpoint, token string) (ec2RoleCredRespBody, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return ec2RoleCredRespBody{}, err
}
@@ -330,20 +355,20 @@ func getEcsTaskCredentials(client *http.Client, endpoint, token string) (ec2Role
return respCreds, nil
}
func getEKSPodIdentityCredentials(client *http.Client, endpoint string, tokenFile string) (ec2RoleCredRespBody, error) {
func getEKSPodIdentityCredentials(ctx context.Context, client *http.Client, endpoint string, tokenFile string) (ec2RoleCredRespBody, error) {
if tokenFile != "" {
bytes, err := os.ReadFile(tokenFile)
if err != nil {
return ec2RoleCredRespBody{}, fmt.Errorf("getEKSPodIdentityCredentials: failed to read token file:%s", err)
}
token := string(bytes)
return getEcsTaskCredentials(client, endpoint, token)
return getEcsTaskCredentials(ctx, client, endpoint, token)
}
return ec2RoleCredRespBody{}, fmt.Errorf("getEKSPodIdentityCredentials: no tokenFile found")
}
func fetchIMDSToken(client *http.Client, endpoint string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
func fetchIMDSToken(ctx context.Context, client *http.Client, endpoint string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPut, endpoint+TokenPath, nil)
@@ -371,14 +396,18 @@ func fetchIMDSToken(client *http.Client, endpoint string) (string, error) {
//
// If the credentials cannot be found, or there is an error
// reading the response an error will be returned.
func getCredentials(client *http.Client, endpoint string) (ec2RoleCredRespBody, error) {
func getCredentials(ctx context.Context, client *http.Client, endpoint string) (ec2RoleCredRespBody, error) {
if endpoint == "" {
endpoint = DefaultIAMRoleEndpoint
}
// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html
token, err := fetchIMDSToken(client, endpoint)
token, err := fetchIMDSToken(ctx, client, endpoint)
if err != nil {
// A dead caller context is not an IMDSv2 availability signal.
if cerr := ctx.Err(); cerr != nil {
return ec2RoleCredRespBody{}, fmt.Errorf("%w (imds token fetch: %v)", cerr, err)
}
// Return only errors for valid situations, if the IMDSv2 is not enabled
// we will not be able to get the token, in such a situation we have
// to rely on IMDSv1 behavior as a fallback, this check ensures that.
@@ -395,7 +424,7 @@ func getCredentials(client *http.Client, endpoint string) (ec2RoleCredRespBody,
}
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
roleNames, err := listRoleNames(client, u, token)
roleNames, err := listRoleNames(ctx, client, u, token)
if err != nil {
return ec2RoleCredRespBody{}, err
}
@@ -415,7 +444,7 @@ func getCredentials(client *http.Client, endpoint string) (ec2RoleCredRespBody,
// $ curl http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
//
u.Path = path.Join(u.Path, roleName)
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return ec2RoleCredRespBody{}, err
}
+4 -3
View File
@@ -19,6 +19,7 @@ package credentials
import (
"bytes"
"context"
"encoding/xml"
"errors"
"fmt"
@@ -100,7 +101,7 @@ func NewSTSClientGrants(stsEndpoint string, getClientGrantsTokenExpiry func() (*
}), nil
}
func getClientGrantsCredentials(clnt *http.Client, endpoint string,
func getClientGrantsCredentials(ctx context.Context, clnt *http.Client, endpoint string,
getClientGrantsTokenExpiry func() (*ClientGrantsToken, error),
) (AssumeRoleWithClientGrantsResponse, error) {
accessToken, err := getClientGrantsTokenExpiry()
@@ -119,7 +120,7 @@ func getClientGrantsCredentials(clnt *http.Client, endpoint string,
return AssumeRoleWithClientGrantsResponse{}, err
}
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(v.Encode()))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), strings.NewReader(v.Encode()))
if err != nil {
return AssumeRoleWithClientGrantsResponse{}, err
}
@@ -179,7 +180,7 @@ func (m *STSClientGrants) RetrieveWithCredContext(cc *CredContext) (Value, error
return Value{}, errors.New("STS endpoint unknown")
}
a, err := getClientGrantsCredentials(client, stsEndpoint, m.GetClientGrantsTokenExpiry)
a, err := getClientGrantsCredentials(cc.requestContext(), client, stsEndpoint, m.GetClientGrantsTokenExpiry)
if err != nil {
return Value{}, err
}
@@ -107,7 +107,7 @@ func (c *CustomTokenIdentity) RetrieveWithCredContext(cc *CredContext) (value Va
u.RawQuery = v.Encode()
req, err := http.NewRequest(http.MethodPost, u.String(), nil)
req, err := http.NewRequestWithContext(cc.requestContext(), http.MethodPost, u.String(), nil)
if err != nil {
return value, err
}
+1 -1
View File
@@ -172,7 +172,7 @@ func (k *LDAPIdentity) RetrieveWithCredContext(cc *CredContext) (value Value, er
v.Set("ConfigName", k.ConfigName)
}
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(v.Encode()))
req, err := http.NewRequestWithContext(cc.requestContext(), http.MethodPost, u.String(), strings.NewReader(v.Encode()))
if err != nil {
return value, err
}
+1 -1
View File
@@ -131,7 +131,7 @@ func (i *STSCertificateIdentity) RetrieveWithCredContext(cc *CredContext) (Value
}
endpointURL.RawQuery = queryValues.Encode()
req, err := http.NewRequest(http.MethodPost, endpointURL.String(), nil)
req, err := http.NewRequestWithContext(cc.requestContext(), http.MethodPost, endpointURL.String(), nil)
if err != nil {
return Value{}, err
}
+4 -3
View File
@@ -19,6 +19,7 @@ package credentials
import (
"bytes"
"context"
"encoding/xml"
"errors"
"fmt"
@@ -137,7 +138,7 @@ func WithPolicy(policy string) func(*STSWebIdentity) {
}
}
func getWebIdentityCredentials(clnt *http.Client, endpoint, roleARN, roleSessionName string, policy string,
func getWebIdentityCredentials(ctx context.Context, clnt *http.Client, endpoint, roleARN, roleSessionName string, policy string,
getWebIDTokenExpiry func() (*WebIdentityToken, error), tokenRevokeType string,
) (AssumeRoleWithWebIdentityResponse, error) {
idToken, err := getWebIDTokenExpiry()
@@ -180,7 +181,7 @@ func getWebIdentityCredentials(clnt *http.Client, endpoint, roleARN, roleSession
return AssumeRoleWithWebIdentityResponse{}, err
}
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(v.Encode()))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), strings.NewReader(v.Encode()))
if err != nil {
return AssumeRoleWithWebIdentityResponse{}, err
}
@@ -242,7 +243,7 @@ func (m *STSWebIdentity) RetrieveWithCredContext(cc *CredContext) (Value, error)
return Value{}, errors.New("STS endpoint unknown")
}
a, err := getWebIdentityCredentials(client, stsEndpoint, m.RoleARN, m.roleSessionName, m.Policy, m.GetWebIDTokenExpiry, m.TokenRevokeType)
a, err := getWebIdentityCredentials(cc.requestContext(), client, stsEndpoint, m.RoleARN, m.roleSessionName, m.Policy, m.GetWebIDTokenExpiry, m.TokenRevokeType)
if err != nil {
return Value{}, err
}
+95 -5
View File
@@ -209,6 +209,58 @@ func (t Transition) MarshalXML(en *xml.Encoder, startElement xml.StartElement) e
return en.EncodeElement(transitionWrapper(t), startElement)
}
// Compression is a MinIO AIStor extension with no S3 equivalent: it compresses
// matching current object versions in place. Presence of the element enables the
// action, so Rule carries it as a pointer — unlike Transition, there is no
// StorageClass to key presence off and Days: 0 legitimately means "immediately".
//
// HighCompression selects the strongest level the server offers; without it the
// rule writes the level ingest uses and only compresses objects stored
// uncompressed.
//
// Unlike Transition and Expiration there is no absolute Date trigger — a one-off
// sweep is what the compress batch job is for. That also means no custom
// MarshalJSON: with no embedded time.Time to suppress, every field honors
// omitempty, and a zero element still marshals as {} because Rule holds it as a
// pointer and its presence alone enables the action.
type Compression struct {
XMLName xml.Name `xml:"Compression" json:"-"`
Days ExpirationDays `xml:"Days,omitempty" json:"Days,omitempty"`
HighCompression bool `xml:"HighCompression,omitempty" json:"HighCompression,omitempty"`
SkipCompressed bool `xml:"SkipCompressed,omitempty" json:"SkipCompressed,omitempty"`
IncludeEncrypted bool `xml:"IncludeEncrypted,omitempty" json:"IncludeEncrypted,omitempty"`
}
// IsDaysNull returns true if days field is null
func (c *Compression) IsDaysNull() bool {
return c == nil || c.Days == ExpirationDays(0)
}
// IsNull returns true if the element is absent.
func (c *Compression) IsNull() bool {
return c == nil
}
// NoncurrentVersionCompression is the Compression counterpart for noncurrent
// object versions. See Compression for why Rule holds it as a pointer.
type NoncurrentVersionCompression struct {
XMLName xml.Name `xml:"NoncurrentVersionCompression" json:"-"`
NoncurrentDays ExpirationDays `xml:"NoncurrentDays,omitempty" json:"NoncurrentDays,omitempty"`
HighCompression bool `xml:"HighCompression,omitempty" json:"HighCompression,omitempty"`
SkipCompressed bool `xml:"SkipCompressed,omitempty" json:"SkipCompressed,omitempty"`
IncludeEncrypted bool `xml:"IncludeEncrypted,omitempty" json:"IncludeEncrypted,omitempty"`
}
// IsDaysNull returns true if noncurrent days field is null
func (n *NoncurrentVersionCompression) IsDaysNull() bool {
return n == nil || n.NoncurrentDays == ExpirationDays(0)
}
// IsNull returns true if the element is absent.
func (n *NoncurrentVersionCompression) IsNull() bool {
return n == nil
}
// And And Rule for LifecycleTag, to be used in LifecycleRuleFilter
type And struct {
XMLName xml.Name `xml:"And" json:"-"`
@@ -265,12 +317,11 @@ func (f Filter) MarshalJSON() ([]byte, error) {
}
// MarshalXML - produces the xml representation of the Filter struct
// only one of Prefix, And and Tag should be present in the output.
// at most one of Prefix, And, Tag, ObjectSizeGreaterThan and
// ObjectSizeLessThan is present in the output.
// A zero-value Filter marshals as <Filter><Prefix></Prefix></Filter>;
// suppressing the element entirely is the caller's responsibility.
func (f Filter) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if f.IsNull() {
return nil
}
if err := e.EncodeToken(start); err != nil {
return err
}
@@ -473,6 +524,8 @@ func (r Rule) MarshalJSON() ([]byte, error) {
Prefix string `json:"Prefix,omitempty"`
Status string `json:"Status"`
Transition *Transition `json:"Transition,omitempty"`
Compression *Compression `json:"Compression,omitempty"`
NoncurrentVersionCompression *NoncurrentVersionCompression `json:"NoncurrentVersionCompression,omitempty"`
}
newr := rule{
Prefix: r.Prefix,
@@ -504,10 +557,45 @@ func (r Rule) MarshalJSON() ([]byte, error) {
if !r.AllVersionsExpiration.IsNull() {
newr.AllVersionsExpiration = &r.AllVersionsExpiration
}
newr.Compression = r.Compression
newr.NoncurrentVersionCompression = r.NoncurrentVersionCompression
return json.Marshal(newr)
}
// ruleAlias drops Rule's methods so EncodeElement falls back to the default
// struct-tag encoding.
type ruleAlias Rule
// ruleWrapper embeds ruleAlias, so it needs no updating when Rule gains a
// field. Its RuleFilter is shallower than the embedded one, and encoding/xml's
// depth-based field shadowing suppresses the deeper field, so <Filter> is
// emitted only through this pointer: nil omits the element, a set pointer
// emits it (empty) as the last child of <Rule>.
type ruleWrapper struct {
ruleAlias
RuleFilter *Filter `xml:"Filter,omitempty"`
}
// MarshalXML customizes XML encoding of Rule: a rule with neither Filter nor
// Prefix set emits an empty <Filter><Prefix></Prefix></Filter> as the last
// child of <Rule> — S3 requires a Filter when no Prefix element is present;
// the empty <Prefix> child is this library's representation of an empty
// filter. A rule with only a top-level Prefix omits the Filter element; a
// non-null Filter marshals through the default encoding in its declared
// field position. MarshalJSON is unaffected and still omits a null Filter.
func (r Rule) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if !r.RuleFilter.IsNull() {
return e.EncodeElement(ruleAlias(r), start)
}
w := ruleWrapper{ruleAlias: ruleAlias(r)}
if r.Prefix == "" {
w.RuleFilter = &w.ruleAlias.RuleFilter
}
return e.EncodeElement(w, start)
}
// Rule represents a single rule in lifecycle configuration
type Rule struct {
XMLName xml.Name `xml:"Rule,omitempty" json:"-"`
@@ -522,6 +610,8 @@ type Rule struct {
Prefix string `xml:"Prefix,omitempty" json:"Prefix,omitempty"`
Status string `xml:"Status" json:"Status"`
Transition Transition `xml:"Transition,omitempty" json:"Transition,omitempty"`
Compression *Compression `xml:"Compression,omitempty" json:"Compression,omitempty"`
NoncurrentVersionCompression *NoncurrentVersionCompression `xml:"NoncurrentVersionCompression,omitempty" json:"NoncurrentVersionCompression,omitempty"`
}
// Configuration is a collection of Rule objects.
@@ -0,0 +1,114 @@
/*
* MinIO Go Library for Amazon S3 Compatible Cloud Storage
* Copyright 2015-2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package policy
import (
"github.com/minio/minio-go/v7/pkg/set"
)
// ConditionKeyMap - map of policy condition key and value.
type ConditionKeyMap map[string]set.StringSet
// Add - adds key and value. The value is appended If key already exists.
func (ckm ConditionKeyMap) Add(key string, value set.StringSet) {
if v, ok := ckm[key]; ok {
ckm[key] = v.Union(value)
} else {
ckm[key] = set.CopyStringSet(value)
}
}
// Remove - removes value of given key. If key has empty after removal, the key is also removed.
func (ckm ConditionKeyMap) Remove(key string, value set.StringSet) {
if v, ok := ckm[key]; ok {
if value != nil {
ckm[key] = v.Difference(value)
}
if ckm[key].IsEmpty() {
delete(ckm, key)
}
}
}
// RemoveKey - removes key and its value.
func (ckm ConditionKeyMap) RemoveKey(key string) {
delete(ckm, key)
}
// CopyConditionKeyMap - returns new copy of given ConditionKeyMap.
func CopyConditionKeyMap(condKeyMap ConditionKeyMap) ConditionKeyMap {
out := make(ConditionKeyMap)
for k, v := range condKeyMap {
out[k] = set.CopyStringSet(v)
}
return out
}
// mergeConditionKeyMap - returns a new ConditionKeyMap which contains merged key/value of given two ConditionKeyMap.
func mergeConditionKeyMap(condKeyMap1, condKeyMap2 ConditionKeyMap) ConditionKeyMap {
out := CopyConditionKeyMap(condKeyMap1)
for k, v := range condKeyMap2 {
if ev, ok := out[k]; ok {
out[k] = ev.Union(v)
} else {
out[k] = set.CopyStringSet(v)
}
}
return out
}
// ConditionMap - map of condition and conditional values.
type ConditionMap map[string]ConditionKeyMap
// Add - adds condition key and condition value. The value is appended if key already exists.
func (cond ConditionMap) Add(condKey string, condKeyMap ConditionKeyMap) {
if v, ok := cond[condKey]; ok {
cond[condKey] = mergeConditionKeyMap(v, condKeyMap)
} else {
cond[condKey] = CopyConditionKeyMap(condKeyMap)
}
}
// Remove - removes condition key and its value.
func (cond ConditionMap) Remove(condKey string) {
delete(cond, condKey)
}
// mergeConditionMap - returns new ConditionMap which contains merged key/value of two ConditionMap.
func mergeConditionMap(condMap1, condMap2 ConditionMap) ConditionMap {
out := make(ConditionMap)
for k, v := range condMap1 {
out[k] = CopyConditionKeyMap(v)
}
for k, v := range condMap2 {
if ev, ok := out[k]; ok {
out[k] = mergeConditionKeyMap(ev, v)
} else {
out[k] = CopyConditionKeyMap(v)
}
}
return out
}
+680
View File
@@ -0,0 +1,680 @@
/*
* MinIO Go Library for Amazon S3 Compatible Cloud Storage
* Copyright 2015-2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package policy
import (
"encoding/json"
"errors"
"reflect"
"strings"
"github.com/minio/minio-go/v7/pkg/set"
)
// BucketPolicy - Bucket level policy.
type BucketPolicy string
// Different types of Policies currently supported for buckets.
const (
BucketPolicyNone BucketPolicy = "none"
BucketPolicyReadOnly BucketPolicy = "readonly"
BucketPolicyReadWrite BucketPolicy = "readwrite"
BucketPolicyWriteOnly BucketPolicy = "writeonly"
)
// IsValidBucketPolicy - returns true if policy is valid and supported, false otherwise.
func (p BucketPolicy) IsValidBucketPolicy() bool {
switch p {
case BucketPolicyNone, BucketPolicyReadOnly, BucketPolicyReadWrite, BucketPolicyWriteOnly:
return true
}
return false
}
// Resource prefix for all aws resources.
const awsResourcePrefix = "arn:aws:s3:::"
// Common bucket actions for both read and write policies.
var commonBucketActions = set.CreateStringSet("s3:GetBucketLocation")
// Read only bucket actions.
var readOnlyBucketActions = set.CreateStringSet("s3:ListBucket")
// Write only bucket actions.
var writeOnlyBucketActions = set.CreateStringSet("s3:ListBucketMultipartUploads")
// Read only object actions.
var readOnlyObjectActions = set.CreateStringSet("s3:GetObject")
// Write only object actions.
var writeOnlyObjectActions = set.CreateStringSet("s3:AbortMultipartUpload", "s3:DeleteObject", "s3:ListMultipartUploadParts", "s3:PutObject")
// Read and write object actions.
var readWriteObjectActions = readOnlyObjectActions.Union(writeOnlyObjectActions)
// All valid bucket and object actions.
var validActions = commonBucketActions.
Union(readOnlyBucketActions).
Union(writeOnlyBucketActions).
Union(readOnlyObjectActions).
Union(writeOnlyObjectActions)
var startsWithFunc = func(resource, resourcePrefix string) bool {
return strings.HasPrefix(resource, resourcePrefix)
}
// User - canonical users list.
type User struct {
AWS set.StringSet `json:"AWS,omitempty"`
CanonicalUser set.StringSet `json:"CanonicalUser,omitempty"`
}
// UnmarshalJSON is a custom json unmarshaler for Principal field,
// the reason is that Principal can take a json struct represented by
// User string but it can also take a string.
func (u *User) UnmarshalJSON(data []byte) error {
// Try to unmarshal data in a struct equal to User,
// to avoid infinite recursive call of this function
type AliasUser User
var au AliasUser
err := json.Unmarshal(data, &au)
if err == nil {
*u = User(au)
return nil
}
// Data type is not known, check if it is a json string
// which contains a star, which is permitted in the spec
var str string
err = json.Unmarshal(data, &str)
if err == nil {
if str != "*" {
return errors.New("unrecognized Principal field")
}
*u = User{AWS: set.CreateStringSet("*")}
return nil
}
return err
}
// Statement - minio policy statement
type Statement struct {
Actions set.StringSet `json:"Action"`
Conditions ConditionMap `json:"Condition,omitempty"`
Effect string
Principal User `json:"Principal"`
Resources set.StringSet `json:"Resource"`
Sid string
}
// BucketAccessPolicy - minio policy collection
type BucketAccessPolicy struct {
Version string // date in YYYY-MM-DD format
Statements []Statement `json:"Statement"`
}
// isValidStatement - returns whether given statement is valid to process for given bucket name.
func isValidStatement(statement Statement, bucketName string) bool {
if statement.Actions.Intersection(validActions).IsEmpty() {
return false
}
if statement.Effect != "Allow" {
return false
}
if statement.Principal.AWS == nil || !statement.Principal.AWS.Contains("*") {
return false
}
bucketResource := awsResourcePrefix + bucketName
if statement.Resources.Contains(bucketResource) {
return true
}
if statement.Resources.FuncMatch(startsWithFunc, bucketResource+"/").IsEmpty() {
return false
}
return true
}
// Returns new statements with bucket actions for given policy.
func newBucketStatement(policy BucketPolicy, bucketName, prefix string) (statements []Statement) {
statements = []Statement{}
if policy == BucketPolicyNone || bucketName == "" {
return statements
}
bucketResource := set.CreateStringSet(awsResourcePrefix + bucketName)
statement := Statement{
Actions: commonBucketActions,
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: bucketResource,
Sid: "",
}
statements = append(statements, statement)
if policy == BucketPolicyReadOnly || policy == BucketPolicyReadWrite {
statement = Statement{
Actions: readOnlyBucketActions,
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: bucketResource,
Sid: "",
}
if prefix != "" {
condKeyMap := make(ConditionKeyMap)
condKeyMap.Add("s3:prefix", set.CreateStringSet(prefix+"*"))
condMap := make(ConditionMap)
condMap.Add("StringLike", condKeyMap)
statement.Conditions = condMap
}
statements = append(statements, statement)
}
if policy == BucketPolicyWriteOnly || policy == BucketPolicyReadWrite {
statement = Statement{
Actions: writeOnlyBucketActions,
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: bucketResource,
Sid: "",
}
statements = append(statements, statement)
}
return statements
}
// Returns new statements contains object actions for given policy.
func newObjectStatement(policy BucketPolicy, bucketName, prefix string) (statements []Statement) {
statements = []Statement{}
if policy == BucketPolicyNone || bucketName == "" {
return statements
}
statement := Statement{
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: set.CreateStringSet(awsResourcePrefix + bucketName + "/" + prefix + "*"),
Sid: "",
}
switch policy {
case BucketPolicyReadOnly:
statement.Actions = readOnlyObjectActions
case BucketPolicyWriteOnly:
statement.Actions = writeOnlyObjectActions
case BucketPolicyReadWrite:
statement.Actions = readWriteObjectActions
}
statements = append(statements, statement)
return statements
}
// Returns new statements for given policy, bucket and prefix.
func newStatements(policy BucketPolicy, bucketName, prefix string) (statements []Statement) {
statements = []Statement{}
ns := newBucketStatement(policy, bucketName, prefix)
statements = append(statements, ns...)
ns = newObjectStatement(policy, bucketName, prefix)
statements = append(statements, ns...)
return statements
}
// Returns whether given bucket statements are used by other than given prefix statements.
func getInUsePolicy(statements []Statement, bucketName, prefix string) (readOnlyInUse, writeOnlyInUse bool) {
resourcePrefix := awsResourcePrefix + bucketName + "/"
objectResource := awsResourcePrefix + bucketName + "/" + prefix + "*"
for _, s := range statements {
if !s.Resources.Contains(objectResource) && !s.Resources.FuncMatch(startsWithFunc, resourcePrefix).IsEmpty() {
if s.Actions.Intersection(readOnlyObjectActions).Equals(readOnlyObjectActions) {
readOnlyInUse = true
}
if s.Actions.Intersection(writeOnlyObjectActions).Equals(writeOnlyObjectActions) {
writeOnlyInUse = true
}
}
if readOnlyInUse && writeOnlyInUse {
break
}
}
return readOnlyInUse, writeOnlyInUse
}
// Removes object actions in given statement.
func removeObjectActions(statement Statement, objectResource string) Statement {
if statement.Conditions == nil {
if len(statement.Resources) > 1 {
statement.Resources.Remove(objectResource)
} else {
statement.Actions = statement.Actions.Difference(readOnlyObjectActions)
statement.Actions = statement.Actions.Difference(writeOnlyObjectActions)
}
}
return statement
}
// Removes bucket actions for given policy in given statement.
func removeBucketActions(statement Statement, prefix, bucketResource string, readOnlyInUse, writeOnlyInUse bool) Statement {
removeReadOnly := func() {
if !statement.Actions.Intersection(readOnlyBucketActions).Equals(readOnlyBucketActions) {
return
}
if statement.Conditions == nil {
statement.Actions = statement.Actions.Difference(readOnlyBucketActions)
return
}
if prefix != "" {
stringEqualsValue := statement.Conditions["StringEquals"]
values := set.NewStringSet()
if stringEqualsValue != nil {
values = stringEqualsValue["s3:prefix"]
if values == nil {
values = set.NewStringSet()
}
}
values.Remove(prefix)
if stringEqualsValue != nil {
if values.IsEmpty() {
delete(stringEqualsValue, "s3:prefix")
}
if len(stringEqualsValue) == 0 {
delete(statement.Conditions, "StringEquals")
}
}
if len(statement.Conditions) == 0 {
statement.Conditions = nil
statement.Actions = statement.Actions.Difference(readOnlyBucketActions)
}
}
}
removeWriteOnly := func() {
if statement.Conditions == nil {
statement.Actions = statement.Actions.Difference(writeOnlyBucketActions)
}
}
if len(statement.Resources) > 1 {
statement.Resources.Remove(bucketResource)
} else {
if !readOnlyInUse {
removeReadOnly()
}
if !writeOnlyInUse {
removeWriteOnly()
}
}
return statement
}
// Returns statements containing removed actions/statements for given
// policy, bucket name and prefix.
func removeStatements(statements []Statement, bucketName, prefix string) []Statement {
bucketResource := awsResourcePrefix + bucketName
objectResource := awsResourcePrefix + bucketName + "/" + prefix + "*"
readOnlyInUse, writeOnlyInUse := getInUsePolicy(statements, bucketName, prefix)
out := []Statement{}
readOnlyBucketStatements := []Statement{}
s3PrefixValues := set.NewStringSet()
for _, statement := range statements {
if !isValidStatement(statement, bucketName) {
out = append(out, statement)
continue
}
if statement.Resources.Contains(bucketResource) {
if statement.Conditions != nil {
statement = removeBucketActions(statement, prefix, bucketResource, false, false)
} else {
statement = removeBucketActions(statement, prefix, bucketResource, readOnlyInUse, writeOnlyInUse)
}
} else if statement.Resources.Contains(objectResource) {
statement = removeObjectActions(statement, objectResource)
}
if !statement.Actions.IsEmpty() {
if statement.Resources.Contains(bucketResource) &&
statement.Actions.Intersection(readOnlyBucketActions).Equals(readOnlyBucketActions) &&
statement.Effect == "Allow" &&
statement.Principal.AWS.Contains("*") {
if statement.Conditions != nil {
stringEqualsValue := statement.Conditions["StringEquals"]
values := set.NewStringSet()
if stringEqualsValue != nil {
values = stringEqualsValue["s3:prefix"]
if values == nil {
values = set.NewStringSet()
}
}
s3PrefixValues = s3PrefixValues.Union(values.ApplyFunc(func(v string) string {
return bucketResource + "/" + v + "*"
}))
} else if !s3PrefixValues.IsEmpty() {
readOnlyBucketStatements = append(readOnlyBucketStatements, statement)
continue
}
}
out = append(out, statement)
}
}
skipBucketStatement := true
resourcePrefix := awsResourcePrefix + bucketName + "/"
for _, statement := range out {
if !statement.Resources.FuncMatch(startsWithFunc, resourcePrefix).IsEmpty() &&
s3PrefixValues.Intersection(statement.Resources).IsEmpty() {
skipBucketStatement = false
break
}
}
for _, statement := range readOnlyBucketStatements {
if skipBucketStatement &&
statement.Resources.Contains(bucketResource) &&
statement.Effect == "Allow" &&
statement.Principal.AWS.Contains("*") &&
statement.Conditions == nil {
continue
}
out = append(out, statement)
}
if len(out) == 1 {
statement := out[0]
if statement.Resources.Contains(bucketResource) &&
statement.Actions.Intersection(commonBucketActions).Equals(commonBucketActions) &&
statement.Effect == "Allow" &&
statement.Principal.AWS.Contains("*") &&
statement.Conditions == nil {
out = []Statement{}
}
}
return out
}
// Appends given statement into statement list to have unique statements.
// - If statement already exists in statement list, it ignores.
// - If statement exists with different conditions, they are merged.
// - Else the statement is appended to statement list.
func appendStatement(statements []Statement, statement Statement) []Statement {
for i, s := range statements {
if s.Actions.Equals(statement.Actions) &&
s.Effect == statement.Effect &&
s.Principal.AWS.Equals(statement.Principal.AWS) &&
reflect.DeepEqual(s.Conditions, statement.Conditions) {
statements[i].Resources = s.Resources.Union(statement.Resources)
return statements
} else if s.Resources.Equals(statement.Resources) &&
s.Effect == statement.Effect &&
s.Principal.AWS.Equals(statement.Principal.AWS) &&
reflect.DeepEqual(s.Conditions, statement.Conditions) {
statements[i].Actions = s.Actions.Union(statement.Actions)
return statements
}
if s.Resources.Intersection(statement.Resources).Equals(statement.Resources) &&
s.Actions.Intersection(statement.Actions).Equals(statement.Actions) &&
s.Effect == statement.Effect &&
s.Principal.AWS.Intersection(statement.Principal.AWS).Equals(statement.Principal.AWS) {
if reflect.DeepEqual(s.Conditions, statement.Conditions) {
return statements
}
if s.Conditions != nil && statement.Conditions != nil {
if s.Resources.Equals(statement.Resources) {
statements[i].Conditions = mergeConditionMap(s.Conditions, statement.Conditions)
return statements
}
}
}
}
if !statement.Actions.IsEmpty() || !statement.Resources.IsEmpty() {
return append(statements, statement)
}
return statements
}
// Appends two statement lists.
func appendStatements(statements, appendStatements []Statement) []Statement {
for _, s := range appendStatements {
statements = appendStatement(statements, s)
}
return statements
}
// Returns policy of given bucket statement.
func getBucketPolicy(statement Statement, prefix string) (commonFound, readOnly, writeOnly bool) {
if statement.Effect != "Allow" || !statement.Principal.AWS.Contains("*") {
return commonFound, readOnly, writeOnly
}
if statement.Actions.Intersection(commonBucketActions).Equals(commonBucketActions) &&
statement.Conditions == nil {
commonFound = true
}
if statement.Actions.Intersection(writeOnlyBucketActions).Equals(writeOnlyBucketActions) &&
statement.Conditions == nil {
writeOnly = true
}
if statement.Actions.Intersection(readOnlyBucketActions).Equals(readOnlyBucketActions) {
if prefix != "" && statement.Conditions != nil {
if stringEqualsValue, ok := statement.Conditions["StringEquals"]; ok {
if s3PrefixValues, ok := stringEqualsValue["s3:prefix"]; ok {
if s3PrefixValues.Contains(prefix) {
readOnly = true
}
}
} else if stringNotEqualsValue, ok := statement.Conditions["StringNotEquals"]; ok {
if s3PrefixValues, ok := stringNotEqualsValue["s3:prefix"]; ok {
if !s3PrefixValues.Contains(prefix) {
readOnly = true
}
}
} else if stringLikeValue, ok := statement.Conditions["StringLike"]; ok {
if s3PrefixValues, ok := stringLikeValue["s3:prefix"]; ok {
if s3PrefixValues.Contains(prefix + "*") {
readOnly = true
}
}
} else if stringNotLikeValue, ok := statement.Conditions["StringNotLike"]; ok {
if s3PrefixValues, ok := stringNotLikeValue["s3:prefix"]; ok {
if !s3PrefixValues.Contains(prefix + "*") {
readOnly = true
}
}
}
} else if prefix == "" && statement.Conditions == nil {
readOnly = true
} else if prefix != "" && statement.Conditions == nil {
readOnly = true
}
}
return commonFound, readOnly, writeOnly
}
// Returns policy of given object statement.
func getObjectPolicy(statement Statement) (readOnly, writeOnly bool) {
if statement.Effect == "Allow" &&
statement.Principal.AWS.Contains("*") &&
statement.Conditions == nil {
if statement.Actions.Intersection(readOnlyObjectActions).Equals(readOnlyObjectActions) {
readOnly = true
}
if statement.Actions.Intersection(writeOnlyObjectActions).Equals(writeOnlyObjectActions) {
writeOnly = true
}
}
return readOnly, writeOnly
}
// GetPolicy - Returns policy of given bucket name, prefix in given statements.
func GetPolicy(statements []Statement, bucketName, prefix string) BucketPolicy {
bucketResource := awsResourcePrefix + bucketName
objectResource := awsResourcePrefix + bucketName + "/" + prefix + "*"
bucketCommonFound := false
bucketReadOnly := false
bucketWriteOnly := false
matchedResource := ""
objReadOnly := false
objWriteOnly := false
for _, s := range statements {
matchedObjResources := set.NewStringSet()
if s.Resources.Contains(objectResource) {
matchedObjResources.Add(objectResource)
} else {
matchedObjResources = s.Resources.FuncMatch(resourceMatch, objectResource)
}
if !matchedObjResources.IsEmpty() {
readOnly, writeOnly := getObjectPolicy(s)
for resource := range matchedObjResources {
if len(matchedResource) < len(resource) {
objReadOnly = readOnly
objWriteOnly = writeOnly
matchedResource = resource
} else if len(matchedResource) == len(resource) {
objReadOnly = objReadOnly || readOnly
objWriteOnly = objWriteOnly || writeOnly
matchedResource = resource
}
}
}
if s.Resources.Contains(bucketResource) {
commonFound, readOnly, writeOnly := getBucketPolicy(s, prefix)
bucketCommonFound = bucketCommonFound || commonFound
bucketReadOnly = bucketReadOnly || readOnly
bucketWriteOnly = bucketWriteOnly || writeOnly
}
}
policy := BucketPolicyNone
if bucketCommonFound {
if bucketReadOnly && bucketWriteOnly && objReadOnly && objWriteOnly {
policy = BucketPolicyReadWrite
} else if bucketReadOnly && objReadOnly {
policy = BucketPolicyReadOnly
} else if bucketWriteOnly && objWriteOnly {
policy = BucketPolicyWriteOnly
}
}
return policy
}
// GetPolicies - returns a map of policies of given bucket name, prefix in given statements.
func GetPolicies(statements []Statement, bucketName, prefix string) map[string]BucketPolicy {
policyRules := map[string]BucketPolicy{}
objResources := set.NewStringSet()
// Search all resources related to objects policy
for _, s := range statements {
for r := range s.Resources {
if strings.HasPrefix(r, awsResourcePrefix+bucketName+"/"+prefix) {
objResources.Add(r)
}
}
}
// Pretend that policy resource as an actual object and fetch its policy
for r := range objResources {
// Put trailing * if exists in asterisk
asterisk := ""
if strings.HasSuffix(r, "*") {
r = r[:len(r)-1]
asterisk = "*"
}
var objectPath string
if len(r) >= len(awsResourcePrefix+bucketName)+1 {
objectPath = r[len(awsResourcePrefix+bucketName)+1:]
}
p := GetPolicy(statements, bucketName, objectPath)
policyRules[bucketName+"/"+objectPath+asterisk] = p
}
return policyRules
}
// SetPolicy - Returns new statements containing policy of given bucket name and prefix are appended.
func SetPolicy(statements []Statement, policy BucketPolicy, bucketName, prefix string) []Statement {
out := removeStatements(statements, bucketName, prefix)
// fmt.Println("out = ")
// printstatement(out)
ns := newStatements(policy, bucketName, prefix)
// fmt.Println("ns = ")
// printstatement(ns)
rv := appendStatements(out, ns)
// fmt.Println("rv = ")
// printstatement(rv)
return rv
}
// Match function matches wild cards in 'pattern' for resource.
func resourceMatch(pattern, resource string) bool {
if pattern == "" {
return resource == pattern
}
if pattern == "*" {
return true
}
parts := strings.Split(pattern, "*")
if len(parts) == 1 {
return resource == pattern
}
tGlob := strings.HasSuffix(pattern, "*")
end := len(parts) - 1
if !strings.HasPrefix(resource, parts[0]) {
return false
}
for i := 1; i < end; i++ {
if !strings.Contains(resource, parts[i]) {
return false
}
idx := strings.Index(resource, parts[i]) + len(parts[i])
resource = resource[idx:]
}
return tGlob || strings.HasSuffix(resource, parts[end])
}
@@ -61,10 +61,10 @@ func getUSStreamLength(dataLen, chunkSize int64, trailers http.Header) int64 {
return streamLen
}
// prepareStreamingRequest - prepares a request with appropriate
// headers before computing the seed signature.
// prepareUSStreamingRequest - prepares a request with the headers
// required for an unsigned aws-chunked streaming upload.
func prepareUSStreamingRequest(req *http.Request, sessionToken string, dataLen int64, timestamp time.Time) {
req.TransferEncoding = []string{"aws-chunked"}
setAwsChunkedContentEncoding(req)
if sessionToken != "" {
req.Header.Set("X-Amz-Security-Token", sessionToken)
}
@@ -132,8 +132,8 @@ func prepareStreamingRequest(req *http.Request, sessionToken string, dataLen int
for k := range req.Trailer {
req.Header.Add("X-Amz-Trailer", strings.ToLower(k))
}
req.TransferEncoding = []string{"aws-chunked"}
}
setAwsChunkedContentEncoding(req)
if sessionToken != "" {
req.Header.Set("X-Amz-Security-Token", sessionToken)
+2 -2
View File
@@ -331,7 +331,7 @@ func signV4(req http.Request, accessKeyID, secretAccessKey, sessionToken, locati
req.Header.Add("X-Amz-Trailer", strings.ToLower(k))
}
req.Header.Set("Content-Encoding", "aws-chunked")
setAwsChunkedContentEncoding(&req)
req.Header.Set("x-amz-decoded-content-length", strconv.FormatInt(req.ContentLength, 10))
}
@@ -395,7 +395,7 @@ func UnsignedTrailer(req http.Request, trailer http.Header) *http.Request {
req.Header.Add("X-Amz-Trailer", strings.ToLower(k))
}
req.Header.Set("Content-Encoding", "aws-chunked")
setAwsChunkedContentEncoding(&req)
req.Header.Set("x-amz-decoded-content-length", strconv.FormatInt(req.ContentLength, 10))
// Use custom chunked encoding.
+25
View File
@@ -22,6 +22,8 @@ import (
"crypto/sha256"
"net/http"
"strings"
"golang.org/x/net/http/httpguts"
)
// unsignedPayload - value to be set to X-Amz-Content-Sha256 header when
@@ -60,3 +62,26 @@ func signV4TrimAll(input string) string {
// unicode.IsSpace() internally here) to one space and return
return strings.Join(strings.Fields(input), " ")
}
// awsChunkedEncoding is the content coding AWS SigV4 streaming uploads
// declare on the Content-Encoding header.
const awsChunkedEncoding = "aws-chunked"
// setAwsChunkedContentEncoding marks the request payload as aws-chunked
// encoded, keeping any content encoding the caller already set, for example
// "aws-chunked,gzip". AWS SigV4 streaming uploads require this header.
// Assigning "aws-chunked" to http.Request.TransferEncoding never reaches
// the wire — net/http silently drops assigned values other than "chunked" —
// so this header is the only signal that declares the aws-chunked framing.
func setAwsChunkedContentEncoding(req *http.Request) {
encodings := req.Header.Values("Content-Encoding")
if httpguts.HeaderValuesContainsToken(encodings, awsChunkedEncoding) {
return
}
existing := strings.TrimSpace(strings.Join(encodings, ","))
if existing == "" {
req.Header.Set("Content-Encoding", awsChunkedEncoding)
return
}
req.Header.Set("Content-Encoding", awsChunkedEncoding+","+existing)
}
+5 -3
View File
@@ -172,10 +172,12 @@ func (g *Group[K, V]) doCall(c *call[V], key K, fn func() (V, error)) {
} else {
panic(e)
}
} else if c.err == errGoexit {
// Already in the process of goexit, no need to call again
} else {
// Normal return
// Normal return, and runtime.Goexit, which reaches here with
// c.err set to errGoexit. This goroutine is already being torn
// down and must not call runtime.Goexit again: Do callers
// re-Goexit themselves once they see c.err, but DoChan callers
// hold a channel and have nothing else to wake them.
for _, ch := range c.chans {
ch <- Result[V]{c.val, c.err, c.dups > 0}
}
+34 -1
View File
@@ -26,6 +26,25 @@ import (
var ErrRDMANotConnected = errors.New("RDMA infrastructure not connected")
// maxRDMABufferSize is the largest transfer a single RDMA descriptor can
// describe: the x-amz-rdma-token carries the window size in a 32-bit field.
// libminiocpp itself does not fail on a larger buffer: it skips RDMA and
// transfers it over one ordinary HTTP request. The guards below reject it
// instead, so an oversize buffer does not silently become a much slower HTTP
// transfer on a path the caller explicitly opted into for RDMA. Keep this in
// step with kRDMAMaxMemoryRegSize in minio-cpp -- a value even one byte larger
// lets a buffer through here that libminiocpp then declines. The lower bound
// also stops a negative size from wrapping to a huge C.size_t.
const maxRDMABufferSize int64 = 1<<32 - 1 // 4 GiB - 1
// rdmaBufferSizeInRange reports whether a descriptor can name this many bytes.
// Both entry points gate on it before converting to C.size_t, so it is the one
// place the bound is expressed -- and the only part of the guard that can be
// exercised without an RDMA device.
func rdmaBufferSizeInRange(size int) bool {
return size >= 0 && int64(size) <= maxRDMABufferSize
}
type rdmaClientHandle struct {
cptr *C.miniocpp_client
}
@@ -63,6 +82,12 @@ func newRDMAClient(c *Client) (*rdmaClientHandle, error) {
func (c *Client) putObjectRDMA(_ context.Context, bucketName, objectName string,
opts PutObjectOptions,
) (UploadInfo, error) {
if !rdmaBufferSizeInRange(opts.RDMABufferSize) {
return UploadInfo{}, fmt.Errorf(
"RDMA put: buffer size %d must be between 0 and the %d bytes an RDMA descriptor can describe",
opts.RDMABufferSize, maxRDMABufferSize)
}
h, err := c.rdma()
if err != nil {
return UploadInfo{}, err
@@ -93,6 +118,12 @@ func (c *Client) putObjectRDMA(_ context.Context, bucketName, objectName string,
func (c *Client) getObjectRDMA(_ context.Context, bucketName, objectName string,
opts GetObjectOptions,
) (int64, error) {
if !rdmaBufferSizeInRange(opts.RDMABufferSize) {
return 0, fmt.Errorf(
"RDMA get: buffer size %d must be between 0 and the %d bytes an RDMA descriptor can describe",
opts.RDMABufferSize, maxRDMABufferSize)
}
h, err := c.rdma()
if err != nil {
return 0, err
@@ -136,5 +167,7 @@ func AlignedBuffer(n int) unsafe.Pointer {
// FreeAlignedBuffer releases a buffer from AlignedBuffer.
func FreeAlignedBuffer(p unsafe.Pointer) { C.miniocpp_free_aligned(p) }
// IsRDMAAvailable reports whether cuObj is connected to a cuObjServer.
// IsRDMAAvailable reports whether this host has a usable RDMA device, so an
// RDMA transfer is worth attempting. Whether the server serves RDMA for a
// given object is answered per request, by x-amz-rdma-reply.
func IsRDMAAvailable() bool { return C.miniocpp_rdma_available() != 0 }
+1
View File
@@ -62,6 +62,7 @@ const (
InvalidDuration = "InvalidDuration"
XAmzContentSHA256Mismatch = "XAmzContentSHA256Mismatch"
XMinioInvalidObjectName = "XMinioInvalidObjectName"
XMinioPaidTierLicenseRequired = "XMinioPaidTierLicenseRequired"
NoSuchCORSConfiguration = "NoSuchCORSConfiguration"
BucketAlreadyExists = "BucketAlreadyExists"
NoSuchVersion = "NoSuchVersion"
+57 -7
View File
@@ -33,6 +33,7 @@ import (
"mime"
"net"
"net/http"
"net/textproto"
"net/url"
"regexp"
"strconv"
@@ -63,7 +64,7 @@ func amzExpirationToExpiryDateRuleID(expiration string) (time.Time, string) {
return time.Time{}, ""
}
var restoreRegex = regexp.MustCompile(`ongoing-request="(.*?)"(, expiry-date="(.*?)")?`)
var restoreRegex = regexp.MustCompile(`ongoing-request="(.*?)"(, ?expiry-date="(.*?)")?`)
func amzRestoreToStruct(restore string) (ongoing bool, expTime time.Time, err error) {
matches := restoreRegex.FindStringSubmatch(restore)
@@ -105,8 +106,32 @@ func sumMD5Base64(data []byte) string {
return base64.StdEncoding.EncodeToString(hash.Sum(nil))
}
// getEndpointURL - construct a new endpoint.
// getEndpointURL - construct a new endpoint from a host[:port] endpoint
// or an http(s):// URL whose scheme agrees with the secure option.
func getEndpointURL(endpoint string, secure bool) (*url.URL, error) {
// An endpoint that already carries a scheme is parsed directly instead
// of prefixing another scheme. It must agree with the secure option
// since signing and transport behavior are derived from that option.
// A "://" preceded by a path, query, or fragment delimiter is endpoint
// data rather than a scheme, so such endpoints keep the scheme-less path.
if i := strings.Index(endpoint, "://"); i == 0 || (i > 0 && !strings.ContainsAny(endpoint[:i], "/?#")) {
scheme := strings.ToLower(endpoint[:i])
if scheme != "http" && scheme != "https" {
return nil, errInvalidArgument("Endpoint url scheme \"" + scheme + "\" is unsupported; use http or https or omit the scheme.")
}
endpointURL, err := url.Parse(endpoint)
if err != nil {
return nil, err
}
if secure != (endpointURL.Scheme == "https") {
return nil, errInvalidArgument("Endpoint url scheme \"" + endpointURL.Scheme + "\" conflicts with the secure option; remove the scheme from the endpoint or align the secure option.")
}
if err := isValidEndpointURL(*endpointURL); err != nil {
return nil, err
}
return endpointURL, nil
}
// If secure is false, use 'http' scheme.
scheme := "https"
if !secure {
@@ -199,6 +224,9 @@ func isValidExpiry(expires time.Duration) error {
return nil
}
// amzMetaPrefix is the canonical prefix of S3 user metadata headers.
const amzMetaPrefix = "X-Amz-Meta-"
// Extract only necessary metadata header key/values by
// filtering them out with a list of custom header keys.
func extractObjMetadata(header http.Header) http.Header {
@@ -215,7 +243,7 @@ func extractObjMetadata(header http.Header) http.Header {
"X-Amz-Website-Redirect-Location",
"X-Amz-Server-Side-Encryption",
"X-Amz-Tagging-Count",
"X-Amz-Meta-",
amzMetaPrefix,
"X-Minio-Meta-",
// Add new headers to be preserved.
// if you add new headers here, please extend
@@ -230,7 +258,7 @@ func extractObjMetadata(header http.Header) http.Header {
continue
}
found = true
if prefix == "X-Amz-Meta-" || prefix == "X-Minio-Meta-" {
if prefix == amzMetaPrefix || prefix == "X-Minio-Meta-" {
for index, val := range v {
if strings.HasPrefix(val, "=?") {
decoder := mime.WordDecoder{}
@@ -249,8 +277,29 @@ func extractObjMetadata(header http.Header) http.Header {
return filteredHeader
}
// stripUserMetadata converts the raw <UserMetadata> element of MinIO list
// responses into the keyed form StatObject and GetObject return in
// ObjectInfo.UserMetadata: only "X-Amz-Meta-*" entries are kept, with the
// prefix stripped and values passed through verbatim (list responses carry
// the stored values, so no decoding applies). Returns nil if raw contains
// no user metadata.
func stripUserMetadata(raw StringMap) StringMap {
var stripped StringMap
for k, v := range raw {
k = textproto.CanonicalMIMEHeaderKey(k)
if !strings.HasPrefix(k, amzMetaPrefix) {
continue
}
if stripped == nil {
stripped = make(StringMap, len(raw))
}
stripped[strings.TrimPrefix(k, amzMetaPrefix)] = v
}
return stripped
}
const (
// RFC 7231#section-7.1.1.1 timetamp format. e.g Tue, 29 Apr 2014 18:30:38 GMT
// RFC 7231#section-7.1.1.1 timestamp format. e.g Tue, 29 Apr 2014 18:30:38 GMT
rfc822TimeFormat = "Mon, 2 Jan 2006 15:04:05 GMT"
rfc822TimeFormatSingleDigitDay = "Mon, _2 Jan 2006 15:04:05 GMT"
rfc822TimeFormatSingleDigitDayTwoDigitYear = "Mon, _2 Jan 06 15:04:05 GMT"
@@ -351,8 +400,8 @@ func ToObjectInfo(bucketName, objectName string, h http.Header) (ObjectInfo, err
metadata := extractObjMetadata(h)
userMetadata := make(map[string]string)
for k, v := range metadata {
if strings.HasPrefix(k, "X-Amz-Meta-") {
userMetadata[strings.TrimPrefix(k, "X-Amz-Meta-")] = v[0]
if strings.HasPrefix(k, amzMetaPrefix) {
userMetadata[strings.TrimPrefix(k, amzMetaPrefix)] = v[0]
}
}
@@ -412,6 +461,7 @@ func ToObjectInfo(bucketName, objectName string, h http.Header) (ObjectInfo, err
// following function filters out a list of standard set of keys
// which are not part of object metadata.
Metadata: metadata,
Headers: h,
UserMetadata: userMetadata,
UserTags: userTags.ToMap(),
UserTagCount: tagCount,
+109 -22
View File
@@ -196,6 +196,75 @@ type serviceRespEntry struct {
msub string
}
// rrIndexThreshold is the number of outstanding responses sharing a single
// reply subject above which we build an index for constant time removal.
// Reply subjects are normally unique per request, so the overwhelming majority
// of entries stay a one element list and never allocate the index.
const rrIndexThreshold = 16
// respEntries holds the outstanding response entries for one reply subject.
// The list is authoritative and unordered; idx, when present, maps a response
// subject to its position in the list. Once allocated the index is kept for as
// long as the reply subject has any entry left, since a subject that has been
// shared once tends to be shared again.
//
// This is held by value in importMap.rrMap, so mutating it means writing it
// back under its key. Add and remove entries through importMap.addRespEntry
// and importMap.removeRespEntry, which keep that write back in one place,
// rather than calling the methods below directly.
type respEntries struct {
list []*serviceRespEntry
idx map[string]int
}
// add appends an entry, building or maintaining the index as needed.
func (re *respEntries) add(sre *serviceRespEntry) {
re.list = append(re.list, sre)
if re.idx != nil {
re.idx[sre.msub] = len(re.list) - 1
return
}
if len(re.list) > rrIndexThreshold {
re.idx = make(map[string]int, len(re.list))
for i, e := range re.list {
re.idx[e.msub] = i
}
}
}
// remove drops the entry for msub, in constant time once indexed.
func (re *respEntries) remove(msub string) {
i := -1
if re.idx != nil {
var ok bool
if i, ok = re.idx[msub]; !ok {
return
}
delete(re.idx, msub)
} else {
for j, e := range re.list {
if e.msub == msub {
i = j
break
}
}
if i < 0 {
return
}
}
// Swap with the last entry so removal does not shift the whole list.
last := len(re.list) - 1
if i != last {
moved := re.list[last]
re.list[i] = moved
if re.idx != nil {
re.idx[moved.msub] = i
}
}
re.list[last] = nil
re.list = re.list[:last]
}
// ServiceRespType represents the types of service request response types.
type ServiceRespType uint8
@@ -266,7 +335,34 @@ type exportMap struct {
type importMap struct {
streams []*streamImport
services map[string][]*serviceImport
rrMap map[string][]*serviceRespEntry
rrMap map[string]respEntries
}
// addRespEntry records an outstanding response entry under reply.
// Lock should be held on the owning account.
func (im *importMap) addRespEntry(reply string, sre *serviceRespEntry) {
if im.rrMap == nil {
im.rrMap = make(map[string]respEntries)
}
re := im.rrMap[reply]
re.add(sre)
im.rrMap[reply] = re
}
// removeRespEntry drops the outstanding response entry for msub under reply,
// dropping the reply subject itself once its last entry goes.
// Lock should be held on the owning account.
func (im *importMap) removeRespEntry(reply, msub string) {
re, ok := im.rrMap[reply]
if !ok {
return
}
re.remove(msub)
if len(re.list) == 0 {
delete(im.rrMap, reply)
} else {
im.rrMap[reply] = re
}
}
// NewAccount creates a new unlimited account with the given name.
@@ -1872,12 +1968,7 @@ func (a *Account) removeServiceImport(dstAccName, subject string) {
// This tracks responses to service requests mappings. This is used for cleanup.
func (a *Account) addReverseRespMapEntry(acc *Account, reply, from string) {
a.mu.Lock()
if a.imports.rrMap == nil {
a.imports.rrMap = make(map[string][]*serviceRespEntry)
}
sre := &serviceRespEntry{acc, from}
sra := a.imports.rrMap[reply]
a.imports.rrMap[reply] = append(sra, sre)
a.imports.addRespEntry(reply, &serviceRespEntry{acc, from})
a.mu.Unlock()
}
@@ -1957,7 +2048,7 @@ func (a *Account) _checkForReverseEntry(reply string, si *serviceImport, checkIn
return
}
if sres := a.imports.rrMap[reply]; sres == nil {
if _, ok := a.imports.rrMap[reply]; !ok {
a.mu.RUnlock()
return
}
@@ -1979,22 +2070,18 @@ func (a *Account) _checkForReverseEntry(reply string, si *serviceImport, checkIn
// Delete the appropriate entries here based on optional si.
a.mu.Lock()
// We need a new lookup here because we have released the lock.
sres := a.imports.rrMap[reply]
var sres []*serviceRespEntry
if si == nil {
sres = a.imports.rrMap[reply].list
delete(a.imports.rrMap, reply)
} else if sres != nil {
// Find the one we are looking for..
for i, sre := range sres {
if sre.msub == si.from {
sres = append(sres[:i], sres[i+1:]...)
break
}
}
if len(sres) > 0 {
a.imports.rrMap[si.to] = sres
} else {
delete(a.imports.rrMap, si.to)
}
} else {
// Constant time once indexed, instead of a linear scan across every
// outstanding response that happens to share this reply subject.
// This also keys the write back off reply rather than si.to. Every
// caller reaches here with si.to equal to reply, so behavior is
// unchanged, but the lookup and the write back can no longer drift
// apart if that ever stops holding.
a.imports.removeRespEntry(reply, si.from)
}
a.mu.Unlock()
+5 -2
View File
@@ -1841,7 +1841,6 @@ func (c *client) flushOutbound() bool {
// can be tuned to a known maximum quantity (64MB).
nc.SetWriteDeadline(time.Now().Add(wdl))
wn, err = wnb.WriteTo(nc)
nc.SetWriteDeadline(time.Time{})
// Update accounting, move wnb slice onwards if needed, or stop
// if a write error was reported that wasn't a short write.
@@ -1852,6 +1851,10 @@ func (c *client) flushOutbound() bool {
}
}
// The deadline is overwritten at the start of each iteration anyway,
// so only needed to clear the write deadline once after the loop.
nc.SetWriteDeadline(time.Time{})
lft := time.Since(start)
// Re-acquire client lock.
@@ -1885,7 +1888,7 @@ func (c *client) flushOutbound() bool {
// If we've written everything but the underlying array of our working
// buffer has grown excessively then free it — the GC will tidy it up
// and we can allocate a new one next time.
if len(c.out.wnb) == 0 && cap(c.out.wnb) > nbPoolSizeLarge*8 {
if len(c.out.wnb) == 0 && cap(c.out.wnb) > nbMaxVectorSize {
c.out.wnb = nil
}
+1 -1
View File
@@ -66,7 +66,7 @@ func init() {
const (
// VERSION is the current version for the server.
VERSION = "2.14.5"
VERSION = "2.14.6"
// PROTO is the currently supported protocol.
// 0 was the original
+95 -56
View File
@@ -476,6 +476,8 @@ type consumer struct {
maxdc uint64
waiting *waitQueue
cfg ConsumerConfig
direct bool // Immutable, enforced by checkNewConsumerConfig. Read without o.mu.
sourcing bool // Immutable, enforced by checkNewConsumerConfig. Read without o.mu.
ici *ConsumerInfo
store ConsumerStore
active bool
@@ -1184,6 +1186,8 @@ func (mset *stream) addConsumerWithAssignment(config *ConsumerConfig, oname stri
client: s.createInternalJetStreamClient(),
sysc: s.createInternalJetStreamClient(),
cfg: *config,
direct: config.Direct,
sourcing: config.Sourcing,
dsubj: config.DeliverSubject,
outq: mset.outq,
active: true,
@@ -1213,7 +1217,8 @@ func (mset *stream) addConsumerWithAssignment(config *ConsumerConfig, oname stri
if isDurableConsumer(config) {
if len(config.Durable) > JSMaxNameLen {
mset.mu.Unlock()
o.deleteWithoutAdvisory()
// Release the temporary consumer we built; it was never registered.
_ = o.stop()
return nil, NewJSConsumerNameTooLongError(JSMaxNameLen)
}
o.name = config.Durable
@@ -1233,16 +1238,6 @@ func (mset *stream) addConsumerWithAssignment(config *ConsumerConfig, oname stri
config.Name = o.name
}
}
// Create ackMsgs queue now that we have a consumer name
o.ackMsgs = newIPQueue[*jsAckMsg](s, fmt.Sprintf("[ACC:%s] consumer '%s' on stream '%s' ackMsgs", accName, o.name, cfg.Name))
// Create our request waiting queue.
if o.isPullMode() {
o.waiting = newWaitQueue(config.MaxWaiting)
// Create our internal queue for next msg requests.
o.nextMsgReqs = newIPQueue[*nextMsgReq](s, fmt.Sprintf("[ACC:%s] consumer '%s' on stream '%s' pull requests", accName, o.name, cfg.Name))
}
// already under lock, mset.Name() would deadlock
o.stream = cfg.Name
o.ackEventT = JSMetricConsumerAckPre + "." + o.stream + "." + o.name
@@ -1251,16 +1246,43 @@ func (mset *stream) addConsumerWithAssignment(config *ConsumerConfig, oname stri
if !isValidAssetName(o.name) {
mset.mu.Unlock()
o.deleteWithoutAdvisory()
// Release the temporary consumer we built; it was never registered.
_ = o.stop()
return nil, NewJSConsumerBadDurableNameError()
}
// Check if we already have this one registered.
if eo, ok := mset.consumers[o.name]; ok {
mset.mu.Unlock()
if !o.isDurable() || !o.isPushMode() {
_ = o.stop()
return nil, NewJSConsumerNameExistError()
}
// If we are here we have already registered this durable. If it is still active that is an error.
if eo.isActive() {
_ = o.stop()
return nil, NewJSConsumerExistingActiveError()
}
// Since we are here this means we have a potentially new durable so we should update here.
// Check that configs are the same.
if !configsEqualSansDelivery(o.cfg, eo.cfg) {
_ = o.stop()
return nil, NewJSConsumerReplacementWithDifferentNameError()
}
// Once we are here we have a replacement push-based durable.
eo.updateDeliverSubject(o.cfg.DeliverSubject)
// Release the temporary consumer we built; it was never registered.
_ = o.stop()
return eo, nil
}
// Setup our storage if not a direct consumer.
if !config.Direct {
store, err := mset.store.ConsumerStore(o.name, o.created, config)
if err != nil {
mset.mu.Unlock()
o.deleteWithoutAdvisory()
// Store creation failed, so just cleanup.
_ = o.stop()
return nil, NewJSConsumerStoreFailedError(err)
}
o.store = store
@@ -1330,6 +1352,8 @@ func (mset *stream) addConsumerWithAssignment(config *ConsumerConfig, oname stri
if err != nil {
s.Errorf("JetStream consumer '%s > %s > %s' errored while updating state: %v", o.acc.Name, o.stream, o.name, err)
mset.mu.Unlock()
// Release the temporary consumer we built; it was never registered.
_ = o.stop()
return nil, NewJSConsumerStoreFailedError(err)
}
}
@@ -1337,37 +1361,26 @@ func (mset *stream) addConsumerWithAssignment(config *ConsumerConfig, oname stri
// Clustered non-direct consumers defer this to setLeader so the
// expensive store scans don't block the meta apply goroutine.
if err := o.selectStartingSeqNo(); err != nil {
// Delete our store while holding the stream lock, so a concurrent create
// for the same name cannot have registered and be sharing this on-disk
// directory. Then release the rest of the consumer non-destructively.
if o.store != nil {
_ = o.store.Delete()
o.store = nil
}
mset.mu.Unlock()
o.deleteWithoutAdvisory()
_ = o.stop()
return nil, err
}
}
// Now register with mset and create the ack subscription.
// Check if we already have this one registered.
if eo, ok := mset.consumers[o.name]; ok {
mset.mu.Unlock()
if !o.isDurable() || !o.isPushMode() {
o.name = _EMPTY_ // Prevent removal since same name.
o.deleteWithoutAdvisory()
return nil, NewJSConsumerNameExistError()
}
// If we are here we have already registered this durable. If it is still active that is an error.
if eo.isActive() {
o.name = _EMPTY_ // Prevent removal since same name.
o.deleteWithoutAdvisory()
return nil, NewJSConsumerExistingActiveError()
}
// Since we are here this means we have a potentially new durable so we should update here.
// Check that configs are the same.
if !configsEqualSansDelivery(o.cfg, eo.cfg) {
o.name = _EMPTY_ // Prevent removal since same name.
o.deleteWithoutAdvisory()
return nil, NewJSConsumerReplacementWithDifferentNameError()
}
// Once we are here we have a replacement push-based durable.
eo.updateDeliverSubject(o.cfg.DeliverSubject)
return eo, nil
// Create ackMsgs queue now that we have a consumer name
o.ackMsgs = newIPQueue[*jsAckMsg](s, fmt.Sprintf("[ACC:%s] consumer '%s' on stream '%s' ackMsgs", accName, o.name, cfg.Name))
// Create our request waiting queue.
if o.isPullMode() {
o.waiting = newWaitQueue(config.MaxWaiting)
o.nextMsgReqs = newIPQueue[*nextMsgReq](s, fmt.Sprintf("[ACC:%s] consumer '%s' on stream '%s' pull requests", accName, o.name, cfg.Name))
}
// Set up the ack subscription for this consumer. Will use wildcard for all acks.
@@ -1670,6 +1683,8 @@ func (o *consumer) setLeader(isLeader bool, term uint64) error {
o.resetPendingDeliveries()
// Reset num pending, these are only authoritative on the leader.
o.npc, o.npf = 0, 0
// Reset flow control accounting.
o.pbytes, o.fcsz, o.fcid = 0, 0, _EMPTY_
// ok if they are nil, we protect inside unsubscribe()
o.unsubscribe(o.ackSubOld)
o.unsubscribe(o.ackSub)
@@ -2235,7 +2250,7 @@ func (o *consumer) deleteNotActive() {
}
s, js := o.mset.srv, o.srv.js.Load()
acc, stream, name, isDirect := o.acc.Name, o.stream, o.name, o.cfg.Direct
acc, stream, name, isDirect := o.acc.Name, o.stream, o.name, o.direct
// Capture our own view of the assignment while we still hold the lock.
ca := o.ca
var qch, cqch chan struct{}
@@ -2474,6 +2489,14 @@ func (acc *Account) checkNewConsumerConfig(cfg, ncfg *ConsumerConfig) error {
if cfg.MemoryStorage != ncfg.MemoryStorage {
return errors.New("storage type can not be updated")
}
// Direct and Sourcing classify the consumer for its whole lifetime, which the
// stream relies on when walking its consumer list, so they can not change.
if cfg.Direct != ncfg.Direct {
return errors.New("direct can not be updated")
}
if cfg.Sourcing != ncfg.Sourcing {
return errors.New("sourcing can not be updated")
}
if cfg.OptStartSeq != ncfg.OptStartSeq {
return errors.New("start sequence can not be updated")
}
@@ -3687,7 +3710,7 @@ func (o *consumer) processAckMsgLocked(sseq, dseq, dc uint64, reply string, doSa
// violate lock ordering with respect to the stream.
ackInPlace := o.node == nil && o.retention != LimitsPolicy && needLock
var sgap, floor uint64
var ackAllSeqs []uint64
var needSignal bool
switch o.cfg.AckPolicy {
@@ -3716,17 +3739,25 @@ func (o *consumer) processAckMsgLocked(sseq, dseq, dc uint64, reply string, doSa
if o.maxp > 0 && len(o.pending) >= o.maxp {
needSignal = true
}
sgap = sseq - o.asflr
floor = sseq // start at same and set lower as we go.
sgap := sseq - o.asflr
o.adflr, o.asflr = dseq, sseq
// Only needed if we ack in place, otherwise we'd never collect anything.
// At most the pending entries below the ack, don't over-allocate.
if ackInPlace {
ackAllSeqs = make([]uint64, 0, min(uint64(len(o.pending)), sgap-1))
}
remove := func(seq uint64) {
// Only collect what was actually delivered to us.
if ackInPlace && seq != sseq {
if _, ok := o.pending[seq]; ok {
ackAllSeqs = append(ackAllSeqs, seq)
}
}
delete(o.pending, seq)
delete(o.rdc, seq)
o.removeFromRedeliverQueue(seq)
if seq < floor {
floor = seq
}
}
// Determine if smarter to walk all of pending vs the sequence range.
if sgap > uint64(len(o.pending)) {
@@ -3756,13 +3787,9 @@ func (o *consumer) processAckMsgLocked(sseq, dseq, dc uint64, reply string, doSa
unlock()
if ackInPlace {
if sgap > 1 {
// FIXME(dlc) - This can very inefficient, will need to fix.
for seq := sseq; seq >= floor; seq-- {
mset.ackMsg(o, seq)
}
} else {
mset.ackMsg(o, sseq)
mset.ackMsg(o, sseq)
for _, seq := range ackAllSeqs {
mset.ackMsg(o, seq)
}
}
@@ -4745,9 +4772,21 @@ func (o *consumer) incDeliveryCount(sseq uint64) uint64 {
// Lock should be held.
func (o *consumer) decDeliveryCount(sseq uint64) {
if o.rdc == nil {
o.rdc = make(map[uint64]uint64)
return
}
dc, ok := o.rdc[sseq]
if !ok {
return
}
// Mirror incDeliveryCount, which goes from "no entry" to 1 on the first
// redelivery. Going back to the initial delivery therefore has to remove
// the entry rather than leave a zero behind, since a number of call sites
// (needAck, decStreamPending) test for key presence rather than value.
if dc > 1 {
o.rdc[sseq] = dc - 1
} else {
delete(o.rdc, sseq)
}
o.rdc[sseq] -= 1
}
// send a delivery exceeded advisory.
@@ -5698,7 +5737,7 @@ func (o *consumer) deliverMsg(dsubj, ackReply string, pmsg *jsPubMsg, dc uint64,
// If we are ack none and mset is interest only we should make sure stream removes interest.
if ap == AckNone && rp != LimitsPolicy {
if mset != nil && mset.ackq != nil && (o.node == nil || o.cfg.Direct) {
if mset != nil && mset.ackq != nil && (o.node == nil || o.direct) {
mset.ackq.push(seq)
} else {
o.updateAcks(dseq, seq, _EMPTY_)
+185 -51
View File
@@ -16,6 +16,7 @@ package server
import (
"archive/tar"
"bytes"
"cmp"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
@@ -676,6 +677,12 @@ func (fs *fileStore) unlockAllMsgBlocks() {
}
}
func (fs *fileStore) setCreatedTime(created time.Time) {
fs.mu.Lock()
fs.cfg.Created = created
fs.mu.Unlock()
}
func (fs *fileStore) UpdateConfig(cfg *StreamConfig) error {
start := time.Now()
defer func() {
@@ -3858,6 +3865,9 @@ func (fs *fileStore) allLastSeqsLocked() ([]uint64, error) {
// Most clients send in subjects even if they match the stream's ingest subjects.
// Lock should be held.
func (fs *fileStore) filterIsAll(filters []string) bool {
if len(filters) == 1 && filters[0] == fwcs {
return true
}
if len(filters) != len(fs.cfg.Subjects) {
return false
}
@@ -3878,7 +3888,11 @@ func (fs *fileStore) filterIsAll(filters []string) bool {
func (fs *fileStore) MultiLastSeqs(filters []string, maxSeq uint64, maxAllowed int) ([]uint64, error) {
fs.mu.RLock()
defer fs.mu.RUnlock()
return fs.multiLastSeqsLocked(filters, maxSeq, maxAllowed)
}
// Lock should be held.
func (fs *fileStore) multiLastSeqsLocked(filters []string, maxSeq uint64, maxAllowed int) ([]uint64, error) {
if fs.state.Msgs == 0 || fs.noTrackSubjects() {
return nil, nil
}
@@ -3931,6 +3945,17 @@ func (fs *fileStore) MultiLastSeqs(filters []string, maxSeq uint64, maxAllowed i
// Collect all sequences needed.
seqs := make([]uint64, 0, len(subs))
// If covering the whole stream, check fast path of visiting only last blocks.
if maxSeq >= fs.state.LastSeq {
if maxAllowed > 0 && len(subs) > maxAllowed {
return nil, ErrTooManyResults
}
if err := fs.multiLastSeqsByLastBlockLocked(subs, &seqs); err != nil {
return nil, err
}
}
for i, lnf := lastBlkIndex, false; i >= 0; i-- {
if len(subs) == 0 {
break
@@ -4015,6 +4040,107 @@ func (fs *fileStore) MultiLastSeqs(filters []string, maxSeq uint64, maxAllowed i
return seqs, nil
}
// MultiLastMsgs delivers the last message per subject matching the filters,
// up to maxSeq and skipping sequences below minSeq, in ascending sequence
// order through cb, all within a single read section so the batch is a
// point-in-time snapshot of the store.
func (fs *fileStore) MultiLastMsgs(filters []string, minSeq, maxSeq uint64, maxAllowed int, cb func(sm *StoreMsg, np uint64) bool) (uint64, uint64, error) {
fs.mu.RLock()
defer fs.mu.RUnlock()
seqs, err := fs.multiLastSeqsLocked(filters, maxSeq, maxAllowed)
if err != nil || len(seqs) == 0 {
return 0, 0, err
}
total := uint64(len(seqs))
np := total
for _, seq := range seqs {
if np > 0 {
np--
}
if seq < minSeq {
continue
}
var svp StoreMsg
sm, err := fs.msgForSeqLocked(seq, &svp, false)
if err != nil {
return total, np, err
}
if !cb(sm, np) {
break
}
}
return total, np, nil
}
// multiLastSeqsByLastBlockLocked resolves last sequences via each subject's
// last block (psi.lblk), moving resolved subjects from subs into seqs and
// leaving unresolved ones (e.g. stale lblk) in subs for the caller.
// Lock should be held.
func (fs *fileStore) multiLastSeqsByLastBlockLocked(subs map[string]*psi, seqs *[]uint64) error {
// Sort requested subjects by their last block so each block is visited
// once and in order, one flat slice instead of per-block map bookkeeping.
type lblkSubj struct {
lblk uint32
subj string
info *psi
}
pairs := make([]lblkSubj, 0, len(subs))
for subj, info := range subs {
pairs = append(pairs, lblkSubj{info.lblk, subj, info})
}
slices.SortFunc(pairs, func(a, b lblkSubj) int {
return cmp.Compare(a.lblk, b.lblk)
})
var unresolved []lblkSubj
for i := 0; i < len(pairs); {
blkIdx := pairs[i].lblk
j := i + 1
for j < len(pairs) && pairs[j].lblk == blkIdx {
j++
}
mb := fs.bim[blkIdx]
if mb == nil {
unresolved = append(unresolved, pairs[i:j]...)
i = j
continue
}
mb.mu.Lock()
if err := mb.ensurePerSubjectInfoLoaded(); err != nil {
mb.mu.Unlock()
return err
}
for ; i < j; i++ {
subj := pairs[i].subj
ss, ok := mb.fss.Find(stringToBytes(subj))
if !ok || ss == nil {
unresolved = append(unresolved, pairs[i])
continue
}
// Check if we need to recalculate. We only care about the last sequence.
if ss.lastNeedsUpdate {
if err := mb.recalculateForSubj(subj, ss); err != nil {
mb.mu.Unlock()
return err
}
}
*seqs = append(*seqs, ss.Last)
}
mb.mu.Unlock()
}
// Shrink subs down to only the unresolved subjects, clearing wholesale
// rather than deleting per resolved subject.
if len(unresolved) < len(subs) {
clear(subs)
for _, p := range unresolved {
subs[p.subj] = p.info
}
}
return nil
}
// NumPending will return the number of pending messages matching the filter subject starting at sequence.
// Optimized for stream num pending calculations for consumers.
func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool) (total, validThrough uint64, err error) {
@@ -6255,20 +6381,13 @@ func (mb *msgBlock) compactWithFloor(floor uint64, fsDmap *interiorDeletes) erro
// We will write to a new file and mv/rename it in case of failure.
mfn := filepath.Join(mb.fs.fcfg.StoreDir, msgDir, fmt.Sprintf(newScan, mb.index))
mb.fs.dios.acquire()
err := os.WriteFile(mfn, nbuf, defaultFilePerms)
mb.fs.dios.release()
if err != nil {
_ = os.Remove(mfn)
return err
}
if err := os.Rename(mfn, mb.mfn); err != nil {
_ = os.Remove(mfn)
sync := mb.syncAlways
if err := writeAtomicallyWithTemp(mb.fs.dios, mfn, mb.mfn, nbuf, defaultFilePerms, sync); err != nil {
return err
}
// Make sure to sync
mb.needSync = true
// Make sure to sync if we have not done so yet
mb.needSync = !sync
// Capture the updated rbytes.
if rbytes := uint64(len(nbuf)); rbytes == mb.rbytes {
@@ -7833,6 +7952,35 @@ func (mb *msgBlock) ensureRawBytesLoaded() error {
return nil
}
// Lock should be held.
func (mb *msgBlock) syncFile() error {
mb.fs.dios.acquire()
defer mb.fs.dios.release()
fd, didOpen := mb.mfd, false
if fd == nil {
var err error
fd, err = os.OpenFile(mb.mfn, os.O_RDWR, defaultFilePerms)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
didOpen = true
}
if err := fd.Sync(); err != nil {
// Close fd if we opened it, but ignore its error since sync takes precedence.
if didOpen {
_ = fd.Close()
}
return err
}
if didOpen {
return fd.Close()
}
return nil
}
// Sync msg and index files as needed. This is called from a timer.
func (fs *fileStore) syncBlocks() {
if fs.isClosed() {
@@ -7858,6 +8006,7 @@ func (fs *fileStore) syncBlocks() {
var fsDmap *interiorDeletes
var markDirty bool
var needDirSync bool
for _, mb := range blks {
// Do actual sync. Hold lock for consistency.
mb.mu.Lock()
@@ -7928,12 +8077,14 @@ func (fs *fileStore) syncBlocks() {
err := mb.compactWithFloor(firstSeq, fsDmap)
// If this compact removed all raw bytes due to tombstone cleanup, schedule to remove.
shouldRemove := mb.rbytes == 0
needSync = mb.needSync
mb.mu.Unlock()
fs.mu.RUnlock()
if err != nil {
storeFsWerr(err)
continue
}
needDirSync = needDirSync || needSync || shouldRemove
// Check if we should remove. This will not be common, so we will re-take fs write lock here vs changing
// it above which we would prefer to be a readlock such that other lookups can occur while compacting this block.
@@ -7962,43 +8113,23 @@ func (fs *fileStore) syncBlocks() {
// Check if we need to sync this block.
if needSync {
mb.mu.Lock()
var fd *os.File
var err error
var didOpen bool
if mb.mfd != nil {
fd = mb.mfd
} else {
fs.dios.acquire()
fd, err = os.OpenFile(mb.mfn, os.O_RDWR, defaultFilePerms)
fs.dios.release()
didOpen = true
if err != nil && !os.IsNotExist(err) {
mb.mu.Unlock()
storeFsWerr(err)
continue
}
}
// If we have an fd.
if fd != nil {
if err = fd.Sync(); err != nil {
// Close fd if we opened it, but ignore its error since sync takes precedence.
if didOpen {
_ = fd.Close()
}
mb.mu.Unlock()
storeFsWerr(err)
continue
}
// If we opened the file close the fd.
if didOpen {
if err = fd.Close(); err != nil {
mb.mu.Unlock()
storeFsWerr(err)
continue
}
}
err := mb.syncFile()
if err == nil {
mb.needSync = false
}
mb.mu.Unlock()
if err != nil {
storeFsWerr(err)
continue
}
}
}
if needDirSync && canFsyncDirectories {
fs.dios.acquire()
err := syncDir(filepath.Join(fs.fcfg.StoreDir, msgDir))
fs.dios.release()
if err != nil {
storeFsWerr(err)
}
}
@@ -13959,7 +14090,10 @@ func writeFileWithSync(dios *diskIOSemaphore, name string, data []byte, perm fs.
const canFsyncDirectories = runtime.GOOS != "windows"
func writeAtomically(dios *diskIOSemaphore, name string, data []byte, perm fs.FileMode, sync bool) error {
tmp := name + ".tmp"
return writeAtomicallyWithTemp(dios, name+".tmp", name, data, perm, sync)
}
func writeAtomicallyWithTemp(dios *diskIOSemaphore, tmp, name string, data []byte, perm fs.FileMode, sync bool) error {
flags := os.O_CREATE | os.O_WRONLY | os.O_TRUNC
if sync {
flags = flags | os.O_SYNC
@@ -13987,7 +14121,7 @@ func writeAtomically(dios *diskIOSemaphore, name string, data []byte, perm fs.Fi
if sync && canFsyncDirectories {
// To ensure that the file rename was persisted on all filesystems,
// also try to flush the directory metadata.
if err = syncDir(name); err != nil {
if err = syncDir(filepath.Dir(name)); err != nil {
return err
}
}
@@ -14013,7 +14147,7 @@ func (fs *fileStore) syncFileAndDir(name string) error {
return err
}
if canFsyncDirectories {
if err = syncDir(name); err != nil {
if err = syncDir(filepath.Dir(name)); err != nil {
return err
}
}
@@ -14021,10 +14155,10 @@ func (fs *fileStore) syncFileAndDir(name string) error {
}
// Dios should already be held.
func syncDir(name string) error {
func syncDir(path string) error {
var d *os.File
var err error
if d, err = os.Open(filepath.Dir(name)); err != nil {
if d, err = os.Open(path); err != nil {
return err
}
if err = d.Sync(); err != nil {
+40 -2
View File
@@ -50,6 +50,11 @@ type JetStreamConfig struct {
CompressOK bool `json:"compress_ok,omitempty"` // CompressOK indicates if compression is supported
UniqueTag string `json:"unique_tag,omitempty"` // UniqueTag is the unique tag assigned to this instance
Strict bool `json:"strict,omitempty"` // Strict indicates if strict JSON parsing is performed
// maxStorePending is set when MaxStore was derived from the available disk
// space rather than configured, and has not been adjusted yet for the space
// that recovered streams already occupy. See finalizeDynamicMaxStore.
maxStorePending bool
}
// Statistics about JetStream for this server.
@@ -516,6 +521,10 @@ func (s *Server) enableJetStream(cfg JetStreamConfig) error {
return err
}
// All file based streams have been recovered, so we now know how much of
// the disk we already occupy and can settle on a dynamic limit.
js.finalizeDynamicMaxStore()
// If we are in clustered mode go ahead and start the meta controller.
if !standAlone || canExtend {
if err := s.enableJetStreamClustering(); err != nil {
@@ -531,6 +540,30 @@ func (s *Server) enableJetStream(cfg JetStreamConfig) error {
return nil
}
// finalizeDynamicMaxStore settles a dynamic max store limit once all file based
// streams have been recovered. diskAvailable only reports free space, so add back
// what we occupy ourselves to keep the limit stable across restarts.
func (js *jetStream) finalizeDynamicMaxStore() {
js.mu.Lock()
if !js.config.maxStorePending {
js.mu.Unlock()
return
}
// From here on the limit is real and can be enforced, see sufficientResources.
js.config.maxStorePending = false
recovered := atomic.LoadInt64(&js.storeUsed)
if recovered <= 0 {
js.mu.Unlock()
return
}
// diskAvailable is already scaled down to 75% of what is free, so scale the
// recovered bytes the same way before adding them back.
maxStore := addSaturate(js.config.MaxStore, recovered/4*3)
js.config.MaxStore = maxStore
atomic.StoreInt64(&js.storeMax, maxStore)
js.mu.Unlock()
}
const jsNoExtend = "no_extend"
const jsWillExtend = "will_extend"
@@ -1325,6 +1358,8 @@ func (a *Account) EnableJetStream(limits map[string]JetStreamAccountLimits, tq c
acc: a,
srv: s,
cfg: cfg.ConsumerConfig,
direct: cfg.Direct,
sourcing: cfg.Sourcing,
active: false,
stream: mset.name(),
name: cfg.Name,
@@ -2619,7 +2654,9 @@ func (js *jetStream) sufficientResources(limits map[string]JetStreamAccountLimit
if js.memReserved+totalMaxMemory > js.config.MaxMemory {
return NewJSMemoryResourcesExceededError()
}
if js.storeReserved+totalMaxStore > js.config.MaxStore {
// A dynamic limit is still provisional until recovery has run.
recovering := js.config.maxStorePending
if !recovering && js.storeReserved+totalMaxStore > js.config.MaxStore {
return NewJSStorageResourcesExceededError()
}
@@ -2639,7 +2676,7 @@ func (js *jetStream) sufficientResources(limits map[string]JetStreamAccountLimit
if memReserved+totalMaxMemory > js.config.MaxMemory {
return NewJSMemoryResourcesExceededError()
}
if storeReserved+totalMaxStore > js.config.MaxStore {
if !recovering && storeReserved+totalMaxStore > js.config.MaxStore {
return NewJSStorageResourcesExceededError()
}
@@ -2724,6 +2761,7 @@ func (s *Server) dynJetStreamConfig(storeDir string, maxStore, maxMem int64) *Je
jsc.MaxStore = maxStore
} else {
jsc.MaxStore = diskAvailable(jsc.StoreDir)
jsc.maxStorePending = true
}
if maxMem > 0 || (opts.maxMemSet && maxMem == 0) {
+2 -2
View File
@@ -3457,8 +3457,8 @@ func (s *Server) jsMsgGetRequest(sub *subscription, c *client, _ *Account, subje
var sm *StoreMsg
// Ensure this read request is isolated and doesn't interleave with writes.
mset.mu.RLock()
defer mset.mu.RUnlock()
mset.isolateMu.RLock()
defer mset.isolateMu.RUnlock()
// If AsOfTime is set, perform this first to get the sequence.
var seq uint64
+8 -26
View File
@@ -497,7 +497,6 @@ func (diff *batchStagedDiff) commit(mset *stream) {
}
type batchApply struct {
mu sync.Mutex
id string // ID of the current batch.
count uint64 // Number of entries in the batch, for consistency checks.
entries []*CommittedEntry // Previous entries that are part of this batch.
@@ -505,9 +504,8 @@ type batchApply struct {
maxApplied uint64 // Applied value before the entry containing the first message of the batch.
}
// clearBatchStateLocked clears in-memory apply-batch-related state.
// batch.mu lock should be held.
func (batch *batchApply) clearBatchStateLocked() {
// clearBatchState clears in-memory apply-batch-related state.
func (batch *batchApply) clearBatchState() {
batch.id = _EMPTY_
batch.count = 0
batch.entries = nil
@@ -517,8 +515,7 @@ func (batch *batchApply) clearBatchStateLocked() {
// rejectBatchStateLocked rejects the batch and clears in-memory apply-batch-related state.
// Corrects mset.clfs to take the failed batch into account.
// batch.mu lock should be held.
func (batch *batchApply) rejectBatchStateLocked(mset *stream) {
func (batch *batchApply) rejectBatchState(mset *stream) {
mset.clMu.Lock()
mset.clfs += batch.count
mset.clMu.Unlock()
@@ -526,13 +523,7 @@ func (batch *batchApply) rejectBatchStateLocked(mset *stream) {
for _, bce := range batch.entries {
bce.ReturnToPool()
}
batch.clearBatchStateLocked()
}
func (batch *batchApply) rejectBatchState(mset *stream) {
batch.mu.Lock()
defer batch.mu.Unlock()
batch.rejectBatchStateLocked(mset)
batch.clearBatchState()
}
// checkMsgHeadersPreClusteredProposal checks the message for expected/consistency headers.
@@ -1047,25 +1038,16 @@ func checkMsgHeadersPreClusteredProposal(
// mset.clMu lock must be held.
func recalculateClusteredSeq(mset *stream, needStreamLock bool) (lseq uint64) {
// Need to unlock and re-acquire the locks in the proper order.
mset.clMu.Unlock()
// Locking order is stream -> batchMu -> clMu
// Locking order is stream -> clMu
if needStreamLock {
mset.clMu.Unlock()
mset.mu.RLock()
mset.clMu.Lock()
}
batch := mset.batchApply
var batchCount uint64
if batch != nil {
batch.mu.Lock()
batchCount = batch.count
}
mset.clMu.Lock()
// Re-capture
lseq = mset.lseq
mset.clseq = lseq + mset.clfs + batchCount
mset.clseq = lseq + mset.clfs
// Keep hold of the mset.clMu, but unlock the others.
if batch != nil {
batch.mu.Unlock()
}
if needStreamLock {
mset.mu.RUnlock()
}
+169 -158
View File
@@ -3220,6 +3220,25 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnaps
failedSnapshots int
)
// Make sure all pending data is flushed before allowing snapshots. Returns false if
// it couldn't be flushed, in which case we have no safe way to continue.
flushPending := func() bool {
err := mset.flushAllPending()
if err == nil {
return true
}
s.Errorf("Failed to flush pending data for '%s > %s' [%s]: %v", accName, mset.name(), n.Group(), err)
assert.Unreachable("Stream snapshot flush failed", map[string]any{
"account": accName,
"stream": mset.name(),
"group": n.Group(),
"err": err,
})
mset.setWriteErr(err)
n.Stop()
return false
}
doSnapshot := func(force bool) {
// Suppress during recovery.
if mset == nil || isRecovering || isRestore {
@@ -3227,6 +3246,20 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnaps
}
snapMu.Lock()
defer snapMu.Unlock()
// Don't suppress a snapshot during shutdown.
if js.isShuttingDown() {
if !flushPending() {
return
}
if err := n.InstallSnapshot(mset.stateSnapshot(), true); err != nil &&
err != errNoSnapAvailable && err != errNodeClosed {
s.RateLimitWarnf("Failed to install snapshot for '%s > %s' [%s]: %v",
mset.acc.Name, mset.name(), n.Group(), err)
}
return
}
// If snapshots have failed, and we're not forced to, we'll wait for the timer since it'll now be forced.
if !force && failedSnapshots > 0 {
return
@@ -3254,20 +3287,8 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnaps
}
return
}
// Make sure all pending data is flushed before allowing snapshots.
if err := mset.flushAllPending(); err != nil {
// If the pending data couldn't be flushed, we have no safe way to continue.
s.Errorf("Failed to flush pending data for '%s > %s' [%s]: %v", accName, mset.name(), n.Group(), err)
assert.Unreachable("Stream snapshot flush failed", map[string]any{
"account": accName,
"stream": mset.name(),
"group": n.Group(),
"err": err,
})
if !flushPending() {
c.Abort()
mset.setWriteErr(err)
n.Stop()
return
}
@@ -3393,23 +3414,26 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnaps
sendSnapshot = false
}
// State to check for atomic batch completeness before applying it.
batch := &batchApply{}
defer func() {
for _, bce := range batch.entries {
bce.ReturnToPool()
}
batch.clearBatchState()
}()
for {
select {
case <-s.quitCh:
// Server shutting down, but we might receive this before qch, so try to snapshot.
snapMu.Lock()
fallbackSnapshot = true
snapMu.Unlock()
doSnapshot(false)
return
case <-mqch:
// Clean signal from shutdown routine so do best effort attempt to snapshot.
// Don't snapshot if not shutting down, monitor goroutine could be going away
// on a scale down or a remove for example.
if s.isShuttingDown() {
snapMu.Lock()
fallbackSnapshot = true
snapMu.Unlock()
if js.isShuttingDown() {
doSnapshot(false)
}
return
@@ -3444,13 +3468,8 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnaps
continue
} else if len(ce.Entries) == 0 {
// If we have a partial batch, it needs to be rejected to ensure CLFS is correct.
if mset != nil {
mset.mu.RLock()
batch := mset.batchApply
mset.mu.RUnlock()
if batch != nil {
batch.rejectBatchState(mset)
}
if mset != nil && batch != nil && batch.id != _EMPTY_ {
batch.rejectBatchState(mset)
}
// Entry could be empty on a restore when mset is nil.
@@ -3460,7 +3479,7 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnaps
}
// Apply our entries.
if maxApplied, err := js.applyStreamEntries(mset, ce, isRecovering); err == nil {
if maxApplied, err := js.applyStreamEntries(mset, n, ce, isRecovering, batch); err == nil {
// Update our applied.
if maxApplied > 0 {
// Indicate we've processed (but not applied) everything up to this point.
@@ -3488,12 +3507,20 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnaps
// instead of fully resetting the state. Resetting the clustered state may result in
// race conditions and should only be used as a last effort attempt.
if errors.Is(err, errCatchupAbortedNoLeader) || err == errCatchupTooManyRetries || err == errAlreadyLeader {
if node := mset.raftNode(); node != nil && node.DrainAndReplaySnapshot() {
if n.DrainAndReplaySnapshot() {
break
} else if n.IsDeleted() {
// The only reason we can't replay is our node being deleted, which
// means the meta layer is deliberately tearing this monitor down.
// Don't fall through to a reset, that would resurrect this group.
s.Warnf("Will not reset stream '%s > %s', raft group %q was removed",
accName, sa.Config.Name, n.Group())
aq.recycle(&ces)
return
}
}
// We will attempt to reset our cluster state.
if mset.resetClusteredState(err) {
if mset.resetClusteredState(n, err) {
aq.recycle(&ces)
return
}
@@ -3882,7 +3909,7 @@ func (mset *stream) isMigrating() bool {
}
// resetClusteredState is called when a clustered stream had an error (e.g sequence mismatch, bad snapshot) and needs to be reset.
func (mset *stream) resetClusteredState(err error) bool {
func (mset *stream) resetClusteredState(n RaftNode, err error) bool {
mset.mu.RLock()
s, js, jsa, sa, acc, node, name := mset.srv, mset.js, mset.jsa, mset.sa, mset.acc, mset.node, mset.nameLocked(false)
stype, tierName, replicas := mset.cfg.Storage, mset.tier, mset.cfg.Replicas
@@ -3890,12 +3917,24 @@ func (mset *stream) resetClusteredState(err error) bool {
// The stream might already be deleted and not assigned to us anymore.
// In any case, don't revive the stream if it's already closed.
if mset.closed.Load() || (node != nil && node.IsDeleted()) {
// A nil node means it was removed out from underneath us, which only happens
// when the meta layer is deliberately tearing this monitor down.
if mset.closed.Load() || node == nil || node.IsDeleted() {
s.Warnf("Will not reset stream '%s > %s', stream is closed", acc, mset.name())
// Explicitly returning true here, we want the outside to break out of the monitoring loop as well.
return true
}
// The node we were monitoring is no longer this stream's node. The meta layer has
// remapped us into a different group and is tearing this monitor down, so resetting
// here would resurrect a group that has already been replaced.
if n != nil && n != node {
s.Warnf("Will not reset stream '%s > %s', raft group %q was replaced by %q",
acc, mset.name(), n.Group(), node.Group())
// Explicitly returning true here, we want the outside to break out of the monitoring loop as well.
return true
}
assert.Unreachable("Reset clustered state", map[string]any{
"stream": name,
"account": acc.Name,
@@ -3903,9 +3942,7 @@ func (mset *stream) resetClusteredState(err error) bool {
})
// Stepdown regardless if we are the leader here.
if node != nil {
node.StepDown()
}
node.StepDown()
// If we detect we are shutting down just return.
if js != nil && js.isShuttingDown() {
@@ -3925,14 +3962,12 @@ func (mset *stream) resetClusteredState(err error) bool {
return false
}
if node != nil {
if errors.Is(err, errCatchupAbortedNoLeader) || err == errCatchupTooManyRetries {
// Don't delete all state, could've just been temporarily unable to reach the leader.
node.Stop()
} else {
// We delete our raft state. Will recreate.
node.Delete()
}
if errors.Is(err, errCatchupAbortedNoLeader) || err == errCatchupTooManyRetries {
// Don't delete all state, could've just been temporarily unable to reach the leader.
node.Stop()
} else {
// We delete our raft state. Will recreate.
node.Delete()
}
// Preserve our current state and messages unless we have a first sequence mismatch.
@@ -3992,11 +4027,7 @@ func isControlHdr(hdr []byte) bool {
// Apply our stream entries.
// Return maximum allowed applied value, if currently inside a batch, zero otherwise.
func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isRecovering bool) (uint64, error) {
mset.mu.RLock()
batch := mset.batchApply
mset.mu.RUnlock()
func (js *jetStream) applyStreamEntries(mset *stream, n RaftNode, ce *CommittedEntry, isRecovering bool, batch *batchApply) (uint64, error) {
for i, e := range ce.Entries {
// Ignore if lower-level catchup is started.
// We don't need to optimize during this, all entries are handled as normal.
@@ -4019,29 +4050,21 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
if err != nil {
panic(err.Error())
}
// Initialize if unset.
if batch == nil {
batch = &batchApply{}
mset.mu.Lock()
mset.batchApply = batch
mset.mu.Unlock()
}
// Need to grab the stream lock before the batch lock.
// Need to grab the stream lock first.
if isRecovering {
mset.mu.Lock()
}
batch.mu.Lock()
// Previous batch (if any) was abandoned.
if batch.id != _EMPTY_ && batchId != batch.id {
batch.rejectBatchStateLocked(mset)
batch.rejectBatchState(mset)
}
if batchSeq == 1 {
// If this is the first message in the batch, need to mark the start index.
// We'll continue to check batch-completeness and try to find the commit.
// At that point we'll commit the whole batch.
batch.rejectBatchStateLocked(mset)
batch.rejectBatchState(mset)
batch.entryStart = i
batch.maxApplied = ce.Index - 1
}
@@ -4054,7 +4077,6 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
if isRecovering {
if batchSeq > 1 && batch.count == 0 {
if skip, err := mset.skipBatchIfRecovering(batch, buf); err != nil || skip {
batch.mu.Unlock()
mset.mu.Unlock()
if err != nil {
panic(err.Error())
@@ -4068,37 +4090,24 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
batch.count++
// If the sequence is not monotonically increasing/we identify gaps, the batch can't be accepted.
if batchSeq != batch.count {
batch.rejectBatchStateLocked(mset)
batch.mu.Unlock()
batch.rejectBatchState(mset)
continue
}
batch.mu.Unlock()
continue
} else if op == batchCommitMsgOp {
batchId, batchSeq, _, _, err := decodeBatchMsg(buf[1:])
if err != nil {
panic(err.Error())
}
// Ensure the whole batch is fully isolated, and reads
// can only happen after the full batch is committed.
mset.mu.Lock()
// Initialize if unset.
if batch == nil {
batch = &batchApply{}
mset.batchApply = batch
}
batch.mu.Lock()
// Previous batch (if any) was abandoned.
if batch.id != _EMPTY_ && batchId != batch.id {
batch.rejectBatchStateLocked(mset)
batch.rejectBatchState(mset)
}
if batchSeq == 1 {
// If this is the first message in the batch, need to mark the start index.
// This is a batch of size one that immediately commits.
batch.rejectBatchStateLocked(mset)
batch.rejectBatchState(mset)
batch.entryStart = i
batch.maxApplied = ce.Index - 1
}
@@ -4110,7 +4119,6 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
// If we still see the first message of the batch, we don't skip any messages of the batch here.
if isRecovering && batchSeq > 1 && batch.count == 0 {
if skip, err := mset.skipBatchIfRecovering(batch, buf); err != nil || skip {
batch.mu.Unlock()
mset.mu.Unlock()
if err != nil {
panic(err.Error())
@@ -4122,12 +4130,16 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
batch.count++
// Detected a gap, reject the batch.
if batchSeq != batch.count {
batch.rejectBatchStateLocked(mset)
batch.mu.Unlock()
batch.rejectBatchState(mset)
mset.mu.Unlock()
continue
}
// Ensure the whole batch is fully isolated, and reads
// can only happen after the full batch is committed.
mset.mu.Unlock()
mset.isolateMu.Lock()
// Process any entries that are part of this batch but prior to the current one.
var entries []*Entry
for j, bce := range batch.entries {
@@ -4138,6 +4150,15 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
// Otherwise, all entries are used.
entries = bce.Entries
}
clearAndUnlock := func() {
// Make sure to return remaining entries to the pool on an error.
for _, nce := range batch.entries[j:] {
nce.ReturnToPool()
}
// Important to clear, otherwise we could return the entries to the pool multiple times.
batch.clearBatchState()
mset.isolateMu.Unlock()
}
for _, entry := range entries {
// Non-normal entries (e.g. EntryCatchup) can be buffered but must be ignored.
if entry.Type != EntryNormal {
@@ -4145,19 +4166,11 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
}
_, _, op, buf, err = decodeBatchMsg(entry.Data[1:])
if err != nil {
batch.mu.Unlock()
mset.mu.Unlock()
clearAndUnlock()
panic(err.Error())
}
if err = js.applyStreamMsgOp(mset, op, buf, isRecovering, false); err != nil {
// Make sure to return remaining entries to the pool on an error.
for _, nce := range batch.entries[j:] {
nce.ReturnToPool()
}
// Important to clear, otherwise we could return the entries to the pool multiple times.
batch.clearBatchStateLocked()
batch.mu.Unlock()
mset.mu.Unlock()
clearAndUnlock()
return 0, err
}
}
@@ -4171,6 +4184,11 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
// Get all entries up to and including the current one.
entries = ce.Entries[:i+1]
}
clearAndUnlock := func() {
// Important to clear, otherwise we could return the entries to the pool multiple times.
batch.clearBatchState()
mset.isolateMu.Unlock()
}
// Process remaining entries in the current entry.
for _, entry := range entries {
// Non-normal entries (e.g. EntryCatchup) can be buffered but must be ignored.
@@ -4179,22 +4197,17 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
}
_, _, op, buf, err = decodeBatchMsg(entry.Data[1:])
if err != nil {
batch.mu.Unlock()
mset.mu.Unlock()
clearAndUnlock()
panic(err.Error())
}
if err = js.applyStreamMsgOp(mset, op, buf, isRecovering, false); err != nil {
// Important to clear, otherwise we could return the entries to the pool multiple times.
batch.clearBatchStateLocked()
batch.mu.Unlock()
mset.mu.Unlock()
clearAndUnlock()
return 0, err
}
}
// Clear state, batch was successful.
batch.clearBatchStateLocked()
batch.mu.Unlock()
mset.mu.Unlock()
batch.clearBatchState()
mset.isolateMu.Unlock()
continue
} else if batch != nil && batch.id != _EMPTY_ {
// If a batch is abandoned without a commit, reject it.
@@ -4221,11 +4234,14 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
if dr.Num == 0 {
continue
}
// Delete ranges mutate message state, so hold the isolation lock like any other write.
mset.isolateMu.Lock()
mset.mu.Lock()
first, num := dr.First, dr.Num
lseq := first + num - 1
if mset.lseq >= lseq {
mset.mu.Unlock()
mset.isolateMu.Unlock()
continue
}
// Trim any prefix already applied so we only skip the uncovered tail.
@@ -4235,6 +4251,7 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
}
if err = mset.store.SkipMsgs(first, num); err != nil {
mset.mu.Unlock()
mset.isolateMu.Unlock()
js.srv.RateLimitWarnf("JetStream cluster failed to apply delete range [%d..%d] for '%s > %s': %v",
first, lseq, mset.account().Name, mset.cfg.Name, err)
return 0, err
@@ -4242,6 +4259,7 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
mset.clearAllPreAcksInRange(first, lseq)
mset.lseq = lseq
mset.mu.Unlock()
mset.isolateMu.Unlock()
case deleteMsgOp:
md, err := decodeMsgDelete(buf[1:])
@@ -4261,6 +4279,8 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
} else {
removed, err = mset.eraseMsg(md.Seq)
}
// Only respond for deletes that originated from a client request.
isClientReq := md.Client != nil
var isLeader bool
if node := mset.raftNode(); node != nil && node.Leader() {
@@ -4268,7 +4288,7 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
}
if err == ErrStoreEOF {
if isLeader && !isRecovering {
if isClientReq && isLeader && !isRecovering {
var resp = JSApiMsgDeleteResponse{ApiResponse: ApiResponse{Type: JSApiMsgDeleteResponseType}}
resp.Error = NewJSStreamMsgDeleteFailedError(err, Unless(err))
s.sendAPIErrResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
@@ -4281,7 +4301,7 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
md.Seq, md.Client.serviceAccount(), md.Stream, err)
}
if isLeader && !isRecovering {
if isClientReq && isLeader && !isRecovering {
var resp = JSApiMsgDeleteResponse{ApiResponse: ApiResponse{Type: JSApiMsgDeleteResponseType}}
if err != nil {
resp.Error = NewJSStreamMsgDeleteFailedError(err, Unless(err))
@@ -4352,7 +4372,7 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
s, accName, streamName := mset.srv, mset.acc.GetName(), mset.cfg.Name
mset.mu.RUnlock()
s.Warnf("Detected bad stream state, resetting '%s > %s'", accName, streamName)
mset.resetClusteredState(err)
mset.resetClusteredState(n, err)
}
}
@@ -4412,21 +4432,19 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
// If we're still actively processing a batch, must store the entry in-memory
// to come back to it later once we find the commit.
if batch != nil && batch.id != _EMPTY_ {
batch.mu.Lock()
if batch.entries == nil {
batch.entries = []*CommittedEntry{ce}
} else {
batch.entries = append(batch.entries, ce)
}
maxApplied := batch.maxApplied
batch.mu.Unlock()
return maxApplied, nil
}
return 0, nil
}
// skipBatchIfRecovering returns whether the batched message can be skipped because the batch was already fully applied.
// Stream and batch.mu locks should be held.
// Stream lock should be held.
func (mset *stream) skipBatchIfRecovering(batch *batchApply, buf []byte) (bool, error) {
_, _, op, mbuf, err := decodeBatchMsg(buf[1:])
if err != nil {
@@ -4453,13 +4471,15 @@ func (mset *stream) skipBatchIfRecovering(batch *batchApply, buf []byte) (bool,
mset.accountLocked(false), mset.nameLocked(false), lseq+1-clfs, last)
// Check for any preAcks in case we are interest based.
mset.clearAllPreAcks(lseq + 1 - clfs)
batch.clearBatchStateLocked()
batch.clearBatchState()
return true, nil
}
return false, nil
}
func (js *jetStream) applyStreamMsgOp(mset *stream, op entryOp, mbuf []byte, isRecovering bool, needLock bool) error {
// needIsolation should be false only if the caller already holds isolateMu
// across a whole atomic batch; mset.mu must NOT be held by the caller.
func (js *jetStream) applyStreamMsgOp(mset *stream, op entryOp, mbuf []byte, isRecovering bool, needIsolation bool) error {
s := js.srv
if op == compressedStreamMsgOp {
@@ -4472,11 +4492,8 @@ func (js *jetStream) applyStreamMsgOp(mset *stream, op entryOp, mbuf []byte, isR
subject, reply, hdr, msg, lseq, ts, sourced, err := decodeStreamMsg(mbuf)
if err != nil {
// We're going to panic below, but if we're already holding the stream lock, we should let go now.
// Otherwise we'll deadlock when trying to get the raft node.
if !needLock {
mset.mu.Unlock()
}
// We're going to panic below, we're not holding the stream lock, so
// we'll not deadlock when trying to get the raft node.
if node := mset.raftNode(); node != nil {
s.Errorf("JetStream cluster could not decode stream msg for '%s > %s' [%s]",
mset.account(), mset.name(), node.Group())
@@ -4487,38 +4504,26 @@ func (js *jetStream) applyStreamMsgOp(mset *stream, op entryOp, mbuf []byte, isR
// Check for flowcontrol here.
if len(msg) == 0 && len(hdr) > 0 && reply != _EMPTY_ && isControlHdr(hdr) {
if !isRecovering {
if needLock {
mset.mu.RLock()
}
mset.mu.RLock()
mset.sendFlowControlReply(reply, hdr)
if needLock {
mset.mu.RUnlock()
}
mset.mu.RUnlock()
}
return nil
}
if needLock {
mset.mu.RLock()
}
mset.mu.RLock()
// Grab last sequence and CLFS.
last, clfs := mset.lastSeqAndCLFS()
if needLock {
mset.mu.RUnlock()
}
mset.mu.RUnlock()
// We can skip if we know this is less than what we already have.
if lseq-clfs < last {
mset.mu.Lock()
s.Debugf("Apply stream entries for '%s > %s' skipping message with sequence %d with last of %d",
mset.accountLocked(needLock), mset.nameLocked(needLock), lseq+1-clfs, last)
if needLock {
mset.mu.Lock()
}
mset.accountLocked(false), mset.nameLocked(false), lseq+1-clfs, last)
// Check for any preAcks in case we are interest based.
mset.clearAllPreAcks(lseq + 1 - clfs)
if needLock {
mset.mu.Unlock()
}
mset.mu.Unlock()
return nil
}
@@ -4536,14 +4541,10 @@ func (js *jetStream) applyStreamMsgOp(mset *stream, op entryOp, mbuf []byte, isR
if err != nil {
return err
}
if needLock {
mset.mu.Lock()
}
mset.mu.Lock()
mset.lseq = last
mset.clearAllPreAcks(last)
if needLock {
mset.mu.Unlock()
}
mset.mu.Unlock()
return nil
}
@@ -4555,7 +4556,7 @@ func (js *jetStream) applyStreamMsgOp(mset *stream, op entryOp, mbuf []byte, isR
mt = mset.getAndDeleteMsgTrace(lseq)
}
// Process the actual message here.
err = mset.processJetStreamMsg(subject, reply, hdr, msg, lseq, ts, mt, sourced, needLock)
err = mset.processJetStreamMsg(subject, reply, hdr, msg, lseq, ts, mt, sourced, needIsolation)
// Take into account subject transforms, if any.
// The untransformed subject is replicated, but the transformed subject is used for consistency checks below.
@@ -4635,7 +4636,7 @@ func (js *jetStream) applyStreamMsgOp(mset *stream, op entryOp, mbuf []byte, isR
_, err = mset.store.Compact(lseq + 1)
if err == nil {
// Retry
err = mset.processJetStreamMsg(subject, reply, hdr, msg, lseq, ts, mt, sourced, needLock)
err = mset.processJetStreamMsg(subject, reply, hdr, msg, lseq, ts, mt, sourced, needIsolation)
}
}
// FIXME(dlc) - We could just run a catchup with a request defining the span between what we expected
@@ -4647,7 +4648,7 @@ func (js *jetStream) applyStreamMsgOp(mset *stream, op entryOp, mbuf []byte, isR
return err
}
s.Debugf("Apply stream entries for '%s > %s' got error processing message: %v",
mset.accountLocked(needLock), mset.nameLocked(needLock), err)
mset.accountLocked(true), mset.nameLocked(true), err)
// There are some errors that we can't recover from.
if err != ErrMaxMsgs && err != ErrMaxBytes && err != ErrMaxMsgsPerSubject && err != ErrMsgTooLarge && err != ErrStoreClosed {
@@ -7078,13 +7079,22 @@ func (o *consumer) processReplicatedAck(dseq, sseq uint64) error {
// Update activity.
o.lat = time.Now()
var sagap uint64
if o.cfg.AckPolicy == AckAll || o.cfg.AckPolicy == AckFlowControl {
var ackAllSeqs []uint64
if o.retention != LimitsPolicy && (o.cfg.AckPolicy == AckAll || o.cfg.AckPolicy == AckFlowControl) {
// Always use the store state, as o.asflr is skipped ahead already.
// Capture before updating store.
// Capture before updating store, which clears the pending below.
state, err := o.store.BorrowState()
if err == nil {
sagap = sseq - state.AckFloor.Stream
// Only need to collect if the ack covers more than the sequence itself.
if sagap := sseq - state.AckFloor.Stream; sagap > 1 {
// At most the pending entries below the ack, don't over-allocate.
ackAllSeqs = make([]uint64, 0, min(uint64(len(state.Pending)), sagap-1))
for seq := range state.Pending {
if seq < sseq {
ackAllSeqs = append(ackAllSeqs, seq)
}
}
}
}
}
@@ -7114,13 +7124,9 @@ func (o *consumer) processReplicatedAck(dseq, sseq uint64) error {
}
o.mu.Unlock()
if sagap > 1 {
// FIXME(dlc) - This is very inefficient, will need to fix.
for seq := sseq; seq > sseq-sagap; seq-- {
mset.ackMsg(o, seq)
}
} else {
mset.ackMsg(o, sseq)
mset.ackMsg(o, sseq)
for _, seq := range ackAllSeqs {
mset.ackMsg(o, seq)
}
return nil
}
@@ -9525,7 +9531,8 @@ func (s *Server) jsClusteredConsumerRequest(ci *ClientInfo, acc *Account, subjec
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
selectedLimits, _, _, apiErr := acc.selectLimits(cfg.replicas(&streamCfg))
selectedReplicas := cfg.replicas(&streamCfg)
selectedLimits, selectedTier, _, apiErr := acc.selectLimits(selectedReplicas)
if apiErr != nil {
resp.Error = apiErr
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
@@ -9574,26 +9581,30 @@ func (s *Server) jsClusteredConsumerRequest(ci *ClientInfo, acc *Account, subjec
// Start with limit on a stream, but if one is defined at the level of the account
// and is lower, use that limit.
if action == ActionCreate || action == ActionCreateOrUpdate {
maxc := sa.Config.MaxConsumers
if maxc <= 0 || (selectedLimits.MaxConsumers > 0 && selectedLimits.MaxConsumers < maxc) {
maxc = selectedLimits.MaxConsumers
}
if maxc > 0 {
// The stream limit caps every consumer of the stream. The account limit
// caps only the consumers of the selected tier, so the two need separate
// counts.
streamMaxc := sa.Config.MaxConsumers
tierMaxc := selectedLimits.MaxConsumers
if streamMaxc > 0 || tierMaxc > 0 {
// If the consumer name is specified and we think it already exists, then
// we're likely updating an existing consumer, so don't count it. Otherwise
// we will incorrectly return NewJSMaximumConsumersLimitError for an update.
if oname == _EMPTY_ || js.consumerAssignmentOrInflight(acc.Name, stream, oname) == nil {
// Don't count direct/sourcing consumers.
total := 0
var total, tierTotal int
for ca := range js.consumerAssignmentsOrInflightSeq(acc.Name, stream) {
if ca.unsupported != nil {
continue
}
if ca.Config != nil && !ca.Config.Direct && !ca.Config.Sourcing {
total++
if selectedTier == _EMPTY_ || isSameTier(ca.Config.replicas(&streamCfg), selectedReplicas) {
tierTotal++
}
}
}
if total >= maxc {
if (streamMaxc > 0 && total >= streamMaxc) || (tierMaxc > 0 && tierTotal >= tierMaxc) {
resp.Error = NewJSMaximumConsumersLimitError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
+40
View File
@@ -825,6 +825,9 @@ func (ms *memStore) allLastSeqsLocked() ([]uint64, error) {
// Most clients send in subjects even if they match the stream's ingest subjects.
// Lock should be held.
func (ms *memStore) filterIsAll(filters []string) bool {
if len(filters) == 1 && filters[0] == fwcs {
return true
}
if len(filters) != len(ms.cfg.Subjects) {
return false
}
@@ -845,7 +848,11 @@ func (ms *memStore) filterIsAll(filters []string) bool {
func (ms *memStore) MultiLastSeqs(filters []string, maxSeq uint64, maxAllowed int) ([]uint64, error) {
ms.mu.Lock()
defer ms.mu.Unlock()
return ms.multiLastSeqsLocked(filters, maxSeq, maxAllowed)
}
// Write lock should be held, for recalculateForSubj.
func (ms *memStore) multiLastSeqsLocked(filters []string, maxSeq uint64, maxAllowed int) ([]uint64, error) {
if len(ms.msgs) == 0 {
return nil, nil
}
@@ -897,6 +904,39 @@ func (ms *memStore) MultiLastSeqs(filters []string, maxSeq uint64, maxAllowed in
return seqs, nil
}
// MultiLastMsgs delivers the last message per subject matching the filters,
// up to maxSeq and skipping sequences below minSeq, in ascending sequence
// order through cb, all within a single read section so the batch is a
// point-in-time snapshot of the store.
func (ms *memStore) MultiLastMsgs(filters []string, minSeq, maxSeq uint64, maxAllowed int, cb func(sm *StoreMsg, np uint64) bool) (uint64, uint64, error) {
ms.mu.Lock()
defer ms.mu.Unlock()
seqs, err := ms.multiLastSeqsLocked(filters, maxSeq, maxAllowed)
if err != nil || len(seqs) == 0 {
return 0, 0, err
}
total := uint64(len(seqs))
np := total
for _, seq := range seqs {
if np > 0 {
np--
}
if seq < minSeq {
continue
}
var svp StoreMsg
sm, err := ms.loadMsgLocked(seq, &svp, false)
if err != nil {
return total, np, err
}
if !cb(sm, np) {
break
}
}
return total, np, nil
}
// SubjectsTotals return message totals per subject.
func (ms *memStore) SubjectsTotals(filterSubject string) map[string]uint64 {
ms.mu.RLock()
Loaded 100 of 238 files, more files were not shown because too many files have changed in this diff. Show more